diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 0d16606..41b8000 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -7,6 +7,7 @@ on: permissions: contents: write + actions: write jobs: nightly: @@ -35,12 +36,15 @@ jobs: fi fi - - name: Read version from manifest + - name: Compute next patch version if: steps.check.outputs.has_changes == 'true' id: version run: | - VERSION=$(jq -r '.["."]' .release-please-manifest.json) - echo "version=$VERSION" >> "$GITHUB_OUTPUT" + # The manifest holds the last released version. A nightly must sort + # above it under semver, so tag the next patch: 0.15.0 -> v0.15.1-nightly.. + RELEASED=$(jq -r '.["."]' .release-please-manifest.json) + IFS=. read -r MAJOR MINOR PATCH <<< "$RELEASED" + echo "version=${MAJOR}.${MINOR}.$((PATCH + 1))" >> "$GITHUB_OUTPUT" - name: Create nightly tag if: steps.check.outputs.has_changes == 'true' @@ -52,6 +56,9 @@ jobs: git config user.email "github-actions[bot]@users.noreply.github.com" git tag -a "$TAG" -m "Nightly build $DATE" git push origin "$TAG" + gh workflow run prerelease.yml --ref "$TAG" + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} cleanup: runs-on: ubuntu-latest diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml index e050724..ec305d0 100644 --- a/.github/workflows/prerelease.yml +++ b/.github/workflows/prerelease.yml @@ -7,6 +7,7 @@ on: - 'v*-beta*' - 'v*-alpha*' - 'v*-nightly*' + workflow_dispatch: permissions: contents: write diff --git a/README.md b/README.md index ea681c0..11e802f 100644 --- a/README.md +++ b/README.md @@ -492,6 +492,21 @@ task docker:up - `GET /api/v1/projects/:id/issues/:iid/events` - Get audit events +## Releasing + +### Release candidates and nightlies + +Tag release candidates on `main` with the next version and a dotted counter: +`v0.16.0-rc.1`, `v0.16.0-rc.2`. The dot matters from the tenth candidate on. +Semver compares `rc.10` and `rc.9` numerically but `rc10` and `rc9` lexically. +Without the dot, `v0.16.0-rc10` sorts below `v0.16.0-rc9` and the rc channel +never offers it. `arc self update` asks for confirmation before installing. +Pass `-y` or `--yes` to skip the prompt in scripts. + +Nightlies are tagged automatically as `v-nightly.`. The next +patch, not the released version, is what makes a nightly sort above the current +release. The update channel logic always prefers a newer stable release. + ## License MIT diff --git a/cmd/arc/main.go b/cmd/arc/main.go index 156cba3..c38d168 100644 --- a/cmd/arc/main.go +++ b/cmd/arc/main.go @@ -5,13 +5,17 @@ package main import ( + "context" "encoding/json" "errors" "fmt" "io" "os" + "os/signal" "strings" + "syscall" "text/tabwriter" + "time" "github.com/fatih/color" "github.com/sentiolabs/arc/internal/client" @@ -81,11 +85,72 @@ var ( ) func main() { - if err := rootCmd.Execute(); err != nil { + if err := runRoot(); err != nil { os.Exit(1) } } +// runRoot executes the root command under a context that SIGINT or SIGTERM +// cancels. The first signal no longer kills the process, so every command +// that can block for a long time must watch ctx.Done. See tailFollow and +// planWaitCmd. +func runRoot() error { + ctx, stop := signalContext() + defer stop() + return rootCmd.ExecuteContext(ctx) +} + +// Signal-handling constants. +const ( + // signalBuffer holds the two signals signalContext reads: the one that + // cancels the context and the one that exits the process. + signalBuffer = 2 + + // signalExitBase is the offset a shell adds to a signal number when it + // reports a process killed by that signal. + signalExitBase = 128 +) + +// signalContext returns a context cancelled by the first SIGINT or SIGTERM. +// A second signal exits the process with 128 plus the signal number, the +// same status a shell reports for a process killed by that signal. +func signalContext() (context.Context, context.CancelFunc) { + ctx, cancel := context.WithCancel(context.Background()) + sigs := make(chan os.Signal, signalBuffer) + signal.Notify(sigs, os.Interrupt, syscall.SIGTERM) + go func() { + <-sigs + cancel() + s := <-sigs + if n, ok := s.(syscall.Signal); ok { + os.Exit(signalExitBase + int(n)) + } + os.Exit(1) + }() + return ctx, func() { signal.Stop(sigs); cancel() } +} + +// cmdContext returns cmd's context. Tests that call RunE directly never go +// through Execute, so cmd.Context() is nil for them and a never-cancelled +// background context keeps their behavior unchanged. +func cmdContext(cmd *cobra.Command) context.Context { + if ctx := cmd.Context(); ctx != nil { + return ctx + } + return context.Background() +} + +// sleepOrCancel waits for d, or returns early when ctx is cancelled. It +// reports whether the full delay elapsed. +func sleepOrCancel(ctx context.Context, d time.Duration) bool { + select { + case <-ctx.Done(): + return false + case <-time.After(d): + return true + } +} + // ProjectSource indicates how the project was resolved type ProjectSource int diff --git a/cmd/arc/plan.go b/cmd/arc/plan.go index 4a080b4..a29b817 100644 --- a/cmd/arc/plan.go +++ b/cmd/arc/plan.go @@ -320,11 +320,17 @@ type planWaitResult struct { Comments []*types.PlanComment `json:"comments"` } +// planWaitCancelled reports an interrupted wait. It stays non-zero so a +// caller still tells "no decision yet" from a decision. +func planWaitCancelled(planID string, cause error) error { + return fmt.Errorf("stopped waiting for a decision on %s: %w", planID, cause) +} + // planWaitCmd blocks until a review decision is made in the planner web UI. // It polls the plan status every 2s until it leaves draft/in_review, then // prints the decision and the full comment thread (the same formats used by // `arc plan comments`). Exits non-zero on timeout so callers can distinguish -// "no decision yet" from a decision. +// "no decision yet" from a decision. A cancelled context also ends the wait. var planWaitCmd = &cobra.Command{ Use: "wait ", Short: "Block until the plan is approved/rejected/changes-requested in the web UI", @@ -335,6 +341,7 @@ var planWaitCmd = &cobra.Command{ return err } planID := args[0] + ctx := cmdContext(cmd) deadline := time.Now().Add(planWaitTimeout) var consecutiveErrors int @@ -350,7 +357,9 @@ var planWaitCmd = &cobra.Command{ return fmt.Errorf("timed out after %s waiting for a decision on %s: %w", planWaitTimeout, planID, err) } - time.Sleep(planWaitPollInterval) + if !sleepOrCancel(ctx, planWaitPollInterval) { + return planWaitCancelled(planID, ctx.Err()) + } continue } consecutiveErrors = 0 @@ -371,7 +380,9 @@ var planWaitCmd = &cobra.Command{ return fmt.Errorf("timed out after %s waiting for a decision on %s (status: %s)", planWaitTimeout, planID, plan.Status) } - time.Sleep(planWaitPollInterval) + if !sleepOrCancel(ctx, planWaitPollInterval) { + return planWaitCancelled(planID, ctx.Err()) + } } }, } diff --git a/cmd/arc/self.go b/cmd/arc/self.go index ecc9c7c..c7ffcb7 100644 --- a/cmd/arc/self.go +++ b/cmd/arc/self.go @@ -1,344 +1,97 @@ // Package main provides the self-management commands for the arc CLI, -// including self-update functionality to fetch the latest version from GitHub. +// delegating update and channel logic to github.com/sentiolabs/go-selfupdate. package main import ( - "encoding/json" + "context" "fmt" - "net/http" "os" - "os/exec" "path/filepath" - "regexp" - cfgpkg "github.com/sentiolabs/arc/internal/config" "github.com/sentiolabs/arc/internal/project" "github.com/sentiolabs/arc/internal/storage/sqlite" "github.com/sentiolabs/arc/internal/version" - "github.com/spf13/cobra" + "github.com/sentiolabs/go-selfupdate" + "github.com/sentiolabs/go-selfupdate/cobracmd" "golang.org/x/mod/semver" ) -// selfForce forces update even if already up-to-date. -var selfForce bool +// cliName is the binary name, which is also arc's GitHub repository name. +const cliName = "arc" -// selfCheck enables check-only mode without installing. -var selfCheck bool +// installScriptURL is arc's install script, run with --force --tag=. +const installScriptURL = "https://raw.githubusercontent.com/sentiolabs/arc/main/scripts/install.sh" -// selfYes skips confirmation prompts. -var selfYes bool +// selfCmd is registered by main.go. It is the go-selfupdate command tree with +// arc's wiring: GitHub releases of sentiolabs/arc, the channel from +// ~/.arc/config.toml, and a database backup before a major or minor bump. +var selfCmd = cobracmd.New(newSelfUpdater(), cobracmd.WithCheckShorthand("c")) -// Release channel names. -const ( - channelStable = "stable" - channelRC = "rc" - channelNightly = "nightly" -) - -// selfCmd is the parent command for arc self-management (update, channel). -var selfCmd = &cobra.Command{ - Use: "self", - Short: "Manage the arc CLI itself", -} - -// selfUpdateCmd checks for and installs newer versions of the arc CLI. -var selfUpdateCmd = &cobra.Command{ - Use: "update", - Short: "Update arc to the latest version", - SilenceUsage: true, - Long: `Update arc to the latest version from GitHub releases. - -The update channel determines which releases are considered: - stable Official releases (default) - rc Release candidates - nightly Daily builds from main branch - -Use 'arc self channel' to view or switch the update channel. - -Examples: - arc self update Update if a new version is available - arc self update --check Check for updates without installing - arc self update --force Force reinstall even if up-to-date`, - RunE: runSelfUpdate, -} - -// selfChannelCmd views or switches the release channel (stable, rc, nightly). -var selfChannelCmd = &cobra.Command{ - Use: "channel [stable|rc|nightly]", - Short: "View or switch the update channel", - Long: `View or switch the update channel for arc self update. - -Channels: - stable Official releases (default) - rc Release candidates - nightly Daily builds from main branch - -Examples: - arc self channel Show current channel - arc self channel nightly Switch to nightly (prompts for confirmation) - arc self channel nightly -y Switch without prompting`, - Args: cobra.MaximumNArgs(1), - RunE: runSelfChannel, -} - -func init() { - selfCmd.AddCommand(selfUpdateCmd) - selfCmd.AddCommand(selfChannelCmd) - - selfUpdateCmd.Flags().BoolVarP(&selfForce, "force", "f", false, "Force update even if already up-to-date") - selfUpdateCmd.Flags().BoolVarP(&selfCheck, "check", "c", false, "Check for updates without installing") - selfChannelCmd.Flags().BoolVarP(&selfYes, "yes", "y", false, "Skip confirmation prompt") -} - -// githubReleasesURL is the base URL for GitHub releases API (var for testing). -var githubReleasesURL = "https://api.github.com/repos/sentiolabs/arc/releases" - -// githubRelease represents a GitHub release. -type githubRelease struct { - TagName string `json:"tag_name"` - Prerelease bool `json:"prerelease"` -} - -// channelTagPattern maps channel names to their tag matching patterns. -var channelTagPattern = map[string]*regexp.Regexp{ - channelRC: regexp.MustCompile(`^v\d+\.\d+\.\d+-rc\.?\d+$`), - channelNightly: regexp.MustCompile(`^v\d+\.\d+\.\d+-nightly\.\d{8}$`), -} - -func runSelfUpdate(cmd *cobra.Command, args []string) error { - current := ensureVPrefix(version.Short()) - - cfg, err := loadConfig() - if err != nil { - return err - } - - channel := cfg.Updates.Channel - if channel == "" { - channel = channelStable - } - - latest, err := resolveChannelVersion(channel) - if err != nil { - return fmt.Errorf("failed to check for updates: %w", err) +// newSelfUpdater builds arc's updater. +func newSelfUpdater() *selfupdate.Updater { + return &selfupdate.Updater{ + Name: cliName, + Version: version.Short(), + Source: &selfupdate.GitHubSource{Owner: "sentiolabs", Repo: cliName}, + Store: arcChannelStore(), + Installer: &selfupdate.ScriptInstaller{ScriptURL: installScriptURL}, + PreInstall: preInstallBackup(backupArcDatabase), } - - cmp := semver.Compare(latest, current) - - // Check-only mode - if selfCheck { - switch { - case cmp == 0: - _, _ = fmt.Printf("arc %s (%s) is the latest version\n", current, channel) - case cmp > 0: - _, _ = fmt.Printf("arc %s installed (%s channel)\n", current, channel) - _, _ = fmt.Printf("arc %s available\n", latest) - _, _ = fmt.Println("\nRun 'arc self update' to upgrade") - default: - _, _ = fmt.Printf("arc %s installed (newer than latest %s release %s)\n", current, channel, latest) - } - return nil - } - - // Compare versions - if cmp == 0 && !selfForce { - fmt.Printf("arc %s (%s) is already the latest version\n", current, channel) - return nil - } - - if cmp < 0 && !selfForce { - fmt.Printf("arc %s is newer than latest %s release %s\n", current, channel, latest) - return nil - } - - // Full backup before major/minor version bumps - if semver.MajorMinor(latest) != semver.MajorMinor(current) { - dbPath := filepath.Join(project.DefaultArcHome(), "data.db") - result, backupErr := sqlite.BackupDatabase(dbPath) - if backupErr != nil { - _, _ = fmt.Fprintf(os.Stderr, "Warning: pre-update backup failed: %v\n", backupErr) - } else if result != nil { - fmt.Printf("Pre-update backup: %s (%s → %s)\n", - result.Path, formatSize(result.OriginalSize), formatSize(result.BackupSize)) - } - } - - // Run the install script - fmt.Printf("Updating arc %s → %s...\n", current, latest) - return runInstallScript(latest) } -// resolveChannelVersion finds the latest release tag for the given channel. -// For non-stable channels, it also checks the latest stable release and -// returns whichever is newer, so users on rc/nightly channels still get -// prompted when a new stable version surpasses their pre-release. -func resolveChannelVersion(channel string) (string, error) { - if channel == "" || channel == channelStable { - return getLatestVersion() - } - - pattern, ok := channelTagPattern[channel] - if !ok { - return "", fmt.Errorf("unknown channel: %s", channel) - } - - resp, err := http.Get(githubReleasesURL + "?per_page=100") - if err != nil { - return "", err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("GitHub API returned status %d", resp.StatusCode) - } - - var releases []githubRelease - if err := json.NewDecoder(resp.Body).Decode(&releases); err != nil { - return "", err +// arcChannelStore persists the channel in cfg.Updates.Channel. An empty +// value reads as stable. +func arcChannelStore() selfupdate.Store { + return selfupdate.FuncStore{ + Get: func() (selfupdate.Channel, error) { + cfg, err := loadConfig() + if err != nil { + return "", err + } + if cfg.Updates.Channel == "" { + return selfupdate.ChannelStable, nil + } + return selfupdate.Channel(cfg.Updates.Channel), nil + }, + Set: func(c selfupdate.Channel) error { + cfg, err := loadConfig() + if err != nil { + return err + } + cfg.Updates.Channel = string(c) + if err := saveConfig(cfg); err != nil { + return fmt.Errorf("save config: %w", err) + } + return nil + }, } +} - var channelTag, stableTag string - for _, r := range releases { - if channelTag == "" && pattern.MatchString(r.TagName) { - channelTag = r.TagName - } - if stableTag == "" && !r.Prerelease { - stableTag = r.TagName - } - if channelTag != "" && stableTag != "" { - break +// preInstallBackup returns a PreInstall hook that calls backup when the +// update crosses a major or minor version boundary. Backup failures are +// reported on stderr and do not abort the update, matching prior behavior. +func preInstallBackup(backup func() error) func(context.Context, string, string) error { + return func(_ context.Context, current, latest string) error { + if semver.MajorMinor(latest) == semver.MajorMinor(current) { + return nil } - } - - switch { - case channelTag != "" && stableTag != "": - if semver.Compare(stableTag, channelTag) > 0 { - return stableTag, nil + if err := backup(); err != nil { + _, _ = fmt.Fprintf(os.Stderr, "Warning: pre-update backup failed: %v\n", err) } - return channelTag, nil - case channelTag != "": - return channelTag, nil - case stableTag != "": - return stableTag, nil - default: - return "", fmt.Errorf("no %s release found", channel) - } -} - -// getLatestVersion fetches just the version tag from GitHub. -func getLatestVersion() (string, error) { - resp, err := http.Get(githubReleasesURL + "/latest") - if err != nil { - return "", err - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("GitHub API returned status %d", resp.StatusCode) - } - - var release githubRelease - if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { - return "", err - } - - return release.TagName, nil -} - -// runInstallScript downloads and runs the install script. -func runInstallScript(tag string) error { - scriptArgs := "--force" - if tag != "" { - scriptArgs += " --tag=" + tag - } - installURL := "https://raw.githubusercontent.com/sentiolabs/arc/main/scripts/install.sh" - script := "curl -fsSL " + installURL + " | bash -s -- " + scriptArgs - - cmd := exec.Command("bash", "-c", script) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - cmd.Stdin = os.Stdin - - return cmd.Run() -} - -// ensureVPrefix adds a "v" prefix if not already present. -func ensureVPrefix(v string) string { - if v == "" || v == "dev" { - return "v0.0.0-dev" - } - if v[0] != 'v' { - return "v" + v + return nil } - return v } -func runSelfChannel(cmd *cobra.Command, args []string) error { - cfg, err := loadConfig() +// backupArcDatabase backs up ~/.arc/data.db and prints the result. +func backupArcDatabase() error { + dbPath := filepath.Join(project.DefaultArcHome(), "data.db") + result, err := sqlite.BackupDatabase(dbPath) if err != nil { return err } - - // Show current channel if no args - if len(args) == 0 { - channel := cfg.Updates.Channel - if channel == "" { - channel = channelStable - } - fmt.Printf("Current update channel: %s\n", channel) - return nil - } - - newChannel := args[0] - - // Validate channel name early - switch newChannel { - case channelStable, channelRC, channelNightly: - // valid - default: - return fmt.Errorf("invalid channel %q: must be stable, rc, or nightly", newChannel) - } - - // Warn and confirm for non-stable channels - if newChannel != channelStable && !selfYes { - var warning string - switch newChannel { - case channelRC: - warning = "Release candidates may contain bugs that haven't been fully tested." - case channelNightly: - warning = "Nightly builds are built from the latest main branch and may be unstable." - } - _, _ = fmt.Fprintf(os.Stderr, "\n⚠ %s\n\n", warning) - _, _ = fmt.Fprintf(os.Stderr, "Switch to %s channel? [y/N] ", newChannel) - - var response string - _, _ = fmt.Scanln(&response) - if response != "y" && response != "Y" { - fmt.Println("Cancelled.") - return nil - } - } - - return setSelfChannel(cfg, newChannel) -} - -// setSelfChannel validates and persists the update channel. -func setSelfChannel(cfg *cfgpkg.Config, channel string) error { - switch channel { - case channelStable, channelRC, channelNightly: - // valid - default: - return fmt.Errorf("invalid channel %q: must be stable, rc, or nightly", channel) - } - - cfg.Updates.Channel = channel - if err := saveConfig(cfg); err != nil { - return fmt.Errorf("save config: %w", err) - } - - _, _ = fmt.Printf("\n✓ Switched to %s channel\n", channel) - if channel != channelStable { - _, _ = fmt.Printf(" Run 'arc self update' to get the latest %s build\n", channel) + if result != nil { + _, _ = fmt.Printf("Pre-update backup: %s (%s -> %s)\n", + result.Path, formatSize(result.OriginalSize), formatSize(result.BackupSize)) } return nil } diff --git a/cmd/arc/self_test.go b/cmd/arc/self_test.go index 2677d85..3a32dcb 100644 --- a/cmd/arc/self_test.go +++ b/cmd/arc/self_test.go @@ -1,249 +1,155 @@ package main import ( - "encoding/json" - "fmt" - "net/http" - "net/http/httptest" + "context" + "io" "path/filepath" "testing" + "github.com/sentiolabs/go-selfupdate" + "github.com/sentiolabs/go-selfupdate/cobracmd" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "golang.org/x/mod/semver" ) -func TestSelfChannelShowDefault(t *testing.T) { - tmp := t.TempDir() - cfgFile := filepath.Join(tmp, "config.toml") - +// useTempConfig points configPath at a throwaway file for the test. +func useTempConfig(t *testing.T) { + t.Helper() origPath := configPath - configPath = cfgFile + configPath = filepath.Join(t.TempDir(), "config.toml") t.Cleanup(func() { configPath = origPath }) +} - // Run with no args — should show default channel - cfg, err := loadConfig() +func TestChannelStore_DefaultIsStable(t *testing.T) { + useTempConfig(t) + ch, err := arcChannelStore().Channel() require.NoError(t, err) + assert.Equal(t, selfupdate.ChannelStable, ch) +} - channel := cfg.Updates.Channel - if channel == "" { - channel = channelStable +func TestChannelStore_PersistsRCAndNightly(t *testing.T) { + useTempConfig(t) + store := arcChannelStore() + for _, ch := range []selfupdate.Channel{selfupdate.ChannelNightly, selfupdate.ChannelRC} { + require.NoError(t, store.SetChannel(ch)) + cfg, err := loadConfig() + require.NoError(t, err) + assert.Equal(t, string(ch), cfg.Updates.Channel) + got, err := store.Channel() + require.NoError(t, err) + assert.Equal(t, ch, got) } - assert.Equal(t, channelStable, channel) } -func TestSelfChannelSwitchNightly(t *testing.T) { - tmp := t.TempDir() - cfgFile := filepath.Join(tmp, "config.toml") - - origPath := configPath - configPath = cfgFile - t.Cleanup(func() { configPath = origPath }) - - // Simulate setting channel (what runSelfChannel does with --yes) - cfg, err := loadConfig() - require.NoError(t, err) - - err = setSelfChannel(cfg, channelNightly) - require.NoError(t, err) - - // Re-read and verify - cfg, err = loadConfig() - require.NoError(t, err) - assert.Equal(t, channelNightly, cfg.Updates.Channel) +func TestSelfUpdaterWiring(t *testing.T) { + useTempConfig(t) + u := newSelfUpdater() + assert.Equal(t, "arc", u.Name) + src, ok := u.Source.(*selfupdate.GitHubSource) + require.True(t, ok) + assert.Equal(t, "sentiolabs", src.Owner) + assert.Equal(t, "arc", src.Repo) + inst, ok := u.Installer.(*selfupdate.ScriptInstaller) + require.True(t, ok) + assert.Contains(t, inst.ScriptURL, "sentiolabs/arc/main/scripts/install.sh") + assert.NotNil(t, u.PreInstall) } -func TestSelfChannelSwitchRC(t *testing.T) { - tmp := t.TempDir() - cfgFile := filepath.Join(tmp, "config.toml") - - origPath := configPath - configPath = cfgFile - t.Cleanup(func() { configPath = origPath }) - - cfg, err := loadConfig() - require.NoError(t, err) +// channelCmdName is the "channel" subcommand's name. +const channelCmdName = "channel" - err = setSelfChannel(cfg, channelRC) +func TestSelfCommandKeepsCheckShorthand(t *testing.T) { + update, _, err := selfCmd.Find([]string{"update"}) require.NoError(t, err) - - cfg, err = loadConfig() + check := update.Flags().Lookup("check") + require.NotNil(t, check) + assert.Equal(t, "c", check.Shorthand) + channel, _, err := selfCmd.Find([]string{channelCmdName}) require.NoError(t, err) - assert.Equal(t, channelRC, cfg.Updates.Channel) + assert.Equal(t, "y", channel.Flags().Lookup("yes").Shorthand) } -func TestSelfChannelInvalid(t *testing.T) { - tmp := t.TempDir() - cfgFile := filepath.Join(tmp, "config.toml") - - origPath := configPath - configPath = cfgFile - t.Cleanup(func() { configPath = origPath }) - - cfg, err := loadConfig() - require.NoError(t, err) - - err = setSelfChannel(cfg, "beta") +func TestInvalidChannelRejected(t *testing.T) { + useTempConfig(t) + u := newSelfUpdater() + u.Store = &selfupdate.MemStore{} + err := u.SwitchChannel("beta", true) require.Error(t, err) assert.Contains(t, err.Error(), "invalid channel") } -// mockReleases creates test data for GitHub API mocking. -// Uses real-world tag formats: rc3 (no dot) and nightly.20260302 (with dot). -// Nightly builds use the next unreleased version (v0.11.0) so they sort -// higher than the latest stable (v0.10.0) per semver. -func mockReleases() []githubRelease { - return []githubRelease{ - {TagName: "v0.11.0-rc3", Prerelease: true}, - {TagName: "v0.11.0-rc2", Prerelease: true}, - {TagName: "v0.11.0-rc.1", Prerelease: true}, // also accept dotted format - {TagName: "v0.11.0-nightly.20260302", Prerelease: true}, - {TagName: "v0.11.0-nightly.20260301", Prerelease: true}, - {TagName: "v0.10.0", Prerelease: false}, - } -} - -func TestResolveChannelVersion_Stable(t *testing.T) { - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/releases/latest" { - _ = json.NewEncoder(w).Encode(map[string]string{"tag_name": "v0.10.0"}) - } - })) - defer srv.Close() - - origURL := githubReleasesURL - githubReleasesURL = srv.URL + "/releases" - t.Cleanup(func() { githubReleasesURL = origURL }) - - tag, err := resolveChannelVersion(channelStable) - require.NoError(t, err) - assert.Equal(t, "v0.10.0", tag) -} - -func TestResolveChannelVersion_RC(t *testing.T) { - releases := mockReleases() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _ = json.NewEncoder(w).Encode(releases) - })) - defer srv.Close() - - origURL := githubReleasesURL - githubReleasesURL = srv.URL + "/releases" - t.Cleanup(func() { githubReleasesURL = origURL }) - - tag, err := resolveChannelVersion(channelRC) - require.NoError(t, err) - assert.Equal(t, "v0.11.0-rc3", tag) -} - -func TestResolveChannelVersion_RC_StableIsNewer(t *testing.T) { - // When stable surpasses the latest RC, channel should return stable - releases := []githubRelease{ - {TagName: "v0.12.0", Prerelease: false}, - {TagName: "v0.11.0-rc3", Prerelease: true}, - {TagName: "v0.11.0-rc2", Prerelease: true}, - {TagName: "v0.10.0", Prerelease: false}, - } - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _ = json.NewEncoder(w).Encode(releases) - })) - defer srv.Close() - - origURL := githubReleasesURL - githubReleasesURL = srv.URL + "/releases" - t.Cleanup(func() { githubReleasesURL = origURL }) - - tag, err := resolveChannelVersion(channelRC) - require.NoError(t, err) - assert.Equal(t, "v0.12.0", tag) +func TestPreInstallBacksUpOnlyOnMajorMinorChange(t *testing.T) { + calls := 0 + hook := preInstallBackup(func() error { calls++; return nil }) + require.NoError(t, hook(t.Context(), "v0.15.0", "v0.15.1")) + assert.Equal(t, 0, calls, "patch bump must not back up") + require.NoError(t, hook(t.Context(), "v0.15.0", "v0.16.0")) + assert.Equal(t, 1, calls, "minor bump must back up") + require.NoError(t, hook(t.Context(), "v0.16.0", "v1.0.0")) + assert.Equal(t, 2, calls, "major bump must back up") } -func TestResolveChannelVersion_Nightly(t *testing.T) { - releases := mockReleases() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _ = json.NewEncoder(w).Encode(releases) - })) - defer srv.Close() - - origURL := githubReleasesURL - githubReleasesURL = srv.URL + "/releases" - t.Cleanup(func() { githubReleasesURL = origURL }) +// fakeSource serves one release tag without touching the network. +type fakeSource struct{ tag string } - tag, err := resolveChannelVersion(channelNightly) - require.NoError(t, err) - assert.Equal(t, "v0.11.0-nightly.20260302", tag) +func (f fakeSource) Latest(context.Context) (selfupdate.Release, error) { + return selfupdate.Release{Tag: f.tag}, nil } -func TestResolveChannelVersion_Nightly_StableIsNewer(t *testing.T) { - releases := []githubRelease{ - {TagName: "v0.11.0", Prerelease: false}, - {TagName: "v0.10.0-nightly.20260302", Prerelease: true}, - } - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _ = json.NewEncoder(w).Encode(releases) - })) - defer srv.Close() - - origURL := githubReleasesURL - githubReleasesURL = srv.URL + "/releases" - t.Cleanup(func() { githubReleasesURL = origURL }) - - tag, err := resolveChannelVersion(channelNightly) - require.NoError(t, err) - assert.Equal(t, "v0.11.0", tag) +func (f fakeSource) List(context.Context, int) ([]selfupdate.Release, error) { + return []selfupdate.Release{{Tag: f.tag}}, nil } -func TestResolveChannelVersion_NoChannelMatch_FallsBackToStable(t *testing.T) { - // No nightly releases exist, but stable does — should return stable - releases := []githubRelease{ - {TagName: "v0.10.0", Prerelease: false}, - } - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _ = json.NewEncoder(w).Encode(releases) - })) - defer srv.Close() - - origURL := githubReleasesURL - githubReleasesURL = srv.URL + "/releases" - t.Cleanup(func() { githubReleasesURL = origURL }) +// blockingInstaller announces that Install started, then waits for the +// context it was handed and reports why it stopped. +type blockingInstaller struct{ started chan struct{} } - tag, err := resolveChannelVersion(channelNightly) - require.NoError(t, err) - assert.Equal(t, "v0.10.0", tag) +func (b *blockingInstaller) Install(ctx context.Context, _ string) error { + close(b.started) + <-ctx.Done() + return ctx.Err() } -func TestResolveChannelVersion_NoMatch(t *testing.T) { - // Empty releases — no match for RC - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - _ = json.NewEncoder(w).Encode([]githubRelease{}) - })) - defer srv.Close() - - origURL := githubReleasesURL - githubReleasesURL = srv.URL + "/releases" - t.Cleanup(func() { githubReleasesURL = origURL }) - - _, err := resolveChannelVersion(channelRC) - require.Error(t, err) - assert.Contains(t, err.Error(), "no rc release found") +// useFakeSelfCmd swaps rootCmd's real self command for one driving u, so the +// test exercises arc's own command tree without reaching GitHub. It silences +// rootCmd's streams and restores every change when the test ends. +func useFakeSelfCmd(t *testing.T, u *selfupdate.Updater) { + t.Helper() + fake := cobracmd.New(u, cobracmd.WithCheckShorthand("c")) + rootCmd.RemoveCommand(selfCmd) + rootCmd.AddCommand(fake) + rootCmd.SetOut(io.Discard) + rootCmd.SetErr(io.Discard) + t.Cleanup(func() { + rootCmd.RemoveCommand(fake) + rootCmd.AddCommand(selfCmd) + rootCmd.SetArgs(nil) + // A nil writer restores cobra's os.Stdout and os.Stderr defaults. + rootCmd.SetOut(nil) + rootCmd.SetErr(nil) + }) } -func TestSemverComparison(t *testing.T) { - tests := []struct { - a, b string - want int // +1 if a > b, 0 if equal, -1 if a < b - }{ - {"v0.10.0", "v0.9.0", 1}, - {"v0.11.0-rc.2", "v0.11.0-rc.1", 1}, - {"v0.11.0", "v0.11.0-rc.1", 1}, // stable > prerelease per semver - {"v0.11.0-nightly.20260302", "v0.11.0-nightly.20260301", 1}, - {"v0.10.0", "v0.10.0", 0}, - } - - for _, tt := range tests { - t.Run(fmt.Sprintf("%s_vs_%s", tt.a, tt.b), func(t *testing.T) { - got := semver.Compare(tt.a, tt.b) - assert.Equal(t, tt.want, got) - }) - } +// TestSelfUpdateHonorsCancelledRootContext covers the reason main runs the +// root command with ExecuteContext: cobra must hand the installer a context +// whose Done channel actually closes. +func TestSelfUpdateHonorsCancelledRootContext(t *testing.T) { + inst := &blockingInstaller{started: make(chan struct{})} + useFakeSelfCmd(t, &selfupdate.Updater{ + Name: cliName, + Version: "v0.1.0", + Source: fakeSource{tag: "v99.0.0"}, + Installer: inst, + }) + rootCmd.SetArgs([]string{"self", "update", "-y"}) + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go func() { + <-inst.started + cancel() + }() + + err := awaitCommand(t, func() error { return rootCmd.ExecuteContext(ctx) }) + require.ErrorIs(t, err, context.Canceled) } diff --git a/cmd/arc/server.go b/cmd/arc/server.go index 0c5017d..539e5e9 100644 --- a/cmd/arc/server.go +++ b/cmd/arc/server.go @@ -2,6 +2,7 @@ package main import ( "bufio" + "context" "encoding/json" "errors" "fmt" @@ -303,7 +304,7 @@ func runServerLogs(cmd *cobra.Command, args []string) error { } if follow { - return tailFollow(logPath, lines) + return tailFollow(cmdContext(cmd), logPath, lines) } return tailLines(logPath, lines) @@ -438,8 +439,9 @@ func tailLines(path string, n int) error { return scanner.Err() } -// tailFollow follows a log file (like tail -f) -func tailFollow(path string, initialLines int) error { +// tailFollow follows a log file (like tail -f). It returns nil once ctx is +// cancelled, so Ctrl-C ends the follow without reporting an error. +func tailFollow(ctx context.Context, path string, initialLines int) error { // Print initial lines if err := tailLines(path, initialLines); err != nil { return err @@ -458,15 +460,18 @@ func tailFollow(path string, initialLines int) error { } reader := bufio.NewReader(file) - for { + for ctx.Err() == nil { line, err := reader.ReadString('\n') if err != nil { if err == io.EOF { - time.Sleep(serverPollInterval) + if !sleepOrCancel(ctx, serverPollInterval) { + return nil + } continue } return err } _, _ = fmt.Print(line) } + return nil } diff --git a/cmd/arc/signal_context_test.go b/cmd/arc/signal_context_test.go new file mode 100644 index 0000000..d3755d6 --- /dev/null +++ b/cmd/arc/signal_context_test.go @@ -0,0 +1,136 @@ +package main + +import ( + "context" + "net/http/httptest" + "os" + "path/filepath" + "syscall" + "testing" + "time" + + "github.com/sentiolabs/arc/internal/api" + "github.com/sentiolabs/arc/internal/client" + "github.com/sentiolabs/arc/internal/storage/sqlite" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +const ( + // cancelReturnTimeout bounds how long a cancelled command may take to return. + cancelReturnTimeout = 2 * time.Second + // followSettle is long enough for tailFollow to reach EOF and start + // waiting on its context. + followSettle = 250 * time.Millisecond +) + +// awaitCommand reports the error run produced, failing the test if run has +// not returned within cancelReturnTimeout. +func awaitCommand(t *testing.T, run func() error) error { + t.Helper() + done := make(chan error, 1) + go func() { done <- run() }() + select { + case err := <-done: + return err + case <-time.After(cancelReturnTimeout): + t.Fatal("command did not return after its context was cancelled") + return nil + } +} + +// TestSignalContextCancelsOnInterrupt sends exactly one SIGINT. A second +// signal would exit the test binary, which is the helper's whole point. +func TestSignalContextCancelsOnInterrupt(t *testing.T) { + ctx, stop := signalContext() + defer stop() + require.NotNil(t, ctx.Done(), "the context must be cancellable") + require.NoError(t, ctx.Err(), "the context must not start cancelled") + + require.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGINT)) + + select { + case <-ctx.Done(): + require.ErrorIs(t, ctx.Err(), context.Canceled) + case <-time.After(cancelReturnTimeout): + t.Fatal("SIGINT did not cancel the context from signalContext") + } +} + +func TestCmdContextFallsBackToBackground(t *testing.T) { + cmd := &cobra.Command{Use: "probe"} + require.Nil(t, cmd.Context(), "an unexecuted command has no context") + ctx := cmdContext(cmd) + require.NotNil(t, ctx) + assert.NoError(t, ctx.Err(), "the fallback context must not start cancelled") +} + +func TestSleepOrCancelReportsCancellation(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + assert.False(t, sleepOrCancel(ctx, time.Hour), "a cancelled context must not wait") + assert.True(t, sleepOrCancel(t.Context(), time.Millisecond), "a live context must wait out the delay") +} + +// writeLogFile returns the path to a one-line log file for tailFollow. +func writeLogFile(t *testing.T) string { + t.Helper() + path := filepath.Join(t.TempDir(), "server.log") + require.NoError(t, os.WriteFile(path, []byte("first line\n"), 0o600)) + return path +} + +// TestTailFollowStopsOnCancelledContext covers `server logs --follow` handed +// a context that is already cancelled. +func TestTailFollowStopsOnCancelledContext(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + logPath := writeLogFile(t) + assert.NoError(t, awaitCommand(t, func() error { return tailFollow(ctx, logPath, 1) })) +} + +// TestTailFollowStopsWhileFollowing cancels after tailFollow has reached EOF, +// so it covers the wait that would otherwise poll forever. +func TestTailFollowStopsWhileFollowing(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + logPath := writeLogFile(t) + go func() { + time.Sleep(followSettle) + cancel() + }() + assert.NoError(t, awaitCommand(t, func() error { return tailFollow(ctx, logPath, 1) })) +} + +// TestPlanWaitStopsOnCancel covers `arc plan wait`, whose default poll runs +// for 30 minutes. It must give up as soon as its context is cancelled. +func TestPlanWaitStopsOnCancel(t *testing.T) { + store, err := sqlite.New(filepath.Join(t.TempDir(), "test.db")) + require.NoError(t, err) + defer store.Close() + ts := httptest.NewServer(api.New(api.ServerOptions{Address: ":0", Store: store}).Echo()) + defer ts.Close() + + c := client.New(ts.URL) + c.SetActor("test-user") + planPath := filepath.Join(t.TempDir(), "plan.md") + require.NoError(t, os.WriteFile(planPath, []byte("# Plan\n"), 0o600)) + plan, err := c.CreatePlan(planPath) + require.NoError(t, err) + + origServerURL, origTimeout := serverURL, planWaitTimeout + serverURL, planWaitTimeout = ts.URL, time.Hour + t.Cleanup(func() { serverURL, planWaitTimeout = origServerURL, origTimeout }) + + // A separate command carries the context so the shared planWaitCmd, which + // other tests invoke with no context at all, keeps its nil one. + ctx, cancel := context.WithCancel(t.Context()) + cancel() + probe := &cobra.Command{Use: "wait"} + probe.SetContext(ctx) + + err = awaitCommand(t, func() error { return planWaitCmd.RunE(probe, []string{plan.ID}) }) + require.ErrorIs(t, err, context.Canceled) + assert.Contains(t, err.Error(), "stopped waiting for a decision") +} diff --git a/go.mod b/go.mod index afa2d67..d14747a 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,9 @@ require ( github.com/labstack/echo/v4 v4.15.0 github.com/oapi-codegen/runtime v1.1.2 github.com/pressly/goose/v3 v3.26.0 + github.com/sentiolabs/go-selfupdate v0.1.1 github.com/spf13/cobra v1.10.2 + github.com/spf13/pflag v1.0.9 github.com/stretchr/testify v1.11.1 golang.org/x/mod v0.33.0 gopkg.in/yaml.v3 v3.0.1 @@ -69,7 +71,6 @@ require ( github.com/sethvargo/go-retry v0.3.0 // indirect github.com/speakeasy-api/jsonpath v0.6.0 // indirect github.com/speakeasy-api/openapi-overlay v0.10.2 // indirect - github.com/spf13/pflag v1.0.9 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.2 // indirect github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect diff --git a/go.sum b/go.sum index 4e14b3c..cc13990 100644 --- a/go.sum +++ b/go.sum @@ -171,6 +171,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qq github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sentiolabs/go-selfupdate v0.1.1 h1:76DV5ZJyldwHtDUWD1AMH145QTNOMB7OXzrfq+RIm3E= +github.com/sentiolabs/go-selfupdate v0.1.1/go.mod h1:EWIEmMHrf3qT8mxGo4GkZSlSNvbCrAdPWDthNrgvCiA= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE=