diff --git a/commands.go b/commands.go index 3951ecf..b6354c3 100644 --- a/commands.go +++ b/commands.go @@ -21,7 +21,8 @@ func sortedKeys[V any](m map[string]V) []string { } // digitSpan renders sorted ladder digits compactly: "1-5" when -// contiguous, else "1,3,7". +// contiguous, else "1,3,7". The byte arithmetic relies on every key +// being a single digit, which effortKeyRe in config.go enforces. func digitSpan(digits []string) string { contiguous := len(digits) > 1 for i := 1; i < len(digits); i++ { @@ -74,23 +75,6 @@ func tokensOf(cfg Config) []string { return tokens } -// tokenSource reports where a token's effective definition comes from: -// "project" for profiles the project file declares and for grammar -// tokens of project-declared model letters, else "global". -func tokenSource(token string, projModels, projProfiles map[string]bool) string { - if projProfiles[token] { - return "project" - } - letters := token - if last := token[len(token)-1]; last >= '0' && last <= '9' { - letters = token[:len(token)-1] - } - if projModels[letters] { - return "project" - } - return "global" -} - // viewContext carries everything the list and show renderers need, // assembled once per command so the renderers stay pure and testable. type viewContext struct { @@ -103,6 +87,7 @@ type viewContext struct { projModels map[string]bool // model letters the project file declares projProfiles map[string]bool // profile names the project file declares globalTokens map[string]bool // tokens `clau link` would create (global set) + projEfforts bool // the project file declares a non-empty [efforts] pal palette } @@ -110,6 +95,33 @@ func (vc viewContext) linked(token string) bool { return isOwned(filepath.Join(vc.dir, linkFileName("c"+token, vc.goos)), vc.clauPath) } +// tokenSource reports where a token's effective definition comes from: +// "project" for profiles the project file declares, for grammar tokens +// of project-declared model letters, and for every digit token when the +// project declares [efforts] (it replaces the whole ladder, so even a +// digit the global ladder also had is the project's), else "global". +// A profile the project does not declare is global whatever its name +// looks like: profiles beat the grammar in resolveToken, so the digit +// rules never apply to one. +func (vc viewContext) tokenSource(token string) string { + if vc.projProfiles[token] { + return "project" + } + if _, ok := vc.cfg.Profiles[token]; ok { + return "global" + } + letters := token + digit := false + if last := token[len(token)-1]; last >= '0' && last <= '9' { + letters = token[:len(token)-1] + digit = true + } + if vc.projModels[letters] || (digit && vc.projEfforts) { + return "project" + } + return "global" +} + // joinBadges dim-joins non-empty annotation parts with " · ". func joinBadges(pal palette, parts ...string) string { var kept []string @@ -151,16 +163,24 @@ func profileCell(p Profile, pal palette) string { } // familyStates aggregates link state over a model letter's grammar -// family (the letter plus its effort digits): linkable when any family -// token is in the global set, linked when every family command exists. -// The digits come from the effective ladder, so a project [efforts] -// replacement leaves the badge conservative: it can warn about family -// commands the global-only `clau link` will never create. -func familyStates(letter string, spec ModelSpec, vc viewContext) (linkable, linked bool) { +// family as `clau link` manages it: the letter plus the digit tokens in +// the global set. Linkable when any of those is global, linked when +// every one has its command. The effective ladder is deliberately not +// consulted: link is global-only, so under a project [efforts] +// replacement it would warn forever about commands link never creates +// while missing the global ones it prunes. A project-only digit token +// shows up in the footer count and in `clau show`, not on the row. +// A profile named like a digit token (o5, o7) is skipped: it wins +// resolution, so its command is the profile row's to warn about. +func familyStates(letter string, vc viewContext) (linkable, linked bool) { toks := []string{letter} - if spec.Efforts { - for _, d := range sortedKeys(vc.cfg.Efforts) { - toks = append(toks, letter+d) + for d := '1'; d <= '9'; d++ { + t := letter + string(d) + if _, isProfile := vc.cfg.Profiles[t]; isProfile { + continue + } + if vc.globalTokens[t] { + toks = append(toks, t) } } linked = true @@ -199,17 +219,20 @@ func renderSection(header string, rows []listRowV, pal palette) []string { return lines } -// footerLine summarizes link health: linkable commands are the global -// token set (what `clau link` manages); the rest are project-only. +// footerLine summarizes link health: linkable commands are the whole +// global token set (what `clau link` creates and prunes, whether or not +// the project layer still exposes them); effective tokens outside that +// set are project-only. func footerLine(vc viewContext) string { linkable, linked, projectOnly := 0, 0, 0 + for t := range vc.globalTokens { + linkable++ + if vc.linked(t) { + linked++ + } + } for _, t := range tokensOf(vc.cfg) { - if vc.globalTokens[t] { - linkable++ - if vc.linked(t) { - linked++ - } - } else { + if !vc.globalTokens[t] { projectOnly++ } } @@ -246,7 +269,7 @@ func listView(vc viewContext) []string { var mrows []listRowV for _, letter := range sortedKeys(vc.cfg.Models) { spec := vc.cfg.Models[letter] - linkable, linked := familyStates(letter, spec, vc) + linkable, linked := familyStates(letter, vc) note := "" if !spec.Efforts { note = pal.dim + "no effort digits" + pal.reset @@ -377,7 +400,7 @@ func showView(vc viewContext, arg string) ([]string, error) { out = append(out, row("kind", kindLine(vc, token))) src := "global (" + contractHome(vc.globalPath) + ")" - if tokenSource(token, vc.projModels, vc.projProfiles) == "project" { + if vc.tokenSource(token) == "project" { src = "project (" + vc.st.Path + ")" } out = append(out, row("source", src)) @@ -483,7 +506,7 @@ func newViewContext(cfg Config, st ProjectStatus, dir string) viewContext { if g, err := loadConfig(configPath()); err == nil { globalCfg = g } - vc.projModels, vc.projProfiles, _ = projectDeclarations(st.Path) + vc.projModels, vc.projProfiles, vc.projEfforts, _ = projectDeclarations(st.Path) } vc.globalTokens = map[string]bool{} for _, t := range tokensOf(globalCfg) { @@ -663,7 +686,7 @@ func projectFindings(st ProjectStatus, store map[string]string, corrupt bool) [] fs = append(fs, finding{"ok", "no project config in effect"}) case st.Applied: fs = append(fs, finding{"ok", fmt.Sprintf("project config %s trusted and applied", st.Path)}) - if models, profiles, err := projectDeclarations(st.Path); err == nil { + if models, profiles, _, err := projectDeclarations(st.Path); err == nil { var parts []string if len(models) > 0 { keys := make([]string, 0, len(models)) diff --git a/commands_test.go b/commands_test.go index 4ac76fb..ebde7d7 100644 --- a/commands_test.go +++ b/commands_test.go @@ -102,23 +102,52 @@ func TestStarterConfigIsValidAndInert(t *testing.T) { } func TestTokenSource(t *testing.T) { - projModels := map[string]bool{"g": true} - projProfiles := map[string]bool{"rev": true} + cfg := defaultConfig() + cfg.Profiles["rev"] = Profile{Model: "opus"} + cfg.Profiles["v2"] = Profile{Model: "opus"} // global profile ending in a digit + cfg.Profiles["g3"] = Profile{Model: "sonnet"} // global profile shaped like a project letter's grammar + vc := viewContext{cfg: cfg, + projModels: map[string]bool{"g": true}, + projProfiles: map[string]bool{"rev": true}, + } cases := map[string]string{ "rev": "project", // declared profile, even if it shadows a global one "g": "project", // project model letter "g5": "project", // grammar token of a project model + "g3": "global", // a profile beats the grammar, and this one is not the project's + "v2": "global", "o5": "global", "s": "global", } for token, want := range cases { - if got := tokenSource(token, projModels, projProfiles); got != want { + if got := vc.tokenSource(token); got != want { t.Errorf("tokenSource(%q) = %q, want %q", token, got, want) } } - if got := tokenSource("rev", nil, nil); got != "global" { + if got := (viewContext{cfg: cfg}).tokenSource("rev"); got != "global" { t.Errorf("nil maps must mean global, got %q", got) } + + // A project [efforts] replaces the whole ladder, so every digit token + // is project-sourced then, even a digit the global ladder also had; + // bare letters and global profiles keep their own provenance. + vc.projEfforts = true + ladder := map[string]string{ + "o6": "project", + "o5": "project", // remapped, not inherited + "g5": "project", + "g3": "global", + "v2": "global", + "o": "global", + "s": "global", + "g": "project", + "rev": "project", + } + for token, want := range ladder { + if got := vc.tokenSource(token); got != want { + t.Errorf("tokenSource(%q, efforts) = %q, want %q", token, got, want) + } + } } func TestProjectFindings(t *testing.T) { @@ -222,7 +251,10 @@ func TestRowBadges(t *testing.T) { }{ {"linked global", false, true, true, ""}, {"unlinked global", false, true, false, "not linked — run clau link"}, + {"orphaned link", false, false, true, ""}, // linked, but no longer in the global set {"project linked", true, true, true, "project"}, + {"project unlinked global", true, true, false, "project · not linked — run clau link"}, + {"project orphaned link", true, false, true, "project"}, {"project only unlinked", true, false, false, "project · c gma"}, {"unlinkable unlinked", false, false, false, "c gma"}, } @@ -257,7 +289,7 @@ func TestFamilyStates(t *testing.T) { } // Nothing linked yet: linkable but not linked. - linkable, linked := familyStates("o", cfg.Models["o"], vc) + linkable, linked := familyStates("o", vc) if !linkable || linked { t.Errorf("unlinked family: linkable=%v linked=%v, want true false", linkable, linked) } @@ -268,19 +300,80 @@ func TestFamilyStates(t *testing.T) { t.Fatal(err) } } - linkable, linked = familyStates("o", cfg.Models["o"], vc) + linkable, linked = familyStates("o", vc) if !linkable || !linked { t.Errorf("linked family: linkable=%v linked=%v, want true true", linkable, linked) } - // A project-declared letter is not linkable and not linked. + // A letter without effort digits is a family of one. + cfg.Models["k"] = ModelSpec{Model: "kimi"} + vc.globalTokens["k"] = true + linkable, linked = familyStates("k", vc) + if !linkable || linked { + t.Errorf("unlinked k: linkable=%v linked=%v, want true false", linkable, linked) + } + if err := os.Symlink(clauPath, filepath.Join(dir, "ck")); err != nil { + t.Fatal(err) + } + linkable, linked = familyStates("k", vc) + if !linkable || !linked { + t.Errorf("linked k: linkable=%v linked=%v, want true true", linkable, linked) + } + + // Links that are no longer in the global set (a project-declared + // letter, or orphans) are not linkable, but still count as linked: + // the badge then shows nothing extra. vc2 := vc vc2.globalTokens = map[string]bool{} - linkable, linked = familyStates("o", cfg.Models["o"], vc2) - if linkable { - t.Errorf("project family must not be linkable") + linkable, linked = familyStates("o", vc2) + if linkable || !linked { + t.Errorf("orphaned family: linkable=%v linked=%v, want false true", linkable, linked) + } + + // A project [efforts] ladder replaces the effective digits, but the + // family clau link manages is still co, co1..co5: all present means + // nothing to warn about, and a missing one is still a warning. + vc3 := vc + vc3.cfg.Efforts = map[string]string{"6": "max"} + linkable, linked = familyStates("o", vc3) + if !linkable || !linked { + t.Errorf("project ladder, global family linked: linkable=%v linked=%v, want true true", linkable, linked) + } + if err := os.Remove(filepath.Join(dir, "co5")); err != nil { + t.Fatal(err) + } + linkable, linked = familyStates("o", vc3) + if !linkable || linked { + t.Errorf("project ladder, co5 missing: linkable=%v linked=%v, want true false", linkable, linked) + } +} + +// A profile named like a grammar token owns its command (it wins +// resolution), so a missing one warns on the profile row only, whether +// the name shadows a ladder digit (o5) or sits outside the ladder (o7). +func TestFamilyStatesSkipsProfiles(t *testing.T) { + cfg := defaultConfig() + cfg.Profiles["o5"] = Profile{Model: "opus"} + cfg.Profiles["o7"] = Profile{Model: "opus"} + vc := plainListVC(t, cfg) + for _, tok := range []string{"o", "o1", "o2", "o3", "o4"} { + if err := os.Symlink(vc.clauPath, filepath.Join(vc.dir, "c"+tok)); err != nil { + t.Fatal(err) + } + } + linkable, linked := familyStates("o", vc) + if !linkable || !linked { + t.Errorf("o family with co5/co7 owned by profiles: linkable=%v linked=%v, want true true", linkable, linked) + } + lines := listView(vc) + if l := lineWith(t, lines, " o opus"); strings.Contains(l, "not linked") { + t.Errorf("model row warns about a profile's command: %q", l) + } + for _, name := range []string{"o5", "o7"} { + if l := lineWith(t, lines, " "+name+" opus"); !strings.Contains(l, "not linked — run clau link") { + t.Errorf("%s profile row must warn: %q", name, l) + } } - _ = linked // linked=true here (symlinks exist) is acceptable: badge shows nothing extra } // plainListVC builds a no-color viewContext over cfg with nothing linked. @@ -417,6 +510,20 @@ func TestFooterLine(t *testing.T) { if got := footerLine(vc); got != "all 24 commands linked in "+contractHome(vc.dir)+" · 1 project-only · details: clau show " { t.Errorf("linked footer = %q", got) } + + // A project [efforts] ladder (digit 6 only) swaps the effective + // digits, but the denominator stays the 24 commands clau link + // manages; f6 h6 o6 s6 join gma as project-only. + vc.cfg.Efforts = map[string]string{"6": "max"} + if got := footerLine(vc); got != "all 24 commands linked in "+contractHome(vc.dir)+" · 5 project-only · details: clau show " { + t.Errorf("project ladder footer = %q", got) + } + if err := os.Remove(filepath.Join(vc.dir, "co5")); err != nil { + t.Fatal(err) + } + if got := footerLine(vc); got != "23 of 24 commands linked in "+contractHome(vc.dir)+" — run clau link · 5 project-only · details: clau show " { + t.Errorf("project ladder footer with co5 missing = %q", got) + } } func TestListViewColorSmoke(t *testing.T) { @@ -439,7 +546,11 @@ func TestMaskedEnvName(t *testing.T) { "MY_SECRET": true, "DB_PASSWORD": true, "anthropic_auth_token": true, + "TOKEN_EXPIRY": true, // the segment can sit anywhere "CLAUDE_CODE_MAX_CONTEXT_TOKENS": false, // segment is TOKENS, not TOKEN + "KEYS": false, + "SECRETS": false, + "PASSWORDS": false, "ANTHROPIC_BASE_URL": false, "MONKEYS": false, } @@ -477,7 +588,7 @@ func TestShowViewProfile(t *testing.T) { "gem → cgem", "kind profile · extends base: ollama", "source global (" + contractHome("/g/config.toml") + ")", - "linked no", + "linked no — run clau link", // global token: link can fix it "launches claude --model gemma4:12b --bare --strict-mcp-config", "ANTHROPIC_AUTH_TOKEN=•••", "ANTHROPIC_BASE_URL=http://localhost:11434", @@ -510,6 +621,18 @@ func TestShowViewKinds(t *testing.T) { } } +func TestShowViewPlainProfileKind(t *testing.T) { + vc := showVC(t) + vc.cfg.Profiles["rev"] = Profile{Model: "opus", Effort: "high"} + lines, err := showView(vc, "rev") + if err != nil { + t.Fatal(err) + } + if l := lineWith(t, lines, "kind"); l != " kind profile" { + t.Errorf("plain profile kind row = %q, want exactly profile", l) + } +} + func TestShowViewFallbacksAndErrors(t *testing.T) { vc := showVC(t) @@ -566,3 +689,32 @@ func TestShowViewProjectSourceAndLinked(t *testing.T) { t.Errorf("linked-yes line missing:\n%s", out) } } + +func TestShowViewProjectLadderSource(t *testing.T) { + vc := showVC(t) + vc.cfg.Efforts = map[string]string{"6": "max"} + vc.st = ProjectStatus{Path: "/repo/.clau.toml", Trusted: true, Applied: true} + vc.projEfforts = true + lines, err := showView(vc, "o6") + if err != nil { + t.Fatal(err) + } + if out := strings.Join(lines, "\n"); !strings.Contains(out, "source project (/repo/.clau.toml)") { + t.Errorf("project-ladder digit token must be project-sourced:\n%s", out) + } + lines, err = showView(vc, "o") + if err != nil { + t.Fatal(err) + } + if out := strings.Join(lines, "\n"); !strings.Contains(out, "source global (") { + t.Errorf("bare global letter must stay global-sourced:\n%s", out) + } + vc.cfg.Profiles["v2"] = Profile{Model: "opus"} + lines, err = showView(vc, "v2") + if err != nil { + t.Fatal(err) + } + if out := strings.Join(lines, "\n"); !strings.Contains(out, "source global (") { + t.Errorf("global profile ending in a digit must stay global-sourced:\n%s", out) + } +} diff --git a/completions_test.go b/completions_test.go index d108afa..da293e3 100644 --- a/completions_test.go +++ b/completions_test.go @@ -1,6 +1,7 @@ package main import ( + "regexp" "strings" "testing" ) @@ -32,14 +33,38 @@ func TestCompletionsIncludeTrustVerbs(t *testing.T) { } } -func TestCompletionsIncludeShow(t *testing.T) { - for _, shell := range []string{"fish", "zsh", "bash"} { - s, err := completionScript(shell) +// TestCompletionsPlaceShow checks show is a first-word verb and that +// its second word completes tokens like run's does, per shell. +func TestCompletionsPlaceShow(t *testing.T) { + cases := []struct { + shell string + verbs *regexp.Regexp // captures the literal verb list + branch string // the run/show token-completion guard + }{ + {"fish", regexp.MustCompile(`-a '(link [^']*)'`), "contains -- (commandline -opc)[2] run show;"}, + {"bash", regexp.MustCompile(`compgen -W "(link [^"$]*)`), `[ "${COMP_WORDS[1]}" = show ]`}, + {"zsh", regexp.MustCompile(`items=\((link [^)]*)\)`), "${words[2]} == (run|show)"}, + } + for _, c := range cases { + s, err := completionScript(c.shell) if err != nil { t.Fatal(err) } - if !strings.Contains(s, "show") { - t.Errorf("%s completions missing the show verb", shell) + m := c.verbs.FindStringSubmatch(s) + if m == nil { + t.Fatalf("%s: verb list not found:\n%s", c.shell, s) + } + inVerbs := false + for _, v := range strings.Fields(m[1]) { + if v == "show" { + inVerbs = true + } + } + if !inVerbs { + t.Errorf("%s: show missing from the verb list %q", c.shell, m[1]) + } + if !strings.Contains(s, c.branch) { + t.Errorf("%s: show missing from the token-completion branch (want %q):\n%s", c.shell, c.branch, s) } } } diff --git a/project.go b/project.go index 2fac405..7baf75a 100644 --- a/project.go +++ b/project.go @@ -158,19 +158,21 @@ func loadEffectiveConfig(cwd string, enforce bool) (Config, ProjectStatus, error } // projectDeclarations reports which model keys and profile names the -// project file itself declares, for provenance display. The file has -// already been validated by the time this is called. -func projectDeclarations(path string) (map[string]bool, map[string]bool, error) { +// project file itself declares, and whether it declares a non-empty +// [efforts] table (which replaces the whole ladder, see applyConfigFile), +// for provenance display. The file has already been validated by the +// time this is called. +func projectDeclarations(path string) (models, profiles map[string]bool, efforts bool, err error) { var raw rawConfig - if _, err := toml.DecodeFile(path, &raw); err != nil { - return nil, nil, err + if _, err = toml.DecodeFile(path, &raw); err != nil { + return nil, nil, false, err } - models, profiles := map[string]bool{}, map[string]bool{} + models, profiles = map[string]bool{}, map[string]bool{} for k := range raw.Models { models[k] = true } for k := range raw.Profiles { profiles[k] = true } - return models, profiles, nil + return models, profiles, len(raw.Efforts) > 0, nil } diff --git a/project_test.go b/project_test.go index 9482aa3..f4a02da 100644 --- a/project_test.go +++ b/project_test.go @@ -239,7 +239,7 @@ func TestProjectDeclarations(t *testing.T) { if err := os.WriteFile(p, []byte(body), 0o644); err != nil { t.Fatal(err) } - models, profiles, err := projectDeclarations(p) + models, profiles, efforts, err := projectDeclarations(p) if err != nil { t.Fatal(err) } @@ -249,4 +249,28 @@ func TestProjectDeclarations(t *testing.T) { if !profiles["deploy"] || len(profiles) != 1 { t.Errorf("profiles = %v", profiles) } + if efforts { + t.Error("no [efforts] table, but efforts reported as declared") + } +} + +func TestProjectDeclarationsEfforts(t *testing.T) { + p := filepath.Join(t.TempDir(), ".clau.toml") + if err := os.WriteFile(p, []byte("[efforts]\n6 = \"max\"\n"), 0o644); err != nil { + t.Fatal(err) + } + _, _, efforts, err := projectDeclarations(p) + if err != nil { + t.Fatal(err) + } + if !efforts { + t.Error("[efforts] table not reported as declared") + } + // An empty table is inert (applyConfigFile keeps the global ladder). + if err := os.WriteFile(p, []byte("[efforts]\n"), 0o644); err != nil { + t.Fatal(err) + } + if _, _, efforts, err = projectDeclarations(p); err != nil || efforts { + t.Errorf("empty [efforts]: efforts=%v err=%v, want false nil", efforts, err) + } } diff --git a/style.go b/style.go index 9252bab..63dabf5 100644 --- a/style.go +++ b/style.go @@ -42,6 +42,9 @@ func colorChoice(isTTY bool, goos string, getenv func(string) string) bool { return true } +// stdoutIsTTY uses the char-device heuristic deliberately: it also says +// yes for /dev/null, but nobody can see the escapes sent there, and the +// alternative is a golang.org/x/term dependency for no visible effect. func stdoutIsTTY() bool { fi, err := os.Stdout.Stat() if err != nil { @@ -66,16 +69,39 @@ func padCell(s string, w int) string { } // contractHome shortens a path under the user's home to ~/... for display. +// The raw strings are compared first, then the path's parent and home +// with symlinks resolved, so a home reached through a different +// symlinked path still contracts. Only the parent is resolved: the leaf +// is the thing being named, and a link file (co5 → clau) must not turn +// into its target. A parent that does not exist yet (the link dir +// before the first clau link) cannot be resolved and keeps the raw +// comparison. func contractHome(p string) string { home, err := os.UserHomeDir() if err != nil || home == "" { return p } + if rel, ok := tildeRel(p, home); ok { + return rel + } + clean := filepath.Clean(p) + rd, errD := filepath.EvalSymlinks(filepath.Dir(clean)) + rh, errH := filepath.EvalSymlinks(home) + if errD == nil && errH == nil { + if rel, ok := tildeRel(filepath.Join(rd, filepath.Base(clean)), rh); ok { + return rel + } + } + return p +} + +// tildeRel rewrites p as ~ or ~/... when it is home or inside it. +func tildeRel(p, home string) (string, bool) { if p == home { - return "~" + return "~", true } if strings.HasPrefix(p, home+string(filepath.Separator)) { - return "~" + p[len(home):] + return "~" + p[len(home):], true } - return p + return "", false } diff --git a/style_test.go b/style_test.go index ce5bc2b..2e0e5ed 100644 --- a/style_test.go +++ b/style_test.go @@ -3,6 +3,7 @@ package main import ( "os" "path/filepath" + "runtime" "testing" ) @@ -66,7 +67,62 @@ func TestContractHome(t *testing.T) { if got := contractHome(filepath.Join(home, ".local", "bin")); got != filepath.Join("~", ".local", "bin") { t.Errorf("contractHome = %q", got) } + if got := contractHome(home); got != "~" { + t.Errorf("home itself = %q, want ~", got) + } if got := contractHome("/opt/x"); got != "/opt/x" { t.Errorf("non-home path must pass through: %q", got) } } + +// TestContractHomeThroughSymlink covers a home reached via a different +// symlinked path, in both directions. On macOS t.TempDir() already sits +// under the /var → /private/var link, so even the raw strings differ. +func TestContractHomeThroughSymlink(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlinks need privileges and UserHomeDir reads USERPROFILE") + } + home := t.TempDir() + bin := filepath.Join(home, ".local", "bin") + if err := os.MkdirAll(bin, 0o755); err != nil { + t.Fatal(err) + } + alias := filepath.Join(t.TempDir(), "alias") + if err := os.Symlink(home, alias); err != nil { + t.Fatal(err) + } + want := filepath.Join("~", ".local", "bin") + + t.Setenv("HOME", home) + if got := contractHome(filepath.Join(alias, ".local", "bin")); got != want { + t.Errorf("path via alias, HOME real: %q, want %q", got, want) + } + if got := contractHome(filepath.Join(alias, ".local", "bin") + string(filepath.Separator)); got != want { + t.Errorf("trailing separator via alias: %q, want %q", got, want) + } + // The leaf is the thing being named: a link file must not turn into + // its target (co5 → ~/bin/clau) when the parent is resolved. + if err := os.MkdirAll(filepath.Join(home, "bin"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(home, "bin", "clau"), nil, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(home, "bin", "clau"), filepath.Join(bin, "co5")); err != nil { + t.Fatal(err) + } + if got, want := contractHome(filepath.Join(alias, ".local", "bin", "co5")), filepath.Join(want, "co5"); got != want { + t.Errorf("link file via alias: %q, want %q", got, want) + } + t.Setenv("HOME", alias) + if got := contractHome(bin); got != want { + t.Errorf("real path, HOME via alias: %q, want %q", got, want) + } + if got := contractHome(alias); got != "~" { + t.Errorf("alias itself with HOME via alias: %q, want ~", got) + } + // Outside home stays untouched even when it does not exist. + if p := filepath.Join(t.TempDir(), "nope"); contractHome(p) != p { + t.Errorf("non-home path must pass through: %q", contractHome(p)) + } +}