/
config.go
189 lines (154 loc) · 4.55 KB
/
config.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package config
import (
"fmt"
"os"
"regexp"
"strings"
"gopkg.in/yaml.v2"
)
// DefaultLocal contains the default filepath to the local todocheck config for the current repository
const DefaultLocal = ".todocheck.yaml"
var (
windowsAbsolutePathPattern = regexp.MustCompile("^[A-Z]{1}:")
gitRemoteOriginPattern = regexp.MustCompile(`(?Um)url\s=\s\w+(://|@)(?P<origin>(?P<host>.+)?(:|/).+)(\.git)?$`)
)
// Local todocheck configuration struct definition
type Local struct {
Origin string `yaml:"origin"`
IssueTracker IssueTracker `yaml:"issue_tracker"`
IgnoredPaths []string `yaml:"ignored"`
CustomTodos []string `yaml:"custom_todos"`
Auth *Auth `yaml:"auth"`
MatchCaseInsensitive bool `yaml:"match_case_insensitive"`
}
// NewLocal configuration from a given file path
func NewLocal(cfgPath, basepath string) (*Local, error) {
if cfgPath == "" {
cfgPath = basepath + "/" + DefaultLocal
}
var (
cfg *Local
err error
)
if exists(cfgPath) {
cfg, err = fromFile(cfgPath)
if err != nil {
return nil, err
}
} else {
cfg, err = autoDetect(basepath)
if err != nil {
return nil, fmt.Errorf("file %s not found: unable to automatically detect issue tracker: %w", cfgPath, err)
}
}
cfg.Auth.TokensCache = prependBasepath(cfg.Auth.TokensCache, basepath)
prependDoublestarGlob(cfg.IgnoredPaths, basepath)
trimTrailingSlashesFromDirs(cfg.IgnoredPaths)
removeCurrentDirReference(cfg.IgnoredPaths)
cfg.CustomTodos = decodeEscapedReservedCharacters(cfg.CustomTodos)
cfg.CustomTodos = addDefaultFormatIfMissing(cfg.CustomTodos)
return cfg, nil
}
func fromFile(cfgPath string) (*Local, error) {
bs, err := os.ReadFile(cfgPath)
if err != nil {
return nil, fmt.Errorf("couldn't open local configuration (%s): %w", cfgPath, err)
}
cfg := &Local{Auth: defaultAuthCfg()}
err = yaml.Unmarshal(bs, &cfg)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal local configuration (%s): %w", cfgPath, err)
}
return cfg, nil
}
func autoDetect(basepath string) (*Local, error) {
bs, err := os.ReadFile(basepath + "/.git/config")
if err != nil {
return nil, err
}
result := map[string]string{}
match := gitRemoteOriginPattern.FindStringSubmatch(string(bs))
for i, group := range gitRemoteOriginPattern.SubexpNames() {
result[group] = match[i]
}
var issueTracker IssueTracker
switch result["host"] {
case "github.com":
issueTracker = IssueTrackerGithub
case "gitlab.com":
issueTracker = IssueTrackerGitlab
default:
return nil, fmt.Errorf("unable to auto-detect issue tracker")
}
// Since origin urls can be found in both formats of HTTP based URLs and SSH URIs,
// it's necessary to replace colon with slash to convert it to a valid HTTP URL.
// Example: git@github:username/repo.git, https://github.com/username/repo.git
origin := strings.Replace(result["origin"], ":", "/", 1)
fmt.Printf("Detected %q as issue tracker since no config file was found.\n", origin)
return &Local{
Auth: defaultAuthCfg(),
IssueTracker: issueTracker,
Origin: origin,
}, nil
}
func exists(filepath string) bool {
info, err := os.Stat(filepath)
if os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
func trimTrailingSlashesFromDirs(dirs []string) {
for i, dir := range dirs {
dirs[i] = strings.TrimRight(dir, "/")
}
}
func prependDoublestarGlob(dirs []string, basepath string) {
for i := range dirs {
dirs[i] = "**/" + dirs[i]
}
}
func prependBasepath(path, basepath string) string {
if !isRelativePath(path) {
return path
}
if basepath[len(basepath)-1] != '/' {
basepath = basepath + "/"
}
return basepath + path
}
func removeCurrentDirReference(dirs []string) {
for i := range dirs {
if dirs[i][:2] == "./" {
dirs[i] = dirs[i][2:]
}
}
}
func isRelativePath(path string) bool {
return path[0] != '/' && path[0] != '~' && !windowsAbsolutePathPattern.MatchString(path)
}
// addDefaultFormatIfMissing trying find default TODO string and adding it if not exists
func addDefaultFormatIfMissing(todos []string) []string {
var isExists bool
for _, v := range todos {
if v == "TODO" {
isExists = true
continue
}
}
if !isExists {
todos = append(todos, "TODO")
}
return todos
}
func decodeEscapedReservedCharacters(slice []string) []string {
// Remove leading escaping "\" for reserved strings.
// "@", "`" in YAML is reserved indicators
// https://yaml.org/spec/1.2/spec.html#id2772075
for i, v := range slice {
if strings.HasPrefix(v, "\\@") || strings.HasPrefix(v, "\\`") {
slice[i] = v[1:]
}
}
return slice
}