diff --git a/README.md b/README.md
index 95b19e3b..4b37de92 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,7 @@ echo 'Invoke-Expression "$(vfox activate pwsh)"' >> $PROFILE
# 3. copy internal/shell/clink_vfox.lua to script path
# For Nushell:
-vfox activate nushell $nu.default-config-dir | save --append $nu.config-path
+vfox activate nu $nu.default-config-dir | save --append $nu.config-path
```
> Remember to restart your shell to apply the changes.
diff --git a/README_CN.md b/README_CN.md
index ea182e22..fdc49495 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -52,7 +52,7 @@ if (-not (Test-Path -Path $PROFILE)) { New-Item -Type File -Path $PROFILE -Force
# 3. 复制 internal/shell/clink_vfox.lua 到脚本路径
# 对于 Nushell:
-vfox activate nushell $nu.default-config-dir | save --append $nu.config-path
+vfox activate nu $nu.default-config-dir | save --append $nu.config-path
```
> 请记住重启你的 Shell 以应用更改。
diff --git a/cmd/commands/activate_test.go b/cmd/commands/activate_test.go
index 18b31bf4..b6efa9ed 100644
--- a/cmd/commands/activate_test.go
+++ b/cmd/commands/activate_test.go
@@ -65,3 +65,52 @@ func TestRenderActivateScriptPassesNushellConfigPath(t *testing.T) {
t.Fatalf("generated vfox.nu does not reference self path:\n%s", string(content))
}
}
+
+func TestRenderActivateScriptPassesNuConfigPath(t *testing.T) {
+ configDir := t.TempDir()
+
+ got, err := renderActivateScript("nu", "/usr/bin/vfox", []string{configDir}, env.Vars{}, false)
+ if err != nil {
+ t.Fatalf("renderActivateScript() failed: %v", err)
+ }
+
+ if !strings.Contains(got, `source ($nu.default-config-dir | path join "vfox.nu")`) {
+ t.Fatalf("renderActivateScript() returned unexpected Nushell source script:\n%s", got)
+ }
+
+ vfoxNu := filepath.Join(configDir, "vfox.nu")
+ content, err := os.ReadFile(vfoxNu)
+ if err != nil {
+ t.Fatalf("expected generated %s: %v", vfoxNu, err)
+ }
+ if !strings.Contains(string(content), "^'/usr/bin/vfox' activate nushell $nu.default-config-dir") {
+ t.Fatalf("generated vfox.nu does not reference self path:\n%s", string(content))
+ }
+}
+
+func TestRenderActivateScriptNushellDirectOutput(t *testing.T) {
+ for _, shellName := range []string{"nu", "nushell"} {
+ t.Run(shellName, func(t *testing.T) {
+ got, err := renderActivateScript(shellName, "/usr/bin/vfox", nil, env.Vars{}, false)
+ if err != nil {
+ t.Fatalf("renderActivateScript(%q) failed: %v", shellName, err)
+ }
+
+ if strings.Contains(got, "source ($nu.default-config-dir") {
+ t.Fatalf("direct activation script should not contain source line:\n%s", got)
+ }
+ if !strings.Contains(got, "export-env") {
+ t.Fatalf("direct activation script missing export-env:\n%s", got)
+ }
+ if !strings.Contains(got, "def --env updateVfoxEnvironment") {
+ t.Fatalf("direct activation script missing updateVfoxEnvironment:\n%s", got)
+ }
+ if !strings.Contains(got, "/usr/bin/vfox") {
+ t.Fatalf("direct activation script missing self path:\n%s", got)
+ }
+ if !strings.Contains(got, "$env.__VFOX_SHELL = 'nushell'") {
+ t.Fatalf("direct activation script missing __VFOX_SHELL:\n%s", got)
+ }
+ })
+ }
+}
diff --git a/docs/guides/quick-start.md b/docs/guides/quick-start.md
index 2fe834e1..14130b10 100644
--- a/docs/guides/quick-start.md
+++ b/docs/guides/quick-start.md
@@ -195,10 +195,33 @@ Type `Y` and press Enter to confirm.
+> Requires Nushell 0.106.0+.
+
+Add the hook to your Nushell configuration:
+
```shell
-vfox activate nushell $nu.default-config-dir | save --append $nu.config-path
+vfox activate nu $nu.default-config-dir | save --append $nu.config-path
```
+Alternatively, you can directly generate and append the activation script without specifying a config directory:
+
+```shell
+vfox activate nu | save --append $nu.config-path
+```
+
+Or save the activation script to Nushell's vendor autoload directory:
+
+```shell
+mkdir ($nu.data-dir | path join "vendor/autoload")
+vfox activate nu | save -f ($nu.data-dir | path join "vendor/autoload/vfox.nu")
+```
+
+::: tip 💡 Tip
+The direct (`vfox activate nu | save --append ...`) and vendor autoload setups save a static snapshot of the activation script. Unlike the config-directory form, they do not automatically update when vfox is upgraded. When upgrading vfox:
+- For vendor autoload configurations, re-running the command safely overwrites the file in place (`save -f`).
+- For direct `$nu.config-path` configurations, remove the previous vfox hook block from `$nu.config-path` before re-appending to avoid duplicate hooks.
+:::
+
diff --git a/docs/guides/uninstallation.md b/docs/guides/uninstallation.md
index fab58d1c..23934bb9 100644
--- a/docs/guides/uninstallation.md
+++ b/docs/guides/uninstallation.md
@@ -97,7 +97,17 @@ After saving the file, reload your PowerShell profile:
::: details Nushell
-Open your Nushell config file (location shown by `$nu.config-path`) and remove the vfox activation line that was appended during installation.
+Depending on the configuration method used:
+
+- **Config directory setup**: Open your Nushell configuration file (shown by `$nu.config-path`) and remove the line sourcing `vfox.nu`. Then delete the generated `vfox.nu` file:
+ ```shell
+ rm ($nu.default-config-dir | path join "vfox.nu")
+ ```
+- **Direct configuration**: Open your Nushell configuration file (shown by `$nu.config-path`) and remove the appended `vfox` activation script block.
+- **Vendor autoload**: Delete the activation script from the vendor autoload directory:
+ ```shell
+ rm ($nu.data-dir | path join "vendor/autoload/vfox.nu")
+ ```
:::
diff --git a/docs/zh-hans/guides/quick-start.md b/docs/zh-hans/guides/quick-start.md
index 768623a3..d9020cf7 100644
--- a/docs/zh-hans/guides/quick-start.md
+++ b/docs/zh-hans/guides/quick-start.md
@@ -195,10 +195,33 @@ Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
+> 需要 Nushell 0.106.0+。
+
+将 Hook 添加到 Nushell 配置文件:
+
+```shell
+vfox activate nu $nu.default-config-dir | save --append $nu.config-path
+```
+
+或者直接生成激活脚本并追加到配置中(无需指定配置目录参数):
+
```shell
-vfox activate nushell $nu.default-config-dir | save --append $nu.config-path
+vfox activate nu | save --append $nu.config-path
```
+也可以将激活脚本保存到 Nushell 的 vendor autoload 目录:
+
+```shell
+mkdir ($nu.data-dir | path join "vendor/autoload")
+vfox activate nu | save -f ($nu.data-dir | path join "vendor/autoload/vfox.nu")
+```
+
+::: tip 💡 提示
+直接追加(`vfox activate nu | save --append ...`)以及 vendor autoload 方式生成的是激活脚本的静态快照。与配置目录方式不同,它们在升级 vfox 时不会自动更新。升级 vfox 时:
+- 对于 vendor autoload 配置,重新运行该命令即可安全覆盖原文件(`save -f`)。
+- 对于直接追加到 `$nu.config-path` 的配置,在重新追加前需先从 `$nu.config-path` 中移除原有的 vfox hook 代码块,以避免重复添加 hook。
+:::
+
diff --git a/docs/zh-hans/guides/uninstallation.md b/docs/zh-hans/guides/uninstallation.md
index 2ba0fc89..1d9abbc2 100644
--- a/docs/zh-hans/guides/uninstallation.md
+++ b/docs/zh-hans/guides/uninstallation.md
@@ -97,7 +97,17 @@ Invoke-Expression "$(vfox activate pwsh)"
::: details Nushell
-打开您的 Nushell 配置文件(位置由 `$nu.config-path` 显示)并删除安装期间添加的 vfox 激活行。
+根据您采用的配置方式:
+
+- **配置目录方式**:打开您的 Nushell 配置文件(位置由 `$nu.config-path` 显示)并删除引用 `vfox.nu` 的行。然后删除生成的 `vfox.nu` 文件:
+ ```shell
+ rm ($nu.default-config-dir | path join "vfox.nu")
+ ```
+- **直接写入配置方式**:打开您的 Nushell 配置文件(位置由 `$nu.config-path` 显示)并删除追加的 `vfox` 激活脚本代码块。
+- **Vendor autoload 方式**:删除 vendor autoload 目录下的激活脚本:
+ ```shell
+ rm ($nu.data-dir | path join "vendor/autoload/vfox.nu")
+ ```
:::
diff --git a/internal/shell/nushell.go b/internal/shell/nushell.go
index 2df63038..6950985f 100644
--- a/internal/shell/nushell.go
+++ b/internal/shell/nushell.go
@@ -16,12 +16,7 @@ type nushell struct{}
var Nushell = nushell{}
-const nushellConfig = `
-# This script is automatically generated by vfox. It takes care of environment setup in Nushell.
-
-# Make sure this script file is up to date when opening a new shell.
-^'{{.SelfPath}}' activate nushell $nu.default-config-dir | ignore
-
+const nushellHookBody = `
export-env {
# This function updates environment variables based on the output of the "vfox env" command.
def --env updateVfoxEnvironment [] {
@@ -66,18 +61,30 @@ export-env {
}
`
+const nushellHook = `
+# This script is automatically generated by vfox. It takes care of environment setup in Nushell.
+` + nushellHookBody
+
+const nushellConfig = `
+# This script is automatically generated by vfox. It takes care of environment setup in Nushell.
+
+# Make sure this script file is up to date when opening a new shell.
+^'{{.SelfPath}}' activate nushell $nu.default-config-dir | ignore
+` + nushellHookBody
+
// Activate implements shell.Activate by:
//
-// 1. Creating a `vfox.nu` script file in Nushell's default configuration directory. This script takes care of vfox
-// environment setup in Nushell.
-// 2. Returning a short script to be added to the Nushell configuration file, which runs the `vfox.nu` script.
+// 1. Returning the Nushell activation script directly when no config path argument is given.
+// 2. Creating a 'vfox.nu' script file in Nushell's configuration directory and returning the source script
+// when a config directory argument is provided (e.g. $nu.default-config-dir).
func (n nushell) Activate(config ActivateConfig) (string, error) {
- if len(config.Args) == 0 {
- return "", fmt.Errorf("config path is required")
+ templateContent := nushellHook
+ if len(config.Args) > 0 {
+ templateContent = nushellConfig
}
// Parse and execute the template
- tmpl, err := template.New("nushell").Parse(nushellConfig)
+ tmpl, err := template.New("nushell").Parse(templateContent)
if err != nil {
return "", fmt.Errorf("failed to parse template: %w", err)
}
@@ -99,13 +106,19 @@ func (n nushell) Activate(config ActivateConfig) (string, error) {
return "", fmt.Errorf("failed to execute template: %w", err)
}
- // Replace newlines for platform compatibility
- nushellConfig := strings.ReplaceAll(buf.String(), "\n", env.Newline)
+ renderedConfig := strings.ReplaceAll(buf.String(), "\n", env.Newline)
+
+ if len(config.Args) == 0 {
+ return renderedConfig, nil
+ }
// write file to config
+ if err := os.MkdirAll(config.Args[0], 0755); err != nil {
+ return "", fmt.Errorf("failed to create config directory: %w", err)
+ }
targetPath := filepath.Join(config.Args[0], "vfox.nu")
- if err := os.WriteFile(targetPath, []byte(nushellConfig), 0755); err != nil {
- return "", fmt.Errorf("failed to write file: %s", err)
+ if err := os.WriteFile(targetPath, []byte(renderedConfig), 0755); err != nil {
+ return "", fmt.Errorf("failed to write file: %w", err)
}
script := "# vfox configuration" + env.Newline +
diff --git a/internal/shell/nushell_test.go b/internal/shell/nushell_test.go
index 25e8faf7..78ec4c2d 100644
--- a/internal/shell/nushell_test.go
+++ b/internal/shell/nushell_test.go
@@ -83,6 +83,14 @@ func TestExport(t *testing.T) {
EnvsToUnset: make([]string, 0),
},
},
+ {
+ "PathNil",
+ env.Vars{"PATH": nil},
+ nushellExportData{
+ EnvsToSet: map[string]any{pathVarName: []any{}},
+ EnvsToUnset: make([]string, 0),
+ },
+ },
{
"PathAndOtherEnv",
env.Vars{
@@ -202,6 +210,20 @@ func TestNushellActivateWithPidCheck(t *testing.T) {
t.Error("Missing correct 'get -o hooks.pre_prompt'")
}
+ // Verify environment variable loading and unsetting
+ if !strings.Contains(contentStr, "load-env $envData.envsToSet") {
+ t.Error("Missing load-env $envData.envsToSet")
+ }
+ if !strings.Contains(contentStr, "hide-env ...$envData.envsToUnset") {
+ t.Error("Missing hide-env ...$envData.envsToUnset")
+ }
+ if strings.Contains(contentStr, "if not ($envData.envsToSet | is-empty)") {
+ t.Error("Unexpected envsToSet emptiness check guard")
+ }
+ if strings.Contains(contentStr, "if not ($envData.envsToUnset | is-empty)") {
+ t.Error("Unexpected envsToUnset emptiness check guard")
+ }
+
// Check for PID check block presence/absence
hasPidCheck := strings.Contains(contentStr, "# Check if PID changed") &&
strings.Contains(contentStr, "if ($nu.pid != $env.__VFOX_PID)")
@@ -257,3 +279,164 @@ func TestNushellActivateRecordsTheBaseline(t *testing.T) {
t.Errorf("the baseline is set outside export-env, which would not reach the session:\n%s", script)
}
}
+
+func TestNushellActivateDirect(t *testing.T) {
+ n := nushell{}
+
+ tests := []struct {
+ name string
+ enablePidCheck bool
+ expectPidBlock bool
+ }{
+ {
+ name: "Direct activate with PID check",
+ enablePidCheck: true,
+ expectPidBlock: true,
+ },
+ {
+ name: "Direct activate without PID check",
+ enablePidCheck: false,
+ expectPidBlock: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ script, err := n.Activate(ActivateConfig{
+ SelfPath: "/usr/local/bin/vfox",
+ Args: nil,
+ EnablePidCheck: tt.enablePidCheck,
+ })
+ if err != nil {
+ t.Fatalf("Activate() failed: %v", err)
+ }
+
+ if script == "" {
+ t.Fatal("Activate() returned empty script")
+ }
+
+ // Direct activation should return the script directly without sourcing
+ if strings.Contains(script, "source ($nu.default-config-dir") {
+ t.Error("Direct script should not contain source line")
+ }
+ if strings.Contains(script, "^'/usr/local/bin/vfox' activate nushell $nu.default-config-dir") {
+ t.Error("Direct script should not contain self-re-activate line")
+ }
+
+ // Verify template evaluation
+ if strings.Contains(script, "{{if .EnablePidCheck}}") || strings.Contains(script, "{{end}}") {
+ t.Error("Template conditional directives were not evaluated")
+ }
+ if strings.Contains(script, "{{.SelfPath}}") {
+ t.Error("Template variable '{{.SelfPath}}' was not evaluated")
+ }
+
+ // Verify self path and required nushell hooks
+ if !strings.Contains(script, "/usr/local/bin/vfox") {
+ t.Error("SelfPath missing from script")
+ }
+ if !strings.Contains(script, "export-env") {
+ t.Error("Missing export-env block")
+ }
+ if !strings.Contains(script, "def --env updateVfoxEnvironment") {
+ t.Error("Missing updateVfoxEnvironment function definition")
+ }
+ if !strings.Contains(script, "$env.config = ($env.config | upsert hooks.pre_prompt") {
+ t.Error("Missing hooks.pre_prompt configuration")
+ }
+ if !strings.Contains(script, "get -o hooks.pre_prompt") {
+ t.Error("Missing optional get flag for hooks.pre_prompt")
+ }
+ if !strings.Contains(script, "$env.__VFOX_SHELL = 'nushell'") {
+ t.Error("Missing __VFOX_SHELL declaration")
+ }
+ if !strings.Contains(script, "load-env $envData.envsToSet") {
+ t.Error("Missing load-env $envData.envsToSet")
+ }
+ if !strings.Contains(script, "hide-env ...$envData.envsToUnset") {
+ t.Error("Missing hide-env ...$envData.envsToUnset")
+ }
+ if strings.Contains(script, "if not ($envData.envsToSet | is-empty)") {
+ t.Error("Unexpected envsToSet emptiness check guard")
+ }
+ if strings.Contains(script, "if not ($envData.envsToUnset | is-empty)") {
+ t.Error("Unexpected envsToUnset emptiness check guard")
+ }
+
+ hasPidCheck := strings.Contains(script, "# Check if PID changed") &&
+ strings.Contains(script, "if ($nu.pid != $env.__VFOX_PID)")
+
+ if tt.expectPidBlock && !hasPidCheck {
+ t.Error("Expected PID check block to be present when EnablePidCheck is true")
+ }
+ if !tt.expectPidBlock && hasPidCheck {
+ t.Error("Expected PID check block to be absent when EnablePidCheck is false")
+ }
+ })
+ }
+}
+
+func TestNushellActivateErrors(t *testing.T) {
+ n := nushell{}
+
+ t.Run("MkdirAll error", func(t *testing.T) {
+ tempDir := t.TempDir()
+ filePath := filepath.Join(tempDir, "regular_file")
+ if err := os.WriteFile(filePath, []byte("data"), 0644); err != nil {
+ t.Fatalf("Failed to create file: %v", err)
+ }
+ // Passing filePath/child causes os.MkdirAll to fail because filePath is a regular file
+ invalidDirPath := filepath.Join(filePath, "child")
+ _, err := n.Activate(ActivateConfig{
+ SelfPath: "/usr/bin/vfox",
+ Args: []string{invalidDirPath},
+ })
+ if err == nil {
+ t.Fatal("Expected error from MkdirAll, got nil")
+ }
+ if !strings.Contains(err.Error(), "failed to create config directory") {
+ t.Errorf("Unexpected error message: %v", err)
+ }
+ })
+
+ t.Run("WriteFile error", func(t *testing.T) {
+ tempDir := t.TempDir()
+ // Create a directory where the file would be written
+ dirInPlaceOfFile := filepath.Join(tempDir, "vfox.nu")
+ if err := os.Mkdir(dirInPlaceOfFile, 0755); err != nil {
+ t.Fatalf("Failed to create directory: %v", err)
+ }
+ _, err := n.Activate(ActivateConfig{
+ SelfPath: "/usr/bin/vfox",
+ Args: []string{tempDir},
+ })
+ if err == nil {
+ t.Fatal("Expected error from WriteFile, got nil")
+ }
+ if !strings.Contains(err.Error(), "failed to write file") {
+ t.Errorf("Unexpected error message: %v", err)
+ }
+ })
+}
+
+func TestNushellActivateCreatesConfigDir(t *testing.T) {
+ n := nushell{}
+ tempDir := t.TempDir()
+ configDir := filepath.Join(tempDir, "nested", "config")
+
+ script, err := n.Activate(ActivateConfig{
+ SelfPath: "/usr/bin/vfox",
+ Args: []string{configDir},
+ })
+ if err != nil {
+ t.Fatalf("Activate() failed: %v", err)
+ }
+ if script == "" {
+ t.Fatal("Activate() returned empty script")
+ }
+
+ targetPath := filepath.Join(configDir, "vfox.nu")
+ if _, err := os.Stat(targetPath); err != nil {
+ t.Fatalf("Expected %s to exist, stat failed: %v", targetPath, err)
+ }
+}
diff --git a/internal/shell/shell.go b/internal/shell/shell.go
index 7dbd007d..bf4fbe6f 100644
--- a/internal/shell/shell.go
+++ b/internal/shell/shell.go
@@ -57,7 +57,7 @@ func NewShell(name string) Shell {
return Fish
case "clink":
return Clink
- case "nushell":
+ case "nu", "nushell":
return Nushell
}
return nil
diff --git a/internal/shell/shell_test.go b/internal/shell/shell_test.go
index f52a387b..c23e1956 100644
--- a/internal/shell/shell_test.go
+++ b/internal/shell/shell_test.go
@@ -123,3 +123,33 @@ func TestZshActivateReinitializesInheritedSession(t *testing.T) {
}
}
}
+
+func TestNewShell(t *testing.T) {
+ tests := []struct {
+ name string
+ shellName string
+ want Shell
+ }{
+ {"bash", "bash", Bash},
+ {"BASH upper", "BASH", Bash},
+ {"zsh", "zsh", Zsh},
+ {"fish", "fish", Fish},
+ {"pwsh", "pwsh", Pwsh},
+ {"clink", "clink", Clink},
+ {"nu", "nu", Nushell},
+ {"NU upper", "NU", Nushell},
+ {"nushell", "nushell", Nushell},
+ {"NuShell mixed", "NuShell", Nushell},
+ {"unknown", "unknown", nil},
+ {"empty", "", nil},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := NewShell(tt.shellName)
+ if got != tt.want {
+ t.Fatalf("NewShell(%q) = %v, want %v", tt.shellName, got, tt.want)
+ }
+ })
+ }
+}