-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdiff.ts
132 lines (107 loc) · 2.72 KB
/
diff.ts
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
export type Diff = {
beforeFileName: string
afterFileName: string
hunks: Hunk[]
}
export type Hunk = {
header: HunkHeader
lines: Line[]
}
type HunkHeader = {
beforeLines: number
afterLines: number
beforeStartLine: number
afterStartLine: number
}
type Line = {
text: string
mark: 'add' | 'delete' | 'nomodified'
}
const hunkHeaderRegexp = /@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@/
export function toString(diff: Diff): string {
if (diff.hunks.length === 0) {
return "";
}
let res: string
res = '--- ' + diff.beforeFileName + '\n'
res += '+++ ' + diff.afterFileName + '\n'
diff.hunks.forEach((hunk: Hunk) => {
res += '@@ -' + hunk.header.beforeStartLine + ',' + hunk.header.beforeLines + ' +' + hunk.header.afterStartLine + ',' + hunk.header.afterLines + ' @@\n'
hunk.lines.forEach((line: Line) => {
switch (line.mark) {
case 'add':
res += '+';
break;
case 'delete':
res += '-';
break;
case 'nomodified':
res += ' ';
break;
}
res += line.text + '\n';
})
})
return res;
}
export function parse(text: string): Diff[] {
const diffs: Diff[] = [];
let currentDiffIndex = 0;
let currentHunkIndex = 0;
text.split('\n').forEach((l) => {
if (l.startsWith('---')) {
diffs.push({
beforeFileName: '',
afterFileName: '',
hunks: [],
});
currentDiffIndex = diffs.length - 1;
currentHunkIndex = 0;
diffs[currentDiffIndex].beforeFileName = l.slice(4);
return;
}
if (l.startsWith('+++')) {
diffs[currentDiffIndex].afterFileName = l.slice(4);
return;
}
if (l.startsWith('@@')) {
const matched = l.match(hunkHeaderRegexp);
if (!matched) {
return;
}
diffs[currentDiffIndex].hunks.push({
header: {
beforeStartLine: Number(matched[1]),
beforeLines: matched[2] ? Number(matched[2]) : 1,
afterStartLine: Number(matched[3]),
afterLines: matched[4] ? Number(matched[4]) : 1,
},
lines: [],
});
currentHunkIndex = diffs[currentDiffIndex].hunks.length - 1;
return;
}
if (l.startsWith('-')) {
diffs[currentDiffIndex].hunks[currentHunkIndex].lines.push({
text: l.slice(1),
mark: 'delete',
});
return;
}
if (l.startsWith('+')) {
diffs[currentDiffIndex].hunks[currentHunkIndex].lines.push({
text: l.slice(1),
mark: 'add',
});
return;
}
if (l.startsWith(' ')) {
diffs[currentDiffIndex].hunks[currentHunkIndex].lines.push({
text: l.slice(1),
mark: 'nomodified',
});
return;
}
});
return diffs;
}