Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,18 @@ jobs:
uses: jdx/mise-action@6612f0ef07ed2a736cd1e00a94a065522dd41195 # v5.2.5
with:
version: 2026.11.11
install_args: go
- name: Find the Go build cache
id: go-cache
run: echo "dir=$(go env GOCACHE)" >> "$GITHUB_OUTPUT"
- name: Cache the Go build cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ steps.go-cache.outputs.dir }}
key: go-build-${{ runner.os }}-${{ hashFiles('go.sum') }}
restore-keys: go-build-${{ runner.os }}-
- name: Install the tools
run: mise install
- name: Run check
run: mise run check
test:
Expand All @@ -45,6 +57,7 @@ jobs:
id: go-cache
run: echo "dir=$(go env GOCACHE)" >> "$GITHUB_OUTPUT"
- name: Cache the Go build cache
id: restore-go-cache
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
with:
path: ${{ steps.go-cache.outputs.dir }}
Expand All @@ -54,5 +67,11 @@ jobs:
# install them here to give that time a line of its own.
- name: Install the tools
run: mise install
- name: Download Go modules
run: go mod download
# Some test packages build non-race binaries even though CI tests with -race.
- name: Warm the Go build cache for subprocess tests
if: steps.restore-go-cache.outputs.cache-hit != 'true'
run: go build ./...
- name: Run tests
run: mise run ci-test
4 changes: 3 additions & 1 deletion internal/cli/hooks/commitmsg/commitmsg.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"strings"

"github.com/spf13/cobra"

"github.com/nnutter/timber/internal/process"
)

// New builds the commit-msg subcommand. Successful hooks produce no output.
Expand Down Expand Up @@ -65,7 +67,7 @@ func (h hook) config(args ...string) (string, error) {
}

