Skip to content

Commit

Permalink
Merge pull request #16 from beuluis/feature/add-more-hooks
Browse files Browse the repository at this point in the history
Feature/add more hooks
  • Loading branch information
beuluis authored May 16, 2023
2 parents 630f58b + 6dcc501 commit 9423265
Show file tree
Hide file tree
Showing 8 changed files with 505 additions and 16 deletions.
126 changes: 121 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,89 @@ Run commands. For example using the hooks in `.husky`.

### Commands

#### checkCommitMessageIssueKey

Check the pattern of a commit message

| Option | Description | Type | default |
| ----------------- | ------------------------------------------------------------------------ | --------- | ------- |
| `-p`, `--prefix` | Prefix of the issue key. | `string` | `` |
| `-m`, `--message` | Get message from command line instead of file. | `string` | `` |
| `-n`, `--no-fail` | If true only prints warning messages and do not exit with not zero code. | `boolean` | `false` |

##### Example usage

```bash
npx hook-cli checkCommitMessageIssueKey "$1" -p "HelloWorld"
```

```bash
npx hook-cli checkCommitMessageIssueKey .git/COMMIT_EDITMSG -p "KEY"
```

```bash
npx hook-cli checkCommitMessageIssueKey -m "KEY-12 message" -p "KEY"
```

```bash
npx hook-cli checkCommitMessageIssueKey -m "KEY-12 message" -p "KEY" -n
```

#### checkCommitMessagePattern

Check the pattern of a commit message

| Option | Description | Type | default |
| ----------------- | ------------------------------------------------------------------------ | --------- | ------- |
| `-p`, `--pattern` | Regex pattern to check the message against. | `string` | `` |
| `-m`, `--message` | Get message from command line instead of file. | `string` | `` |
| `-n`, `--no-fail` | If true only prints warning messages and do not exit with not zero code. | `boolean` | `false` |

##### Example usage

```bash
npx hook-cli checkCommitMessagePattern "$1" -p "HelloWorld"
```

```bash
npx hook-cli checkCommitMessagePattern .git/COMMIT_EDITMSG -p "HelloWorld"
```

```bash
npx hook-cli checkCommitMessagePattern -m "I say HelloWorld" -p "HelloWorld"
```

```bash
npx hook-cli checkCommitMessagePattern -m "I say HelloWorld" -p "HelloWorld" -n
```

#### checkForFileChanged

Check if a staged file like a changelog was changed locale or remote compared to another branch

| Option | Description | Type | default |
| ----------------- | ------------------------------------------------------------------------ | --------- | ------- |
| `-b`, `--branch` | Branch to compare to. | `string` | `main` |
| `-n`, `--no-fail` | If true only prints warning messages and do not exit with not zero code. | `boolean` | `true` |

##### Example usage

```bash
npx hook-cli checkForFileChanged CHANGELOG.md
```

```bash
npx hook-cli checkForFileChanged CHANGELOG.md -b trunk
```

```bash
npx hook-cli checkForFileChanged CHANGELOG.md -n
```

```bash
npx hook-cli checkForFileChanged CHANGELOG.md -b trunk -n
```

#### checkForVulnerabilities

Runs a package audit and collects the results.
Expand All @@ -56,8 +139,8 @@ Runs a package audit and collects the results.
| ------------------------- | ------------------------------------------------------------------------------------------------ | --------------------------------------------- | ---------- |
| `-m`, `--package-manager` | The package manager you want to use. Keep in mind that both package managers report differently. | `yarn`, `npm` | `npm` |
| `-l`, `--audit-level` | The severity of the vulnerabilities what the script will report. | `info`, `low`, `moderate`, `high`, `critical` | `critical` |
| `-n`, `--no-fail` | If true only prints warning messages and do not exit with not zero code. | `boolean` | `false` |
| `-p`, `--prod` | If true only run audit for prod dependencies and skip dev ones. | `boolean` | `false` |
| `-n`, `--no-fail` | If true only prints warning messages and do not exit with not zero code. | `boolean` | `false` |

##### Example usage

