diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f81d4ca9..09320651 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,11 @@ jobs: run: | go build . - name: Test and coverage + env: + # The CLI tests in cmd/commands run on Windows as well. There, selecting + # an SDK globally writes the PATH that the registry holds for the user, + # so they only run where that may happen: a runner that is thrown away. + VFOX_TEST_WINDOWS_REGISTRY: '1' run: | go test ./... -coverprofile=coverage.out -covermode=atomic - name: Upload coverage to Codecov @@ -59,6 +64,39 @@ jobs: go test ./internal/sdk -run '^TestInstall' -count=1 -v if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + nushell: + name: Nushell integration + runs-on: ubuntu-latest + timeout-minutes: 10 + env: + # A release and the digest of its archive, so that this job tests the vfox + # change and not whatever Nushell published last. Bump them together: the + # digest is listed with the archive on the release page. + NU_VERSION: 0.117.0 + NU_SHA256: 33b907da92b0e80bd10fea9fa0e8a1624cabfebd89ee2568e365da3c492ffc68 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version-file: go.mod + - name: Install Nushell + run: | + archive="nu-${NU_VERSION}-x86_64-unknown-linux-gnu" + curl --fail --silent --show-error --location --retry 3 \ + --output "${RUNNER_TEMP}/nu.tar.gz" \ + "https://github.com/nushell/nushell/releases/download/${NU_VERSION}/${archive}.tar.gz" + echo "${NU_SHA256} ${RUNNER_TEMP}/nu.tar.gz" | sha256sum --check --strict - + mkdir "${RUNNER_TEMP}/nu" + tar --extract --gzip --file "${RUNNER_TEMP}/nu.tar.gz" --directory "${RUNNER_TEMP}/nu" + echo "${RUNNER_TEMP}/nu/${archive}" >> "${GITHUB_PATH}" + - name: Exercise a native Nushell session + env: + # Without it a Nushell that failed to install would skip the test. + VFOX_TEST_NUSHELL: '1' + run: | + nu --version + go test ./cmd/commands -run '^TestNushell' -count=1 -v + fish-completion: name: Fish completion integration runs-on: ubuntu-latest diff --git a/AGENTS.md b/AGENTS.md index e9b3166e..53278e3b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,6 +28,8 @@ go test ./... -coverprofile=coverage.out -covermode=atomic - Format changed Go files with `gofmt -w `. Use `go fmt ./...` when formatting the whole module is intended; preserve unrelated working-tree changes. - Use `go mod tidy` for dependency maintenance and `go get @` for intentional dependency changes. These commands can modify `go.mod` and `go.sum`. - Consult [.github/workflows/ci.yml](.github/workflows/ci.yml) for CI checks and `go.mod` for the required Go version. +- The CLI tests in `cmd/commands` (`cliFixture` in [cli_test.go](cmd/commands/cli_test.go)) run on Windows too, where selecting an SDK globally writes the user's PATH to the registry. `newCLIFixture` therefore skips there unless `VFOX_TEST_WINDOWS_REGISTRY=1`, which only a runner or VM that is thrown away should set (the `build` job in ci.yml does). Write new CLI tests so that they work on Windows: create commands with `writeCommand` and name them with `commandFile` (Windows runs files with a `PATHEXT` extension only), build PATH values with `pathList`, compare what `vfox env` and `vfox activate` export for bash with `shellPath`/`shellPaths` (`/c/a/b` on Windows), and make links with `linkDirectory` and `linkFile` (a junction and a hard link there, which need no privilege). The separate fixture in [env_test.go](cmd/commands/env_test.go) still skips on Windows. +- Tests that start a real shell skip when it is not installed: Fish (`TestFishCompletion`) and Nushell (`TestNushellSessionUsesTheBaselineItRecorded`, which builds vfox and runs `nu` on the `vfox.nu` it generates). The `fish-completion` and `nushell` jobs in ci.yml install them; the Nushell job pins a release by its SHA-256 and sets `VFOX_TEST_NUSHELL=1`, which turns a missing `nu` into a failure. ## E2E and release workflows @@ -110,7 +112,7 @@ java = { version = "21", vendor = "openjdk" } - Config chains append from lowest to highest priority. Use `GetToolConfig`/`GetToolVersion` for the winning configuration, or `GetToolConfigsByPriority` for fallback candidates; check the found flag before using a returned scope. - Within vfox-managed paths, priority is Project > Session > Global. Append paths in that order; merge ordinary variables in reverse order so Project wins. - Final PATH assembly preserves user paths before the first existing vfox path, such as an activated virtualenv: preserved prefix > vfox-managed paths > remaining system paths. Which of those entries stay in front depends on `path.mode` (`baseline`, the default, keeps those added after `vfox activate`; `legacy` keeps all, as vfox 1.0.x did; `aggressive` keeps only active virtualenv/conda directories and `path.preserve`); see [pathpolicy.go](internal/env/pathpolicy.go), [SplitSystemPaths](internal/env/context.go) and [environment export](cmd/commands/env.go). `vfox exec` puts the SDK paths before the preserved prefix. -- `vfox activate` records the PATH it found, minus vfox directories, in `__VFOX_ORIG_PATH` once per shell session (recomputed for an inherited session, never exported while resolving an IDE environment). `vfox env` only reads it. Nushell cannot evaluate what `activate` prints, so the `vfox.nu` template in [nushell.go](internal/shell/nushell.go) records it itself in `export-env`, before the first `env` call (the PATH as it is then, vfox directories included, which `env` skips anyway). A missing baseline means legacy behavior. The cached `env` output is also keyed by the PATH policy (`RuntimeEnvContext.PathPolicyKey`: `path.mode`, the expanded `path.preserve`, the active virtualenv/conda directories), because `config.yaml` is not among the files whose modification time is tracked; a setting that changes the PATH order has to be part of that key. It is keyed by the project scope as well (`projectToolsKey` in [env.go](cmd/commands/env.go): the project SDK directory and the project tools, empty when there are none), because legacy version files such as `.nvmrc` are not tracked either. It is also keyed by what is installed (`installsStamp`: whether the plugin of each configured tool is added and the modification time of its install directory) and by the links the output points at (`linksStamp`: which of `/` exist in the project, session and global link directories, taken again after the slow path, which makes them), because `vfox install`, `vfox add` and a removed `.vfox` change neither a tracked file nor the PATH. Config file times are compared with `!=` in nanoseconds, so a file replaced by an older one counts as changed. +- `vfox activate` records the PATH it found, minus vfox directories, in `__VFOX_ORIG_PATH` once per shell session (recomputed for an inherited session, never exported while resolving an IDE environment). `vfox env` only reads it. Nushell cannot evaluate what `activate` prints, so the `vfox.nu` template in [nushell.go](internal/shell/nushell.go) records it itself in `export-env`, before the first `env` call (the PATH as it is then, vfox directories included, which `env` skips anyway); a real Nushell checks that in `TestNushellSessionUsesTheBaselineItRecorded`, because the text of the script cannot show it. A missing baseline means legacy behavior. The cached `env` output is also keyed by the PATH policy (`RuntimeEnvContext.PathPolicyKey`: `path.mode`, the expanded `path.preserve`, the active virtualenv/conda directories), because `config.yaml` is not among the files whose modification time is tracked; a setting that changes the PATH order has to be part of that key. It is keyed by the project scope as well (`projectToolsKey` in [env.go](cmd/commands/env.go): the project SDK directory and the project tools, empty when there are none), because legacy version files such as `.nvmrc` are not tracked either. It is also keyed by what is installed (`installsStamp`: whether the plugin of each configured tool is added and the modification time of its install directory) and by the links the output points at (`linksStamp`: which of `/` exist in the project, session and global link directories, taken again after the slow path, which makes them), because `vfox install`, `vfox add` and a removed `.vfox` change neither a tracked file nor the PATH. Config file times are compared with `!=` in nanoseconds, so a file replaced by an older one counts as changed. - `baseline` is the default `path.mode`, defined once as `config.DefaultPathMode` in [path.go](internal/config/path.go): `EmptyPath`, both fallbacks of `EffectiveMode` (an empty or unknown value is the default, never a failure of a command that runs at every prompt) and the starting mode of `pathPolicy()` use it. `EffectiveMode` must name `legacy` as a case of its own, since it is no longer the fallback. Only `baseline` uses the recorded baseline to decide what stays in front; without one it behaves like `legacy`, so an upgrade does not reorder the PATH of a running shell. `aggressive` demotes the same entries with or without a baseline. In tests, a setting that has to survive a merge or a save needs a value other than the default (`legacy`), or the assertion cannot fail. - Preserve state-cache invalidation on configuration, project, and PATH changes. Use named scope constants; their numeric values do not define priority. diff --git a/cmd/commands/cli_test.go b/cmd/commands/cli_test.go index 5fefde6a..a8188efd 100644 --- a/cmd/commands/cli_test.go +++ b/cmd/commands/cli_test.go @@ -36,6 +36,7 @@ import ( "github.com/urfave/cli/v3" "github.com/version-fox/vfox/internal" + "github.com/version-fox/vfox/internal/env" ) // TestCLIProcess is the child of cliFixture.runProcess: it runs one vfox command line @@ -127,12 +128,24 @@ type cliFixture struct { // newCLIFixture sets up a vfox home with the alpha and plain plugins. When // splitShared is true the shared root is separate from the user's directory, // as with a VFOX_HOME that several users share. +// +// On Windows the tests select SDKs globally, which puts the SDK's directories in +// the PATH that the registry holds for the user who runs them. They only run +// where that does not matter: a CI runner, or a VM that is thrown away. func newCLIFixture(t *testing.T, splitShared bool) *cliFixture { t.Helper() - if runtime.GOOS == "windows" { - t.Skip("the fixture uses a POSIX shell environment") + if runtime.GOOS == "windows" && os.Getenv("VFOX_TEST_WINDOWS_REGISTRY") != "1" { + t.Skip("these tests change the user PATH in the Windows registry: set VFOX_TEST_WINDOWS_REGISTRY=1 on a runner or VM that is thrown away (CI does)") } root := t.TempDir() + if runtime.GOOS == "windows" { + // TEMP can name the user's directory by its short name (RUNNER~1) while + // calls that resolve a path report the long one, and the tests compare + // paths as text: use the long spelling throughout. + resolved, err := filepath.EvalSymlinks(root) + must(t, err) + root = resolved + } f := &cliFixture{ root: root, userHome: filepath.Join(root, ".vfox"), @@ -173,7 +186,7 @@ func (f *cliFixture) installOnDisk(t *testing.T, sdk, version string, commands . main := filepath.Join(f.shared, "cache", sdk, "v-"+version, sdk+"-"+version) must(t, os.MkdirAll(filepath.Join(main, "bin"), 0755)) for _, name := range commands { - must(t, os.WriteFile(filepath.Join(main, "bin", name), []byte("#!/bin/sh\n"), 0755)) + writeCommand(t, filepath.Join(main, "bin"), name) } return main } @@ -181,10 +194,15 @@ func (f *cliFixture) installOnDisk(t *testing.T, sdk, version string, commands . // external creates an SDK that belongs to somebody else. func (f *cliFixture) external(t *testing.T, commands ...string) string { t.Helper() - dir := filepath.Join(f.root, "external", fmt.Sprintf("sdk-%d", time.Now().UnixNano())) + parent := filepath.Join(f.root, "external") + must(t, os.MkdirAll(parent, 0755)) + // Two calls within one tick of the clock would get the same name from it, and + // the clock on Windows ticks slowly: let the file system pick a free one. + dir, err := os.MkdirTemp(parent, "sdk-") + must(t, err) must(t, os.MkdirAll(filepath.Join(dir, "bin"), 0755)) for _, name := range commands { - must(t, os.WriteFile(filepath.Join(dir, "bin", name), []byte("#!/bin/sh\n"), 0755)) + writeCommand(t, filepath.Join(dir, "bin"), name) } return dir } @@ -223,6 +241,9 @@ func (f *cliFixture) run(t *testing.T, args ...string) cliResult { // it gives to vfox: everything vfox reads from the environment of whoever runs // the tests. func stripped(key string) bool { + if runtime.GOOS == "windows" { + key = strings.ToUpper(key) // the names are case-insensitive there: Path is PATH + } return strings.HasPrefix(key, "VFOX_") || strings.HasPrefix(key, "__VFOX_") || key == "HOME" || key == "PATH" || key == "VIRTUAL_ENV" || key == "CONDA_PREFIX" || key == "TMUX" || key == "VSCODE_RESOLVING_ENVIRONMENT" || key == "INTELLIJ_ENVIRONMENT_READER" @@ -238,41 +259,45 @@ func (f *cliFixture) environ() map[string]string { "__VFOX_CURTMPPATH": filepath.Join(f.userHome, "tmp", "test-session"), "__VFOX_SHELL": "bash", // an activated shell, unless a test says otherwise } + if runtime.GOOS == "windows" { + environ["USERPROFILE"] = f.root // where os.UserHomeDir looks, instead of HOME + } for k, v := range f.env { environ[k] = v } return environ } -// runProcess executes `vfox ` in a fresh process inside the fixture. -func (f *cliFixture) runProcess(t *testing.T, args ...string) cliResult { - t.Helper() - exe, err := os.Executable() - must(t, err) - ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) - defer cancel() - - cmd := exec.CommandContext(ctx, exe, append([]string{"-test.run=^TestCLIProcess$", "--"}, args...)...) +// command is a process that runs in the fixture: in the project directory, with +// the environment of the fixture and nothing of vfox from the environment of +// whoever runs the tests. +func (f *cliFixture) command(ctx context.Context, name string, args ...string) *exec.Cmd { + cmd := exec.CommandContext(ctx, name, args...) cmd.Dir = f.work for _, kv := range os.Environ() { if key, _, _ := strings.Cut(kv, "="); !stripped(key) { cmd.Env = append(cmd.Env, kv) } } - environ := f.environ() - environ["VFOX_TEST_CLI"] = "1" - for k, v := range environ { + for k, v := range f.environ() { if v != "-" { cmd.Env = append(cmd.Env, k+"="+v) } } + return cmd +} + +// runCommand runs cmd to its end. A process that exits with a code is a result; +// one that cannot be started fails the test. +func runCommand(t *testing.T, cmd *exec.Cmd) cliResult { + t.Helper() var stdout, stderr bytes.Buffer cmd.Stdout, cmd.Stderr = &stdout, &stderr result := cliResult{} if err := cmd.Run(); err != nil { var exitErr *exec.ExitError if !errors.As(err, &exitErr) { - t.Fatalf("vfox %v: %v", args, err) + t.Fatalf("%v: %v", cmd.Args, err) } result.code = exitErr.ExitCode() } @@ -280,6 +305,19 @@ func (f *cliFixture) runProcess(t *testing.T, args ...string) cliResult { return result } +// runProcess executes `vfox ` in a fresh process inside the fixture. +func (f *cliFixture) runProcess(t *testing.T, args ...string) cliResult { + t.Helper() + exe, err := os.Executable() + must(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + + cmd := f.command(ctx, exe, append([]string{"-test.run=^TestCLIProcess$", "--"}, args...)...) + cmd.Env = append(cmd.Env, "VFOX_TEST_CLI=1") + return runCommand(t, cmd) +} + // manager is a vfox manager in the environment of the fixture, for the tests // that call the code behind a command directly. func (f *cliFixture) manager(t *testing.T) *internal.Manager { @@ -433,6 +471,74 @@ func exists(path string) bool { return err == nil } +// pathList is the value of a PATH that holds the given directories. +func pathList(dirs ...string) string { + return strings.Join(dirs, string(os.PathListSeparator)) +} + +// shellPath is how vfox writes a directory for the bash hook that the fixture +// pretends to run in: Git Bash spells C:\a\b as /c/a/b, which is what the +// PATH a command tells the shell to export holds on Windows. +func shellPath(dir string) string { + if runtime.GOOS != "windows" { + return dir + } + dir = filepath.ToSlash(dir) + if len(dir) > 1 && dir[1] == ':' { + dir = "/" + strings.ToLower(dir[:1]) + dir[2:] + } + return dir +} + +// shellPaths are the entries of the PATH that bash gets for the directories. +func shellPaths(dirs ...string) []string { + paths := make([]string, len(dirs)) + for i, dir := range dirs { + paths[i] = shellPath(dir) + } + return paths +} + +// commandFile is the file that provides a command in a bin directory. Windows +// runs a file only if its name has an extension from PATHEXT. +func commandFile(name string) string { + if runtime.GOOS == "windows" { + return name + ".cmd" + } + return name +} + +// writeCommand puts a command in dir and returns its file. No test runs it. +func writeCommand(t *testing.T, dir, name string) string { + t.Helper() + path := filepath.Join(dir, commandFile(name)) + content := "#!/bin/sh\n" + if runtime.GOOS == "windows" { + content = "@echo off\r\n" + } + must(t, os.WriteFile(path, []byte(content), 0755)) + return path +} + +// linkDirectory makes link lead to the directory target, the way a user does by +// hand: with a symlink, or with a junction on Windows, which needs no privilege. +func linkDirectory(t *testing.T, target, link string) { + t.Helper() + must(t, env.CreateDirSymlink(target, link)) +} + +// linkFile gives the file a second name, the way Homebrew does with a symlink. +// A symlink takes a privilege on Windows, so a hard link stands in there, which +// os.SameFile sees through as well. +func linkFile(t *testing.T, target, link string) { + t.Helper() + if runtime.GOOS == "windows" { + must(t, os.Link(target, link)) + return + } + must(t, os.Symlink(target, link)) +} + func readFile(t *testing.T, path string) string { t.Helper() content, err := os.ReadFile(path) diff --git a/cmd/commands/doctor_cli_test.go b/cmd/commands/doctor_cli_test.go index e226f924..944e4451 100644 --- a/cmd/commands/doctor_cli_test.go +++ b/cmd/commands/doctor_cli_test.go @@ -20,6 +20,7 @@ import ( "encoding/json" "os" "path/filepath" + "runtime" "strings" "testing" ) @@ -70,11 +71,21 @@ func TestDoctorOnAnEmptyHome(t *testing.T) { func TestDoctorNeedsAnActivatedShell(t *testing.T) { f := newCLIFixture(t, false) f.env["__VFOX_SHELL"] = "-" - r := f.run(t, "doctor").mustFail(t, "doctor in a shell that did not activate vfox") - mustContain(t, "doctor", r.output(), "error", "path.not-activated", "vfox activate") - report := parseDoctor(t, f.run(t, "doctor", "--json").mustFail(t, "doctor --json")) - if severity, ok := report.find("path.not-activated"); !ok || severity != "error" || report.OK { + // Without a hook only the global scope works on Windows, which is still + // something: there it is a warning, and it does not fail the check. + severity, passes := "error", false + if runtime.GOOS == "windows" { + severity, passes = "warn", true + } + r := f.run(t, "doctor") + if (r.code == 0) != passes { + t.Fatalf("doctor in a shell that did not activate vfox exited with %d, want success: %v\nstdout: %s\nstderr: %s", r.code, passes, r.stdout, r.stderr) + } + mustContain(t, "doctor", r.output(), severity, "path.not-activated", "vfox activate") + + report := parseDoctor(t, f.run(t, "doctor", "--json")) + if got, ok := report.find("path.not-activated"); !ok || got != severity || report.OK != passes { t.Errorf("report = %+v", report) } } @@ -215,8 +226,8 @@ func newShadowFixture(t *testing.T, dirName string) shadowFixture { f.installOnDisk(t, "alpha", "1.0.0", "alphatool") shadowDir := filepath.Join(f.root, dirName, "bin") must(t, os.MkdirAll(shadowDir, 0755)) - must(t, os.WriteFile(filepath.Join(shadowDir, "alphatool"), []byte("#!/bin/sh\n"), 0755)) - f.env["PATH"] = strings.Join([]string{shadowDir, filepath.Join(f.userHome, "sdks", "alpha", "bin"), f.system}, ":") + writeCommand(t, shadowDir, "alphatool") + f.env["PATH"] = pathList(shadowDir, filepath.Join(f.userHome, "sdks", "alpha", "bin"), f.system) return shadowFixture{cliFixture: f, shadowDir: shadowDir} } @@ -227,7 +238,7 @@ func TestUseSaysWhenACommandIsShadowed(t *testing.T) { out := r.output() mustContain(t, "use", out, "Now using", "alpha@1.0.0", - "`alphatool` runs "+filepath.Join(f.shadowDir, "alphatool")+" instead of alpha@1.0.0", + "`alphatool` runs "+filepath.Join(f.shadowDir, commandFile("alphatool"))+" instead of alpha@1.0.0", "comes before vfox in PATH", "pnpm put its own alphatool first. See https://example.com/pnpm", "path.mode aggressive") @@ -248,7 +259,7 @@ func TestDoctorChecksTheVersionEnvFallsBackTo(t *testing.T) { must(t, os.WriteFile(project, []byte("[tools]\nalpha = \"2.0.0\"\n"), 0644)) // not installed // What the shell uses is the global version. - mustContain(t, "env", f.run(t, "env", "-s", "bash").mustSucceed(t, "env").stdout, vfoxBin) + mustContain(t, "env", f.run(t, "env", "-s", "bash").mustSucceed(t, "env").stdout, shellPath(vfoxBin)) out := f.run(t, "doctor", "alpha").mustSucceed(t, "doctor alpha").stdout mustContain(t, "doctor alpha", out, "warn path.shadowed alpha@1.0.0", "pnpm put its own alphatool first.") @@ -282,8 +293,8 @@ func TestDoctorFollowsALegacyVersionFileLikeEnv(t *testing.T) { must(t, os.WriteFile(filepath.Join(f.work, ".legacy-version"), []byte("1.0.0\n"), 0644)) shadowDir := filepath.Join(f.root, "pnpm", "bin") must(t, os.MkdirAll(shadowDir, 0755)) - must(t, os.WriteFile(filepath.Join(shadowDir, "legacytool"), []byte("#!/bin/sh\n"), 0755)) - f.env["PATH"] = strings.Join([]string{shadowDir, filepath.Join(f.userHome, "sdks", "legacy", "bin"), f.system}, ":") + writeCommand(t, shadowDir, "legacytool") + f.env["PATH"] = pathList(shadowDir, filepath.Join(f.userHome, "sdks", "legacy", "bin"), f.system) out := f.run(t, "doctor", "legacy").mustSucceed(t, "doctor legacy").stdout mustContain(t, "doctor legacy", out, "warn path.shadowed legacy@1.0.0") @@ -301,9 +312,9 @@ func TestDoctorDoesNotCallALinkToTheSDKsOwnCommandAShadow(t *testing.T) { f.run(t, "link", "alpha@sys", external).mustSucceed(t, "link") front := filepath.Join(f.root, "homebrew", "bin") must(t, os.MkdirAll(front, 0755)) - command := filepath.Join(front, "alphatool") - must(t, os.Symlink(filepath.Join(external, "bin", "alphatool"), command)) - f.env["PATH"] = strings.Join([]string{front, filepath.Join(f.userHome, "sdks", "alpha", "bin"), f.system}, ":") + command := filepath.Join(front, commandFile("alphatool")) + linkFile(t, filepath.Join(external, "bin", commandFile("alphatool")), command) + f.env["PATH"] = pathList(front, filepath.Join(f.userHome, "sdks", "alpha", "bin"), f.system) out := f.run(t, "use", "-g", "alpha@sys").mustSucceed(t, "use").output() mustContain(t, "use", out, "Now using", "alpha@sys") @@ -312,7 +323,7 @@ func TestDoctorDoesNotCallALinkToTheSDKsOwnCommandAShadow(t *testing.T) { // Another file of that name in the same place is a shadow. must(t, os.Remove(command)) - must(t, os.WriteFile(command, []byte("#!/bin/sh\n"), 0755)) + writeCommand(t, front, "alphatool") out = f.run(t, "use", "-g", "alpha@sys").mustSucceed(t, "use").output() mustContain(t, "use", out, "`alphatool` runs "+command+" instead of alpha@sys") mustContain(t, "doctor", f.run(t, "doctor", "alpha").mustSucceed(t, "doctor").stdout, "warn path.shadowed alpha@sys") @@ -321,7 +332,7 @@ func TestDoctorDoesNotCallALinkToTheSDKsOwnCommandAShadow(t *testing.T) { func TestUseStaysQuietWhenNothingIsShadowed(t *testing.T) { f := newCLIFixture(t, false) f.installOnDisk(t, "alpha", "1.0.0", "alphatool") - f.env["PATH"] = strings.Join([]string{filepath.Join(f.userHome, "sdks", "alpha", "bin"), f.system}, ":") + f.env["PATH"] = pathList(filepath.Join(f.userHome, "sdks", "alpha", "bin"), f.system) out := f.run(t, "use", "-g", "alpha@1.0.0").mustSucceed(t, "use").output() mustContain(t, "use", out, "Now using") mustNotContain(t, "use", out, "comes before vfox", "WARNING") @@ -362,7 +373,7 @@ func TestUseUnderTheBaselineMode(t *testing.T) { // such directories behind vfox's: nothing shadows vfox any more. That mode is // the default, so it makes no difference whether the file says so. f := newShadowFixture(t, "system-path-helper") - f.env["__VFOX_ORIG_PATH"] = strings.Join([]string{f.shadowDir, f.system}, ":") + f.env["__VFOX_ORIG_PATH"] = pathList(f.shadowDir, f.system) for _, content := range []string{"", "path:\n mode: baseline\n"} { f.writeUserConfig(t, content) out := f.run(t, "use", "-g", "alpha@1.0.0").mustSucceed(t, "use").output() diff --git a/cmd/commands/info_cli_test.go b/cmd/commands/info_cli_test.go index cb48ddf8..e0faa6a5 100644 --- a/cmd/commands/info_cli_test.go +++ b/cmd/commands/info_cli_test.go @@ -119,7 +119,7 @@ func TestAHandMadeLinkIsFoundByEveryCommand(t *testing.T) { pkg := filepath.Join(f.shared, "cache", "alpha", "v-ext") home := filepath.Join(pkg, "alpha-ext") must(t, os.MkdirAll(pkg, 0755)) - must(t, os.Symlink(external, home)) + linkDirectory(t, external, home) mustContain(t, "list", f.run(t, "list", "alpha").mustSucceed(t, "list").output(), "ext") if out := strings.TrimSpace(f.run(t, "info", "alpha@ext").mustSucceed(t, "info").stdout); out != pkg { @@ -132,7 +132,7 @@ func TestAHandMadeLinkIsFoundByEveryCommand(t *testing.T) { out := f.run(t, "use", "-g", "alpha@ext").mustSucceed(t, "use").output() mustContain(t, "use", out, "Now using", "alpha@ext") mustContain(t, "global config", readFile(t, filepath.Join(f.userHome, ".vfox.toml")), `alpha = "ext"`) - if !exists(filepath.Join(f.userHome, "sdks", "alpha", "bin", "alphatool")) { + if !exists(filepath.Join(f.userHome, "sdks", "alpha", "bin", commandFile("alphatool"))) { t.Error("the global link does not reach the linked SDK") } } diff --git a/cmd/commands/install_cli_test.go b/cmd/commands/install_cli_test.go index 3198ac59..1ac066d1 100644 --- a/cmd/commands/install_cli_test.go +++ b/cmd/commands/install_cli_test.go @@ -18,6 +18,7 @@ package commands import ( "path/filepath" + "runtime" "testing" ) @@ -54,6 +55,11 @@ func TestInstallCommandUseFollowsTheInstalledVersion(t *testing.T) { } func TestInstallCommandUseOnShellWithoutHookSaysWhatFailed(t *testing.T) { + if runtime.GOOS == "windows" { + // There, a shell without a hook still gets the global scope and a new + // shell, which vfox opens for the user and which would wait for input. + t.Skip("use succeeds on Windows without a hook") + } f := newCLIFixture(t, false) // What a container build step gives vfox: no activated shell, hence no hook. f.env["__VFOX_SHELL"] = "-" diff --git a/cmd/commands/link_cli_test.go b/cmd/commands/link_cli_test.go index 34639526..aa8b92f0 100644 --- a/cmd/commands/link_cli_test.go +++ b/cmd/commands/link_cli_test.go @@ -21,6 +21,8 @@ import ( "path/filepath" "strings" "testing" + + "github.com/version-fox/vfox/internal/env" ) // The scenario of #706 and #669: a JDK that is already on the machine. @@ -80,7 +82,7 @@ func TestLinkCommandEndToEnd(t *testing.T) { if content, err := os.ReadFile(data); err != nil || string(content) != "precious" { t.Errorf("the linked SDK's file: %q, %v", content, err) } - if !exists(filepath.Join(external, "bin", "alphatool")) { + if !exists(filepath.Join(external, "bin", commandFile("alphatool"))) { t.Error("the linked SDK lost a command") } if exists(pkg) { @@ -136,7 +138,7 @@ func TestLinkCommandForce(t *testing.T) { f.run(t, "link", "--force", "alpha@sys", second).mustSucceed(t, "link --force") out := f.run(t, "list", "alpha").mustSucceed(t, "list").output() mustContain(t, "list", out, "(linked → "+second+")") - if !exists(filepath.Join(first, "bin", "alphatool")) { + if !exists(filepath.Join(first, "bin", commandFile("alphatool"))) { t.Error("the old target must stay as it was") } @@ -200,12 +202,12 @@ func TestLinkedVersionCanBeSelected(t *testing.T) { // The shell gets the linked SDK's commands through the global link. link := filepath.Join(f.userHome, "sdks", "alpha") - if !exists(filepath.Join(link, "bin", "alphatool")) { + if !exists(filepath.Join(link, "bin", commandFile("alphatool"))) { t.Errorf("%s does not reach the linked SDK", link) } - info, err := os.Lstat(link) - if err != nil || info.Mode()&os.ModeSymlink == 0 { - t.Errorf("global link: %v, %v", info, err) + // A symlink, or a junction on Windows. + if !env.IsDirSymlink(link) { + t.Errorf("%s is not a link", link) } // And `list` says it is the one in use. diff --git a/cmd/commands/nushell_cli_test.go b/cmd/commands/nushell_cli_test.go new file mode 100644 index 00000000..f7a94a85 --- /dev/null +++ b/cmd/commands/nushell_cli_test.go @@ -0,0 +1,193 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package commands + +import ( + "context" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" + "time" +) + +// nushellOrSkip finds Nushell for the tests that start a real session. CI +// installs it and sets VFOX_TEST_NUSHELL=1, so that an installation that went +// wrong fails the job instead of skipping the tests. +func nushellOrSkip(t *testing.T) string { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("the Nushell session is exercised on Unix only") + } + nu, err := exec.LookPath("nu") + if err != nil { + if os.Getenv("VFOX_TEST_NUSHELL") == "1" { + t.Fatalf("VFOX_TEST_NUSHELL=1 asks for Nushell, but nu is not on PATH: %v", err) + } + t.Skip("nu is not installed; install Nushell to run the native Nushell tests") + } + return nu +} + +// buildVfox builds the vfox command of this module. The vfox.nu that vfox +// generates runs the very file that generated it, with arguments the test binary +// does not take, so the tests cannot stand in for it the way TestCLIProcess does. +func buildVfox(t *testing.T) string { + t.Helper() + goTool, err := exec.LookPath("go") + if err != nil { + t.Fatalf("the go command is needed to build vfox for this test: %v", err) + } + bin := filepath.Join(t.TempDir(), "vfox") + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, goTool, "build", "-buildvcs=false", "-o", bin, ".") + cmd.Dir = filepath.Join("..", "..") + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("go build: %v\n%s", err, out) + } + return bin +} + +// nushellState is what nushellProbe prints about a session. +type nushellState struct { + Stage string + Path []string + Orig string + Shell string +} + +// nushellProbe runs in a Nushell that has loaded the configuration `vfox +// activate` asked for. It reports the session as it starts, puts a directory in +// front of PATH the way `pnpm setup` or a virtualenv does after the start, runs +// the prompt hooks the way the REPL does before it shows the next prompt, and +// reports again. `do --env` keeps what a hook changes in this session. The +// format verb stands for the directory that goes in front. +const nushellProbe = ` +def state [stage: string] { + {stage: $stage, path: $env.PATH, orig: ($env.__VFOX_ORIG_PATH? | default ""), shell: ($env.__VFOX_SHELL? | default "")} | to json --raw +} +print (state "started") +$env.PATH = ($env.PATH | prepend '%s') +for hook in $env.config.hooks.pre_prompt { do --env $hook } +print (state "prompt") +` + +// The generated vfox.nu records the PATH its session starts with in +// __VFOX_ORIG_PATH, because Nushell cannot evaluate what `vfox activate` prints +// and so never receives the line the other shells get. Whether `vfox env` sees +// that baseline cannot be told from the text of the script: it shows in the +// order of PATH that Nushell ends up with. +func TestNushellSessionUsesTheBaselineItRecorded(t *testing.T) { + nu := nushellOrSkip(t) + vfox := buildVfox(t) + + f := newCLIFixture(t, false) + f.installOnDisk(t, "alpha", "1.0.0", "alphatool") + must(t, os.WriteFile(filepath.Join(f.userHome, ".vfox.toml"), []byte("[tools]\nalpha = \"1.0.0\"\n"), 0644)) + inherited := filepath.Join(f.root, "usr-local", "bin") // what the machine put in front of vfox's directory + added := filepath.Join(f.root, "pnpm", "bin") // what a tool puts there once the shell runs + vfoxBin := filepath.Join(f.userHome, "sdks", "alpha", "bin") + for _, dir := range []string{inherited, added} { + must(t, os.MkdirAll(dir, 0755)) + } + if strings.Contains(added, "'") { + t.Fatalf("%s cannot go into a single-quoted Nushell string", added) + } + + // Nothing of vfox from a shell that is already running, and a Nushell that + // keeps its files below the fixture. + f.env["__VFOX_SHELL"] = "-" + f.env["__VFOX_CURTMPPATH"] = "-" + f.env["XDG_CONFIG_HOME"] = filepath.Join(f.root, "config") + run := func(t *testing.T, name string, args ...string) cliResult { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + return runCommand(t, f.command(ctx, name, args...)) + } + + // Where this Nushell keeps its configuration, whatever the platform calls it. + configDir := strings.TrimSpace(run(t, nu, "--no-config-file", "--commands", "print $nu.default-config-dir").mustSucceed(t, "nu").stdout) + if !strings.HasPrefix(configDir, f.root) { + t.Fatalf("Nushell's configuration directory %q is outside the fixture %q: the test would write into a real home", configDir, f.root) + } + must(t, os.MkdirAll(configDir, 0755)) + + // The documented setup: vfox activate nushell $nu.default-config-dir | save --append $nu.config-path + activated := run(t, vfox, "activate", "nushell", configDir).mustSucceed(t, "vfox activate nushell") + configNu := filepath.Join(configDir, "config.nu") + must(t, os.WriteFile(configNu, []byte(activated.stdout), 0644)) + if !exists(filepath.Join(configDir, "vfox.nu")) { + t.Fatalf("vfox activate nushell wrote no vfox.nu to %s", configDir) + } + + // A new terminal. The machine's directories come first and vfox's own comes + // later, where Windows puts the user PATH and macOS path_helper the rest. + f.env["PATH"] = pathList(inherited, vfoxBin, f.system) + start := func(t *testing.T) (started, prompt nushellState) { + t.Helper() + // --config: Nushell loads no configuration for --commands otherwise. + r := run(t, nu, "--config", configNu, "--commands", fmt.Sprintf(nushellProbe, added)).mustSucceed(t, "nu") + var states []nushellState + for _, line := range strings.Split(r.stdout, "\n") { + if !strings.HasPrefix(line, "{") { + continue + } + var state nushellState + if err := json.Unmarshal([]byte(line), &state); err != nil { + t.Fatalf("nu printed %q: %v\nstdout: %s\nstderr: %s", line, err, r.stdout, r.stderr) + } + states = append(states, state) + } + if len(states) != 2 || states[0].Stage != "started" || states[1].Stage != "prompt" { + t.Fatalf("nu reported %+v, want the states \"started\" and \"prompt\"\nstdout: %s\nstderr: %s", states, r.stdout, r.stderr) + } + return states[0], states[1] + } + check := func(t *testing.T, what string, got nushellState, want ...string) { + t.Helper() + if strings.Join(got.Path, "\n") != strings.Join(want, "\n") { + t.Errorf("%s: PATH = %v, want %v", what, got.Path, want) + } + } + + t.Run("the default mode moves what the session started with behind vfox", func(t *testing.T) { + started, prompt := start(t) + if started.Shell != "nushell" { + t.Errorf("__VFOX_SHELL = %q", started.Shell) + } + // Recorded as the shell found it, vfox's own directory included. + if want := pathList(inherited, vfoxBin, f.system); started.Orig != want { + t.Errorf("__VFOX_ORIG_PATH = %q, want %q", started.Orig, want) + } + check(t, "when the session started", started, vfoxBin, inherited, f.system) + // What came after the start is not part of the baseline, so it stays in front. + check(t, "after a directory was put in front and the prompt hook ran", prompt, added, vfoxBin, inherited, f.system) + }) + + t.Run("the legacy mode keeps everything in front of vfox in front", func(t *testing.T) { + f.writeUserConfig(t, "path:\n mode: legacy\n") + started, prompt := start(t) + check(t, "when the session started", started, inherited, vfoxBin, f.system) + check(t, "after a directory was put in front and the prompt hook ran", prompt, added, inherited, vfoxBin, f.system) + }) +} diff --git a/cmd/commands/path_cli_test.go b/cmd/commands/path_cli_test.go index ec4f653e..0efb34ff 100644 --- a/cmd/commands/path_cli_test.go +++ b/cmd/commands/path_cli_test.go @@ -21,6 +21,7 @@ import ( "os" "path/filepath" "regexp" + "runtime" "strings" "testing" ) @@ -29,6 +30,8 @@ var ( exportedPath = regexp.MustCompile(`export PATH="([^"]*)"`) // bash quotes a value that holds ':' as $'...' exportedOrig = regexp.MustCompile(`export __VFOX_ORIG_PATH=(?:\$'([^']*)'|([^;']*));`) + // PowerShell is told $env:PATH='...' + exportedPwshPath = regexp.MustCompile(`\$env:PATH='([^']*)'`) ) // exportedBaseline returns the value the script exports as __VFOX_ORIG_PATH. @@ -68,7 +71,7 @@ func newPathFixture(t *testing.T) pathFixture { inherited: filepath.Join(f.root, "usr-local", "bin"), vfoxBin: filepath.Join(f.userHome, "sdks", "alpha", "bin"), } - f.env["PATH"] = strings.Join([]string{p.inherited, p.vfoxBin, f.system}, ":") + f.env["PATH"] = pathList(p.inherited, p.vfoxBin, f.system) return p } @@ -83,9 +86,9 @@ func indexOf(entries []string, want string) int { func TestEnvPathModeDecidesWhatStaysInFront(t *testing.T) { f := newPathFixture(t) - f.env["__VFOX_ORIG_PATH"] = strings.Join([]string{f.inherited, f.system}, ":") - legacyOrder := []string{f.inherited, f.vfoxBin, f.system} // vfox 1.0.x: everything in front of vfox's directory stays there - baselineOrder := []string{f.vfoxBin, f.inherited, f.system} + f.env["__VFOX_ORIG_PATH"] = pathList(f.inherited, f.system) + legacyOrder := shellPaths(f.inherited, f.vfoxBin, f.system) // vfox 1.0.x: everything in front of vfox's directory stays there + baselineOrder := shellPaths(f.vfoxBin, f.inherited, f.system) check := func(what string, want []string) { t.Helper() got := pathOf(t, f.run(t, "env", "-s", "bash").mustSucceed(t, "env")) @@ -116,11 +119,61 @@ func TestEnvPathModeDecidesWhatStaysInFront(t *testing.T) { // `path.preserve` is read from config.yaml, which the cache does not watch by // modification time, and the mode can stay the same while the directories to // preserve change. The next prompt must still follow the setting. +// PowerShell gets the PATH the way the operating system spells it, where bash +// gets a POSIX list: `;` between C:\a\b on Windows, `:` elsewhere. The order is +// the same one. +func TestEnvWritesThePathTheWayPowerShellSpellsIt(t *testing.T) { + f := newPathFixture(t) + f.env["__VFOX_SHELL"] = "pwsh" // vfox spells the PATH after the hook it runs in + f.env["__VFOX_ORIG_PATH"] = pathList(f.inherited, f.system) + check := func(what string, want ...string) { + t.Helper() + r := f.run(t, "env", "-s", "pwsh").mustSucceed(t, "env") + match := exportedPwshPath.FindStringSubmatch(r.stdout) + if match == nil { + t.Fatalf("%s: no PATH export in:\n%s\nstderr: %s", what, r.stdout, r.stderr) + } + if got := strings.Split(match[1], string(os.PathListSeparator)); strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("%s: PATH = %v, want %v", what, got, want) + } + } + + check("the default", f.vfoxBin, f.inherited, f.system) + f.writeUserConfig(t, "path:\n mode: legacy\n") + check("legacy", f.inherited, f.vfoxBin, f.system) +} + +// Git Bash and MSYS2 keep the lists of their shell in POSIX form (/c/a:/c/b) and +// hand a native program that or, converted, the Windows form (C:\a;C:\b). The +// baseline that `vfox activate` recorded has to be understood in both: this is +// the machine PATH of #732. +func TestEnvReadsTheBaselineInTheFormGitBashHoldsIt(t *testing.T) { + if runtime.GOOS != "windows" { + t.Skip("only Windows has two spellings of a path list") + } + for _, tt := range []struct { + name string + orig func(inherited, system string) string + }{ + {"the Windows form", func(inherited, system string) string { return pathList(inherited, system) }}, + {"the POSIX form", func(inherited, system string) string { return strings.Join(shellPaths(inherited, system), ":") }}, + } { + t.Run(tt.name, func(t *testing.T) { + f := newPathFixture(t) // a fixture of its own: the output of a prompt is cached + f.env["__VFOX_ORIG_PATH"] = tt.orig(f.inherited, f.system) + got := pathOf(t, f.run(t, "env", "-s", "bash").mustSucceed(t, "env")) + if want := shellPaths(f.vfoxBin, f.inherited, f.system); strings.Join(got, ":") != strings.Join(want, ":") { + t.Errorf("PATH = %v, want %v: the inherited directory belongs behind vfox's", got, want) + } + }) + } +} + func TestEnvFollowsPathPreserveAtTheNextPrompt(t *testing.T) { f := newPathFixture(t) - f.env["__VFOX_ORIG_PATH"] = strings.Join([]string{f.inherited, f.system}, ":") - inFront := []string{f.inherited, f.vfoxBin, f.system} - behind := []string{f.vfoxBin, f.inherited, f.system} + f.env["__VFOX_ORIG_PATH"] = pathList(f.inherited, f.system) + inFront := shellPaths(f.inherited, f.vfoxBin, f.system) + behind := shellPaths(f.vfoxBin, f.inherited, f.system) check := func(what string, want []string) { t.Helper() got := pathOf(t, f.run(t, "env", "-s", "bash").mustSucceed(t, "env")) @@ -144,17 +197,17 @@ func TestEnvFollowsPathPreserveAtTheNextPrompt(t *testing.T) { // without the PATH changing. func TestEnvFollowsAnEnvironmentVariableOfPathPreserve(t *testing.T) { f := newPathFixture(t) - f.env["__VFOX_ORIG_PATH"] = strings.Join([]string{f.inherited, f.system}, ":") + f.env["__VFOX_ORIG_PATH"] = pathList(f.inherited, f.system) f.writeUserConfig(t, "path:\n mode: baseline\n preserve:\n - $PNPM_HOME\n") f.env["PNPM_HOME"] = f.inherited got := pathOf(t, f.run(t, "env", "-s", "bash").mustSucceed(t, "env")) - if got[0] != f.inherited { + if got[0] != shellPath(f.inherited) { t.Fatalf("PNPM_HOME is preserved, so it stays in front: PATH = %v", got) } delete(f.env, "PNPM_HOME") got = pathOf(t, f.run(t, "env", "-s", "bash").mustSucceed(t, "env")) - if got[0] != f.vfoxBin { + if got[0] != shellPath(f.vfoxBin) { t.Errorf("PNPM_HOME is gone, so nothing is preserved: PATH = %v, want vfox first (a cached answer was served?)", got) } } @@ -162,12 +215,12 @@ func TestEnvFollowsAnEnvironmentVariableOfPathPreserve(t *testing.T) { func TestEnvKeepsWhatWasAddedAfterActivation(t *testing.T) { f := newPathFixture(t) pnpm := filepath.Join(f.root, "pnpm", "bin") - f.env["PATH"] = strings.Join([]string{pnpm, f.inherited, f.vfoxBin, f.system}, ":") - f.env["__VFOX_ORIG_PATH"] = strings.Join([]string{f.inherited, f.system}, ":") + f.env["PATH"] = pathList(pnpm, f.inherited, f.vfoxBin, f.system) + f.env["__VFOX_ORIG_PATH"] = pathList(f.inherited, f.system) f.writeUserConfig(t, "path:\n mode: baseline\n") got := pathOf(t, f.run(t, "env", "-s", "bash").mustSucceed(t, "env")) - if want := []string{pnpm, f.vfoxBin, f.inherited, f.system}; strings.Join(got, ":") != strings.Join(want, ":") { + if want := shellPaths(pnpm, f.vfoxBin, f.inherited, f.system); strings.Join(got, ":") != strings.Join(want, ":") { t.Errorf("PATH = %v, want %v: pnpm was added after activation and stays in front, the inherited directory does not", got, want) } } @@ -176,13 +229,13 @@ func TestEnvKeepsAnActiveVirtualenvInFrontInEveryMode(t *testing.T) { f := newPathFixture(t) venv := filepath.Join(f.root, "venv") f.env["VIRTUAL_ENV"] = venv - f.env["PATH"] = strings.Join([]string{filepath.Join(venv, "bin"), f.inherited, f.vfoxBin, f.system}, ":") - f.env["__VFOX_ORIG_PATH"] = strings.Join([]string{filepath.Join(venv, "bin"), f.inherited, f.system}, ":") + f.env["PATH"] = pathList(filepath.Join(venv, "bin"), f.inherited, f.vfoxBin, f.system) + f.env["__VFOX_ORIG_PATH"] = pathList(filepath.Join(venv, "bin"), f.inherited, f.system) for _, mode := range []string{"legacy", "baseline", "aggressive"} { f.writeUserConfig(t, "path:\n mode: "+mode+"\n") got := pathOf(t, f.run(t, "env", "-s", "bash").mustSucceed(t, "env")) - if got[0] != filepath.Join(venv, "bin") { + if got[0] != shellPath(filepath.Join(venv, "bin")) { t.Errorf("%s: PATH = %v, the active virtualenv must stay first", mode, got) } } @@ -191,11 +244,11 @@ func TestEnvKeepsAnActiveVirtualenvInFrontInEveryMode(t *testing.T) { func TestEnvAggressiveModeAndPreserve(t *testing.T) { f := newPathFixture(t) cargo := filepath.Join(f.root, "cargo", "bin") - f.env["PATH"] = strings.Join([]string{cargo, f.inherited, f.vfoxBin, f.system}, ":") + f.env["PATH"] = pathList(cargo, f.inherited, f.vfoxBin, f.system) f.writeUserConfig(t, fmt.Sprintf("path:\n mode: aggressive\n preserve:\n - %s\n", cargo)) got := pathOf(t, f.run(t, "env", "-s", "bash").mustSucceed(t, "env")) - if want := []string{cargo, f.vfoxBin, f.inherited, f.system}; strings.Join(got, ":") != strings.Join(want, ":") { + if want := shellPaths(cargo, f.vfoxBin, f.inherited, f.system); strings.Join(got, ":") != strings.Join(want, ":") { t.Errorf("PATH = %v, want %v", got, want) } } @@ -207,8 +260,8 @@ func TestEnvAggressiveModeAndPreserve(t *testing.T) { // it demotes the same entries with or without one. func TestEnvWithoutABaselineOnlyBaselineModeFallsBackToLegacy(t *testing.T) { f := newPathFixture(t) - legacyOrder := []string{f.inherited, f.vfoxBin, f.system} - demotedOrder := []string{f.vfoxBin, f.inherited, f.system} + legacyOrder := shellPaths(f.inherited, f.vfoxBin, f.system) + demotedOrder := shellPaths(f.vfoxBin, f.inherited, f.system) for _, tt := range []struct { name, config string want []string @@ -228,13 +281,14 @@ func TestEnvWithoutABaselineOnlyBaselineModeFallsBackToLegacy(t *testing.T) { func TestActivateRecordsTheBaselineOncePerSession(t *testing.T) { f := newPathFixture(t) - f.env["PATH"] = strings.Join([]string{f.inherited, f.system}, ":") // nothing of vfox's yet + f.env["PATH"] = pathList(f.inherited, f.system) // nothing of vfox's yet delete(f.env, "__VFOX_SHELL") + baseline := strings.Join(shellPaths(f.inherited, f.system), ":") // as the bash hook holds it // A fresh shell: the PATH it found is recorded. r := f.run(t, "activate", "bash").mustSucceed(t, "activate") - if got, ok := exportedBaseline(r.stdout); !ok || got != f.inherited+":"+f.system { - t.Fatalf("baseline export = %q (%v), want %s:%s\n%s", got, ok, f.inherited, f.system, r.stdout) + if got, ok := exportedBaseline(r.stdout); !ok || got != baseline { + t.Fatalf("baseline export = %q (%v), want %s\n%s", got, ok, baseline, r.stdout) } // The same session running activate again (a re-sourced rc file) keeps the @@ -247,7 +301,7 @@ func TestActivateRecordsTheBaselineOncePerSession(t *testing.T) { // A shell started from another shell inherited the variable, not the session. f.env["__VFOX_PID"] = "1" r = f.run(t, "activate", "bash").mustSucceed(t, "activate") - if got, ok := exportedBaseline(r.stdout); !ok || got != f.inherited+":"+f.system { + if got, ok := exportedBaseline(r.stdout); !ok || got != baseline { t.Fatalf("an inherited session must record its own baseline, got %q (%v)\n%s", got, ok, r.stdout) } } @@ -256,7 +310,7 @@ func TestActivateBaselineLeavesOutVfoxDirectories(t *testing.T) { f := newPathFixture(t) // PATH: inherited, vfox, system delete(f.env, "__VFOX_SHELL") r := f.run(t, "activate", "bash").mustSucceed(t, "activate") - if got, ok := exportedBaseline(r.stdout); !ok || got != f.inherited+":"+f.system { + if got, ok := exportedBaseline(r.stdout); !ok || got != strings.Join(shellPaths(f.inherited, f.system), ":") { t.Fatalf("baseline = %q (%v): vfox's own directory is not part of what the shell brought", got, ok) } } @@ -274,7 +328,7 @@ func TestActivateAppliesThePathMode(t *testing.T) { } { f.writeUserConfig(t, tt.config) got := pathOf(t, f.run(t, "activate", "bash").mustSucceed(t, "activate")) - if got[0] != f.vfoxBin || indexOf(got, f.inherited) < 1 { + if got[0] != shellPath(f.vfoxBin) || indexOf(got, shellPath(f.inherited)) < 1 { t.Errorf("%s: PATH = %v, want vfox's directory first and the inherited one behind it", tt.name, got) } } @@ -282,7 +336,7 @@ func TestActivateAppliesThePathMode(t *testing.T) { // What vfox 1.0.x did has to be asked for. f.writeUserConfig(t, "path:\n mode: legacy\n") legacy := pathOf(t, f.run(t, "activate", "bash").mustSucceed(t, "activate")) - if legacy[0] != f.inherited { + if legacy[0] != shellPath(f.inherited) { t.Errorf("legacy: PATH = %v, want the inherited directory first as before", legacy) } } @@ -322,9 +376,9 @@ func TestConfigCommandHandlesTheNewSettings(t *testing.T) { // What was set is what the other commands see. f.installOnDisk(t, "alpha", "1.0.0", "alphatool") - f.env["PATH"] = strings.Join([]string{filepath.Join(f.root, "pnpm", "bin"), filepath.Join(f.userHome, "sdks", "alpha", "bin"), f.system}, ":") + f.env["PATH"] = pathList(filepath.Join(f.root, "pnpm", "bin"), filepath.Join(f.userHome, "sdks", "alpha", "bin"), f.system) must(t, os.MkdirAll(filepath.Join(f.root, "pnpm", "bin"), 0755)) - must(t, os.WriteFile(filepath.Join(f.root, "pnpm", "bin", "alphatool"), []byte("#!/bin/sh\n"), 0755)) + writeCommand(t, filepath.Join(f.root, "pnpm", "bin"), "alphatool") mustNotContain(t, "use with diagnostics.onUse false", f.run(t, "use", "-g", "alpha@1.0.0").mustSucceed(t, "use").output(), "comes before vfox") f.run(t, "config", "--unset", "diagnostics.onUse").mustSucceed(t, "config --unset diagnostics.onUse") diff --git a/cmd/commands/version_name_cli_test.go b/cmd/commands/version_name_cli_test.go index 798d820e..ce419a19 100644 --- a/cmd/commands/version_name_cli_test.go +++ b/cmd/commands/version_name_cli_test.go @@ -186,7 +186,7 @@ func TestUninstallTakesTheNameAsTypedBeforeDroppingAV(t *testing.T) { if !exists(one) || (tt.removed != "2.0.0" && !exists(two)) { t.Error("another installation was removed") } - if external != "" && !exists(filepath.Join(external, "bin", "alphatool")) { + if external != "" && !exists(filepath.Join(external, "bin", commandFile("alphatool"))) { t.Error("the linked external target was removed") } })