-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracked.ts
More file actions
192 lines (185 loc) · 6.25 KB
/
Copy pathtracked.ts
File metadata and controls
192 lines (185 loc) · 6.25 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
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
/**
* @file Tracked-status + submodule-membership probes for a working-tree path.
* `isTracked` answers "does git track this exact path?"; `getSubmodulePaths`
* lists the repo's submodule mount points; `isInSubmodule` answers "does this
* path live inside one?"; `isUntrackedNonSubmodulePath` composes them into
* the safe-to-touch condition for cleanup tooling — never delete a tracked
* file or reach into a submodule's own tree (which would dirty it).
*/
import { getNodePath } from '../node/path'
import { normalizePath } from '../paths/normalize'
import { ArrayPrototypeSome } from '../primordials/array'
import {
StringPrototypeEndsWith,
StringPrototypeSplit,
StringPrototypeStartsWith,
StringPrototypeTrim,
} from '../primordials/string'
import { spawn } from '../process/spawn/child'
import { getCwd } from './repo'
/**
* The repo's submodule mount points as normalized, repo-root-relative paths
* (e.g. `vendor/acorn`). Reads `git config` on `.gitmodules`, so it lists
* declared submodules whether or not they are initialized — the case a
* stderr-message check on `git ls-files` misses.
*
* @example
* ;```typescript
* await getSubmodulePaths()
* // => ['packages/acorn/upstream/acorn', 'vendor/mbedtls']
* ```
*/
export async function getSubmodulePaths(
options?: GitPathOptions | undefined,
): Promise<string[]> {
const { cwd = getCwd() } = { __proto__: null, ...options } as GitPathOptions
const stdout = await spawn(
'git',
['config', '--file', '.gitmodules', '--get-regexp', 'path'],
{ cwd, stdioString: true },
).then(
/* c8 ignore next - stdioString:true always yields a string stdout; the
?? '' is a defensive fallback that never fires on real spawn output. */
result => String((result as { stdout?: string | undefined })?.stdout ?? ''),
() => '',
)
const lines = StringPrototypeSplit(stdout, '\n')
const paths: string[] = []
for (let i = 0, { length } = lines; i < length; i += 1) {
const line = StringPrototypeTrim(lines[i]!)
/* c8 ignore start - defensive parse guards: `git config --get-regexp`
always emits a `key value` line, so the blank-line and no-space skips
and the empty-value branch never fire on real git output. */
if (!line) {
continue
}
// Each line is `submodule.<name>.path <relative-path>`.
const spaceIdx = line.indexOf(' ')
if (spaceIdx === -1) {
continue
}
const rel = StringPrototypeTrim(line.slice(spaceIdx + 1))
if (!rel) {
continue
}
/* c8 ignore stop */
paths.push(normalizePath(rel))
}
return paths
}
/**
* Whether `targetPath` lives inside one of the repo's submodules. Resolves the
* submodule list itself; for a batch sweep prefer `getSubmodulePaths` once plus
* `pathIsUnderSubmodule` per path.
*
* @example
* ;```typescript
* await isInSubmodule('vendor/mbedtls/x.py') // => true
* await isInSubmodule('src/index.ts') // => false
* ```
*/
export async function isInSubmodule(
targetPath: string,
options?: GitPathOptions | undefined,
): Promise<boolean> {
const submodulePaths = await getSubmodulePaths(options)
if (!submodulePaths.length) {
return false
}
return pathIsUnderSubmodule(targetPath, submodulePaths)
}
export interface GitPathOptions {
/**
* The git working-tree directory the path is resolved against.
*
* @default process.cwd()
*/
cwd?: string | undefined
}
/**
* Whether git tracks `targetPath` exactly. Uses `git ls-files --error-unmatch`,
* which exits non-zero for an untracked path. A path inside a submodule, or one
* git does not know, returns `false`.
*
* @example
* ;```typescript
* await isTracked('src/index.ts') // => true
* await isTracked('.DS_Store') // => false
* ```
*/
export async function isTracked(
targetPath: string,
options?: GitPathOptions | undefined,
): Promise<boolean> {
const { cwd = getCwd() } = { __proto__: null, ...options } as GitPathOptions
return await spawn('git', ['ls-files', '--error-unmatch', targetPath], {
cwd,
stdioString: true,
}).then(
() => true,
() => false,
)
}
/**
* Whether `targetPath` is git does NOT track AND does not live inside a
* submodule — the safe-to-touch condition for cleanup tooling. A tracked path
* is a deliberate file; a submodule-internal path belongs to that submodule's
* own git (touching it would dirty the submodule). Composes `isTracked` +
* `getSubmodulePaths`/`pathIsUnderSubmodule`. Fails closed — any check error
* resolves to `false`.
*
* For a batch sweep, call `getSubmodulePaths` once and compose `isTracked` +
* `pathIsUnderSubmodule` per path to avoid re-reading `.gitmodules` each time.
*
* @example
* ;```typescript
* await isUntrackedNonSubmodulePath('.DS_Store') // => true
* await isUntrackedNonSubmodulePath('src/index.ts') // => false (tracked)
* await isUntrackedNonSubmodulePath('vendor/sub/x.pyc') // => false (submodule)
* ```
*/
export async function isUntrackedNonSubmodulePath(
targetPath: string,
options?: GitPathOptions | undefined,
): Promise<boolean> {
const { cwd = getCwd() } = { __proto__: null, ...options } as GitPathOptions
const tracked = await isTracked(targetPath, { cwd }).catch(() => true)
if (tracked) {
return false
}
const submodulePaths = await getSubmodulePaths({ cwd }).catch(
() => [] as string[],
)
if (submodulePaths.length) {
const path = getNodePath()
const rel = path.relative(cwd, path.resolve(cwd, targetPath))
if (pathIsUnderSubmodule(rel, submodulePaths)) {
return false
}
}
return true
}
/**
* Whether `relativePath` (repo-root-relative) lies at or under any of
* `submodulePaths`. Pure — pass the result of `getSubmodulePaths` so the git
* read happens once for a whole sweep.
*
* @example
* ;```typescript
* pathIsUnderSubmodule('vendor/mbedtls/scripts/__pycache__', ['vendor/mbedtls'])
* // => true
* ```
*/
export function pathIsUnderSubmodule(
relativePath: string,
submodulePaths: string[],
): boolean {
const normalized = normalizePath(relativePath)
return ArrayPrototypeSome(submodulePaths, sub => {
return (
normalized === sub ||
StringPrototypeStartsWith(normalized, `${sub}/`) ||
StringPrototypeEndsWith(sub, normalized)
)
})
}