How to use lifecycle hooks
After CONGA parses and validates the command line, a command can run three hooks around Run:
PreRunacquires resources beforeRunstarts.PostRunruns follow-up work only afterRunreturnsnil.Finallycleans up afterRunandPostRun, whether they succeeded or failed.
When the user runs a subcommand, CONGA calls PreRun top-down from the root command to the subcommand, calls Run on the subcommand, and calls PostRun and Finally bottom-up from the subcommand back to the root. Only commands on the active path run their hooks, and every hook except Run is optional.
This guide builds snap, which copies a directory into a snapshot store. The root snap command locks the store in PreRun and unlocks it in Finally. The snap create subcommand creates a staging directory in PreRun, copies files into it in Run, renames it into place in PostRun, and deletes it in Finally if an earlier stage failed:
Acquire and release a shared resource
Section titled “Acquire and release a shared resource”To set up before a command runs and clean up afterwards, implement the lifecycle interfaces conga.PreRunner and conga.Finalizer:
type PreRunner interface { PreRun(ctx context.Context, session *Session) error}
type Finalizer interface { Finally(ctx context.Context, session *Session, err error) error}Here the root CLI struct creates a .lock file in PreRun so only one run at a time modifies the store, and removes .lock in Finally:
type CLI struct { Store conga.OptionalFlag[string] `default:"snapshots" help:"Directory that holds the snapshots"` Create conga.Command[CreateCmd] `summary:"Snapshot a directory"` List conga.Command[ListCmd] `summary:"List snapshots"`
lock string}
func (c *CLI) PreRun(ctx context.Context, session *conga.Session) error { store := c.Store.Get() if err := os.MkdirAll(store, 0o755); err != nil { return err }
lock := filepath.Join(store, ".lock") file, err := os.OpenFile(lock, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644) if errors.Is(err, fs.ErrExist) { return fmt.Errorf("%s is in use by another run (delete %s if none is running)", store, lock) } if err != nil { return err }
c.lock = lock
return file.Close()}
func (c *CLI) Finally(ctx context.Context, session *conga.Session, err error) error { return os.Remove(c.lock)}
func main() { app := conga.New[CLI]().Name("snap").Description("Keep snapshots of a directory")
if err := app.Run(); err != nil { app.Exit(err) }}CONGA binds only container fields, such as OptionalFlag and Command, so any ordinary struct field, exported or unexported, can hold state between hooks. Define the hook methods on a pointer receiver, as *CLI does here, so a value that PreRun sets, such as c.lock, is still there when Finally runs.
CONGA calls a command’s Finally only when every PreRun from the root down to that command succeeded. When a second process tries to run while .lock exists, the root’s PreRun returns an error:
$ snap create docs v2Error:snap: error: snapshots is in use by another run (delete snapshots/.lock if none is running)ErrorBecause the root’s PreRun failed, CONGA stops before create and skips the root’s Finally, so the lock owned by the active run stays in place.
Set up and roll back in a subcommand
Section titled “Set up and roll back in a subcommand”CreateCmd implements PreRun, Run, and Finally for its own staging directory. Because the root’s PreRun runs first, the store is already locked when CreateCmd.PreRun starts.
CreateCmd.PreRun reads the root’s --store flag through session.Root[CLI](), returns an error if a snapshot with that name exists, and creates a .partial-* directory inside the store. Run copies the source tree into that directory. The listing collapses copyFile:
type CreateCmd struct { Source conga.RequiredArg[conga.Dir] `existing:"true" help:"Directory to snapshot"` Name conga.RequiredArg[string] `help:"Name of the snapshot"`
partial string}
func (c *CreateCmd) PreRun(ctx context.Context, session *conga.Session) error { store := session.Root[CLI]().Store.Get() final := filepath.Join(store, c.Name.Get())
if _, err := os.Stat(final); err == nil { return fmt.Errorf("snapshot %q already exists", c.Name.Get()) }
partial, err := os.MkdirTemp(store, ".partial-") if err != nil { return err }
c.partial = partial
return nil}
func (c *CreateCmd) Run(ctx context.Context, session *conga.Session) error { source := c.Source.Get().String()
return filepath.WalkDir(source, func(path string, entry fs.DirEntry, err error) error { if err != nil { return err }
Stops the copy if ctx is canceled. if err := ctx.Err(); err != nil { return err }
relative, err := filepath.Rel(source, path) if err != nil { return err }
target := filepath.Join(c.partial, relative)
switch { case entry.IsDir(): return os.MkdirAll(target, 0o755) case entry.Type()&fs.ModeSymlink != 0: link, err := os.Readlink(path) if err != nil { return err }
return os.Symlink(link, target) default: return copyFile(path, target) } })}Finally receives the error that stopped the run, or nil when Run and PostRun succeeded. CreateCmd.Finally removes the .partial-* directory only when something failed:
func (c *CreateCmd) Finally(ctx context.Context, session *conga.Session, err error) error { if err == nil { return nil }
if removeErr := os.RemoveAll(c.partial); removeErr != nil { return removeErr }
fmt.Fprintln(session.Stderr(), "discarded the partial snapshot")
return nil}When Run meets a file it can’t read, CreateCmd.Finally removes the partial directory, and then CLI.Finally removes .lock. Here docs/secret.txt has mode 000:
$ snap create docs v2discarded the partial snapshotError:snap: error: open docs/secret.txt: permission deniedErrorWhen a snapshot named v1 already exists, snap create docs v1 fails in CreateCmd.PreRun before any files are copied. CONGA skips CreateCmd.Finally, because its PreRun failed before it created a .partial-* directory, and runs CLI.Finally to release .lock:
$ snap create docs v1Error:snap: error: snapshot "v1" already existsErrorIf Finally returns an error on a run that otherwise succeeded, the run fails with that error. If Finally returns an error after an earlier stage failed, CONGA joins both with errors.Join and prints the run’s error first, followed by each Finally error on its own line.
Commit work after success
Section titled “Commit work after success”To run code only after Run returns nil, implement conga.PostRunner:
type PostRunner interface { PostRun(ctx context.Context, session *Session) error}CreateCmd.PostRun renames the finished .partial-* directory to the snapshot’s final name, so a snapshot appears in the store only after every file has been copied:
func (c *CreateCmd) PostRun(ctx context.Context, session *conga.Session) error { store := session.Root[CLI]().Store.Get() final := filepath.Join(store, c.Name.Get())
if err := os.Rename(c.partial, final); err != nil { return err }
fmt.Fprintf(session.Stdout(), "created snapshot %s\n", c.Name.Get())
return nil}ListCmd prints the snapshots in the store and skips .lock and .partial-*, whose names start with a dot:
type ListCmd struct{}
func (l *ListCmd) Run(ctx context.Context, session *conga.Session) error { entries, err := os.ReadDir(session.Root[CLI]().Store.Get()) if err != nil { return err }
for _, entry := range entries { if entry.IsDir() && entry.Name()[0] != '.' { fmt.Fprintln(session.Stdout(), entry.Name()) } }
return nil}$ snap create docs v1created snapshot v1$ snap listv1Renaming in PostRun keeps a failed rename safe. When os.Rename fails in PostRun, CONGA passes that error to CreateCmd.Finally, which deletes c.partial. A rename inside Finally, behind if err == nil, would run in the success branch, and a failure there would leave c.partial in the store, because no hook runs after Finally to remove it.
Stop cleanly on Ctrl+C
Section titled “Stop cleanly on Ctrl+C”app.Run() passes the hooks a context that is canceled on SIGINT) or SIGTERM, as Default signal context versus custom context explains. The process keeps running after the signal. To stop cleanly, a long-running hook checks ctx and returns its error, and the Finally hooks then clean up.
In CreateCmd.Run, the filepath.WalkDir callback checks ctx.Err() before each entry. Pressing context.Canceled, skips PostRun, removes the partial snapshot in CreateCmd.Finally, and releases .lock in CLI.Finally. The run exits with status 1:
$ snap create photos tripdiscarded the partial snapshotError:snap: error: context canceledErrorapp.RunContext(ctx) passes the caller’s context to every hook as it is and installs no signal handler. Under a context such as context.Background(), Finally hook runs, and leaves .lock and the .partial-* directory in the store. To stop cleanly under RunContext, build the context with signal.NotifyContext:
import ( "context" "errors" "fmt" "io" "io/fs" "os" "os/signal" "path/filepath" "syscall"
"github.com/conga-sh/conga")
func main() { ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop()
app := conga.New[CLI]().Name("snap").Description("Keep snapshots of a directory")
if err := app.RunContext(ctx); err != nil { app.Exit(err) }}When Finally runs after ctx is already canceled. If a cleanup step calls a function that takes a context.Context, such as one that rolls back a database transaction or deletes a remote object, pass it context.WithoutCancel(ctx) so the call gets a live context. Wrap that in context.WithTimeout when the call can hang.
Know what users see
Section titled “Know what users see”| What fails | Finally hooks that run |
Exit status |
|---|---|---|
Flag parsing, a struct tag check (such as existing:"true"), or Validate |
None | 2 |
CLI.PreRun (the store is locked) |
None | 1 |
CreateCmd.PreRun (the snapshot name already exists) |
CLI.Finally |
1 |
CreateCmd.Run (a file cannot be read) |
CreateCmd.Finally, then CLI.Finally |
1 |
CreateCmd.PostRun (os.Rename fails) |
CreateCmd.Finally, then CLI.Finally |
1 |
A Finally hook |
The remaining Finally hooks, with every error joined |
1 |
app.Run(), in a command that checks ctx |
Each Finally whose PreRun succeeded, receiving context.Canceled |
1 |
app.Run(), in a command that ignores ctx |
Every Finally hook, once Run finishes |
The command’s own |
app.RunContext with a context that has no signal handler |
None | 130, set by the shell |
Where to go next
Section titled “Where to go next”- How to validate input: check values against each other in
Validate, beforePreRun. - About the command lifecycle: why CONGA splits a run into these stages, and how they compose across a command tree.
- Lifecycle interfaces: the interface behind each hook.
- Lifecycle hooks example: every hook on a root and three subcommands, printing as it runs.