diff --git a/src/cli/lint/internalLints/upgrade/patches/8.2.1/collapseDuplicateMergeKeys.test.ts b/src/cli/lint/internalLints/upgrade/patches/8.2.1/collapseDuplicateMergeKeys.test.ts index c41692b5b..12f2e3c9f 100644 --- a/src/cli/lint/internalLints/upgrade/patches/8.2.1/collapseDuplicateMergeKeys.test.ts +++ b/src/cli/lint/internalLints/upgrade/patches/8.2.1/collapseDuplicateMergeKeys.test.ts @@ -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 diff --git a/src/cli/lint/internalLints/upgrade/patches/8.2.1/collapseDuplicateMergeKeys.ts b/src/cli/lint/internalLints/upgrade/patches/8.2.1/collapseDuplicateMergeKeys.ts index 7cdaec5e8..dbbde40fe 100644 --- a/src/cli/lint/internalLints/upgrade/patches/8.2.1/collapseDuplicateMergeKeys.ts +++ b/src/cli/lint/internalLints/upgrade/patches/8.2.1/collapseDuplicateMergeKeys.ts @@ -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; },