-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
65 lines (55 loc) · 1.63 KB
/
parser.go
File metadata and controls
65 lines (55 loc) · 1.63 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
package main
import (
"encoding/json"
"regexp"
"strings"
)
// PackageJSON struct to map only necessary fields
type PackageJSON struct {
Dependencies map[string]string `json:"dependencies"`
DevDependencies map[string]string `json:"devDependencies"`
}
// ParsePackageJSON extracts package names from package.json content
func ParsePackageJSON(content []byte) ([]string, error) {
var pkg PackageJSON
if err := json.Unmarshal(content, &pkg); err != nil {
return nil, err
}
var packages []string
for k := range pkg.Dependencies {
packages = append(packages, k)
}
for k := range pkg.DevDependencies {
packages = append(packages, k)
}
return Deduplicate(packages), nil
}
// ParseYarnLock extracts package names from yarn.lock content
func ParseYarnLock(content []byte) ([]string, error) {
// Yarn lock entries look like: "package-name@version":
// Regex to capture the package name at the start of the line or structure
// This is a simplified regex effectively capturing "string@" or "@scope/string@"
re := regexp.MustCompile(`^"?(@?[a-zA-Z0-9.\-\/]+)@`)
lines := strings.Split(string(content), "\n")
var packages []string
for _, line := range lines {
line = strings.TrimSpace(line)
match := re.FindStringSubmatch(line)
if len(match) > 1 {
packages = append(packages, match[1])
}
}
return Deduplicate(packages), nil
}
// Deduplicate removes duplicate strings from a slice
func Deduplicate(input []string) []string {
seen := make(map[string]struct{})
var result []string
for _, item := range input {
if _, ok := seen[item]; !ok {
seen[item] = struct{}{}
result = append(result, item)
}
}
return result
}