Expand Down Expand Up @@ -85,14 +168,47 @@ npx hook-clicheckForVulnerabilities --prod
npx hook-cli checkForVulnerabilities -l high -m yarn -n -p
```

#### checkPackageVersion

Check if the version field is the same for package.json and package-lock.json

| Option | Description | Type | default |
| ----------------- | ------------------------------------------------------------------------ | --------- | ------- |
| `-n`, `--no-fail` | If true only prints warning messages and do not exit with not zero code. | `boolean` | `false` |

##### Example usage

```bash
npx hook-cli checkPackageVersion
```

#### checkPackageVersionInFile

Check if the version field is the same for package.json and file

| Option | Description | Type | default |
| ------------------- | ------------------------------------------------------------------------ | --------- | ------- |
| `-p`, `--json-path` | Path in json file to check | `string` | `` |
| `-n`, `--no-fail` | If true only prints warning messages and do not exit with not zero code. | `boolean` | `false` |

##### Example usage

```bash
npx hook-cli checkPackageVersionInFile hello.json -p 'path.version'
```

```bash
npx hook-cli checkPackageVersionInFile hello.json -p 'path.version' -n
```

#### updateReminder

Prints a list of packages that have updates.

| Option | Description | Type | default |
| ------------------------- | ------------------------------------------------------------------------------------------------ | ------------- | ------- |
| `-m`, `--package-manager` | The package manager you want to use. Keep in mind that both package managers report differently. | `yarn`, `npm` | `npm` |
| `-f`, `--fail` | If true it will exit with a non zero in case of updates. | `boolean` | `false` |
| `-n`, `--no-fail` | If true only prints warning messages and do not exit with not zero code. | `boolean` | `false` |

##### Example usage

Expand All @@ -101,15 +217,15 @@ npx hook-cli updateReminder
```

```bash
npx hook-cli updateReminder - yarn
npx hook-cli updateReminder -m yarn
```

```bash
npx hook-cli updateReminder -f
npx hook-cli updateReminder -n
```

```bash
npx hook-cli updateReminder - yarn -f
npx hook-cli updateReminder -m yarn -n
```

<!-- REGISTER NEW COMMAND -->
Expand Down
74 changes: 74 additions & 0 deletions src/modules/checkCommitMessageIssueKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import Listr from 'listr';
import { HookFailedError, registerCommandModule } from '../util/commandModule.helper';
import { execute, ExecuteError } from '../util/exec.helper';

export = registerCommandModule<{ commitMsgPath: string }>()({
command: 'checkCommitMessageIssueKey [commitMsgPath]',
describe: 'Check the commit message for a issue key',
builder: {
'no-fail': {
alias: 'n',
type: 'boolean',
description: 'If true only prints warning messages and do not exit with not zero code',
default: false,
},
message: {
alias: 'm',
type: 'string',
description: 'Get message from command line instead of file',
},
prefix: {
alias: 'p',
type: 'string',
description: 'Prefix of the issue key',
},
},
handler: async argv => {
const { 'no-fail': noFail, prefix, message, commitMsgPath } = argv;
const tasks = new Listr([
{
title: 'Check if commit message contains issue key',
task: async (_context, task) => {
if (!commitMsgPath && !message) {
task.title = 'No commit message provided';
throw new HookFailedError();
}

// eslint-disable-next-line canonical/id-match
const command = __filename.endsWith('.ts')
? 'npx ts-node src/index.ts checkCommitMessagePattern'
: 'npx hook-cli checkCommitMessagePattern';

const messageArguments = message ? `-m "${message}"` : commitMsgPath;

const ticketRegex = `^(${prefix ? prefix : '[A-Z]+'}-[0-9]{1,10})( ?/ ?(${
prefix ? prefix : '[A-Z]+'
}-[0-9]{1,10}))*? (?!/).*`;

await execute(`${command} ${messageArguments} -p "${ticketRegex}"`)
.then(() => (task.title = 'Issue key found'))
.catch(async (error: unknown) => {
if (error instanceof ExecuteError) {
task.title = 'Issue key not found';
throw new HookFailedError();
} else {
// eslint-disable-next-line unicorn/prefer-type-error
throw new Error('Unknown error');
}
});
},
},
]);

try {
await tasks.run();
process.exit(0);
} catch (error) {
if (error instanceof HookFailedError && noFail) {
process.exit(0);
}

process.exit(1);
}
},
});
86 changes: 86 additions & 0 deletions src/modules/checkCommitMessagePattern.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import fs from 'fs';
import Listr from 'listr';
import { HookFailedError, registerCommandModule } from '../util/commandModule.helper';