func (h hook) git(input []byte, args ...string) ([]byte, error) {
cmd := exec.CommandContext(h.ctx, "git", args...)
cmd := process.Command(h.ctx, "git", args...)
cmd.Dir = h.dir
cmd.Stdin = bytes.NewReader(input)
var stderr bytes.Buffer
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/review/activity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
func TestReviewRunningReportsLiveLockNotPersistedAttempt(t *testing.T) {
binary := buildGitReview(t)
dir := featureRepo(t)
path, err := review.WorktreePath(dir)
path, err := review.WorktreePath(t.Context(), dir)
require.NoError(t, err)
check := func(cwd string, running bool) {
t.Helper()
Expand Down
4 changes: 2 additions & 2 deletions internal/cli/review/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ package log
import (
"fmt"
"io"
"os/exec"

"github.com/spf13/cobra"

"github.com/nnutter/timber/internal/process"
"github.com/nnutter/timber/internal/timber/review"
)

Expand All @@ -34,7 +34,7 @@ func (c *Command) RunE(cmd *cobra.Command, _ []string) error {
if asJSON {
return fmt.Errorf("log does not support --json")
}
git := exec.CommandContext(cmd.Context(), "git", c.gitArgs()...)
git := process.Command(cmd.Context(), "git", c.gitArgs()...)
git.Dir = c.Service.Repository.Dir
git.Stdin = c.Input
git.Stdout = c.Output
Expand Down
7 changes: 4 additions & 3 deletions internal/cli/review/root/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import (
"context"
"errors"
"io"
"os"
"syscall"

charmlog "charm.land/log/v2"

Expand All @@ -24,6 +22,7 @@ import (
"github.com/nnutter/timber/internal/cli/review/reset"
"github.com/nnutter/timber/internal/cli/review/status"
"github.com/nnutter/timber/internal/display"
"github.com/nnutter/timber/internal/process"
coreconfig "github.com/nnutter/timber/internal/timber/config"
"github.com/nnutter/timber/internal/timber/review"
)
Expand Down Expand Up @@ -96,7 +95,9 @@ func Execute(ctx context.Context, args []string, dir string, input io.Reader, ou
root.SetIn(input)
root.SetOut(output)
root.SetErr(terminal)
err := fang.Execute(ctx, root, fang.WithVersion(version), fang.WithoutManpage(), fang.WithNotifySignal(os.Interrupt, syscall.SIGTERM), fang.WithErrorHandler(func(w io.Writer, styles fang.Styles, err error) {
ctx, stop := process.InterruptContext(ctx)
defer stop()
err := fang.Execute(ctx, root, fang.WithVersion(version), fang.WithoutManpage(), fang.WithErrorHandler(func(w io.Writer, styles fang.Styles, err error) {
if c.JSON {
failed, _, _ := root.Find(args)
if failed == nil {
Expand Down
54 changes: 54 additions & 0 deletions internal/process/signal.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Package process provides cancellation for CLI subprocesses.
package process

import (
"context"
"errors"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
)

type interruption struct{ signal os.Signal }

func (x interruption) Error() string { return x.signal.String() }

// InterruptContext cancels on the first shutdown signal, preserving which
// signal arrived so a running Git command can receive the same one.
func InterruptContext(parent context.Context) (context.Context, func()) {
ctx, cancel := context.WithCancelCause(parent)
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM)
go func() {
select {
case sig := <-signals:
cancel(interruption{signal: sig})
case <-ctx.Done():
}
}()
return ctx, func() {
signal.Stop(signals)
cancel(nil)
}
}

// Command forwards OS shutdown signals to Git. Ordinary context cancellation
// retains the default kill behavior. WaitDelay bounds the grace period and
// prevents inherited output pipes from holding up shutdown indefinitely.
func Command(ctx context.Context, name string, args ...string) *exec.Cmd {
cmd := exec.CommandContext(ctx, name, args...)
if name != "git" {
return cmd
}
cmd.WaitDelay = 2 * time.Second
kill := cmd.Cancel
cmd.Cancel = func() error {
if cause, ok := errors.AsType[interruption](context.Cause(ctx)); ok {
return cmd.Process.Signal(cause.signal)
}
return kill()
}
return cmd
}
3 changes: 2 additions & 1 deletion internal/timber/git_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package timber

import (
"bytes"
"cmp"
"context"
"errors"
"fmt"
Expand All @@ -17,7 +18,7 @@ type gitCommandResult struct {
}

func gitOutput(runtime Runtime, directory string, args ...string) (gitCommandResult, error) {
command := runtime.command(context.Background(), "git", args...)
command := runtime.command(cmp.Or(runtime.processContext, context.Background()), "git", args...)
command.Dir = directory

var stdout bytes.Buffer
Expand Down
4 changes: 2 additions & 2 deletions internal/timber/review/auto_split.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ func validateAutoEvaluator(evaluator autoreview.Evaluator, options *AutoOptions)
return nil
}

func autoLock(s Service, options AutoOptions) (*os.File, error) {
path, err := WorktreePath(s.Repository.Dir)
func autoLock(ctx context.Context, s Service, options AutoOptions) (*os.File, error) {
path, err := WorktreePath(ctx, s.Repository.Dir)
if err != nil {
return nil, err
}
Expand Down
8 changes: 4 additions & 4 deletions internal/timber/review/bounds_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func TestReviewSelectsWithinInclusiveBounds(t *testing.T) {
return nil
}))
}
path, err := WorktreePath(r.Dir)
path, err := WorktreePath(t.Context(), r.Dir)
require.NoError(t, err)
scope := view.Stacks[1]
scope.Repo = path
Expand Down Expand Up @@ -77,7 +77,7 @@ func TestBoundedReviewContinuesUntilApprovalOrUserInput(t *testing.T) {
gitTest(t, r.Dir, "commit", "--allow-empty", "-m", "Fourth")
view, err := r.Snapshot(t.Context())
require.NoError(t, err)
path, err := WorktreePath(r.Dir)
path, err := WorktreePath(t.Context(), r.Dir)
require.NoError(t, err)
first, second := view.Stacks[1], view.Stacks[2]
first.Repo, second.Repo = path, path
Expand Down Expand Up @@ -145,7 +145,7 @@ func TestBoundedReviewRetainsFeedbackAndContinuesToLaterStacks(t *testing.T) {
gitTest(t, r.Dir, "commit", "--allow-empty", "-m", "Outside range")
view, err := r.Snapshot(t.Context())
require.NoError(t, err)
path, err := WorktreePath(r.Dir)
path, err := WorktreePath(t.Context(), r.Dir)
require.NoError(t, err)
wantLaunch := ""
for i, stack := range view.Stacks[:3] {
Expand Down Expand Up @@ -237,7 +237,7 @@ func TestBoundedReviewRetainsDeferredAndActiveAttempts(t *testing.T) {
state.Attempts = append(state.Attempts, active)
return nil
}))
path, err := WorktreePath(r.Dir)
path, err := WorktreePath(t.Context(), r.Dir)
require.NoError(t, err)
scope := first
scope.Repo = path
Expand Down
8 changes: 4 additions & 4 deletions internal/timber/review/carry.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,14 @@ func carrySavedReviews(ctx context.Context, repository Repository, reader SavedR

// carrySavedSession moves the session that captured from onto the current stack.
func carrySavedSession(ctx context.Context, repository Repository, reader SavedReader, from Attempt, to Stack) error {
source, err := carrySource(reader, from)
source, err := carrySource(ctx, reader, from)
if err != nil {
return err
}
if source == nil {
return nil
}
checkout, err := WorktreePath(to.Repo)
checkout, err := WorktreePath(ctx, to.Repo)
if err != nil {
return err
}
Expand All @@ -95,8 +95,8 @@ func carrySavedSession(ctx context.Context, repository Repository, reader SavedR

// carrySource reads the session that captured an attempt, or nil when the
// attempt left no session to move.
func carrySource(reader SavedReader, from Attempt) (*carriedSession, error) {
saved, err := readAttempt(reader, from, "")
func carrySource(ctx context.Context, reader SavedReader, from Attempt) (*carriedSession, error) {
saved, err := readAttempt(ctx, reader, from, "")
if err != nil {
return nil, err
}
Expand Down
10 changes: 5 additions & 5 deletions internal/timber/review/carry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
func carryFixture(t *testing.T, reviewer Reviewer, view Snapshot, store string) {
t.Helper()
scope := view.Stacks[0]
path, err := WorktreePath(scope.Repo)
path, err := WorktreePath(t.Context(), scope.Repo)
require.NoError(t, err)
require.NoError(t, prepareWorktree(t.Context(), reviewer.Service.Repository, path, scope))
scope.Repo = path
Expand Down Expand Up @@ -116,7 +116,7 @@ func TestCarrySavedReviewKeepsMarksAcrossRewrite(t *testing.T) {
carrySavedReviews(t.Context(), reviewer.Service.Repository, reviewer.Reader)

scope := carried.Stacks[0]
checkout, err := WorktreePath(scope.Repo)
checkout, err := WorktreePath(t.Context(), scope.Repo)
require.NoError(t, err)
scope.Repo = checkout
saved, err := (SavedReader{Stores: []string{store}}).Read(scope, "")
Expand Down Expand Up @@ -231,7 +231,7 @@ func TestCarrySavedReviewStoresTheRangeTheWayTuicrStoresIt(t *testing.T) {
carrySavedReviews(t.Context(), reviewer.Service.Repository, reviewer.Reader)

scope := carried.Stacks[0]
checkout, err := WorktreePath(scope.Repo)
checkout, err := WorktreePath(t.Context(), scope.Repo)
require.NoError(t, err)
scope.Repo = checkout
saved, err := (SavedReader{Stores: []string{store}}).Read(scope, "")
Expand Down Expand Up @@ -275,7 +275,7 @@ func TestCarrySavedReviewCarriesARangeOfSeveralCommits(t *testing.T) {
carrySavedReviews(t.Context(), reviewer.Service.Repository, reviewer.Reader)

scope := carried.Stacks[0]
checkout, err := WorktreePath(scope.Repo)
checkout, err := WorktreePath(t.Context(), scope.Repo)
require.NoError(t, err)
scope.Repo = checkout
saved, err := (SavedReader{Stores: []string{store}}).Read(scope, "")
Expand Down Expand Up @@ -335,7 +335,7 @@ func TestReviewContinuesWithTheLastRecordedSession(t *testing.T) {
func addSecondSession(t *testing.T, store string, view Snapshot, updatedAt string) {
t.Helper()
scope := view.Stacks[0]
checkout, err := WorktreePath(scope.Repo)
checkout, err := WorktreePath(t.Context(), scope.Repo)
require.NoError(t, err)
session := map[string]any{
"version": "1.3", "id": "second-session", "repo_path": checkout,
Expand Down
2 changes: 1 addition & 1 deletion internal/timber/review/files.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ func (r FileReviewer) lockReview(ctx context.Context) (*os.File, error) {
if err != nil {
return nil, err
}
path, err := WorktreePath(r.Service.Repository.Dir)
path, err := WorktreePath(ctx, r.Service.Repository.Dir)
if err != nil {
return nil, err
}
Expand Down
8 changes: 5 additions & 3 deletions internal/timber/review/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ import (
"unicode/utf8"

"charm.land/log/v2"

"github.com/nnutter/timber/internal/process"
)

// Stack identifies an original commit and its adjacent feedback commits.
Expand Down Expand Up @@ -184,7 +186,7 @@ func (r Repository) WarmCache(ctx context.Context, ref string) error {
func (r Repository) autoGit(ctx context.Context, limit int, args ...string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", args...)
cmd := process.Command(ctx, "git", args...)
cmd.Dir = r.Dir
cmd.Env = append(slices.Clone(r.environment()), "LC_ALL=C", "GIT_TERMINAL_PROMPT=0", "GIT_NO_REPLACE_OBJECTS=1")
out := autoOutput{limit: limit}
Expand Down Expand Up @@ -252,7 +254,7 @@ func (r Repository) gitInput(ctx context.Context, input string, args ...string)
defer func() { r.logger().Debug("Git command completed", "args", args, "elapsed", time.Since(started)) }()
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", args...)
cmd := process.Command(ctx, "git", args...)
cmd.Dir = r.Dir
cmd.Stdin = strings.NewReader(input)
// Keep Git diagnostics stable so repository discovery errors can be identified.
Expand Down Expand Up @@ -294,7 +296,7 @@ func (r Repository) patchHash(ctx context.Context, base, tip string) (string, er
// and hunk line numbers so an unchanged patch can survive relocation.
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "git", "patch-id", "--verbatim")
cmd := process.Command(ctx, "git", "patch-id", "--verbatim")
cmd.Dir = r.Dir
cmd.Env = append(slices.Clone(r.environment()), "LC_ALL=C")
cmd.Stdin = strings.NewReader(patch)
Expand Down
2 changes: 1 addition & 1 deletion internal/timber/review/mise_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func TestPrepareWorktreeMirrorsMiseTrust(t *testing.T) {
require.NoError(t, os.WriteFile(trustedPath, []byte(r.Dir+"\n"), 0o600))
view, err := r.Snapshot(t.Context())
require.NoError(t, err)
path, err := WorktreePath(r.Dir)
path, err := WorktreePath(t.Context(), r.Dir)
require.NoError(t, err)
require.NoError(t, prepareWorktree(t.Context(), r, path, view.Stacks[0]))
data, err := os.ReadFile(trustedPath)
Expand Down
Loading
Loading