-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathgit.ts
More file actions
428 lines (374 loc) · 13.2 KB
/
Copy pathgit.ts
File metadata and controls
428 lines (374 loc) · 13.2 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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
import { execSync } from "node:child_process";
import type { CommitContext, GitInfo, RepoInfo } from "./types";
import { error as logError, verbose, warn } from "./log";
/** Strips leading "./" or "/" so paths are clean for git pathspec. */
export function normalizePathspec(pattern: string): string {
return pattern.replace(/^(\.\/|\/)+/, "").trim();
}
/**
* Builds git pathspec arguments from include patterns.
*
* Uses `:(top,glob)` pathspec prefix:
* - `top`: paths are relative to repo root, not the current working directory
* - `glob`: enables `**` for recursive matching (e.g., "src/**")
*
* @see https://git-scm.com/docs/gitglossary#Documentation/gitglossary.txt-aiddefpathspec
*/
export function buildPathspecArgs(includePaths: string[] | null): string {
if (!includePaths || includePaths.length === 0) {
return "";
}
const patterns = includePaths
.map((p) => normalizePathspec(p))
.filter((p) => p.length > 0)
.map((p) => `":(top,glob)${p}"`);
if (patterns.length === 0) {
return "";
}
return `-- ${patterns.join(" ")}`;
}
/**
* Verifies the runtime environment can satisfy the CLI's git requirements:
* 1. The `git` binary is on PATH.
* 2. The current working directory is inside a git repository.
*
* Call once at startup, before any other git operations, so cryptic
* downstream failures (ENOENT, "not a git repository") become useful
* diagnostics for CI users.
*/
export function assertGitAvailable(cwd: string = process.cwd()): void {
try {
execSync("git --version", {
cwd,
stdio: ["ignore", "ignore", "pipe"],
});
} catch {
throw new Error("linear-release requires `git` on PATH, but `git --version` failed. Install git in your CI image.");
}
try {
execSync("git rev-parse --is-inside-work-tree", {
cwd,
stdio: ["ignore", "ignore", "pipe"],
});
} catch {
throw new Error("linear-release must run inside a git repository, but no `.git` directory was found.");
}
}
export function getCurrentGitInfo(cwd: string = process.cwd()): GitInfo {
try {
const branch = execSync("git rev-parse --abbrev-ref HEAD", {
cwd,
stdio: ["ignore", "pipe", "ignore"],
encoding: "utf8",
})
.trim()
.replace(/^HEAD$/, "detached");
const commit = execSync("git rev-parse HEAD", {
cwd,
stdio: ["ignore", "pipe", "ignore"],
encoding: "utf8",
}).trim();
const message = execSync("git log -1 --pretty=%B", {
cwd,
stdio: ["ignore", "pipe", "ignore"],
encoding: "utf8",
})
.trim()
.replace(/\s+/g, " ");
return { branch, commit, message };
} catch {
return { branch: null, commit: null, message: null };
}
}
/**
* Extracts the most relevant branch name from git decoration refs.
* Prefers feature branches over common branches (main, master, develop, etc.)
* and picks the longest name when multiple candidates exist.
*/
export function extractBranchName(rawDecorations: string | undefined): string | null {
if (!rawDecorations || rawDecorations.trim().length === 0) {
return null;
}
const refs = rawDecorations.split(",").map((ref) => ref.trim());
const branches = refs
.map((ref) => ref.replace(/^HEAD ->\s*/, ""))
.filter((ref) => ref.length > 0 && !ref.toLowerCase().startsWith("tag:") && !ref.startsWith("origin/HEAD"));
if (branches.length === 0) {
return null;
}
const common = new Set(["main", "master", "develop", "dev", "staging", "production", "prod"]);
const normalizedBranches = branches.map((b) => b.replace(/^remotes\/[^/]+\//, ""));
const candidates = normalizedBranches.filter((b) => !common.has(b.toLowerCase()));
const preferred = candidates.length > 0 ? candidates : normalizedBranches;
return preferred.sort((a, b) => b.length - a.length)[0]!;
}
export function commitExists(sha: string, cwd: string = process.cwd()): boolean {
try {
execSync(`git cat-file -e ${sha}^{commit}`, {
cwd,
stdio: ["ignore", "ignore", "ignore"],
});
return true;
} catch {
return false;
}
}
const SHA_PATTERN = /^[0-9a-f]{7,40}$/i;
/**
* Returns true if the commit has more than one parent (i.e., is a merge commit).
*/
export function isMergeCommit(sha: string, cwd: string = process.cwd()): boolean {
if (!SHA_PATTERN.test(sha)) {
warn(`isMergeCommit: Invalid SHA format "${sha}"`);
return false;
}
try {
// %P returns space-separated parent hashes
// Regular commits have 1 parent (no space), merge commits have 2+ (contains space)
const parentHashes = execSync(`git log -1 --format=%P ${sha}`, {
cwd,
stdio: ["ignore", "pipe", "ignore"],
encoding: "utf8",
}).trim();
return parentHashes.includes(" ");
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
warn(`isMergeCommit: Failed to check ${sha}: ${message}`);
return false;
}
}
/**
* Extracts the branch name from a merge commit message.
* Supports:
* - GitHub: "Merge pull request #X from owner/branch-name"
* - GitLab: "Merge branch 'branch-name' into 'target'"
* - GitLab (no target): "Merge branch 'branch-name'"
* - Bitbucket: "Merged in branch-name (pull request #X)"
*/
export function extractBranchNameFromMergeMessage(message: string | null | undefined): string | null {
if (!message) {
return null;
}
// GitHub: "Merge pull request #123 from owner/branch-name"
const githubMatch = message.match(/Merge pull request #\d+ from [^/]+\/(\S+)/i);
if (githubMatch?.[1]) {
return githubMatch[1];
}
// GitLab: "Merge branch 'branch-name' into 'target'" or "Merge branch 'branch-name'"
const gitlabMatch = message.match(/Merge branch '([^']+)'/i);
if (gitlabMatch?.[1]) {
return gitlabMatch[1];
}
// Bitbucket: "Merged in feature/ENG-123-fix-auth (pull request #42)"
const bitbucketMatch = message.match(/Merged in (\S+) \(pull request #\d+\)/i);
return bitbucketMatch?.[1] ?? null;
}
/**
* Parses a commit chunk (from git log --format=%H%x1f%B%x1f%D) into a CommitContext.
* Prefers branch name from merge message over decorations for issue tracking.
*/
function parseCommitChunk(chunk: string): CommitContext {
const [sha, rawMessage, rawDecorations] = chunk.split("\x1f");
const message = (rawMessage ?? "").trim().replace(/\s+/g, " ");
const branchName = extractBranchNameFromMergeMessage(message) ?? extractBranchName(rawDecorations);
return { sha: sha.trim(), branchName, message };
}
/**
* Returns the commit context for a single commit without path filtering.
*/
export function getCommitContext(sha: string, cwd: string = process.cwd()): CommitContext | null {
if (!SHA_PATTERN.test(sha)) {
warn(`getCommitContext: Invalid SHA format "${sha}"`);
return null;
}
try {
const output = execSync(`git log -1 --format=%H%x1f%B%x1f%D%x1e ${sha}`, {
cwd,
stdio: ["ignore", "pipe", "pipe"],
encoding: "utf8",
});
const chunk = output.split("\x1e")[0];
if (!chunk || chunk.trim().length === 0) {
warn(`getCommitContext: Empty output for ${sha}`);
return null;
}
return parseCommitChunk(chunk);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
warn(`getCommitContext: Failed to get context for ${sha}: ${message}`);
return null;
}
}
/**
* Ensures a commit is available in the local repository.
* For shallow clones, progressively fetches more history until the commit is found.
* Throws if the commit cannot be made available (e.g., not on the current branch).
*/
export function ensureCommitAvailable(sha: string, cwd: string = process.cwd()): void {
if (commitExists(sha, cwd)) {
return;
}
const strategies = [
{
command: "git fetch --deepen=200 origin",
label: "Deepening by 200 commits",
},
{
command: "git fetch --deepen=500 origin",
label: "Deepening by 500 commits",
},
{ command: "git fetch --unshallow origin", label: "Fetching full history" },
];
verbose(`Commit ${sha} not in local history (likely shallow clone)`);
for (const { command, label } of strategies) {
verbose(label);
try {
execSync(command, { cwd, stdio: ["ignore", "ignore", "pipe"], timeout: 30_000 });
if (commitExists(sha, cwd)) {
verbose(`Found commit ${sha}`);
return;
}
} catch (e) {
const reason = e instanceof Error ? e.message : String(e);
verbose(`Strategy "${label}" failed: ${reason}`);
}
}
const currentBranch = getCurrentGitInfo(cwd).branch ?? "unknown";
throw new Error(
`Commit ${sha} not reachable from branch "${currentBranch}" even after fetching full history. ` +
`Ensure the commit exists on branch "${currentBranch}".`,
);
}
/**
* Returns commits between two SHAs, optionally filtered by file paths.
*
* @param fromSha - Starting commit SHA (exclusive)
* @param toSha - Ending commit SHA (inclusive)
* @param options.includePaths - Glob patterns to filter commits by file paths (relative to repo root)
* @param options.cwd - Working directory for git commands (defaults to process.cwd())
*/
export function getCommitContextsBetweenShas(
fromSha: string,
toSha: string,
options: { includePaths?: string[] | null; cwd?: string } = {},
): CommitContext[] {
const { includePaths = null, cwd = process.cwd() } = options;
if (!SHA_PATTERN.test(fromSha)) {
warn(`getCommitContextsBetweenShas: Invalid fromSha format "${fromSha}"`);
return [];
}
if (!SHA_PATTERN.test(toSha)) {
warn(`getCommitContextsBetweenShas: Invalid toSha format "${toSha}"`);
return [];
}
const pathspecArgs = buildPathspecArgs(includePaths);
// If fromSha and toSha are the same, get that single commit only
const logCommand =
fromSha === toSha
? `git log -1 --format=%H%x1f%B%x1f%D%x1e ${toSha} ${pathspecArgs}`
: `git log --format=%H%x1f%B%x1f%D%x1e ${fromSha}..${toSha} ${pathspecArgs}`;
const output = execSync(logCommand, {
cwd,
stdio: ["ignore", "pipe", "pipe"],
encoding: "utf8",
});
const commits = output
.split("\x1e")
.filter((chunk) => chunk.trim().length > 0)
.map(parseCommitChunk);
/**
* Path filtering can exclude a merge commit at toSha. This is because merge commits have no direct file changes.
* We still want to include it for metadata extraction, like PR numbers and branch names.
*/
const toShaWasExcluded = includePaths?.length && !commits.some((c) => c.sha === toSha);
if (toShaWasExcluded && isMergeCommit(toSha, cwd)) {
const mergeCommit = getCommitContext(toSha, cwd);
if (mergeCommit) {
commits.unshift(mergeCommit);
}
}
if (commits.length === 0) {
verbose(
`getCommitContextsBetweenShas: No commits found between ${fromSha}..${toSha}` +
(includePaths?.length ? ` with paths: ${includePaths.join(", ")}` : ""),
);
}
return commits;
}
function hostToProvider(host: string): string | null {
if (host === "gitlab.com" || host.includes("gitlab")) {
return "gitlab";
}
if (host === "github.com" || host.endsWith(".ghe.com") || host.includes("github")) {
return "github";
}
if (host === "bitbucket.org" || host.includes("bitbucket")) {
return "bitbucket";
}
return null;
}
/**
* Parses a git remote URL (HTTPS or SSH) into repo information.
*
* @param remoteUrl The raw git remote URL string.
* @returns Parsed repo info, or null if the URL could not be parsed.
*/
export function parseRepoUrl(remoteUrl: string): RepoInfo | null {
// Handle HTTPS URLs: https://github.com/owner/repo.git
const httpsMatch = remoteUrl.match(/^https?:\/\/(?:[^@]+@)?([^/]+)\/([^/]+)\/([^/]+?)(?:\.git)?$/);
if (httpsMatch) {
const host = httpsMatch[1];
const owner = httpsMatch[2] || null;
const name = httpsMatch[3]?.replace(/\.git$/, "") || null;
return {
owner,
name,
provider: hostToProvider(host),
url: owner && name ? `https://${host}/${owner}/${name}` : null,
};
}
// Handle SSH URLs: git@github.com:owner/repo.git
const sshMatch = remoteUrl.match(/^git@([^:]+):([^/]+)\/([^/]+?)(?:\.git)?$/);
if (sshMatch) {
const host = sshMatch[1];
const owner = sshMatch[2] || null;
const name = sshMatch[3]?.replace(/\.git$/, "") || null;
return {
owner,
name,
provider: hostToProvider(host),
url: owner && name ? `https://${host}/${owner}/${name}` : null,
};
}
return null;
}
export function getRepoInfo(remote: string = "origin", cwd: string = process.cwd()): RepoInfo | null {
try {
const url = execSync(`git remote get-url ${remote}`, {
cwd,
stdio: ["ignore", "pipe", "ignore"],
encoding: "utf8",
}).trim();
return parseRepoUrl(url);
} catch (error) {
logError(`Error getting repo info: ${error}`);
return null;
}
}
export function getPullRequestNumbers(commits: CommitContext[]): number[] {
const prNumbers = new Set<number>();
for (const commit of commits) {
if (!commit.message) {
continue;
}
const matches = commit.message.matchAll(/\(#(\d+)\)/g);
for (const match of matches) {
const prNumber = Number.parseInt(match[1]!, 10);
if (!Number.isNaN(prNumber)) {
verbose(`Found pull request number ${prNumber} in commit ${commit.sha}`);
prNumbers.add(prNumber);
}
}
}
return Array.from(prNumbers);
}