From d45ac3536c3ba8c01ad403e325bbd8e7481a7cce Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 8 Nov 2026 04:56:22 +0000 Subject: [PATCH 1/6] sync: keep crontab output on API failure, fix dry-run hint PutMonitors called fatal, and os.Exit skipped the deferred crontab print. `cronitor sync --auto file | crontab -` then installed an empty crontab. Return that failure like a shim or save failure: print the original crontab and exit 1. Verbose logs for that run go to stderr so they are not part of the pipe. The dry-run reminder no longer appends --auto --silent. Completing the run is the same command without --dry-run. Co-authored-by: August Flanagan --- README.md | 2 +- cmd/discover.go | 48 +++++++++++++++++++++++++---- cmd/root.go | 23 ++++++++++++-- cmd/shell_shim_sync_test.go | 7 +++++ cmd/sync_rerun_test.go | 60 +++++++++++++++++++++++++++++++++++++ docs/releases/33.15.md | 2 +- 6 files changed, 133 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e8adccd..65f2639 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ There are three ways to run sync: | `cronitor sync --auto` | nothing | yes | **all of them** | - Run plain `cronitor sync` again whenever you add jobs or change a schedule. It shows one summary with each change (for example `L3 Nightly backup: schedule 0 2 * * * → 30 3 * * *`) and asks once. If nothing changed, it asks nothing. -- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed, so `cronitor sync --auto file | crontab -` is safe. If the shell wrapper cannot be installed or the crontab cannot be saved, it prints the original crontab and exits 1. It also monitors every new job, so it is not the way to pick up one schedule change. +- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed, so `cronitor sync --auto file | crontab -` is safe. If the Cronitor API call fails, the shell wrapper cannot be installed, or the crontab cannot be saved, it prints the original crontab and exits 1. It also monitors every new job, so it is not the way to pick up one schedule change. - If any crontab fails to apply, in any mode, sync exits 1. - For a monitored job, sync sends only what changed. Names, tags and alert lists set in Cronitor are kept; alert lists change only with `--notification-list` (omitting the flag keeps existing lists; new monitors get Cronitor's default). A `# Name:` comment is updated to the name in Cronitor. - If a monitor was deleted in Cronitor, sync warns and does not create it again. A hand-written `CRONITOR=new-key` line for a monitor that was never created gets the same warning; create the monitor first, or remove the key and let sync add it. diff --git a/cmd/discover.go b/cmd/discover.go index 3212904..a11b550 100644 --- a/cmd/discover.go +++ b/cmd/discover.go @@ -111,9 +111,25 @@ var notificationList string var existingMonitors = ExistingMonitors{} var processingMultipleCrontabs = false var userAbortedSync = false // Set to true when user presses Ctrl+D to abort sync entirely -var syncFile string // Path to YAML/JSON file for bulk monitor import -var syncFormat string // --format: "", "short" or "exec" -var withMonitored bool // --with-monitored: also ask about jobs that are already monitored + +// stdoutIsCrontab is true while `cronitor sync --auto` handles one crontab +// file and will print it on stdout. Verbose logs go to stderr so the pipe +// cannot install log text or a partial crontab. +var stdoutIsCrontab bool + +// reserveStdoutForCrontab reports whether this sync should keep stdout for +// the crontab. Flags are already parsed when it runs (including from +// initConfig, before the config file is logged). +func reserveStdoutForCrontab(args []string) bool { + if runtime.GOOS == "windows" || !isAutoDiscover || isSilent { + return false + } + return len(args) > 0 && !isPathToDirectory(args[0]) +} + +var syncFile string // Path to YAML/JSON file for bulk monitor import +var syncFormat string // --format: "", "short" or "exec" +var withMonitored bool // --with-monitored: also ask about jobs that are already monitored // To deprecate this feature we are hijacking this flag that will trigger removal of auto-discover lines from existing user's crontabs. var noAutoDiscover = true @@ -199,6 +215,7 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read processingMultipleCrontabs = false userAbortedSync = false jobsNeedingSudo = 0 + stdoutIsCrontab = false if len(viper.GetString(varApiKey)) < 10 { fatal(discoverMissingAPIKeyGuidance(), 1) @@ -216,6 +233,14 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read return } + // initConfig may already have set this so the config log stays off + // stdout. Set it again from the args Run received, and clear it + // when the command returns. + if reserveStdoutForCrontab(args) { + stdoutIsCrontab = true + defer func() { stdoutIsCrontab = false }() + } + var username string if u, err := user.Current(); err == nil { username = u.Username @@ -296,7 +321,12 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read if importedCrontabs > 0 { msg := "Reminder: This is a DRY-RUN. Integration is not complete." next := "To complete integration, run:" - cmd := fmt.Sprintf(" %s --auto --silent", saveCommand) + // Same command without --dry-run. That is `cronitor sync` + // after an interactive dry run, or `cronitor sync --auto` + // when --auto was already set. --auto --silent is neither: + // --auto would monitor every new job, and with --silent it + // also skips printing the crontab. + cmd := " " + saveCommand if isAutoDiscover || isSilent { fmt.Fprintln(os.Stderr, msg) fmt.Fprintln(os.Stderr, next) @@ -639,6 +669,7 @@ func finishSync(plans []*crontabPlan) int { // When running --auto mode with a single crontab, you should be able to pipe or redirect crontab // output elsewhere, so print it whether or not anything changed. Print first, then // exit, so a failed apply still writes the original crontab before exitFn. + // applyPlan must return on failure. os.Exit skips this print. applyFailed := false defer func() { if !isSilent && isAutoDiscover && !processingMultipleCrontabs { @@ -1052,7 +1083,14 @@ func applyPlan(plan *crontabPlan) bool { printDoneText("Sending to Cronitor", true) sent, err := getCronitorApi().PutMonitors(monitors) if err != nil { - fatal(err.Error(), 1) + // os.Exit here skips finishSync's deferred print, so + // `cronitor sync --auto file | crontab -` installs an empty + // crontab. Same as a shim or save failure: stdout gets the + // original crontab (not the planned rewrite) and the process + // exits 1. + plan.output = crontab.Original() + reportError(err.Error()) + return false } // New monitors get their code from the response. Existing lines keep // the key they have: it may be a hand-written key, not the code. diff --git a/cmd/root.go b/cmd/root.go index 76a5d43..8a11e68 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -111,12 +111,19 @@ func init() { // initConfig reads in config file and ENV variables if set. func initConfig() { viper.AutomaticEnv() // read in environment variables that match + // ParseFlags has already run. Do this before logging the config path: + // with --verbose that line would otherwise precede the crontab on stdout. + stdoutIsCrontab = reserveStdoutForCrontab(discoverCmd.Flags().Args()) configFile := viper.GetString(varConfig) // If a custom config file is specified by flag or env var, use it. Otherwise use default file. if len(configFile) > 0 { if len(configFile) < 5 || strings.ToLower(configFile[len(configFile)-5:]) != ".json" { - fmt.Println("Error: Config file must be a .json file") + if stdoutIsCrontab { + fmt.Fprintln(os.Stderr, "Error: Config file must be a .json file") + } else { + fmt.Println("Error: Config file must be a .json file") + } } viper.SetConfigFile(configFile) } else { @@ -483,11 +490,24 @@ func log(msg string) { } if verbose { + // sync --auto on one crontab file owns stdout (`... | crontab -`). + // Verbose text there would be installed as the crontab. + if stdoutIsCrontab { + fmt.Fprintln(os.Stderr, msg) + return + } fmt.Println(msg) } } func fatal(msg string, exitCode int) { + reportError(msg) + os.Exit(exitCode) +} + +// reportError writes a redacted error to stderr and the debug log. +// It does not exit, so a caller can still print a crontab on stdout. +func reportError(msg string) { msg = redactSecrets(msg) debugLog := viper.GetString(varLog) if len(debugLog) > 0 { @@ -497,7 +517,6 @@ func fatal(msg string, exitCode int) { } fmt.Fprintln(os.Stderr, msg) - os.Exit(exitCode) } // redactSecrets removes remembered secrets and the configured API / ping keys diff --git a/cmd/shell_shim_sync_test.go b/cmd/shell_shim_sync_test.go index f5d8672..b9894ab 100644 --- a/cmd/shell_shim_sync_test.go +++ b/cmd/shell_shim_sync_test.go @@ -41,6 +41,12 @@ func runSyncArgs(t *testing.T, serverURL, path string, extra ...string) string { isAutoDiscover = false isSilent = false withMonitored = false + stdoutIsCrontab = false + verbose = false + if f := RootCmd.PersistentFlags().Lookup("verbose"); f != nil { + _ = f.Value.Set("false") + f.Changed = false + } _ = discoverCmd.Flags().Set("format", "") _ = discoverCmd.Flags().Set("dry-run", "false") _ = discoverCmd.Flags().Set("no-stdout", "false") @@ -151,6 +157,7 @@ func withSyncFixture(t *testing.T) (serverURL, shimPath string) { lib.BaseURLOverride = oldBase isAutoDiscover = oldAuto isSilent = oldSilent + stdoutIsCrontab = false syncFormat = oldFormat dryRun = oldDry existingMonitors = oldMonitors diff --git a/cmd/sync_rerun_test.go b/cmd/sync_rerun_test.go index fc6a106..d511e1a 100644 --- a/cmd/sync_rerun_test.go +++ b/cmd/sync_rerun_test.go @@ -603,6 +603,66 @@ func TestSyncAutoPrintsOriginalWhenShimInstallFails(t *testing.T) { } } +// An API failure used to os.Exit inside applyPlan, skipping the deferred +// print. `cronitor sync --auto file | crontab -` then installed an empty crontab. +func TestSyncAutoPrintsOriginalWhenAPIFails(t *testing.T) { + withSyncFixture(t) + withNotificationList(t, "") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.Method == http.MethodGet { + io.WriteString(w, `{"total_monitor_count":0,"page_size":50,"monitors":[]}`) + return + } + http.Error(w, "nope", http.StatusInternalServerError) + })) + t.Cleanup(srv.Close) + body := "0 2 * * * /usr/bin/backup.sh\n" + path := writeCron(t, body) + + var code int + oldExit := exitFn + t.Cleanup(func() { + exitFn = oldExit + verbose = false + if f := RootCmd.PersistentFlags().Lookup("verbose"); f != nil { + _ = f.Value.Set("false") + f.Changed = false + } + }) + exitFn = func(c int) { code = c } + + // A previous test may have viper.Set the config path, which hides + // --config. Clear that so this run actually logs "Reading config". + viperUnset(varConfig) + // --verbose must not prefix the crontab with the config log or the + // request body. Those used to be written before os.Exit, so the pipe + // installed a partial crontab. + stderr := runSyncArgs(t, srv.URL, path, "--auto", "--verbose") + + if code != 1 { + t.Fatalf("exit %d; want 1 after the API call fails", code) + } + if strings.TrimSpace(lastSyncStdout) == "" { + t.Fatal("stdout is empty; the pipe would install an empty crontab") + } + if strings.Contains(lastSyncStdout, "SHELL=") || strings.Contains(lastSyncStdout, "CRONITOR=") { + t.Fatalf("stdout is the planned crontab:\n%s", lastSyncStdout) + } + if strings.Contains(lastSyncStdout, "Reading config") || strings.Contains(lastSyncStdout, "Request:") { + t.Fatalf("stdout mixed with logs:\n%s", lastSyncStdout) + } + if strings.TrimSpace(lastSyncStdout) != strings.TrimSpace(body) { + t.Fatalf("stdout = %q; want the original crontab", lastSyncStdout) + } + if got := readCron(t, path); got != body { + t.Fatalf("crontab on disk changed:\n%s", got) + } + if !strings.Contains(stderr, "Error from") || !strings.Contains(stderr, "Request:") || !strings.Contains(stderr, "Reading config") { + t.Fatalf("stderr = %q; want the API error and the verbose logs", stderr) + } +} + func TestSyncSilentStillConfirms(t *testing.T) { withSyncFixture(t) withNotificationList(t, "") diff --git a/docs/releases/33.15.md b/docs/releases/33.15.md index e14d0bf..4f73ac2 100644 --- a/docs/releases/33.15.md +++ b/docs/releases/33.15.md @@ -8,7 +8,7 @@ Sync is now safe and quiet to run again on a crontab it already set up ([#90](ht - Plain `cronitor sync` is the normal way to rerun. It checks every monitored job against Cronitor and picks up schedule and timezone changes without asking about the job. - For a job that is already monitored, sync sends only what changed: the schedule, the timezone, and the alert list when you pass `--notification-list`. Without that flag, existing alert lists are kept and new monitors get Cronitor's default. Before, every sync replaced tags set in Cronitor with `cron-job` and reset alert lists to `default`. - A changed `CRON_TZ` or `TZ` line now updates the monitor's timezone even when the schedule stays the same. Before, sync missed it. -- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`), so `cronitor sync --auto file | crontab -` never installs an empty crontab. If the shell wrapper cannot be installed or the crontab cannot be saved, it prints the original crontab and exits 1, so that pipe reinstalls a working crontab instead of one whose `SHELL=` points at a missing wrapper. Use it for scripts, not to pick up one schedule change. +- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`), so `cronitor sync --auto file | crontab -` never installs an empty crontab. If the Cronitor API call fails, the shell wrapper cannot be installed, or the crontab cannot be saved, it prints the original crontab and exits 1, so that pipe reinstalls a working crontab instead of an empty one or one whose `SHELL=` points at a missing wrapper. Use it for scripts, not to pick up one schedule change. - If any crontab fails to apply, in any mode (interactive or `--auto`, one crontab or several), sync now exits 1. Before, it exited 0. - `--silent` hides status messages. On an interactive run it still asks `Apply these changes?` before sending or writing, so a monitored job's schedule cannot change with no confirmation. Combined with `--auto`, it also skips printing the crontab. - The name in Cronitor wins. Sync no longer sends the name from a `# Name:` comment for a monitored job, so a rename in the dashboard stays. If the comment differs, sync updates it. It does not add a new `# Name:` comment. From ebee7b9acc95f5784e141a6a52d60e1bbbd96619 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 8 Nov 2026 05:19:25 +0000 Subject: [PATCH 2/6] sync: exit 1 when a named crontab cannot be used A missing, unreadable, or unwritable file passed to sync used to print nothing and exit 0, so a pipe could install an empty crontab. Fail those runs, and print the original crontab when it is readable. Also print that crontab before a missing API key or bad --format in --auto single-file mode, and keep API keys out of the dry-run reminder. Co-authored-by: August Flanagan --- README.md | 2 +- cmd/discover.go | 153 +++++++++++++++++++++++++++++++++++++++-- cmd/sync_rerun_test.go | 70 +++++++++++++++---- docs/releases/33.15.md | 2 +- 4 files changed, 205 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 65f2639..46a4d8c 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ There are three ways to run sync: | `cronitor sync --auto` | nothing | yes | **all of them** | - Run plain `cronitor sync` again whenever you add jobs or change a schedule. It shows one summary with each change (for example `L3 Nightly backup: schedule 0 2 * * * → 30 3 * * *`) and asks once. If nothing changed, it asks nothing. -- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed, so `cronitor sync --auto file | crontab -` is safe. If the Cronitor API call fails, the shell wrapper cannot be installed, or the crontab cannot be saved, it prints the original crontab and exits 1. It also monitors every new job, so it is not the way to pick up one schedule change. +- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. On any failure, sync exits 1 and prints the original crontab when it can read one. Use `set -o pipefail` (or check the exit code) so a pipe does not install output from a failed run, for example when the file is missing. It also monitors every new job, so it is not the way to pick up one schedule change. - If any crontab fails to apply, in any mode, sync exits 1. - For a monitored job, sync sends only what changed. Names, tags and alert lists set in Cronitor are kept; alert lists change only with `--notification-list` (omitting the flag keeps existing lists; new monitors get Cronitor's default). A `# Name:` comment is updated to the name in Cronitor. - If a monitor was deleted in Cronitor, sync warns and does not create it again. A hand-written `CRONITOR=new-key` line for a monitor that was never created gets the same warning; create the monitor first, or remove the key and let sync add it. diff --git a/cmd/discover.go b/cmd/discover.go index a11b550..d07e15c 100644 --- a/cmd/discover.go +++ b/cmd/discover.go @@ -127,6 +127,92 @@ func reserveStdoutForCrontab(args []string) bool { return len(args) > 0 && !isPathToDirectory(args[0]) } +// printOriginalCrontab prints the crontab for a --auto run on one readable +// file. Sync calls it when it fails before a plan exists. A missing or +// unreadable file prints nothing. +func printOriginalCrontab(args []string) { + if !reserveStdoutForCrontab(args) { + return + } + info, err := os.Stat(args[0]) + if err != nil || !info.Mode().IsRegular() { + return + } + b, err := os.ReadFile(args[0]) + if err != nil { + return + } + text := strings.TrimSpace(string(b)) + if text == "" { + return + } + fmt.Println(text) +} + +// redactAPIKeyArgs hides a Cronitor API key passed on the command line so +// the dry-run reminder does not print it. Forms: -k X, -kX, -k=X, +// --api-key X, --api-key=X, and -k with the value attached in a short +// cluster such as -vkX. +func redactAPIKeyArgs(args []string) []string { + out := make([]string, 0, len(args)) + for i := 0; i < len(args); i++ { + a := args[i] + if i == 0 { + out = append(out, a) + continue + } + redacted, takeNext := redactAPIKeyToken(a) + out = append(out, redacted) + if takeNext && i+1 < len(args) { + i++ + out = append(out, "") + } + } + return out +} + +// shortFlagTakesValue reports shorthands on sync whose value consumes the +// rest of a combined short-flag cluster. k is handled by the caller. +func shortFlagTakesValue(letter byte) bool { + switch letter { + case 'c', 'e', 'l', 'n', 'p', 'u': + return true + default: + return false + } +} + +// redactAPIKeyToken redacts one argv element. takeNext is true when the +// API key is the following argument. +func redactAPIKeyToken(token string) (string, bool) { + switch { + case token == "--api-key" || token == "-k": + return token, true + case strings.HasPrefix(token, "--api-key="): + return "--api-key=", false + case strings.HasPrefix(token, "-k="): + return "-k=", false + } + if !strings.HasPrefix(token, "-") || strings.HasPrefix(token, "--") || len(token) < 2 { + return token, false + } + body := token[1:] + for i := 0; i < len(body); i++ { + switch body[i] { + case 'k': + if i+1 < len(body) { + return token[:i+2] + "", false + } + return token, true + default: + if shortFlagTakesValue(body[i]) { + return token, false + } + } + } + return token, false +} + var syncFile string // Path to YAML/JSON file for bulk monitor import var syncFormat string // --format: "", "short" or "exec" var withMonitored bool // --with-monitored: also ask about jobs that are already monitored @@ -166,8 +252,9 @@ There are three ways to run sync: $ cronitor sync --auto > Asks nothing. Monitors every new job, sends schedule and timezone changes, and writes the crontab - > Prints the crontab to stdout even when nothing changed, so pipelines such as - cronitor sync --auto file | crontab - never install an empty crontab + > Prints the crontab to stdout even when nothing changed. On failure it exits 1 + and prints the original crontab when it can read one. Use set -o pipefail + (or check the exit code) so a pipe does not install output from a failed run > Use it to automate sync, not to pick up one schedule change: it also monitors every new job For a job that is already monitored, sync sends only what changed. Names, tags and alert lists set @@ -218,9 +305,13 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read stdoutIsCrontab = false if len(viper.GetString(varApiKey)) < 10 { + // Fail before a plan exists. When this is --auto on one readable + // file, stdout still gets that crontab so a pipe can reinstall it. + printOriginalCrontab(args) fatal(discoverMissingAPIKeyGuidance(), 1) } if _, err := parseSyncFormat(syncFormat); err != nil { + printOriginalCrontab(args) fatal(err.Error(), 1) } if runtime.GOOS == "windows" && syncFormat != "" { @@ -315,7 +406,7 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read printSuccessText("View your dashboard https://cronitor.io/app/dashboard", false) } if dryRun { - saveCommand := strings.Join(os.Args, " ") + saveCommand := strings.Join(redactAPIKeyArgs(os.Args), " ") saveCommand = strings.Replace(saveCommand, " --dry-run", "", -1) if importedCrontabs > 0 { @@ -344,6 +435,18 @@ On Unix, new jobs use a SHELL shim (CRONITOR=; MONITORIO= is also read // crontabWritable reports whether sync can write a crontab. Tests replace it. var crontabWritable = func(c *lib.Crontab) bool { return c.IsWritable() } +// crontabFileReadable reports whether a file crontab can be opened. A user +// crontab is not a path. Callers use this after Parse fails, to tell an +// unreadable file from an empty one. +func crontabFileReadable(c *lib.Crontab) bool { + f, err := os.Open(c.Filename) + if err != nil { + return false + } + f.Close() + return true +} + // jobsNeedingSudo counts jobs in crontabs this user cannot write. var jobsNeedingSudo int @@ -670,10 +773,24 @@ func finishSync(plans []*crontabPlan) int { // output elsewhere, so print it whether or not anything changed. Print first, then // exit, so a failed apply still writes the original crontab before exitFn. // applyPlan must return on failure. os.Exit skips this print. + // A missing or unwritable file is the same kind of failure: exit 1, and + // print the original only when there is one to print. applyFailed := false + unusable := false + for _, p := range plans { + if p.unusable { + unusable = true + applyFailed = true + } + } defer func() { if !isSilent && isAutoDiscover && !processingMultipleCrontabs { for _, p := range plans { + // A missing file has no crontab. A blank line would still + // be installed by `... | crontab -`. + if p.unusable && strings.TrimSpace(p.output) == "" { + continue + } fmt.Println(strings.TrimSpace(p.output)) } } @@ -681,6 +798,9 @@ func finishSync(plans []*crontabPlan) int { exitFn(1) } }() + if unusable { + return 0 + } var todo []*crontabPlan for _, p := range plans { if p.hasChanges() { @@ -772,6 +892,7 @@ type crontabPlan struct { aborted bool // the user quit rewrites bool // the crontab text changes even if no monitor does output string // the crontab text --auto prints: as planned, or as written + unusable bool // missing or not writable: do not apply; finishSync exits 1 } type promptChoice int @@ -815,15 +936,30 @@ var askAboutJob = func(line *lib.Line, name string, monitored bool) promptResult } // planCrontab reads a crontab and decides what to do with each job. It -// returns nil when the crontab cannot be used. +// returns nil when a crontab is skipped. One named file that does not exist +// or is not writable is an unusable plan: sync prints the original crontab +// when it has one, and exits 1. func planCrontab(crontab *lib.Crontab) *crontabPlan { if !crontab.Exists() { + // One named file that is not there is a failure. Scanning many + // crontabs still skips a user who has none. + if !processingMultipleCrontabs { + reportError(fmt.Sprintf("%s does not exist", crontab.DisplayName())) + return &crontabPlan{crontab: crontab, unusable: true} + } printWarningText("This crontab does not exist. Skipping.", true) return nil } // This will mostly happen when the crontab is empty if err, _ := crontab.Parse(noAutoDiscover); err != nil { + // A named file that cannot be read is a failure. There is nothing + // to print. An empty crontab is still a skip: installing it changes + // nothing. Scanning many crontabs keeps the old skip. + if !processingMultipleCrontabs && !crontab.IsUserCrontab && !crontabFileReadable(crontab) { + reportError(err.Error()) + return &crontabPlan{crontab: crontab, unusable: true} + } // While scanning, an empty or unreadable system crontab is only logged. if !processingMultipleCrontabs || crontab.IsUserCrontab { printWarningText("This crontab is empty. Skipping.", true) @@ -837,10 +973,13 @@ func planCrontab(crontab *lib.Crontab) *crontabPlan { if !crontabWritable(crontab) { if processingMultipleCrontabs { jobsNeedingSudo += countJobs(crontab) - } else { - printWarningText("This crontab is not writable. Run sync with sudo.", true) + return nil } - return nil + // Readable (Parse succeeded) but not writable. Same as an API, shim + // or save failure: stdout gets the original crontab when this run + // prints one, and the process exits 1. + reportError(fmt.Sprintf("%s is not writable. Run sync with sudo.", crontab.DisplayName())) + return &crontabPlan{crontab: crontab, output: crontab.Original(), unusable: true} } // If a timezone env var is set in the crontab it takes precedence over system tz diff --git a/cmd/sync_rerun_test.go b/cmd/sync_rerun_test.go index d511e1a..a113b7d 100644 --- a/cmd/sync_rerun_test.go +++ b/cmd/sync_rerun_test.go @@ -632,12 +632,10 @@ func TestSyncAutoPrintsOriginalWhenAPIFails(t *testing.T) { }) exitFn = func(c int) { code = c } - // A previous test may have viper.Set the config path, which hides - // --config. Clear that so this run actually logs "Reading config". + // A previous test may have viper.Set the config path, which hides --config. viperUnset(varConfig) - // --verbose must not prefix the crontab with the config log or the - // request body. Those used to be written before os.Exit, so the pipe - // installed a partial crontab. + // --verbose must not prefix the crontab. Those logs used to be written + // before os.Exit, so the pipe installed a partial crontab. stderr := runSyncArgs(t, srv.URL, path, "--auto", "--verbose") if code != 1 { @@ -646,23 +644,69 @@ func TestSyncAutoPrintsOriginalWhenAPIFails(t *testing.T) { if strings.TrimSpace(lastSyncStdout) == "" { t.Fatal("stdout is empty; the pipe would install an empty crontab") } - if strings.Contains(lastSyncStdout, "SHELL=") || strings.Contains(lastSyncStdout, "CRONITOR=") { - t.Fatalf("stdout is the planned crontab:\n%s", lastSyncStdout) - } - if strings.Contains(lastSyncStdout, "Reading config") || strings.Contains(lastSyncStdout, "Request:") { - t.Fatalf("stdout mixed with logs:\n%s", lastSyncStdout) - } if strings.TrimSpace(lastSyncStdout) != strings.TrimSpace(body) { t.Fatalf("stdout = %q; want the original crontab", lastSyncStdout) } if got := readCron(t, path); got != body { t.Fatalf("crontab on disk changed:\n%s", got) } - if !strings.Contains(stderr, "Error from") || !strings.Contains(stderr, "Request:") || !strings.Contains(stderr, "Reading config") { - t.Fatalf("stderr = %q; want the API error and the verbose logs", stderr) + if strings.TrimSpace(stderr) == "" { + t.Fatal("stderr is empty; the API error was not reported") } } +// A missing or unwritable file used to print nothing and exit 0, so +// `cronitor sync --auto file | crontab -` installed an empty crontab. +func TestSyncAutoExitsWhenCrontabMissingOrUnwritable(t *testing.T) { + withSyncFixture(t) + withNotificationList(t, "") + _, apiURL := newRerunAPI(t, backupMonitor) + + var code int + oldExit := exitFn + t.Cleanup(func() { exitFn = oldExit }) + exitFn = func(c int) { code = c } + + t.Run("missing", func(t *testing.T) { + code = 0 + missing := filepath.Join(t.TempDir(), "no-such-crontab") + stderr := runSyncArgs(t, apiURL, missing, "--auto") + if code != 1 { + t.Fatalf("exit %d; want 1 when the crontab does not exist", code) + } + if lastSyncStdout != "" { + t.Fatalf("stdout = %q; want nothing when the file does not exist", lastSyncStdout) + } + if strings.TrimSpace(stderr) == "" { + t.Fatal("stderr is empty; the missing file was not reported") + } + }) + + t.Run("unwritable", func(t *testing.T) { + code = 0 + body := "0 2 * * * /usr/bin/backup.sh\n" + path := writeCron(t, body) + // Root can still open a mode 0444 file, so stub the check planCrontab uses. + old := crontabWritable + t.Cleanup(func() { crontabWritable = old }) + crontabWritable = func(*lib.Crontab) bool { return false } + + stderr := runSyncArgs(t, apiURL, path, "--auto") + if code != 1 { + t.Fatalf("exit %d; want 1 when the crontab is not writable", code) + } + if strings.TrimSpace(lastSyncStdout) != strings.TrimSpace(body) { + t.Fatalf("stdout = %q; want the original crontab", lastSyncStdout) + } + if got := readCron(t, path); got != body { + t.Fatalf("crontab on disk changed:\n%s", got) + } + if strings.TrimSpace(stderr) == "" { + t.Fatal("stderr is empty; the unwritable file was not reported") + } + }) +} + func TestSyncSilentStillConfirms(t *testing.T) { withSyncFixture(t) withNotificationList(t, "") diff --git a/docs/releases/33.15.md b/docs/releases/33.15.md index 4f73ac2..04cd519 100644 --- a/docs/releases/33.15.md +++ b/docs/releases/33.15.md @@ -8,7 +8,7 @@ Sync is now safe and quiet to run again on a crontab it already set up ([#90](ht - Plain `cronitor sync` is the normal way to rerun. It checks every monitored job against Cronitor and picks up schedule and timezone changes without asking about the job. - For a job that is already monitored, sync sends only what changed: the schedule, the timezone, and the alert list when you pass `--notification-list`. Without that flag, existing alert lists are kept and new monitors get Cronitor's default. Before, every sync replaced tags set in Cronitor with `cron-job` and reset alert lists to `default`. - A changed `CRON_TZ` or `TZ` line now updates the monitor's timezone even when the schedule stays the same. Before, sync missed it. -- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`), so `cronitor sync --auto file | crontab -` never installs an empty crontab. If the Cronitor API call fails, the shell wrapper cannot be installed, or the crontab cannot be saved, it prints the original crontab and exits 1, so that pipe reinstalls a working crontab instead of an empty one or one whose `SHELL=` points at a missing wrapper. Use it for scripts, not to pick up one schedule change. +- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`). On any failure, sync exits 1 and, when it can read the file, prints the original crontab rather than an empty one or one whose `SHELL=` points at a missing wrapper. If it cannot read a crontab (for example the file is missing), nothing is printed: use `set -o pipefail` (or check the exit code) so the pipe does not install that failed run. Use it for scripts, not to pick up one schedule change. - If any crontab fails to apply, in any mode (interactive or `--auto`, one crontab or several), sync now exits 1. Before, it exited 0. - `--silent` hides status messages. On an interactive run it still asks `Apply these changes?` before sending or writing, so a monitored job's schedule cannot change with no confirmation. Combined with `--auto`, it also skips printing the crontab. - The name in Cronitor wins. Sync no longer sends the name from a `# Name:` comment for a monitored job, so a rename in the dashboard stays. If the comment differs, sync updates it. It does not add a new `# Name:` comment. From d9d25324600a1cf7e5b57423d044c4907806e293 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 8 Nov 2026 05:36:25 +0000 Subject: [PATCH 3/6] sync: capture crontab output before installing it pipefail does not stop crontab - from installing empty input. Point the README, release note, and sync help at a capture-first command, and redact ping keys in the dry-run reminder. Co-authored-by: August Flanagan --- README.md | 2 +- cmd/discover.go | 72 ++++++++++++++++++++++++++---------------- docs/releases/33.15.md | 3 +- 3 files changed, 48 insertions(+), 29 deletions(-) diff --git a/README.md b/README.md index 46a4d8c..c3a5244 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ There are three ways to run sync: | `cronitor sync --auto` | nothing | yes | **all of them** | - Run plain `cronitor sync` again whenever you add jobs or change a schedule. It shows one summary with each change (for example `L3 Nightly backup: schedule 0 2 * * * → 30 3 * * *`) and asks once. If nothing changed, it asks nothing. -- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. On any failure, sync exits 1 and prints the original crontab when it can read one. Use `set -o pipefail` (or check the exit code) so a pipe does not install output from a failed run, for example when the file is missing. It also monitors every new job, so it is not the way to pick up one schedule change. +- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. It also monitors every new job, so it is not the way to pick up one schedule change. - If any crontab fails to apply, in any mode, sync exits 1. - For a monitored job, sync sends only what changed. Names, tags and alert lists set in Cronitor are kept; alert lists change only with `--notification-list` (omitting the flag keeps existing lists; new monitors get Cronitor's default). A `# Name:` comment is updated to the name in Cronitor. - If a monitor was deleted in Cronitor, sync warns and does not create it again. A hand-written `CRONITOR=new-key` line for a monitor that was never created gets the same warning; create the monitor first, or remove the key and let sync add it. diff --git a/cmd/discover.go b/cmd/discover.go index d07e15c..4cc0f6c 100644 --- a/cmd/discover.go +++ b/cmd/discover.go @@ -149,10 +149,10 @@ func printOriginalCrontab(args []string) { fmt.Println(text) } -// redactAPIKeyArgs hides a Cronitor API key passed on the command line so -// the dry-run reminder does not print it. Forms: -k X, -kX, -k=X, -// --api-key X, --api-key=X, and -k with the value attached in a short -// cluster such as -vkX. +// redactAPIKeyArgs hides API and ping keys passed on the command line so +// the dry-run reminder does not print them. Forms: -k X, -kX, -k=X, +// --api-key X, --api-key=X, a short cluster such as -vkX or -vk=X, and the +// same forms for -p / --ping-api-key (placeholder ). func redactAPIKeyArgs(args []string) []string { out := make([]string, 0, len(args)) for i := 0; i < len(args); i++ { @@ -161,56 +161,72 @@ func redactAPIKeyArgs(args []string) []string { out = append(out, a) continue } - redacted, takeNext := redactAPIKeyToken(a) + redacted, next := redactAPIKeyToken(a) out = append(out, redacted) - if takeNext && i+1 < len(args) { + if next != "" && i+1 < len(args) { i++ - out = append(out, "") + out = append(out, next) } } return out } // shortFlagTakesValue reports shorthands on sync whose value consumes the -// rest of a combined short-flag cluster. k is handled by the caller. +// rest of a combined short-flag cluster. k and p are handled by the caller. func shortFlagTakesValue(letter byte) bool { switch letter { - case 'c', 'e', 'l', 'n', 'p', 'u': + case 'c', 'e', 'l', 'n', 'u': return true default: return false } } -// redactAPIKeyToken redacts one argv element. takeNext is true when the -// API key is the following argument. -func redactAPIKeyToken(token string) (string, bool) { +// redactAPIKeyToken redacts one argv element. next is the placeholder for +// the following argument, or "" when this token already holds the value. +func redactAPIKeyToken(token string) (string, string) { switch { case token == "--api-key" || token == "-k": - return token, true + return token, "" + case token == "--ping-api-key" || token == "-p": + return token, "" case strings.HasPrefix(token, "--api-key="): - return "--api-key=", false + return "--api-key=", "" + case strings.HasPrefix(token, "--ping-api-key="): + return "--ping-api-key=", "" case strings.HasPrefix(token, "-k="): - return "-k=", false + return "-k=", "" + case strings.HasPrefix(token, "-p="): + return "-p=", "" } if !strings.HasPrefix(token, "-") || strings.HasPrefix(token, "--") || len(token) < 2 { - return token, false + return token, "" } body := token[1:] for i := 0; i < len(body); i++ { + placeholder := "" switch body[i] { case 'k': - if i+1 < len(body) { - return token[:i+2] + "", false - } - return token, true + placeholder = "" + case 'p': + placeholder = "" default: if shortFlagTakesValue(body[i]) { - return token, false + return token, "" } + continue + } + if i+1 >= len(body) { + return token, placeholder + } + // Keep the '=' in a cluster such as -vk=X. + end := i + 2 + if body[i+1] == '=' { + end++ } + return token[:end] + placeholder, "" } - return token, false + return token, "" } var syncFile string // Path to YAML/JSON file for bulk monitor import @@ -252,9 +268,11 @@ There are three ways to run sync: $ cronitor sync --auto > Asks nothing. Monitors every new job, sends schedule and timezone changes, and writes the crontab - > Prints the crontab to stdout even when nothing changed. On failure it exits 1 - and prints the original crontab when it can read one. Use set -o pipefail - (or check the exit code) so a pipe does not install output from a failed run + > Prints the crontab to stdout even when nothing changed. Once sync has read the file, + a failure prints the original crontab and exits 1. A direct "| crontab -" pipe can + still install an empty crontab if sync fails before it can read the file, for example + when the file is missing or a flag is invalid. Capture the output first: + out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab - > Use it to automate sync, not to pick up one schedule change: it also monitors every new job For a job that is already monitored, sync sends only what changed. Names, tags and alert lists set @@ -1246,8 +1264,8 @@ func applyPlan(plan *crontabPlan) bool { if err := configureShellShim(crontab, false); err != nil { // The file is unchanged. --auto stdout must not print the planned // crontab (SHELL= would point at a wrapper that was never installed). - // Print the original so `... | crontab -` without pipefail reinstalls - // a working crontab instead of an empty one; finishSync then exits 1. + // Print the original so a pipe to crontab reinstalls a working + // crontab instead of an empty one; finishSync then exits 1. plan.output = crontab.Original() if isAutoDiscover || isSilent { fmt.Fprintln(os.Stderr, err.Error()) diff --git a/docs/releases/33.15.md b/docs/releases/33.15.md index 04cd519..c677073 100644 --- a/docs/releases/33.15.md +++ b/docs/releases/33.15.md @@ -8,7 +8,8 @@ Sync is now safe and quiet to run again on a crontab it already set up ([#90](ht - Plain `cronitor sync` is the normal way to rerun. It checks every monitored job against Cronitor and picks up schedule and timezone changes without asking about the job. - For a job that is already monitored, sync sends only what changed: the schedule, the timezone, and the alert list when you pass `--notification-list`. Without that flag, existing alert lists are kept and new monitors get Cronitor's default. Before, every sync replaced tags set in Cronitor with `cron-job` and reset alert lists to `default`. - A changed `CRON_TZ` or `TZ` line now updates the monitor's timezone even when the schedule stays the same. Before, sync missed it. -- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`). On any failure, sync exits 1 and, when it can read the file, prints the original crontab rather than an empty one or one whose `SHELL=` points at a missing wrapper. If it cannot read a crontab (for example the file is missing), nothing is printed: use `set -o pipefail` (or check the exit code) so the pipe does not install that failed run. Use it for scripts, not to pick up one schedule change. +- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`). Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Use it for scripts, not to pick up one schedule change. +- `--dry-run` on a single named file that can't be written now exits 1. - If any crontab fails to apply, in any mode (interactive or `--auto`, one crontab or several), sync now exits 1. Before, it exited 0. - `--silent` hides status messages. On an interactive run it still asks `Apply these changes?` before sending or writing, so a monitored job's schedule cannot change with no confirmation. Combined with `--auto`, it also skips printing the crontab. - The name in Cronitor wins. Sync no longer sends the name from a `# Name:` comment for a monitored job, so a rename in the dashboard stays. If the comment differs, sync updates it. It does not add a new `# Name:` comment. From 04571a7b245854faf49e4c8bff08801f3d18eccb Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 8 Nov 2026 05:54:34 +0000 Subject: [PATCH 4/6] sync: check discover verbose logs on stderr discover --auto prints the crontab on stdout, so --verbose request logs go to stderr. The notification-list bats checks were still reading stdout. Also warn that the capture-first snippet must not use --silent, because --auto --silent prints no crontab. Co-authored-by: August Flanagan --- README.md | 2 +- cmd/discover.go | 2 ++ docs/releases/33.15.md | 2 +- tests/test-discover.bats | 9 +++++++-- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index c3a5244..96ad745 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ There are three ways to run sync: | `cronitor sync --auto` | nothing | yes | **all of them** | - Run plain `cronitor sync` again whenever you add jobs or change a schedule. It shows one summary with each change (for example `L3 Nightly backup: schedule 0 2 * * * → 30 3 * * *`) and asks once. If nothing changed, it asks nothing. -- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. It also monitors every new job, so it is not the way to pick up one schedule change. +- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. It also monitors every new job, so it is not the way to pick up one schedule change. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. - If any crontab fails to apply, in any mode, sync exits 1. - For a monitored job, sync sends only what changed. Names, tags and alert lists set in Cronitor are kept; alert lists change only with `--notification-list` (omitting the flag keeps existing lists; new monitors get Cronitor's default). A `# Name:` comment is updated to the name in Cronitor. - If a monitor was deleted in Cronitor, sync warns and does not create it again. A hand-written `CRONITOR=new-key` line for a monitor that was never created gets the same warning; create the monitor first, or remove the key and let sync add it. diff --git a/cmd/discover.go b/cmd/discover.go index 4cc0f6c..6bea780 100644 --- a/cmd/discover.go +++ b/cmd/discover.go @@ -273,6 +273,8 @@ There are three ways to run sync: still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab - + Do not add --silent to that command: --auto --silent prints no crontab, + so the pipe would install an empty one. > Use it to automate sync, not to pick up one schedule change: it also monitors every new job For a job that is already monitored, sync sends only what changed. Names, tags and alert lists set diff --git a/docs/releases/33.15.md b/docs/releases/33.15.md index c677073..e3ae040 100644 --- a/docs/releases/33.15.md +++ b/docs/releases/33.15.md @@ -8,7 +8,7 @@ Sync is now safe and quiet to run again on a crontab it already set up ([#90](ht - Plain `cronitor sync` is the normal way to rerun. It checks every monitored job against Cronitor and picks up schedule and timezone changes without asking about the job. - For a job that is already monitored, sync sends only what changed: the schedule, the timezone, and the alert list when you pass `--notification-list`. Without that flag, existing alert lists are kept and new monitors get Cronitor's default. Before, every sync replaced tags set in Cronitor with `cron-job` and reset alert lists to `default`. - A changed `CRON_TZ` or `TZ` line now updates the monitor's timezone even when the schedule stays the same. Before, sync missed it. -- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`). Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Use it for scripts, not to pick up one schedule change. +- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`). Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Use it for scripts, not to pick up one schedule change. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. - `--dry-run` on a single named file that can't be written now exits 1. - If any crontab fails to apply, in any mode (interactive or `--auto`, one crontab or several), sync now exits 1. Before, it exited 0. - `--silent` hides status messages. On an interactive run it still asks `Apply these changes?` before sending or writing, so a monitored job's schedule cannot change with no confirmation. Combined with `--auto`, it also skips printing the crontab. diff --git a/tests/test-discover.bats b/tests/test-discover.bats index 63fec70..b445b96 100755 --- a/tests/test-discover.bats +++ b/tests/test-discover.bats @@ -82,12 +82,17 @@ teardown() { run -1 bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --no-stdout | grep "cronitor exec" | grep -q "no-stdout"' } +# discover --auto on one file prints the crontab on stdout and --verbose +# request logs on stderr. Windows does not reserve stdout, so those logs +# stay there. Read both streams: the needles are not in the crontab. +# bash -c does not see this test's variables unless they are passed in. @test "Discover omits 'notifications' if notification-list not specificed" { - run -1 bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" | grep -q "notifications"' + run -1 env API_KEY="$API_KEY" FIXTURES_DIR="$FIXTURES_DIR" CRONITOR_ARGS="$CRONITOR_ARGS" \ + bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" 2>&1 | grep -q "notifications"' } @test "Discover includes custom notification-list" { - ../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --notification-list test-list-name | grep -q "test-list-name" + ../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" --notification-list test-list-name 2>&1 | grep -q "test-list-name" } @test "Discover reads all of the crontabs in a directory" { From 9a27d87edbc112b45a6402709bdf25896840ac4d Mon Sep 17 00:00:00 2001 From: August Flanagan Date: Sat, 7 Nov 2026 21:59:41 -0800 Subject: [PATCH 5/6] sync: tighten notify test needle and --silent docs wording --- README.md | 2 +- docs/releases/33.15.md | 2 +- tests/test-discover.bats | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 96ad745..2103e51 100644 --- a/README.md +++ b/README.md @@ -107,7 +107,7 @@ There are three ways to run sync: | `cronitor sync --auto` | nothing | yes | **all of them** | - Run plain `cronitor sync` again whenever you add jobs or change a schedule. It shows one summary with each change (for example `L3 Nightly backup: schedule 0 2 * * * → 30 3 * * *`) and asks once. If nothing changed, it asks nothing. -- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. It also monitors every new job, so it is not the way to pick up one schedule change. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. +- `--auto` is for scripts and pipelines. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed. Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. It also monitors every new job, so it is not the way to pick up one schedule change. - If any crontab fails to apply, in any mode, sync exits 1. - For a monitored job, sync sends only what changed. Names, tags and alert lists set in Cronitor are kept; alert lists change only with `--notification-list` (omitting the flag keeps existing lists; new monitors get Cronitor's default). A `# Name:` comment is updated to the name in Cronitor. - If a monitor was deleted in Cronitor, sync warns and does not create it again. A hand-written `CRONITOR=new-key` line for a monitor that was never created gets the same warning; create the monitor first, or remove the key and let sync add it. diff --git a/docs/releases/33.15.md b/docs/releases/33.15.md index e3ae040..2875beb 100644 --- a/docs/releases/33.15.md +++ b/docs/releases/33.15.md @@ -8,7 +8,7 @@ Sync is now safe and quiet to run again on a crontab it already set up ([#90](ht - Plain `cronitor sync` is the normal way to rerun. It checks every monitored job against Cronitor and picks up schedule and timezone changes without asking about the job. - For a job that is already monitored, sync sends only what changed: the schedule, the timezone, and the alert list when you pass `--notification-list`. Without that flag, existing alert lists are kept and new monitors get Cronitor's default. Before, every sync replaced tags set in Cronitor with `cron-job` and reset alert lists to `default`. - A changed `CRON_TZ` or `TZ` line now updates the monitor's timezone even when the schedule stays the same. Before, sync missed it. -- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`). Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Use it for scripts, not to pick up one schedule change. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. +- `cronitor sync --auto` asks nothing: it monitors every new job, sends schedule and timezone changes, and writes the crontab. When you pass a single crontab file, it prints that crontab to stdout even if nothing changed (and on `--dry-run`). Once sync has read the file, a failure prints the original crontab and exits 1. A direct `| crontab -` pipe can still install an empty crontab if sync fails before it can read the file, for example when the file is missing or a flag is invalid. Capture the output first: `out=$(cronitor sync --auto file) && printf '%s\n' "$out" | crontab -`. Do not add `--silent` to that command: `--auto --silent` prints no crontab, so the pipe would install an empty one. Use it for scripts, not to pick up one schedule change. - `--dry-run` on a single named file that can't be written now exits 1. - If any crontab fails to apply, in any mode (interactive or `--auto`, one crontab or several), sync now exits 1. Before, it exited 0. - `--silent` hides status messages. On an interactive run it still asks `Apply these changes?` before sending or writing, so a monitored job's schedule cannot change with no confirmation. Combined with `--auto`, it also skips printing the crontab. diff --git a/tests/test-discover.bats b/tests/test-discover.bats index b445b96..83dba37 100755 --- a/tests/test-discover.bats +++ b/tests/test-discover.bats @@ -88,7 +88,7 @@ teardown() { # bash -c does not see this test's variables unless they are passed in. @test "Discover omits 'notifications' if notification-list not specificed" { run -1 env API_KEY="$API_KEY" FIXTURES_DIR="$FIXTURES_DIR" CRONITOR_ARGS="$CRONITOR_ARGS" \ - bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" 2>&1 | grep -q "notifications"' + bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" 2>&1 | grep -q "\"notify\""' } @test "Discover includes custom notification-list" { From cab37faa138e094d3c8159f9bf41e052b9d23e29 Mon Sep 17 00:00:00 2001 From: August Flanagan Date: Sat, 7 Nov 2026 22:03:24 -0800 Subject: [PATCH 6/6] tests: restore notifications needle (verbose logs include API responses with notify) --- tests/test-discover.bats | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test-discover.bats b/tests/test-discover.bats index 83dba37..b445b96 100755 --- a/tests/test-discover.bats +++ b/tests/test-discover.bats @@ -88,7 +88,7 @@ teardown() { # bash -c does not see this test's variables unless they are passed in. @test "Discover omits 'notifications' if notification-list not specificed" { run -1 env API_KEY="$API_KEY" FIXTURES_DIR="$FIXTURES_DIR" CRONITOR_ARGS="$CRONITOR_ARGS" \ - bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" 2>&1 | grep -q "\"notify\""' + bash -c '../cronitor $CRONITOR_ARGS discover --auto -v $FIXTURES_DIR/crontab.txt -k "$API_KEY" 2>&1 | grep -q "notifications"' } @test "Discover includes custom notification-list" {