-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathpath-resolve.ts
297 lines (271 loc) · 8.88 KB
/
path-resolve.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { existsSync, promises as fs, realpathSync, statSync } from 'node:fs'
import path from 'node:path'
import process from 'node:process'
import ignore from 'ignore'
import micromatch from 'micromatch'
import { glob as tinyGlob } from 'tinyglobby'
import which from 'which'
import { debugLog } from './debug'
import { directoryPatterns } from './ignore-by-default'
import constants from '../constants'
import type { SocketYml } from '@socketsecurity/config'
import type { SocketSdkReturnType } from '@socketsecurity/sdk'
import type { GlobOptions } from 'tinyglobby'
type GlobWithGitIgnoreOptions = GlobOptions & {
socketConfig?: SocketYml | undefined
}
const { NODE_MODULES, NPM, shadowBinPath } = constants
async function filterGlobResultToSupportedFiles(
entries: string[],
supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data']
): Promise<string[]> {
const patterns = ['golang', NPM, 'maven', 'pypi'].reduce(
(r: string[], n: string) => {
const supported = supportedFiles[n]
r.push(
...(supported
? Object.values(supported).map(p => `**/${p.pattern}`)
: [])
)
return r
},
[]
)
return entries.filter(p => micromatch.some(p, patterns))
}
async function globWithGitIgnore(
patterns: string[],
options: GlobWithGitIgnoreOptions
) {
const {
cwd = process.cwd(),
socketConfig,
...additionalOptions
} = <GlobWithGitIgnoreOptions>{ __proto__: null, ...options }
const projectIgnorePaths = socketConfig?.projectIgnorePaths
const ignoreFiles = await tinyGlob(['**/.gitignore'], {
absolute: true,
cwd,
expandDirectories: true
})
const ignores = [
...directoryPatterns(),
...(Array.isArray(projectIgnorePaths)
? ignoreFileLinesToGlobPatterns(
projectIgnorePaths,
path.join(cwd, '.gitignore'),
cwd
)
: []),
...(
await Promise.all(
ignoreFiles.map(async filepath =>
ignoreFileToGlobPatterns(
await fs.readFile(filepath, 'utf8'),
filepath,
cwd
)
)
)
).flat()
]
const hasNegatedPattern = ignores.some(p => p.charCodeAt(0) === 33 /*'!'*/)
const globOptions = {
absolute: true,
cwd,
expandDirectories: false,
ignore: hasNegatedPattern ? [] : ignores,
...additionalOptions
}
const result = await tinyGlob(patterns, globOptions)
if (!hasNegatedPattern) {
return result
}
const { absolute } = globOptions
// Note: the input files must be INSIDE the cwd. If you get strange looking
// relative path errors here, most likely your path is outside the given cwd.
const filtered = ignore()
.add(ignores)
.filter(absolute ? result.map(p => path.relative(cwd, p)) : result)
return absolute ? filtered.map(p => path.resolve(cwd, p)) : filtered
}
function ignoreFileLinesToGlobPatterns(
lines: string[],
filepath: string,
cwd: string
): string[] {
const base = path.relative(cwd, path.dirname(filepath)).replace(/\\/g, '/')
const patterns = []
for (let i = 0, { length } = lines; i < length; i += 1) {
const pattern = lines[i]!.trim()
if (pattern.length > 0 && pattern.charCodeAt(0) !== 35 /*'#'*/) {
patterns.push(
ignorePatternToMinimatch(
pattern.length && pattern.charCodeAt(0) === 33 /*'!'*/
? `!${path.posix.join(base, pattern.slice(1))}`
: path.posix.join(base, pattern)
)
)
}
}
return patterns
}
function ignoreFileToGlobPatterns(
content: string,
filepath: string,
cwd: string
): string[] {
return ignoreFileLinesToGlobPatterns(content.split(/\r?\n/), filepath, cwd)
}
// Based on `@eslint/compat` convertIgnorePatternToMinimatch.
// Apache v2.0 licensed
// Copyright Nicholas C. Zakas
// https://github.com/eslint/rewrite/blob/compat-v1.2.1/packages/compat/src/ignore-file.js#L28
function ignorePatternToMinimatch(pattern: string): string {
const isNegated = pattern.startsWith('!')
const negatedPrefix = isNegated ? '!' : ''
const patternToTest = (isNegated ? pattern.slice(1) : pattern).trimEnd()
// Special cases.
if (
patternToTest === '' ||
patternToTest === '**' ||
patternToTest === '/**' ||
patternToTest === '**'
) {
return `${negatedPrefix}${patternToTest}`
}
const firstIndexOfSlash = patternToTest.indexOf('/')
const matchEverywherePrefix =
firstIndexOfSlash === -1 || firstIndexOfSlash === patternToTest.length - 1
? '**/'
: ''
const patternWithoutLeadingSlash =
firstIndexOfSlash === 0 ? patternToTest.slice(1) : patternToTest
// Escape `{` and `(` because in gitignore patterns they are just
// literal characters without any specific syntactic meaning,
// while in minimatch patterns they can form brace expansion or extglob syntax.
//
// For example, gitignore pattern `src/{a,b}.js` ignores file `src/{a,b}.js`.
// But, the same minimatch pattern `src/{a,b}.js` ignores files `src/a.js` and `src/b.js`.
// Minimatch pattern `src/\{a,b}.js` is equivalent to gitignore pattern `src/{a,b}.js`.
const escapedPatternWithoutLeadingSlash =
patternWithoutLeadingSlash.replaceAll(
/(?=((?:\\.|[^{(])*))\1([{(])/guy,
'$1\\$2'
)
const matchInsideSuffix = patternToTest.endsWith('/**') ? '/*' : ''
return `${negatedPrefix}${matchEverywherePrefix}${escapedPatternWithoutLeadingSlash}${matchInsideSuffix}`
}
function pathsToPatterns(paths: string[]): string[] {
// TODO: Does not support `~/` paths.
return paths.map(p => (p === '.' ? '**/*' : p))
}
export function findBinPathDetailsSync(binName: string): {
name: string
path: string | undefined
shadowed: boolean
} {
let shadowIndex = -1
const bins =
which.sync(binName, {
all: true,
nothrow: true
}) ?? []
let binPath: string | undefined
for (let i = 0, { length } = bins; i < length; i += 1) {
const bin = realpathSync.native(bins[i]!)
// Skip our bin directory if it's in the front.
if (path.dirname(bin) === shadowBinPath) {
shadowIndex = i
} else {
binPath = bin
break
}
}
return { name: binName, path: binPath, shadowed: shadowIndex !== -1 }
}
export function findNpmPathSync(npmBinPath: string): string | undefined {
let thePath = npmBinPath
while (true) {
const nmPath = path.join(thePath, NODE_MODULES)
if (
// npm bin paths may look like:
// /usr/local/share/npm/bin/npm
// /Users/SomeUsername/.nvm/versions/node/vX.X.X/bin/npm
// C:\Users\SomeUsername\AppData\Roaming\npm\bin\npm.cmd
// OR
// C:\Program Files\nodejs\npm.cmd
//
// In all cases the npm path contains a node_modules folder:
// /usr/local/share/npm/bin/npm/node_modules
// C:\Program Files\nodejs\node_modules
//
// Use existsSync here because statsSync, even with { throwIfNoEntry: false },
// will throw an ENOTDIR error for paths like ./a-file-that-exists/a-directory-that-does-not.
// See https://github.com/nodejs/node/issues/56993.
existsSync(nmPath) &&
statSync(nmPath, { throwIfNoEntry: false })?.isDirectory() &&
// Optimistically look for the default location.
(path.basename(thePath) === NPM ||
// Chocolatey installs npm bins in the same directory as node bins.
// Lazily access constants.WIN32.
(constants.WIN32 && existsSync(path.join(thePath, `${NPM}.cmd`))))
) {
return thePath
}
const parent = path.dirname(thePath)
if (parent === thePath) {
return undefined
}
thePath = parent
}
}
export async function getPackageFiles(
cwd: string,
inputPaths: string[],
config: SocketYml | undefined,
supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data']
): Promise<string[]> {
debugLog(`Globbed resolving ${inputPaths.length} paths:`, inputPaths)
const entries = await globWithGitIgnore(pathsToPatterns(inputPaths), {
cwd,
socketConfig: config
})
debugLog(
`Globbed resolved ${inputPaths.length} paths to ${entries.length} paths:`,
entries
)
const packageFiles = await filterGlobResultToSupportedFiles(
entries,
supportedFiles
)
debugLog(
`Mapped ${entries.length} entries to ${packageFiles.length} files:`,
packageFiles
)
return packageFiles
}
export async function getPackageFilesFullScans(
cwd: string,
inputPaths: string[],
supportedFiles: SocketSdkReturnType<'getReportSupportedFiles'>['data'],
debugLog: typeof console.error = () => {}
): Promise<string[]> {
debugLog(`Globbed resolving ${inputPaths.length} paths:`, inputPaths)
const entries = await globWithGitIgnore(pathsToPatterns(inputPaths), {
cwd
})
debugLog(
`Globbed resolved ${inputPaths.length} paths to ${entries.length} paths:`,
entries
)
const packageFiles = await filterGlobResultToSupportedFiles(
entries,
supportedFiles
)
debugLog(
`Mapped ${entries.length} entries to ${packageFiles.length} files:`,
packageFiles
)
return packageFiles
}