hooks

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package hooks runs the scripts configured in <vault>/.nota/hooks.toml when core events happen, like git hooks:

[[hook]]
event = "inbox.added"        # see events.Types
run = "sh scripts/file.sh"   # run with the vault as working directory (sh -c; cmd /C on Windows)
mode = "transform"           # "after" (default) or "transform"
timeout = "2s"               # default 2s for transform, 30s for after
match = { folder = "Inbox", tag = "x" }

A hook gets the event as JSON on stdin (see Payload) and NOTA_VAULT, NOTA_EVENT, NOTA_NOTE and NOTA_HOOK in its environment.

After hooks run in the background and never block the write that triggered them. Transform hooks run only on note.created and inbox.added, before the write returns; they print a Patch as JSON on stdout, which is applied through the vault like any other edit. A failing, slow or confused hook is logged and leaves the note as it was.

Index

Constants

View Source
const (
	DefaultTransformTimeout = 2 * time.Second
	DefaultAfterTimeout     = 30 * time.Second
)

Default timeouts.

View Source
const File = vault.MetaDirName + "/hooks.toml"

File is the vault-relative path of the hooks configuration.

View Source
const OriginPrefix = "hook:"

OriginPrefix starts the Event.Origin of changes made by a hook.

Variables

TransformEvents are the events transform hooks may run on.

Functions

func ShellExec

func ShellExec(ctx context.Context, h Hook, dir string, env []string, stdin []byte) ([]byte, error)

ShellExec runs h.Run through the shell (sh -c, or cmd /C on Windows) in dir. When ctx ends, the whole process group is killed, so a hook that started children cannot outlive its timeout. A non-zero exit is an error that includes the end of stderr.

Types

type Config

type Config struct {
	Hooks []Hook `toml:"hook"`
}

Config is the parsed hooks file.

func Load

func Load(v *vault.Vault) (Config, error)

Load reads the vault's hooks file. A missing file means no hooks.

func Parse

func Parse(data []byte) (Config, error)

Parse decodes and validates a hooks file, filling in defaults.

type Exec

type Exec func(ctx context.Context, h Hook, dir string, env []string, stdin []byte) (stdout []byte, err error)

Exec runs a hook's command with stdin and returns its stdout. The context carries the hook's timeout.

type Hook

type Hook struct {
	// ID names the hook in logs and event origins: its name, else "#N"
	// for the N-th entry.
	ID      string        `toml:"-" json:"id"`
	Name    string        `toml:"name" json:"name,omitempty"`
	Event   events.Type   `toml:"event" json:"event"`
	Run     string        `toml:"run" json:"run"`
	Mode    Mode          `toml:"mode" json:"mode"`
	Timeout time.Duration `toml:"-" json:"-"`
	Match   Match         `toml:"match" json:"match"`

	RawTimeout string `toml:"timeout" json:"-"`
}

Hook is one [[hook]] entry.

type Match

type Match struct {
	// Folder matches notes in this folder and its subfolders.
	Folder string `toml:"folder" json:"folder,omitempty"`
	// Tag matches notes with this tag in frontmatter or body, nested tags included.
	Tag string `toml:"tag" json:"tag,omitempty"`
}

Match filters the notes a hook runs for. Empty fields match everything.

type Mode

type Mode string

Mode says how a hook runs.

const (
	After     Mode = "after"
	Transform Mode = "transform"
)

Hook modes.

type Options

type Options struct {
	// Dir is the hooks' working directory; the vault root when empty.
	Dir string
	// Logger gets failures (warn) and runs (debug); slog.Default when nil.
	Logger *slog.Logger
	// Exec runs commands; ShellExec when nil. Tests replace it.
	Exec Exec
}

Options configure a Runner.

type Patch

type Patch struct {
	Set   map[string]any `json:"set,omitempty"`
	Unset []string       `json:"unset,omitempty"`
	Tags  struct {
		Add    []string `json:"add,omitempty"`
		Remove []string `json:"remove,omitempty"`
	} `json:"tags,omitzero"`
	// Folder moves the note; "/" is the vault root.
	Folder string `json:"folder,omitempty"`
}

Patch is what a transform hook prints on stdout. Every field is optional; empty output means "no change".

func ParsePatch

func ParsePatch(out []byte) (Patch, error)

ParsePatch decodes a transform hook's output. Blank output is the empty patch; unknown fields are errors, so typos do not pass silently.

func (Patch) Empty

func (p Patch) Empty() bool

Empty reports whether the patch changes nothing.

type Payload

type Payload struct {
	Event events.Type `json:"event"`
	// Vault is the vault directory (also the hook's working directory).
	Vault string `json:"vault"`
	// Path is the note's vault-relative path (its new path for
	// note.moved), empty for sync.completed.
	Path    string `json:"path,omitempty"`
	OldPath string `json:"oldPath,omitempty"`
	Trash   string `json:"trash,omitempty"`
	Folder  string `json:"folder"`
	Title   string `json:"title,omitempty"`
	// Tags are the note's frontmatter and inline tags.
	Tags        []string       `json:"tags"`
	Frontmatter map[string]any `json:"frontmatter"`
	// Body is set for note.created, note.saved and inbox.added.
	Body   string    `json:"body,omitempty"`
	Time   time.Time `json:"time"`
	Origin string    `json:"origin,omitempty"`
}

Payload is the JSON a hook reads on stdin.

type Result

type Result struct {
	Hook     string        `json:"hook"`
	Mode     Mode          `json:"mode"`
	Duration time.Duration `json:"-"`
	Seconds  float64       `json:"seconds"`
	Output   string        `json:"output,omitempty"`
	Patch    *Patch        `json:"patch,omitempty"`
	Error    string        `json:"error,omitempty"`
}

Result is the outcome of one hook run.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner runs a vault's hooks on its events.

func New

func New(v *vault.Vault, cfg Config, opts Options) *Runner

New returns a runner for the hooks in cfg. Attach it to the vault's bus.

func (*Runner) Attach

func (r *Runner) Attach(bus *events.Bus) (detach func())

Attach subscribes the runner to bus. Transform hooks run on the emitting goroutine, inside the write that triggered them; after hooks are started in the background. The returned func detaches it.

func (*Runner) Handle

func (r *Runner) Handle(e events.Event)

Handle runs the hooks for one event. A change a hook made never runs that hook again, and transform hooks never run on changes made by a transform hook, so hooks cannot loop.

func (*Runner) Hooks

func (r *Runner) Hooks() []Hook

Hooks returns the configured hooks.

func (*Runner) Test

func (r *Runner) Test(event events.Type, path string) ([]Result, error)

Test runs every hook for event on the note at path, as if the event had happened, and reports what each did. Patches are parsed but not applied; it is for `nota hooks test`.

func (*Runner) Wait

func (r *Runner) Wait()

Wait blocks until every after hook started so far has finished. Commands call it before they exit so background hooks are not cut off.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL