-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
107 lines (86 loc) · 2.07 KB
/
main.go
File metadata and controls
107 lines (86 loc) · 2.07 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"flag"
"fmt"
"os"
"strings"
"unicode"
"github.com/elliotchance/pie/v2"
)
var (
path = flag.String("path", os.Getenv("PATH"), "PATH to add onto")
pathFile = flag.String("file", "~/.paths", "The location of your paths file")
allowReverse = flag.Bool("allowReverse", false, "Read paths file in reverse")
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)
p = strings.TrimSuffix(p, "/")
if s, ok := strings.CutPrefix(p, "~"); ok {
p = homeDir + s
}
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(processLines(string(b), *allowReverse))
validatePath(pie.Reverse(strings.Split(*path, ":")))
fmt.Printf(`export PATH="%s"`, strings.Join(paths, ":"))
}
func processLines(s string, r bool) []string {
a := make([]string, 0)
for _, p := range getReversed(strings.Split(s, "\n"), r) {
a = append(a, strings.Split(p, ":")...)
}
return pie.FilterNot(a, func(f string) bool {
if len(f) == 0 {
return true
}
// This handles \n and \t cases as well
// See Pattern_White_Space in https://www.unicode.org/reports/tr31/
for _, c := range f {
if !unicode.IsSpace(c) {
return false
}
}
return true
})
}
func getReversed(s []string, r bool) []string {
if !r {
return s
}
return pie.Reverse(s)
}