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/esm/types.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * How a file came to be in the changed set. `deleted` and `renamed` are the two
3
+ * a naive implementation gets wrong: linting a path that no longer exists is a
4
+ * crash, and a rename must be reported at its *destination*.
5
+ */
6
+ export type ChangeStatus = 'added' | 'modified' | 'deleted' | 'renamed' | 'untracked' | 'unknown';
7
+ export interface ChangedFile {
8
+ /** Absolute path. */
9
+ path: string;
10
+ /** Path relative to `cwd`, `/`-separated — what you print. */
11
+ relative: string;
12
+ status: ChangeStatus;
13
+ /** For a rename, the path it came from. */
14
+ from?: string;
15
+ /** Present in the diff against the base. */
16
+ committed: boolean;
17
+ /** Present in `git status` — uncommitted or untracked. */
18
+ worktree: boolean;
19
+ /** Whether the path exists on disk right now. */
20
+ exists: boolean;
21
+ }
22
+ /** Where the committed half of the set came from. */
23
+ export type ChangedSource =
24
+ /** `merge-base HEAD <base>` — the normal PR case. */
25
+ 'merge-base'
26
+ /** The base ref exists but has no merge base with HEAD (unrelated history). */
27
+ | 'base'
28
+ /** No base at all: working-tree changes only (shallow, detached, no remote). */
29
+ | 'worktree';
30
+ export interface ChangedOptions {
31
+ /** Directory to resolve from and report relative to. Default `process.cwd()`. */
32
+ cwd?: string;
33
+ /**
34
+ * Ref to diff against. Omit to auto-resolve (`$GITHUB_BASE_REF` → default
35
+ * branch); pass `false` for working-tree changes only.
36
+ */
37
+ base?: string | false;
38
+ /** Keep only these extensions, e.g. `'.sql'` or `['.sql', '.psql']`. */
39
+ ext?: string | string[];
40
+ /** Keep only paths matching these globs. */
41
+ include?: string[];
42
+ /** Drop paths matching these globs — generated trees, `dist/`, fixtures. */
43
+ exclude?: string[];
44
+ /**
45
+ * Restrict to these directories. Cheaper and more predictable than an
46
+ * `include` glob when you already know the subtree (a package dir, a CLI's
47
+ * positional paths).
48
+ */
49
+ within?: string[];
50
+ /** Drop paths that no longer exist. Default `true`. */
51
+ existingOnly?: boolean;
52
+ /** Include uncommitted/untracked working-tree changes. Default `true`. */
53
+ worktree?: boolean;
54
+ /** Include untracked files. Default `true`; ignored when `worktree` is false. */
55
+ untracked?: boolean;
56
+ }
57
+ export interface ChangedResult {
58
+ /** The changed files, sorted by path, after filtering. */
59
+ files: ChangedFile[];
60
+ /** Absolute paths — the common case, so you don't map every call site. */
61
+ paths: string[];
62
+ /** The base that was used, if any. */
63
+ base?: string;
64
+ /** The resolved merge-base commit, if one was found. */
65
+ mergeBase?: string;
66
+ source: ChangedSource;
67
+ /** Absolute path to the repository root. */
68
+ repoRoot: string;
69
+ }
package/esm/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/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/git.js ADDED
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GitChangedError = void 0;
4
+ exports.git = git;
5
+ exports.tryGit = tryGit;
6
+ exports.repoRoot = repoRoot;
7
+ exports.isRepo = isRepo;
8
+ exports.isShallow = isShallow;
9
+ const child_process_1 = require("child_process");
10
+ /** Thrown when git itself is unusable: not installed, or `cwd` is not a repo. */
11
+ class GitChangedError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = 'GitChangedError';
15
+ }
16
+ }
17
+ exports.GitChangedError = GitChangedError;
18
+ /**
19
+ * Run git and return stdout. Arguments are passed as an array — never a shell
20
+ * string — so a branch name like `feat/it's-fine` cannot become a shell quoting
21
+ * bug.
22
+ */
23
+ function git(args, cwd) {
24
+ const result = (0, child_process_1.spawnSync)('git', args, {
25
+ cwd,
26
+ encoding: 'utf8',
27
+ // A monorepo diff can be large, and the default 1 MB cap truncates it
28
+ // *silently* — which reads as "nothing changed" rather than an error.
29
+ maxBuffer: 64 * 1024 * 1024
30
+ });
31
+ if (result.error) {
32
+ throw new GitChangedError(`git ${args[0]} failed: ${result.error.message}`);
33
+ }
34
+ if (result.status !== 0) {
35
+ const stderr = (result.stderr ?? '').trim();
36
+ throw new GitChangedError(`git ${args.join(' ')} exited ${result.status}${stderr ? `: ${stderr}` : ''}`);
37
+ }
38
+ return result.stdout ?? '';
39
+ }
40
+ /**
41
+ * Run git, returning `undefined` instead of throwing. For the probes where
42
+ * failure is a legitimate answer: a ref that does not exist, a shallow clone
43
+ * with no merge base, a directory that is not a repository.
44
+ */
45
+ function tryGit(args, cwd) {
46
+ try {
47
+ return git(args, cwd);
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ }
53
+ /** Absolute path to the repository root, or `undefined` outside a repository. */
54
+ function repoRoot(cwd) {
55
+ return tryGit(['rev-parse', '--show-toplevel'], cwd)?.trim() || undefined;
56
+ }
57
+ /** Whether `cwd` is inside a git work tree. */
58
+ function isRepo(cwd) {
59
+ return tryGit(['rev-parse', '--is-inside-work-tree'], cwd)?.trim() === 'true';
60
+ }
61
+ /** Whether the repository is a shallow clone (no merge base to be had). */
62
+ function isShallow(cwd) {
63
+ return tryGit(['rev-parse', '--is-shallow-repository'], cwd)?.trim() === 'true';
64
+ }
package/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/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withinAny = exports.normalizeExts = exports.makeMatcher = exports.repoRoot = exports.isShallow = exports.isRepo = exports.GitChangedError = exports.toAbsolute = exports.GitChanged = exports.changedPaths = exports.changedFiles = exports.resolveBase = exports.defaultBranch = void 0;
4
+ var base_1 = require("./base");
5
+ Object.defineProperty(exports, "defaultBranch", { enumerable: true, get: function () { return base_1.defaultBranch; } });
6
+ Object.defineProperty(exports, "resolveBase", { enumerable: true, get: function () { return base_1.resolveBase; } });
7
+ var changed_1 = require("./changed");
8
+ Object.defineProperty(exports, "changedFiles", { enumerable: true, get: function () { return changed_1.changedFiles; } });
9
+ Object.defineProperty(exports, "changedPaths", { enumerable: true, get: function () { return changed_1.changedPaths; } });
10
+ Object.defineProperty(exports, "GitChanged", { enumerable: true, get: function () { return changed_1.GitChanged; } });
11
+ Object.defineProperty(exports, "toAbsolute", { enumerable: true, get: function () { return changed_1.toAbsolute; } });
12
+ var git_1 = require("./git");
13
+ Object.defineProperty(exports, "GitChangedError", { enumerable: true, get: function () { return git_1.GitChangedError; } });
14
+ Object.defineProperty(exports, "isRepo", { enumerable: true, get: function () { return git_1.isRepo; } });
15
+ Object.defineProperty(exports, "isShallow", { enumerable: true, get: function () { return git_1.isShallow; } });
16
+ Object.defineProperty(exports, "repoRoot", { enumerable: true, get: function () { return git_1.repoRoot; } });
17
+ var match_1 = require("./match");
18
+ Object.defineProperty(exports, "makeMatcher", { enumerable: true, get: function () { return match_1.makeMatcher; } });
19
+ Object.defineProperty(exports, "normalizeExts", { enumerable: true, get: function () { return match_1.normalizeExts; } });
20
+ Object.defineProperty(exports, "withinAny", { enumerable: true, get: function () { return match_1.withinAny; } });
package/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/match.js ADDED
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeMatcher = makeMatcher;
4
+ exports.withinAny = withinAny;
5
+ exports.normalizeExts = normalizeExts;
6
+ const path_1 = require("path");
7
+ /**
8
+ * Gitignore-flavoured glob matching, deliberately not a full glob engine — the
9
+ * patterns these tools carry are `dist/`, `**\/generated/**`, `*.sql`, and the
10
+ * occasional `packages/*\/deploy`. Supported:
11
+ *
12
+ * - `*` — any run of characters within one path segment
13
+ * - `**` — any run of segments
14
+ * - `?` — exactly one character
15
+ * - a plain path (`sql/`, `dist`) matches that path *and everything under it*
16
+ * - an unanchored pattern matches at any segment boundary (`generated/`
17
+ * matches `a/b/generated/c.sql`)
18
+ * - a leading `/` anchors the pattern to `cwd`
19
+ */
20
+ function toRegExp(pattern) {
21
+ const anchored = pattern.startsWith('/');
22
+ let body = anchored ? pattern.slice(1) : pattern;
23
+ // A trailing slash is a directory marker; the subtree suffix below covers it.
24
+ body = body.replace(/\/+$/, '');
25
+ let source = '';
26
+ for (let i = 0; i < body.length; i++) {
27
+ const ch = body[i];
28
+ if (ch === '*') {
29
+ if (body[i + 1] === '*') {
30
+ // `**/` spans zero or more segments; a bare `**` spans anything.
31
+ if (body[i + 2] === '/') {
32
+ source += '(?:[^/]+/)*';
33
+ i += 2;
34
+ }
35
+ else {
36
+ source += '.*';
37
+ i += 1;
38
+ }
39
+ }
40
+ else {
41
+ source += '[^/]*';
42
+ }
43
+ continue;
44
+ }
45
+ if (ch === '?') {
46
+ source += '[^/]';
47
+ continue;
48
+ }
49
+ source += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
50
+ }
51
+ // Match the path itself or anything beneath it, so `sql/` excludes the tree.
52
+ const tail = '(?:/.*)?$';
53
+ return new RegExp(anchored ? `^${source}${tail}` : `^(?:.*/)?${source}${tail}`);
54
+ }
55
+ /** Normalize to a `/`-separated path relative to `cwd`, for matching. */
56
+ function toRelative(file, cwd) {
57
+ const abs = (0, path_1.isAbsolute)(file) ? file : (0, path_1.resolve)(cwd, file);
58
+ return (0, path_1.relative)(cwd, abs).split(path_1.sep).join('/');
59
+ }
60
+ /**
61
+ * Compile patterns into a predicate. An empty pattern list matches nothing, so
62
+ * `exclude: []` excludes nothing and `include: []` is treated as "no include
63
+ * filter" by the caller rather than "include nothing".
64
+ */
65
+ function makeMatcher(patterns = [], cwd = process.cwd()) {
66
+ const regexes = patterns.filter((p) => p && p.trim()).map((p) => toRegExp(p.trim()));
67
+ if (regexes.length === 0)
68
+ return () => false;
69
+ return (file) => {
70
+ const rel = toRelative(file, cwd);
71
+ return regexes.some((re) => re.test(rel));
72
+ };
73
+ }
74
+ /** `true` when `file` is inside one of `dirs` (or `dirs` is empty). */
75
+ function withinAny(file, dirs, cwd) {
76
+ if (dirs.length === 0)
77
+ return true;
78
+ const abs = (0, path_1.isAbsolute)(file) ? file : (0, path_1.resolve)(cwd, file);
79
+ return dirs.some((dir) => {
80
+ const root = (0, path_1.isAbsolute)(dir) ? dir : (0, path_1.resolve)(cwd, dir);
81
+ if (abs === root)
82
+ return true;
83
+ return abs.startsWith(root.endsWith(path_1.sep) ? root : root + path_1.sep);
84
+ });
85
+ }
86
+ /** Normalize `.sql` / `sql` / `['.sql','.psql']` into a `.ext` list. */
87
+ function normalizeExts(ext) {
88
+ const list = Array.isArray(ext) ? ext : ext ? [ext] : [];
89
+ return list
90
+ .flatMap((e) => e.split(','))
91
+ .map((e) => e.trim())
92
+ .filter(Boolean)
93
+ .map((e) => (e.startsWith('.') ? e : `.${e}`))
94
+ .map((e) => e.toLowerCase());
95
+ }
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "git-changed",
3
+ "version": "0.3.0",
4
+ "author": "Constructive <developers@constructive.io>",
5
+ "description": "List the files changed against a merge base, including working-tree and untracked changes",
6
+ "main": "index.js",
7
+ "module": "esm/index.js",
8
+ "types": "index.d.ts",
9
+ "bin": {
10
+ "git-changed": "cli.js"
11
+ },
12
+ "homepage": "https://github.com/constructive-io/dev-utils",
13
+ "license": "MIT",
14
+ "publishConfig": {
15
+ "access": "public",
16
+ "directory": "dist"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "https://github.com/constructive-io/dev-utils"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/constructive-io/dev-utils/issues"
24
+ },
25
+ "scripts": {
26
+ "copy": "makage assets",
27
+ "clean": "makage clean",
28
+ "prepublishOnly": "npm run build",
29
+ "build": "makage build",
30
+ "lint": "eslint . --fix",
31
+ "test": "jest",
32
+ "test:watch": "jest --watch"
33
+ },
34
+ "devDependencies": {
35
+ "makage": "0.1.10"
36
+ },
37
+ "keywords": [
38
+ "git",
39
+ "changed",
40
+ "merge-base",
41
+ "diff",
42
+ "lint-staged",
43
+ "ci",
44
+ "incremental"
45
+ ],
46
+ "gitHead": "8285e90d5985f800079f8e1cf36426db392ff565"
47
+ }
package/types.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * How a file came to be in the changed set. `deleted` and `renamed` are the two
3
+ * a naive implementation gets wrong: linting a path that no longer exists is a
4
+ * crash, and a rename must be reported at its *destination*.
5
+ */
6
+ export type ChangeStatus = 'added' | 'modified' | 'deleted' | 'renamed' | 'untracked' | 'unknown';
7
+ export interface ChangedFile {
8
+ /** Absolute path. */
9
+ path: string;
10
+ /** Path relative to `cwd`, `/`-separated — what you print. */
11
+ relative: string;
12
+ status: ChangeStatus;
13
+ /** For a rename, the path it came from. */
14
+ from?: string;
15
+ /** Present in the diff against the base. */
16
+ committed: boolean;
17
+ /** Present in `git status` — uncommitted or untracked. */
18
+ worktree: boolean;
19
+ /** Whether the path exists on disk right now. */
20
+ exists: boolean;
21
+ }
22
+ /** Where the committed half of the set came from. */
23
+ export type ChangedSource =
24
+ /** `merge-base HEAD <base>` — the normal PR case. */
25
+ 'merge-base'
26
+ /** The base ref exists but has no merge base with HEAD (unrelated history). */
27
+ | 'base'
28
+ /** No base at all: working-tree changes only (shallow, detached, no remote). */
29
+ | 'worktree';
30
+ export interface ChangedOptions {
31
+ /** Directory to resolve from and report relative to. Default `process.cwd()`. */
32
+ cwd?: string;
33
+ /**
34
+ * Ref to diff against. Omit to auto-resolve (`$GITHUB_BASE_REF` → default
35
+ * branch); pass `false` for working-tree changes only.
36
+ */
37
+ base?: string | false;
38
+ /** Keep only these extensions, e.g. `'.sql'` or `['.sql', '.psql']`. */
39
+ ext?: string | string[];
40
+ /** Keep only paths matching these globs. */
41
+ include?: string[];
42
+ /** Drop paths matching these globs — generated trees, `dist/`, fixtures. */
43
+ exclude?: string[];
44
+ /**
45
+ * Restrict to these directories. Cheaper and more predictable than an
46
+ * `include` glob when you already know the subtree (a package dir, a CLI's
47
+ * positional paths).
48
+ */
49
+ within?: string[];
50
+ /** Drop paths that no longer exist. Default `true`. */
51
+ existingOnly?: boolean;
52
+ /** Include uncommitted/untracked working-tree changes. Default `true`. */
53
+ worktree?: boolean;
54
+ /** Include untracked files. Default `true`; ignored when `worktree` is false. */
55
+ untracked?: boolean;
56
+ }
57
+ export interface ChangedResult {
58
+ /** The changed files, sorted by path, after filtering. */
59
+ files: ChangedFile[];
60
+ /** Absolute paths — the common case, so you don't map every call site. */
61
+ paths: string[];
62
+ /** The base that was used, if any. */
63
+ base?: string;
64
+ /** The resolved merge-base commit, if one was found. */
65
+ mergeBase?: string;
66
+ source: ChangedSource;
67
+ /** Absolute path to the repository root. */
68
+ repoRoot: string;
69
+ }
package/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });