Commit bf4adbcd authored by Thomas Randolph's avatar Thomas Randolph

Add a utility for getting a suggestion commit message

By default, the commit message has a bunch of variables
in it, like `%{some_var}`. We want to be able to replace
those variables with actual values. Rather than doing it
ad hoc (maybe in some leaf component), this utility
provides a central place where that logic lives.
parent 9f4230b0
function removeEmptyProperties(dict) {
const noBlanks = Object.entries(dict).reduce((final, [key, value]) => {
const upd = { ...final };
// The number 0 shouldn't be falsey when we're printing variables
if (value || value === 0) {
upd[key] = value;
}
return upd;
}, {});
return noBlanks;
}
export function computeSuggestionCommitMessage({ message, values = {} } = {}) {
const noEmpties = removeEmptyProperties(values);
const matchPhrases = Object.keys(noEmpties)
.map((key) => `%{${key}}`)
.join('|');
const replacementExpression = new RegExp(`(${matchPhrases})`, 'gm');
return message.replace(replacementExpression, (match) => {
const key = match.replace(/(^%{|}$)/gm, '');
return noEmpties[key];
});
}
import { computeSuggestionCommitMessage } from '~/diffs/utils/suggestions';
describe('Diff Suggestions utilities', () => {
describe('computeSuggestionCommitMessage', () => {
it.each`
description | input | values | output
${'makes the appropriate replacements'} | ${'%{foo} %{bar}'} | ${{ foo: 'foo', bar: 'bar' }} | ${'foo bar'}
${"skips replacing values that aren't passed"} | ${'%{foo} %{bar}'} | ${{ foo: 'foo' }} | ${'foo %{bar}'}
${'treats the number 0 as a valid value (not falsey)'} | ${'%{foo} %{bar}'} | ${{ foo: 'foo', bar: 0 }} | ${'foo 0'}
${"works when the variables don't have any space between them"} | ${'%{foo}%{bar}'} | ${{ foo: 'foo', bar: 'bar' }} | ${'foobar'}
`('$description', ({ input, output, values }) => {
expect(computeSuggestionCommitMessage({ message: input, values })).toBe(output);
});
});
});
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