Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions cmd/deploy/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
42 changes: 42 additions & 0 deletions cmd/deploy/deploy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package deploy

import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
Expand Down Expand Up @@ -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())
}
}
126 changes: 110 additions & 16 deletions cmd/deploy/versions.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,53 +4,147 @@ 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.
w := tabwriter.NewWriter(out, 0, 4, 2, ' ', 0)
_, _ = 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
}
Expand All @@ -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 {
Expand Down
Loading