From 0e60781f4773669c8d8dc2b881865855b816b0eb Mon Sep 17 00:00:00 2001 From: unkin-agent Date: Sun, 8 Nov 2026 21:32:46 +1100 Subject: [PATCH] Add environment aliases pointing at their target's worktree --- internal/deploy/config.go | 15 ++- internal/deploy/config_test.go | 4 + internal/deploy/deploy.go | 72 +++++++++++- internal/deploy/deploy_test.go | 196 +++++++++++++++++++++++++++++++++ main.go | 12 +- 5 files changed, 291 insertions(+), 8 deletions(-) diff --git a/internal/deploy/config.go b/internal/deploy/config.go index aaf43bd..f53bc7b 100644 --- a/internal/deploy/config.go +++ b/internal/deploy/config.go @@ -15,9 +15,10 @@ type Config struct { Cachedir string `yaml:"cachedir"` Sources map[string]*Source `yaml:"sources"` W10k struct { - GCGrace *time.Duration `yaml:"gc_grace"` - GitTimeout *time.Duration `yaml:"git_timeout"` - GenerateTypes bool `yaml:"generate_types"` + GCGrace *time.Duration `yaml:"gc_grace"` + GitTimeout *time.Duration `yaml:"git_timeout"` + GenerateTypes bool `yaml:"generate_types"` + Aliases map[string]string `yaml:"aliases"` } `yaml:"w10k"` } @@ -58,6 +59,14 @@ func ParseConfig(b []byte) (*Config, error) { if c.W10k.GitTimeout != nil && *c.W10k.GitTimeout <= 0 { return nil, fmt.Errorf("w10k.git_timeout must be positive") } + for alias, target := range c.W10k.Aliases { + if !wordOnly.MatchString(alias) || !wordOnly.MatchString(target) { + return nil, fmt.Errorf("w10k.aliases: %s -> %s: names must match \\w+", alias, target) + } + if _, ok := c.W10k.Aliases[target]; ok { + return nil, fmt.Errorf("w10k.aliases: %s -> %s: target is an alias", alias, target) + } + } if len(c.Sources) == 0 { return nil, fmt.Errorf("no sources defined") } diff --git a/internal/deploy/config_test.go b/internal/deploy/config_test.go index 82b514e..5f7164d 100644 --- a/internal/deploy/config_test.go +++ b/internal/deploy/config_test.go @@ -67,6 +67,10 @@ func TestParseConfigErrors(t *testing.T) { "bad prefix": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, prefix: [x]}}", "bad invalid": "cachedir: /c\nsources: {a: {remote: r, basedir: /b, invalid_branches: nope}}", "bad source name": "cachedir: /c\nsources: {a-b: {remote: r, basedir: /b}}", + "bad alias name": "cachedir: /c\nw10k: {aliases: {a-b: develop}}\nsources: {a: {remote: r, basedir: /b}}", + "bad alias target": "cachedir: /c\nw10k: {aliases: {production: dev/x}}\nsources: {a: {remote: r, basedir: /b}}", + "alias of alias": "cachedir: /c\nw10k: {aliases: {production: staging, staging: develop}}\nsources: {a: {remote: r, basedir: /b}}", + "self alias": "cachedir: /c\nw10k: {aliases: {production: production}}\nsources: {a: {remote: r, basedir: /b}}", } { if _, err := ParseConfig([]byte(in)); err == nil { t.Errorf("%s: expected error", name) diff --git a/internal/deploy/deploy.go b/internal/deploy/deploy.go index cc35f6e..2ea4274 100644 --- a/internal/deploy/deploy.go +++ b/internal/deploy/deploy.go @@ -241,6 +241,11 @@ func (d *Deployer) Deploy(ctx context.Context, only []string, modules bool) erro } plans = append(plans, p) } + if err := d.checkAliases(plans); err != nil { + d.count("failed") + end() + return errors.Join(append(errs, err)...) + } errs = append(errs, d.selectEnvs(plans, only)...) for _, p := range plans { if err := d.deploySource(ctx, p, modules); err != nil { @@ -279,6 +284,9 @@ func (d *Deployer) selectEnvs(plans []*srcPlan, only []string) []error { p.want = map[string]bool{} } for _, a := range only { + if t, ok := d.cfg.W10k.Aliases[a]; ok { + a = t + } isEnv := slices.ContainsFunc(plans, func(p *srcPlan) bool { _, ok := p.envs[a]; return ok }) hit := false var why []error @@ -310,6 +318,42 @@ func (d *Deployer) selectEnvs(plans []*srcPlan, only []string) []error { return errs } +// checkAliases requires every alias name to be free and its target to come from at most one source. +func (d *Deployer) checkAliases(plans []*srcPlan) error { + var errs []error + for _, a := range slices.Sorted(maps.Keys(d.cfg.W10k.Aliases)) { + t := d.cfg.W10k.Aliases[a] + var in []string + for _, p := range plans { + if _, ok := p.envs[a]; ok { + errs = append(errs, fmt.Errorf("alias %s collides with an environment in source %s", a, p.s.Name)) + } + if _, ok := p.envs[t]; ok { + in = append(in, p.s.Name) + } + } + if len(in) > 1 { + errs = append(errs, fmt.Errorf("alias %s: target %s exists in sources %s", a, t, strings.Join(in, ", "))) + } + } + return errors.Join(errs...) +} + +// aliasesOf returns the aliases targeting env, sorted. +func (d *Deployer) aliasesOf(env string) []string { + var out []string + for a, t := range d.cfg.W10k.Aliases { + if t == env { + out = append(out, a) + } + } + slices.Sort(out) + return out +} + +// Aliases maps alias env name -> target env name. +func (d *Deployer) Aliases() map[string]string { return d.cfg.W10k.Aliases } + // skipErrs returns the distinct reasons, in branch order, for skipped branches match accepts. func (p *srcPlan) skipErrs(match func(string) bool) []error { var out []error @@ -421,7 +465,11 @@ func (d *Deployer) deploySource(ctx context.Context, p *srcPlan, modules bool) e wg.Add(1) go func() { defer wg.Done() - if err := d.deployEnv(ctx, s, name, ref, modules); err != nil { + err := d.deployEnv(ctx, s, name, ref, modules) + if err == nil { + err = d.swapAliases(s, name) + } + if err != nil { mu.Lock() errs = append(errs, fmt.Errorf("environment %s: %w", name, err)) mu.Unlock() @@ -435,6 +483,25 @@ func (d *Deployer) deploySource(ctx context.Context, p *srcPlan, modules bool) e return errors.Join(errs...) } +// swapAliases points each alias of env at env's worktree itself, never at env's link. +func (d *Deployer) swapAliases(s *Source, env string) error { + target := d.owned(s, filepath.Join(s.Basedir, env)) + if target == "" { + return fmt.Errorf("environment link not owned after deploy") + } + for _, a := range d.aliasesOf(env) { + link := filepath.Join(s.Basedir, a) + if t, err := os.Readlink(link); err == nil && t == target { + continue + } + if err := Swap(target, link); err != nil { + return fmt.Errorf("alias %s: %w", a, err) + } + log.Printf("alias %s -> %s", a, filepath.Base(target)) + } + return nil +} + func linkTarget(link string) string { t, err := os.Readlink(link) if err != nil { @@ -835,6 +902,9 @@ func (d *Deployer) purge(s *Source, envs map[string]envRef) error { if _, ok := envs[e.Name()]; ok { continue } + if _, ok := envs[d.cfg.W10k.Aliases[e.Name()]]; ok { + continue + } link := filepath.Join(s.Basedir, e.Name()) if d.owned(s, link) == "" { continue diff --git a/internal/deploy/deploy_test.go b/internal/deploy/deploy_test.go index 0ec941b..c21e64b 100644 --- a/internal/deploy/deploy_test.go +++ b/internal/deploy/deploy_test.go @@ -1490,3 +1490,199 @@ func TestCorrectedBranchCollisionSkipsAll(t *testing.T) { t.Fatal("collision must not block other envs") } } + +func aliasFixture(t *testing.T) (*fixture, string, string) { + f := newFixture(t) + commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"}) + gitT(t, f.control, "branch", "develop") + f.cfg.W10k.Aliases = map[string]string{"production": "develop"} + return f, filepath.Join(f.basedir, "production"), filepath.Join(f.basedir, "develop") +} + +func readlinkT(t *testing.T, p string) string { + t.Helper() + s, err := os.Readlink(p) + if err != nil { + t.Fatal(err) + } + return s +} + +func TestAliasPointsAtTargetWorktree(t *testing.T) { + f, prod, dev := aliasFixture(t) + f.mustDeploy(false) + got, want := readlinkT(t, prod), readlinkT(t, dev) + if got != want || !filepath.IsAbs(got) || filepath.Dir(got) != f.cache("worktrees", "unkin") { + t.Fatalf("production -> %q, develop -> %q; want the same absolute worktree", got, want) + } + live, err := f.deployer().Live(f.cfg.Sources["unkin"]) + if err != nil || live["production"] != want { + t.Fatalf("alias must be live: %v %v", live, err) + } +} + +func TestAliasSwapsAtomicallyWithTarget(t *testing.T) { + f, prod, dev := aliasFixture(t) + f.mustDeploy(false) + gitT(t, f.control, "checkout", "-q", "develop") + sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node new {}\n"}) + stop := make(chan struct{}) + missing := make(chan string, 1) + go func() { + for { + select { + case <-stop: + close(missing) + return + default: + } + if _, err := os.Stat(prod); err != nil { + missing <- err.Error() + close(missing) + return + } + } + }() + f.mustDeploy(false) + close(stop) + if m, ok := <-missing; ok { + t.Fatalf("production vanished during swap: %s", m) + } + if got := readlinkT(t, prod); got != readlinkT(t, dev) || !strings.HasPrefix(filepath.Base(got), sha+"-") { + t.Fatalf("production -> %s, want develop's new worktree at %s", got, sha) + } + if exists(filepath.Join(f.basedir, ".production.w10k")) { + t.Fatal("leftover swap temp link") + } +} + +func TestAliasNamedDeploys(t *testing.T) { + f, prod, dev := aliasFixture(t) + f.mustDeploy(false) + gitT(t, f.control, "checkout", "-q", "develop") + for _, arg := range []string{"develop", "production"} { + sha := commit(t, f.control, map[string]string{"manifests/site.pp": "node " + arg + " {}\n"}) + main := f.env("main") + if err := f.deploy(false, arg); err != nil { + t.Fatalf("deploy %s: %v", arg, err) + } + if got := readlinkT(t, prod); got != readlinkT(t, dev) || !strings.HasPrefix(filepath.Base(got), sha+"-") { + t.Fatalf("deploy %s: production -> %s, want develop at %s", arg, got, sha) + } + if f.env("main") != main { + t.Fatalf("deploy %s touched main", arg) + } + } +} + +func TestAliasValidationErrors(t *testing.T) { + t.Run("collision", func(t *testing.T) { + f, prod, _ := aliasFixture(t) + gitT(t, f.control, "branch", "production") + if err := f.deploy(false); err == nil || !strings.Contains(err.Error(), "alias production collides") { + t.Fatalf("want collision error, got %v", err) + } + if exists(prod) || f.env("develop") != "" { + t.Fatal("a config error must deploy nothing") + } + }) + t.Run("ambiguous", func(t *testing.T) { + f, _, _ := aliasFixture(t) + f.cfg.Sources["other"] = &Source{Name: "other", Remote: f.control, Basedir: filepath.Join(f.root, "code", "other"), InvalidBranches: "correct_and_warn"} + if err := f.deploy(false, "main"); err == nil || !strings.Contains(err.Error(), "target develop exists in sources other, unkin") { + t.Fatalf("want ambiguity error, got %v", err) + } + if f.env("main") != "" { + t.Fatal("a config error must deploy nothing") + } + }) +} + +func TestAliasPurged(t *testing.T) { + t.Run("removed from config", func(t *testing.T) { + f, prod, _ := aliasFixture(t) + f.mustDeploy(false) + f.cfg.W10k.Aliases = nil + if err := f.deploy(false, "develop"); err != nil || !exists(prod) { + t.Fatalf("named deploys never purge: %v", err) + } + f.mustDeploy(false) + if exists(prod) { + t.Fatal("alias removed from config must be purged") + } + }) + t.Run("target gone", func(t *testing.T) { + f, prod, _ := aliasFixture(t) + f.mustDeploy(false) + gitT(t, f.control, "branch", "-D", "develop") + f.mustDeploy(false) + if exists(prod) { + t.Fatal("alias of a vanished target must be purged") + } + }) +} + +func TestGCKeepsAliasOnlyWorktree(t *testing.T) { + f, prod, dev := aliasFixture(t) + f.mustDeploy(false) + wt := readlinkT(t, prod) + mustRemove(t, dev) + d := f.deployer() + for range 3 { + f.clock = f.clock.Add(11 * time.Minute) + if err := d.GC(context.Background()); err != nil { + t.Fatal(err) + } + } + if _, err := os.Stat(filepath.Join(wt, "manifests", "site.pp")); err != nil { + t.Fatalf("GC removed a worktree referenced by an alias: %v", err) + } +} + +func TestAliasCutover(t *testing.T) { + for name, setup := range map[string]func(t *testing.T, prod string){ + "real dir": func(t *testing.T, prod string) { + mkdirs(t, prod) + if err := os.WriteFile(filepath.Join(prod, "site.pp"), []byte("old"), 0o644); err != nil { + t.Fatal(err) + } + }, + "relative symlink": func(t *testing.T, prod string) { + mkdirs(t, filepath.Join(filepath.Dir(prod), "g10k_develop")) + if err := os.Symlink("g10k_develop", prod); err != nil { + t.Fatal(err) + } + }, + } { + t.Run(name, func(t *testing.T) { + f, prod, dev := aliasFixture(t) + setup(t, prod) + f.mustDeploy(false) + if got := readlinkT(t, prod); got != readlinkT(t, dev) || !filepath.IsAbs(got) { + t.Fatalf("production -> %q after cutover", got) + } + }) + } +} + +func TestAliasPinsCompileAcrossMove(t *testing.T) { + f, prod, _ := aliasFixture(t) + f.mustDeploy(false) + pinned, err := filepath.EvalSymlinks(prod) + if err != nil { + t.Fatal(err) + } + gitT(t, f.control, "checkout", "-q", "develop") + commit(t, f.control, map[string]string{"manifests/site.pp": "node moved {}\n"}) + f.mustDeploy(false) + f.clock = f.clock.Add(time.Minute) + if err := f.deployer().GC(context.Background()); err != nil { + t.Fatal(err) + } + if got := readFileT(t, filepath.Join(pinned, "manifests", "site.pp")); got != "node default {}\n" { + t.Fatalf("pinned compile read %q", got) + } + if readFileT(t, filepath.Join(prod, "manifests", "site.pp")) != "node moved {}\n" { + t.Fatal("alias did not follow the move") + } +} diff --git a/main.go b/main.go index 6efec92..13acaeb 100644 --- a/main.go +++ b/main.go @@ -51,12 +51,12 @@ func rootCmd() *cobra.Command { } return d, nil } - live := func() ([][3]string, error) { + live := func() ([][4]string, error) { d, err := load() if err != nil { return nil, err } - var rows [][3]string + var rows [][4]string for _, s := range d.Sources() { live, err := d.Live(s) if err != nil { @@ -64,7 +64,11 @@ func rootCmd() *cobra.Command { } for _, e := range slices.Sorted(maps.Keys(live)) { sha, _, _ := strings.Cut(filepath.Base(live[e]), "-") - rows = append(rows, [3]string{s.Name, e, sha}) + alias := "" + if t, ok := d.Aliases()[e]; ok { + alias = "\talias of " + t + } + rows = append(rows, [4]string{s.Name, e, sha, alias}) } } return rows, nil @@ -123,7 +127,7 @@ func rootCmd() *cobra.Command { return err } for _, r := range rows { - _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", r[0], r[1], r[2]) + _, _ = fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s%s\n", r[0], r[1], r[2], r[3]) } return nil },