const ignoreWildcards: RegExp[] = [
// eslint-disable-next-line unicorn/no-unsafe-regex
/^((Merge pull request)|(Merge (.*?) into (.*)|(Merge branch (.*)))(?:\r?\n)*$)/mu,
// eslint-disable-next-line unicorn/no-unsafe-regex
/^(Merge tag (.*))(?:\r?\n)*$/mu,
/^(R|r)evert (.*)/u,
/^(fixup|squash)!/u,
/^(Merged (.*?)(in|into) (.*)|Merged PR (.*): (.*))/u,
/^Merge remote-tracking branch(\s*)(.*)/u,
/^Automatic merge(.*)/u,
/^Auto-merged (.*?) into (.*)/u,
];

export = registerCommandModule<{ commitMsgPath: string }>()({
command: 'checkCommitMessagePattern [commitMsgPath]',
describe: 'Check the pattern of a commit message',
builder: {
'no-fail': {
alias: 'n',
type: 'boolean',
description: 'If true only prints warning messages and do not exit with not zero code',
default: false,
},
message: {
alias: 'm',
type: 'string',
description: 'Get message from command line instead of file',
},
pattern: {
alias: 'p',
type: 'string',
description: 'Regex pattern to check the message against',
},
},
handler: async argv => {
const { 'no-fail': noFail, message, pattern, commitMsgPath } = argv;
const tasks = new Listr([
{
title: 'Check if commit message matches pattern',
task: async (_context, task) => {
if (!commitMsgPath && !message) {
task.title = 'No commit message provided';
throw new HookFailedError();
}

if (!pattern) {
task.title = 'No pattern provided';
throw new HookFailedError();
}

const finalMessage = message ?? fs.readFileSync(commitMsgPath, 'utf8');

for (const ignorePattern of ignoreWildcards) {
if (ignorePattern.test(finalMessage)) {
task.title = 'Commit message matches ignore pattern';

process.exit(0);
}
}

if (!new RegExp(pattern, 'u').test(finalMessage)) {
task.title = 'Commit message does not match pattern';
throw new HookFailedError();
}

task.title = 'Commit message matches pattern';
},
},
]);

try {
await tasks.run();
process.exit(0);
} catch (error) {
if (error instanceof HookFailedError && noFail) {
process.exit(0);
}

process.exit(1);
}
},
});
63 changes: 63 additions & 0 deletions src/modules/checkForFileChanged.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { color } from 'console-log-colors';
import Listr from 'listr';
import { HookFailedError, registerCommandModule } from '../util/commandModule.helper';
import { execute, ExecuteError } from '../util/exec.helper';

export = registerCommandModule<{ filePath: string }>()({
command: 'checkForFileChanged [filePath]',
describe:
'Check if a staged file like a changelog was changed locale or remote compared to another branch',
builder: {
'no-fail': {
alias: 'n',
type: 'boolean',
description: 'If true only prints warning messages and do not exit with not zero code',
default: false,
},
branch: {
alias: 'b',
type: 'string',
description: 'Branch to compare to',
default: 'main',
},
},
handler: async argv => {
const { 'no-fail': noFail, branch, filePath } = argv;
const tasks = new Listr([
{
title: `Check if ${color.cyan(filePath)} differs from ${color.cyan(branch)}`,
task: async (_context, task) =>
await execute(`! git diff origin/${branch} --cached --exit-code -- ${filePath}`)
.then(
() =>
(task.title = `${color.green(
filePath,
)} differs from the version on ${color.green(branch)}`),
)
.catch(async (error: unknown) => {
if (error instanceof ExecuteError) {
task.title = `${color.red(filePath)} do not differ from ${color.red(
branch,
)}`;
throw new HookFailedError();
} else {
// TODO: recheck if we dont have a message for such cases
// eslint-disable-next-line unicorn/prefer-type-error
throw new Error('Unknown error');
}
}),
},
]);

try {
await tasks.run();
process.exit(0);
} catch (error) {
if (error instanceof HookFailedError && noFail) {
process.exit(0);
}

process.exit(1);
}
},
});
Loading

0 comments on commit 9423265

Please sign in to comment.