-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprefix.go
More file actions
68 lines (54 loc) · 1.47 KB
/
prefix.go
File metadata and controls
68 lines (54 loc) · 1.47 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
package archives
import (
"io"
"strings"
)
// prefixStripper wraps a Reader and strips a prefix from all file paths.
type prefixStripper struct {
reader Reader
prefix string
}
func (p *prefixStripper) List() ([]FileInfo, error) {
files, err := p.reader.List()
if err != nil {
return nil, err
}
return p.stripPrefix(files), nil
}
func (p *prefixStripper) ListDir(dirPath string) ([]FileInfo, error) {
// Add prefix to the requested directory
prefixedPath := p.prefix + dirPath
files, err := p.reader.ListDir(prefixedPath)
if err != nil {
return nil, err
}
return p.stripPrefix(files), nil
}
func (p *prefixStripper) Extract(filePath string) (io.ReadCloser, error) {
// Add prefix to the requested file path
prefixedPath := p.prefix + filePath
return p.reader.Extract(prefixedPath)
}
func (p *prefixStripper) Close() error {
return p.reader.Close()
}
// stripPrefix removes the prefix from all file paths.
func (p *prefixStripper) stripPrefix(files []FileInfo) []FileInfo {
result := make([]FileInfo, 0, len(files))
for _, f := range files {
// Skip files that don't have the prefix
if !strings.HasPrefix(f.Path, p.prefix) {
continue
}
// Strip the prefix
stripped := f
stripped.Path = strings.TrimPrefix(f.Path, p.prefix)
stripped.Name = extractName(stripped.Path)
// Skip if path is now empty (was the prefix directory itself)
if stripped.Path == "" || stripped.Path == "/" {
continue
}
result = append(result, stripped)
}
return result
}