Preserve text indentation

Match tabs and spaces leading the token so that indentation is preserved
when inserting hints.
parent d811c7b3
...@@ -11,7 +11,15 @@ export const insertTip = ({ snippet, tip, token }) => { ...@@ -11,7 +11,15 @@ export const insertTip = ({ snippet, tip, token }) => {
if (!isString(token)) { if (!isString(token)) {
throw new Error('token must be a string'); throw new Error('token must be a string');
} }
return snippet.replace(token, `# ${tip}\n${token}`); const lines = snippet.split('\n');
for (let i = 0; i < lines.length; i += 1) {
if (lines[i].includes(token)) {
const indent = lines[i].match(/^[ \t]+/)?.[0] ?? '';
lines[i] = lines[i].replace(token, `# ${tip}\n${indent}${token}`);
break;
}
}
return lines.join('\n');
}; };
export const insertTips = (snippet, tips = []) => export const insertTips = (snippet, tips = []) =>
......
...@@ -43,6 +43,27 @@ describe('insertTip', () => { ...@@ -43,6 +43,27 @@ describe('insertTip', () => {
}), }),
).toBe(expected); ).toBe(expected);
}); });
it('preserves indentation', () => {
const snippet = `---
default:
artifacts:
expire_in: 30 days`;
const expected = `---
default:
artifacts:
# a very helpful tip
expire_in: 30 days`;
expect(
insertTip({
snippet,
token: 'expire_in:',
tip,
}),
).toBe(expected);
});
}); });
describe('insertTips', () => { describe('insertTips', () => {
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment