Skip to content

How to use lifecycle hooks

After CONGA parses and validates the command line, a command can run three hooks around Run:

  • PreRun acquires resources before Run starts.
  • PostRun runs follow-up work only after Run returns nil.
  • Finally cleans up after Run and PostRun, 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:

A snap create run goes PreRun (snap then create), Run (create), PostRun (create), Finally (create then snap). If snap fails in PreRun, the run exits with status 1 without calling Finally. If create fails in PreRun, CONGA skips Run, PostRun, and create’s Finally, and calls snap’s Finally before exiting with status 1. If create fails in Run or PostRun, CONGA calls create’s Finally and then snap’s Finally before exiting with status 1. After Finally on a successful run, the program exits with status 0.PreRunsnapcreateRuncreaterequiredPostRuncreateFinallycreatesnaperrorExit 1errorerrorExit 0on errorExit 1

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:

main.go
package main
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/conga-sh/conga"
)
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:

Terminal window
$ snap create docs v2
Error:snap: error: snapshots is in use by another run (delete snapshots/.lock if none is running)

Because 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.

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:

main.go
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)
}
})
}
func copyFile(source, target string) error {
in, err := os.Open(source)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(target)
if err != nil {
return err
}
if _, err := io.Copy(out, in); err != nil {
out.Close()
return err
}
return out.Close()
}

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:

main.go
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:

Terminal window
$ snap create docs v2
discarded the partial snapshot
Error:snap: error: open docs/secret.txt: permission denied

When 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:

Terminal window
$ snap create docs v1
Error:snap: error: snapshot "v1" already exists

If 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.

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:

main.go
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:

main.go
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
}
Terminal window
$ snap create docs v1
created snapshot v1
$ snap list
v1

Renaming 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.

app.Run() passes the hooks a context that is canceled on Control + C (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 Control + C partway through a large copy returns context.Canceled, skips PostRun, removes the partial snapshot in CreateCmd.Finally, and releases .lock in CLI.Finally. The run exits with status 1:

Terminal window
$ snap create photos trip
discarded the partial snapshot
Error:snap: error: context canceled

app.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(), Control + C ends the process at once, before any Finally hook runs, and leaves .lock and the .partial-* directory in the store. To stop cleanly under RunContext, build the context with signal.NotifyContext:

main.go
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 Control + C, 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.

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
Control + C under app.Run(), in a command that checks ctx Each Finally whose PreRun succeeded, receiving context.Canceled 1
Control + C under app.Run(), in a command that ignores ctx Every Finally hook, once Run finishes The command’s own
Control + C under app.RunContext with a context that has no signal handler None 130, set by the shell