git-changed 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +328 -0
- package/base.d.ts +17 -0
- package/base.js +49 -0
- package/changed.d.ts +49 -0
- package/changed.js +269 -0
- package/cli.d.ts +14 -0
- package/cli.js +200 -0
- package/esm/base.d.ts +17 -0
- package/esm/base.js +45 -0
- package/esm/changed.d.ts +49 -0
- package/esm/changed.js +262 -0
- package/esm/cli.d.ts +14 -0
- package/esm/cli.js +196 -0
- package/esm/git.d.ts +22 -0
- package/esm/git.js +55 -0
- package/esm/index.d.ts +5 -0
- package/esm/index.js +4 -0
- package/esm/match.d.ts +10 -0
- package/esm/match.js +90 -0
- package/esm/types.d.ts +69 -0
- package/esm/types.js +1 -0
- package/git.d.ts +22 -0
- package/git.js +64 -0
- package/index.d.ts +5 -0
- package/index.js +20 -0
- package/match.d.ts +10 -0
- package/match.js +95 -0
- package/package.json +47 -0
- package/types.d.ts +69 -0
- package/types.js +2 -0
package/esm/changed.js
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { existsSync } from 'fs';
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from 'path';
|
|
3
|
+
import { resolveBase } from './base';
|
|
4
|
+
import { GitChangedError, isRepo, repoRoot, tryGit } from './git';
|
|
5
|
+
import { makeMatcher, normalizeExts, withinAny } from './match';
|
|
6
|
+
/** Map a `git diff --name-status` letter to a status. */
|
|
7
|
+
function diffStatus(code) {
|
|
8
|
+
switch (code[0]) {
|
|
9
|
+
case 'A':
|
|
10
|
+
return 'added';
|
|
11
|
+
case 'M':
|
|
12
|
+
case 'T':
|
|
13
|
+
return 'modified';
|
|
14
|
+
case 'D':
|
|
15
|
+
return 'deleted';
|
|
16
|
+
case 'R':
|
|
17
|
+
case 'C':
|
|
18
|
+
return 'renamed';
|
|
19
|
+
default:
|
|
20
|
+
return 'unknown';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/** Map the two-letter `git status --porcelain` code to a status. */
|
|
24
|
+
function porcelainStatus(code) {
|
|
25
|
+
if (code === '??')
|
|
26
|
+
return 'untracked';
|
|
27
|
+
// Either column can carry the interesting letter: `M ` is staged, ` M` is
|
|
28
|
+
// unstaged, `MM` is both. Prefer the first non-space.
|
|
29
|
+
const letter = code.trim()[0] ?? '';
|
|
30
|
+
switch (letter) {
|
|
31
|
+
case 'A':
|
|
32
|
+
return 'added';
|
|
33
|
+
case 'D':
|
|
34
|
+
return 'deleted';
|
|
35
|
+
case 'R':
|
|
36
|
+
case 'C':
|
|
37
|
+
return 'renamed';
|
|
38
|
+
case 'M':
|
|
39
|
+
case 'T':
|
|
40
|
+
return 'modified';
|
|
41
|
+
default:
|
|
42
|
+
return 'unknown';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Strip git's quoting of paths with unusual characters. */
|
|
46
|
+
function unquote(p) {
|
|
47
|
+
if (!p.startsWith('"'))
|
|
48
|
+
return p;
|
|
49
|
+
const inner = p.slice(1, -1);
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(`"${inner}"`);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return inner;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Merge a path into the accumulator. A path can show up twice — committed
|
|
59
|
+
* against the base *and* modified again in the working tree — so keep the union
|
|
60
|
+
* of the flags and let the later, more specific status win.
|
|
61
|
+
*/
|
|
62
|
+
function record(map, path, next) {
|
|
63
|
+
const prev = map.get(path);
|
|
64
|
+
if (!prev) {
|
|
65
|
+
map.set(path, next);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
map.set(path, {
|
|
69
|
+
// A path deleted in the working tree is deleted, whatever the base said.
|
|
70
|
+
status: next.status === 'deleted' ? 'deleted' : prev.status,
|
|
71
|
+
from: prev.from ?? next.from,
|
|
72
|
+
committed: prev.committed || next.committed,
|
|
73
|
+
worktree: prev.worktree || next.worktree
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/** Committed changes between the merge base (or the base ref) and `HEAD`. */
|
|
77
|
+
function collectCommitted(map, cwd, from) {
|
|
78
|
+
// -M detects renames so the destination is reported instead of an
|
|
79
|
+
// add/delete pair.
|
|
80
|
+
const out = tryGit(['diff', '--name-status', '-M', from, 'HEAD'], cwd) ?? '';
|
|
81
|
+
for (const line of out.split('\n')) {
|
|
82
|
+
if (!line.trim())
|
|
83
|
+
continue;
|
|
84
|
+
const parts = line.split('\t');
|
|
85
|
+
const code = parts[0];
|
|
86
|
+
const status = diffStatus(code);
|
|
87
|
+
if (status === 'renamed' && parts.length >= 3) {
|
|
88
|
+
// R100<TAB>old<TAB>new — the destination is what exists now.
|
|
89
|
+
record(map, unquote(parts[2]), {
|
|
90
|
+
status,
|
|
91
|
+
from: unquote(parts[1]),
|
|
92
|
+
committed: true,
|
|
93
|
+
worktree: false
|
|
94
|
+
});
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
if (parts.length < 2)
|
|
98
|
+
continue;
|
|
99
|
+
record(map, unquote(parts[1]), { status, committed: true, worktree: false });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/** Uncommitted and untracked changes in the working tree. */
|
|
103
|
+
function collectWorktree(map, cwd, untracked) {
|
|
104
|
+
// -uall lists files inside a new directory individually. Without it git
|
|
105
|
+
// reports the directory as a single entry and every file under it is invisible
|
|
106
|
+
// to the caller — the bug this utility exists to stop re-implementing.
|
|
107
|
+
const args = ['status', '--porcelain', untracked ? '-uall' : '-uno'];
|
|
108
|
+
const out = tryGit(args, cwd) ?? '';
|
|
109
|
+
for (const raw of out.split('\n')) {
|
|
110
|
+
const line = raw.replace(/\s+$/, '');
|
|
111
|
+
if (!line)
|
|
112
|
+
continue;
|
|
113
|
+
const code = line.slice(0, 2);
|
|
114
|
+
let path = line.slice(3);
|
|
115
|
+
let from;
|
|
116
|
+
const arrow = path.indexOf(' -> ');
|
|
117
|
+
if (arrow !== -1) {
|
|
118
|
+
from = unquote(path.slice(0, arrow));
|
|
119
|
+
path = path.slice(arrow + 4);
|
|
120
|
+
}
|
|
121
|
+
path = unquote(path);
|
|
122
|
+
if (!path)
|
|
123
|
+
continue;
|
|
124
|
+
record(map, path, {
|
|
125
|
+
status: porcelainStatus(code),
|
|
126
|
+
from,
|
|
127
|
+
committed: false,
|
|
128
|
+
worktree: true
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Files changed relative to a base ref, unioned with working-tree changes.
|
|
134
|
+
*
|
|
135
|
+
* ```ts
|
|
136
|
+
* changedFiles({ ext: '.sql', exclude: ['**\/generated/**'] });
|
|
137
|
+
* // → { files: [...], paths: [...], base: 'origin/main', source: 'merge-base' }
|
|
138
|
+
* ```
|
|
139
|
+
*
|
|
140
|
+
* Resolution order for the base is `options.base` → `$GITHUB_BASE_REF` → the
|
|
141
|
+
* repository default branch; pass `base: false` to skip it entirely. When no
|
|
142
|
+
* base is available the result falls back to the working tree with
|
|
143
|
+
* `source: 'worktree'` rather than throwing, so a gate still checks what the
|
|
144
|
+
* author is editing on a shallow or detached checkout.
|
|
145
|
+
*/
|
|
146
|
+
export function changedFiles(options = {}) {
|
|
147
|
+
const cwd = resolve(options.cwd ?? process.cwd());
|
|
148
|
+
if (!isRepo(cwd)) {
|
|
149
|
+
throw new GitChangedError(`Not a git repository: ${cwd}`);
|
|
150
|
+
}
|
|
151
|
+
const root = repoRoot(cwd) ?? cwd;
|
|
152
|
+
const base = options.base === false ? undefined : resolveBase(options.base, cwd);
|
|
153
|
+
let mergeBase;
|
|
154
|
+
let source = 'worktree';
|
|
155
|
+
if (base) {
|
|
156
|
+
mergeBase = tryGit(['merge-base', 'HEAD', base], cwd)?.trim() || undefined;
|
|
157
|
+
source = mergeBase ? 'merge-base' : 'base';
|
|
158
|
+
}
|
|
159
|
+
const map = new Map();
|
|
160
|
+
// Diff from the merge base, not the branch tip: changes the base picked up
|
|
161
|
+
// since this branch forked are not this branch's changes.
|
|
162
|
+
if (base)
|
|
163
|
+
collectCommitted(map, cwd, mergeBase ?? base);
|
|
164
|
+
if (options.worktree !== false) {
|
|
165
|
+
collectWorktree(map, cwd, options.untracked !== false);
|
|
166
|
+
}
|
|
167
|
+
const exts = normalizeExts(options.ext);
|
|
168
|
+
const included = makeMatcher(options.include ?? [], cwd);
|
|
169
|
+
const hasInclude = (options.include ?? []).filter((p) => p && p.trim()).length > 0;
|
|
170
|
+
const excluded = makeMatcher(options.exclude ?? [], cwd);
|
|
171
|
+
const within = options.within ?? [];
|
|
172
|
+
const existingOnly = options.existingOnly !== false;
|
|
173
|
+
const files = [];
|
|
174
|
+
for (const [gitPath, entry] of map) {
|
|
175
|
+
// git reports paths from the repository root; everything else here is
|
|
176
|
+
// relative to `cwd`, which may be a subdirectory.
|
|
177
|
+
const abs = resolve(root, gitPath);
|
|
178
|
+
const rel = relative(cwd, abs).split(sep).join('/');
|
|
179
|
+
const exists = existsSync(abs);
|
|
180
|
+
if (existingOnly && !exists)
|
|
181
|
+
continue;
|
|
182
|
+
if (exts.length > 0 && !exts.some((e) => abs.toLowerCase().endsWith(e)))
|
|
183
|
+
continue;
|
|
184
|
+
if (!withinAny(abs, within, cwd))
|
|
185
|
+
continue;
|
|
186
|
+
if (hasInclude && !included(abs))
|
|
187
|
+
continue;
|
|
188
|
+
if (excluded(abs))
|
|
189
|
+
continue;
|
|
190
|
+
files.push({
|
|
191
|
+
path: abs,
|
|
192
|
+
relative: rel,
|
|
193
|
+
status: entry.status,
|
|
194
|
+
from: entry.from,
|
|
195
|
+
committed: entry.committed,
|
|
196
|
+
worktree: entry.worktree,
|
|
197
|
+
exists
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
201
|
+
return {
|
|
202
|
+
files,
|
|
203
|
+
paths: files.map((f) => f.path),
|
|
204
|
+
base,
|
|
205
|
+
mergeBase,
|
|
206
|
+
source,
|
|
207
|
+
repoRoot: root
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
/** Just the absolute paths — the common case. */
|
|
211
|
+
export function changedPaths(options = {}) {
|
|
212
|
+
return changedFiles(options).paths;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Bound to one repository, so a tool that asks several questions resolves the
|
|
216
|
+
* repository root and the base once.
|
|
217
|
+
*
|
|
218
|
+
* ```ts
|
|
219
|
+
* const changed = new GitChanged({ cwd, exclude: ['dist/'] });
|
|
220
|
+
* changed.paths({ ext: '.sql' });
|
|
221
|
+
* changed.paths({ ext: ['.ts', '.tsx'] });
|
|
222
|
+
* ```
|
|
223
|
+
*
|
|
224
|
+
* Options given to the constructor are defaults; options passed to a method
|
|
225
|
+
* override them key by key. Array options replace rather than merge — an
|
|
226
|
+
* `exclude` on a call means "these instead", which is easier to reason about
|
|
227
|
+
* than a growing union.
|
|
228
|
+
*/
|
|
229
|
+
export class GitChanged {
|
|
230
|
+
defaults;
|
|
231
|
+
cwd;
|
|
232
|
+
constructor(options = {}) {
|
|
233
|
+
this.cwd = resolve(options.cwd ?? process.cwd());
|
|
234
|
+
this.defaults = { ...options, cwd: this.cwd };
|
|
235
|
+
}
|
|
236
|
+
/** Whether `cwd` is inside a git work tree. */
|
|
237
|
+
isRepo() {
|
|
238
|
+
return isRepo(this.cwd);
|
|
239
|
+
}
|
|
240
|
+
/** Absolute path to the repository root. */
|
|
241
|
+
root() {
|
|
242
|
+
return repoRoot(this.cwd);
|
|
243
|
+
}
|
|
244
|
+
/** The base ref this instance would diff against. */
|
|
245
|
+
base() {
|
|
246
|
+
const base = this.defaults.base;
|
|
247
|
+
return base === false ? undefined : resolveBase(base, this.cwd);
|
|
248
|
+
}
|
|
249
|
+
files(options = {}) {
|
|
250
|
+
return this.result(options).files;
|
|
251
|
+
}
|
|
252
|
+
paths(options = {}) {
|
|
253
|
+
return this.result(options).paths;
|
|
254
|
+
}
|
|
255
|
+
result(options = {}) {
|
|
256
|
+
return changedFiles({ ...this.defaults, ...options, cwd: this.cwd });
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/** Resolve a path against `cwd`, for callers holding relative paths. */
|
|
260
|
+
export function toAbsolute(file, cwd = process.cwd()) {
|
|
261
|
+
return isAbsolute(file) ? file : resolve(cwd, file);
|
|
262
|
+
}
|
package/esm/cli.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import type { ChangedOptions } from './types';
|
|
3
|
+
interface Parsed {
|
|
4
|
+
options: ChangedOptions;
|
|
5
|
+
status: boolean;
|
|
6
|
+
absolute: boolean;
|
|
7
|
+
json: boolean;
|
|
8
|
+
nul: boolean;
|
|
9
|
+
help: boolean;
|
|
10
|
+
version: boolean;
|
|
11
|
+
}
|
|
12
|
+
export declare function parseArgs(argv: string[]): Parsed;
|
|
13
|
+
export declare function run(argv?: string[]): number;
|
|
14
|
+
export {};
|
package/esm/cli.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { changedFiles } from './changed';
|
|
3
|
+
import { GitChangedError } from './git';
|
|
4
|
+
const USAGE = `git-changed — list files changed against the merge base
|
|
5
|
+
|
|
6
|
+
Usage:
|
|
7
|
+
git-changed [options]
|
|
8
|
+
|
|
9
|
+
Options:
|
|
10
|
+
--base <ref> Diff against <ref> (default: $GITHUB_BASE_REF, else the
|
|
11
|
+
repository default branch)
|
|
12
|
+
--no-base Working-tree changes only
|
|
13
|
+
--ext <exts> Keep only these extensions (repeatable, comma-separated)
|
|
14
|
+
--include <globs> Keep only paths matching these globs (repeatable)
|
|
15
|
+
--exclude <globs> Drop paths matching these globs (repeatable)
|
|
16
|
+
--within <dirs> Restrict to these directories (repeatable)
|
|
17
|
+
--no-worktree Committed changes only
|
|
18
|
+
--no-untracked Skip untracked files
|
|
19
|
+
--deleted Include paths that no longer exist
|
|
20
|
+
--status Prefix each path with its status
|
|
21
|
+
--absolute Print absolute paths (default: relative to cwd)
|
|
22
|
+
--json Print the full result as JSON
|
|
23
|
+
-0, --null NUL-separate output, for \`xargs -0\`
|
|
24
|
+
--cwd <dir> Run as if in <dir>
|
|
25
|
+
-h, --help Show this help
|
|
26
|
+
-v, --version Show the version
|
|
27
|
+
|
|
28
|
+
Exit code is 0 whether or not anything changed; an empty list is an answer, not
|
|
29
|
+
an error. Use --json (or test for empty output) to branch on it.
|
|
30
|
+
|
|
31
|
+
Examples:
|
|
32
|
+
git-changed --ext .sql --exclude 'dist/' '**/generated/**'
|
|
33
|
+
git-changed --ext .ts --null | xargs -0 -r prettier --check
|
|
34
|
+
git-changed --base origin/develop --status`;
|
|
35
|
+
function packageVersion() {
|
|
36
|
+
// The CLI sits in dist/ in the repo but at the package root once published,
|
|
37
|
+
// so the manifest is one directory up in one layout and alongside in the other.
|
|
38
|
+
for (const candidate of ['../package.json', './package.json']) {
|
|
39
|
+
try {
|
|
40
|
+
return require(candidate).version;
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Wrong layout; try the next candidate.
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return 'unknown';
|
|
47
|
+
}
|
|
48
|
+
/** Split repeatable, comma-separated list values: `--ext .ts,.tsx --ext .mts`. */
|
|
49
|
+
function pushList(target, value) {
|
|
50
|
+
for (const part of value.split(',')) {
|
|
51
|
+
const trimmed = part.trim();
|
|
52
|
+
if (trimmed)
|
|
53
|
+
target.push(trimmed);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
export function parseArgs(argv) {
|
|
57
|
+
const ext = [];
|
|
58
|
+
const include = [];
|
|
59
|
+
const exclude = [];
|
|
60
|
+
const within = [];
|
|
61
|
+
const options = {};
|
|
62
|
+
const parsed = {
|
|
63
|
+
options,
|
|
64
|
+
status: false,
|
|
65
|
+
absolute: false,
|
|
66
|
+
json: false,
|
|
67
|
+
nul: false,
|
|
68
|
+
help: false,
|
|
69
|
+
version: false
|
|
70
|
+
};
|
|
71
|
+
for (let i = 0; i < argv.length; i++) {
|
|
72
|
+
const arg = argv[i];
|
|
73
|
+
// Accept both `--ext .sql` and `--ext=.sql`.
|
|
74
|
+
const eq = arg.indexOf('=');
|
|
75
|
+
const flag = arg.startsWith('--') && eq !== -1 ? arg.slice(0, eq) : arg;
|
|
76
|
+
const inline = arg.startsWith('--') && eq !== -1 ? arg.slice(eq + 1) : undefined;
|
|
77
|
+
const next = () => {
|
|
78
|
+
const value = inline ?? argv[++i];
|
|
79
|
+
if (value === undefined) {
|
|
80
|
+
throw new GitChangedError(`${flag} requires a value`);
|
|
81
|
+
}
|
|
82
|
+
return value;
|
|
83
|
+
};
|
|
84
|
+
switch (flag) {
|
|
85
|
+
case '-h':
|
|
86
|
+
case '--help':
|
|
87
|
+
parsed.help = true;
|
|
88
|
+
break;
|
|
89
|
+
case '-v':
|
|
90
|
+
case '--version':
|
|
91
|
+
parsed.version = true;
|
|
92
|
+
break;
|
|
93
|
+
case '--base':
|
|
94
|
+
options.base = next();
|
|
95
|
+
break;
|
|
96
|
+
case '--no-base':
|
|
97
|
+
options.base = false;
|
|
98
|
+
break;
|
|
99
|
+
case '--ext':
|
|
100
|
+
pushList(ext, next());
|
|
101
|
+
break;
|
|
102
|
+
case '--include':
|
|
103
|
+
pushList(include, next());
|
|
104
|
+
break;
|
|
105
|
+
case '--exclude':
|
|
106
|
+
pushList(exclude, next());
|
|
107
|
+
break;
|
|
108
|
+
case '--within':
|
|
109
|
+
pushList(within, next());
|
|
110
|
+
break;
|
|
111
|
+
case '--cwd':
|
|
112
|
+
options.cwd = next();
|
|
113
|
+
break;
|
|
114
|
+
case '--no-worktree':
|
|
115
|
+
options.worktree = false;
|
|
116
|
+
break;
|
|
117
|
+
case '--no-untracked':
|
|
118
|
+
options.untracked = false;
|
|
119
|
+
break;
|
|
120
|
+
case '--deleted':
|
|
121
|
+
options.existingOnly = false;
|
|
122
|
+
break;
|
|
123
|
+
case '--status':
|
|
124
|
+
parsed.status = true;
|
|
125
|
+
break;
|
|
126
|
+
case '--absolute':
|
|
127
|
+
parsed.absolute = true;
|
|
128
|
+
break;
|
|
129
|
+
case '--json':
|
|
130
|
+
parsed.json = true;
|
|
131
|
+
break;
|
|
132
|
+
case '-0':
|
|
133
|
+
case '--null':
|
|
134
|
+
parsed.nul = true;
|
|
135
|
+
break;
|
|
136
|
+
default:
|
|
137
|
+
throw new GitChangedError(`Unknown option: ${arg}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (ext.length)
|
|
141
|
+
options.ext = ext;
|
|
142
|
+
if (include.length)
|
|
143
|
+
options.include = include;
|
|
144
|
+
if (exclude.length)
|
|
145
|
+
options.exclude = exclude;
|
|
146
|
+
if (within.length)
|
|
147
|
+
options.within = within;
|
|
148
|
+
return parsed;
|
|
149
|
+
}
|
|
150
|
+
export function run(argv = process.argv.slice(2)) {
|
|
151
|
+
let parsed;
|
|
152
|
+
try {
|
|
153
|
+
parsed = parseArgs(argv);
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
157
|
+
console.error(`\n${USAGE}`);
|
|
158
|
+
return 2;
|
|
159
|
+
}
|
|
160
|
+
if (parsed.help) {
|
|
161
|
+
console.log(USAGE);
|
|
162
|
+
return 0;
|
|
163
|
+
}
|
|
164
|
+
if (parsed.version) {
|
|
165
|
+
console.log(packageVersion());
|
|
166
|
+
return 0;
|
|
167
|
+
}
|
|
168
|
+
let result;
|
|
169
|
+
try {
|
|
170
|
+
result = changedFiles(parsed.options);
|
|
171
|
+
}
|
|
172
|
+
catch (err) {
|
|
173
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
174
|
+
return 1;
|
|
175
|
+
}
|
|
176
|
+
if (parsed.json) {
|
|
177
|
+
console.log(JSON.stringify(result, null, 2));
|
|
178
|
+
return 0;
|
|
179
|
+
}
|
|
180
|
+
const lines = result.files.map((f) => {
|
|
181
|
+
const path = parsed.absolute ? f.path : f.relative;
|
|
182
|
+
return parsed.status ? `${f.status}\t${path}` : path;
|
|
183
|
+
});
|
|
184
|
+
if (parsed.nul) {
|
|
185
|
+
// No trailing newline: xargs -0 splits on NUL, and a stray newline would
|
|
186
|
+
// become part of the last filename.
|
|
187
|
+
process.stdout.write(lines.map((l) => `${l}\0`).join(''));
|
|
188
|
+
}
|
|
189
|
+
else if (lines.length) {
|
|
190
|
+
process.stdout.write(`${lines.join('\n')}\n`);
|
|
191
|
+
}
|
|
192
|
+
return 0;
|
|
193
|
+
}
|
|
194
|
+
if (require.main === module) {
|
|
195
|
+
process.exit(run());
|
|
196
|
+
}
|
package/esm/git.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Thrown when git itself is unusable: not installed, or `cwd` is not a repo. */
|
|
2
|
+
export declare class GitChangedError extends Error {
|
|
3
|
+
constructor(message: string);
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Run git and return stdout. Arguments are passed as an array — never a shell
|
|
7
|
+
* string — so a branch name like `feat/it's-fine` cannot become a shell quoting
|
|
8
|
+
* bug.
|
|
9
|
+
*/
|
|
10
|
+
export declare function git(args: string[], cwd: string): string;
|
|
11
|
+
/**
|
|
12
|
+
* Run git, returning `undefined` instead of throwing. For the probes where
|
|
13
|
+
* failure is a legitimate answer: a ref that does not exist, a shallow clone
|
|
14
|
+
* with no merge base, a directory that is not a repository.
|
|
15
|
+
*/
|
|
16
|
+
export declare function tryGit(args: string[], cwd: string): string | undefined;
|
|
17
|
+
/** Absolute path to the repository root, or `undefined` outside a repository. */
|
|
18
|
+
export declare function repoRoot(cwd: string): string | undefined;
|
|
19
|
+
/** Whether `cwd` is inside a git work tree. */
|
|
20
|
+
export declare function isRepo(cwd: string): boolean;
|
|
21
|
+
/** Whether the repository is a shallow clone (no merge base to be had). */
|
|
22
|
+
export declare function isShallow(cwd: string): boolean;
|
package/esm/git.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { spawnSync } from 'child_process';
|
|
2
|
+
/** Thrown when git itself is unusable: not installed, or `cwd` is not a repo. */
|
|
3
|
+
export class GitChangedError extends Error {
|
|
4
|
+
constructor(message) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.name = 'GitChangedError';
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Run git and return stdout. Arguments are passed as an array — never a shell
|
|
11
|
+
* string — so a branch name like `feat/it's-fine` cannot become a shell quoting
|
|
12
|
+
* bug.
|
|
13
|
+
*/
|
|
14
|
+
export function git(args, cwd) {
|
|
15
|
+
const result = spawnSync('git', args, {
|
|
16
|
+
cwd,
|
|
17
|
+
encoding: 'utf8',
|
|
18
|
+
// A monorepo diff can be large, and the default 1 MB cap truncates it
|
|
19
|
+
// *silently* — which reads as "nothing changed" rather than an error.
|
|
20
|
+
maxBuffer: 64 * 1024 * 1024
|
|
21
|
+
});
|
|
22
|
+
if (result.error) {
|
|
23
|
+
throw new GitChangedError(`git ${args[0]} failed: ${result.error.message}`);
|
|
24
|
+
}
|
|
25
|
+
if (result.status !== 0) {
|
|
26
|
+
const stderr = (result.stderr ?? '').trim();
|
|
27
|
+
throw new GitChangedError(`git ${args.join(' ')} exited ${result.status}${stderr ? `: ${stderr}` : ''}`);
|
|
28
|
+
}
|
|
29
|
+
return result.stdout ?? '';
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Run git, returning `undefined` instead of throwing. For the probes where
|
|
33
|
+
* failure is a legitimate answer: a ref that does not exist, a shallow clone
|
|
34
|
+
* with no merge base, a directory that is not a repository.
|
|
35
|
+
*/
|
|
36
|
+
export function tryGit(args, cwd) {
|
|
37
|
+
try {
|
|
38
|
+
return git(args, cwd);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/** Absolute path to the repository root, or `undefined` outside a repository. */
|
|
45
|
+
export function repoRoot(cwd) {
|
|
46
|
+
return tryGit(['rev-parse', '--show-toplevel'], cwd)?.trim() || undefined;
|
|
47
|
+
}
|
|
48
|
+
/** Whether `cwd` is inside a git work tree. */
|
|
49
|
+
export function isRepo(cwd) {
|
|
50
|
+
return tryGit(['rev-parse', '--is-inside-work-tree'], cwd)?.trim() === 'true';
|
|
51
|
+
}
|
|
52
|
+
/** Whether the repository is a shallow clone (no merge base to be had). */
|
|
53
|
+
export function isShallow(cwd) {
|
|
54
|
+
return tryGit(['rev-parse', '--is-shallow-repository'], cwd)?.trim() === 'true';
|
|
55
|
+
}
|
package/esm/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { defaultBranch, resolveBase } from './base';
|
|
2
|
+
export { changedFiles, changedPaths, GitChanged, toAbsolute } from './changed';
|
|
3
|
+
export { GitChangedError, isRepo, isShallow, repoRoot } from './git';
|
|
4
|
+
export { makeMatcher, normalizeExts, withinAny } from './match';
|
|
5
|
+
export type { ChangedFile, ChangedOptions, ChangedResult, ChangedSource, ChangeStatus } from './types';
|
package/esm/index.js
ADDED
package/esm/match.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compile patterns into a predicate. An empty pattern list matches nothing, so
|
|
3
|
+
* `exclude: []` excludes nothing and `include: []` is treated as "no include
|
|
4
|
+
* filter" by the caller rather than "include nothing".
|
|
5
|
+
*/
|
|
6
|
+
export declare function makeMatcher(patterns?: string[], cwd?: string): (file: string) => boolean;
|
|
7
|
+
/** `true` when `file` is inside one of `dirs` (or `dirs` is empty). */
|
|
8
|
+
export declare function withinAny(file: string, dirs: string[], cwd: string): boolean;
|
|
9
|
+
/** Normalize `.sql` / `sql` / `['.sql','.psql']` into a `.ext` list. */
|
|
10
|
+
export declare function normalizeExts(ext?: string | string[]): string[];
|
package/esm/match.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { isAbsolute, relative, resolve, sep } from 'path';
|
|
2
|
+
/**
|
|
3
|
+
* Gitignore-flavoured glob matching, deliberately not a full glob engine — the
|
|
4
|
+
* patterns these tools carry are `dist/`, `**\/generated/**`, `*.sql`, and the
|
|
5
|
+
* occasional `packages/*\/deploy`. Supported:
|
|
6
|
+
*
|
|
7
|
+
* - `*` — any run of characters within one path segment
|
|
8
|
+
* - `**` — any run of segments
|
|
9
|
+
* - `?` — exactly one character
|
|
10
|
+
* - a plain path (`sql/`, `dist`) matches that path *and everything under it*
|
|
11
|
+
* - an unanchored pattern matches at any segment boundary (`generated/`
|
|
12
|
+
* matches `a/b/generated/c.sql`)
|
|
13
|
+
* - a leading `/` anchors the pattern to `cwd`
|
|
14
|
+
*/
|
|
15
|
+
function toRegExp(pattern) {
|
|
16
|
+
const anchored = pattern.startsWith('/');
|
|
17
|
+
let body = anchored ? pattern.slice(1) : pattern;
|
|
18
|
+
// A trailing slash is a directory marker; the subtree suffix below covers it.
|
|
19
|
+
body = body.replace(/\/+$/, '');
|
|
20
|
+
let source = '';
|
|
21
|
+
for (let i = 0; i < body.length; i++) {
|
|
22
|
+
const ch = body[i];
|
|
23
|
+
if (ch === '*') {
|
|
24
|
+
if (body[i + 1] === '*') {
|
|
25
|
+
// `**/` spans zero or more segments; a bare `**` spans anything.
|
|
26
|
+
if (body[i + 2] === '/') {
|
|
27
|
+
source += '(?:[^/]+/)*';
|
|
28
|
+
i += 2;
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
source += '.*';
|
|
32
|
+
i += 1;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
source += '[^/]*';
|
|
37
|
+
}
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
if (ch === '?') {
|
|
41
|
+
source += '[^/]';
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
source += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
|
|
45
|
+
}
|
|
46
|
+
// Match the path itself or anything beneath it, so `sql/` excludes the tree.
|
|
47
|
+
const tail = '(?:/.*)?$';
|
|
48
|
+
return new RegExp(anchored ? `^${source}${tail}` : `^(?:.*/)?${source}${tail}`);
|
|
49
|
+
}
|
|
50
|
+
/** Normalize to a `/`-separated path relative to `cwd`, for matching. */
|
|
51
|
+
function toRelative(file, cwd) {
|
|
52
|
+
const abs = isAbsolute(file) ? file : resolve(cwd, file);
|
|
53
|
+
return relative(cwd, abs).split(sep).join('/');
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Compile patterns into a predicate. An empty pattern list matches nothing, so
|
|
57
|
+
* `exclude: []` excludes nothing and `include: []` is treated as "no include
|
|
58
|
+
* filter" by the caller rather than "include nothing".
|
|
59
|
+
*/
|
|
60
|
+
export function makeMatcher(patterns = [], cwd = process.cwd()) {
|
|
61
|
+
const regexes = patterns.filter((p) => p && p.trim()).map((p) => toRegExp(p.trim()));
|
|
62
|
+
if (regexes.length === 0)
|
|
63
|
+
return () => false;
|
|
64
|
+
return (file) => {
|
|
65
|
+
const rel = toRelative(file, cwd);
|
|
66
|
+
return regexes.some((re) => re.test(rel));
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
/** `true` when `file` is inside one of `dirs` (or `dirs` is empty). */
|
|
70
|
+
export function withinAny(file, dirs, cwd) {
|
|
71
|
+
if (dirs.length === 0)
|
|
72
|
+
return true;
|
|
73
|
+
const abs = isAbsolute(file) ? file : resolve(cwd, file);
|
|
74
|
+
return dirs.some((dir) => {
|
|
75
|
+
const root = isAbsolute(dir) ? dir : resolve(cwd, dir);
|
|
76
|
+
if (abs === root)
|
|
77
|
+
return true;
|
|
78
|
+
return abs.startsWith(root.endsWith(sep) ? root : root + sep);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
/** Normalize `.sql` / `sql` / `['.sql','.psql']` into a `.ext` list. */
|
|
82
|
+
export function normalizeExts(ext) {
|
|
83
|
+
const list = Array.isArray(ext) ? ext : ext ? [ext] : [];
|
|
84
|
+
return list
|
|
85
|
+
.flatMap((e) => e.split(','))
|
|
86
|
+
.map((e) => e.trim())
|
|
87
|
+
.filter(Boolean)
|
|
88
|
+
.map((e) => (e.startsWith('.') ? e : `.${e}`))
|
|
89
|
+
.map((e) => e.toLowerCase());
|
|
90
|
+
}
|