diff --git a/cmd/cbzoptimizer/commands/watch_command.go b/cmd/cbzoptimizer/commands/watch_command.go index e7447dc..3e82d8e 100644 --- a/cmd/cbzoptimizer/commands/watch_command.go +++ b/cmd/cbzoptimizer/commands/watch_command.go @@ -115,9 +115,7 @@ func WatchCommand(_ *cobra.Command, args []string) error { if err := addRecursiveWatch(watcher, path); err != nil { return fmt.Errorf("failed to watch path %s: %w", path, err) } - if backfill { - backfillExistingArchives(path, debouncer.Trigger) - } + maybeBackfillExistingArchives(backfill, path, debouncer.Trigger) for { select { @@ -208,6 +206,17 @@ func backfillExistingArchives(rootPath string, process func(path string)) { } } +// maybeBackfillExistingArchives runs backfillExistingArchives against +// rootPath only when enabled is true. It exists as its own function (rather +// than inlining the `if` check at the call site) so the gating decision used +// by WatchCommand can be exercised directly in tests. +func maybeBackfillExistingArchives(enabled bool, rootPath string, process func(path string)) { + if !enabled { + return + } + backfillExistingArchives(rootPath, process) +} + func shouldProcessWatchEvent(event fsnotify.Event) bool { return event.Has(fsnotify.Create) || event.Has(fsnotify.Write) || event.Has(fsnotify.Rename) } diff --git a/cmd/cbzoptimizer/commands/watch_command_test.go b/cmd/cbzoptimizer/commands/watch_command_test.go index d3a4222..0484511 100644 --- a/cmd/cbzoptimizer/commands/watch_command_test.go +++ b/cmd/cbzoptimizer/commands/watch_command_test.go @@ -181,11 +181,11 @@ func TestWatchCommandBackfillFlagDefaultsToFalse(t *testing.T) { assert.Equal(t, "bool", flag.Value.Type()) } -func TestBackfillExistingArchivesOnlyInvokedWhenRequested(t *testing.T) { +func TestMaybeBackfillExistingArchivesOnlyInvokedWhenRequested(t *testing.T) { root := t.TempDir() require.NoError(t, os.WriteFile(filepath.Join(root, "chapter1.cbz"), []byte("data"), 0o644)) - runBackfill := func(backfill bool) []string { + runBackfill := func(enabled bool) []string { var found []string var mu sync.Mutex process := func(path string) { @@ -193,11 +193,9 @@ func TestBackfillExistingArchivesOnlyInvokedWhenRequested(t *testing.T) { defer mu.Unlock() found = append(found, path) } - // Mirrors the gating logic in WatchCommand: backfillExistingArchives - // must only run when the --backfill flag is set. - if backfill { - backfillExistingArchives(root, process) - } + // This is the exact same gating call WatchCommand makes based on the + // --backfill flag value. + maybeBackfillExistingArchives(enabled, root, process) return found }