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 ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2025 Constructive <developers@constructive.io>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,328 @@
1
+ # git-changed
2
+
3
+ <p align="center">
4
+ <img src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" height="250">
5
+ <br />
6
+ <strong>the files you changed, correctly</strong>
7
+ <br />
8
+ <br />
9
+ Merge-base-scoped changed-file detection for lint gates, incremental checks, and CI scripts — working tree and untracked files included, renames and deletions handled, zero dependencies
10
+ <br />
11
+ <br />
12
+ <a href="https://github.com/constructive-io/dev-utils/actions/workflows/ci.yml">
13
+ <img height="20" src="https://github.com/constructive-io/dev-utils/actions/workflows/ci.yml/badge.svg" />
14
+ </a>
15
+ <a href="https://github.com/constructive-io/dev-utils/blob/main/LICENSE">
16
+ <img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
17
+ </a>
18
+ <a href="https://www.npmjs.com/package/git-changed">
19
+ <img height="20" src="https://img.shields.io/npm/v/git-changed?color=blue"/>
20
+ </a>
21
+ </p>
22
+
23
+ ## Why
24
+
25
+ Every repo eventually grows a tool that should only look at what you changed — a linter, a formatter check, a "is this generated artifact stale?" test. The git plumbing for that is four commands long and easy to get subtly wrong, so it gets re-implemented per tool, slightly differently each time, and the differences are bugs:
26
+
27
+ - `git diff base...HEAD` vs `git merge-base` + `git diff` — get this wrong and commits that landed on `main` after you forked are attributed to your branch.
28
+ - `git status --porcelain` without `-uall` reports a **new directory** as one entry, so every file inside a brand-new module is invisible.
29
+ - Deleted paths come back from `git diff` and then get handed to a tool that stats them and crashes.
30
+ - A rename shows up as an add plus a delete unless you ask for `-M`.
31
+ - On a shallow clone or a detached CI checkout there is no base at all, and a tool that throws there checks nothing.
32
+
33
+ `git-changed` is that plumbing, once, with the sharp edges filed off — as a library for tools and as a CLI for shell and CI.
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ npm install git-changed
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ```typescript
44
+ import { changedFiles } from 'git-changed';
45
+
46
+ const { files, paths, base, source } = changedFiles({ ext: '.sql' });
47
+
48
+ console.log(`${files.length} changed .sql files vs ${base ?? '(no base)'} [${source}]`);
49
+ for (const file of files) {
50
+ console.log(file.status, file.relative);
51
+ }
52
+ ```
53
+
54
+ Only want the paths?
55
+
56
+ ```typescript
57
+ import { changedPaths } from 'git-changed';
58
+
59
+ const paths = changedPaths({ ext: ['.ts', '.tsx'], exclude: ['**/*.d.ts'] });
60
+ ```
61
+
62
+ Asking more than one question about the same repository? `GitChanged` resolves the repo root and base once and takes per-call overrides:
63
+
64
+ ```typescript
65
+ import { GitChanged } from 'git-changed';
66
+
67
+ const changed = new GitChanged({ cwd: repoRoot, exclude: ['dist/', '**/generated/**'] });
68
+
69
+ const sql = changed.paths({ ext: '.sql' });
70
+ const ts = changed.paths({ ext: ['.ts', '.tsx'] });
71
+ const base = changed.base(); // e.g. 'origin/main'
72
+ ```
73
+
74
+ ## CLI
75
+
76
+ ```bash
77
+ $ git-changed --ext .sql
78
+ pgpm-modules/app-scope/deploy/schemas/app_scope/procedures/membership_parent.sql
79
+ pgpm-modules/utils/deploy/schemas/utils/procedures/ensure_singleton.sql
80
+ ```
81
+
82
+ ```
83
+ git-changed [options]
84
+
85
+ --base <ref> Diff against <ref> (default: $GITHUB_BASE_REF, else the
86
+ repository default branch)
87
+ --no-base Working-tree changes only
88
+ --ext <exts> Keep only these extensions (repeatable, comma-separated)
89
+ --include <globs> Keep only paths matching these globs (repeatable)
90
+ --exclude <globs> Drop paths matching these globs (repeatable)
91
+ --within <dirs> Restrict to these directories (repeatable)
92
+ --no-worktree Committed changes only
93
+ --no-untracked Skip untracked files
94
+ --deleted Include paths that no longer exist
95
+ --status Prefix each path with its status
96
+ --absolute Print absolute paths (default: relative to cwd)
97
+ --json Print the full result as JSON
98
+ -0, --null NUL-separate output, for `xargs -0`
99
+ --cwd <dir> Run as if in <dir>
100
+ -h, --help Show this help
101
+ -v, --version Show the version
102
+ ```
103
+
104
+ **Exit code is `0` whether or not anything changed.** An empty list is an answer, not an error — so `git-changed && ...` does not mean what you might hope. Test for empty output, or use `xargs -r`.
105
+
106
+ ## API
107
+
108
+ ### `changedFiles(options?): ChangedResult`
109
+
110
+ ### `changedPaths(options?): string[]`
111
+
112
+ Same options; returns `result.paths`.
113
+
114
+ ### Options
115
+
116
+ | Option | Type | Default | Description |
117
+ |---|---|---|---|
118
+ | `cwd` | `string` | `process.cwd()` | Directory to run in. May be a subdirectory of the repo; results are reported relative to it. |
119
+ | `base` | `string \| false` | resolved (see below) | Ref to diff against. `false` means working tree only. |
120
+ | `ext` | `string \| string[]` | — | Extension filter. `'sql'`, `'.sql'`, `'.ts,.tsx'` and `['.ts', '.tsx']` all work; matching is case-insensitive. |
121
+ | `include` | `string[]` | — | Keep only paths matching these globs. |
122
+ | `exclude` | `string[]` | — | Drop paths matching these globs. Applied after `include`. |
123
+ | `within` | `string[]` | — | Restrict to these directories (cheaper and clearer than a glob when you mean "under here"). |
124
+ | `existingOnly` | `boolean` | `true` | Drop paths that no longer exist on disk. |
125
+ | `worktree` | `boolean` | `true` | Include uncommitted changes. |
126
+ | `untracked` | `boolean` | `true` | Include untracked files (uses `-uall`). |
127
+
128
+ ### `ChangedResult`
129
+
130
+ | Field | Type | Description |
131
+ |---|---|---|
132
+ | `files` | `ChangedFile[]` | The changed files, sorted by path. |
133
+ | `paths` | `string[]` | Absolute paths, same order. |
134
+ | `base` | `string \| undefined` | The ref actually used, after resolution. |
135
+ | `mergeBase` | `string \| undefined` | The resolved merge-base commit, if one was found. |
136
+ | `source` | `'merge-base' \| 'base' \| 'worktree'` | How the answer was produced — see [Degradation](#degradation). |
137
+ | `repoRoot` | `string` | Absolute path to the repository root. |
138
+
139
+ ### `ChangedFile`
140
+
141
+ | Field | Type | Description |
142
+ |---|---|---|
143
+ | `path` | `string` | Absolute path. |
144
+ | `relative` | `string` | Path relative to `cwd`, always `/`-separated. |
145
+ | `status` | `ChangeStatus` | `added`, `modified`, `deleted`, `renamed`, `untracked`, `unknown`. |
146
+ | `from` | `string \| undefined` | For a rename, the previous path. |
147
+ | `committed` | `boolean` | Changed in a commit since the merge base. |
148
+ | `worktree` | `boolean` | Changed in the working tree. Both can be true. |
149
+ | `exists` | `boolean` | Whether the path is on disk (only ever `false` with `existingOnly: false`). |
150
+
151
+ ### Helpers
152
+
153
+ | Export | Description |
154
+ |---|---|
155
+ | `resolveBase(base?, cwd?)` | The base resolution below, on its own. |
156
+ | `defaultBranch(cwd)` | `origin/HEAD`, else the first of `origin/main`, `origin/master`, `main`, `master` that exists. |
157
+ | `repoRoot(cwd)` / `isRepo(cwd)` / `isShallow(cwd)` | Thin git queries. `isShallow` is useful for warning that a diff may be incomplete. |
158
+ | `makeMatcher(patterns, cwd)` | The glob matcher, if you want to filter something else the same way. |
159
+ | `GitChangedError` | Thrown when git is unusable or `cwd` is not a repository. |
160
+
161
+ ## Behavior
162
+
163
+ ### Base resolution
164
+
165
+ In order, first hit wins:
166
+
167
+ 1. `options.base` / `--base <ref>` — explicit always wins.
168
+ 2. `$GITHUB_BASE_REF` as `origin/<ref>`, **if that ref exists locally**. On a pull request GitHub sets this to the target branch. The existence check matters: without it you hand back a ref that every subsequent git call rejects.
169
+ 3. The repository default branch — `origin/HEAD` if set, else the first of `origin/main`, `origin/master`, `main`, `master` that resolves.
170
+
171
+ Then the diff is taken from `git merge-base HEAD <base>`, not from the base tip, so work that landed on the base after you forked is not attributed to you.
172
+
173
+ ### What counts as changed
174
+
175
+ The union of:
176
+
177
+ - committed changes since the merge base (`git diff --name-status -M`), and
178
+ - working-tree changes, staged or not, plus untracked files (`git status --porcelain -uall`).
179
+
180
+ A file in both is one entry with both `committed` and `worktree` true. This union is what makes the same call correct locally (where your work is uncommitted) and in CI (where it is committed) — no branching on environment.
181
+
182
+ ### Degradation
183
+
184
+ `source` reports how the answer was produced, so a caller can decide whether to trust it:
185
+
186
+ | `source` | Meaning |
187
+ |---|---|
188
+ | `merge-base` | Normal: diffed from the merge base of `HEAD` and `base`. |
189
+ | `base` | A base was resolved but no merge base exists — unrelated histories, or a shallow clone that does not reach the fork point. Diffed against the base directly. |
190
+ | `worktree` | No base at all: no `--base`, no `$GITHUB_BASE_REF`, no default branch. Working tree only. |
191
+
192
+ Nothing here throws — a gate that fails open on a detached checkout checks nothing, which is worse than checking a little. Only an unusable git or a non-repository `cwd` raises `GitChangedError`.
193
+
194
+ ### Globs
195
+
196
+ Small deliberate subset, matched against the path relative to `cwd`:
197
+
198
+ | Pattern | Matches |
199
+ |---|---|
200
+ | `dist/` | The `dist` directory and everything under it, at any depth |
201
+ | `/sql/` | Leading slash anchors to `cwd` — root `sql/` only |
202
+ | `*.sql` | Any `.sql` file, at any depth |
203
+ | `pkg/*/deploy` | Exactly one segment for `*` |
204
+ | `**/generated/**` | Any depth |
205
+ | `**/sql/*--*.sql` | e.g. the pgpm bundle artifacts |
206
+
207
+ ## Recipes
208
+
209
+ ### SQL lint gate
210
+
211
+ ```json
212
+ {
213
+ "scripts": {
214
+ "lint:sql:changed": "git-changed --ext .sql --null | xargs -0 -r pgsql-lint"
215
+ }
216
+ }
217
+ ```
218
+
219
+ Or from inside the tool, which is better — it can report *which* base it used:
220
+
221
+ ```typescript
222
+ const { paths, base, source } = changedFiles({ ext: '.sql' });
223
+ if (!paths.length) {
224
+ console.log('no changed SQL');
225
+ process.exit(0);
226
+ }
227
+ if (source === 'worktree') {
228
+ console.warn('no base ref; linting working-tree changes only');
229
+ }
230
+ lint(paths);
231
+ ```
232
+
233
+ ### Is a generated artifact stale?
234
+
235
+ ```typescript
236
+ const changed = new GitChanged({ cwd: moduleDir });
237
+ const deployChanged = changed.paths({ within: ['deploy'], ext: '.sql' }).length > 0;
238
+ const bundleChanged = changed.paths({ within: ['sql'] }).length > 0;
239
+
240
+ if (deployChanged && !bundleChanged) {
241
+ throw new Error(`${moduleName}: deploy/ changed but sql/ was not rebuilt`);
242
+ }
243
+ ```
244
+
245
+ ### Shell
246
+
247
+ ```bash
248
+ # Format only what changed. -r keeps xargs quiet when nothing did.
249
+ git-changed --ext .ts,.tsx --null | xargs -0 -r prettier --check
250
+
251
+ # Review the diff, one file at a time, filenames with spaces and all.
252
+ git-changed --null | xargs -0 -r -n1 git diff --
253
+
254
+ # Branch on emptiness — remember the exit code is always 0.
255
+ if [ -z "$(git-changed --ext .sql)" ]; then echo "no SQL touched"; fi
256
+
257
+ # What kind of change was each one?
258
+ git-changed --status
259
+ ```
260
+
261
+ ### In CI
262
+
263
+ ```yaml
264
+ - uses: actions/checkout@v4
265
+ with:
266
+ fetch-depth: 0 # without this there is no merge base to find
267
+ - run: npx git-changed --ext .sql --status
268
+ ```
269
+
270
+ `fetch-depth: 0` is the one thing worth remembering. `actions/checkout` defaults to a depth-1 clone, which has no merge base with the target branch; `git-changed` then degrades to `source: 'worktree'` and — in CI, where your work is already committed — finds **nothing**. It won't fail; it will just quietly pass. Prefer failing loudly if that matters to you:
271
+
272
+ ```typescript
273
+ const { source } = changedFiles({ ext: '.sql' });
274
+ if (process.env.CI && source === 'worktree') {
275
+ throw new Error('No base ref in CI — is fetch-depth: 0 set?');
276
+ }
277
+ ```
278
+
279
+ ## Troubleshooting
280
+
281
+ | Symptom | Cause |
282
+ |---|---|
283
+ | Empty result in CI, works locally | Shallow clone — set `fetch-depth: 0`. Check `source`. |
284
+ | Files from someone else's merge included | You diffed the base tip somewhere else in your pipeline; this package uses the merge base. Verify with `--json` and look at `mergeBase`. |
285
+ | A new module's files are missing | You're not using this package, or not `-uall`. Untracked files inside a new directory need it. |
286
+ | Tool crashes on a missing path | Something passed `existingOnly: false`. The default drops deleted paths. |
287
+ | `origin/main` not found | `$GITHUB_BASE_REF` was set but unfetched. This package falls through to the local default branch rather than returning a broken ref. |
288
+
289
+ ## License
290
+
291
+ MIT
292
+
293
+ ---
294
+
295
+ ## Development
296
+
297
+ ### Setup
298
+
299
+ 1. Clone the repository:
300
+
301
+ ```bash
302
+ git clone https://github.com/constructive-io/dev-utils.git
303
+ ```
304
+
305
+ 2. Install dependencies:
306
+
307
+ ```bash
308
+ cd dev-utils
309
+ pnpm install
310
+ pnpm build
311
+ ```
312
+
313
+ 3. Test the package of interest:
314
+
315
+ ```bash
316
+ cd packages/<packagename>
317
+ pnpm test:watch
318
+ ```
319
+
320
+ ## Credits
321
+
322
+ **🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
323
+
324
+ ## Disclaimer
325
+
326
+ AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
327
+
328
+ No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
package/base.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ /** The repository's default branch (`origin/main`, `origin/master`, …). */
2
+ export declare function defaultBranch(cwd: string): string | undefined;
3
+ /**
4
+ * Resolve the ref to diff against, in precedence order:
5
+ *
6
+ * 1. an explicit base (`--base`, or `base` in code) — always wins;
7
+ * 2. `$GITHUB_BASE_REF` — the PR's target branch, set by GitHub Actions on
8
+ * `pull_request` events, as `origin/<branch>` since only the remote ref is
9
+ * fetched;
10
+ * 3. the repository's default branch.
11
+ *
12
+ * `undefined` means "no base is available" — a detached checkout, a fresh repo
13
+ * with no remote, or a shallow clone whose base ref was never fetched. Callers
14
+ * fall back to the working tree rather than failing: a gate that cannot see the
15
+ * base should still catch what the author is editing right now.
16
+ */
17
+ export declare function resolveBase(base?: string, cwd?: string): string | undefined;
package/base.js ADDED
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defaultBranch = defaultBranch;
4
+ exports.resolveBase = resolveBase;
5
+ const git_1 = require("./git");
6
+ /**
7
+ * Candidate default branches, in the order git itself would find them. Tried
8
+ * only when the remote HEAD symref is missing — which is the norm in CI, where
9
+ * `actions/checkout` never sets it.
10
+ */
11
+ const FALLBACK_BASES = ['origin/main', 'origin/master', 'main', 'master'];
12
+ /** The repository's default branch (`origin/main`, `origin/master`, …). */
13
+ function defaultBranch(cwd) {
14
+ const head = (0, git_1.tryGit)(['symbolic-ref', 'refs/remotes/origin/HEAD'], cwd)?.trim();
15
+ if (head) {
16
+ // refs/remotes/origin/HEAD → refs/remotes/origin/main → origin/main
17
+ const short = head.replace(/^refs\/remotes\//, '');
18
+ if (short)
19
+ return short;
20
+ }
21
+ return FALLBACK_BASES.find((ref) => (0, git_1.tryGit)(['rev-parse', '--verify', '--quiet', ref], cwd) !== undefined);
22
+ }
23
+ /**
24
+ * Resolve the ref to diff against, in precedence order:
25
+ *
26
+ * 1. an explicit base (`--base`, or `base` in code) — always wins;
27
+ * 2. `$GITHUB_BASE_REF` — the PR's target branch, set by GitHub Actions on
28
+ * `pull_request` events, as `origin/<branch>` since only the remote ref is
29
+ * fetched;
30
+ * 3. the repository's default branch.
31
+ *
32
+ * `undefined` means "no base is available" — a detached checkout, a fresh repo
33
+ * with no remote, or a shallow clone whose base ref was never fetched. Callers
34
+ * fall back to the working tree rather than failing: a gate that cannot see the
35
+ * base should still catch what the author is editing right now.
36
+ */
37
+ function resolveBase(base, cwd = process.cwd()) {
38
+ if (base && base.trim())
39
+ return base.trim();
40
+ const prBase = process.env.GITHUB_BASE_REF;
41
+ if (prBase && prBase.trim()) {
42
+ const ref = `origin/${prBase.trim()}`;
43
+ if ((0, git_1.tryGit)(['rev-parse', '--verify', '--quiet', ref], cwd) !== undefined)
44
+ return ref;
45
+ // The remote ref is missing (a single-branch or shallow fetch). Fall through
46
+ // rather than handing back a ref that every later git call will reject.
47
+ }
48
+ return defaultBranch(cwd);
49
+ }
package/changed.d.ts ADDED
@@ -0,0 +1,49 @@
1
+ import type { ChangedFile, ChangedOptions, ChangedResult } from './types';
2
+ /**
3
+ * Files changed relative to a base ref, unioned with working-tree changes.
4
+ *
5
+ * ```ts
6
+ * changedFiles({ ext: '.sql', exclude: ['**\/generated/**'] });
7
+ * // → { files: [...], paths: [...], base: 'origin/main', source: 'merge-base' }
8
+ * ```
9
+ *
10
+ * Resolution order for the base is `options.base` → `$GITHUB_BASE_REF` → the
11
+ * repository default branch; pass `base: false` to skip it entirely. When no
12
+ * base is available the result falls back to the working tree with
13
+ * `source: 'worktree'` rather than throwing, so a gate still checks what the
14
+ * author is editing on a shallow or detached checkout.
15
+ */
16
+ export declare function changedFiles(options?: ChangedOptions): ChangedResult;
17
+ /** Just the absolute paths — the common case. */
18
+ export declare function changedPaths(options?: ChangedOptions): string[];
19
+ /**
20
+ * Bound to one repository, so a tool that asks several questions resolves the
21
+ * repository root and the base once.
22
+ *
23
+ * ```ts
24
+ * const changed = new GitChanged({ cwd, exclude: ['dist/'] });
25
+ * changed.paths({ ext: '.sql' });
26
+ * changed.paths({ ext: ['.ts', '.tsx'] });
27
+ * ```
28
+ *
29
+ * Options given to the constructor are defaults; options passed to a method
30
+ * override them key by key. Array options replace rather than merge — an
31
+ * `exclude` on a call means "these instead", which is easier to reason about
32
+ * than a growing union.
33
+ */
34
+ export declare class GitChanged {
35
+ private readonly defaults;
36
+ readonly cwd: string;
37
+ constructor(options?: ChangedOptions);
38
+ /** Whether `cwd` is inside a git work tree. */
39
+ isRepo(): boolean;
40
+ /** Absolute path to the repository root. */
41
+ root(): string | undefined;
42
+ /** The base ref this instance would diff against. */
43
+ base(): string | undefined;
44
+ files(options?: ChangedOptions): ChangedFile[];
45
+ paths(options?: ChangedOptions): string[];
46
+ result(options?: ChangedOptions): ChangedResult;
47
+ }
48
+ /** Resolve a path against `cwd`, for callers holding relative paths. */
49
+ export declare function toAbsolute(file: string, cwd?: string): string;