Skip to content

Commit 2db0889

Browse files
committed
fix: honor interrupt outside default stream and keep --json abort machine-readable
Propagate RunCtx cancel to dry-run/TUI scans and sequential --rain processing so SIGINT/SIGTERM skips remaining work instead of marking leftovers frozen. On --json cancel, emit schema_version 1 and return interrupted instead of printing Aborted. with exit 0.
1 parent 6cbf7c2 commit 2db0889

2 files changed

Lines changed: 273 additions & 10 deletions

File tree

‎cmd/default_stream_stall_test.go‎

Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package cmd
33
import (
44
"bytes"
55
"context"
6+
"encoding/json"
67
"fmt"
78
"io"
89
"net"
@@ -169,6 +170,230 @@ func TestRunRainDefaultStream_CancelStopsRemainingRepos(t *testing.T) {
169170
}
170171
}
171172

173+
func TestRunRainDefaultStream_JSONCancelEmitsJSONNotAborted(t *testing.T) {
174+
baseURL, cleanup := startStallTCPListener(t)
175+
defer cleanup()
176+
177+
stallA := testutil.CreateTestRepo(t, testutil.RepoOptions{
178+
Name: "json-stall-a",
179+
Remotes: map[string]string{
180+
"origin": baseURL + "/json-stall-a.git",
181+
},
182+
})
183+
stallB := testutil.CreateTestRepo(t, testutil.RepoOptions{
184+
Name: "json-stall-b",
185+
Remotes: map[string]string{
186+
"origin": baseURL + "/json-stall-b.git",
187+
},
188+
})
189+
190+
prevJSON := rainJSON
191+
rainJSON = true
192+
defer func() { rainJSON = prevJSON }()
193+
194+
cfg := config.DefaultConfig()
195+
cfg.Global.FetchWorkers = 1
196+
cfg.Global.FetchTimeoutSec = 30
197+
cfg.Global.DisableScan = true
198+
199+
opts := git.DefaultScanOptions()
200+
opts.DisableScan = true
201+
opts.KnownPaths = map[string]bool{
202+
stallA: true,
203+
stallB: true,
204+
}
205+
opts.Workers = 1
206+
207+
runCtx, cancel := context.WithCancel(context.Background())
208+
rainOpts := git.RainOptions{
209+
FetchTimeoutSec: 30,
210+
RunCtx: runCtx,
211+
}
212+
213+
oldStdout := os.Stdout
214+
r, w, _ := os.Pipe()
215+
os.Stdout = w
216+
defer func() { os.Stdout = oldStdout }()
217+
218+
done := make(chan error, 1)
219+
go func() {
220+
done <- runRainDefaultStream(&cfg, &registry.Registry{}, "", opts, rainOpts, false)
221+
}()
222+
223+
time.Sleep(300 * time.Millisecond)
224+
cancel()
225+
226+
select {
227+
case err := <-done:
228+
if err == nil {
229+
t.Fatal("expected non-nil error on JSON cancel")
230+
}
231+
if !strings.Contains(err.Error(), "interrupted") {
232+
t.Fatalf("expected interrupted error, got: %v", err)
233+
}
234+
case <-time.After(5 * time.Second):
235+
t.Fatal("runRainDefaultStream did not return after cancel")
236+
}
237+
238+
_ = w.Close()
239+
var out bytes.Buffer
240+
_, _ = io.Copy(&out, r)
241+
body := out.String()
242+
243+
if strings.Contains(body, "Aborted.") {
244+
t.Fatalf("--json cancel must not print Aborted. on stdout, got:\n%s", body)
245+
}
246+
var doc jsonRunDocument
247+
if err := json.Unmarshal([]byte(body), &doc); err != nil {
248+
t.Fatalf("expected schema_version 1 JSON on cancel, decode error: %v\nraw:\n%s", err, body)
249+
}
250+
if doc.SchemaVersion != jsonSchemaVersion {
251+
t.Fatalf("schema_version = %d", doc.SchemaVersion)
252+
}
253+
}
254+
255+
func TestRunRainOnRepos_CancelSkipsRemaining(t *testing.T) {
256+
baseURL, cleanup := startStallTCPListener(t)
257+
defer cleanup()
258+
259+
stallA := testutil.CreateTestRepo(t, testutil.RepoOptions{
260+
Name: "seq-stall-a",
261+
Remotes: map[string]string{
262+
"origin": baseURL + "/seq-stall-a.git",
263+
},
264+
})
265+
stallB := testutil.CreateTestRepo(t, testutil.RepoOptions{
266+
Name: "seq-stall-b",
267+
Remotes: map[string]string{
268+
"origin": baseURL + "/seq-stall-b.git",
269+
},
270+
})
271+
stallC := testutil.CreateTestRepo(t, testutil.RepoOptions{
272+
Name: "seq-stall-c",
273+
Remotes: map[string]string{
274+
"origin": baseURL + "/seq-stall-c.git",
275+
},
276+
})
277+
278+
runCtx, cancel := context.WithCancel(context.Background())
279+
rainOpts := git.RainOptions{
280+
FetchTimeoutSec: 30,
281+
RunCtx: runCtx,
282+
}
283+
repos := []git.Repository{
284+
{Name: "seq-stall-a", Path: stallA, Selected: true},
285+
{Name: "seq-stall-b", Path: stallB, Selected: true},
286+
{Name: "seq-stall-c", Path: stallC, Selected: true},
287+
}
288+
289+
oldStdout := os.Stdout
290+
r, w, _ := os.Pipe()
291+
os.Stdout = w
292+
defer func() { os.Stdout = oldStdout }()
293+
294+
done := make(chan error, 1)
295+
start := time.Now()
296+
go func() {
297+
done <- runRainOnRepos(&registry.Registry{}, repos, rainOpts, false)
298+
}()
299+
300+
time.Sleep(300 * time.Millisecond)
301+
cancel()
302+
303+
select {
304+
case err := <-done:
305+
if err != nil {
306+
t.Fatalf("runRainOnRepos: %v", err)
307+
}
308+
case <-time.After(5 * time.Second):
309+
t.Fatal("runRainOnRepos did not return after cancel")
310+
}
311+
elapsed := time.Since(start)
312+
313+
_ = w.Close()
314+
var out bytes.Buffer
315+
_, _ = io.Copy(&out, r)
316+
body := out.String()
317+
318+
if !strings.Contains(body, "Aborted.") {
319+
t.Fatalf("expected Aborted. after cancel, got:\n%s", body)
320+
}
321+
if strings.Contains(body, "rain delivered") {
322+
t.Fatalf("did not expect completed summary after cancel, got:\n%s", body)
323+
}
324+
if elapsed > 5*time.Second {
325+
t.Fatalf("run took %v after cancel; remaining repos should be skipped", elapsed)
326+
}
327+
frozenLines := strings.Count(body, "❄")
328+
if frozenLines >= 3 {
329+
t.Fatalf("expected remaining repos skipped after cancel, got %d frozen lines:\n%s", frozenLines, body)
330+
}
331+
}
332+
333+
func TestRunDryRun_CancelAborts(t *testing.T) {
334+
runCtx, cancel := context.WithCancel(context.Background())
335+
cancel() // already cancelled before scan
336+
337+
cfg := config.DefaultConfig()
338+
opts := git.DefaultScanOptions()
339+
opts.RootPath = t.TempDir()
340+
opts.DisableScan = false
341+
opts.Workers = 1
342+
343+
oldStdout := os.Stdout
344+
r, w, _ := os.Pipe()
345+
os.Stdout = w
346+
defer func() { os.Stdout = oldStdout }()
347+
348+
err := runDryRun(opts, git.RainOptions{RunCtx: runCtx}, false, &cfg)
349+
_ = w.Close()
350+
var out bytes.Buffer
351+
_, _ = io.Copy(&out, r)
352+
body := out.String()
353+
354+
if err != nil {
355+
t.Fatalf("human dry-run cancel should return nil, got %v", err)
356+
}
357+
if !strings.Contains(body, "Aborted.") {
358+
t.Fatalf("expected Aborted. after dry-run cancel, got:\n%s", body)
359+
}
360+
if strings.Contains(body, "Would run") {
361+
t.Fatalf("did not expect dry-run listing after cancel, got:\n%s", body)
362+
}
363+
}
364+
365+
func TestRunDryRun_JSONCancelReturnsError(t *testing.T) {
366+
runCtx, cancel := context.WithCancel(context.Background())
367+
cancel()
368+
369+
prevJSON := rainJSON
370+
rainJSON = true
371+
defer func() { rainJSON = prevJSON }()
372+
373+
cfg := config.DefaultConfig()
374+
opts := git.DefaultScanOptions()
375+
opts.RootPath = t.TempDir()
376+
opts.Workers = 1
377+
378+
oldStdout := os.Stdout
379+
r, w, _ := os.Pipe()
380+
os.Stdout = w
381+
defer func() { os.Stdout = oldStdout }()
382+
383+
err := runDryRun(opts, git.RainOptions{RunCtx: runCtx}, false, &cfg)
384+
_ = w.Close()
385+
var out bytes.Buffer
386+
_, _ = io.Copy(&out, r)
387+
body := out.String()
388+
389+
if err == nil || !strings.Contains(err.Error(), "interrupted") {
390+
t.Fatalf("expected interrupted error, got %v", err)
391+
}
392+
if strings.Contains(body, "Aborted.") {
393+
t.Fatalf("--json dry-run cancel must not print Aborted., got:\n%s", body)
394+
}
395+
}
396+
172397
func startStallTCPListener(t *testing.T) (baseURL string, cleanup func()) {
173398
t.Helper()
174399
ln, err := net.Listen("tcp", "127.0.0.1:0")

‎cmd/root.go‎

Lines changed: 48 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -338,8 +338,12 @@ type rainTotals struct {
338338
// and accumulates outcome counts. Each repo's output is written as a single block
339339
// directly to stdout. Used for the --rain TUI post-processing path; the default
340340
// CLI run uses runRainDefaultStream for parallel execution.
341+
// Stops starting new repos when RunCtx is cancelled (SIGINT/SIGTERM).
341342
func processRainRepositories(reg *registry.Registry, repos []git.Repository, rainOpts git.RainOptions, fullSync bool, totals *rainTotals, jsonReports *[]jsonRepoResult) {
342343
for i, repo := range repos {
344+
if rainOpts.RunCtx != nil && rainOpts.RunCtx.Err() != nil {
345+
return
346+
}
343347
var buf strings.Builder
344348
delta, report := runRainOnRepo(reg, repo, rainOpts, fullSync, i+1, len(repos), &buf, !rainJSON)
345349
if !rainJSON {
@@ -355,6 +359,20 @@ func processRainRepositories(reg *registry.Registry, repos []git.Repository, rai
355359
}
356360
}
357361

362+
// reportRunInterrupted handles SIGINT/SIGTERM after work stops. Human mode prints
363+
// Aborted. and returns nil; --json emits schema_version 1 then a non-zero error so
364+
// agents do not treat cancel as a successful empty run.
365+
func reportRunInterrupted(rainOpts git.RainOptions, fullSync bool, totals rainTotals, reports []jsonRepoResult) error {
366+
if rainJSON {
367+
if err := emitJSONRun(buildJSONRunMeta(rainOpts, fullSync), totals, reports); err != nil {
368+
return err
369+
}
370+
return fmt.Errorf("interrupted")
371+
}
372+
fmt.Println("Aborted.")
373+
return nil
374+
}
375+
358376
// runRainOnRepo runs the rain operation for a single repository, writing its
359377
// entire output block (header + branch lines + trailing blank line) into out.
360378
// totalStr is rendered as "[N/M] reponame"; pass "?" for M when the total is
@@ -511,10 +529,21 @@ func summarizeBranchRun(failed, frozen, updated int, branches []git.RainBranchRe
511529
}
512530

513531
func runDryRun(scanOpts git.ScanOptions, rainOpts git.RainOptions, fullSync bool, cfg *config.Config) error {
532+
// Honor RunCtx so SIGINT/SIGTERM can stop a long scan (NotifyContext owns the signals).
533+
if rainOpts.RunCtx != nil {
534+
scanOpts.Ctx = rainOpts.RunCtx
535+
}
514536
repos, err := git.ScanRepositories(scanOpts)
515537
if err != nil {
516538
return fmt.Errorf("repository scan failed: %w", err)
517539
}
540+
if rainOpts.RunCtx != nil && rainOpts.RunCtx.Err() != nil {
541+
if rainJSON {
542+
return fmt.Errorf("interrupted")
543+
}
544+
fmt.Println("Aborted.")
545+
return nil
546+
}
518547

519548
if rainJSON {
520549
return emitJSONDryRun(buildJSONRunMeta(rainOpts, fullSync), repos)
@@ -582,7 +611,13 @@ func runDryRun(scanOpts git.ScanOptions, rainOpts git.RainOptions, fullSync bool
582611
// The filesystem scan runs concurrently; repos stream into the picker as they
583612
// are discovered. After confirmation, the same default or --sync behavior runs.
584613
func runRainTUIStream(cfg *config.Config, reg *registry.Registry, regPath string, opts git.ScanOptions, rainOpts git.RainOptions, fullSync bool) error {
585-
ctx, cancelScan := context.WithCancel(context.Background())
614+
// Derive scan cancellation from RunCtx so SIGINT/SIGTERM stops the walk
615+
// (and in-flight analyze git) instead of only the network process group.
616+
parent := rainOpts.RunCtx
617+
if parent == nil {
618+
parent = context.Background()
619+
}
620+
ctx, cancelScan := context.WithCancel(parent)
586621
defer cancelScan()
587622
opts.Ctx = ctx
588623

@@ -930,9 +965,15 @@ func runRainDefaultStream(cfg *config.Config, reg *registry.Registry, regPath st
930965
printMu.Lock()
931966
defer printMu.Unlock()
932967

968+
totals := rainTotals{
969+
updated: int(atomic.LoadInt64(&updated)),
970+
skipped: int(atomic.LoadInt64(&skipped)),
971+
frozen: int(atomic.LoadInt64(&frozen)),
972+
failed: int(atomic.LoadInt64(&failed)),
973+
}
974+
933975
if ctx.Err() != nil {
934-
fmt.Println("Aborted.")
935-
return nil
976+
return reportRunInterrupted(rainOpts, fullSync, totals, jsonReports)
936977
}
937978

938979
if atomic.LoadInt64(&seq) == 0 {
@@ -943,13 +984,6 @@ func runRainDefaultStream(cfg *config.Config, reg *registry.Registry, regPath st
943984
return nil
944985
}
945986

946-
totals := rainTotals{
947-
updated: int(atomic.LoadInt64(&updated)),
948-
skipped: int(atomic.LoadInt64(&skipped)),
949-
frozen: int(atomic.LoadInt64(&frozen)),
950-
failed: int(atomic.LoadInt64(&failed)),
951-
}
952-
953987
if rainJSON {
954988
if err := emitJSONRun(buildJSONRunMeta(rainOpts, fullSync), totals, jsonReports); err != nil {
955989
return err
@@ -999,6 +1033,10 @@ func runRainOnRepos(reg *registry.Registry, repos []git.Repository, opts git.Rai
9991033
var jsonReports []jsonRepoResult
10001034
processRainRepositories(reg, repos, opts, fullSync, &totals, &jsonReports)
10011035

1036+
if opts.RunCtx != nil && opts.RunCtx.Err() != nil {
1037+
return reportRunInterrupted(opts, fullSync, totals, jsonReports)
1038+
}
1039+
10021040
if rainJSON {
10031041
if err := emitJSONRun(buildJSONRunMeta(opts, fullSync), totals, jsonReports); err != nil {
10041042
return err

0 commit comments

Comments
 (0)