-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.ts
More file actions
238 lines (209 loc) · 6.03 KB
/
diff.ts
File metadata and controls
238 lines (209 loc) · 6.03 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
import { execSync, spawn } from 'child_process'
const Red = '\x1b[31m'
const Green = '\x1b[32m'
const Cyan = '\x1b[36m'
const Bold = '\x1b[1m'
const Underline = '\x1b[4m'
const Overline = '\x1b[53m' // \u203E
const Reset = '\x1b[0m'
export type DiffOptions = {
/* Include plus/minus signs in the diff output */
includePlusMinus: boolean
/* Include colors in the diff output */
includeColors: boolean
/* Include emojis next to file names to visually group them. */
includeEmoji: boolean
/* Include a line as a footer to close out the diff output */
includeFooter: boolean
/* Include untracked files in the diff output */
includeUntracked: boolean
/* Show staged changes */
cached: boolean
}
export type Diff = {
path: string
lineNumber: number
contents: string
}
function openInLess(content: string) {
const less = spawn('less', ['-R'], { stdio: ['pipe', process.stdout, process.stderr] })
less.stdin.write(content)
less.stdin.end()
}
// Set of animal emojis that will be mapped to files for easier identification
const ANIMALS = [
'🐶',
'🐱',
'🐭',
'🐹',
'🐰',
'🦊',
'🐻',
'🐼',
'🐨',
'🐯',
'🦁',
'🐮',
'🐷',
'🐸',
'🐵',
'🐔',
'🐧',
'🐦',
'🦆',
'🦉',
]
export function splitFilesInDiff(input: string): string[] {
const lines = input.split('\n')
const diffs: string[] = []
let currentDiff = ''
for (const line of lines) {
if (line.startsWith('diff --git')) {
if (currentDiff) {
diffs.push(currentDiff)
}
currentDiff = line
} else {
currentDiff += '\n' + line
}
}
if (currentDiff) {
diffs.push(currentDiff)
}
return diffs.filter((d) => d.trim() !== '')
}
function getLineNumber(line: string): number | null {
const lineNumberMatch = line.match(/@@ -(\d+),\d+ .* @@/)
return lineNumberMatch ? parseInt(lineNumberMatch[1]) : null
}
export function parseDiff(diffOutput: string): Diff[] {
if (diffOutput.trim() === '') {
return []
}
const fileParts = splitFilesInDiff(diffOutput)
const diffs: Diff[] = []
fileParts.forEach((part) => {
const lines = part.split('\n')
const filePath =
lines[0]
.split(' b/')
.pop()
?.trim()
.replace(/^"(.+)"$/, '$1') || ''
let currentSectionLineNumber: number | null = null
let currentSectionLines: string[] = []
const addDiff = () => {
if (currentSectionLineNumber !== null && currentSectionLines.length > 0) {
diffs.push({
path: filePath,
lineNumber: currentSectionLineNumber,
contents: currentSectionLines.join('\n'),
})
}
}
for (const line of lines) {
const lineNumber = getLineNumber(line)
if (lineNumber !== null) {
addDiff()
currentSectionLines = []
currentSectionLineNumber = lineNumber
} else {
currentSectionLines.push(line)
}
}
addDiff()
})
return diffs
}
function getHeader(diff: Diff, options: DiffOptions, index: number, includeEmoji: boolean): string {
return `${includeEmoji ? ANIMALS[index] + ' ' : ''}${diff.path}:${diff.lineNumber}`
}
function coloredDiff(diff: Diff, options: DiffOptions): string {
return diff.contents
.split('\n')
.map((line) => {
const color = line.startsWith('+') ? Green : line.startsWith('-') ? Red : ''
const text = !options.includePlusMinus ? line.slice(1) : line
return `${options.includeColors ? color : ''}${text}${options.includeColors ? Reset : ''}`
})
.join('\n')
}
function coloredHeader(header: string, options: DiffOptions): string {
return options.includeColors ? `${Bold}${Underline}${Cyan}${header}${Reset}` : header
}
function coloredFooter(footer: string, options: DiffOptions): string {
return options.includeColors ? `${Bold}${Overline}${Cyan}${footer}${Reset}` : footer
}
export function serializeDiffs(diffs: Diff[], options: DiffOptions): string {
if (diffs.length === 0) {
return ''
}
let fileIndex = 0
let lastFile = diffs[0].path
return diffs
.map((diff) => {
if (diff.path !== lastFile) {
lastFile = diff.path
fileIndex++
}
const header = getHeader(diff, options, fileIndex, options.includeEmoji)
const footer = options.includeFooter ? ' '.repeat(header.length) : ''
return `${coloredHeader(header, options)}\n${coloredDiff(diff, options)}\n${coloredFooter(
footer,
options,
)}`
})
.join('\n\n')
}
function getUntrackedFilesAsDiff(): string {
return execSync(
'git ls-files --others --exclude-standard -z | xargs -0 -n 1 git --no-pager diff --no-index /dev/null || true',
{
encoding: 'utf8',
},
)
}
function getDiffString(cached: boolean): string {
const command = cached ? 'git diff --cached' : 'git diff'
return execSync(command, { encoding: 'utf8' })
}
/**
* Get the current git diff as an array of diffs.
*
* @param includeUntracked [boolean] - Include untracked files in the diff output.
* @param cached [boolean] - Show staged changes.
* @returns [String] git diff string
*/
export function getDiffs(includeUntracked: boolean, cached: boolean): Diff[] {
let diffOutput = getDiffString(cached)
if (includeUntracked && !cached) {
const untrackedFiles = getUntrackedFilesAsDiff()
diffOutput += '\n\n'
diffOutput += untrackedFiles
}
return parseDiff(diffOutput)
}
/**
* Get the current git diff as a string.
*
* @param options [DiffOptions] - Options for the diff output.
* @returns [String] git diff string
*/
export function getDiff(options: DiffOptions): string {
const diffs = getDiffs(options.includeUntracked, options.cached)
return serializeDiffs(diffs, options)
}
/**
* Open the current git diff in less.
*
* @param options [DiffOptions] - Options for the diff output.
*/
export function showDiff(options: DiffOptions, useLess: boolean = true) {
const diffs = getDiffs(options.includeUntracked, options.cached)
const serialized = serializeDiffs(diffs, options)
if (useLess) {
openInLess(serialized)
} else {
console.log(serialized)
}
}