-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patharchive.go
89 lines (73 loc) · 1.98 KB
/
archive.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
package k6deps
import (
"archive/tar"
"bytes"
"encoding/json"
"errors"
"io"
"path/filepath"
"slices"
)
type archiveMetadata struct {
Filename string `json:"filename"`
Env map[string]string `json:"env"`
}
const maxFileSize = 1024 * 1024 * 10 // 10M
func processArchive(input io.Reader) (analyzer, error) {
reader := tar.NewReader(input)
analyzers := make([]analyzer, 0)
for {
header, err := reader.Next()
switch {
case errors.Is(err, io.EOF):
return mergeAnalyzers(analyzers...), nil
case err != nil:
return nil, err
case header == nil:
continue
}
if header.Typeflag != tar.TypeReg || !shouldProcess(header.Name) {
continue
}
content := &bytes.Buffer{}
if _, err := io.CopyN(content, reader, maxFileSize); err != nil && !errors.Is(err, io.EOF) {
return nil, err
}
// if the file is metadata.json, we extract the dependencies from the env
if header.Name == "metadata.json" {
analyzer, err := analizeMetadata(content.Bytes())
if err != nil {
return nil, err
}
analyzers = append(analyzers, analyzer)
continue
}
// analize the file content as an script
target := filepath.Clean(filepath.FromSlash(header.Name))
src := Source{
Name: target,
Contents: content.Bytes(),
}
analyzers = append(analyzers, scriptAnalyzer(src))
}
}
// indicates if the file should be processed during extraction
func shouldProcess(target string) bool {
ext := filepath.Ext(target)
return slices.Contains([]string{".js", ".ts"}, ext) || slices.Contains([]string{"metadata.json", "data"}, target)
}
// analizeMetadata extracts the dependencies from the metadata.json file
func analizeMetadata(content []byte) (analyzer, error) {
metadata := archiveMetadata{}
if err := json.Unmarshal(content, &metadata); err != nil {
return nil, err
}
if value, found := metadata.Env[EnvDependencies]; found {
src := Source{
Name: EnvDependencies,
Contents: []byte(value),
}
return envAnalyzer(src), nil
}
return empty, nil
}