Merge pull request 'Add environment aliases' (#8) from benvin/aliases into main

Reviewed-on: #8
This commit was merged in pull request #8.
This commit is contained in:
2026-11-08 22:13:00 +11:00
6 changed files with 415 additions and 10 deletions
+12 -3
View File
@@ -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")
}
+4
View File
@@ -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)
+75 -3
View File
@@ -248,6 +248,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 {
@@ -286,6 +291,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
@@ -317,6 +325,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
@@ -428,7 +472,8 @@ 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 := errors.Join(d.deployEnv(ctx, s, name, ref, modules), d.swapAliases(s, name))
if err != nil {
mu.Lock()
errs = append(errs, fmt.Errorf("environment %s: %w", name, err))
mu.Unlock()
@@ -442,6 +487,29 @@ 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 current worktree itself, never at env's link.
func (d *Deployer) swapAliases(s *Source, env string) error {
aliases := d.aliasesOf(env)
target := d.owned(s, filepath.Join(s.Basedir, env))
if target == "" {
if len(aliases) > 0 {
log.Printf("error: environment %s has no w10k worktree, aliases %s left untouched", env, strings.Join(aliases, ", "))
}
return nil
}
for _, a := range aliases {
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 {
@@ -833,7 +901,7 @@ func Swap(target, link string) error {
return os.Rename(tmp, link)
}
// purge removes owned envs no branch claims; a name only skipped branches claim keeps its live env.
// purge removes owned envs no branch claims; a name only skipped branches claim keeps its live env, as do its aliases.
func (d *Deployer) purge(s *Source, envs map[string]envRef, skipped map[string]error) error {
entries, err := os.ReadDir(s.Basedir)
if err != nil {
@@ -849,7 +917,11 @@ func (d *Deployer) purge(s *Source, envs map[string]envRef, skipped map[string]e
}
}
for _, e := range entries {
if keep[e.Name()] {
name := e.Name()
if t, ok := d.cfg.W10k.Aliases[name]; ok {
name = t
}
if keep[name] {
continue
}
link := filepath.Join(s.Basedir, e.Name())
+284
View File
@@ -1496,6 +1496,290 @@ func TestCorrectedBranchCollisionSkipsAll(t *testing.T) {
}
}
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)
}
},
"absolute symlink": func(t *testing.T, prod string) {
g := filepath.Join(filepath.Dir(prod), "g10k_develop")
mkdirs(t, g)
if err := os.Symlink(g, 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")
}
}
func TestAliasSurvivesTargetCollision(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
gitT(t, f.control, "branch", "feature-x")
f.cfg.W10k.Aliases = map[string]string{"production": "feature_x"}
f.mustDeploy(false)
prod, fx := filepath.Join(f.basedir, "production"), filepath.Join(f.basedir, "feature_x")
old := readlinkT(t, prod)
gitT(t, f.control, "branch", "feature.x")
if err := f.deploy(false); err == nil {
t.Fatal("want collision error")
}
if !exists(prod) || readlinkT(t, prod) != old || readlinkT(t, fx) != old {
t.Fatal("a colliding push must keep the target and its alias on their worktree")
}
}
func TestAliasKeptOnFetchFailure(t *testing.T) {
f, prod, _ := aliasFixture(t)
f.mustDeploy(false)
old := readlinkT(t, prod)
f.cfg.Sources["unkin"].Remote = filepath.Join(f.root, "missing")
if err := f.deploy(false); err == nil {
t.Fatal("want fetch error")
}
if readlinkT(t, prod) != old {
t.Fatal("fetch failure moved or purged the alias")
}
}
func failDevelop(t *testing.T, f *fixture) {
t.Helper()
gitT(t, f.control, "checkout", "-q", "develop")
commit(t, f.control, map[string]string{"Puppetfile": "mod 'bind', :git => 'file:///nope'\n"})
}
func TestAliasFollowsTargetOldWorktreeOnFailure(t *testing.T) {
f, prod, dev := aliasFixture(t)
f.mustDeploy(false)
old := readlinkT(t, dev)
failDevelop(t, f)
if err := f.deploy(false); err == nil {
t.Fatal("want deploy error")
}
if readlinkT(t, dev) != old || readlinkT(t, prod) != old {
t.Fatalf("develop -> %s, production -> %s, want both on %s", readlinkT(t, dev), readlinkT(t, prod), old)
}
}
func TestNewAliasOfFailingTargetReplacesLinkToLink(t *testing.T) {
f, prod, dev := aliasFixture(t)
f.cfg.W10k.Aliases = nil
f.mustDeploy(false)
if err := os.Symlink("develop", prod); err != nil {
t.Fatal(err)
}
failDevelop(t, f)
f.cfg.W10k.Aliases = map[string]string{"production": "develop"}
if err := f.deploy(false); err == nil {
t.Fatal("want deploy error")
}
if readlinkT(t, prod) != readlinkT(t, dev) {
t.Fatalf("production -> %s, want develop's worktree %s", readlinkT(t, prod), readlinkT(t, dev))
}
}
func TestAliasUntouchedWhenTargetHasNoLink(t *testing.T) {
f, prod, _ := aliasFixture(t)
f.mustDeploy(false)
old := readlinkT(t, prod)
gitT(t, f.control, "checkout", "-q", "-b", "staging")
commit(t, f.control, map[string]string{"Puppetfile": "mod 'bind', :git => 'file:///nope'\n"})
f.cfg.W10k.Aliases = map[string]string{"production": "staging"}
if err := f.deploy(false); err == nil {
t.Fatal("want deploy error")
}
if readlinkT(t, prod) != old || f.env("staging") != "" {
t.Fatalf("production -> %s, want %s untouched", readlinkT(t, prod), old)
}
}
func TestCorrectedBranchCollisionKeepsLiveEnv(t *testing.T) {
f := newFixture(t)
commit(t, f.control, map[string]string{"manifests/site.pp": "node default {}\n"})
+8 -4
View File
@@ -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
},
+32
View File
@@ -36,3 +36,35 @@ func TestTimingsFlag(t *testing.T) {
}
}
}
func TestListShowsAliasRows(t *testing.T) {
root := t.TempDir()
cache, base := filepath.Join(root, "cache"), filepath.Join(root, "code")
wt := filepath.Join(cache, "worktrees", "unkin", "abc123-0123456789ab")
for _, d := range []string{wt, base} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
for _, e := range []string{"develop", "production"} {
if err := os.Symlink(wt, filepath.Join(base, e)); err != nil {
t.Fatal(err)
}
}
cfg := filepath.Join(root, "r10k.yaml")
y := "cachedir: " + cache + "\nw10k: {aliases: {production: develop}}\nsources: {unkin: {remote: r, basedir: " + base + "}}\n"
if err := os.WriteFile(cfg, []byte(y), 0o644); err != nil {
t.Fatal(err)
}
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"-c", cfg, "list"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
want := "unkin\tdevelop\tabc123\nunkin\tproduction\tabc123\talias of develop\n"
if out.String() != want {
t.Fatalf("list:\n%q\nwant\n%q", out.String(), want)
}
}