-
Notifications
You must be signed in to change notification settings - Fork 0
/
walk.go
73 lines (66 loc) · 1.59 KB
/
walk.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
package main
import (
"context"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"github.com/ozanh/arch-transfer/common"
)
func walkPath(ctx context.Context, source string, addFn common.AddFunc) error {
source = filepath.Clean(source)
info, err := os.Lstat(source)
if err != nil {
return fmt.Errorf("failed to get source info: %w", err)
}
if info.IsDir() {
err = walkDir(ctx, source, addFn)
} else if info.Mode().IsRegular() {
var f *os.File
f, err = os.Open(source)
if err != nil {
return fmt.Errorf("failed to open source file: %w", err)
}
defer f.Close()
name := filepath.Base(source)
err = addFn(ctx, name, info, f)
} else {
err = fmt.Errorf("path is not a directory or regular file: %s", source)
}
return err
}
func walkDir(ctx context.Context, source string, addFn common.AddFunc) error {
parent := filepath.Dir(source)
root := filepath.Base(source)
if root == "" {
root = "."
}
fsys := os.DirFS(parent)
return fs.WalkDir(fsys, root, func(path string, d os.DirEntry, err error) error {
if ctx.Err() != nil {
return ctx.Err()
}
if err != nil {
return fmt.Errorf("failed to walk path: %s: %w", path, err)
}
if path == "." || !(d.IsDir() || d.Type().IsRegular()) {
return nil
}
info, err := d.Info()
if err != nil {
return fmt.Errorf("failed to get info: %s: %w", path, err)
}
var src io.Reader
if d.Type().IsRegular() {
f, err := fsys.Open(path)
if err != nil {
return fmt.Errorf("failed to open file: %s: %w", path, err)
}
defer f.Close()
src = f
}
path = filepath.ToSlash(path)
return addFn(ctx, path, info, src)
})
}