This repository has been archived by the owner on Nov 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmapping.go
105 lines (93 loc) · 2.08 KB
/
mapping.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
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/user"
"regexp"
"strings"
)
type prefix struct {
key string
url string
}
// prefixMap - Converts a prefix string to a full URI.
// Returns the input string if no prefix is found.
func prefixMap(str string) string {
httpCheck, err := regexp.MatchString(`http.*`, str)
if err != nil {
log.Fatal(err)
}
// By default, return the input string
output := str
// If the input starts with http, don't look up the mapping
if httpCheck {
return output
}
// Check for colon prefix syntax, e.g. `schema:description`
matches := colonCheck.FindStringSubmatch(str)
if len(matches) > 2 {
output = fmt.Sprintf("%v%v", getPrefix(matches[1]), matches[2])
} else {
// Directly use the prefix
output = getPrefix(str)
}
return output
}
// Regex for the user's ~/.ldget/prefixes file
var selector, _ = regexp.Compile(`(.*)=(.*)`)
// Parses the prefixes file
func readMap(filePath string) []prefix {
file, err := os.Open(filePath)
if err != nil {
log.Fatal(err)
}
var prefixes []prefix
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// Lines that start with # are comments
if strings.HasPrefix(line, "#") {
continue
}
// Ignore empty lines
if line == "" {
continue
}
matches := selector.FindStringSubmatch(line)
if len(matches) < 2 {
log.Fatal("Something is wrong with your prefixes file.")
}
var p prefix
p.key = matches[1]
p.url = matches[2]
prefixes = append(prefixes, p)
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
return prefixes
}
func getAllMaps() []prefix {
var allPrefixes []prefix
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
userMappingLocation := fmt.Sprintf("%v/.ldget/prefixes", usr.HomeDir)
allPrefixes = append(allPrefixes, readMap(userMappingLocation)...)
return allPrefixes
}
var colonCheck, _ = regexp.Compile(`(.*):(.*)`)
// Returns URL for some prefix
func getPrefix(key string) string {
output := key
for _, prefix := range getAllMaps() {
if prefix.key == key {
output = prefix.url
break
}
}
return output
}