Skip to content

Commit

Permalink
Make beautiful regex even beautifuler (#1690)
Browse files Browse the repository at this point in the history
  • Loading branch information
AaronMoat committed Sep 28, 2024
1 parent 5fd488d commit 893b968
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,72 @@ steps:
});
});

it('should handle comments', async () => {
const input = `
steps:
- <<: *prod # hi
<<: *timeout
label: 'My Step'
command: echo 'Hello, world!'
- <<: *prod
<<: *timeout# hi
label: 'My Step'
command: echo 'Hello, world!'
- <<: *prod # hello
<<: *timeout# world
label: 'My Step'
command: echo 'Hello, world!'
- label: something
<<: *prod # hello
<<: *timeout# world
command: echo 'Hello, world!'
`;

vol.fromJSON({
'.buildkite/pipeline.yml': input,
});

await expect(
tryCollapseDuplicateMergeKeys({
...baseArgs,
mode,
}),
).resolves.toEqual({ result: 'apply' });

expect(volToJson()).toEqual({
'.buildkite/pipeline.yml':
mode === 'lint'
? input
: `
steps:
# hi
- <<: [*prod, *timeout]
label: 'My Step'
command: echo 'Hello, world!'
# hi
- <<: [*prod, *timeout]
label: 'My Step'
command: echo 'Hello, world!'
# hello
# world
- <<: [*prod, *timeout]
label: 'My Step'
command: echo 'Hello, world!'
- label: something
# hello
# world
<<: [*prod, *timeout]
command: echo 'Hello, world!'
`,
});
});

it('should not bother if the keys are separated by other keys', async () => {
const input = `steps:
- <<: *prod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,18 @@ const collapseDuplicateMergeKeys: PatchFunction = async ({
const collapseDuplicateMergeKeysInFile = (input: string) =>
replaceAllUntilStable(
input,
/^([ \-]*)<<: \[?(\*[^\n\]]+)\]?$\n^( *)<<: \[?(\*[^\n\]]+)\]?$/gm,
(match, a, b, c, d) => {
if (a.length === c.length) {
return `${a}<<: [${b}, ${d}]`;
/^([ \-]*)<<: \[?(\*[^\n#\]]+)\]?(\s*#.*)?$\n^( *)<<: \[?(\*[^\n#\]]+)\]?(\s*#.*)?$/gm,
(match, prefixA, keyA, commentA, prefixB, keyB, commentB) => {
if (prefixA.length === prefixB.length) {
return [
...(commentA
? [`${' '.repeat(prefixA.length)}${commentA.trim()}`]
: []),
...(commentB
? [`${' '.repeat(prefixA.length)}${commentB.trim()}`]
: []),
`${prefixA}<<: [${keyA.trim()}, ${keyB.trim()}]`,
].join('\n');
}
return match;
},
Expand Down

0 comments on commit 893b968

Please sign in to comment.