-
Notifications
You must be signed in to change notification settings - Fork 0
/
file-logic.go
110 lines (91 loc) · 2.48 KB
/
file-logic.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
109
110
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
s "strings"
)
func checkIfValidFile(filename string) (bool, error) {
// Check if file is yaml
if fileExtension := filepath.Ext(filename); !(fileExtension == ".yaml" || fileExtension == ".yml") {
return false, fmt.Errorf("File %s is not YAML", filename)
}
// Check if file does exist
if _, err := os.Stat(filename); err != nil && os.IsNotExist(err) {
return false, fmt.Errorf("File %s does not exist", filename)
}
return true, nil
}
func filterFingerprintsFromFile(filePath string) []string {
// open file
file, err := os.Open(filePath)
check(err)
defer func(file *os.File) {
err := file.Close()
check(err)
}(file)
// parse input into string array
fileReader := bufio.NewScanner(file)
fileReader.Split(bufio.ScanLines)
var content []string
for fileReader.Scan() {
content = append(content, fileReader.Text())
}
debug(fmt.Sprintf("Read lines from file: %d", len(content)))
result := make([]string, 0)
// filter content for fingerprints
isInPgpBracket := false
for i := 0; i < len(content); i++ {
line := content[i]
// check for pgp bracket start
if isInPgpBracket == false && s.Contains(line, "pgp:") {
debug("found pgp bracket")
isInPgpBracket = true
continue
}
// check for pgp bracket end
if isInPgpBracket == true && s.Contains(line, ": ") {
debug("closing pgp bracket")
isInPgpBracket = false
continue
}
// filter out comment lines
if isInPgpBracket == true && s.HasPrefix(s.TrimSpace(line), "#") {
continue
}
if isInPgpBracket == true {
trimmedLine := s.Trim(line, " -") // remove list operator
trimmedLine = s.Split(trimmedLine, " #")[0] // remove possible comments after fingerprint
debug("adding line to file result: " + trimmedLine)
result = append(result, trimmedLine)
}
}
debug(fmt.Sprintf("Fingerprints in file: %d", len(result)))
result = removeDuplicates(result)
debug(fmt.Sprintf("Unique fingerprints: %d", len(result)))
return result
}
func removeDuplicates[T string | int](sliceList []T) []T {
allKeys := make(map[T]bool)
list := []T{}
for _, item := range sliceList {
if _, value := allKeys[item]; !value {
allKeys[item] = true
list = append(list, item)
}
}
return list
}
func createPublicKeyFile(fingerprint string, key string) {
f, err := os.Create(fingerprint)
check(err)
_, err = f.WriteString(key)
check(err)
err = f.Close()
check(err)
}
func removeFile(filePath string) {
err := os.Remove(filePath)
check(err)
}