diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml new file mode 100644 index 0000000..d2033a7 --- /dev/null +++ b/.github/workflows/nightly.yml @@ -0,0 +1,86 @@ +name: Nightly + +on: + schedule: + - cron: '0 6 * * *' + workflow_dispatch: + +permissions: + contents: write + actions: write + +jobs: + nightly: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Check for new commits since the last nightly + id: check + run: | + LATEST_NIGHTLY=$(git tag -l 'v*-nightly.*' --sort=-v:refname | head -1) + if [ -z "$LATEST_NIGHTLY" ]; then + echo "No previous nightly tag, proceeding" + echo "has_changes=true" >> "$GITHUB_OUTPUT" + elif [ "$(git rev-list "${LATEST_NIGHTLY}..HEAD" --count)" -gt 0 ]; then + echo "New commits since $LATEST_NIGHTLY" + echo "has_changes=true" >> "$GITHUB_OUTPUT" + else + echo "No new commits since $LATEST_NIGHTLY, skipping" + echo "has_changes=false" >> "$GITHUB_OUTPUT" + fi + + - name: Compute next patch version + if: steps.check.outputs.has_changes == 'true' + id: version + run: | + # The manifest holds the last released version. A nightly must sort + # above it under semver, so tag the next patch: 0.6.0 -> v0.6.1-nightly.. + RELEASED=$(jq -r '.["."]' .release-please-manifest.json) + IFS=. read -r MAJOR MINOR PATCH <<< "$RELEASED" + echo "next=${MAJOR}.${MINOR}.$((PATCH + 1))" >> "$GITHUB_OUTPUT" + + - name: Create nightly tag + if: steps.check.outputs.has_changes == 'true' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + DATE=$(date -u +%Y%m%d) + TAG="v${{ steps.version.outputs.next }}-nightly.${DATE}" + echo "Creating tag: $TAG" + git config user.name "github-actions[bot]" + 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" + + cleanup: + runs-on: ubuntu-latest + steps: + - name: Delete nightly releases older than 7 days + uses: actions/github-script@v7 + with: + script: | + const cutoff = new Date(); + cutoff.setDate(cutoff.getDate() - 7); + const releases = await github.rest.repos.listReleases({ + owner: context.repo.owner, repo: context.repo.repo, per_page: 100, + }); + for (const release of releases.data) { + if (!release.tag_name.includes('-nightly.')) continue; + if (new Date(release.created_at) >= cutoff) continue; + console.log(`Deleting old nightly release: ${release.tag_name}`); + await github.rest.repos.deleteRelease({ + owner: context.repo.owner, repo: context.repo.repo, release_id: release.id, + }); + try { + await github.rest.git.deleteRef({ + owner: context.repo.owner, repo: context.repo.repo, ref: `tags/${release.tag_name}`, + }); + } catch (e) { + console.log(`Tag ${release.tag_name} already deleted`); + } + } diff --git a/.github/workflows/prerelease.yml b/.github/workflows/prerelease.yml new file mode 100644 index 0000000..9229d90 --- /dev/null +++ b/.github/workflows/prerelease.yml @@ -0,0 +1,36 @@ +name: Pre-release + +on: + push: + tags: + - 'v*-rc*' + - 'v*-beta*' + - 'v*-alpha*' + - 'v*-nightly*' + workflow_dispatch: + +permissions: + contents: write + +jobs: + goreleaser: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up Go + uses: actions/setup-go@v5 + with: + go-version-file: go.mod + + - name: Run GoReleaser + uses: goreleaser/goreleaser-action@v6 + with: + distribution: goreleaser + version: "~> v2" + args: release --clean + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/README.md b/README.md index 021f6e1..7120f91 100644 --- a/README.md +++ b/README.md @@ -98,10 +98,31 @@ make build ### Updating ```bash -envctl self update +envctl self update # update to the newest release on your channel +envctl self update --check # show what would be installed +envctl self update -y # skip the confirmation prompt ``` -This checks GitHub for the latest release and updates in place. Use `--check` to see if an update is available without installing. +#### Release channels + +`self update` follows one of three channels: + +| Channel | Serves | Tag shape | +|---|---|---| +| `stable` | Official releases (default) | `v1.3.0` | +| `rc` | Release candidates | `v1.4.0-rc.1` | +| `nightly` | Daily builds from `main` | `v1.3.1-nightly.20260904` | + +```bash +envctl self channel # show the current channel +envctl self channel rc # switch (asks for confirmation) +envctl self channel rc -y # switch without prompting +envctl self channel stable # back to releases +``` + +A newer stable release always wins. On the `rc` channel you are offered `v1.4.0` the moment it ships, even if `v1.4.0-rc.3` is what you have. + +The channel is stored in `$XDG_CONFIG_HOME/envctl/config.yaml` (default `~/.config/envctl/config.yaml`), separate from the project's `.envctl.yaml`, so a team never inherits one developer's opt-in. ### Shell Completions @@ -133,6 +154,17 @@ source <(envctl completion zsh) After installing completions, restart your shell or source your profile. +### Cutting a release candidate + +Release candidates are manual tags on `main` using the next version and a dotted counter. The dot matters: semver compares `rc.10` and `rc.9` numerically but `rc10` and `rc9` lexically. + +```bash +git tag -a v0.9.0-rc.1 -m "v0.9.0-rc.1" +git push origin v0.9.0-rc.1 +``` + +The `Pre-release` workflow builds the archives and publishes a GitHub prerelease. Nightlies need no action: a scheduled workflow tags `v-nightly.` whenever `main` has new commits and removes nightlies older than seven days. + ## Quick Start ### 1. Initialize Configuration diff --git a/go.mod b/go.mod index 3ef357b..a0184d7 100644 --- a/go.mod +++ b/go.mod @@ -11,10 +11,10 @@ require ( github.com/charmbracelet/bubbletea v1.3.10 github.com/charmbracelet/lipgloss v1.1.0 github.com/charmbracelet/x/exp/golden v0.0.0-20260316093931-f2fb44ab3145 + github.com/sentiolabs/go-selfupdate v0.1.1 github.com/spf13/cobra v1.10.2 github.com/stretchr/testify v1.11.1 github.com/zalando/go-keyring v0.2.6 - golang.org/x/mod v0.33.0 gopkg.in/yaml.v3 v3.0.1 ) @@ -59,6 +59,7 @@ require ( github.com/spf13/pflag v1.0.9 // indirect github.com/stretchr/objx v0.5.2 // indirect github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect + golang.org/x/mod v0.33.0 // indirect golang.org/x/sys v0.38.0 // indirect golang.org/x/text v0.28.0 // indirect ) diff --git a/go.sum b/go.sum index 338461b..720802f 100644 --- a/go.sum +++ b/go.sum @@ -94,6 +94,8 @@ github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUc github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sahilm/fuzzy v0.1.1 h1:ceu5RHF8DGgoi+/dR5PsECjCDH1BE3Fnmpo7aVXOdRA= github.com/sahilm/fuzzy v0.1.1/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y= +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/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= diff --git a/internal/cmd/e2e_test.go b/internal/cmd/e2e_test.go index 0a043d7..c94c5c2 100644 --- a/internal/cmd/e2e_test.go +++ b/internal/cmd/e2e_test.go @@ -281,6 +281,56 @@ waitLoop: assert.True(t, os.IsNotExist(statErr), "run dir must be removed after SIGINT; stderr: %s", stderr.String()) } +// TestE2E_RunSecondSIGINTStillWaitsForChild proves run releases the root +// signal handler. With the force exit still armed, the second SIGINT would +// end envctl immediately, skipping the deferred cleanup that removes the run +// directory and its secret files. +func TestE2E_RunSecondSIGINTStillWaitsForChild(t *testing.T) { + configPath, secretsPath := e2eFixture(t, "") + out := t.TempDir() + + // The child ignores SIGINT and exits on its own, so envctl can only exit + // zero by waiting for it rather than by being killed. + cmd, _, stderr := envctlCmd(t, secretsPath, []string{"OUT=" + out}, + "-c", configPath, "run", "--", "sh", "-c", + `trap "" INT; `+e2eChildScript(`sleep 2; exit 0`)) + require.NoError(t, cmd.Start()) + + require.Eventually(t, func() bool { + _, err := os.Stat(filepath.Join(out, "ready")) + return err == nil + }, 15*time.Second, 20*time.Millisecond, "child never started; stderr: %s", stderr.String()) + + // Keep signalling until envctl exits. Two calls back to back are not + // enough, because a second instance of the same signal is coalesced away + // while the first is still pending, and the force exit would never see it. + done := make(chan error, 1) + go func() { done <- cmd.Wait() }() + + resend := time.NewTicker(100 * time.Millisecond) + defer resend.Stop() + require.NoError(t, cmd.Process.Signal(syscall.SIGINT)) + + var waitErr error +waitLoop: + for { + select { + case waitErr = <-done: + break waitLoop + case <-resend.C: + _ = cmd.Process.Signal(syscall.SIGINT) + case <-time.After(20 * time.Second): + _ = cmd.Process.Kill() + t.Fatal("envctl never exited") + } + } + require.NoError(t, waitErr, + "envctl must wait for the child instead of exiting on a later signal; stderr: %s", stderr.String()) + + _, statErr := os.Stat(readMarker(t, out, "dir")) + assert.True(t, os.IsNotExist(statErr), "run dir must be removed; stderr: %s", stderr.String()) +} + func TestE2E_EnvSkipsEphemeralAndNeverPrintsContent(t *testing.T) { configPath, secretsPath := e2eFixture(t, "") stdout, stderr, code := runEnvctl(t, secretsPath, nil, "-c", configPath, "env") diff --git a/internal/cmd/edit.go b/internal/cmd/edit.go index bfe90b1..082aaaf 100644 --- a/internal/cmd/edit.go +++ b/internal/cmd/edit.go @@ -56,7 +56,7 @@ func runEdit(cmd *cobra.Command, args []string) error { return errors.New("--item requires --vault") } - ctx := context.Background() + ctx := commandContext(cmd) // Load config if available var cfg *config.Config diff --git a/internal/cmd/env.go b/internal/cmd/env.go index d62177a..e47afae 100644 --- a/internal/cmd/env.go +++ b/internal/cmd/env.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "os" "github.com/sentiolabs/envctl/internal/output" @@ -34,7 +33,7 @@ func init() { } func runEnv(cmd *cobra.Command, args []string) error { - ctx := context.Background() + ctx := commandContext(cmd) entries, cfg, err := loadAndBuild(ctx, cmd, nil) if err != nil { diff --git a/internal/cmd/export.go b/internal/cmd/export.go index 3c6a36f..bccf040 100644 --- a/internal/cmd/export.go +++ b/internal/cmd/export.go @@ -3,7 +3,6 @@ package cmd import ( - "context" "os" "github.com/sentiolabs/envctl/internal/output" @@ -44,7 +43,7 @@ func init() { // runExport outputs secrets in the requested format. func runExport(cmd *cobra.Command, args []string) error { - ctx := context.Background() + ctx := commandContext(cmd) format, err := output.ParseFormat(exportFormat) if err != nil { diff --git a/internal/cmd/get.go b/internal/cmd/get.go index 2f062ff..69f99f6 100644 --- a/internal/cmd/get.go +++ b/internal/cmd/get.go @@ -50,7 +50,7 @@ func init() { // runGet retrieves a single secret value by key name from the configured secrets. func runGet(cmd *cobra.Command, args []string) error { - ctx := context.Background() + ctx := commandContext(cmd) key := args[0] // If --secret flag is provided, bypass config diff --git a/internal/cmd/list.go b/internal/cmd/list.go index 241aa93..1fb62bf 100644 --- a/internal/cmd/list.go +++ b/internal/cmd/list.go @@ -1,7 +1,6 @@ package cmd import ( - "context" "os" "github.com/sentiolabs/envctl/internal/config" @@ -34,7 +33,7 @@ func init() { } func runList(cmd *cobra.Command, args []string) error { - ctx := context.Background() + ctx := commandContext(cmd) // Load config configPath, err := resolveConfigPath() diff --git a/internal/cmd/root.go b/internal/cmd/root.go index b35e66b..4ccfa71 100644 --- a/internal/cmd/root.go +++ b/internal/cmd/root.go @@ -6,8 +6,11 @@ import ( "errors" "fmt" "os" + "os/signal" "path/filepath" "sort" + "sync" + "syscall" "github.com/sentiolabs/envctl/internal/cache" "github.com/sentiolabs/envctl/internal/config" @@ -60,19 +63,97 @@ func init() { _ = rootCmd.RegisterFlagCompletionFunc("env", completeEnvironmentNames) } -// Execute runs the root command. A *runner.ExitError from envctl run is -// turned into the child's exit code only here, after every deferred cleanup -// in the command has already run. +// Execute runs the root command and exits with the resulting code. A +// *runner.ExitError from envctl run is turned into the child's exit code +// only here, after every deferred cleanup in the command has already run. +func Execute() { + os.Exit(executeRoot()) +} + +// executeRoot runs the root command under a context that cancels on SIGINT or +// SIGTERM and maps the command error to a process exit code. Commands that +// read cmd.Context() get a live Done channel, so exec.Cmd inside them (the +// install pipeline behind self update) starts its cancellation watcher. +// envctl run keeps its own signal trap and hands the runner an uncancelled +// context, so a forwarded signal never becomes a SIGKILL. // //nolint:revive // CLI output to stderr always succeeds -func Execute() { - if err := rootCmd.Execute(); err != nil { - if exitErr, ok := errors.AsType[*runner.ExitError](err); ok { - os.Exit(exitErr.Code) +func executeRoot() int { + ctx, stop := signalContext() + defer stop() + + err := rootCmd.ExecuteContext(ctx) + if err == nil { + return 0 + } + if exitErr, ok := errors.AsType[*runner.ExitError](err); ok { + return exitErr.Code + } + fmt.Fprintln(os.Stderr, "Error:", err) + return 1 +} + +const ( + // signalExitBase is the shell convention for a process killed by a + // signal: 128 plus the signal number. + signalExitBase = 128 + // pendingSignals buffers the signal that cancels the context and the one + // that forces the exit. + pendingSignals = 2 +) + +// rootSignals is the channel signalContext armed, guarded because the +// command goroutine releases it while the handler goroutine reads it. +var ( + rootSignalsMu sync.Mutex + rootSignals chan os.Signal +) + +// 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, pendingSignals) + signal.Notify(sigs, os.Interrupt, syscall.SIGTERM) + rootSignalsMu.Lock() + rootSignals = sigs + rootSignalsMu.Unlock() + go func() { + <-sigs + cancel() + s := <-sigs + if n, ok := s.(syscall.Signal); ok { + os.Exit(signalExitBase + int(n)) } - fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) + }() + return ctx, func() { signal.Stop(sigs); cancel() } +} + +// releaseRootSignals stops the root handler so the force exit in +// signalContext can never fire. A command that forwards signals to a child +// and waits for it calls this, because an os.Exit from the handler goroutine +// would skip that command's deferred cleanup. Calling it before anything is +// armed, or more than once, does nothing. +func releaseRootSignals() { + rootSignalsMu.Lock() + defer rootSignalsMu.Unlock() + if rootSignals == nil { + return + } + signal.Stop(rootSignals) + rootSignals = nil +} + +// commandContext returns the context cobra attached to cmd. It falls back to +// context.Background() because the tests call the RunE functions directly +// with commands that never went through Execute. +func commandContext(cmd *cobra.Command) context.Context { + if ctx := cmd.Context(); ctx != nil { + return ctx } + return context.Background() } // verboseLog prints a message if verbose mode is enabled. diff --git a/internal/cmd/root_test.go b/internal/cmd/root_test.go index 350d677..faf93a3 100644 --- a/internal/cmd/root_test.go +++ b/internal/cmd/root_test.go @@ -2,9 +2,14 @@ package cmd import ( + "context" + "os" + "syscall" "testing" + "time" "github.com/sentiolabs/envctl/internal/config" + "github.com/spf13/cobra" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -133,3 +138,90 @@ func TestOutputCommandsMentionFileSinks(t *testing.T) { assert.Contains(t, exportCmd.Long, "file.path") assert.Contains(t, getCmd.Long, "file.path") } + +// TestExecuteRootGivesCommandsACancellableContext guards the ExecuteContext +// wiring. Under plain Execute cobra hands commands context.Background(), +// whose Done channel is nil, and exec.Cmd then skips its cancellation +// watcher, so a cancelled context never stops an install pipeline. +func TestExecuteRootGivesCommandsACancellableContext(t *testing.T) { + var probeCtx context.Context + probe := &cobra.Command{ + Use: "ctxprobe", + Hidden: true, + RunE: func(cmd *cobra.Command, _ []string) error { + probeCtx = cmd.Context() + return nil + }, + } + rootCmd.AddCommand(probe) + rootCmd.SetArgs([]string{"ctxprobe"}) + // executeRoot leaves its cancelled signal context on rootCmd, and cobra + // reuses a stored context for every later Execute. + t.Cleanup(func() { + rootCmd.RemoveCommand(probe) + rootCmd.SetArgs(nil) + rootCmd.SetContext(context.Background()) + }) + + assert.Zero(t, executeRoot()) + require.NotNil(t, probeCtx) + assert.NotNil(t, probeCtx.Done(), "commands must get a context that cancels on SIGINT or SIGTERM") + // executeRoot's deferred stop cancels the context it handed down, so a + // command that outlives it cannot keep using a dead signal context. + assert.ErrorIs(t, probeCtx.Err(), context.Canceled) +} + +// TestSignalContextCancelsOnSIGINT delivers a real SIGINT to the test +// process. signalContext has a handler installed at that point, so the +// signal cancels the context instead of killing the binary. +func TestSignalContextCancelsOnSIGINT(t *testing.T) { + ctx, stop := signalContext() + defer stop() + + require.NoError(t, syscall.Kill(os.Getpid(), syscall.SIGINT)) + + select { + case <-ctx.Done(): + require.ErrorIs(t, ctx.Err(), context.Canceled) + case <-time.After(2 * time.Second): + t.Fatal("SIGINT did not cancel the signal context") + } +} + +// TestCommandContextFallsBackToBackground covers the RunE functions the +// tests call directly, where cobra never attached a context. +func TestCommandContextFallsBackToBackground(t *testing.T) { + assert.NotNil(t, commandContext(&cobra.Command{Use: "bare"})) + + withCtx := &cobra.Command{Use: "withctx"} + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + withCtx.SetContext(ctx) + assert.Equal(t, ctx, commandContext(withCtx)) +} + +// TestReleaseRootSignalsIsSafeBeforeArmingAndIdempotent covers the two calls +// that must do nothing: one before any handler exists and a repeat. +func TestReleaseRootSignalsIsSafeBeforeArmingAndIdempotent(t *testing.T) { + rootSignalsMu.Lock() + rootSignals = nil + rootSignalsMu.Unlock() + + releaseRootSignals() + + ctx, stop := signalContext() + defer stop() + rootSignalsMu.Lock() + armed := rootSignals + rootSignalsMu.Unlock() + require.NotNil(t, armed, "signalContext must record the channel it armed") + + releaseRootSignals() + releaseRootSignals() + + rootSignalsMu.Lock() + released := rootSignals + rootSignalsMu.Unlock() + assert.Nil(t, released) + assert.NoError(t, ctx.Err(), "releasing the handler must not cancel the context") +} diff --git a/internal/cmd/run.go b/internal/cmd/run.go index 9bfdc2e..5abae9b 100644 --- a/internal/cmd/run.go +++ b/internal/cmd/run.go @@ -68,6 +68,13 @@ func runRun(cmd *cobra.Command, args []string) error { sigCtx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP) defer stop() + // Run forwards signals to the child and waits for it, so the root force + // exit on a second Ctrl-C would skip the cleanup below and leave the run + // directory, with its secret files, on disk. Release the root handler + // only now that this command's own trap is registered, so no signal falls + // back to the default disposition in between. + releaseRootSignals() + overrides := parseOverrides(setFlags) out, err := loadAndBuildFiles(sigCtx, cmd, overrides, sinkModeRun) diff --git a/internal/cmd/self.go b/internal/cmd/self.go index f51a8a9..78626ff 100644 --- a/internal/cmd/self.go +++ b/internal/cmd/self.go @@ -1,169 +1,41 @@ // Package cmd implements the CLI commands for envctl. -// This file contains the self command group and self update subcommand. +// This file wires the self command group (update, channel) to go-selfupdate. package cmd import ( - "bufio" - "encoding/json" - "fmt" - "net/http" - "os" - "os/exec" - "strings" - + "github.com/sentiolabs/envctl/internal/userconfig" "github.com/sentiolabs/envctl/internal/version" - "github.com/spf13/cobra" - "golang.org/x/mod/semver" -) - -var ( - selfForce bool - selfCheck bool - selfYes bool + "github.com/sentiolabs/go-selfupdate" + "github.com/sentiolabs/go-selfupdate/cobracmd" ) -// selfCmd is the parent command for self-management subcommands. -var selfCmd = &cobra.Command{ - Use: "self", - Short: "Manage the envctl CLI itself", -} - -// selfUpdateCmd checks for and installs updates to the envctl binary. -var selfUpdateCmd = &cobra.Command{ - Use: "update", - Short: "Update envctl to the latest version", - SilenceUsage: true, - Long: `Update envctl to the latest version from GitHub releases. - -Examples: - envctl self update Update if a new version is available - envctl self update --check Check for updates without installing - envctl self update --force Force reinstall even if up-to-date - envctl self update -y Update without confirmation prompt`, - RunE: runSelfUpdate, -} - -func init() { - selfCmd.AddCommand(selfUpdateCmd) - rootCmd.AddCommand(selfCmd) - - selfUpdateCmd.Flags().BoolVarP(&selfForce, "force", "f", false, "Force update even if already up-to-date") - selfUpdateCmd.Flags().BoolVar(&selfCheck, "check", false, "Check for updates without installing") - selfUpdateCmd.Flags().BoolVarP(&selfYes, "yes", "y", false, "Skip confirmation prompt") -} - -// githubReleasesURL is the base URL for the GitHub releases API. -// It is a package-level var so tests can override it. -var githubReleasesURL = "https://api.github.com/repos/sentiolabs/envctl/releases" - -// githubRelease represents the relevant fields from the GitHub releases API response. -type githubRelease struct { - TagName string `json:"tag_name"` -} - -// getLatestVersion fetches the latest release tag from the GitHub API. -func getLatestVersion() (string, error) { - resp, err := http.Get(githubReleasesURL + "/latest") //nolint:noctx // Simple one-shot HTTP request for CLI tool - if err != nil { - return "", fmt.Errorf("failed to fetch latest release: %w", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return "", fmt.Errorf("unexpected status %d from GitHub API", resp.StatusCode) - } - - var release githubRelease - if err := json.NewDecoder(resp.Body).Decode(&release); err != nil { - return "", fmt.Errorf("failed to decode release response: %w", err) - } - - return release.TagName, nil -} - -// ensureVPrefix normalizes a version string to have a "v" prefix. -// Empty strings and "dev" are treated as development versions. -func ensureVPrefix(v string) string { - if v == "" || v == "dev" { - return "v0.0.0-dev" - } - if !strings.HasPrefix(v, "v") { - return "v" + v - } - return v -} - -// runSelfUpdate implements the self update command logic. -// -//nolint:revive // CLI output to stdout -func runSelfUpdate(cmd *cobra.Command, _ []string) error { - current := ensureVPrefix(version.Version) - - latest, err := getLatestVersion() - if err != nil { - return fmt.Errorf("failed to check for updates: %w", err) - } - - cmp := semver.Compare(latest, current) +// installScriptURL is the install script that self update pipes into bash +// with --force --tag=. +const installScriptURL = "https://raw.githubusercontent.com/sentiolabs/envctl/main/scripts/install.sh" - // Check-only mode: print status and return - if selfCheck { - switch { - case cmp == 0: - fmt.Fprintf(cmd.OutOrStdout(), "envctl %s is up to date\n", current) - case cmp > 0: - fmt.Fprintf(cmd.OutOrStdout(), "Update available: %s -> %s\n", current, latest) - default: - fmt.Fprintf(cmd.OutOrStdout(), "Current version %s is newer than latest release %s\n", current, latest) - } - return nil - } - - // Already up to date - if cmp == 0 && !selfForce { - fmt.Fprintf(cmd.OutOrStdout(), "envctl %s is already up to date\n", current) - return nil - } - - // Current is newer than latest - if cmp < 0 && !selfForce { - fmt.Fprintf(cmd.OutOrStdout(), "Current version %s is newer than latest release %s\n", current, latest) - return nil - } +// binaryName and repoOwner identify the GitHub releases self update reads. +const ( + binaryName = "envctl" + repoOwner = "sentiolabs" +) - fmt.Fprintf(cmd.OutOrStdout(), "Updating envctl %s -> %s...\n", current, latest) +// selfUpdater is the shared updater. Tests swap its Source and Store. +var selfUpdater = newSelfUpdater() - // Confirmation prompt - if !selfYes { - fmt.Fprint(cmd.OutOrStdout(), "Continue? [y/N] ") - reader := bufio.NewReader(os.Stdin) - answer, err := reader.ReadString('\n') - if err != nil { - return fmt.Errorf("failed to read input: %w", err) - } - answer = strings.TrimSpace(answer) - if answer != "y" && answer != "Y" { - fmt.Fprintln(cmd.OutOrStdout(), "Update cancelled.") - return nil - } +// newSelfUpdater builds the updater for the envctl binary: releases come from +// github.com/sentiolabs/envctl, the channel lives in the per-user config file, +// and installs run the repository's install script. +func newSelfUpdater() *selfupdate.Updater { + return &selfupdate.Updater{ + Name: binaryName, + Version: version.Version, + Source: &selfupdate.GitHubSource{Owner: repoOwner, Repo: binaryName}, + Store: userconfig.ChannelStore(), + Installer: &selfupdate.ScriptInstaller{ScriptURL: installScriptURL}, } - - return runInstallScript(latest) } -// runInstallScript downloads and runs the install script for the given version tag. -func runInstallScript(tag string) error { - const installURL = "https://raw.githubusercontent.com/sentiolabs/envctl/main/scripts/install.sh" - script := fmt.Sprintf( - "curl -fsSL %s | bash -s -- --force --tag=%s", installURL, tag, - ) - installCmd := exec.Command("bash", "-c", script) - installCmd.Stdout = os.Stdout - installCmd.Stderr = os.Stderr - installCmd.Stdin = os.Stdin - - if err := installCmd.Run(); err != nil { - return fmt.Errorf("install script failed: %w", err) - } - return nil +func init() { + // --check has no shorthand: the root command owns -c for --config. + rootCmd.AddCommand(cobracmd.New(selfUpdater)) } diff --git a/internal/cmd/self_test.go b/internal/cmd/self_test.go index 26b9fdb..e6bf4a9 100644 --- a/internal/cmd/self_test.go +++ b/internal/cmd/self_test.go @@ -3,167 +3,192 @@ package cmd import ( "bytes" + "context" "encoding/json" "net/http" "net/http/httptest" "testing" + "time" - "github.com/sentiolabs/envctl/internal/version" + "github.com/sentiolabs/go-selfupdate" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -// testVersionTag is the tagged version string used by the version fixtures. -const testVersionTag = "v0.1.0" - -func TestEnsureVPrefix(t *testing.T) { - tests := []struct { - name string - input string - expected string - }{ - { - name: "empty string becomes dev version", - input: "", - expected: "v0.0.0-dev", - }, - { - name: "dev becomes dev version", - input: testDevEnv, - expected: "v0.0.0-dev", - }, - { - name: "version without v prefix gets v added", - input: "0.1.0", - expected: testVersionTag, - }, - { - name: "version with v prefix unchanged", - input: testVersionTag, - expected: testVersionTag, - }, - } +const ( + // selfCmdName is the command group under test. + selfCmdName = "self" + // updateCmdName is the subcommand that installs a new release. + updateCmdName = "update" + // tagNameKey and prereleaseKey are the GitHub release JSON fields the + // httptest server returns. + tagNameKey = "tag_name" + prereleaseKey = "prerelease" +) - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - result := ensureVPrefix(tt.input) - assert.Equal(t, tt.expected, result) - }) - } +func TestSelfUpdaterWiring(t *testing.T) { + u := newSelfUpdater() + assert.Equal(t, binaryName, u.Name) + src, ok := u.Source.(*selfupdate.GitHubSource) + require.True(t, ok) + assert.Equal(t, repoOwner, src.Owner) + assert.Equal(t, binaryName, src.Repo) + inst, ok := u.Installer.(*selfupdate.ScriptInstaller) + require.True(t, ok) + assert.Equal(t, installScriptURL, inst.ScriptURL) + assert.NotNil(t, u.Store) } -func TestGetLatestVersion(t *testing.T) { - t.Run("success returns tag_name", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, "/latest", r.URL.Path) - w.Header().Set("Content-Type", "application/json") - err := json.NewEncoder(w).Encode(githubRelease{TagName: "v1.2.3"}) - assert.NoError(t, err) - })) - defer server.Close() - - original := githubReleasesURL - githubReleasesURL = server.URL - defer func() { githubReleasesURL = original }() - - ver, err := getLatestVersion() - require.NoError(t, err) - assert.Equal(t, "v1.2.3", ver) - }) - - t.Run("non-200 status returns error", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.WriteHeader(http.StatusNotFound) - })) - defer server.Close() - - original := githubReleasesURL - githubReleasesURL = server.URL - defer func() { githubReleasesURL = original }() - - _, err := getLatestVersion() - require.Error(t, err) - assert.Contains(t, err.Error(), "unexpected status") - }) - - t.Run("invalid JSON returns error", func(t *testing.T) { - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - _, err := w.Write([]byte("not json")) - assert.NoError(t, err) - })) - defer server.Close() - - original := githubReleasesURL - githubReleasesURL = server.URL - defer func() { githubReleasesURL = original }() - - _, err := getLatestVersion() - require.Error(t, err) - }) +func TestSelfCommandTree(t *testing.T) { + self, _, err := rootCmd.Find([]string{selfCmdName}) + require.NoError(t, err) + update, _, err := rootCmd.Find([]string{selfCmdName, "update"}) + require.NoError(t, err) + channel, _, err := rootCmd.Find([]string{selfCmdName, "channel"}) + require.NoError(t, err) + assert.Equal(t, selfCmdName, self.Name()) + + check := update.Flags().Lookup("check") + require.NotNil(t, check) + assert.Empty(t, check.Shorthand, "-c belongs to --config on the root command") + assert.Equal(t, "f", update.Flags().Lookup("force").Shorthand) + assert.Equal(t, "y", update.Flags().Lookup("yes").Shorthand) + assert.Equal(t, "y", channel.Flags().Lookup("yes").Shorthand) } -// setupCheckModeTest creates a mock GitHub server and configures the test environment -// for a self-update check mode test case. It returns the output buffer. -func setupCheckModeTest(t *testing.T, latestTag, currentVersion string) *bytes.Buffer { +// withTestReleases points the shared updater at an httptest GitHub and an +// in-memory store for the duration of the test. +func withTestReleases(t *testing.T, channel selfupdate.Channel, latest string, list []map[string]any) *bytes.Buffer { t.Helper() - - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { - w.Header().Set("Content-Type", "application/json") - err := json.NewEncoder(w).Encode(githubRelease{TagName: latestTag}) - assert.NoError(t, err) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/repos/sentiolabs/envctl/releases/latest": + _ = json.NewEncoder(w).Encode(map[string]any{tagNameKey: latest}) + case "/repos/sentiolabs/envctl/releases": + _ = json.NewEncoder(w).Encode(list) + default: + w.WriteHeader(http.StatusNotFound) + } })) - t.Cleanup(server.Close) - - original := githubReleasesURL - githubReleasesURL = server.URL - t.Cleanup(func() { githubReleasesURL = original }) + t.Cleanup(srv.Close) - origVersion := version.Version - version.Version = currentVersion - t.Cleanup(func() { version.Version = origVersion }) - - buf := new(bytes.Buffer) - selfUpdateCmd.SetOut(buf) - selfUpdateCmd.SetErr(buf) - - err := selfUpdateCmd.Flags().Set("check", "true") - require.NoError(t, err) + prevSource, prevStore := selfUpdater.Source, selfUpdater.Store + prevOut, prevErr := selfUpdater.Out, selfUpdater.ErrOut t.Cleanup(func() { - err := selfUpdateCmd.Flags().Set("check", "false") - if err != nil { - t.Logf("failed to reset flag: %v", err) - } + selfUpdater.Source, selfUpdater.Store = prevSource, prevStore + selfUpdater.Out, selfUpdater.ErrOut = prevOut, prevErr }) + out := &bytes.Buffer{} + selfUpdater.Source = &selfupdate.GitHubSource{Owner: repoOwner, Repo: binaryName, BaseURL: srv.URL} + selfUpdater.Store = &selfupdate.MemStore{Current: channel} + selfUpdater.Out = out + selfUpdater.ErrOut = out + return out +} - return buf +func execRoot(t *testing.T, args ...string) error { + t.Helper() + rootCmd.SetArgs(args) + t.Cleanup(func() { rootCmd.SetArgs(nil) }) + return rootCmd.Execute() } -func TestSelfUpdateCheckMode_UpToDate(t *testing.T) { - buf := setupCheckModeTest(t, "v1.0.0", "v1.0.0") +func TestSelfUpdateCheck_StableChannel(t *testing.T) { + out := withTestReleases(t, selfupdate.ChannelStable, "v9.0.0", nil) + require.NoError(t, execRoot(t, selfCmdName, "update", "--check")) + assert.Contains(t, out.String(), "Update available: v0.0.0-dev -> v9.0.0 (stable channel)") +} - err := selfUpdateCmd.RunE(selfUpdateCmd, []string{}) - require.NoError(t, err) +func TestSelfUpdateCheck_RCChannelPrefersRC(t *testing.T) { + list := []map[string]any{ + {tagNameKey: "v9.1.0-rc.1", prereleaseKey: true}, + {tagNameKey: "v9.0.0", prereleaseKey: false}, + } + out := withTestReleases(t, selfupdate.ChannelRC, "v9.0.0", list) + require.NoError(t, execRoot(t, selfCmdName, "update", "--check")) + assert.Contains(t, out.String(), "v9.1.0-rc.1 (rc channel)") +} - assert.Contains(t, buf.String(), "up to date") +func TestSelfUpdateCheck_RCChannelStableNewerWins(t *testing.T) { + list := []map[string]any{ + {tagNameKey: "v9.2.0", prereleaseKey: false}, + {tagNameKey: "v9.1.0-rc.1", prereleaseKey: true}, + } + out := withTestReleases(t, selfupdate.ChannelRC, "v9.2.0", list) + require.NoError(t, execRoot(t, selfCmdName, "update", "--check")) + assert.Contains(t, out.String(), "-> v9.2.0 (rc channel)") } -func TestSelfUpdateCheckMode_UpdateAvailable(t *testing.T) { - buf := setupCheckModeTest(t, "v2.0.0", "v1.0.0") +func TestSelfChannelShowAndSwitch(t *testing.T) { + out := withTestReleases(t, selfupdate.ChannelStable, "v1.0.0", nil) + require.NoError(t, execRoot(t, selfCmdName, "channel")) + assert.Contains(t, out.String(), "Current update channel: stable") - err := selfUpdateCmd.RunE(selfUpdateCmd, []string{}) - require.NoError(t, err) + out.Reset() + require.NoError(t, execRoot(t, selfCmdName, "channel", "rc", "-y")) + assert.Contains(t, out.String(), "Switched to rc channel") + store := selfUpdater.Store.(*selfupdate.MemStore) + assert.Equal(t, selfupdate.ChannelRC, store.Current) - output := buf.String() - assert.Contains(t, output, "v2.0.0") - assert.Contains(t, output, "available") + err := execRoot(t, selfCmdName, "channel", "bogus", "-y") + require.Error(t, err) + assert.Contains(t, err.Error(), "invalid channel") } -func TestSelfUpdateCheckMode_CurrentIsNewer(t *testing.T) { - buf := setupCheckModeTest(t, "v1.0.0", "v2.0.0") +// blockingInstaller stands in for ScriptInstaller. It reports that it +// started and then returns only once its context is done, so an installer +// handed a context with a nil Done channel would block forever. +type blockingInstaller struct{ started chan struct{} } - err := selfUpdateCmd.RunE(selfUpdateCmd, []string{}) +func (b *blockingInstaller) Install(ctx context.Context, _ string) error { + close(b.started) + <-ctx.Done() + return ctx.Err() +} + +// TestSelfUpdateCancelsWithRootContext checks that the command context +// reaches the installer. Cancelling it must end self update instead of +// leaving it waiting on the install. +func TestSelfUpdateCancelsWithRootContext(t *testing.T) { + withTestReleases(t, selfupdate.ChannelStable, "v9.0.0", nil) + + inst := &blockingInstaller{started: make(chan struct{})} + prevInstaller := selfUpdater.Installer + t.Cleanup(func() { selfUpdater.Installer = prevInstaller }) + selfUpdater.Installer = inst + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + go func() { + select { + case <-inst.started: + cancel() + case <-ctx.Done(): + } + }() + + // The context goes on the update command itself: cobra copies the root + // context down only while the subcommand's own context is nil, and the + // --check tests above already stamped context.Background() onto this one. + // --check=false is explicit for the same reason, because cobra keeps the + // value an earlier Execute parsed into the flag variable. + update, _, err := rootCmd.Find([]string{selfCmdName, updateCmdName}) require.NoError(t, err) + update.SetContext(ctx) + rootCmd.SetArgs([]string{selfCmdName, updateCmdName, "-y", "--check=false"}) + t.Cleanup(func() { + rootCmd.SetArgs(nil) + update.SetContext(context.Background()) + rootCmd.SetContext(context.Background()) + }) - assert.Contains(t, buf.String(), "newer than latest") + done := make(chan error, 1) + go func() { done <- rootCmd.Execute() }() + + select { + case err := <-done: + require.ErrorIs(t, err, context.Canceled) + case <-time.After(2 * time.Second): + t.Fatal("self update did not return after its context was cancelled") + } } diff --git a/internal/cmd/validate.go b/internal/cmd/validate.go index 7d85f3f..de7d973 100644 --- a/internal/cmd/validate.go +++ b/internal/cmd/validate.go @@ -43,7 +43,7 @@ func init() { // //nolint:revive // Validation requires checking multiple conditions; stdout writes always succeed func runValidate(cmd *cobra.Command, args []string) error { - ctx := context.Background() + ctx := commandContext(cmd) // Load config configPath, err := resolveConfigPath() diff --git a/internal/userconfig/userconfig.go b/internal/userconfig/userconfig.go new file mode 100644 index 0000000..7983c1f --- /dev/null +++ b/internal/userconfig/userconfig.go @@ -0,0 +1,128 @@ +// Package userconfig reads and writes envctl's per-user settings file. Unlike +// .envctl.yaml, which describes a project and is checked in, this file holds +// preferences that belong to one machine, such as the update channel. +package userconfig + +import ( + "errors" + "fmt" + "os" + "path/filepath" + + "github.com/sentiolabs/go-selfupdate" + "gopkg.in/yaml.v3" +) + +const ( + // appDir and fileName join to form the path under XDG_CONFIG_HOME. + appDir = "envctl" + fileName = "config.yaml" + // dirMode and fileMode keep the settings file readable only by its owner. + dirMode = 0o700 + fileMode = 0o600 +) + +// Config is the per-user settings file. +type Config struct { + Updates Updates `yaml:"updates,omitempty"` +} + +// Updates holds settings for envctl self update. +type Updates struct { + // Channel is the update channel: stable, rc, or nightly. + Channel string `yaml:"channel,omitempty"` +} + +// Path returns $XDG_CONFIG_HOME/envctl/config.yaml, or ~/.config/envctl/config.yaml. +func Path() (string, error) { + if base := os.Getenv("XDG_CONFIG_HOME"); base != "" { + return filepath.Join(base, appDir, fileName), nil + } + home, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("resolve home directory: %w", err) + } + return filepath.Join(home, ".config", appDir, fileName), nil +} + +// Load reads the file. A missing file is an empty Config, not an error. +func Load() (*Config, error) { + p, err := Path() + if err != nil { + return nil, err + } + data, err := os.ReadFile(p) + if errors.Is(err, os.ErrNotExist) { + return &Config{}, nil + } + if err != nil { + return nil, fmt.Errorf("read %s: %w", p, err) + } + var cfg Config + if err := yaml.Unmarshal(data, &cfg); err != nil { + return nil, fmt.Errorf("parse %s: %w", p, err) + } + return &cfg, nil +} + +// Save writes cfg atomically with mode 0600 inside a 0700 directory. +func Save(cfg *Config) error { + p, err := Path() + if err != nil { + return err + } + dir := filepath.Dir(p) + if err := os.MkdirAll(dir, dirMode); err != nil { + return fmt.Errorf("create %s: %w", dir, err) + } + data, err := yaml.Marshal(cfg) + if err != nil { + return fmt.Errorf("encode config: %w", err) + } + tmp, err := os.CreateTemp(dir, "."+fileName+".tmp-*") + if err != nil { + return fmt.Errorf("create temp file: %w", err) + } + tmpName := tmp.Name() + cleanup := func() { _ = os.Remove(tmpName) } + if _, err := tmp.Write(data); err != nil { + _ = tmp.Close() + cleanup() + return fmt.Errorf("write %s: %w", p, err) + } + if err := tmp.Close(); err != nil { + cleanup() + return fmt.Errorf("close %s: %w", p, err) + } + if err := os.Chmod(tmpName, fileMode); err != nil { + cleanup() + return fmt.Errorf("chmod %s: %w", p, err) + } + if err := os.Rename(tmpName, p); err != nil { + cleanup() + return fmt.Errorf("replace %s: %w", p, err) + } + return nil +} + +// ChannelStore adapts the file to selfupdate.Store. An absent file reads as +// an empty channel, which the updater treats as stable. +func ChannelStore() selfupdate.Store { + return selfupdate.FuncStore{ + Get: func() (selfupdate.Channel, error) { + cfg, err := Load() + if err != nil { + return "", err + } + return selfupdate.Channel(cfg.Updates.Channel), nil + }, + Set: func(c selfupdate.Channel) error { + cfg, err := Load() + if err != nil { + return err + } + cfg.Updates.Channel = string(c) + return Save(cfg) + }, + } +} diff --git a/internal/userconfig/userconfig_test.go b/internal/userconfig/userconfig_test.go new file mode 100644 index 0000000..6327deb --- /dev/null +++ b/internal/userconfig/userconfig_test.go @@ -0,0 +1,90 @@ +package userconfig_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/sentiolabs/envctl/internal/userconfig" + "github.com/sentiolabs/go-selfupdate" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestPath_XDGOverride(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", "/tmp/xdg-test") + p, err := userconfig.Path() + require.NoError(t, err) + assert.Equal(t, "/tmp/xdg-test/envctl/config.yaml", p) +} + +func TestPath_DefaultUnderHome(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", "") + home := t.TempDir() + t.Setenv("HOME", home) + p, err := userconfig.Path() + require.NoError(t, err) + assert.Equal(t, filepath.Join(home, ".config", "envctl", "config.yaml"), p) +} + +func TestLoad_MissingFileIsEmptyConfig(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + cfg, err := userconfig.Load() + require.NoError(t, err) + assert.Empty(t, cfg.Updates.Channel) +} + +func TestSaveLoadRoundTripAndModes(t *testing.T) { + xdg := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", xdg) + + require.NoError(t, userconfig.Save(&userconfig.Config{Updates: userconfig.Updates{Channel: "rc"}})) + + p, _ := userconfig.Path() + info, err := os.Stat(p) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o600), info.Mode().Perm()) + dir, err := os.Stat(filepath.Dir(p)) + require.NoError(t, err) + assert.Equal(t, os.FileMode(0o700), dir.Mode().Perm()) + + raw, err := os.ReadFile(p) + require.NoError(t, err) + assert.Contains(t, string(raw), "channel: rc") + + cfg, err := userconfig.Load() + require.NoError(t, err) + assert.Equal(t, "rc", cfg.Updates.Channel) + + entries, err := os.ReadDir(filepath.Dir(p)) + require.NoError(t, err) + assert.Len(t, entries, 1, "no temp file may remain") +} + +func TestLoad_InvalidYAMLIsError(t *testing.T) { + xdg := t.TempDir() + t.Setenv("XDG_CONFIG_HOME", xdg) + dir := filepath.Join(xdg, "envctl") + require.NoError(t, os.MkdirAll(dir, 0o700)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yaml"), []byte("updates: [\n"), 0o600)) + _, err := userconfig.Load() + require.Error(t, err) +} + +func TestChannelStore(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + store := userconfig.ChannelStore() + + ch, err := store.Channel() + require.NoError(t, err) + assert.Equal(t, selfupdate.Channel(""), ch, "fresh machine has no stored channel") + + require.NoError(t, store.SetChannel(selfupdate.ChannelNightly)) + ch, err = store.Channel() + require.NoError(t, err) + assert.Equal(t, selfupdate.ChannelNightly, ch) + + cfg, err := userconfig.Load() + require.NoError(t, err) + assert.Equal(t, "nightly", cfg.Updates.Channel) +}