-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatch.ts
More file actions
80 lines (69 loc) · 1.97 KB
/
Copy pathpatch.ts
File metadata and controls
80 lines (69 loc) · 1.97 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
import { findPythonVersionMatches, type VersionMatch } from '../scanning';
export interface RewriteContext {
filePath: string;
originalContent: string;
fromVersion: string;
toVersion: string;
}
export interface PatchResult {
filePath: string;
originalContent: string;
updatedContent: string;
changed: boolean;
replacements: VersionMatch[];
fromVersion: string;
toVersion: string;
}
function shareTrack(fromVersion: string, toVersion: string): boolean {
const fromParts = fromVersion.split('.');
const toParts = toVersion.split('.');
return fromParts[0] === toParts[0] && fromParts[1] === toParts[1];
}
export function computePatch(context: RewriteContext): PatchResult {
const { filePath, originalContent, fromVersion, toVersion } = context;
if (!shareTrack(fromVersion, toVersion)) {
return {
filePath,
originalContent,
updatedContent: originalContent,
changed: false,
replacements: [],
fromVersion,
toVersion,
};
}
const matches = findPythonVersionMatches(filePath, originalContent);
const replacements = matches.filter((match) => match.matched === fromVersion);
if (replacements.length === 0) {
return {
filePath,
originalContent,
updatedContent: originalContent,
changed: false,
replacements: [],
fromVersion,
toVersion,
};
}
const sortedReplacements = [...replacements].sort((a, b) => a.index - b.index);
let cursor = 0;
let updatedContent = '';
for (const replacement of sortedReplacements) {
const start = replacement.index;
const end = start + fromVersion.length;
updatedContent += originalContent.slice(cursor, start);
updatedContent += toVersion;
cursor = end;
}
updatedContent += originalContent.slice(cursor);
const changed = cursor !== 0 && updatedContent !== originalContent;
return {
filePath,
originalContent,
updatedContent,
changed,
replacements,
fromVersion,
toVersion,
};
}