-
Notifications
You must be signed in to change notification settings - Fork 0
/
go.ts
96 lines (77 loc) · 2.46 KB
/
go.ts
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
import * as core from '@actions/core'
import path from 'path'
import { GITHUB_DOMAIN } from './constants'
import { execSync } from 'child_process'
import { uniqBy } from 'lodash'
const sourceDir = core.getInput('src_dir') || process.cwd()
const resolveDir = (dir: string) => path.resolve(sourceDir, dir)
const filterDependency = (line: string) => line.startsWith(GITHUB_DOMAIN)
const parseDependency = (line: string) => {
switch (true) {
case line.startsWith(GITHUB_DOMAIN):
const [domain, owner, repo] = line.split('/')
return `https://${domain}/${owner}/${repo}`
default:
return
}
}
const parseModuleUrl = (m: string) => {
const [url, version = ''] = m.split('@')
const [domain, owner, repo] = url.split('/')
return { module: [domain, owner, repo].join('/'), version }
}
export const listDirectDeps = (dir: string) => {
let output = execSync(
`go list -f '{{if not .Indirect}}{{.}}{{end}}' -m all`,
{ cwd: resolveDir(dir) }
).toString()
return output
.split('\n')
.map((d) => {
const [module, version = ''] = d.split(' ')
return { module, version }
})
.filter((entry) => filterDependency(entry.module))
}
export const getModuleGraph = (dir: string) => {
const output = execSync(`go mod graph`, {
cwd: resolveDir(dir),
}).toString()
const graph: Record<string, { module: string; version: string }[]> = {}
output.split('\n').forEach((line) => {
if (!line) {
return
}
const [parent, child] = line.split(' ')
const mod = parseModuleUrl(parent)
const childMod = parseModuleUrl(child)
const key = `${mod.module}@${mod.version}`
graph[key] = graph[key] || []
if (childMod.module !== key) {
graph[key].push(childMod)
}
})
Object.entries(graph).forEach(([key, deps]) => {
graph[key] = uniqBy(deps, 'module')
})
return graph
}
export const getDependencies = (dir: string = '') => {
const graph = getModuleGraph(dir)
const direct = listDirectDeps(dir)
let dependencies = direct
.filter((d) => filterDependency(d.module))
.map((d) => {
const url = parseModuleUrl(d.module).module
const deps = graph[`${url}@${d.version}`] || []
return {
source: parseDependency(d.module) as string,
dependencies: deps
.filter((d) => filterDependency(d.module))
.map((d) => ({
source: parseDependency(d.module) as string,
})),
}
})
return dependencies as StackAidDependency[]
}