Skip to content

Commit 3006ca2

Browse files
committed
重构 PATH 处理逻辑,添加 removeNodePath 函数以移除包含 node 二进制文件的目录, close #12
1 parent 3b69bef commit 3006ca2

File tree

1 file changed

+50
-1
lines changed

1 file changed

+50
-1
lines changed

internal/util/appendEnvPath.go

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,59 @@ package util
33
import (
44
"fmt"
55
"os"
6+
"runtime"
7+
"strings"
68
)
79

10+
func removeFromSlice(s []string, r string) []string {
11+
result := s[:0] // Use the same slice to avoid extra allocations
12+
for _, v := range s {
13+
if v != r {
14+
result = append(result, v)
15+
}
16+
}
17+
return result
18+
}
19+
20+
func removeNodePath(paths string) string {
21+
// Split the PATH into directories
22+
dirs := strings.Split(paths, string(os.PathListSeparator))
23+
24+
// Remove the node binary directory from the PATH
25+
for _, dir := range dirs {
26+
stat, err := os.Stat(dir)
27+
28+
if err != nil {
29+
continue
30+
}
31+
32+
if !stat.IsDir() {
33+
continue
34+
}
35+
36+
// Check if the directory contains the node binary
37+
files, err := os.ReadDir(dir)
38+
if err != nil {
39+
continue
40+
}
41+
42+
fileLoop:
43+
for _, file := range files {
44+
isContainsNodeBinary := (runtime.GOOS == "windows" && file.Name() == "node.exe") || (runtime.GOOS != "windows" && file.Name() == "node")
45+
46+
if isContainsNodeBinary {
47+
// Remove the directory from the PATH
48+
dirs = removeFromSlice(dirs, dir)
49+
break fileLoop
50+
}
51+
}
52+
}
53+
54+
return strings.Join(dirs, string(os.PathListSeparator))
55+
}
56+
857
func AppendEnvPath(pathDir string) string {
9-
oldPath := os.Getenv("PATH")
58+
oldPath := removeNodePath(os.Getenv("PATH"))
1059

1160
newPath := fmt.Sprintf("%s%c%s%c%s", pathDir, os.PathListSeparator, oldPath, os.PathListSeparator, pathDir)
1261

0 commit comments

Comments
 (0)