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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ go test ./... -coverprofile=coverage.out -covermode=atomic
- Format changed Go files with `gofmt -w <files>`. 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 <module>@<version>` 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

Expand Down Expand Up @@ -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 `<link dir>/<name>` 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 `<link dir>/<name>` 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.

Expand Down
142 changes: 124 additions & 18 deletions cmd/commands/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -173,18 +186,23 @@ 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
}

// 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
}
Expand Down Expand Up @@ -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"
Expand All @@ -238,48 +259,65 @@ 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 <args>` 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()
}
result.stdout, result.stderr = stdout.String(), stderr.String()
return result
}

// runProcess executes `vfox <args>` 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 {
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading