-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.ts
More file actions
244 lines (225 loc) Β· 6.55 KB
/
Copy pathgit.ts
File metadata and controls
244 lines (225 loc) Β· 6.55 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
// Diff fetching, --against PR mode, file status, and pure diff-line helpers.
export interface FileDiff {
file: string
raw: string
lines: string[]
status?: string
}
export const splitByFile = (raw: string): FileDiff[] => {
const blocks = raw.split(/(?=^diff --git )/m).filter(Boolean)
return blocks.map((block) => {
const fileMatch =
block.match(/^\+\+\+ b\/(.+)$/m) ?? block.match(/^--- a\/(.+)$/m)
const file = fileMatch?.[1] ?? "unknown"
const lines = block.split("\n")
while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop()
return { file, raw: block, lines }
})
}
export const getFiletype = (filename: string): string | undefined => {
const lower = filename.toLowerCase()
// Jest/Vitest snapshots hold JS/JSX source in a `.snap` file β highlight them
// as TypeScript so the diff isn't a colourless wall of text.
if (lower.endsWith(".snap")) return "typescript"
const ext = lower.split(".").pop() ?? ""
const map: Record<string, string> = {
ts: "typescript",
tsx: "typescript",
mts: "typescript",
cts: "typescript",
js: "javascript",
jsx: "javascript",
mjs: "javascript",
cjs: "javascript",
mdx: "markdown",
py: "python",
rb: "ruby",
go: "go",
rs: "rust",
java: "java",
c: "c",
cpp: "cpp",
h: "c",
hpp: "cpp",
cs: "csharp",
css: "css",
scss: "css",
html: "html",
json: "json",
yaml: "yaml",
yml: "yaml",
md: "markdown",
sh: "bash",
zsh: "bash",
}
return map[ext]
}
// ββ Pure diff-line math (operate on a FileDiff's `lines`) ββββββββββββββββββββββ
export const isContentLine = (l: string) =>
(l.startsWith("+") && !l.startsWith("+++")) ||
(l.startsWith("-") && !l.startsWith("---")) ||
l.startsWith(" ")
export const rawToContentIdx = (lines: string[], rawIdx: number): number => {
let idx = 0
for (let i = 0; i < rawIdx && i < lines.length; i++) {
if (isContentLine(lines[i]!)) idx++
}
return idx
}
export const nextContentRawIdx = (
lines: string[],
rawIdx: number,
dir: 1 | -1,
): number => {
let idx = rawIdx + dir
while (idx >= 0 && idx < lines.length) {
if (isContentLine(lines[idx]!)) return idx
idx += dir
}
return rawIdx
}
export const firstContentRawIdx = (lines: string[]): number => {
for (let i = 0; i < lines.length; i++) {
if (isContentLine(lines[i]!)) return i
}
return 0
}
export const totalContentLines = (lines: string[]): number =>
lines.filter(isContentLine).length
export type DiffLineInfo = { lineNum: number; side: "old" | "new" }
export const diffLineToFileLineNum = (
lines: string[],
lineIdx: number,
): DiffLineInfo | null => {
let newCounter = 0
let oldCounter = 0
for (let i = 0; i <= lineIdx && i < lines.length; i++) {
const l = lines[i]!
if (l.startsWith("@@ ")) {
const m = l.match(/@@ -(\d+)(?:,\d+)? \+(\d+)/)
if (m) {
oldCounter = parseInt(m[1]!, 10)
newCounter = parseInt(m[2]!, 10)
}
} else if (l.startsWith("+")) {
if (i === lineIdx) return { lineNum: newCounter, side: "new" }
newCounter++
} else if (l.startsWith("-")) {
if (i === lineIdx) return { lineNum: oldCounter, side: "old" }
oldCounter++
} else if (l) {
if (i === lineIdx) return { lineNum: newCounter, side: "new" }
newCounter++
oldCounter++
}
}
return null
}
// ββ Diff gathering βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export interface DiffData {
targetDir: string
prMode: boolean
currentBranch: string | null
againstBranch: string | null
commitList: string[]
fileDiffs: FileDiff[]
files: string[]
}
export const gatherDiff = async ({
rawTarget,
againstBranch,
}: {
rawTarget: string
againstBranch: string | null
}): Promise<DiffData> => {
const targetFile = await (async () => {
try {
const result = await Bun.$`test -f ${rawTarget}`.nothrow().quiet()
return result.exitCode === 0 ? rawTarget : null
} catch {
return null
}
})()
const targetDir = targetFile
? (
await Bun.$`git rev-parse --show-toplevel`
.cwd(
rawTarget.includes("/")
? rawTarget.slice(0, rawTarget.lastIndexOf("/"))
: process.cwd(),
)
.text()
).trim()
: rawTarget
const prMode = againstBranch !== null
let fullDiff: string
let currentBranch: string | null = null
let commitList: string[] = []
const fileStatusMap = new Map<string, string>()
if (prMode) {
try {
fullDiff = await Bun.$`git diff ${againstBranch}...HEAD`
.cwd(targetDir)
.text()
} catch {
throw new Error(
`Branch '${againstBranch}' not found or has no common ancestor with HEAD.`,
)
}
const nameStatus =
await Bun.$`git diff --name-status ${againstBranch}...HEAD`
.cwd(targetDir)
.text()
for (const line of nameStatus.trim().split("\n").filter(Boolean)) {
const parts = line.split("\t")
const status = parts[0]!.charAt(0)
const file = status === "R" ? parts[2]! : parts[1]!
fileStatusMap.set(file, status)
}
currentBranch = (
await Bun.$`git rev-parse --abbrev-ref HEAD`.cwd(targetDir).text()
).trim()
commitList = (
await Bun.$`git log ${againstBranch}..HEAD --oneline`
.cwd(targetDir)
.text()
)
.trim()
.split("\n")
.filter(Boolean)
} else if (targetFile) {
const relPath = targetFile.replace(targetDir + "/", "")
const stagedOutput = await Bun.$`git diff --staged -- ${relPath}`
.cwd(targetDir)
.text()
fullDiff = stagedOutput.trim()
? stagedOutput
: await Bun.$`git diff -- ${relPath}`.cwd(targetDir).text()
} else {
const stagedOutput = await Bun.$`git diff --staged`.cwd(targetDir).text()
fullDiff = stagedOutput.trim()
? stagedOutput
: await Bun.$`git diff`.cwd(targetDir).text()
}
if (!fullDiff.trim()) {
throw new Error(
prMode
? `No diff found between '${againstBranch}' and HEAD.`
: "No diff found (neither staged nor unstaged changes).",
)
}
const fileDiffs = splitByFile(fullDiff)
if (prMode) {
for (const fd of fileDiffs) fd.status = fileStatusMap.get(fd.file) ?? "M"
}
const files = fileDiffs.map((f) => f.file)
return {
targetDir,
prMode,
currentBranch,
againstBranch,
commitList,
fileDiffs,
files,
}
}