forked from microsoft/vscode-pull-request-github
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiffPositionMapping.ts
More file actions
78 lines (63 loc) · 2.26 KB
/
diffPositionMapping.ts
File metadata and controls
78 lines (63 loc) · 2.26 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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { DiffHunk, DiffLine, parseDiffHunk } from './diffHunk';
/**
* Line position in a git diff is 1 based, except for the case when the original or changed file have
* no content, in which case it is 0. Normalize the position to be zero based.
* @param line The line in a file from the diff header
*/
export function getZeroBased(line: number): number {
if (line === undefined || line === 0) {
return 0;
}
return line - 1;
}
export function getDiffLineByPosition(diffHunks: DiffHunk[], diffLineNumber: number): DiffLine | undefined {
for (let i = 0; i < diffHunks.length; i++) {
const diffHunk = diffHunks[i];
for (let j = 0; j < diffHunk.diffLines.length; j++) {
if (diffHunk.diffLines[j].positionInHunk === diffLineNumber) {
return diffHunk.diffLines[j];
}
}
}
return undefined;
}
export function mapOldPositionToNew(patch: string, line: number): number {
const diffReader = parseDiffHunk(patch);
let diffIter = diffReader.next();
let delta = 0;
while (!diffIter.done) {
const diffHunk: DiffHunk = diffIter.value;
if (diffHunk.oldLineNumber > line) {
// No-op
} else if (diffHunk.oldLineNumber + diffHunk.oldLength - 1 < line) {
delta += diffHunk.newLength - diffHunk.oldLength;
} else {
delta += diffHunk.newLength - diffHunk.oldLength;
return line + delta;
}
diffIter = diffReader.next();
}
return line + delta;
}
export function mapNewPositionToOld(patch: string, line: number): number {
const diffReader = parseDiffHunk(patch);
let diffIter = diffReader.next();
let delta = 0;
while (!diffIter.done) {
const diffHunk: DiffHunk = diffIter.value;
if (diffHunk.newLineNumber > line) {
// No-op
} else if (diffHunk.newLineNumber + diffHunk.newLength - 1 < line) {
delta += diffHunk.oldLength - diffHunk.newLength;
} else {
delta += diffHunk.oldLength - diffHunk.newLength;
return line + delta;
}
diffIter = diffReader.next();
}
return line + delta;
}