diff --git a/cmd/deploy/config.go b/cmd/deploy/config.go index 64ad7df..f56a505 100644 --- a/cmd/deploy/config.go +++ b/cmd/deploy/config.go @@ -17,6 +17,10 @@ func loadDeployConfig(clusterName string) (map[string]any, error) { return nil, fmt.Errorf("failed to read deploy.yaml: %w", err) } + return parseDeployConfig(data) +} + +func parseDeployConfig(data []byte) (map[string]any, error) { var config map[string]any if err := yaml.Unmarshal(data, &config); err != nil { return nil, fmt.Errorf("failed to parse deploy.yaml: %w", err) diff --git a/cmd/deploy/deploy_test.go b/cmd/deploy/deploy_test.go index 1cf5c8b..26b274d 100644 --- a/cmd/deploy/deploy_test.go +++ b/cmd/deploy/deploy_test.go @@ -2,6 +2,7 @@ package deploy import ( "os" + "os/exec" "path/filepath" "strings" "testing" @@ -729,3 +730,44 @@ func TestDeployRenderDefaultsToDeployYAML(t *testing.T) { t.Fatalf("expected missing deploy.yaml path in error, got: %v", err) } } + +func TestDeployVersionsFromGitReadsOriginMain(t *testing.T) { + repo := t.TempDir() + git := func(args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", repo, "-c", "user.name=test", "-c", "user.email=test@example.com"}, args...)...) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v failed: %v\n%s", args, err, out) + } + } + write := func(ref string) { + t.Helper() + dir := filepath.Join(repo, "cluster-a") + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + content := "understack_ref: " + ref + "\ndeploy_ref: HEAD\n" + if err := os.WriteFile(filepath.Join(dir, "deploy.yaml"), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + + git("init", "-b", "main") + write("v1.0.0") + git("add", ".") + git("commit", "-m", "main") + git("update-ref", "refs/remotes/origin/main", "HEAD") + + git("checkout", "-b", "feature") + write("v2.0.0") + git("commit", "-am", "feature") + + var out strings.Builder + if err := runDeployVersionsFromGit(repo, &out, false, false); err != nil { + t.Fatalf("runDeployVersionsFromGit failed: %v", err) + } + + if !strings.Contains(out.String(), "v1.0.0") || strings.Contains(out.String(), "v2.0.0") { + t.Errorf("expected origin/main state, got: %q", out.String()) + } +} diff --git a/cmd/deploy/versions.go b/cmd/deploy/versions.go index d380fb4..9d97187 100644 --- a/cmd/deploy/versions.go +++ b/cmd/deploy/versions.go @@ -4,35 +4,138 @@ import ( "fmt" "io" "os" + "os/exec" + "path" "path/filepath" + "strings" "text/tabwriter" "github.com/spf13/cobra" ) +const ( + versionsRemote = "origin" + versionsBranch = "main" +) + +// deployConfigSource yields the environments of a deployment repo and the +// parsed deploy.yaml of each, from either the working tree or a git ref. +type deployConfigSource struct { + environments func() ([]string, error) + load func(environment string) (map[string]any, error) +} + func newCmdDeployVersions() *cobra.Command { - var showUnknowns bool + var showUnknowns, local, noFetch bool cmd := &cobra.Command{ Use: "versions", Short: "Show the UnderStack version deployed in each environment", Long: `List every environment in the deployment repo along with its understack_ref and deploy_ref from deploy.yaml. +By default origin/main is fetched and read straight from git, so the output reflects the latest main +regardless of the branch checked out. Use --local to read the working tree instead. Environments where either ref is unknown are hidden unless --show-unknowns is passed.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { - return runDeployVersions(".", cmd.OutOrStdout(), showUnknowns) + if local { + return runDeployVersions(".", cmd.OutOrStdout(), showUnknowns) + } + return runDeployVersionsFromGit(".", cmd.OutOrStdout(), showUnknowns, !noFetch) }, } cmd.Flags().BoolVar(&showUnknowns, "show-unknowns", false, "include environments whose understack_ref or deploy_ref is unknown") + cmd.Flags().BoolVar(&local, "local", false, "read the working tree instead of origin/main") + cmd.Flags().BoolVar(&noFetch, "no-fetch", false, "skip fetching origin/main and use the last fetched state") + cmd.MarkFlagsMutuallyExclusive("local", "no-fetch") return cmd } func runDeployVersions(repoDir string, out io.Writer, showUnknowns bool) error { - entries, err := os.ReadDir(repoDir) + return printDeployVersions(workingTreeSource(repoDir), out, showUnknowns) +} + +func runDeployVersionsFromGit(repoDir string, out io.Writer, showUnknowns, fetch bool) error { + ref := versionsRemote + "/" + versionsBranch + + if fetch { + if _, err := runGit(repoDir, "fetch", versionsRemote, versionsBranch); err != nil { + return fmt.Errorf("failed to fetch %s (use --no-fetch or --local to work offline): %w", ref, err) + } + } + + return printDeployVersions(gitRefSource(repoDir, ref), out, showUnknowns) +} + +func workingTreeSource(repoDir string) deployConfigSource { + return deployConfigSource{ + environments: func() ([]string, error) { + entries, err := os.ReadDir(repoDir) + if err != nil { + return nil, fmt.Errorf("failed to read deployment repo: %w", err) + } + + var names []string + for _, entry := range entries { + if !entry.IsDir() { + continue + } + if _, err := os.Stat(filepath.Join(repoDir, entry.Name(), "deploy.yaml")); err != nil { + continue + } + names = append(names, entry.Name()) + } + return names, nil + }, + load: func(environment string) (map[string]any, error) { + return loadDeployConfig(filepath.Join(repoDir, environment)) + }, + } +} + +func gitRefSource(repoDir, ref string) deployConfigSource { + return deployConfigSource{ + environments: func() ([]string, error) { + listing, err := runGit(repoDir, "ls-tree", "-r", "--name-only", ref) + if err != nil { + return nil, fmt.Errorf("failed to list files in %s: %w", ref, err) + } + + var names []string + for _, file := range strings.Split(listing, "\n") { + if dir, base := path.Split(file); base == "deploy.yaml" && strings.Count(dir, "/") == 1 { + names = append(names, strings.TrimSuffix(dir, "/")) + } + } + return names, nil + }, + load: func(environment string) (map[string]any, error) { + data, err := runGit(repoDir, "show", ref+":"+environment+"/deploy.yaml") + if err != nil { + return nil, fmt.Errorf("failed to read deploy.yaml for %s from %s: %w", environment, ref, err) + } + return parseDeployConfig([]byte(data)) + }, + } +} + +func runGit(repoDir string, args ...string) (string, error) { + cmd := exec.Command("git", append([]string{"-C", repoDir}, args...)...) + output, err := cmd.Output() + if err != nil { + if exitErr, ok := err.(*exec.ExitError); ok && len(exitErr.Stderr) > 0 { + return "", fmt.Errorf("%w: %s", err, strings.TrimSpace(string(exitErr.Stderr))) + } + return "", err + } + return string(output), nil +} + +func printDeployVersions(source deployConfigSource, out io.Writer, showUnknowns bool) error { + environments, err := source.environments() if err != nil { - return fmt.Errorf("failed to read deployment repo: %w", err) + return err } // tabwriter defers write errors to Flush, which is returned below. @@ -40,17 +143,8 @@ func runDeployVersions(repoDir string, out io.Writer, showUnknowns bool) error { _, _ = fmt.Fprintln(w, "ENVIRONMENT\tUNDERSTACK\tDEPLOY") found := false - for _, entry := range entries { - if !entry.IsDir() { - continue - } - - clusterDir := filepath.Join(repoDir, entry.Name()) - if _, err := os.Stat(filepath.Join(clusterDir, "deploy.yaml")); err != nil { - continue - } - - config, err := loadDeployConfig(clusterDir) + for _, environment := range environments { + config, err := source.load(environment) if err != nil { return err } @@ -71,7 +165,7 @@ func runDeployVersions(repoDir string, out io.Writer, showUnknowns bool) error { continue } - _, _ = fmt.Fprintf(w, "%s\t%s\t%s\n", entry.Name(), understackRef, deployRef) + _, _ = fmt.Fprintf(w, "%s\t%s\t%s\n", environment, understackRef, deployRef) } if !found {