-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathutils.go
More file actions
599 lines (504 loc) · 13.8 KB
/
utils.go
File metadata and controls
599 lines (504 loc) · 13.8 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
/* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the cpackget project. */
package utils
import (
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/xml"
"fmt"
"io"
"io/fs"
"math"
"math/rand"
"net"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"time"
errs "github.com/open-cmsis-pack/cpackget/cmd/errors"
"github.com/schollz/progressbar/v3"
log "github.com/sirupsen/logrus"
"golang.org/x/net/html/charset"
)
var gEncodedProgress = false
var gSkipTouch = false
var gUserAgent string
func SetEncodedProgress(encodedProgress bool) {
gEncodedProgress = encodedProgress
}
func GetEncodedProgress() bool {
return gEncodedProgress
}
func SetSkipTouch(skipTouch bool) {
gSkipTouch = skipTouch
}
func GetSkipTouch() bool {
return gSkipTouch
}
func SetUserAgent(userAgent string) {
gUserAgent = userAgent
}
// CacheDir is used for cpackget to temporarily host downloaded pack files
// before moving it to CMSIS_PACK_ROOT
var CacheDir string
var instCnt = 0
var HTTPClient *http.Client
type TimeoutTransport struct {
http.Transport
RoundTripTimeout time.Duration
}
// Helper function to set timeouts on HTTP connections
// that use keep-alive connections (the most common one)
func (t *TimeoutTransport) RoundTrip(req *http.Request) (*http.Response, error) {
type respAndErr struct {
resp *http.Response
err error
}
timeout := time.After(t.RoundTripTimeout)
resp := make(chan respAndErr, 1)
go func() {
r, e := t.Transport.RoundTrip(req)
resp <- respAndErr{
resp: r,
err: e,
}
}()
select {
case <-timeout:
//nolint:staticcheck
t.Transport.CancelRequest(req)
return nil, errs.ErrHTTPtimeout
case r := <-resp:
return r.resp, r.err
}
}
var (
// File RO (ReadOnly) and RW (Read + Write) modes
FileModeRO = fs.FileMode(0444)
FileModeRW = fs.FileMode(0666)
// Directory RO (ReadOnly + Traverse) and RW (Read + Write + Traverse) modes
DirModeRO = fs.FileMode(0555)
DirModeRW = fs.FileMode(0777)
)
// DownloadFile downloads a file from an URL and saves it locally under destionationFilePath
func DownloadFile(URL string, timeout int) (string, error) {
parsedURL, _ := url.Parse(URL)
fileBase := path.Base(parsedURL.Path)
filePath := filepath.Join(CacheDir, fileBase)
log.Debugf("Downloading %s to %s", URL, filePath)
if FileExists(filePath) {
log.Debugf("Download not required, using the one from cache")
return filePath, nil
}
// For now, skip insecure HTTPS downloads verification only for localhost
var tls tls.Config
if strings.Contains(URL, "https://127.0.0.1") {
// #nosec G402
tls.InsecureSkipVerify = true //nolint:gosec
} else {
tls.InsecureSkipVerify = false
}
var rtt time.Duration
if timeout == 0 {
rtt = time.Duration(math.MaxInt64)
} else {
rtt = time.Second * time.Duration(timeout)
}
client := &http.Client{
Transport: &TimeoutTransport{
Transport: http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
return net.Dial(netw, addr)
},
TLSClientConfig: &tls,
Proxy: http.ProxyFromEnvironment,
},
RoundTripTimeout: rtt,
},
}
req, _ := http.NewRequest("GET", URL, nil)
req.Header.Add("User-Agent", gUserAgent)
resp, err := client.Do(req)
if err != nil {
log.Error(err)
return "", fmt.Errorf("\"%s\": %w", URL, errs.ErrFailedDownloadingFile)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
// resend GET request without user agent header
req.Header.Del("User-Agent")
resp, err = client.Do(req)
if err != nil {
log.Error(err)
return "", fmt.Errorf("\"%s\": %w", URL, errs.ErrFailedDownloadingFile)
}
}
if resp.StatusCode == http.StatusForbidden {
cookie := resp.Header.Get("Set-Cookie")
if len(cookie) > 0 {
// add cookie and resend GET request
log.Debugf("Cookie: %s", cookie)
req.Header.Add("Cookie", cookie)
resp, err = client.Do(req)
if err != nil {
log.Error(err)
return "", fmt.Errorf("\"%s\": %w", URL, errs.ErrFailedDownloadingFile)
}
}
}
if resp.StatusCode != http.StatusOK {
log.Debugf("bad status: %s", resp.Status)
return "", fmt.Errorf("\"%s\": %w", URL, errs.ErrBadRequest)
}
out, err := os.Create(filePath)
if err != nil {
log.Error(err)
return "", errs.ErrFailedCreatingFile
}
defer out.Close()
log.Infof("Downloading %s...", fileBase)
writers := []io.Writer{out}
if log.GetLevel() != log.ErrorLevel {
length := resp.ContentLength
if GetEncodedProgress() {
progressWriter := NewEncodedProgress(length, instCnt, fileBase)
writers = append(writers, progressWriter)
instCnt++
} else {
if IsTerminalInteractive() {
progressWriter := progressbar.DefaultBytes(length, "I:")
writers = append(writers, progressWriter)
}
}
}
// Download file in smaller bits straight to a local file
written, err := SecureCopy(io.MultiWriter(writers...), resp.Body)
// fmt.Printf("\n")
log.Debugf("Downloaded %d bytes", written)
if err != nil {
out.Close()
_ = os.Remove(filePath)
}
return filePath, err
}
func CheckConnection(url string, timeOut int) error {
timeout := time.Duration(timeOut) * time.Second
client := http.Client{
Timeout: timeout,
}
resp, err := client.Get(url)
connStatus := "offline"
if err == nil {
connStatus = "online"
if !GetEncodedProgress() {
log.Debugf("Respond: %v (%v)", resp.Status, connStatus)
}
}
if GetEncodedProgress() {
log.Infof("[O:%v]", connStatus)
}
if connStatus == "offline" {
return fmt.Errorf("\"%s\": %w", url, errs.ErrOffline)
}
return nil
}
// FileExists checks if filePath is an actual file in the local file system
func FileExists(filePath string) bool {
info, err := os.Stat(filePath)
if info == nil || os.IsNotExist(err) {
return false
}
return !info.IsDir()
}
// DirExists checks if dirPath is an actual directory in the local file system
func DirExists(dirPath string) bool {
info, err := os.Stat(dirPath)
if os.IsNotExist(err) {
return false
}
return info.IsDir()
}
// EnsureDir recursevily creates a directory tree if it doesn't exist already
func EnsureDir(dirName string) error {
log.Debugf("Ensuring \"%s\" directory exists", dirName)
err := os.MkdirAll(dirName, 0755)
if err != nil && !os.IsExist(err) {
log.Error(err)
return errs.ErrFailedCreatingDirectory
}
return nil
}
func SameFile(source, destination string) bool {
if source == destination {
return true
}
srcInfo, err := os.Stat(source)
if err != nil {
return false
}
dstInfo, err := os.Stat(destination)
if err != nil {
return false
}
return os.SameFile(srcInfo, dstInfo)
}
// CopyFile copies the contents of source into a new file in destination
func CopyFile(source, destination string) error {
log.Debugf("Copying file from \"%s\" to \"%s\"", source, destination)
if SameFile(source, destination) {
return nil
}
sourceFile, err := os.Open(source)
if err != nil {
return err
}
defer sourceFile.Close()
destinationFile, err := os.Create(destination)
if err != nil {
return err
}
defer destinationFile.Close()
_, err = SecureCopy(destinationFile, sourceFile)
return err
}
// MoveFile moves a file from one source to destination
func MoveFile(source, destination string) error {
log.Debugf("Moving file from \"%s\" to \"%s\"", source, destination)
if SameFile(source, destination) {
return nil
}
UnsetReadOnly(source)
err := os.Rename(source, destination)
if err != nil {
log.Errorf("Can't move file \"%s\" to \"%s\": %s", source, destination, err)
return err
}
return nil
}
// ReadXML reads in a file into an XML struct
func ReadXML(path string, targetStruct interface{}) error {
contents, err := os.ReadFile(path)
if err != nil {
return err
}
reader := bytes.NewReader(contents)
decoder := xml.NewDecoder(reader)
decoder.CharsetReader = charset.NewReaderLabel
return decoder.Decode(targetStruct)
}
// WriteXML writes an XML struct to a file
func WriteXML(path string, targetStruct interface{}) error {
output, err := xml.MarshalIndent(targetStruct, "", " ")
if err != nil {
return err
}
xmlText := []byte(xml.Header)
xmlText = append(xmlText, output...)
return os.WriteFile(path, xmlText, FileModeRW)
}
// ListDir generates a list of files and directories in "dir".
// If pattern is specified, generates a list with matches only.
// It does NOT walk subdirectories
func ListDir(dir, pattern string) ([]string, error) {
regexPattern := regexp.MustCompile(`.*`)
if pattern != "" {
regexPattern = regexp.MustCompile(pattern)
}
log.Debugf("Listing files and directories in \"%v\" that match \"%v\"", dir, regexPattern)
files := []string{}
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// The target dir is always passed, skip it
if path == dir {
return nil
}
if regexPattern.MatchString(path) {
files = append(files, path)
}
// Avoid digging subdirs
if info.IsDir() {
return filepath.SkipDir
}
return nil
})
return files, err
}
// TouchFile touches the file specified by filePath.
// If the file does not exist, create it.
// Touch also updates the modified timestamp of the file.
func TouchFile(filePath string) error {
file, err := os.Create(filePath)
if err != nil {
log.Error(err)
return err
}
defer file.Close()
currentTime := time.Now().Local()
return os.Chtimes(filePath, currentTime, currentTime)
}
// IsBase64 tells whether a string is correctly b64 encoded.
func IsBase64(s string) bool {
_, err := base64.StdEncoding.DecodeString(s)
return err == nil
}
// IsEmpty tells whether a directory specified by "dir" is empty or not
func IsEmpty(dir string) bool {
file, err := os.Open(dir)
if err != nil {
return false
}
defer file.Close()
_, err = file.Readdirnames(1)
return err == io.EOF
}
// RandStringBytes returns a random string with n bytes long
// Ref: https://stackoverflow.com/a/31832326/3908350
func RandStringBytes(n int) string {
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
b := make([]byte, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))] // #nosec
}
return string(b)
}
// CountLines returns the number of lines in a string
// Ref: https://stackoverflow.com/a/24563853
func CountLines(content string) int {
reader := strings.NewReader(content)
buffer := make([]byte, 32*1024)
count := 0
lineFeed := []byte{'\n'}
for {
c, err := reader.Read(buffer)
count += bytes.Count(buffer[:c], lineFeed)
switch {
case err == io.EOF:
return count
case err != nil:
return count
}
}
}
// FilterPackId returns the original string if any of the
// received filter words are present - designed specifically to filter pack IDs
func FilterPackID(content string, filter string) string {
log.Debugf("Filtering by words \"%s\"", filter)
// Don't accept the separator or version char
if filter == "" || strings.ContainsAny(filter, ":") || strings.ContainsAny(filter, "@") {
return ""
}
words := strings.Split(filter, " ")
// We're only interested in the first "word" (pack id)
target := strings.Split(content, " ")[0]
for w := 0; w < len(words); w++ {
if strings.Contains(target, words[w]) {
return target
}
}
return ""
}
// IsTerminalInteractive tells whether or not the current terminal is
// capable of complex interactions
func IsTerminalInteractive() bool {
fileInfo, _ := os.Stdout.Stat()
return (fileInfo.Mode() & os.ModeCharDevice) != 0
}
func CleanPath(path string) string {
cleanPath := filepath.Clean(path)
windowsLeadingSlashRegex := regexp.MustCompile(`^[\\/][a-zA-Z]:[\\/]`)
if windowsLeadingSlashRegex.MatchString(cleanPath) {
cleanPath = cleanPath[1:]
}
return cleanPath
}
// SetReadOnly takes in a file or directory and set it
// to read-only mode. Should work on both Windows and Linux.
func SetReadOnly(path string) {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return
}
if !info.IsDir() {
_ = os.Chmod(path, FileModeRO)
return
}
_ = os.Chmod(path, DirModeRO)
}
// SetReadOnlyR works the same as SetReadOnly, except that it is recursive
func SetReadOnlyR(path string) {
info, err := os.Stat(path)
if os.IsNotExist(err) || !info.IsDir() {
return
}
// At this point all files and subdirs should be set to read-only recurisively
// there's only one catch that files and subdirs need to be set to read-only before
// its parent directory. This is why dirsByLevel exist. It'll help set read-only
// permissions in leaf directories before setting it root ones
dirsByLevel := make(map[int][]string)
maxLevel := -1
_ = filepath.WalkDir(path, func(path string, info fs.DirEntry, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
_ = os.Chmod(path, FileModeRO)
} else {
levelCount := strings.Count(path, "/") + strings.Count(path, "\\")
dirsByLevel[levelCount] = append(dirsByLevel[levelCount], path)
if levelCount > maxLevel {
maxLevel = levelCount
}
}
return nil
})
// Now set all directories to read-only, from bottom-up
for level := maxLevel; level >= 0; level-- {
if dirs, ok := dirsByLevel[level]; ok {
for _, dir := range dirs {
_ = os.Chmod(dir, DirModeRO)
}
}
}
}
// UnsetReadOnly takes in a file or directory and set it
// to read-write mode. Should work on both Windows and Linux.
func UnsetReadOnly(path string) {
info, err := os.Stat(path)
if os.IsNotExist(err) {
return
}
mode := FileModeRW
if info.IsDir() {
mode = DirModeRW
}
_ = os.Chmod(path, mode)
}
// UnsetReadOnlyR works the same as UnsetReadOnly, but recursive
func UnsetReadOnlyR(path string) {
info, err := os.Stat(path)
if os.IsNotExist(err) || !info.IsDir() {
return
}
_ = filepath.WalkDir(path, func(path string, info fs.DirEntry, err error) error {
if err != nil {
return err
}
mode := FileModeRW
if info.IsDir() {
mode = DirModeRW
}
_ = os.Chmod(path, mode)
return nil
})
}
func init() {
// rand.Seed(time.Now().UnixNano()) // rand.Seed deprecated, not necessary anymore
HTTPClient = &http.Client{}
}