-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
72 lines (58 loc) · 1.39 KB
/
main.go
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// SPDX-FileCopyrightText: 2023 froggie <[email protected]>
//
// SPDX-License-Identifier: OSL-3.0
package main
import (
"flag"
"fmt"
"github.com/elliotchance/pie/v2"
"os"
"strings"
)
var (
path = flag.String("path", os.Getenv("PATH"), "PATH to add onto")
pathFile = flag.String("file", "~/.paths", "The location of your paths file")
allowMissing = flag.Bool("allowMissing", true, "Add non-existent directories to PATH")
allowInvalid = flag.Bool("allowInvalid", false, "Add invalid directories to PATH")
)
func main() {
flag.Parse()
homeDir, err := os.UserHomeDir()
if err != nil {
panic(err)
}
if s, ok := strings.CutPrefix(*pathFile, "~"); ok {
*pathFile = homeDir + s
}
b, err := os.ReadFile(*pathFile)
if err != nil {
panic(err)
}
paths := make([]string, 0)
validatePath := func(pathsNew []string) {
for _, p := range pathsNew {
p = os.ExpandEnv(p)
if _, err := os.Stat(p); err != nil {
if os.IsNotExist(err) { // file does not exist
if !*allowMissing {
continue
}
} else { // other error
if !*allowInvalid {
continue
}
}
}
if p == " " || len(p) == 0 {
continue
}
if pie.Contains(paths, p) {
continue
}
paths = pie.Insert(paths, 0, p)
}
}
validatePath(strings.Split(string(b), "\n"))
validatePath(strings.Split(*path, ":"))
fmt.Printf(`export PATH="%s"`, strings.Join(paths, ":"))
}