path.go 1.24 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package lookup

import (
	"os"
	"path"
	"path/filepath"
	"strings"
)

const (
	envPath = "PATH"
)

var (
	defaultPath = []string{"/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"}
)

// GetPaths returns a list of paths for a specified root. These are constructed from the
// PATH environment variable, a default path list, and the supplied root.
func GetPaths(root string) []string {
	dirs := filepath.SplitList(os.Getenv(envPath))

	inDirs := make(map[string]bool)
	for _, d := range dirs {
		inDirs[d] = true
	}

	// directories from the environment have higher precedence
	for _, d := range defaultPath {
		if inDirs[d] {
			// We don't add paths that are already included
			continue
		}
		dirs = append(dirs, d)
	}

	if root != "" && root != "/" {
		rootDirs := []string{}
		for _, dir := range dirs {
			rootDirs = append(rootDirs, path.Join(root, dir))
		}
		// directories with the root prefix have higher precedence
		dirs = append(rootDirs, dirs...)
	}

	return dirs
}

// GetPath returns a colon-separated path value that can be used to set the PATH
// environment variable
func GetPath(root string) string {
	return strings.Join(GetPaths(root), ":")
}