Repository navigation
Expand file tree
/
Copy pathstring.ts
More file actions
77 lines (70 loc) · 2.66 KB
/
Copy pathstring.ts
File metadata and controls
77 lines (70 loc) · 2.66 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
/**
* Unicode punctuation normalisation helpers
* Makes patch matching resilient to visually identical but different Unicode code-points
*/
const PUNCT_EQUIV: Record<string, string> = {
// Hyphen / dash variants
"-": "-",
"\u2010": "-", // HYPHEN
"\u2011": "-", // NO-BREAK HYPHEN
"\u2012": "-", // FIGURE DASH
"\u2013": "-", // EN DASH
"\u2014": "-", // EM DASH
"\u2212": "-", // MINUS SIGN
// Double quotes
"\u0022": '"', // QUOTATION MARK
"\u201C": '"', // LEFT DOUBLE QUOTATION MARK
"\u201D": '"', // RIGHT DOUBLE QUOTATION MARK
"\u201E": '"', // DOUBLE LOW-9 QUOTATION MARK
"\u00AB": '"', // LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
"\u00BB": '"', // RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
// Single quotes
"\u0027": "'", // APOSTROPHE
"\u2018": "'", // LEFT SINGLE QUOTATION MARK
"\u2019": "'", // RIGHT SINGLE QUOTATION MARK
"\u201B": "'", // SINGLE HIGH-REVERSED-9 QUOTATION MARK
// Spaces
"\u00A0": " ", // NO-BREAK SPACE
"\u202F": " ", // NARROW NO-BREAK SPACE
};
/**
* Canonicalize a string by normalizing unicode punctuation and quotes
*/
export function canonicalize(s: string): string {
// First normalize unicode and punctuation
let normalized = s.normalize("NFC").replace(/./gu, (c) => PUNCT_EQUIV[c] ?? c);
// Then normalize escaped/unescaped quotes to handle cases where:
// - patch has ` but file has \`
// - patch has ' but file has \'
// - patch has " but file has \"
normalized = normalized
.replace(/\\`/g, "`") // \` -> `
.replace(/\\'/g, "'") // \' -> '
.replace(/\\"/g, '"'); // \" -> "
return normalized;
}
/**
* Preserve the escaping style from original text when applying new text
* If original has \`, preserve that style in the replacement
*/
export function preserveEscaping(originalText: string, newText: string): string {
// Check if original has escaped backticks, quotes, or apostrophes
const hasEscapedBacktick = originalText.includes("\\`");
const hasEscapedSingleQuote = originalText.includes("\\'");
const hasEscapedDoubleQuote = originalText.includes('\\"');
let result = newText;
// Apply escaping to match original style
if (hasEscapedBacktick && !newText.includes("\\`")) {
// Escape backslashes first, then backticks
result = result.replace(/\\/g, "\\\\").replace(/`/g, "\\`");
}
if (hasEscapedSingleQuote && !newText.includes("\\'")) {
// Escape backslashes first, then single quotes
result = result.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
}
if (hasEscapedDoubleQuote && !newText.includes('\\"')) {
// Escape backslashes first, then double quotes
result = result.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
}
return result;
}