Skip to content

Commit eec5be9

Browse files
fix: Anchor type and scope patterns as a whole (#326)
* fix: Anchor type and scope patterns as a whole Patterns in `types`, `scopes` and `disallowScopes` are documented as auto-wrapped in `^ $`, but `^${pattern}$` only anchors the first and the last alternative of a pattern that contains `|`: `^feat|fix$` means `(^feat)|(fix$)`. So `types: feat|fix` accepted `feature: x` and `prefix: x`, `scopes: core|ui` accepted `cores` and `build-ui`, and `disallowScopes: release|test` rejected `releases` and `mytest`. Wrap each pattern in a non-capturing group, `^(?:${pattern})$`, so the whole pattern has to match. Well-formed patterns without `|`, and patterns already wrapped in `^ $`, behave as before. A malformed pattern can fail differently: `foo\` now throws as an invalid regex, while `a)|(b` now compiles. * test: Add a positive check for patterns with alternatives
1 parent 1ee9a55 commit eec5be9

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

‎src/validatePrTitle.js‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,13 +51,15 @@ export default async function validatePrTitle(
5151
}
5252

5353
function isUnknownScope(s) {
54-
return scopes && !scopes.some((scope) => new RegExp(`^${scope}$`).test(s));
54+
return (
55+
scopes && !scopes.some((scope) => new RegExp(`^(?:${scope})$`).test(s))
56+
);
5557
}
5658

5759
function isDisallowedScope(s) {
5860
return (
5961
disallowScopes &&
60-
disallowScopes.some((scope) => new RegExp(`^${scope}$`).test(s))
62+
disallowScopes.some((scope) => new RegExp(`^(?:${scope})$`).test(s))
6163
);
6264
}
6365

@@ -71,7 +73,7 @@ export default async function validatePrTitle(
7173
raiseError(`No subject found in pull request title "${prTitle}".`);
7274
}
7375

74-
if (!types.some((type) => new RegExp(`^${type}$`).test(result.type))) {
76+
if (!types.some((type) => new RegExp(`^(?:${type})$`).test(result.type))) {
7577
raiseError(
7678
`Unknown release type "${
7779
result.type

‎src/validatePrTitle.test.js‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,19 @@ it('throws for PR titles with an unknown type', async () => {
3939
);
4040
});
4141

42+
it('matches patterns with alternatives as a whole', async () => {
43+
await expect(
44+
validatePrTitle('feature: Bar', {types: ['feat|fix']})
45+
).rejects.toThrow('Unknown release type "feature"');
46+
await expect(
47+
validatePrTitle('fix(cores): Bar', {scopes: ['core|ui']})
48+
).rejects.toThrow('Unknown scope "cores"');
49+
await validatePrTitle('fix(ui): Bar', {scopes: ['core|ui']});
50+
await validatePrTitle('fix(releases): Bar', {
51+
disallowScopes: ['release|test']
52+
});
53+
});
54+
4255
describe('regex types', () => {
4356
const headerPattern = /^([\w-]*)(?:\(([\w$.\-*/ ]*)\))?: (.*)$/;
4457

0 commit comments

Comments
 (0)