-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathlistCommitsApi.ts
More file actions
157 lines (137 loc) · 5.24 KB
/
listCommitsApi.ts
File metadata and controls
157 lines (137 loc) · 5.24 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
import { sew } from '@/actions';
import { invalidGitRef, notFound, ServiceError, unexpectedError } from '@/lib/serviceError';
import { withOptionalAuthV2 } from '@/withAuthV2';
import { getRepoPath } from '@sourcebot/shared';
import { z } from 'zod';
import { simpleGit } from 'simple-git';
import { toGitDate, validateDateRange } from './dateUtils';
import { commitSchema } from './schemas';
import { isGitRefValid } from './utils';
export type Commit = z.infer<typeof commitSchema>;
export interface SearchCommitsResult {
commits: Commit[];
totalCount: number;
}
type ListCommitsRequest = {
repo: string;
query?: string;
since?: string;
until?: string;
author?: string;
ref?: string;
path?: string;
maxCount?: number;
skip?: number;
}
/**
* List commits in a repository using git log.
*
* **Date Formats**: Supports both ISO 8601 dates and relative formats
* (e.g., "30 days ago", "last week", "yesterday"). Git natively handles
* these formats in the --since and --until flags.
*/
export const listCommits = async ({
repo: repoName,
query,
since,
until,
author,
ref = 'HEAD',
path,
maxCount = 50,
skip = 0,
}: ListCommitsRequest): Promise<SearchCommitsResult | ServiceError> => sew(() =>
withOptionalAuthV2(async ({ org, prisma }) => {
const repo = await prisma.repo.findFirst({
where: {
name: repoName,
orgId: org.id,
},
});
if (!repo) {
return notFound(`Repository "${repoName}" not found.`);
}
if (!isGitRefValid(ref)) {
return invalidGitRef(ref);
}
const { path: repoPath } = getRepoPath(repo);
// Validate date range if both since and until are provided
const dateRangeError = validateDateRange(since, until);
if (dateRangeError) {
return unexpectedError(dateRangeError);
}
// Parse dates to git-compatible format
const gitSince = toGitDate(since);
const gitUntil = toGitDate(until);
const git = simpleGit().cwd(repoPath);
try {
const sharedOptions: Record<string, string | number | null> = {
...(gitSince ? { '--since': gitSince } : {}),
...(gitUntil ? { '--until': gitUntil } : {}),
...(author ? {
'--author': author,
'--regexp-ignore-case': null /// Case insensitive
} : {}),
...(query ? {
'--grep': query,
'--regexp-ignore-case': null /// Case insensitive
} : {}),
};
// Build args array directly to ensure correct ordering:
// git log [flags] <ref> [-- <path>]
const logArgs: string[] = [`--max-count=${maxCount}`];
if (skip > 0) {
logArgs.push(`--skip=${skip}`);
}
for (const [key, value] of Object.entries(sharedOptions)) {
logArgs.push(value !== null ? `${key}=${value}` : key);
}
logArgs.push(ref);
if (path) {
logArgs.push('--', path);
}
// First, get the commits
const log = await git.log(logArgs);
// Then, use rev-list to get the total count of commits
const countArgs = ['rev-list', '--count', ref];
for (const [key, value] of Object.entries(sharedOptions)) {
countArgs.push(value !== null ? `${key}=${value}` : key);
}
if (path) {
countArgs.push('--', path);
}
const totalCount = parseInt((await git.raw(countArgs)).trim(), 10);
return { commits: log.all as unknown as Commit[], totalCount };
} catch (error: unknown) {
// Provide detailed error messages for common git errors
const errorMessage = error instanceof Error ? error.message : String(error);
if (errorMessage.includes('not a git repository')) {
return unexpectedError(
`Invalid git repository at ${repoPath}. ` +
`The directory exists but is not a valid git repository.`
);
}
if (errorMessage.includes('ambiguous argument')) {
return unexpectedError(
`Invalid git reference or date format. ` +
`Please check your date parameters: since="${since}", until="${until}"`
);
}
if (errorMessage.includes('timeout')) {
return unexpectedError(
`Git operation timed out after 30 seconds for repository ${repoName}. ` +
`The repository may be too large or the git operation is taking too long.`
);
}
// Generic error fallback
if (error instanceof Error) {
throw new Error(
`Failed to search commits in repository ${repoName}: ${error.message}`
);
} else {
throw new Error(
`Failed to search commits in repository ${repoName}: ${errorMessage}`
);
}
}
}));