-
-
Notifications
You must be signed in to change notification settings - Fork 371
Expand file tree
/
Copy pathreview-checkpoints.ts
More file actions
257 lines (223 loc) · 7.92 KB
/
Copy pathreview-checkpoints.ts
File metadata and controls
257 lines (223 loc) · 7.92 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
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { git, getGitEligibility, safeWorkspaceRefSegment } from "./git.js";
export type ReviewSince = "last_shown" | "last_review" | "workspace_open";
export interface ReviewSummary {
files: number;
additions: number;
removals: number;
}
export interface ReviewFile {
path: string;
previousPath?: string;
type: "change" | "rename-pure" | "rename-changed" | "new" | "deleted";
additions: number;
removals: number;
}
export interface ReviewChangesResult {
result: string;
summary: ReviewSummary;
files: ReviewFile[];
patch: string;
}
interface WorkspaceReviewState {
root: string;
gitRoot?: string;
openRef: string;
baselineRef: string;
diagnostic?: string;
}
export interface ReviewCheckpointManager {
initializeWorkspace(input: { workspaceId: string; root: string }): Promise<void>;
reviewChanges(input: {
workspaceId: string;
root: string;
since?: ReviewSince;
markReviewed?: boolean;
}): Promise<ReviewChangesResult>;
}
const REVIEW_REF_PREFIX = "refs/devspace/review";
export function createReviewCheckpointManager(): ReviewCheckpointManager {
const states = new Map<string, WorkspaceReviewState>();
const initializations = new Map<string, Promise<void>>();
return {
async initializeWorkspace({ workspaceId, root }) {
const existingState = states.get(workspaceId);
if (
existingState?.root === root &&
(existingState.gitRoot !== undefined || existingState.diagnostic !== undefined)
) {
return;
}
const pending = initializations.get(workspaceId);
if (pending) {
await pending;
return;
}
const initialize = initializeWorkspaceState(states, workspaceId, root);
initializations.set(workspaceId, initialize);
try {
await initialize;
} finally {
if (initializations.get(workspaceId) === initialize) {
initializations.delete(workspaceId);
}
}
},
async reviewChanges({ workspaceId, root, since = "last_shown", markReviewed = true }) {
let state = states.get(workspaceId);
if (!state) {
await this.initializeWorkspace({ workspaceId, root });
state = states.get(workspaceId);
}
if (!state?.gitRoot) {
throw new Error(state?.diagnostic ?? "show_changes requires a Git workspace in this version.");
}
const baselineRef = since === "workspace_open" ? state.openRef : state.baselineRef;
const baseline = (await git(state.gitRoot, ["rev-parse", "--verify", `${baselineRef}^{commit}`])).stdout.trim();
const current = await createWorkingTreeSnapshot(state.gitRoot);
const patch = (await git(state.gitRoot, ["diff", "--binary", "--no-color", baseline, current], {
maxBuffer: 50 * 1024 * 1024,
})).stdout;
const numstat = (await git(state.gitRoot, ["diff", "--numstat", "-z", baseline, current], {
maxBuffer: 50 * 1024 * 1024,
})).stdout;
const files = parseNumstat(numstat);
const summary = summarizeFiles(files);
if (markReviewed) {
await git(state.gitRoot, ["update-ref", state.baselineRef, current]);
}
return {
result:
summary.files === 0
? `No changes since ${since === "workspace_open" ? "workspace open" : "last shown changes"}.`
: `Changed ${summary.files} ${summary.files === 1 ? "file" : "files"} (+${summary.additions} -${summary.removals}).`,
summary,
files,
patch,
};
},
};
}
async function initializeWorkspaceState(
states: Map<string, WorkspaceReviewState>,
workspaceId: string,
root: string,
): Promise<void> {
const refs = reviewRefs(workspaceId);
const state: WorkspaceReviewState = { root, ...refs };
states.set(workspaceId, state);
try {
const eligibility = await getGitEligibility(root);
if (!eligibility.ok || !eligibility.gitRoot) {
state.diagnostic = eligibility.message ?? "show_changes requires a Git workspace in this version.";
return;
}
state.gitRoot = eligibility.gitRoot;
const [hasOpenRef, hasBaselineRef] = await Promise.all([
hasCommitRef(eligibility.gitRoot, state.openRef),
hasCommitRef(eligibility.gitRoot, state.baselineRef),
]);
if (hasOpenRef && hasBaselineRef) return;
const commit = await createWorkingTreeSnapshot(eligibility.gitRoot);
if (!hasOpenRef) {
await git(eligibility.gitRoot, ["update-ref", state.openRef, commit]);
}
if (!hasBaselineRef) {
await git(eligibility.gitRoot, ["update-ref", state.baselineRef, commit]);
}
} catch (error) {
state.diagnostic = error instanceof Error ? error.message : String(error);
}
}
async function hasCommitRef(gitRoot: string, ref: string): Promise<boolean> {
try {
await git(gitRoot, ["rev-parse", "--verify", `${ref}^{commit}`]);
return true;
} catch {
return false;
}
}
function reviewRefs(workspaceId: string): Pick<WorkspaceReviewState, "openRef" | "baselineRef"> {
const segment = safeWorkspaceRefSegment(workspaceId);
return {
openRef: `${REVIEW_REF_PREFIX}/${segment}/open`,
baselineRef: `${REVIEW_REF_PREFIX}/${segment}/baseline`,
};
}
async function createWorkingTreeSnapshot(gitRoot: string): Promise<string> {
const tempDir = await mkdtemp(join(tmpdir(), "devspace-review-index-"));
const indexPath = join(tempDir, "index");
const env = checkpointEnv(indexPath);
try {
await git(gitRoot, ["read-tree", "HEAD"], { env });
await git(gitRoot, ["add", "-A", "--", "."], { env });
const tree = (await git(gitRoot, ["write-tree"], { env })).stdout.trim();
const parent = (await git(gitRoot, ["rev-parse", "--verify", "HEAD^{commit}"])).stdout.trim();
return (await git(gitRoot, ["commit-tree", tree, "-p", parent, "-m", "DevSpace review snapshot"], { env })).stdout.trim();
} finally {
await rm(tempDir, { recursive: true, force: true });
}
}
function checkpointEnv(indexPath: string): NodeJS.ProcessEnv {
return {
GIT_INDEX_FILE: indexPath,
GIT_AUTHOR_NAME: "DevSpace",
GIT_AUTHOR_EMAIL: "devspace@users.noreply.local",
GIT_COMMITTER_NAME: "DevSpace",
GIT_COMMITTER_EMAIL: "devspace@users.noreply.local",
};
}
function parseNumstat(output: string): ReviewFile[] {
const fields = output.split("\0").filter((field) => field.length > 0);
const files: ReviewFile[] = [];
for (let index = 0; index < fields.length;) {
const header = fields[index++] ?? "";
const parts = header.split("\t");
const additions = parseStatNumber(parts[0]);
const removals = parseStatNumber(parts[1]);
if (parts.length >= 3) {
const path = parts[2] ?? "";
if (path) files.push({ path, type: fileType(path, undefined, additions, removals), additions, removals });
continue;
}
const previousPath = fields[index++];
const path = fields[index++];
if (!path) continue;
files.push({
path,
previousPath,
type: fileType(path, previousPath, additions, removals),
additions,
removals,
});
}
return files;
}
function parseStatNumber(value: string | undefined): number {
if (!value || value === "-") return 0;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : 0;
}
function fileType(
path: string,
previousPath: string | undefined,
additions: number,
removals: number,
): ReviewFile["type"] {
if (previousPath) return additions === 0 && removals === 0 ? "rename-pure" : "rename-changed";
if (additions > 0 && removals === 0) return "new";
if (additions === 0 && removals > 0) return "deleted";
return "change";
}
function summarizeFiles(files: ReviewFile[]): ReviewSummary {
return files.reduce<ReviewSummary>(
(summary, file) => ({
files: summary.files + 1,
additions: summary.additions + file.additions,
removals: summary.removals + file.removals,
}),
{ files: 0, additions: 0, removals: 0 },
);
}