-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
108 lines (97 loc) · 2.05 KB
/
utils.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
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
108
package main
import (
"bufio"
"fmt"
"log"
"os"
"runtime"
"strings"
)
func getHomeDir() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func handleErr(err error) {
if err != nil {
log.Fatal(err)
}
}
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
// writeLines writes the lines to the given file.
func writeLines(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
}
return w.Flush()
}
func formatCredentials(lines []string) (formattedLines []string) {
firstProfileIsLoaded := false
for _, line := range lines {
if line == "" {
continue
}
if !firstProfileIsLoaded {
if strings.HasPrefix(line, "[") {
firstProfileIsLoaded = true
formattedLines = append(formattedLines, line)
continue
}
}
if firstProfileIsLoaded && strings.HasPrefix(line, "[") {
formattedLines = append(formattedLines, "")
}
formattedLines = append(formattedLines, line)
}
return
}
func removeProfile(profile string, payload []string) []string {
var lines []string
var indexInProfile bool = false
for _, line := range payload {
if strings.HasPrefix(line, "[") && indexInProfile {
indexInProfile = false
}
if !indexInProfile {
if strings.HasPrefix(line, fmt.Sprintf("[%s]", profile)) {
indexInProfile = true
continue
} else {
lines = append(lines, line)
}
}
}
return lines
}
func fileContainsProfile(profile string, lines []string) bool {
// search for profile
for _, line := range lines {
if strings.HasPrefix(line, fmt.Sprintf("[%s]", profile)) {
return true
}
}
return false
}