forked from stormcat24/protodep
/
resolver.go
291 lines (233 loc) · 6.81 KB
/
resolver.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package resolver
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/BurntSushi/toml"
"github.com/gobwas/glob"
"github.com/hr3685930/protodep/pkg/auth"
"github.com/hr3685930/protodep/pkg/config"
"github.com/hr3685930/protodep/pkg/logger"
"github.com/hr3685930/protodep/pkg/repository"
)
type protoResource struct {
source string
relativeDest string
}
type Resolver interface {
Resolve(forceUpdate bool, cleanupCache bool) error
SetHttpsAuthProvider(provider auth.AuthProvider)
SetSshAuthProvider(provider auth.AuthProvider)
}
type resolver struct {
conf *Config
httpsProvider auth.AuthProvider
sshProvider auth.AuthProvider
}
func New(conf *Config) (Resolver, error) {
s := &resolver{
conf: conf,
}
err := s.initAuthProviders()
if err != nil {
return nil, err
}
return s, nil
}
func (s *resolver) Resolve(forceUpdate bool, cleanupCache bool) error {
dep := config.NewDependency(s.conf.TargetDir, forceUpdate)
protodep, err := dep.Load()
if err != nil {
return err
}
newdeps := make([]config.ProtoDepDependency, 0, len(protodep.Dependencies))
protodepDir := filepath.Join(s.conf.HomeDir, ".protodep")
_, err = os.Stat(protodepDir)
if cleanupCache && err == nil {
files, err := os.ReadDir(protodepDir)
if err != nil {
return err
}
for _, file := range files {
if file.IsDir() {
dirpath := filepath.Join(protodepDir, file.Name())
if err := os.RemoveAll(dirpath); err != nil {
return err
}
}
}
}
outdir := filepath.Join(s.conf.OutputDir, protodep.ProtoOutdir)
for _, dep := range protodep.Dependencies {
pathOutdir := filepath.Join(s.conf.OutputDir, protodep.ProtoOutdir, dep.Path)
if err := os.RemoveAll(pathOutdir); err != nil {
return err
}
var authProvider auth.AuthProvider
if s.conf.UseHttps {
authProvider = s.httpsProvider
} else {
switch dep.Protocol {
case "https":
authProvider = s.httpsProvider
case "ssh", "":
authProvider = s.sshProvider
default:
return fmt.Errorf("%s protocol is not accepted (ssh or https only)", dep.Protocol)
}
}
gitrepo := repository.NewGit(protodepDir, dep, authProvider)
repo, err := gitrepo.Open()
if err != nil {
return err
}
sources := make([]protoResource, 0)
compiledIgnores := compileIgnoreToGlob(dep.Ignores)
compiledIncludes := compileIgnoreToGlob(dep.Includes)
hasIncludes := len(dep.Includes) > 0
protoRootDir := gitrepo.ProtoRootDir()
filepath.Walk(protoRootDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasSuffix(path, ".proto") {
isIncludePath := s.isMatchPath(protoRootDir, path, dep.Includes, compiledIncludes)
isIgnorePath := s.isMatchPath(protoRootDir, path, dep.Ignores, compiledIgnores)
if hasIncludes && !isIncludePath {
logger.Info("skipped %s due to include setting", path)
} else if isIgnorePath {
logger.Info("skipped %s due to ignore setting", path)
} else {
sources = append(sources, protoResource{
source: path,
relativeDest: strings.Replace(path, protoRootDir, "", -1),
})
}
}
return nil
})
for _, s := range sources {
outpath := filepath.Join(outdir, dep.Path, s.relativeDest)
content, err := os.ReadFile(s.source)
if err != nil {
return err
}
if err := writeFileWithDirectory(outpath, content, 0644); err != nil {
return err
}
}
newdeps = append(newdeps, config.ProtoDepDependency{
Target: repo.Dep.Target,
Branch: repo.Dep.Branch,
Revision: repo.Hash,
Path: repo.Dep.Path,
Includes: repo.Dep.Includes,
Ignores: repo.Dep.Ignores,
Protocol: repo.Dep.Protocol,
Subgroup: repo.Dep.Subgroup,
})
}
newProtodep := config.ProtoDep{
ProtoOutdir: protodep.ProtoOutdir,
Dependencies: newdeps,
}
if dep.IsNeedWriteLockFile() {
if err := writeToml("protodep.lock", newProtodep); err != nil {
return err
}
}
return nil
}
func (s *resolver) SetHttpsAuthProvider(provider auth.AuthProvider) {
s.httpsProvider = provider
}
func (s *resolver) SetSshAuthProvider(provider auth.AuthProvider) {
s.sshProvider = provider
}
func (s *resolver) initAuthProviders() error {
s.httpsProvider = auth.NewAuthProvider(auth.WithHTTPS(s.conf.BasicAuthUsername, s.conf.BasicAuthPassword))
if s.conf.IdentityFile == "" && s.conf.IdentityPassword == "" {
s.sshProvider = auth.NewAuthProvider()
return nil
}
identifyPath := filepath.Join(s.conf.HomeDir, ".ssh", s.conf.IdentityFile)
isSSH, err := isAvailableSSH(identifyPath)
if err != nil {
return err
}
if isSSH {
s.sshProvider = auth.NewAuthProvider(auth.WithPemFile(identifyPath, s.conf.IdentityPassword))
} else {
logger.Warn("The identity file path has been passed but is not available. Falling back to ssh-agent, the default authentication method.")
s.sshProvider = auth.NewAuthProvider()
}
return nil
}
func compileIgnoreToGlob(ignores []string) []glob.Glob {
globIgnores := make([]glob.Glob, len(ignores))
for idx, ignore := range ignores {
globIgnores[idx] = glob.MustCompile(ignore)
}
return globIgnores
}
func (s *resolver) isMatchPath(protoRootDir string, target string, paths []string, globMatch []glob.Glob) bool {
// convert slashes otherwise doesnt work on windows same was as on linux
target = filepath.ToSlash(target)
// keeping old logic for backward compatibility
for _, pathToMatch := range paths {
// support windows paths correctly
pathPrefix := filepath.ToSlash(filepath.Join(protoRootDir, pathToMatch))
if strings.HasPrefix(target, pathPrefix) {
return true
}
}
for _, pathToMatch := range globMatch {
if pathToMatch.Match(target) {
return true
}
}
return false
}
func writeToml(dest string, input interface{}) error {
var buffer bytes.Buffer
encoder := toml.NewEncoder(&buffer)
if err := encoder.Encode(input); err != nil {
return fmt.Errorf("encode config to toml format: %w", err)
}
if err := os.WriteFile(dest, buffer.Bytes(), 0644); err != nil {
return fmt.Errorf("write to %s: %w", dest, err)
}
return nil
}
func writeFileWithDirectory(path string, data []byte, perm os.FileMode) error {
path = filepath.ToSlash(path)
s := strings.Split(path, "/")
var dir string
if len(s) > 1 {
dir = strings.Join(s[0:len(s)-1], "/")
} else {
dir = path
}
dir = filepath.FromSlash(dir)
path = filepath.FromSlash(path)
if err := os.MkdirAll(dir, 0777); err != nil {
return fmt.Errorf("create directory %s: %w", dir, err)
}
if err := os.WriteFile(path, data, perm); err != nil {
return fmt.Errorf("write data to %s: %w", path, err)
}
return nil
}
// isAvailableSSH is Check whether this machine can use git protocol
func isAvailableSSH(identifyPath string) (bool, error) {
if _, err := os.Stat(identifyPath); err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// TODO: validate ssh key
return true, nil
}