Skip to content

Commit 23cef6b

Browse files
committed
fix(studio): the colour ratchet keeps strings when stripping comments
1 parent 78f0cfb commit 23cef6b

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

‎packages/studio/src/styles/hexRatchet.test.ts‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,20 +27,27 @@ function isScanned(relative: string): boolean {
2727
return /\.(tsx?|css)$/.test(relative);
2828
}
2929

30+
/** Strings match first and are kept, so `"image/*"` or `"a//b"` never opens a comment. */
31+
const STRING_OR_COMMENT =
32+
/("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g;
33+
3034
/** Comments hold issue numbers like `#2291` that read as hex; count code only. */
31-
function stripComments(text: string): string {
32-
return text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`])\/\/.*$/gm, "$1");
35+
function stripComments(text: string, lineComments: boolean): string {
36+
return text.replace(STRING_OR_COMMENT, (match, string?: string) => {
37+
if (string !== undefined) return match;
38+
return match.startsWith("//") && !lineComments ? match : "";
39+
});
3340
}
3441

35-
function countColorLiterals(text: string): number {
36-
return [...stripComments(text).matchAll(COLOR_LITERAL)].length;
42+
function countColorLiterals(text: string, lineComments = true): number {
43+
return [...stripComments(text, lineComments).matchAll(COLOR_LITERAL)].length;
3744
}
3845

3946
/** Repository-relative path to colour-literal count, for every scanned file. */
4047
function scan(): Map<string, number> {
4148
const counts = new Map<string, number>();
4249
for (const [file, text] of listSourceFiles(isScanned, REPO_ROOT)) {
43-
const count = countColorLiterals(text);
50+
const count = countColorLiterals(text, !file.endsWith(".css"));
4451
if (count > 0) counts.set(file, count);
4552
}
4653
return counts;
@@ -117,6 +124,12 @@ describe("colour literal counter", () => {
117124
expect(countColorLiterals(`href="#section-two" // see #12345`)).toBe(0);
118125
});
119126

127+
it("keeps a colour that follows comment-shaped text inside a string", () => {
128+
expect(countColorLiterals(`accept="image/*"; const c = "#161618"; x = "*/";`)).toBe(1);
129+
expect(countColorLiterals("const u = `x//y`; const c = '#161618';")).toBe(1);
130+
expect(countColorLiterals(`.a { background: url(//cdn.test/a.png) #161618; }`, false)).toBe(1);
131+
});
132+
120133
it("ignores a colour-shaped issue number in a line or block comment", () => {
121134
expect(countColorLiterals(`const a = 1; // decision (#2291)`)).toBe(0);
122135
expect(countColorLiterals(`/** see #2291 and rgba(0,0,0,1) */\nconst a = 1;`)).toBe(0);

0 commit comments

Comments
 (0)