diff --git a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml
index 67670dc8fd..7e1df48553 100644
--- a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml
+++ b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml
@@ -1,7 +1,7 @@
-name: '🐛 Bug Report'
+name: "🐛 Bug Report"
description: Create a new ticket for a bug.
-title: 'fix:
'
-labels: ['bug']
+title: "fix: "
+labels: ["bug"]
body:
- type: markdown
attributes:
@@ -10,7 +10,7 @@ body:
- type: textarea
id: steps-to-reproduce
attributes:
- label: 'Steps to Reproduce'
+ label: "Steps to Reproduce"
description: Provide a link to a live example, or an unambiguous set of steps to reproduce this bug. Include code to reproduce, if relevant
value: |
1. First step
@@ -21,14 +21,14 @@ body:
- type: textarea
id: current-behavior
attributes:
- label: 'Current Behavior'
+ label: "Current Behavior"
description: Tell us what happens instead of the expected behavior
validations:
required: false
- type: textarea
id: expected-behavior
attributes:
- label: 'Expected Behavior'
+ label: "Expected Behavior"
description: Tell us what should happen
placeholder: Short and explicit description of your incident...
validations:
@@ -36,7 +36,7 @@ body:
- type: checkboxes
id: affected-packages
attributes:
- label: 'Affected packages'
+ label: "Affected packages"
options:
- label: cli
- label: core
@@ -45,14 +45,14 @@ body:
- type: textarea
id: possible-solution
attributes:
- label: 'Possible Solution'
+ label: "Possible Solution"
description: Not obligatory, but suggest a fix/reason for the bug, or ideas how to implement the addition or change
validations:
required: false
- type: textarea
id: context
attributes:
- label: 'Context'
+ label: "Context"
description: |
How has this issue affected you? What are you trying to accomplish?
Providing context helps us come up with a solution that is most useful in the real world
@@ -61,21 +61,21 @@ body:
- type: input
id: commitlint-version
attributes:
- label: 'commitlint --version'
- placeholder: '@commitlint/cli@x.x.x'
+ label: "commitlint --version"
+ placeholder: "@commitlint/cli@x.x.x"
validations:
required: true
- type: input
id: git-version
attributes:
- label: 'git --version'
+ label: "git --version"
placeholder: vx.x.x
validations:
required: true
- type: input
id: node-version
attributes:
- label: 'node --version'
+ label: "node --version"
placeholder: vx.x.x
validations:
required: true
diff --git a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml
index bf4e9609df..063dd15fe4 100644
--- a/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml
+++ b/.github/ISSUE_TEMPLATE/FEATURE_REQUEST.yml
@@ -1,7 +1,7 @@
-name: '✨ Feature Request'
+name: "✨ Feature Request"
description: Create a new ticket for a new feature request
-title: 'feat: '
-labels: ['feature']
+title: "feat: "
+labels: ["feature"]
body:
- type: markdown
attributes:
@@ -10,7 +10,7 @@ body:
- type: textarea
id: expected-behavior
attributes:
- label: 'Expected Behavior'
+ label: "Expected Behavior"
description: Tell us how it should work
placeholder: Short and explicit description of your request...
validations:
@@ -18,14 +18,14 @@ body:
- type: textarea
id: current-behavior
attributes:
- label: 'Current Behavior'
+ label: "Current Behavior"
description: Explain the difference from current behavior
validations:
required: false
- type: checkboxes
id: affected-packages
attributes:
- label: 'Affected packages'
+ label: "Affected packages"
options:
- label: cli
- label: core
@@ -34,14 +34,14 @@ body:
- type: textarea
id: possible-solution
attributes:
- label: 'Possible Solution'
+ label: "Possible Solution"
description: Ideas how to implement the addition or change
validations:
required: false
- type: textarea
id: context
attributes:
- label: 'Context'
+ label: "Context"
description: |
How has this issue affected you? What are you trying to accomplish?
Providing context helps us come up with a solution that is most useful in the real world
diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml
index 234d2ac6f6..6ca2a6a64b 100644
--- a/.github/workflows/CI.yml
+++ b/.github/workflows/CI.yml
@@ -3,7 +3,7 @@ name: CI
on:
push:
branches:
- - '**'
+ - "**"
pull_request:
types: [opened, synchronize]
@@ -11,7 +11,7 @@ on:
# to execute once a day (more info see https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule )
schedule:
- - cron: '0 0 * * *'
+ - cron: "0 0 * * *"
jobs:
build:
@@ -62,7 +62,7 @@ jobs:
name: NodeJS installed from stock Ubuntu-LTS packages (not external sources)
runs-on: ubuntu-24.04
container:
- image: 'ubuntu:24.04'
+ image: "ubuntu:24.04"
steps:
- uses: actions/checkout@v4
diff --git a/.github/workflows/container-build.yml b/.github/workflows/container-build.yml
index 4465d2f52a..398cc419c3 100644
--- a/.github/workflows/container-build.yml
+++ b/.github/workflows/container-build.yml
@@ -2,12 +2,12 @@ name: container build
on:
push:
tags:
- - '**'
+ - "**"
schedule:
- - cron: '0 0 * * *'
+ - cron: "0 0 * * *"
pull_request:
paths:
- - 'Dockerfile.ci'
+ - "Dockerfile.ci"
jobs:
container-build:
if: github.repository == 'conventional-changelog/commitlint'
diff --git a/@alias/commitlint-config-angular/index.js b/@alias/commitlint-config-angular/index.js
index 772977fc4c..0598f27f73 100644
--- a/@alias/commitlint-config-angular/index.js
+++ b/@alias/commitlint-config-angular/index.js
@@ -1 +1 @@
-export {default} from '@commitlint/config-angular';
+export { default } from "@commitlint/config-angular";
diff --git a/@alias/commitlint-config-lerna-scopes/index.js b/@alias/commitlint-config-lerna-scopes/index.js
index 0cfd98ac94..000c9673ee 100644
--- a/@alias/commitlint-config-lerna-scopes/index.js
+++ b/@alias/commitlint-config-lerna-scopes/index.js
@@ -1 +1 @@
-export {default} from '@commitlint/config-lerna-scopes';
+export { default } from "@commitlint/config-lerna-scopes";
diff --git a/@alias/commitlint-config-nx-scopes/index.js b/@alias/commitlint-config-nx-scopes/index.js
index 3e6a1de683..2ba02e27da 100644
--- a/@alias/commitlint-config-nx-scopes/index.js
+++ b/@alias/commitlint-config-nx-scopes/index.js
@@ -1 +1 @@
-export {default} from '@commitlint/config-nx-scopes';
+export { default } from "@commitlint/config-nx-scopes";
diff --git a/@alias/commitlint-config-patternplate/index.js b/@alias/commitlint-config-patternplate/index.js
index 085cdbe448..d95944f6eb 100644
--- a/@alias/commitlint-config-patternplate/index.js
+++ b/@alias/commitlint-config-patternplate/index.js
@@ -1 +1 @@
-export {default} from '@commitlint/config-patternplate';
+export { default } from "@commitlint/config-patternplate";
diff --git a/@alias/commitlint/cli.js b/@alias/commitlint/cli.js
index 3a54821b24..4b917c9cf5 100755
--- a/@alias/commitlint/cli.js
+++ b/@alias/commitlint/cli.js
@@ -1,2 +1,2 @@
#!/usr/bin/env node
-import '@commitlint/cli/cli.js';
+import "@commitlint/cli/cli.js";
diff --git a/@alias/commitlint/cli.test.js b/@alias/commitlint/cli.test.js
index 5f0674233b..ff28c511b3 100644
--- a/@alias/commitlint/cli.test.js
+++ b/@alias/commitlint/cli.test.js
@@ -1,16 +1,16 @@
-import {test, expect} from 'vitest';
-import {createRequire} from 'node:module';
-import path from 'node:path';
-import {fileURLToPath} from 'node:url';
+import { test, expect } from "vitest";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
-import {x} from 'tinyexec';
-import {fix} from '@commitlint/test';
+import { x } from "tinyexec";
+import { fix } from "@commitlint/test";
const require = createRequire(import.meta.url);
-const __dirname = path.resolve(fileURLToPath(import.meta.url), '..');
+const __dirname = path.resolve(fileURLToPath(import.meta.url), "..");
-const bin = require.resolve('./cli.js');
+const bin = require.resolve("./cli.js");
function cli(args, options, input) {
const result = x(bin, args, {
@@ -28,15 +28,15 @@ function cli(args, options, input) {
const fixBootstrap = (fixture) => fix.bootstrap(fixture, __dirname);
-test('should reprint input from stdin', async () => {
- const cwd = await fixBootstrap('fixtures/default');
- const actual = await cli([], {cwd}, 'foo: bar');
- expect(actual.stdout).toContain('foo: bar');
+test("should reprint input from stdin", async () => {
+ const cwd = await fixBootstrap("fixtures/default");
+ const actual = await cli([], { cwd }, "foo: bar");
+ expect(actual.stdout).toContain("foo: bar");
});
-test('should produce success output with --verbose flag', async () => {
- const cwd = await fixBootstrap('fixtures/default');
- const actual = await cli(['--verbose'], {cwd}, 'type: bar');
- expect(actual.stdout).toContain('0 problems, 0 warnings');
- expect(actual.stderr).toEqual('');
+test("should produce success output with --verbose flag", async () => {
+ const cwd = await fixBootstrap("fixtures/default");
+ const actual = await cli(["--verbose"], { cwd }, "type: bar");
+ expect(actual.stdout).toContain("0 problems, 0 warnings");
+ expect(actual.stderr).toEqual("");
});
diff --git a/@commitlint/cli/cli.js b/@commitlint/cli/cli.js
index 1bda77159f..940e27804b 100755
--- a/@commitlint/cli/cli.js
+++ b/@commitlint/cli/cli.js
@@ -1,2 +1,2 @@
#!/usr/bin/env node
-import './lib/cli.js';
+import "./lib/cli.js";
diff --git a/@commitlint/cli/src/cli-error.ts b/@commitlint/cli/src/cli-error.ts
index 69db5917bc..8b21ae31ee 100644
--- a/@commitlint/cli/src/cli-error.ts
+++ b/@commitlint/cli/src/cli-error.ts
@@ -15,7 +15,7 @@ export class CliError extends Error {
constructor(
message: string,
type: string,
- error_code = ExitCode.CommitlintErrorDefault
+ error_code = ExitCode.CommitlintErrorDefault,
) {
super(message);
diff --git a/@commitlint/cli/src/cli.test.ts b/@commitlint/cli/src/cli.test.ts
index 235e5f8849..d65a5e57ab 100644
--- a/@commitlint/cli/src/cli.test.ts
+++ b/@commitlint/cli/src/cli.test.ts
@@ -1,18 +1,18 @@
-import {describe, test, expect} from 'vitest';
-import {createRequire} from 'node:module';
-import path from 'node:path';
-import {fileURLToPath} from 'node:url';
-import {fix, git} from '@commitlint/test';
-import fs from 'fs-extra';
-import merge from 'lodash.merge';
-import {x} from 'tinyexec';
-import {ExitCode} from './cli-error.js';
+import { describe, test, expect } from "vitest";
+import { createRequire } from "node:module";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { fix, git } from "@commitlint/test";
+import fs from "fs-extra";
+import merge from "lodash.merge";
+import { x } from "tinyexec";
+import { ExitCode } from "./cli-error.js";
const require = createRequire(import.meta.url);
-const __dirname = path.resolve(fileURLToPath(import.meta.url), '..');
+const __dirname = path.resolve(fileURLToPath(import.meta.url), "..");
-const bin = require.resolve('../cli.js');
+const bin = require.resolve("../cli.js");
interface TestOptions {
cwd: string;
@@ -20,7 +20,7 @@ interface TestOptions {
}
const cli = (args: string[], options: TestOptions) => {
- return (input = '') => {
+ return (input = "") => {
const result = x(bin, args, {
nodeOptions: {
cwd: options.cwd,
@@ -38,542 +38,551 @@ const cli = (args: string[], options: TestOptions) => {
const gitBootstrap = (fixture: string) => git.bootstrap(fixture, __dirname);
const fixBootstrap = (fixture: string) => fix.bootstrap(fixture, __dirname);
-test('should throw when called without [input]', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli([], {cwd})();
+test("should throw when called without [input]", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli([], { cwd })();
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should reprint input from stdin', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli([], {cwd})('foo: bar');
+test("should reprint input from stdin", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli([], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toContain('foo: bar');
+ expect(output.stdout.trim()).toContain("foo: bar");
});
-test('should produce success output with --verbose flag', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli(['--verbose'], {cwd})('type: bar');
+test("should produce success output with --verbose flag", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli(["--verbose"], { cwd })("type: bar");
const output = await result;
- expect(output.stdout.trim()).toContain('0 problems, 0 warnings');
- expect(output.stderr).toEqual('');
+ expect(output.stdout.trim()).toContain("0 problems, 0 warnings");
+ expect(output.stderr).toEqual("");
});
-test('should produce last commit and success output with --verbose flag', async () => {
- const cwd = await gitBootstrap('fixtures/simple');
- await x('git', ['add', 'commitlint.config.js'], {nodeOptions: {cwd}});
- await x('git', ['commit', '-m', '"test: this should work"'], {
- nodeOptions: {cwd},
+test("should produce last commit and success output with --verbose flag", async () => {
+ const cwd = await gitBootstrap("fixtures/simple");
+ await x("git", ["add", "commitlint.config.js"], { nodeOptions: { cwd } });
+ await x("git", ["commit", "-m", '"test: this should work"'], {
+ nodeOptions: { cwd },
});
- const result = cli(['--last', '--verbose'], {cwd})();
+ const result = cli(["--last", "--verbose"], { cwd })();
const output = await result;
- expect(output.stdout.trim()).toContain('0 problems, 0 warnings');
- expect(output.stdout.trim()).toContain('test: this should work');
- expect(output.stderr).toEqual('');
+ expect(output.stdout.trim()).toContain("0 problems, 0 warnings");
+ expect(output.stdout.trim()).toContain("test: this should work");
+ expect(output.stderr).toEqual("");
});
-test('regression test for running with --last flag', async () => {
- const cwd = await gitBootstrap('fixtures/last-flag-regression');
- await x('git', ['add', 'commitlint.config.js'], {nodeOptions: {cwd}});
- await x('git', ['commit', '-m', '"test: this should work"'], {
- nodeOptions: {cwd},
+test("regression test for running with --last flag", async () => {
+ const cwd = await gitBootstrap("fixtures/last-flag-regression");
+ await x("git", ["add", "commitlint.config.js"], { nodeOptions: { cwd } });
+ await x("git", ["commit", "-m", '"test: this should work"'], {
+ nodeOptions: { cwd },
});
- const result = cli(['--last', '--verbose'], {cwd})();
+ const result = cli(["--last", "--verbose"], { cwd })();
const output = await result;
- expect(output.stdout.trim()).toContain('0 problems, 0 warnings');
- expect(output.stdout.trim()).toContain('test: this should work');
- expect(output.stderr).toEqual('');
+ expect(output.stdout.trim()).toContain("0 problems, 0 warnings");
+ expect(output.stdout.trim()).toContain("test: this should work");
+ expect(output.stderr).toEqual("");
});
-test('should produce no output with --quiet flag', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli(['--quiet'], {cwd})('foo: bar');
+test("should produce no output with --quiet flag", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli(["--quiet"], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toEqual('');
- expect(output.stderr).toEqual('');
+ expect(output.stdout.trim()).toEqual("");
+ expect(output.stderr).toEqual("");
});
-test('should produce no output with -q flag', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli(['-q'], {cwd})('foo: bar');
+test("should produce no output with -q flag", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli(["-q"], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toEqual('');
- expect(output.stderr).toEqual('');
+ expect(output.stdout.trim()).toEqual("");
+ expect(output.stderr).toEqual("");
});
-test('should produce help for empty config', async () => {
- const cwd = await gitBootstrap('fixtures/empty');
- const result = cli([], {cwd})('foo: bar');
+test("should produce help for empty config", async () => {
+ const cwd = await gitBootstrap("fixtures/empty");
+ const result = cli([], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toContain('Please add rules');
+ expect(output.stdout.trim()).toContain("Please add rules");
expect(result.exitCode).toBe(ExitCode.CommitlintInvalidArgument);
});
-test('should produce help for problems', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli([], {cwd})('foo: bar');
+test("should produce help for problems", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli([], { cwd })("foo: bar");
const output = await result;
expect(output.stdout.trim()).toContain(
- 'Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint'
+ "Get help: https://github.com/conventional-changelog/commitlint/#what-is-commitlint",
);
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should produce help for problems with correct helpurl', async () => {
- const cwd = await gitBootstrap('fixtures/default');
+test("should produce help for problems with correct helpurl", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
const result = cli(
- ['-H https://github.com/conventional-changelog/commitlint/#testhelpurl'],
- {cwd}
- )('foo: bar');
+ ["-H https://github.com/conventional-changelog/commitlint/#testhelpurl"],
+ { cwd },
+ )("foo: bar");
const output = await result;
expect(output.stdout.trim()).toContain(
- 'Get help: https://github.com/conventional-changelog/commitlint/#testhelpurl'
+ "Get help: https://github.com/conventional-changelog/commitlint/#testhelpurl",
);
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should fail for input from stdin without rules', async () => {
- const cwd = await gitBootstrap('fixtures/empty');
- const result = cli([], {cwd})('foo: bar');
+test("should fail for input from stdin without rules", async () => {
+ const cwd = await gitBootstrap("fixtures/empty");
+ const result = cli([], { cwd })("foo: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintInvalidArgument);
});
-test('should succeed for input from stdin with rules', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli([], {cwd})('type: bar');
+test("should succeed for input from stdin with rules", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli([], { cwd })("type: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should fail for input from stdin with rule from rc', async () => {
- const cwd = await gitBootstrap('fixtures/simple');
- const result = cli([], {cwd})('foo: bar');
+test("should fail for input from stdin with rule from rc", async () => {
+ const cwd = await gitBootstrap("fixtures/simple");
+ const result = cli([], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toContain('type must not be one of [foo]');
+ expect(output.stdout.trim()).toContain("type must not be one of [foo]");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should work with --config option', async () => {
- const file = 'config/commitlint.config.js';
- const cwd = await gitBootstrap('fixtures/specify-config-file');
- const result = cli(['--config', file], {cwd})('foo: bar');
+test("should work with --config option", async () => {
+ const file = "config/commitlint.config.js";
+ const cwd = await gitBootstrap("fixtures/specify-config-file");
+ const result = cli(["--config", file], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toContain('type must not be one of [foo]');
+ expect(output.stdout.trim()).toContain("type must not be one of [foo]");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should fail for input from stdin with rule from js', async () => {
- const cwd = await gitBootstrap('fixtures/extends-root');
- const result = cli(['--extends', './extended'], {cwd})('foo: bar');
+test("should fail for input from stdin with rule from js", async () => {
+ const cwd = await gitBootstrap("fixtures/extends-root");
+ const result = cli(["--extends", "./extended"], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toContain('type must not be one of [foo]');
+ expect(output.stdout.trim()).toContain("type must not be one of [foo]");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should output help URL defined in config file', async () => {
- const cwd = await gitBootstrap('fixtures/help-url');
- const result = cli([], {cwd})('foo: bar');
+test("should output help URL defined in config file", async () => {
+ const cwd = await gitBootstrap("fixtures/help-url");
+ const result = cli([], { cwd })("foo: bar");
const output = await result;
expect(output.stdout.trim()).toContain(
- 'Get help: https://www.example.com/foo'
+ "Get help: https://www.example.com/foo",
);
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should produce no error output with --quiet flag', async () => {
- const cwd = await gitBootstrap('fixtures/simple');
- const result = cli(['--quiet'], {cwd})('foo: bar');
+test("should produce no error output with --quiet flag", async () => {
+ const cwd = await gitBootstrap("fixtures/simple");
+ const result = cli(["--quiet"], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toEqual('');
- expect(output.stderr).toEqual('');
+ expect(output.stdout.trim()).toEqual("");
+ expect(output.stderr).toEqual("");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should produce no error output with -q flag', async () => {
- const cwd = await gitBootstrap('fixtures/simple');
- const result = cli(['-q'], {cwd})('foo: bar');
+test("should produce no error output with -q flag", async () => {
+ const cwd = await gitBootstrap("fixtures/simple");
+ const result = cli(["-q"], { cwd })("foo: bar");
const output = await result;
- expect(output.stdout.trim()).toEqual('');
- expect(output.stderr).toEqual('');
+ expect(output.stdout.trim()).toEqual("");
+ expect(output.stderr).toEqual("");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should work with husky commitmsg hook and git commit', async () => {
- const cwd = await gitBootstrap('fixtures/husky/integration');
- await writePkg({husky: {hooks: {'commit-msg': `'${bin}' -e`}}}, {cwd});
+test("should work with husky commitmsg hook and git commit", async () => {
+ const cwd = await gitBootstrap("fixtures/husky/integration");
+ await writePkg(
+ { husky: { hooks: { "commit-msg": `'${bin}' -e` } } },
+ { cwd },
+ );
// await x('npm', ['install'], { nodeOptions: {cwd}}); // npm install is failing on windows machines
- await x('git', ['add', 'package.json'], {nodeOptions: {cwd}});
- const commit = await x('git', ['commit', '-m', '"test: this should work"'], {
- nodeOptions: {cwd},
+ await x("git", ["add", "package.json"], { nodeOptions: { cwd } });
+ const commit = await x("git", ["commit", "-m", '"test: this should work"'], {
+ nodeOptions: { cwd },
});
expect(commit).toBeTruthy();
});
-test('should work with husky commitmsg hook in sub packages', async () => {
- const upper = await gitBootstrap('fixtures/husky');
- const cwd = path.join(upper, 'integration');
- await writePkg({husky: {hooks: {'commit-msg': `'${bin}' -e`}}}, {cwd: upper});
+test("should work with husky commitmsg hook in sub packages", async () => {
+ const upper = await gitBootstrap("fixtures/husky");
+ const cwd = path.join(upper, "integration");
+ await writePkg(
+ { husky: { hooks: { "commit-msg": `'${bin}' -e` } } },
+ { cwd: upper },
+ );
// await x('npm', ['install'], { nodeOptions: {cwd}}); // npm install is failing on windows machines
- await x('git', ['add', 'package.json'], {nodeOptions: {cwd}});
- const commit = await x('git', ['commit', '-m', '"test: this should work"'], {
- nodeOptions: {cwd},
+ await x("git", ["add", "package.json"], { nodeOptions: { cwd } });
+ const commit = await x("git", ["commit", "-m", '"test: this should work"'], {
+ nodeOptions: { cwd },
});
expect(commit).toBeTruthy();
});
-test('should work with husky via commitlint -e $GIT_PARAMS', async () => {
- const cwd = await gitBootstrap('fixtures/husky/integration');
+test("should work with husky via commitlint -e $GIT_PARAMS", async () => {
+ const cwd = await gitBootstrap("fixtures/husky/integration");
await writePkg(
- {husky: {hooks: {'commit-msg': `'${bin}' -e $GIT_PARAMS`}}},
- {cwd}
+ { husky: { hooks: { "commit-msg": `'${bin}' -e $GIT_PARAMS` } } },
+ { cwd },
);
// await x('npm', ['install'], { nodeOptions: {cwd}}); // npm install is failing on windows machines
- await x('git', ['add', 'package.json'], {nodeOptions: {cwd}});
- const commit = await x('git', ['commit', '-m', '"test: this should work"'], {
- nodeOptions: {cwd},
+ await x("git", ["add", "package.json"], { nodeOptions: { cwd } });
+ const commit = await x("git", ["commit", "-m", '"test: this should work"'], {
+ nodeOptions: { cwd },
});
expect(commit).toBeTruthy();
});
-test('should work with husky via commitlint -e %GIT_PARAMS%', async () => {
- const cwd = await gitBootstrap('fixtures/husky/integration');
+test("should work with husky via commitlint -e %GIT_PARAMS%", async () => {
+ const cwd = await gitBootstrap("fixtures/husky/integration");
await writePkg(
- {husky: {hooks: {'commit-msg': `'${bin}' -e %GIT_PARAMS%`}}},
- {cwd}
+ { husky: { hooks: { "commit-msg": `'${bin}' -e %GIT_PARAMS%` } } },
+ { cwd },
);
// await x('npm', ['install'], { nodeOptions: {cwd}}); // npm install is failing on windows machines
- await x('git', ['add', 'package.json'], {nodeOptions: {cwd}});
- const commit = await x('git', ['commit', '-m', '"test: this should work"'], {
- nodeOptions: {cwd},
+ await x("git", ["add", "package.json"], { nodeOptions: { cwd } });
+ const commit = await x("git", ["commit", "-m", '"test: this should work"'], {
+ nodeOptions: { cwd },
});
expect(commit).toBeTruthy();
});
-test('should work with husky via commitlint -e $HUSKY_GIT_PARAMS', async () => {
- const cwd = await gitBootstrap('fixtures/husky/integration');
+test("should work with husky via commitlint -e $HUSKY_GIT_PARAMS", async () => {
+ const cwd = await gitBootstrap("fixtures/husky/integration");
await writePkg(
- {husky: {hooks: {'commit-msg': `'${bin}' -e $HUSKY_GIT_PARAMS`}}},
- {cwd}
+ { husky: { hooks: { "commit-msg": `'${bin}' -e $HUSKY_GIT_PARAMS` } } },
+ { cwd },
);
// await x('npm', ['install'], { nodeOptions: {cwd}}); // npm install is failing on windows machines
- await x('git', ['add', 'package.json'], {nodeOptions: {cwd}});
- const commit = await x('git', ['commit', '-m', '"test: this should work"'], {
- nodeOptions: {cwd},
+ await x("git", ["add", "package.json"], { nodeOptions: { cwd } });
+ const commit = await x("git", ["commit", "-m", '"test: this should work"'], {
+ nodeOptions: { cwd },
});
expect(commit).toBeTruthy();
});
-test('should work with husky via commitlint -e %HUSKY_GIT_PARAMS%', async () => {
- const cwd = await gitBootstrap('fixtures/husky/integration');
+test("should work with husky via commitlint -e %HUSKY_GIT_PARAMS%", async () => {
+ const cwd = await gitBootstrap("fixtures/husky/integration");
await writePkg(
- {husky: {hooks: {'commit-msg': `'${bin}' -e %HUSKY_GIT_PARAMS%`}}},
- {cwd}
+ { husky: { hooks: { "commit-msg": `'${bin}' -e %HUSKY_GIT_PARAMS%` } } },
+ { cwd },
);
// await x('npm', ['install'], { nodeOptions: {cwd}}); // npm install is failing on windows machines
- await x('git', ['add', 'package.json'], {nodeOptions: {cwd}});
- const commit = await x('git', ['commit', '-m', '"test: this should work"'], {
- nodeOptions: {cwd},
+ await x("git", ["add", "package.json"], { nodeOptions: { cwd } });
+ const commit = await x("git", ["commit", "-m", '"test: this should work"'], {
+ nodeOptions: { cwd },
});
expect(commit).toBeTruthy();
});
-test('should allow reading of environment variables for edit file, succeeding if valid', async () => {
- const cwd = await gitBootstrap('fixtures/simple');
- await fs.writeFile(path.join(cwd, 'commit-msg-file'), 'foo');
- const result = cli(['--env', 'variable'], {
+test("should allow reading of environment variables for edit file, succeeding if valid", async () => {
+ const cwd = await gitBootstrap("fixtures/simple");
+ await fs.writeFile(path.join(cwd, "commit-msg-file"), "foo");
+ const result = cli(["--env", "variable"], {
cwd,
- env: {variable: 'commit-msg-file'},
+ env: { variable: "commit-msg-file" },
})();
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should allow reading of environment variables for edit file, failing if invalid', async () => {
- const cwd = await gitBootstrap('fixtures/simple');
+test("should allow reading of environment variables for edit file, failing if invalid", async () => {
+ const cwd = await gitBootstrap("fixtures/simple");
await fs.writeFile(
- path.join(cwd, 'commit-msg-file'),
- 'foo: bar\n\nFoo bar bizz buzz.\n\nCloses #123.'
+ path.join(cwd, "commit-msg-file"),
+ "foo: bar\n\nFoo bar bizz buzz.\n\nCloses #123.",
);
- const result = cli(['--env', 'variable'], {
+ const result = cli(["--env", "variable"], {
cwd,
- env: {variable: 'commit-msg-file'},
+ env: { variable: "commit-msg-file" },
})();
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should pick up parser preset and fail accordingly', async () => {
- const cwd = await gitBootstrap('fixtures/parser-preset');
- const result = cli(['--parser-preset', './parser-preset'], {cwd})(
- 'type(scope): subject'
+test("should pick up parser preset and fail accordingly", async () => {
+ const cwd = await gitBootstrap("fixtures/parser-preset");
+ const result = cli(["--parser-preset", "./parser-preset"], { cwd })(
+ "type(scope): subject",
);
const output = await result;
- expect(output.stdout.trim()).toContain('may not be empty');
+ expect(output.stdout.trim()).toContain("may not be empty");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should pick up parser preset and succeed accordingly', async () => {
- const cwd = await gitBootstrap('fixtures/parser-preset');
- const result = cli(['--parser-preset', './parser-preset'], {cwd})(
- '----type(scope): subject'
+test("should pick up parser preset and succeed accordingly", async () => {
+ const cwd = await gitBootstrap("fixtures/parser-preset");
+ const result = cli(["--parser-preset", "./parser-preset"], { cwd })(
+ "----type(scope): subject",
);
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should pick up config from outside git repo and fail accordingly', async () => {
- const outer = await fixBootstrap('fixtures/outer-scope');
- const cwd = await git.init(path.join(outer, 'inner-scope'));
+test("should pick up config from outside git repo and fail accordingly", async () => {
+ const outer = await fixBootstrap("fixtures/outer-scope");
+ const cwd = await git.init(path.join(outer, "inner-scope"));
- const result = cli([], {cwd})('inner: bar');
+ const result = cli([], { cwd })("inner: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should pick up config from outside git repo and succeed accordingly', async () => {
- const outer = await fixBootstrap('fixtures/outer-scope');
- const cwd = await git.init(path.join(outer, 'inner-scope'));
+test("should pick up config from outside git repo and succeed accordingly", async () => {
+ const outer = await fixBootstrap("fixtures/outer-scope");
+ const cwd = await git.init(path.join(outer, "inner-scope"));
- const result = cli([], {cwd})('outer: bar');
+ const result = cli([], { cwd })("outer: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should pick up config from inside git repo with precedence and succeed accordingly', async () => {
- const outer = await fixBootstrap('fixtures/inner-scope');
- const cwd = await git.init(path.join(outer, 'inner-scope'));
+test("should pick up config from inside git repo with precedence and succeed accordingly", async () => {
+ const outer = await fixBootstrap("fixtures/inner-scope");
+ const cwd = await git.init(path.join(outer, "inner-scope"));
- const result = cli([], {cwd})('inner: bar');
+ const result = cli([], { cwd })("inner: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should pick up config from inside git repo with precedence and fail accordingly', async () => {
- const outer = await fixBootstrap('fixtures/inner-scope');
- const cwd = await git.init(path.join(outer, 'inner-scope'));
+test("should pick up config from inside git repo with precedence and fail accordingly", async () => {
+ const outer = await fixBootstrap("fixtures/inner-scope");
+ const cwd = await git.init(path.join(outer, "inner-scope"));
- const result = cli([], {cwd})('outer: bar');
+ const result = cli([], { cwd })("outer: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should handle --amend with signoff', async () => {
- const cwd = await gitBootstrap('fixtures/signoff');
- await writePkg({husky: {hooks: {'commit-msg': `'${bin}' -e`}}}, {cwd});
+test("should handle --amend with signoff", async () => {
+ const cwd = await gitBootstrap("fixtures/signoff");
+ await writePkg(
+ { husky: { hooks: { "commit-msg": `'${bin}' -e` } } },
+ { cwd },
+ );
// await x('npm', ['install'], { nodeOptions: {cwd}}); // npm install is failing on windows machines
- await x('git', ['add', 'package.json'], {nodeOptions: {cwd}});
- await x('git', ['commit', '-m', '"test: this should work"', '--signoff'], {
- nodeOptions: {cwd},
+ await x("git", ["add", "package.json"], { nodeOptions: { cwd } });
+ await x("git", ["commit", "-m", '"test: this should work"', "--signoff"], {
+ nodeOptions: { cwd },
});
- const commit = await x('git', ['commit', '--amend', '--no-edit'], {
- nodeOptions: {cwd},
+ const commit = await x("git", ["commit", "--amend", "--no-edit"], {
+ nodeOptions: { cwd },
});
expect(commit).toBeTruthy();
}, 10000);
-test('it uses parserOpts.commentChar when not using edit mode', async () => {
- const cwd = await gitBootstrap('fixtures/comment-char');
- const input = 'header: foo\n$body\n';
+test("it uses parserOpts.commentChar when not using edit mode", async () => {
+ const cwd = await gitBootstrap("fixtures/comment-char");
+ const input = "header: foo\n$body\n";
- const result = cli([], {cwd})(input);
+ const result = cli([], { cwd })(input);
const output = await result;
- expect(output.stdout.trim()).toContain('[body-empty]');
+ expect(output.stdout.trim()).toContain("[body-empty]");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
test("it doesn't use parserOpts.commentChar when using edit mode", async () => {
- const cwd = await gitBootstrap('fixtures/comment-char');
+ const cwd = await gitBootstrap("fixtures/comment-char");
await fs.writeFile(
- path.join(cwd, '.git', 'COMMIT_EDITMSG'),
- 'header: foo\n\n$body\n'
+ path.join(cwd, ".git", "COMMIT_EDITMSG"),
+ "header: foo\n\n$body\n",
);
- const result = cli(['--edit', '.git/COMMIT_EDITMSG'], {cwd})();
+ const result = cli(["--edit", ".git/COMMIT_EDITMSG"], { cwd })();
const output = await result;
- expect(output.stdout.trim()).not.toContain('[body-empty]');
+ expect(output.stdout.trim()).not.toContain("[body-empty]");
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('it uses core.commentChar git config when using edit mode', async () => {
- const cwd = await gitBootstrap('fixtures/comment-char');
- await x('git', ['config', '--local', 'core.commentChar', '$'], {
- nodeOptions: {cwd},
+test("it uses core.commentChar git config when using edit mode", async () => {
+ const cwd = await gitBootstrap("fixtures/comment-char");
+ await x("git", ["config", "--local", "core.commentChar", "$"], {
+ nodeOptions: { cwd },
});
await fs.writeFile(
- path.join(cwd, '.git', 'COMMIT_EDITMSG'),
- 'header: foo\n\n$body\n'
+ path.join(cwd, ".git", "COMMIT_EDITMSG"),
+ "header: foo\n\n$body\n",
);
- const result = cli(['--edit', '.git/COMMIT_EDITMSG'], {cwd})();
+ const result = cli(["--edit", ".git/COMMIT_EDITMSG"], { cwd })();
const output = await result;
- expect(output.stdout.trim()).toContain('[body-empty]');
+ expect(output.stdout.trim()).toContain("[body-empty]");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('it falls back to # for core.commentChar when using edit mode', async () => {
- const cwd = await gitBootstrap('fixtures/comment-char');
+test("it falls back to # for core.commentChar when using edit mode", async () => {
+ const cwd = await gitBootstrap("fixtures/comment-char");
await fs.writeFile(
- path.join(cwd, '.git', 'COMMIT_EDITMSG'),
- 'header: foo\n\n#body\n'
+ path.join(cwd, ".git", "COMMIT_EDITMSG"),
+ "header: foo\n\n#body\n",
);
- const result = cli(['--edit', '.git/COMMIT_EDITMSG'], {cwd})();
+ const result = cli(["--edit", ".git/COMMIT_EDITMSG"], { cwd })();
const output = await result;
- expect(output.stdout.trim()).toContain('[body-empty]');
- expect(output.stderr).toEqual('');
+ expect(output.stdout.trim()).toContain("[body-empty]");
+ expect(output.stderr).toEqual("");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should handle linting with issue prefixes', async () => {
- const cwd = await gitBootstrap('fixtures/issue-prefixes');
- const result = cli([], {cwd})('foobar REF-1');
+test("should handle linting with issue prefixes", async () => {
+ const cwd = await gitBootstrap("fixtures/issue-prefixes");
+ const result = cli([], { cwd })("foobar REF-1");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
}, 10000);
-test('should print full commit message when input from stdin fails', async () => {
- const cwd = await gitBootstrap('fixtures/simple');
- const input = 'foo: bar\n\nFoo bar bizz buzz.\n\nCloses #123.';
+test("should print full commit message when input from stdin fails", async () => {
+ const cwd = await gitBootstrap("fixtures/simple");
+ const input = "foo: bar\n\nFoo bar bizz buzz.\n\nCloses #123.";
// output text in plain text so we can compare it
- const result = cli(['--color=false'], {cwd})(input);
+ const result = cli(["--color=false"], { cwd })(input);
const output = await result;
expect(output.stdout.trim()).toContain(input);
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should not print commit message fully or partially when input succeeds', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const message = 'type: bar\n\nFoo bar bizz buzz.\n\nCloses #123.';
+test("should not print commit message fully or partially when input succeeds", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const message = "type: bar\n\nFoo bar bizz buzz.\n\nCloses #123.";
// output text in plain text so we can compare it
- const result = cli(['--color=false'], {cwd})(message);
+ const result = cli(["--color=false"], { cwd })(message);
const output = await result;
expect(output.stdout.trim()).not.toContain(message);
- expect(output.stdout.trim()).not.toContain(message.split('\n')[0]);
+ expect(output.stdout.trim()).not.toContain(message.split("\n")[0]);
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should fail for invalid formatters from configuration', async () => {
- const cwd = await gitBootstrap('fixtures/custom-formatter');
- const result = cli([], {cwd})('foo: bar');
+test("should fail for invalid formatters from configuration", async () => {
+ const cwd = await gitBootstrap("fixtures/custom-formatter");
+ const result = cli([], { cwd })("foo: bar");
const output = await result;
expect(output.stderr).toContain(
- 'Using format custom-formatter, but cannot find the module'
+ "Using format custom-formatter, but cannot find the module",
);
- expect(output.stdout.trim()).toEqual('');
+ expect(output.stdout.trim()).toEqual("");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should skip linting if message matches ignores config', async () => {
- const cwd = await gitBootstrap('fixtures/ignores');
- const result = cli([], {cwd})('WIP');
+test("should skip linting if message matches ignores config", async () => {
+ const cwd = await gitBootstrap("fixtures/ignores");
+ const result = cli([], { cwd })("WIP");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should not skip linting if message does not match ignores config', async () => {
- const cwd = await gitBootstrap('fixtures/ignores');
- const result = cli([], {cwd})('foo');
+test("should not skip linting if message does not match ignores config", async () => {
+ const cwd = await gitBootstrap("fixtures/ignores");
+ const result = cli([], { cwd })("foo");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should not skip linting if defaultIgnores is false', async () => {
- const cwd = await gitBootstrap('fixtures/default-ignores-false');
- const result = cli([], {cwd})('fixup! foo: bar');
+test("should not skip linting if defaultIgnores is false", async () => {
+ const cwd = await gitBootstrap("fixtures/default-ignores-false");
+ const result = cli([], { cwd })("fixup! foo: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should skip linting if defaultIgnores is true', async () => {
- const cwd = await gitBootstrap('fixtures/default-ignores-true');
- const result = cli([], {cwd})('fixup! foo: bar');
+test("should skip linting if defaultIgnores is true", async () => {
+ const cwd = await gitBootstrap("fixtures/default-ignores-true");
+ const result = cli([], { cwd })("fixup! foo: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should skip linting if defaultIgnores is unset', async () => {
- const cwd = await gitBootstrap('fixtures/default-ignores-unset');
- const result = cli([], {cwd})('fixup! foo: bar');
+test("should skip linting if defaultIgnores is unset", async () => {
+ const cwd = await gitBootstrap("fixtures/default-ignores-unset");
+ const result = cli([], { cwd })("fixup! foo: bar");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should fail for invalid formatters from flags', async () => {
- const cwd = await gitBootstrap('fixtures/custom-formatter');
- const result = cli(['--format', 'through-flag'], {cwd})('foo: bar');
+test("should fail for invalid formatters from flags", async () => {
+ const cwd = await gitBootstrap("fixtures/custom-formatter");
+ const result = cli(["--format", "through-flag"], { cwd })("foo: bar");
const output = await result;
expect(output.stderr).toContain(
- 'Using format through-flag, but cannot find the module'
+ "Using format through-flag, but cannot find the module",
);
- expect(output.stdout.trim()).toEqual('');
+ expect(output.stdout.trim()).toEqual("");
expect(result.exitCode).toBe(ExitCode.CommitlintErrorDefault);
});
-test('should work with absolute formatter path', async () => {
+test("should work with absolute formatter path", async () => {
const formatterPath = path.resolve(
__dirname,
- '../fixtures/custom-formatter/formatters/custom.js'
+ "../fixtures/custom-formatter/formatters/custom.js",
);
- const cwd = await gitBootstrap('fixtures/custom-formatter');
- const result = cli(['--format', formatterPath], {cwd})(
- 'test: this should work'
+ const cwd = await gitBootstrap("fixtures/custom-formatter");
+ const result = cli(["--format", formatterPath], { cwd })(
+ "test: this should work",
);
const output = await result;
- expect(output.stdout.trim()).toContain('custom-formatter-ok');
+ expect(output.stdout.trim()).toContain("custom-formatter-ok");
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should work with relative formatter path', async () => {
+test("should work with relative formatter path", async () => {
const cwd = path.resolve(
- await gitBootstrap('fixtures/custom-formatter'),
- './formatters'
+ await gitBootstrap("fixtures/custom-formatter"),
+ "./formatters",
);
- const result = cli(['--format', './custom.js'], {cwd})(
- 'test: this should work'
+ const result = cli(["--format", "./custom.js"], { cwd })(
+ "test: this should work",
);
const output = await result;
- expect(output.stdout.trim()).toContain('custom-formatter-ok');
+ expect(output.stdout.trim()).toContain("custom-formatter-ok");
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('strict: should exit with 3 on error', async () => {
- const cwd = await gitBootstrap('fixtures/warning');
- const result = cli(['--strict'], {cwd})('foo: abcdef');
+test("strict: should exit with 3 on error", async () => {
+ const cwd = await gitBootstrap("fixtures/warning");
+ const result = cli(["--strict"], { cwd })("foo: abcdef");
await result;
expect(result.exitCode).toBe(ExitCode.CommitLintError);
});
-test('strict: should exit with 2 on warning', async () => {
- const cwd = await gitBootstrap('fixtures/warning');
- const result = cli(['--strict'], {cwd})('feat: abcdef');
+test("strict: should exit with 2 on warning", async () => {
+ const cwd = await gitBootstrap("fixtures/warning");
+ const result = cli(["--strict"], { cwd })("feat: abcdef");
await result;
expect(result.exitCode).toBe(ExitCode.CommitLintWarning);
});
-test('strict: should exit with 0 on success', async () => {
- const cwd = await gitBootstrap('fixtures/warning');
- const result = cli(['--strict'], {cwd})('feat: abc');
+test("strict: should exit with 0 on success", async () => {
+ const cwd = await gitBootstrap("fixtures/warning");
+ const result = cli(["--strict"], { cwd })("feat: abc");
await result;
expect(result.exitCode).toBe(ExitCode.CommitlintDefault);
});
-test('should print help', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli(['--help'], {cwd})();
+test("should print help", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli(["--help"], { cwd })();
const output = await result;
- const version = require('../package.json').version;
- const stdout = output.stdout.trim().replace(`@${version}`, '@dev');
+ const version = require("../package.json").version;
+ const stdout = output.stdout.trim().replace(`@${version}`, "@dev");
expect(stdout).toMatchInlineSnapshot(`
"@commitlint/cli@dev - Lint your commit messages
@@ -604,23 +613,23 @@ test('should print help', async () => {
`);
});
-test('should print version', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli(['--version'], {cwd})();
+test("should print version", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli(["--version"], { cwd })();
const output = await result;
- expect(output.stdout.trim()).toMatch('@commitlint/cli@');
+ expect(output.stdout.trim()).toMatch("@commitlint/cli@");
});
-describe('should print config', () => {
- test('should print config when flag is present but without value', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli(['--print-config', 'text', '--no-color'], {cwd})();
+describe("should print config", () => {
+ test("should print config when flag is present but without value", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli(["--print-config", "text", "--no-color"], { cwd })();
const output = await result;
const stdout = output.stdout
.trim()
- .replace(/^{[^\n]/g, '{\n ')
- .replace(/[^\n]}$/g, '\n}')
- .replace(/(helpUrl:)\n[ ]+/, '$1 ');
+ .replace(/^{[^\n]/g, "{\n ")
+ .replace(/[^\n]}$/g, "\n}")
+ .replace(/(helpUrl:)\n[ ]+/, "$1 ");
expect(stdout).toMatchInlineSnapshot(`
"{
extends: [],
@@ -636,15 +645,15 @@ describe('should print config', () => {
`);
});
- test('should print config when flag has `text` value', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli(['--print-config=text', '--no-color'], {cwd})();
+ test("should print config when flag has `text` value", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli(["--print-config=text", "--no-color"], { cwd })();
const output = await result;
const stdout = output.stdout
.trim()
- .replace(/^{[^\n]/g, '{\n ')
- .replace(/[^\n]}$/g, '\n}')
- .replace(/(helpUrl:)\n[ ]+/, '$1 ');
+ .replace(/^{[^\n]/g, "{\n ")
+ .replace(/[^\n]}$/g, "\n}")
+ .replace(/(helpUrl:)\n[ ]+/, "$1 ");
expect(stdout).toMatchInlineSnapshot(`
"{
extends: [],
@@ -660,19 +669,19 @@ describe('should print config', () => {
`);
});
- test('should print config when flag has `json` value', async () => {
- const cwd = await gitBootstrap('fixtures/default');
- const result = cli(['--print-config=json', '--no-color'], {cwd})();
+ test("should print config when flag has `json` value", async () => {
+ const cwd = await gitBootstrap("fixtures/default");
+ const result = cli(["--print-config=json", "--no-color"], { cwd })();
const output = await result;
expect(output.stdout.trim()).toMatchInlineSnapshot(
- `"{"extends":[],"formatter":"@commitlint/format","plugins":{},"rules":{"type-enum":[2,"never",["foo"]]},"helpUrl":"https://github.com/conventional-changelog/commitlint/#what-is-commitlint","prompt":{}}"`
+ `"{"extends":[],"formatter":"@commitlint/format","plugins":{},"rules":{"type-enum":[2,"never",["foo"]]},"helpUrl":"https://github.com/conventional-changelog/commitlint/#what-is-commitlint","prompt":{}}"`,
);
});
});
async function writePkg(payload: unknown, options: TestOptions) {
- const pkgPath = path.join(options.cwd, 'package.json');
- const pkg = JSON.parse(await fs.readFile(pkgPath, 'utf-8'));
+ const pkgPath = path.join(options.cwd, "package.json");
+ const pkg = JSON.parse(await fs.readFile(pkgPath, "utf-8"));
const result = merge(pkg, payload);
- await fs.writeFile(pkgPath, JSON.stringify(result, null, ' '));
+ await fs.writeFile(pkgPath, JSON.stringify(result, null, " "));
}
diff --git a/@commitlint/cli/src/cli.ts b/@commitlint/cli/src/cli.ts
index bce45db4e3..50cfed53f9 100644
--- a/@commitlint/cli/src/cli.ts
+++ b/@commitlint/cli/src/cli.ts
@@ -1,11 +1,11 @@
-import {createRequire} from 'node:module';
-import path from 'node:path';
-import {fileURLToPath, pathToFileURL} from 'node:url';
-import util from 'node:util';
-
-import lint from '@commitlint/lint';
-import load, {resolveFromSilent, resolveGlobalSilent} from '@commitlint/load';
-import read from '@commitlint/read';
+import { createRequire } from "node:module";
+import path from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import util from "node:util";
+
+import lint from "@commitlint/lint";
+import load, { resolveFromSilent, resolveGlobalSilent } from "@commitlint/load";
+import read from "@commitlint/read";
import type {
Formatter,
LintOptions,
@@ -13,150 +13,150 @@ import type {
ParserPreset,
QualifiedConfig,
UserConfig,
-} from '@commitlint/types';
-import type {Options} from 'conventional-commits-parser';
-import {x} from 'tinyexec';
-import yargs, {type Arguments} from 'yargs';
+} from "@commitlint/types";
+import type { Options } from "conventional-commits-parser";
+import { x } from "tinyexec";
+import yargs, { type Arguments } from "yargs";
-import {CliFlags} from './types.js';
+import { CliFlags } from "./types.js";
-import {CliError, ExitCode} from './cli-error.js';
+import { CliError, ExitCode } from "./cli-error.js";
const require = createRequire(import.meta.url);
-const __dirname = path.resolve(fileURLToPath(import.meta.url), '..');
+const __dirname = path.resolve(fileURLToPath(import.meta.url), "..");
const dynamicImport = async (id: string): Promise => {
const imported = await import(
path.isAbsolute(id) ? pathToFileURL(id).toString() : id
);
- return ('default' in imported && imported.default) || imported;
+ return ("default" in imported && imported.default) || imported;
};
-const pkg: typeof import('../package.json') = require('../package.json');
+const pkg: typeof import("../package.json") = require("../package.json");
-const gitDefaultCommentChar = '#';
+const gitDefaultCommentChar = "#";
const cli = yargs(process.argv.slice(2))
.options({
color: {
- alias: 'c',
+ alias: "c",
default: true,
- description: 'toggle colored output',
- type: 'boolean',
+ description: "toggle colored output",
+ type: "boolean",
},
config: {
- alias: 'g',
+ alias: "g",
description:
- 'path to the config file; result code 9 if config is missing',
- type: 'string',
+ "path to the config file; result code 9 if config is missing",
+ type: "string",
},
- 'print-config': {
- choices: ['', 'text', 'json'],
- description: 'print resolved config',
- type: 'string',
+ "print-config": {
+ choices: ["", "text", "json"],
+ description: "print resolved config",
+ type: "string",
},
cwd: {
- alias: 'd',
+ alias: "d",
default: process.cwd(),
- defaultDescription: '(Working Directory)',
- description: 'directory to execute in',
- type: 'string',
+ defaultDescription: "(Working Directory)",
+ description: "directory to execute in",
+ type: "string",
},
edit: {
- alias: 'e',
+ alias: "e",
description:
- 'read last commit message from the specified file or fallbacks to ./.git/COMMIT_EDITMSG',
- type: 'string',
+ "read last commit message from the specified file or fallbacks to ./.git/COMMIT_EDITMSG",
+ type: "string",
},
env: {
- alias: 'E',
+ alias: "E",
description:
- 'check message in the file at path given by environment variable value',
- type: 'string',
+ "check message in the file at path given by environment variable value",
+ type: "string",
},
extends: {
- alias: 'x',
- description: 'array of shareable configurations to extend',
- type: 'array',
+ alias: "x",
+ description: "array of shareable configurations to extend",
+ type: "array",
},
- 'help-url': {
- alias: 'H',
- type: 'string',
- description: 'help url in error message',
+ "help-url": {
+ alias: "H",
+ type: "string",
+ description: "help url in error message",
},
from: {
- alias: 'f',
+ alias: "f",
description:
- 'lower end of the commit range to lint; applies if edit=false',
- type: 'string',
+ "lower end of the commit range to lint; applies if edit=false",
+ type: "string",
},
- 'from-last-tag': {
+ "from-last-tag": {
description:
- 'uses the last tag as the lower end of the commit range to lint; applies if edit=false and from is not set',
- type: 'boolean',
+ "uses the last tag as the lower end of the commit range to lint; applies if edit=false and from is not set",
+ type: "boolean",
},
- 'git-log-args': {
+ "git-log-args": {
description:
"additional git log arguments as space separated string, example '--first-parent --cherry-pick'",
- type: 'string',
+ type: "string",
},
last: {
- alias: 'l',
- description: 'just analyze the last commit; applies if edit=false',
- type: 'boolean',
+ alias: "l",
+ description: "just analyze the last commit; applies if edit=false",
+ type: "boolean",
},
format: {
- alias: 'o',
- description: 'output format of the results',
- type: 'string',
+ alias: "o",
+ description: "output format of the results",
+ type: "string",
},
- 'parser-preset': {
- alias: 'p',
+ "parser-preset": {
+ alias: "p",
description:
- 'configuration preset to use for conventional-commits-parser',
- type: 'string',
+ "configuration preset to use for conventional-commits-parser",
+ type: "string",
},
quiet: {
- alias: 'q',
+ alias: "q",
default: false,
- description: 'toggle console output',
- type: 'boolean',
+ description: "toggle console output",
+ type: "boolean",
},
to: {
- alias: 't',
+ alias: "t",
description:
- 'upper end of the commit range to lint; applies if edit=false',
- type: 'string',
+ "upper end of the commit range to lint; applies if edit=false",
+ type: "string",
},
verbose: {
- alias: 'V',
- type: 'boolean',
- description: 'enable verbose output for reports without problems',
+ alias: "V",
+ type: "boolean",
+ description: "enable verbose output for reports without problems",
},
strict: {
- alias: 's',
- type: 'boolean',
+ alias: "s",
+ type: "boolean",
description:
- 'enable strict mode; result code 2 for warnings, 3 for errors',
+ "enable strict mode; result code 2 for warnings, 3 for errors",
},
})
.version(
- 'version',
- 'display version information',
- `${pkg.name}@${pkg.version}`
+ "version",
+ "display version information",
+ `${pkg.name}@${pkg.version}`,
)
- .alias('v', 'version')
- .help('help')
- .alias('h', 'help')
+ .alias("v", "version")
+ .help("help")
+ .alias("h", "help")
.config(
- 'options',
- 'path to a JSON file or Common.js module containing CLI options',
- require
+ "options",
+ "path to a JSON file or Common.js module containing CLI options",
+ require,
)
.usage(`${pkg.name}@${pkg.version} - ${pkg.description}\n`)
.usage(
- `[input] reads from stdin if --edit, --env, --from and --to are omitted`
+ `[input] reads from stdin if --edit, --env, --from and --to are omitted`,
)
.strict();
@@ -176,13 +176,13 @@ main(cli.argv).catch((err) => {
});
async function stdin() {
- let result = '';
+ let result = "";
if (process.stdin.isTTY) {
return result;
}
- process.stdin.setEncoding('utf8');
+ process.stdin.setEncoding("utf8");
for await (const chunk of process.stdin) {
result += chunk;
@@ -198,30 +198,30 @@ type MainArgsPromise = Promise;
type MainArgs = MainArgsObject | MainArgsPromise;
async function resolveArgs(args: MainArgs): Promise {
- return typeof args.then === 'function' ? await args : args;
+ return typeof args.then === "function" ? await args : args;
}
async function main(args: MainArgs): Promise {
const options = await resolveArgs(args);
- if (typeof options.edit === 'undefined') {
+ if (typeof options.edit === "undefined") {
options.edit = false;
}
const raw = options._;
const flags = normalizeFlags(options);
- if (typeof options['print-config'] === 'string') {
+ if (typeof options["print-config"] === "string") {
const loaded = await load(getSeed(flags), {
cwd: flags.cwd,
file: flags.config,
});
- switch (options['print-config']) {
- case 'json':
+ switch (options["print-config"]) {
+ case "json":
console.log(JSON.stringify(loaded));
return;
- case 'text':
+ case "text":
default:
console.log(util.inspect(loaded, false, null, options.color));
return;
@@ -231,14 +231,14 @@ async function main(args: MainArgs): Promise {
const fromStdin = checkFromStdin(raw, flags);
if (
- Object.hasOwn(flags, 'last') &&
- (Object.hasOwn(flags, 'from') || Object.hasOwn(flags, 'to') || flags.edit)
+ Object.hasOwn(flags, "last") &&
+ (Object.hasOwn(flags, "from") || Object.hasOwn(flags, "to") || flags.edit)
) {
const err = new CliError(
- 'Please use the --last flag alone. The --last flag should not be used with --to or --from or --edit.',
- pkg.name
+ "Please use the --last flag alone. The --last flag should not be used with --to or --from or --edit.",
+ pkg.name,
);
- cli.showHelp('log');
+ cli.showHelp("log");
console.log(err.message);
throw err;
}
@@ -248,24 +248,24 @@ async function main(args: MainArgs): Promise {
: read({
to: flags.to,
from: flags.from,
- fromLastTag: flags['from-last-tag'],
+ fromLastTag: flags["from-last-tag"],
last: flags.last,
edit: flags.edit,
cwd: flags.cwd,
- gitLogArgs: flags['git-log-args'],
- }));
+ gitLogArgs: flags["git-log-args"],
+ }));
const messages = (Array.isArray(input) ? input : [input])
- .filter((message) => typeof message === 'string')
- .filter((message) => message.trim() !== '')
+ .filter((message) => typeof message === "string")
+ .filter((message) => message.trim() !== "")
.filter(Boolean);
if (messages.length === 0 && !checkFromRepository(flags)) {
const err = new CliError(
- '[input] is required: supply via stdin, or --env or --edit or --last or --from and --to',
- pkg.name
+ "[input] is required: supply via stdin, or --env or --edit or --last or --from and --to",
+ pkg.name,
);
- cli.showHelp('log');
+ cli.showHelp("log");
console.log(err.message);
throw err;
}
@@ -275,7 +275,7 @@ async function main(args: MainArgs): Promise {
file: flags.config,
});
const parserOpts = selectParserOpts(loaded.parserPreset);
- const opts: LintOptions & {parserOpts: Options} = {
+ const opts: LintOptions & { parserOpts: Options } = {
parserOpts: {},
plugins: {},
ignores: [],
@@ -298,13 +298,13 @@ async function main(args: MainArgs): Promise {
// If reading from `.git/COMMIT_EDIT_MSG`, strip comments using
// core.commentChar from git configuration, falling back to '#'.
if (flags.edit) {
- const result = x('git', ['config', 'core.commentChar']);
+ const result = x("git", ["config", "core.commentChar"]);
const output = await result;
if (result.exitCode && result.exitCode > 1) {
console.warn(
- 'Could not determine core.commentChar git configuration',
- output.stderr
+ "Could not determine core.commentChar git configuration",
+ output.stderr,
);
opts.parserOpts.commentChar = gitDefaultCommentChar;
} else {
@@ -314,12 +314,12 @@ async function main(args: MainArgs): Promise {
}
const results = await Promise.all(
- messages.map((message) => lint(message, loaded.rules, opts))
+ messages.map((message) => lint(message, loaded.rules, opts)),
);
let isRulesEmpty = false;
if (Object.keys(loaded.rules).length === 0) {
- let input = '';
+ let input = "";
if (results.length !== 0) {
input = results[0].input;
@@ -331,12 +331,12 @@ async function main(args: MainArgs): Promise {
{
level: 2,
valid: false,
- name: 'empty-rules',
+ name: "empty-rules",
message: [
- 'Please add rules to your `commitlint.config.js`',
- ' - Getting started guide: https://commitlint.js.org/guides/getting-started',
- ' - Example config: https://github.com/conventional-changelog/commitlint/blob/master/%40commitlint/config-conventional/src/index.ts',
- ].join('\n'),
+ "Please add rules to your `commitlint.config.js`",
+ " - Getting started guide: https://commitlint.js.org/guides/getting-started",
+ " - Example config: https://github.com/conventional-changelog/commitlint/blob/master/%40commitlint/config-conventional/src/index.ts",
+ ].join("\n"),
},
],
warnings: [],
@@ -365,10 +365,10 @@ async function main(args: MainArgs): Promise {
errorCount: 0,
warningCount: 0,
results: [],
- }
+ },
);
- const helpUrl = flags['help-url']?.trim() || loaded.helpUrl;
+ const helpUrl = flags["help-url"]?.trim() || loaded.helpUrl;
const output = format(report, {
color: flags.color,
@@ -376,7 +376,7 @@ async function main(args: MainArgs): Promise {
helpUrl,
});
- if (!flags.quiet && output !== '') {
+ if (!flags.quiet && output !== "") {
console.log(output);
}
@@ -410,10 +410,10 @@ function checkFromEdit(flags: CliFlags): boolean {
function checkFromHistory(flags: CliFlags): boolean {
return (
- typeof flags.from === 'string' ||
- typeof flags['from-last-tag'] === 'boolean' ||
- typeof flags.to === 'string' ||
- typeof flags.last === 'boolean'
+ typeof flags.from === "string" ||
+ typeof flags["from-last-tag"] === "boolean" ||
+ typeof flags.to === "string" ||
+ typeof flags.last === "boolean"
);
}
@@ -429,18 +429,18 @@ function getEditValue(flags: CliFlags) {
if (flags.env) {
if (!(flags.env in process.env)) {
throw new Error(
- `Received '${flags.env}' as value for -E | --env, but environment variable '${flags.env}' is not available globally`
+ `Received '${flags.env}' as value for -E | --env, but environment variable '${flags.env}' is not available globally`,
);
}
return process.env[flags.env];
}
- const {edit} = flags;
+ const { edit } = flags;
// If the edit flag is set but empty (i.e '-e') we default
// to .git/COMMIT_EDITMSG
- if (edit === '') {
+ if (edit === "") {
return true;
}
- if (typeof edit === 'boolean') {
+ if (typeof edit === "boolean") {
return edit;
}
// The recommended method to specify -e with husky was `commitlint -e $HUSKY_GIT_PARAMS`
@@ -448,22 +448,22 @@ function getEditValue(flags: CliFlags) {
// use a different syntax
// See https://github.com/conventional-changelog/commitlint/issues/103 for details
// This has been superceded by the `-E GIT_PARAMS` / `-E HUSKY_GIT_PARAMS`
- const isGitParams = edit === '$GIT_PARAMS' || edit === '%GIT_PARAMS%';
+ const isGitParams = edit === "$GIT_PARAMS" || edit === "%GIT_PARAMS%";
const isHuskyParams =
- edit === '$HUSKY_GIT_PARAMS' || edit === '%HUSKY_GIT_PARAMS%';
+ edit === "$HUSKY_GIT_PARAMS" || edit === "%HUSKY_GIT_PARAMS%";
if (isGitParams || isHuskyParams) {
console.warn(`Using environment variable syntax (${edit}) in -e |\
--edit is deprecated. Use '{-E|--env} HUSKY_GIT_PARAMS instead'`);
- if (isGitParams && 'GIT_PARAMS' in process.env) {
+ if (isGitParams && "GIT_PARAMS" in process.env) {
return process.env.GIT_PARAMS;
}
- if ('HUSKY_GIT_PARAMS' in process.env) {
+ if ("HUSKY_GIT_PARAMS" in process.env) {
return process.env.HUSKY_GIT_PARAMS;
}
throw new Error(
- `Received ${edit} as value for -e | --edit, but GIT_PARAMS or HUSKY_GIT_PARAMS are not available globally.`
+ `Received ${edit} as value for -e | --edit, but GIT_PARAMS or HUSKY_GIT_PARAMS are not available globally.`,
);
}
return edit;
@@ -471,19 +471,19 @@ function getEditValue(flags: CliFlags) {
function getSeed(flags: CliFlags): UserConfig {
const n = (flags.extends || []).filter(
- (i): i is string => typeof i === 'string'
+ (i): i is string => typeof i === "string",
);
return n.length > 0
- ? {extends: n, parserPreset: flags['parser-preset']}
- : {parserPreset: flags['parser-preset']};
+ ? { extends: n, parserPreset: flags["parser-preset"] }
+ : { parserPreset: flags["parser-preset"] };
}
function selectParserOpts(parserPreset: ParserPreset | undefined) {
- if (typeof parserPreset !== 'object') {
+ if (typeof parserPreset !== "object") {
return undefined;
}
- if (typeof parserPreset.parserOpts !== 'object') {
+ if (typeof parserPreset.parserOpts !== "object") {
return undefined;
}
@@ -492,9 +492,9 @@ function selectParserOpts(parserPreset: ParserPreset | undefined) {
function loadFormatter(
config: QualifiedConfig,
- flags: CliFlags
+ flags: CliFlags,
): Promise {
- const moduleName = flags.format || config.formatter || '@commitlint/format';
+ const moduleName = flags.format || config.formatter || "@commitlint/format";
const modulePath =
resolveFromSilent(moduleName, __dirname) ||
resolveFromSilent(moduleName, flags.cwd) ||
@@ -508,7 +508,7 @@ function loadFormatter(
}
// Catch unhandled rejections globally
-process.on('unhandledRejection', (reason, promise) => {
- console.log('Unhandled Rejection at: Promise ', promise, ' reason: ', reason);
+process.on("unhandledRejection", (reason, promise) => {
+ console.log("Unhandled Rejection at: Promise ", promise, " reason: ", reason);
throw reason;
});
diff --git a/@commitlint/cli/src/types.ts b/@commitlint/cli/src/types.ts
index c9b3a1b8ef..cbc9a8956a 100644
--- a/@commitlint/cli/src/types.ts
+++ b/@commitlint/cli/src/types.ts
@@ -6,19 +6,19 @@ export interface CliFlags {
env?: string;
extends?: (string | number)[];
help?: boolean;
- 'help-url'?: string;
+ "help-url"?: string;
from?: string;
- 'from-last-tag'?: boolean;
- 'git-log-args'?: string;
+ "from-last-tag"?: boolean;
+ "git-log-args"?: string;
last?: boolean;
format?: string;
- 'parser-preset'?: string;
+ "parser-preset"?: string;
quiet: boolean;
to?: string;
version?: boolean;
verbose?: boolean;
/** @type {'' | 'text' | 'json'} */
- 'print-config'?: string;
+ "print-config"?: string;
strict?: boolean;
_: (string | number)[];
$0: string;
diff --git a/@commitlint/config-angular-type-enum/README.md b/@commitlint/config-angular-type-enum/README.md
index 6ffd9dd17e..09df8aa8de 100644
--- a/@commitlint/config-angular-type-enum/README.md
+++ b/@commitlint/config-angular-type-enum/README.md
@@ -23,7 +23,7 @@ echo "build: bar" | commitlint # passes
```js
// commitlint.config.js
-const types = require('@commitlint/config-angular-type-enum');
+const types = require("@commitlint/config-angular-type-enum");
// Use as rule creating errors for non-allowed types
module.exports = {
@@ -35,7 +35,7 @@ module.exports = {
// Warn for non-allowed types
module.exports = {
rules: {
- 'type-enum': [1, 'always', types.values()],
+ "type-enum": [1, "always", types.values()],
},
};
```
diff --git a/@commitlint/config-angular-type-enum/index.js b/@commitlint/config-angular-type-enum/index.js
index 485701638c..658d6259d2 100644
--- a/@commitlint/config-angular-type-enum/index.js
+++ b/@commitlint/config-angular-type-enum/index.js
@@ -1,19 +1,19 @@
const types = [
- 'build',
- 'ci',
- 'docs',
- 'feat',
- 'fix',
- 'perf',
- 'refactor',
- 'revert',
- 'style',
- 'test',
+ "build",
+ "ci",
+ "docs",
+ "feat",
+ "fix",
+ "perf",
+ "refactor",
+ "revert",
+ "style",
+ "test",
];
export default {
rules: {
- 'type-enum': [2, 'always', types],
+ "type-enum": [2, "always", types],
},
value: () => types,
};
diff --git a/@commitlint/config-angular/index.js b/@commitlint/config-angular/index.js
index c433e75baf..81848fb82c 100644
--- a/@commitlint/config-angular/index.js
+++ b/@commitlint/config-angular/index.js
@@ -1,22 +1,24 @@
-import typeEnum from '@commitlint/config-angular-type-enum';
+import typeEnum from "@commitlint/config-angular-type-enum";
export default {
- parserPreset: {parserOpts: {headerPattern: /^(\w*)(?:\((.*)\))?!?: (.*)$/}},
+ parserPreset: {
+ parserOpts: { headerPattern: /^(\w*)(?:\((.*)\))?!?: (.*)$/ },
+ },
rules: {
- 'subject-exclamation-mark': [2, 'never'],
- 'body-leading-blank': [1, 'always'],
- 'footer-leading-blank': [1, 'always'],
- 'header-max-length': [2, 'always', 72],
- 'scope-case': [2, 'always', 'lower-case'],
- 'subject-case': [
+ "subject-exclamation-mark": [2, "never"],
+ "body-leading-blank": [1, "always"],
+ "footer-leading-blank": [1, "always"],
+ "header-max-length": [2, "always", 72],
+ "scope-case": [2, "always", "lower-case"],
+ "subject-case": [
2,
- 'never',
- ['sentence-case', 'start-case', 'pascal-case', 'upper-case'],
+ "never",
+ ["sentence-case", "start-case", "pascal-case", "upper-case"],
],
- 'subject-empty': [2, 'never'],
- 'subject-full-stop': [2, 'never', '.'],
- 'type-case': [2, 'always', 'lower-case'],
- 'type-empty': [2, 'never'],
- 'type-enum': typeEnum.rules['type-enum'],
+ "subject-empty": [2, "never"],
+ "subject-full-stop": [2, "never", "."],
+ "type-case": [2, "always", "lower-case"],
+ "type-empty": [2, "never"],
+ "type-enum": typeEnum.rules["type-enum"],
},
};
diff --git a/@commitlint/config-angular/index.test.js b/@commitlint/config-angular/index.test.js
index 662c233cb3..d76a84c585 100644
--- a/@commitlint/config-angular/index.test.js
+++ b/@commitlint/config-angular/index.test.js
@@ -1,108 +1,108 @@
-import {test, expect} from 'vitest';
-import lint from '@commitlint/lint';
+import { test, expect } from "vitest";
+import lint from "@commitlint/lint";
-import config from './index.js';
+import config from "./index.js";
-const {rules, parserPreset} = config;
+const { rules, parserPreset } = config;
const lintMessage = async (message) => {
const parserOpts = parserPreset.parserOpts;
- const m = message.replace(/^\s+/, '').trim();
- const result = await lint(m, rules, {parserOpts});
+ const m = message.replace(/^\s+/, "").trim();
+ const result = await lint(m, rules, { parserOpts });
if (result.errors.length > 1) {
throw new Error(
- 'Commit test should only have one error message to validate against'
+ "Commit test should only have one error message to validate against",
);
}
if (result.warnings.length > 1) {
throw new Error(
- 'Commit test should only have one warning message to validate against'
+ "Commit test should only have one warning message to validate against",
);
}
return result;
};
-test('a valid commit message', async () => {
- const result = await lintMessage('test: a valid angular commit');
+test("a valid commit message", async () => {
+ const result = await lintMessage("test: a valid angular commit");
expect(result.valid).toBe(true);
expect(result.errors).toStrictEqual([]);
expect(result.warnings).toStrictEqual([]);
});
-test('a valid message with a scope', async () => {
+test("a valid message with a scope", async () => {
const result = await lintMessage(
- 'test(scope): a valid angular commit with a scope'
+ "test(scope): a valid angular commit with a scope",
);
expect(result.valid).toBe(true);
expect(result.errors).toStrictEqual([]);
expect(result.warnings).toStrictEqual([]);
});
-test('a valid multi line commit', async () => {
+test("a valid multi line commit", async () => {
const result = await lintMessage(
`test(scope): a valid angular commit with a scope
- Some content in the body`
+ Some content in the body`,
);
expect(result.valid).toBe(true);
expect(result.errors).toStrictEqual([]);
expect(result.warnings).toStrictEqual([]);
});
-test('a leading blank line after header', async () => {
+test("a leading blank line after header", async () => {
const result = await lintMessage(
`test(scope): a valid angular commit with a scope
- Some content in the body`
+ Some content in the body`,
);
expect(result.valid).toBe(true);
expect(result.errors).toStrictEqual([]);
- expect(result.warnings[0].message).toBe('body must have leading blank line');
+ expect(result.warnings[0].message).toBe("body must have leading blank line");
});
-test('an invalid scope', async () => {
+test("an invalid scope", async () => {
const result = await lintMessage(`no: no is not an invalid commit type`);
expect(result.valid).toBe(false);
expect(result.errors[0].message).toBe(
- 'type must be one of [build, ci, docs, feat, fix, perf, refactor, revert, style, test]'
+ "type must be one of [build, ci, docs, feat, fix, perf, refactor, revert, style, test]",
);
expect(result.warnings).toStrictEqual([]);
});
-test('a long header', async () => {
+test("a long header", async () => {
const result = await lintMessage(
- `test: that its an error when there is ia realllllllllllllllllllllly long header`
+ `test: that its an error when there is ia realllllllllllllllllllllly long header`,
);
expect(result.valid).toBe(false);
expect(result.errors[0].message).toBe(
- 'header must not be longer than 72 characters, current length is 79'
+ "header must not be longer than 72 characters, current length is 79",
);
expect(result.warnings).toStrictEqual([]);
});
-test('message header with ! in it', async () => {
+test("message header with ! in it", async () => {
const result = await lintMessage(`test!: with a breaking change in the type`);
expect(result.valid).toBe(false);
expect(result.errors[0].message).toBe(
- 'subject must not have an exclamation mark in the subject to identify a breaking change'
+ "subject must not have an exclamation mark in the subject to identify a breaking change",
);
expect(result.warnings).toStrictEqual([]);
});
-test('message header with ! in it and a scope', async () => {
+test("message header with ! in it and a scope", async () => {
const result = await lintMessage(
- `test(scope)!: with a breaking change in the type`
+ `test(scope)!: with a breaking change in the type`,
);
expect(result.valid).toBe(false);
expect(result.errors[0].message).toBe(
- 'subject must not have an exclamation mark in the subject to identify a breaking change'
+ "subject must not have an exclamation mark in the subject to identify a breaking change",
);
expect(result.warnings).toStrictEqual([]);
});
diff --git a/@commitlint/config-conventional/src/index.test.ts b/@commitlint/config-conventional/src/index.test.ts
index a44fe8c59a..3603fe74f6 100644
--- a/@commitlint/config-conventional/src/index.test.ts
+++ b/@commitlint/config-conventional/src/index.test.ts
@@ -1,53 +1,53 @@
-import {test, expect} from 'vitest';
-import path from 'node:path';
-import {pathToFileURL} from 'node:url';
+import { test, expect } from "vitest";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
-import lint from '@commitlint/lint';
+import lint from "@commitlint/lint";
-import config from './index.js';
+import config from "./index.js";
-const {rules, parserPreset} = config;
+const { rules, parserPreset } = config;
const dynamicImport = async (id: string) => {
const imported = await import(
path.isAbsolute(id) ? pathToFileURL(id).toString() : id
);
- return ('default' in imported && imported.default) || imported;
+ return ("default" in imported && imported.default) || imported;
};
const commitLint = async (message: string) => {
const preset = await (await dynamicImport(parserPreset))();
- return lint(message, rules, {...preset});
+ return lint(message, rules, { ...preset });
};
const messages = {
- invalidTypeEnum: 'foo: some message',
- invalidTypeCase: 'FIX: some message',
- invalidTypeEmpty: ': some message',
+ invalidTypeEnum: "foo: some message",
+ invalidTypeCase: "FIX: some message",
+ invalidTypeEmpty: ": some message",
invalidSubjectCases: [
- 'fix(scope): Some message',
- 'fix(scope): Some Message',
- 'fix(scope): SomeMessage',
- 'fix(scope): SOMEMESSAGE',
+ "fix(scope): Some message",
+ "fix(scope): Some Message",
+ "fix(scope): SomeMessage",
+ "fix(scope): SOMEMESSAGE",
],
- invalidSubjectEmpty: 'fix:',
- invalidSubjectFullStop: 'fix: some message.',
+ invalidSubjectEmpty: "fix:",
+ invalidSubjectFullStop: "fix: some message.",
invalidHeaderMaxLength:
- 'fix: some message that is way too long and breaks the line max-length by several characters since the max is 100',
+ "fix: some message that is way too long and breaks the line max-length by several characters since the max is 100",
warningFooterLeadingBlank:
- 'fix: some message\n\nbody\nBREAKING CHANGE: It will be significant',
+ "fix: some message\n\nbody\nBREAKING CHANGE: It will be significant",
invalidFooterMaxLineLength:
'fix: some message\n\nbody\n\nBREAKING CHANGE: footer with multiple lines\nhas a message that is way too long and will break the line rule "line-max-length" by several characters',
- warningBodyLeadingBlank: 'fix: some message\nbody',
+ warningBodyLeadingBlank: "fix: some message\nbody",
invalidBodyMaxLineLength:
'fix: some message\n\nbody with multiple lines\nhas a message that is way too long and will break the line rule "line-max-length" by several characters',
validMessages: [
- 'fix: some message',
- 'fix(scope): some message',
- 'fix(scope): some Message',
- 'fix(scope): some message\n\nBREAKING CHANGE: it will be significant!',
- 'fix(scope): some message\n\nbody',
- 'fix(scope)!: some message\n\nbody',
+ "fix: some message",
+ "fix(scope): some message",
+ "fix(scope): some Message",
+ "fix(scope): some message\n\nBREAKING CHANGE: it will be significant!",
+ "fix(scope): some message\n\nbody",
+ "fix(scope)!: some message\n\nbody",
],
};
@@ -55,58 +55,58 @@ const errors = {
typeEnum: {
level: 2,
message:
- 'type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test]',
- name: 'type-enum',
+ "type must be one of [build, chore, ci, docs, feat, fix, perf, refactor, revert, style, test]",
+ name: "type-enum",
valid: false,
},
typeCase: {
level: 2,
- message: 'type must be lower-case',
- name: 'type-case',
+ message: "type must be lower-case",
+ name: "type-case",
valid: false,
},
typeEmpty: {
level: 2,
- message: 'type may not be empty',
- name: 'type-empty',
+ message: "type may not be empty",
+ name: "type-empty",
valid: false,
},
subjectCase: {
level: 2,
message:
- 'subject must not be sentence-case, start-case, pascal-case, upper-case',
- name: 'subject-case',
+ "subject must not be sentence-case, start-case, pascal-case, upper-case",
+ name: "subject-case",
valid: false,
},
subjectEmpty: {
level: 2,
- message: 'subject may not be empty',
- name: 'subject-empty',
+ message: "subject may not be empty",
+ name: "subject-empty",
valid: false,
},
subjectFullStop: {
level: 2,
- message: 'subject may not end with full stop',
- name: 'subject-full-stop',
+ message: "subject may not end with full stop",
+ name: "subject-full-stop",
valid: false,
},
headerMaxLength: {
level: 2,
message:
- 'header must not be longer than 100 characters, current length is 112',
- name: 'header-max-length',
+ "header must not be longer than 100 characters, current length is 112",
+ name: "header-max-length",
valid: false,
},
footerMaxLineLength: {
level: 2,
message: "footer's lines must not be longer than 100 characters",
- name: 'footer-max-line-length',
+ name: "footer-max-line-length",
valid: false,
},
bodyMaxLineLength: {
level: 2,
message: "body's lines must not be longer than 100 characters",
- name: 'body-max-line-length',
+ name: "body-max-line-length",
valid: false,
},
};
@@ -114,42 +114,44 @@ const errors = {
const warnings = {
footerLeadingBlank: {
level: 1,
- message: 'footer must have leading blank line',
- name: 'footer-leading-blank',
+ message: "footer must have leading blank line",
+ name: "footer-leading-blank",
valid: false,
},
bodyLeadingBlank: {
level: 1,
- message: 'body must have leading blank line',
- name: 'body-leading-blank',
+ message: "body must have leading blank line",
+ name: "body-leading-blank",
valid: false,
},
};
-test('type-enum', async () => {
+test("type-enum", async () => {
const result = await commitLint(messages.invalidTypeEnum);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([errors.typeEnum]);
});
-test('type-case', async () => {
+test("type-case", async () => {
const result = await commitLint(messages.invalidTypeCase);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([errors.typeCase, errors.typeEnum]);
});
-test('type-empty', async () => {
+test("type-empty", async () => {
const result = await commitLint(messages.invalidTypeEmpty);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([errors.typeEmpty]);
});
-test('subject-case', async () => {
+test("subject-case", async () => {
const invalidInputs = await Promise.all(
- messages.invalidSubjectCases.map((invalidInput) => commitLint(invalidInput))
+ messages.invalidSubjectCases.map((invalidInput) =>
+ commitLint(invalidInput),
+ ),
);
invalidInputs.forEach((result) => {
@@ -158,58 +160,58 @@ test('subject-case', async () => {
});
});
-test('subject-empty', async () => {
+test("subject-empty", async () => {
const result = await commitLint(messages.invalidSubjectEmpty);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([errors.subjectEmpty, errors.typeEmpty]);
});
-test('subject-full-stop', async () => {
+test("subject-full-stop", async () => {
const result = await commitLint(messages.invalidSubjectFullStop);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([errors.subjectFullStop]);
});
-test('header-max-length', async () => {
+test("header-max-length", async () => {
const result = await commitLint(messages.invalidHeaderMaxLength);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([errors.headerMaxLength]);
});
-test('footer-leading-blank', async () => {
+test("footer-leading-blank", async () => {
const result = await commitLint(messages.warningFooterLeadingBlank);
expect(result.valid).toBe(true);
expect(result.warnings).toEqual([warnings.footerLeadingBlank]);
});
-test('footer-max-line-length', async () => {
+test("footer-max-line-length", async () => {
const result = await commitLint(messages.invalidFooterMaxLineLength);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([errors.footerMaxLineLength]);
});
-test('body-leading-blank', async () => {
+test("body-leading-blank", async () => {
const result = await commitLint(messages.warningBodyLeadingBlank);
expect(result.valid).toBe(true);
expect(result.warnings).toEqual([warnings.bodyLeadingBlank]);
});
-test('body-max-line-length', async () => {
+test("body-max-line-length", async () => {
const result = await commitLint(messages.invalidBodyMaxLineLength);
expect(result.valid).toBe(false);
expect(result.errors).toEqual([errors.bodyMaxLineLength]);
});
-test('valid messages', async () => {
+test("valid messages", async () => {
const validInputs = await Promise.all(
- messages.validMessages.map((input) => commitLint(input))
+ messages.validMessages.map((input) => commitLint(input)),
);
validInputs.forEach((result) => {
diff --git a/@commitlint/config-conventional/src/index.ts b/@commitlint/config-conventional/src/index.ts
index f07f233f0e..09ee1c9a67 100644
--- a/@commitlint/config-conventional/src/index.ts
+++ b/@commitlint/config-conventional/src/index.ts
@@ -2,45 +2,45 @@ import {
RuleConfigCondition,
RuleConfigSeverity,
TargetCaseType,
-} from '@commitlint/types';
+} from "@commitlint/types";
export default {
- parserPreset: 'conventional-changelog-conventionalcommits',
+ parserPreset: "conventional-changelog-conventionalcommits",
rules: {
- 'body-leading-blank': [RuleConfigSeverity.Warning, 'always'] as const,
- 'body-max-line-length': [RuleConfigSeverity.Error, 'always', 100] as const,
- 'footer-leading-blank': [RuleConfigSeverity.Warning, 'always'] as const,
- 'footer-max-line-length': [
+ "body-leading-blank": [RuleConfigSeverity.Warning, "always"] as const,
+ "body-max-line-length": [RuleConfigSeverity.Error, "always", 100] as const,
+ "footer-leading-blank": [RuleConfigSeverity.Warning, "always"] as const,
+ "footer-max-line-length": [
RuleConfigSeverity.Error,
- 'always',
+ "always",
100,
] as const,
- 'header-max-length': [RuleConfigSeverity.Error, 'always', 100] as const,
- 'header-trim': [RuleConfigSeverity.Error, 'always'] as const,
- 'subject-case': [
+ "header-max-length": [RuleConfigSeverity.Error, "always", 100] as const,
+ "header-trim": [RuleConfigSeverity.Error, "always"] as const,
+ "subject-case": [
RuleConfigSeverity.Error,
- 'never',
- ['sentence-case', 'start-case', 'pascal-case', 'upper-case'],
+ "never",
+ ["sentence-case", "start-case", "pascal-case", "upper-case"],
] as [RuleConfigSeverity, RuleConfigCondition, TargetCaseType[]],
- 'subject-empty': [RuleConfigSeverity.Error, 'never'] as const,
- 'subject-full-stop': [RuleConfigSeverity.Error, 'never', '.'] as const,
- 'type-case': [RuleConfigSeverity.Error, 'always', 'lower-case'] as const,
- 'type-empty': [RuleConfigSeverity.Error, 'never'] as const,
- 'type-enum': [
+ "subject-empty": [RuleConfigSeverity.Error, "never"] as const,
+ "subject-full-stop": [RuleConfigSeverity.Error, "never", "."] as const,
+ "type-case": [RuleConfigSeverity.Error, "always", "lower-case"] as const,
+ "type-empty": [RuleConfigSeverity.Error, "never"] as const,
+ "type-enum": [
RuleConfigSeverity.Error,
- 'always',
+ "always",
[
- 'build',
- 'chore',
- 'ci',
- 'docs',
- 'feat',
- 'fix',
- 'perf',
- 'refactor',
- 'revert',
- 'style',
- 'test',
+ "build",
+ "chore",
+ "ci",
+ "docs",
+ "feat",
+ "fix",
+ "perf",
+ "refactor",
+ "revert",
+ "style",
+ "test",
],
] as [RuleConfigSeverity, RuleConfigCondition, string[]],
},
@@ -50,93 +50,93 @@ export default {
description: "Select the type of change that you're committing",
enum: {
feat: {
- description: 'A new feature',
- title: 'Features',
- emoji: '✨',
+ description: "A new feature",
+ title: "Features",
+ emoji: "✨",
},
fix: {
- description: 'A bug fix',
- title: 'Bug Fixes',
- emoji: '🐛',
+ description: "A bug fix",
+ title: "Bug Fixes",
+ emoji: "🐛",
},
docs: {
- description: 'Documentation only changes',
- title: 'Documentation',
- emoji: '📚',
+ description: "Documentation only changes",
+ title: "Documentation",
+ emoji: "📚",
},
style: {
description:
- 'Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)',
- title: 'Styles',
- emoji: '💎',
+ "Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",
+ title: "Styles",
+ emoji: "💎",
},
refactor: {
description:
- 'A code change that neither fixes a bug nor adds a feature',
- title: 'Code Refactoring',
- emoji: '📦',
+ "A code change that neither fixes a bug nor adds a feature",
+ title: "Code Refactoring",
+ emoji: "📦",
},
perf: {
- description: 'A code change that improves performance',
- title: 'Performance Improvements',
- emoji: '🚀',
+ description: "A code change that improves performance",
+ title: "Performance Improvements",
+ emoji: "🚀",
},
test: {
- description: 'Adding missing tests or correcting existing tests',
- title: 'Tests',
- emoji: '🚨',
+ description: "Adding missing tests or correcting existing tests",
+ title: "Tests",
+ emoji: "🚨",
},
build: {
description:
- 'Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)',
- title: 'Builds',
- emoji: '🛠',
+ "Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)",
+ title: "Builds",
+ emoji: "🛠",
},
ci: {
description:
- 'Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)',
- title: 'Continuous Integrations',
- emoji: '⚙️',
+ "Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)",
+ title: "Continuous Integrations",
+ emoji: "⚙️",
},
chore: {
description: "Other changes that don't modify src or test files",
- title: 'Chores',
- emoji: '♻️',
+ title: "Chores",
+ emoji: "♻️",
},
revert: {
- description: 'Reverts a previous commit',
- title: 'Reverts',
- emoji: '🗑',
+ description: "Reverts a previous commit",
+ title: "Reverts",
+ emoji: "🗑",
},
},
},
scope: {
description:
- 'What is the scope of this change (e.g. component or file name)',
+ "What is the scope of this change (e.g. component or file name)",
},
subject: {
description:
- 'Write a short, imperative tense description of the change',
+ "Write a short, imperative tense description of the change",
},
body: {
- description: 'Provide a longer description of the change',
+ description: "Provide a longer description of the change",
},
isBreaking: {
- description: 'Are there any breaking changes?',
+ description: "Are there any breaking changes?",
},
breakingBody: {
description:
- 'A BREAKING CHANGE commit requires a body. Please enter a longer description of the commit itself',
+ "A BREAKING CHANGE commit requires a body. Please enter a longer description of the commit itself",
},
breaking: {
- description: 'Describe the breaking changes',
+ description: "Describe the breaking changes",
},
isIssueAffected: {
- description: 'Does this change affect any open issues?',
+ description: "Does this change affect any open issues?",
},
issuesBody: {
description:
- 'If issues are closed, the commit requires a body. Please enter a longer description of the commit itself',
+ "If issues are closed, the commit requires a body. Please enter a longer description of the commit itself",
},
issues: {
description: 'Add issue references (e.g. "fix #123", "re #123".)',
diff --git a/@commitlint/config-lerna-scopes/index.js b/@commitlint/config-lerna-scopes/index.js
index accda8d8f2..a24642b5ae 100644
--- a/@commitlint/config-lerna-scopes/index.js
+++ b/@commitlint/config-lerna-scopes/index.js
@@ -1,13 +1,13 @@
-import path from 'node:path';
-import fs from 'node:fs/promises';
-import fg from 'fast-glob';
-import configWorkspaceScopes from '@commitlint/config-workspace-scopes';
+import path from "node:path";
+import fs from "node:fs/promises";
+import fg from "fast-glob";
+import configWorkspaceScopes from "@commitlint/config-workspace-scopes";
export default {
- utils: {getProjects},
+ utils: { getProjects },
rules: {
- 'scope-enum': (ctx) =>
- getProjects(ctx).then((packages) => [2, 'always', packages]),
+ "scope-enum": (ctx) =>
+ getProjects(ctx).then((packages) => [2, "always", packages]),
},
};
@@ -20,7 +20,7 @@ export default {
function normalizePatterns(patterns) {
const normalizedPatterns = [];
for (const pattern of patterns) {
- normalizedPatterns.push(pattern.replace(/\/?$/, '/package.json'));
+ normalizedPatterns.push(pattern.replace(/\/?$/, "/package.json"));
}
return normalizedPatterns;
}
@@ -31,8 +31,8 @@ function normalizePatterns(patterns) {
* @returns A list of parsed package.json files as objects
*/
async function findPackages(cwd) {
- const json = await fs.readFile(path.join(cwd, 'lerna.json'), {
- encoding: 'utf-8',
+ const json = await fs.readFile(path.join(cwd, "lerna.json"), {
+ encoding: "utf-8",
});
const packages = JSON.parse(json)?.packages || [];
@@ -43,13 +43,13 @@ async function findPackages(cwd) {
const patterns = normalizePatterns(packages);
const entries = await fg(patterns, {
cwd,
- ignore: ['**/node_modules/**', '**/bower_components/**'],
+ ignore: ["**/node_modules/**", "**/bower_components/**"],
});
const pkgJsons = await Promise.all(
Array.from(new Set(entries.map((entry) => path.join(cwd, entry)))).map(
- (pkgPath) => fs.readFile(pkgPath, {encoding: 'utf-8'})
- )
+ (pkgPath) => fs.readFile(pkgPath, { encoding: "utf-8" }),
+ ),
);
return pkgJsons.map((pkgJson) => JSON.parse(pkgJson) || {});
@@ -70,7 +70,7 @@ async function getProjects(context) {
`It seems that you are using npm/yarn workspaces instead of lernas "packages" declaration.`,
`Support for workspaces will be removed in a future major version of this package.`,
`Please make sure to transition to "@commitlint/config-workspace-scopes" in the near future.`,
- ].join('\n')
+ ].join("\n"),
);
return workspacePackages;
}
@@ -81,7 +81,7 @@ async function getProjects(context) {
.reduce((pkgNames, pkg) => {
const name = pkg.name;
if (name) {
- pkgNames.push(name.charAt(0) === '@' ? name.split('/')[1] : name);
+ pkgNames.push(name.charAt(0) === "@" ? name.split("/")[1] : name);
}
return pkgNames;
}, [])
diff --git a/@commitlint/config-lerna-scopes/index.test.js b/@commitlint/config-lerna-scopes/index.test.js
index 2ed89fcb9e..3de602d281 100644
--- a/@commitlint/config-lerna-scopes/index.test.js
+++ b/@commitlint/config-lerna-scopes/index.test.js
@@ -1,119 +1,119 @@
-import {test, expect, vi} from 'vitest';
-import path from 'path';
-import {fileURLToPath} from 'url';
+import { test, expect, vi } from "vitest";
+import path from "path";
+import { fileURLToPath } from "url";
-import {npm} from '@commitlint/test';
+import { npm } from "@commitlint/test";
-import config from './index.js';
+import config from "./index.js";
-const __dirname = path.resolve(fileURLToPath(import.meta.url), '..');
+const __dirname = path.resolve(fileURLToPath(import.meta.url), "..");
-test('exports rules key', () => {
- expect(config).toHaveProperty('rules');
+test("exports rules key", () => {
+ expect(config).toHaveProperty("rules");
});
-test('rules hold object', () => {
+test("rules hold object", () => {
expect(config).toMatchObject({
rules: expect.any(Object),
});
});
-test('rules contain scope-enum', () => {
+test("rules contain scope-enum", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.anything(),
+ "scope-enum": expect.anything(),
},
});
});
-test('scope-enum is function', () => {
+test("scope-enum is function", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.any(Function),
+ "scope-enum": expect.any(Function),
},
});
});
-test('scope-enum does not throw for missing context', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum does not throw for missing context", async () => {
+ const { "scope-enum": fn } = config.rules;
await expect(fn()).resolves.toBeTruthy();
});
-test('scope-enum has expected severity', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected severity", async () => {
+ const { "scope-enum": fn } = config.rules;
const [severity] = await fn();
expect(severity).toBe(2);
});
-test('scope-enum has expected modifier', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected modifier", async () => {
+ const { "scope-enum": fn } = config.rules;
const [, modifier] = await fn();
- expect(modifier).toBe('always');
+ expect(modifier).toBe("always");
});
-test('returns empty value for empty lerna repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/empty', __dirname);
- const [, , value] = await fn({cwd});
+test("returns empty value for empty lerna repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/empty", __dirname);
+ const [, , value] = await fn({ cwd });
expect(value).toEqual([]);
});
-test('returns all packages for nested lerna packages repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/nested', __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['nested-a', 'nested-b', 'nested-c']);
+test("returns all packages for nested lerna packages repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/nested", __dirname);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["nested-a", "nested-b", "nested-c"]);
});
-test('returns expected value for basic lerna repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/basic', __dirname);
+test("returns expected value for basic lerna repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/basic", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['basic-a', 'basic-b']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["basic-a", "basic-b"]);
});
-test('returns expected value for lerna repository containing modules', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/modules', __dirname);
+test("returns expected value for lerna repository containing modules", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/modules", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['modules-a']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["modules-a"]);
});
-test('returns expected value for scoped lerna repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/scoped', __dirname);
+test("returns expected value for scoped lerna repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/scoped", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['scoped-a', 'scoped-b']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["scoped-a", "scoped-b"]);
});
-test('work with no declared packages', async () => {
- const {'scope-enum': fn} = config.rules;
+test("work with no declared packages", async () => {
+ const { "scope-enum": fn } = config.rules;
const cwd = await npm.bootstrap(
- 'fixtures/no-packages-declaration',
- __dirname
+ "fixtures/no-packages-declaration",
+ __dirname,
);
- const [, , value] = await fn({cwd});
+ const [, , value] = await fn({ cwd });
expect(value).toEqual([]);
});
-test('inform the user about the transition to config-workspace-scopes if the project is using native workspaces', async () => {
- const {'scope-enum': fn} = config.rules;
+test("inform the user about the transition to config-workspace-scopes if the project is using native workspaces", async () => {
+ const { "scope-enum": fn } = config.rules;
const cwd = await npm.bootstrap(
- 'fixtures/transition-to-workspace-scopes',
- __dirname
+ "fixtures/transition-to-workspace-scopes",
+ __dirname,
);
- const consoleWarnSpy = vi.spyOn(console, 'warn');
+ const consoleWarnSpy = vi.spyOn(console, "warn");
- const [, , value] = await fn({cwd});
+ const [, , value] = await fn({ cwd });
expect(consoleWarnSpy).toHaveBeenCalledWith(
- expect.stringContaining(`It seems that you are using npm/yarn workspaces`)
+ expect.stringContaining(`It seems that you are using npm/yarn workspaces`),
);
- expect(value).toEqual(['workspace-package']);
+ expect(value).toEqual(["workspace-package"]);
});
diff --git a/@commitlint/config-nx-scopes/index.js b/@commitlint/config-nx-scopes/index.js
index 5251f49492..25debbeba3 100644
--- a/@commitlint/config-nx-scopes/index.js
+++ b/@commitlint/config-nx-scopes/index.js
@@ -1,12 +1,12 @@
-import {RuleConfigSeverity} from '@commitlint/types';
-import {getProjects as getNXProjects} from 'nx/src/generators/utils/project-configuration.js';
-import {FsTree} from 'nx/src/generators/tree.js';
+import { RuleConfigSeverity } from "@commitlint/types";
+import { getProjects as getNXProjects } from "nx/src/generators/utils/project-configuration.js";
+import { FsTree } from "nx/src/generators/tree.js";
export default {
- utils: {getProjects},
+ utils: { getProjects },
rules: {
- 'scope-enum': (ctx) =>
- Promise.resolve([RuleConfigSeverity.Error, 'always', getProjects(ctx)]),
+ "scope-enum": (ctx) =>
+ Promise.resolve([RuleConfigSeverity.Error, "always", getProjects(ctx)]),
},
};
@@ -28,8 +28,8 @@ function getProjects(context, selector = () => true) {
name: project.name,
projectType: project.projectType,
tags: project.tags,
- })
+ }),
)
.map((project) => project.name)
- .map((name) => (name.charAt(0) === '@' ? name.split('/')[1] : name));
+ .map((name) => (name.charAt(0) === "@" ? name.split("/")[1] : name));
}
diff --git a/@commitlint/config-nx-scopes/index.test.js b/@commitlint/config-nx-scopes/index.test.js
index 22a525f145..1a6f863ef3 100644
--- a/@commitlint/config-nx-scopes/index.test.js
+++ b/@commitlint/config-nx-scopes/index.test.js
@@ -1,91 +1,91 @@
-import {test, expect} from 'vitest';
-import path from 'node:path';
-import {fileURLToPath} from 'node:url';
+import { test, expect } from "vitest";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
-import {npm} from '@commitlint/test';
+import { npm } from "@commitlint/test";
-import config from './index.js';
+import config from "./index.js";
-const __dirname = path.resolve(fileURLToPath(import.meta.url), '..');
+const __dirname = path.resolve(fileURLToPath(import.meta.url), "..");
-test('exports rules key', () => {
- expect(config).toHaveProperty('rules');
+test("exports rules key", () => {
+ expect(config).toHaveProperty("rules");
});
-test('rules hold object', () => {
+test("rules hold object", () => {
expect(config).toMatchObject({
rules: expect.any(Object),
});
});
-test('rules contain scope-enum', () => {
+test("rules contain scope-enum", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.anything(),
+ "scope-enum": expect.anything(),
},
});
});
-test('scope-enum is function', () => {
+test("scope-enum is function", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.any(Function),
+ "scope-enum": expect.any(Function),
},
});
});
-test('scope-enum does not throw for missing context', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum does not throw for missing context", async () => {
+ const { "scope-enum": fn } = config.rules;
await expect(fn()).resolves.toBeTruthy();
});
-test('scope-enum has expected severity', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected severity", async () => {
+ const { "scope-enum": fn } = config.rules;
const [severity] = await fn();
expect(severity).toBe(2);
});
-test('scope-enum has expected modifier', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected modifier", async () => {
+ const { "scope-enum": fn } = config.rules;
const [, modifier] = await fn();
- expect(modifier).toBe('always');
+ expect(modifier).toBe("always");
});
-test('returns empty value for empty nx repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/empty', __dirname);
- const [, , value] = await fn({cwd});
+test("returns empty value for empty nx repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/empty", __dirname);
+ const [, , value] = await fn({ cwd });
expect(value).toEqual([]);
});
-test('returns expected value for basic nx repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/basic', __dirname);
+test("returns expected value for basic nx repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/basic", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['a', 'b']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["a", "b"]);
});
-test('expect correct result from Nx 14', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/nx14', __dirname);
+test("expect correct result from Nx 14", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/nx14", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['c', 'd']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["c", "d"]);
});
-test('expect correct result from Nx 15', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/nx15', __dirname);
+test("expect correct result from Nx 15", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/nx15", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['e', 'f']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["e", "f"]);
});
-test('expect correct result from Nx 17', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/nx17', __dirname);
+test("expect correct result from Nx 17", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/nx17", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['g', 'h']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["g", "h"]);
});
diff --git a/@commitlint/config-nx-scopes/readme.md b/@commitlint/config-nx-scopes/readme.md
index 454a28b1e0..2890f85872 100644
--- a/@commitlint/config-nx-scopes/readme.md
+++ b/@commitlint/config-nx-scopes/readme.md
@@ -24,20 +24,20 @@ In your .commitlintrc.js file:
async function getConfig() {
const {
default: {
- utils: {getProjects},
+ utils: { getProjects },
},
- } = await import('@commitlint/config-nx-scopes');
+ } = await import("@commitlint/config-nx-scopes");
return {
rules: {
- 'scope-enum': async (ctx) => [
+ "scope-enum": async (ctx) => [
2,
- 'always',
+ "always",
[
...(await getProjects(
ctx,
- ({name, projectType}) =>
- !name.includes('e2e') && projectType == 'application'
+ ({ name, projectType }) =>
+ !name.includes("e2e") && projectType == "application",
)),
],
],
@@ -57,19 +57,19 @@ In your .commitlintrc.js file:
async function getConfig() {
const {
default: {
- utils: {getProjects},
+ utils: { getProjects },
},
- } = await import('@commitlint/config-nx-scopes');
+ } = await import("@commitlint/config-nx-scopes");
return {
rules: {
- 'scope-enum': async (ctx) => [
+ "scope-enum": async (ctx) => [
2,
- 'always',
+ "always",
[
...(await getProjects(
ctx,
- ({tags}) => !tags.includes('stage:end-of-life')
+ ({ tags }) => !tags.includes("stage:end-of-life"),
)),
],
],
diff --git a/@commitlint/config-patternplate/index.js b/@commitlint/config-patternplate/index.js
index b732bf932a..240efb9655 100644
--- a/@commitlint/config-patternplate/index.js
+++ b/@commitlint/config-patternplate/index.js
@@ -1,24 +1,24 @@
-import path from 'node:path';
+import path from "node:path";
-import configAngular from '@commitlint/config-angular';
-import {glob} from 'glob';
-import merge from 'lodash.merge';
+import configAngular from "@commitlint/config-angular";
+import { glob } from "glob";
+import merge from "lodash.merge";
function pathToId(root, filePath) {
const relativePath = path.relative(root, filePath);
- return path.dirname(relativePath).split(path.sep).join('/');
+ return path.dirname(relativePath).split(path.sep).join("/");
}
async function getPatternIDs() {
- const root = path.resolve(process.cwd(), './patterns');
- const pattern = path.resolve(root, '**/pattern.json');
+ const root = path.resolve(process.cwd(), "./patterns");
+ const pattern = path.resolve(root, "**/pattern.json");
const files = glob(pattern);
return files.map((result) => pathToId(root, result));
}
export default merge(configAngular, {
rules: {
- 'scope-enum': () =>
- getPatternIDs().then((ids) => [2, 'always', ids.concat(['system'])]),
+ "scope-enum": () =>
+ getPatternIDs().then((ids) => [2, "always", ids.concat(["system"])]),
},
});
diff --git a/@commitlint/config-pnpm-scopes/index.js b/@commitlint/config-pnpm-scopes/index.js
index 6119f3789f..eb93cce86e 100644
--- a/@commitlint/config-pnpm-scopes/index.js
+++ b/@commitlint/config-pnpm-scopes/index.js
@@ -1,20 +1,20 @@
-import path from 'node:path';
+import path from "node:path";
-import fg from 'fast-glob';
-import readYamlFile from 'read-yaml-file';
-import {readExactProjectManifest} from '@pnpm/read-project-manifest';
+import fg from "fast-glob";
+import readYamlFile from "read-yaml-file";
+import { readExactProjectManifest } from "@pnpm/read-project-manifest";
export default {
- utils: {getProjects},
+ utils: { getProjects },
rules: {
- 'scope-enum': (ctx) =>
- getProjects(ctx).then((packages) => [2, 'always', packages]),
+ "scope-enum": (ctx) =>
+ getProjects(ctx).then((packages) => [2, "always", packages]),
},
};
function requirePackagesManifest(dir) {
- return readYamlFile(path.join(dir, 'pnpm-workspace.yaml')).catch((err) => {
- if (err.code === 'ENOENT') {
+ return readYamlFile(path.join(dir, "pnpm-workspace.yaml")).catch((err) => {
+ if (err.code === "ENOENT") {
return null;
}
@@ -25,9 +25,9 @@ function requirePackagesManifest(dir) {
function normalizePatterns(patterns) {
const normalizedPatterns = [];
for (const pattern of patterns) {
- normalizedPatterns.push(pattern.replace(/\/?$/, '/package.json'));
- normalizedPatterns.push(pattern.replace(/\/?$/, '/package.json5'));
- normalizedPatterns.push(pattern.replace(/\/?$/, '/package.yaml'));
+ normalizedPatterns.push(pattern.replace(/\/?$/, "/package.json"));
+ normalizedPatterns.push(pattern.replace(/\/?$/, "/package.json5"));
+ normalizedPatterns.push(pattern.replace(/\/?$/, "/package.yaml"));
}
return normalizedPatterns;
}
@@ -36,22 +36,22 @@ function findWorkspacePackages(cwd) {
return requirePackagesManifest(cwd)
.then((manifest) => {
const patterns = normalizePatterns(
- (manifest && manifest.packages) || ['**']
+ (manifest && manifest.packages) || ["**"],
);
const opts = {
cwd,
- ignore: ['**/node_modules/**', '**/bower_components/**'],
+ ignore: ["**/node_modules/**", "**/bower_components/**"],
};
return fg(patterns, opts);
})
.then((entries) => {
const paths = Array.from(
- new Set(entries.map((entry) => path.join(cwd, entry)))
+ new Set(entries.map((entry) => path.join(cwd, entry))),
);
return Promise.all(
- paths.map((manifestPath) => readExactProjectManifest(manifestPath))
+ paths.map((manifestPath) => readExactProjectManifest(manifestPath)),
);
})
.then((manifests) => {
@@ -69,7 +69,7 @@ function getProjects(context) {
const name = project.name;
if (name) {
- projects.push(name.charAt(0) === '@' ? name.split('/')[1] : name);
+ projects.push(name.charAt(0) === "@" ? name.split("/")[1] : name);
}
return projects;
diff --git a/@commitlint/config-pnpm-scopes/index.test.js b/@commitlint/config-pnpm-scopes/index.test.js
index 26644ec6fe..5b28bf7d1e 100644
--- a/@commitlint/config-pnpm-scopes/index.test.js
+++ b/@commitlint/config-pnpm-scopes/index.test.js
@@ -1,76 +1,76 @@
-import {test, expect} from 'vitest';
-import path from 'node:path';
-import {fileURLToPath} from 'node:url';
+import { test, expect } from "vitest";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
-import {npm} from '@commitlint/test';
+import { npm } from "@commitlint/test";
-import config from './index.js';
+import config from "./index.js";
-const __dirname = path.resolve(fileURLToPath(import.meta.url), '..');
+const __dirname = path.resolve(fileURLToPath(import.meta.url), "..");
-test('exports rules key', () => {
- expect(config).toHaveProperty('rules');
+test("exports rules key", () => {
+ expect(config).toHaveProperty("rules");
});
-test('rules hold object', () => {
+test("rules hold object", () => {
expect(config).toMatchObject({
rules: expect.any(Object),
});
});
-test('rules contain scope-enum', () => {
+test("rules contain scope-enum", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.anything(),
+ "scope-enum": expect.anything(),
},
});
});
-test('scope-enum is function', () => {
+test("scope-enum is function", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.any(Function),
+ "scope-enum": expect.any(Function),
},
});
});
-test('scope-enum does not throw for missing context', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum does not throw for missing context", async () => {
+ const { "scope-enum": fn } = config.rules;
await expect(fn()).resolves.toBeTruthy();
});
-test('scope-enum has expected severity', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected severity", async () => {
+ const { "scope-enum": fn } = config.rules;
const [severity] = await fn();
expect(severity).toBe(2);
});
-test('scope-enum has expected modifier', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected modifier", async () => {
+ const { "scope-enum": fn } = config.rules;
const [, modifier] = await fn();
- expect(modifier).toBe('always');
+ expect(modifier).toBe("always");
});
-test('returns empty value for empty pnpm repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/empty', __dirname);
- const [, , value] = await fn({cwd});
+test("returns empty value for empty pnpm repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/empty", __dirname);
+ const [, , value] = await fn({ cwd });
expect(value).toEqual([]);
});
-test('returns expected value for basic pnpm repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/basic', __dirname);
+test("returns expected value for basic pnpm repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/basic", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['a', 'b']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["a", "b"]);
});
-test('returns expected value for scoped pnpm repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/scoped', __dirname);
+test("returns expected value for scoped pnpm repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/scoped", __dirname);
- const [, , value] = await fn({cwd});
+ const [, , value] = await fn({ cwd });
- expect(value).toEqual(['a', 'b']);
+ expect(value).toEqual(["a", "b"]);
});
diff --git a/@commitlint/config-rush-scopes/index.js b/@commitlint/config-rush-scopes/index.js
index f20d64b4b1..07fc2e1d07 100644
--- a/@commitlint/config-rush-scopes/index.js
+++ b/@commitlint/config-rush-scopes/index.js
@@ -1,13 +1,13 @@
-import Path from 'node:path';
-import fs from 'fs/promises';
+import Path from "node:path";
+import fs from "fs/promises";
-import jsonc from 'jsonc';
+import jsonc from "jsonc";
export default {
- utils: {getPackages},
+ utils: { getPackages },
rules: {
- 'scope-enum': (ctx) =>
- getPackages(ctx).then((packages) => [2, 'always', packages]),
+ "scope-enum": (ctx) =>
+ getPackages(ctx).then((packages) => [2, "always", packages]),
},
};
@@ -18,15 +18,15 @@ function getPackages(context) {
const cwd = ctx.cwd || process.cwd();
return fs
- .readFile(Path.join(cwd, 'rush.json'), {encoding: 'utf8'})
+ .readFile(Path.join(cwd, "rush.json"), { encoding: "utf8" })
.then((content) => jsonc.parse(content))
- .then(({projects}) => projects)
+ .then(({ projects }) => projects)
.catch(() => []);
})
.then((packages) => {
return packages
.map((pkg) => pkg.packageName)
.filter(Boolean)
- .map((name) => (name.charAt(0) === '@' ? name.split('/')[1] : name));
+ .map((name) => (name.charAt(0) === "@" ? name.split("/")[1] : name));
});
}
diff --git a/@commitlint/config-rush-scopes/index.test.js b/@commitlint/config-rush-scopes/index.test.js
index 84b2e04bea..a5ce89033e 100644
--- a/@commitlint/config-rush-scopes/index.test.js
+++ b/@commitlint/config-rush-scopes/index.test.js
@@ -1,76 +1,76 @@
-import {test, expect} from 'vitest';
-import path from 'node:path';
-import {fileURLToPath} from 'node:url';
+import { test, expect } from "vitest";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
-import {npm} from '@commitlint/test';
+import { npm } from "@commitlint/test";
-import config from './index.js';
+import config from "./index.js";
-const __dirname = path.resolve(fileURLToPath(import.meta.url), '..');
+const __dirname = path.resolve(fileURLToPath(import.meta.url), "..");
-test('exports rules key', () => {
- expect(config).toHaveProperty('rules');
+test("exports rules key", () => {
+ expect(config).toHaveProperty("rules");
});
-test('rules hold object', () => {
+test("rules hold object", () => {
expect(config).toMatchObject({
rules: expect.any(Object),
});
});
-test('rules contain scope-enum', () => {
+test("rules contain scope-enum", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.anything(),
+ "scope-enum": expect.anything(),
},
});
});
-test('scope-enum is function', () => {
+test("scope-enum is function", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.any(Function),
+ "scope-enum": expect.any(Function),
},
});
});
-test('scope-enum does not throw for missing context', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum does not throw for missing context", async () => {
+ const { "scope-enum": fn } = config.rules;
await expect(fn()).resolves.toBeTruthy();
});
-test('scope-enum has expected severity', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected severity", async () => {
+ const { "scope-enum": fn } = config.rules;
const [severity] = await fn();
expect(severity).toBe(2);
});
-test('scope-enum has expected modifier', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected modifier", async () => {
+ const { "scope-enum": fn } = config.rules;
const [, modifier] = await fn();
- expect(modifier).toBe('always');
+ expect(modifier).toBe("always");
});
-test('returns empty value for empty rush repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/empty', __dirname);
- const [, , value] = await fn({cwd});
+test("returns empty value for empty rush repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/empty", __dirname);
+ const [, , value] = await fn({ cwd });
expect(value).toEqual([]);
});
-test('returns expected value for basic rush repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/basic', __dirname);
+test("returns expected value for basic rush repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/basic", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['a', 'b']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["a", "b"]);
});
-test('returns expected value for scoped lerna repository', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/scoped', __dirname);
+test("returns expected value for scoped lerna repository", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/scoped", __dirname);
- const [, , value] = await fn({cwd});
+ const [, , value] = await fn({ cwd });
- expect(value).toEqual(['a', 'b']);
+ expect(value).toEqual(["a", "b"]);
});
diff --git a/@commitlint/config-validator/src/commitlint.schema.json b/@commitlint/config-validator/src/commitlint.schema.json
index 12998f4f49..2c6d2075a9 100644
--- a/@commitlint/config-validator/src/commitlint.schema.json
+++ b/@commitlint/config-validator/src/commitlint.schema.json
@@ -39,25 +39,25 @@
"oneOf": [
{
"type": "array",
- "items": {"type": "string"}
+ "items": { "type": "string" }
},
- {"type": "string"}
+ { "type": "string" }
]
},
"parserPreset": {
"description": "Resolveable id to conventional-changelog parser preset to import and use",
"oneOf": [
- {"type": "string"},
+ { "type": "string" },
{
"type": "object",
"properties": {
- "name": {"type": "string"},
- "path": {"type": "string"},
+ "name": { "type": "string" },
+ "path": { "type": "string" },
"parserOpts": {}
},
"additionalProperties": true
},
- {"typeof": "function"}
+ { "typeof": "function" }
]
},
"helpUrl": {
@@ -71,15 +71,15 @@
"rules": {
"description": "Rules to check against",
"type": "object",
- "propertyNames": {"type": "string"},
- "additionalProperties": {"$ref": "#/definitions/rule"}
+ "propertyNames": { "type": "string" },
+ "additionalProperties": { "$ref": "#/definitions/rule" }
},
"plugins": {
"description": "Resolveable ids of commitlint plugins from node_modules",
"type": "array",
"items": {
"anyOf": [
- {"type": "string"},
+ { "type": "string" },
{
"type": "object",
"required": ["rules"],
@@ -94,7 +94,7 @@
},
"ignores": {
"type": "array",
- "items": {"typeof": "function"},
+ "items": { "typeof": "function" },
"description": "Additional commits to ignore, defined by ignore matchers"
},
"defaultIgnores": {
diff --git a/@commitlint/config-validator/src/formatErrors.ts b/@commitlint/config-validator/src/formatErrors.ts
index 3ca61d39a9..1021c92eb8 100644
--- a/@commitlint/config-validator/src/formatErrors.ts
+++ b/@commitlint/config-validator/src/formatErrors.ts
@@ -1,4 +1,4 @@
-import type {ErrorObject} from 'ajv';
+import type { ErrorObject } from "ajv";
/**
* Formats an array of schema validation errors.
@@ -10,8 +10,8 @@ export function formatErrors(errors: ErrorObject[]): string {
return errors
.map((error) => {
if (
- error.keyword === 'additionalProperties' &&
- 'additionalProperty' in error.params
+ error.keyword === "additionalProperties" &&
+ "additionalProperty" in error.params
) {
const formattedPropertyPath = error.instancePath.length
? `${error.instancePath.slice(1)}.${error.params.additionalProperty}`
@@ -19,7 +19,7 @@ export function formatErrors(errors: ErrorObject[]): string {
return `Unexpected top-level property "${formattedPropertyPath}"`;
}
- if (error.keyword === 'type') {
+ if (error.keyword === "type") {
const formattedField = error.instancePath.slice(1);
if (!formattedField) {
return `Config has the wrong type - ${error.message}`;
@@ -27,19 +27,19 @@ export function formatErrors(errors: ErrorObject[]): string {
return `Property "${formattedField}" has the wrong type - ${error.message}`;
}
const field =
- (error.instancePath[0] === '.'
+ (error.instancePath[0] === "."
? error.instancePath.slice(1)
- : error.instancePath) || 'Config';
- if (error.keyword === 'typeof') {
+ : error.instancePath) || "Config";
+ if (error.keyword === "typeof") {
return `"${field}" should be a ${error.schema}. Value: ${JSON.stringify(
- error.data
+ error.data,
)}`;
}
return `"${field}" ${error.message}. Value: ${JSON.stringify(
- error.data
+ error.data,
)}`;
})
.map((message) => `\t- ${message}.\n`)
- .join('');
+ .join("");
}
diff --git a/@commitlint/config-validator/src/validate.test.ts b/@commitlint/config-validator/src/validate.test.ts
index f8e61e069c..1a3c402c4b 100644
--- a/@commitlint/config-validator/src/validate.test.ts
+++ b/@commitlint/config-validator/src/validate.test.ts
@@ -1,75 +1,75 @@
-import {describe, test, expect} from 'vitest';
-import {RuleConfigSeverity, UserConfig} from '@commitlint/types';
+import { describe, test, expect } from "vitest";
+import { RuleConfigSeverity, UserConfig } from "@commitlint/types";
-import {validateConfig} from './validate.js';
+import { validateConfig } from "./validate.js";
const validSchemas: Record = {
empty: {},
- withEmptyExtends: {extends: []},
- withStringExtends: {extends: 'test'},
- withSingleExtends: {extends: ['test']},
- withMultipleExtends: {extends: ['test', 'test2']},
- withFormatter: {formatter: ''},
- withHelpUrl: {helpUrl: ''},
+ withEmptyExtends: { extends: [] },
+ withStringExtends: { extends: "test" },
+ withSingleExtends: { extends: ["test"] },
+ withMultipleExtends: { extends: ["test", "test2"] },
+ withFormatter: { formatter: "" },
+ withHelpUrl: { helpUrl: "" },
withRules: {
rules: {
a: [RuleConfigSeverity.Disabled],
- b: [RuleConfigSeverity.Warning, 'never'],
- c: [RuleConfigSeverity.Error, 'never', true],
+ b: [RuleConfigSeverity.Warning, "never"],
+ c: [RuleConfigSeverity.Error, "never", true],
},
},
- withParserPresetString: {parserPreset: 'test'},
- withParserPresetObject: {parserPreset: {}},
- withParserPresetObject2: {parserPreset: {name: 'string', path: 'string'}},
+ withParserPresetString: { parserPreset: "test" },
+ withParserPresetObject: { parserPreset: {} },
+ withParserPresetObject2: { parserPreset: { name: "string", path: "string" } },
withParserPresetObjectPromise: {
- parserPreset: Promise.resolve({name: 'string'}),
+ parserPreset: Promise.resolve({ name: "string" }),
},
- withParserPresetOpts: {parserPreset: {parserOpts: {test: 1}}},
+ withParserPresetOpts: { parserPreset: { parserOpts: { test: 1 } } },
withParserPresetOptsPromise: {
- parserPreset: {parserOpts: Promise.resolve({test: 1})},
+ parserPreset: { parserOpts: Promise.resolve({ test: 1 }) },
},
- withEmptyIgnores: {ignores: []},
- withIgnores: {ignores: [() => true]},
- withDefaultIgnoresTrue: {defaultIgnores: true},
- withDefaultIgnoresFalse: {defaultIgnores: false},
- withEmptyPlugins: {plugins: []},
- withPluginsAsString: {plugins: ['test']},
- withPluginsAsObject: {plugins: [{rules: {}}]},
- shouldSkipAllowAdditionalProperties: {foo: 1},
+ withEmptyIgnores: { ignores: [] },
+ withIgnores: { ignores: [() => true] },
+ withDefaultIgnoresTrue: { defaultIgnores: true },
+ withDefaultIgnoresFalse: { defaultIgnores: false },
+ withEmptyPlugins: { plugins: [] },
+ withPluginsAsString: { plugins: ["test"] },
+ withPluginsAsObject: { plugins: [{ rules: {} }] },
+ shouldSkipAllowAdditionalProperties: { foo: 1 },
};
const invalidSchemas: Record = {
whenConfigIsNotObject: [],
- whenConfigIsNotObject2: '',
- extendsAsObject: {extends: {test: 1}},
- extendsWithFunction: {extends: [() => true]},
- formatterAsObject: {formatter: {}},
- helpUrlAsArray: {helpUrl: []},
- rulesAsArray: {rules: ['a']},
- rules1: {rules: {a: [3]}},
- rules2: {rules: {b: [1, 'test', 2, 2]}},
- rules3: {rules: {c: []}},
- rules4: {rules: {d: [[], [], []]}},
- rules5: {rules: {e: {}}},
- parserPreset: {parserPreset: []},
- ignoresFunction: {ignores: () => true},
- ignoresNotFunction: {ignores: [1]},
- defaultIgnoresNotBoolean: {defaultIgnores: 'true'},
- pluginsNotArray: {plugins: 'test'},
- withPluginsAsObject: {plugins: [{}]},
- helpUrlNotString: {helpUrl: {}},
+ whenConfigIsNotObject2: "",
+ extendsAsObject: { extends: { test: 1 } },
+ extendsWithFunction: { extends: [() => true] },
+ formatterAsObject: { formatter: {} },
+ helpUrlAsArray: { helpUrl: [] },
+ rulesAsArray: { rules: ["a"] },
+ rules1: { rules: { a: [3] } },
+ rules2: { rules: { b: [1, "test", 2, 2] } },
+ rules3: { rules: { c: [] } },
+ rules4: { rules: { d: [[], [], []] } },
+ rules5: { rules: { e: {} } },
+ parserPreset: { parserPreset: [] },
+ ignoresFunction: { ignores: () => true },
+ ignoresNotFunction: { ignores: [1] },
+ defaultIgnoresNotBoolean: { defaultIgnores: "true" },
+ pluginsNotArray: { plugins: "test" },
+ withPluginsAsObject: { plugins: [{}] },
+ helpUrlNotString: { helpUrl: {} },
};
-describe('validation should pass for', () => {
- test.each(Object.entries(validSchemas))('%s', (file, config) => {
+describe("validation should pass for", () => {
+ test.each(Object.entries(validSchemas))("%s", (file, config) => {
expect(() => validateConfig(`${file}.js`, config)).not.toThrow();
});
});
-describe('validation should fail for', () => {
- test.each(Object.entries(invalidSchemas))('%s', (file, config) => {
+describe("validation should fail for", () => {
+ test.each(Object.entries(invalidSchemas))("%s", (file, config) => {
expect(() =>
- validateConfig(`${file}.js`, config)
+ validateConfig(`${file}.js`, config),
).toThrowErrorMatchingSnapshot();
});
});
diff --git a/@commitlint/config-validator/src/validate.ts b/@commitlint/config-validator/src/validate.ts
index 5eec2704cc..d4c28a2c7a 100644
--- a/@commitlint/config-validator/src/validate.ts
+++ b/@commitlint/config-validator/src/validate.ts
@@ -1,22 +1,22 @@
-import {createRequire} from 'node:module';
+import { createRequire } from "node:module";
-import {UserConfig} from '@commitlint/types';
-import _Ajv from 'ajv';
+import { UserConfig } from "@commitlint/types";
+import _Ajv from "ajv";
-import {formatErrors} from './formatErrors.js';
+import { formatErrors } from "./formatErrors.js";
const require = createRequire(import.meta.url);
-const schema: typeof import('./commitlint.schema.json') = require('./commitlint.schema.json');
+const schema: typeof import("./commitlint.schema.json") = require("./commitlint.schema.json");
const TYPE_OF = [
- 'undefined',
- 'string',
- 'number',
- 'object',
- 'function',
- 'boolean',
- 'symbol',
+ "undefined",
+ "string",
+ "number",
+ "object",
+ "function",
+ "boolean",
+ "symbol",
];
// FIXME: https://github.com/ajv-validator/ajv/issues/2132
@@ -24,7 +24,7 @@ const Ajv = _Ajv as unknown as typeof _Ajv.default;
export function validateConfig(
source: string,
- config: unknown
+ config: unknown,
): asserts config is UserConfig {
const ajv = new Ajv({
meta: false,
@@ -35,11 +35,11 @@ export function validateConfig(
});
ajv.addKeyword({
- keyword: 'typeof',
+ keyword: "typeof",
validate: function typeOfFunc(schema: any, data: any) {
return typeof data === schema;
},
- metaSchema: {type: 'string', enum: TYPE_OF},
+ metaSchema: { type: "string", enum: TYPE_OF },
schema: true,
});
@@ -49,8 +49,8 @@ export function validateConfig(
if (!isValid && validate.errors && validate.errors.length) {
throw new Error(
`Commitlint configuration in ${source} is invalid:\n${formatErrors(
- validate.errors
- )}`
+ validate.errors,
+ )}`,
);
}
}
diff --git a/@commitlint/config-validator/tsconfig.json b/@commitlint/config-validator/tsconfig.json
index 65f2e6c397..5ef37ea5e3 100644
--- a/@commitlint/config-validator/tsconfig.json
+++ b/@commitlint/config-validator/tsconfig.json
@@ -7,5 +7,5 @@
},
"include": ["./src/**/*.ts", "./src/**/*.json"],
"exclude": ["./src/**/*.test.ts", "./lib/**/*"],
- "references": [{"path": "../types"}]
+ "references": [{ "path": "../types" }]
}
diff --git a/@commitlint/config-workspace-scopes/index.js b/@commitlint/config-workspace-scopes/index.js
index c365c099d6..e4fc5ea0f3 100644
--- a/@commitlint/config-workspace-scopes/index.js
+++ b/@commitlint/config-workspace-scopes/index.js
@@ -1,15 +1,15 @@
-import {createRequire} from 'node:module';
-import Path from 'node:path';
+import { createRequire } from "node:module";
+import Path from "node:path";
-import {globSync} from 'glob';
+import { globSync } from "glob";
const require = createRequire(import.meta.url);
export default {
- utils: {getPackages},
+ utils: { getPackages },
rules: {
- 'scope-enum': (ctx) =>
- getPackages(ctx).then((packages) => [2, 'always', packages]),
+ "scope-enum": (ctx) =>
+ getPackages(ctx).then((packages) => [2, "always", packages]),
},
};
@@ -19,15 +19,15 @@ function getPackages(context) {
const ctx = context || {};
const cwd = ctx.cwd || process.cwd();
- const {workspaces} = require(Path.join(cwd, 'package.json'));
+ const { workspaces } = require(Path.join(cwd, "package.json"));
if (!Array.isArray(workspaces)) {
// no workspaces configured, skipping
return [];
}
const wsGlobs = workspaces.flatMap((ws) => {
- const path = Path.posix.join(ws, 'package.json');
- return globSync(path, {cwd, ignore: ['**/node_modules/**']});
+ const path = Path.posix.join(ws, "package.json");
+ return globSync(path, { cwd, ignore: ["**/node_modules/**"] });
});
return wsGlobs.sort().map((pJson) => require(Path.join(cwd, pJson)));
@@ -36,6 +36,6 @@ function getPackages(context) {
return packages
.map((pkg) => pkg.name)
.filter(Boolean)
- .map((name) => (name.charAt(0) === '@' ? name.split('/')[1] : name));
+ .map((name) => (name.charAt(0) === "@" ? name.split("/")[1] : name));
});
}
diff --git a/@commitlint/config-workspace-scopes/index.test.js b/@commitlint/config-workspace-scopes/index.test.js
index e969f4dc58..a7d09239a0 100644
--- a/@commitlint/config-workspace-scopes/index.test.js
+++ b/@commitlint/config-workspace-scopes/index.test.js
@@ -1,86 +1,86 @@
-import {test, expect} from 'vitest';
-import path from 'node:path';
-import {fileURLToPath} from 'node:url';
+import { test, expect } from "vitest";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
-import {npm} from '@commitlint/test';
+import { npm } from "@commitlint/test";
-import config from './index.js';
+import config from "./index.js";
-const __dirname = path.resolve(fileURLToPath(import.meta.url), '..');
+const __dirname = path.resolve(fileURLToPath(import.meta.url), "..");
-test('exports rules key', () => {
- expect(config).toHaveProperty('rules');
+test("exports rules key", () => {
+ expect(config).toHaveProperty("rules");
});
-test('rules hold object', () => {
+test("rules hold object", () => {
expect(config).toMatchObject({
rules: expect.any(Object),
});
});
-test('rules contain scope-enum', () => {
+test("rules contain scope-enum", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.anything(),
+ "scope-enum": expect.anything(),
},
});
});
-test('scope-enum is function', () => {
+test("scope-enum is function", () => {
expect(config).toMatchObject({
rules: {
- 'scope-enum': expect.any(Function),
+ "scope-enum": expect.any(Function),
},
});
});
-test('scope-enum does not throw for missing context', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum does not throw for missing context", async () => {
+ const { "scope-enum": fn } = config.rules;
await expect(fn()).resolves.toBeTruthy();
});
-test('scope-enum has expected severity', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected severity", async () => {
+ const { "scope-enum": fn } = config.rules;
const [severity] = await fn();
expect(severity).toBe(2);
});
-test('scope-enum has expected modifier', async () => {
- const {'scope-enum': fn} = config.rules;
+test("scope-enum has expected modifier", async () => {
+ const { "scope-enum": fn } = config.rules;
const [, modifier] = await fn();
- expect(modifier).toBe('always');
+ expect(modifier).toBe("always");
});
-test('returns empty value for empty workspaces', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/empty', __dirname);
- const [, , value] = await fn({cwd});
+test("returns empty value for empty workspaces", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/empty", __dirname);
+ const [, , value] = await fn({ cwd });
expect(value).toEqual([]);
});
-test('returns expected value for basic workspaces', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/basic', __dirname);
+test("returns expected value for basic workspaces", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/basic", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['a', 'b']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["a", "b"]);
});
-test('returns expected value for scoped workspaces', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/scoped', __dirname);
+test("returns expected value for scoped workspaces", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/scoped", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(['a', 'b']);
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(["a", "b"]);
});
-test('returns expected value for workspaces has nested packages', async () => {
- const {'scope-enum': fn} = config.rules;
- const cwd = await npm.bootstrap('fixtures/nested-workspaces', __dirname);
+test("returns expected value for workspaces has nested packages", async () => {
+ const { "scope-enum": fn } = config.rules;
+ const cwd = await npm.bootstrap("fixtures/nested-workspaces", __dirname);
- const [, , value] = await fn({cwd});
- expect(value).toEqual(expect.arrayContaining(['nested-a', 'nested-b']));
+ const [, , value] = await fn({ cwd });
+ expect(value).toEqual(expect.arrayContaining(["nested-a", "nested-b"]));
expect(value).toEqual(
- expect.not.arrayContaining(['dependency-a', 'dependency-b'])
+ expect.not.arrayContaining(["dependency-a", "dependency-b"]),
);
});
diff --git a/@commitlint/core/src/core.ts b/@commitlint/core/src/core.ts
index eeee4f41b5..3181e0ac71 100644
--- a/@commitlint/core/src/core.ts
+++ b/@commitlint/core/src/core.ts
@@ -1,6 +1,6 @@
-import format from '@commitlint/format';
-import load from '@commitlint/load';
-import lint from '@commitlint/lint';
-import read from '@commitlint/read';
+import format from "@commitlint/format";
+import load from "@commitlint/load";
+import lint from "@commitlint/lint";
+import read from "@commitlint/read";
-export {format, load, lint, read};
+export { format, load, lint, read };
diff --git a/@commitlint/cz-commitlint/src/Process.test.ts b/@commitlint/cz-commitlint/src/Process.test.ts
index 7c6def0f1e..fefca0c40a 100644
--- a/@commitlint/cz-commitlint/src/Process.test.ts
+++ b/@commitlint/cz-commitlint/src/Process.test.ts
@@ -1,13 +1,13 @@
-import {describe, test, expect, vi, beforeEach, afterEach} from 'vitest';
+import { describe, test, expect, vi, beforeEach, afterEach } from "vitest";
import {
QualifiedRules,
RuleConfigSeverity,
UserPromptConfig,
-} from '@commitlint/types';
-import {Answers, DistinctQuestion} from 'inquirer';
-import isFunction from 'lodash.isfunction';
+} from "@commitlint/types";
+import { Answers, DistinctQuestion } from "inquirer";
+import isFunction from "lodash.isfunction";
-import process from './Process.js';
+import process from "./Process.js";
const mockShowTitle = vi.fn();
const mockShowValidation = vi.fn((message) => message);
@@ -15,23 +15,23 @@ const mockShowValidation = vi.fn((message) => message);
// mock inquirer
const mockPrompt = vi.fn(async function (
questions: DistinctQuestion[],
- answers: Answers
+ answers: Answers,
) {
- for (const {name, message, when, filter, validate} of questions) {
- if (typeof when !== 'function' || (await when(answers))) {
+ for (const { name, message, when, filter, validate } of questions) {
+ if (typeof when !== "function" || (await when(answers))) {
const title =
message && isFunction(message)
? await message(answers)
- : typeof message === 'string'
- ? message
- : '';
+ : typeof message === "string"
+ ? message
+ : "";
mockShowTitle(title);
const validation =
- typeof validate !== 'function' ||
- (await validate((name && answers[name]) ?? '', answers));
+ typeof validate !== "function" ||
+ (await validate((name && answers[name]) ?? "", answers));
- if (typeof validation === 'string') {
+ if (typeof validation === "string") {
mockShowValidation(validation);
break;
} else if (filter && name && answers[name]) {
@@ -53,12 +53,12 @@ function InquirerFactory(answers: Answers) {
}
const MESSAGES = {
- skip: '(press enter to skip)',
- max: 'upper %d chars',
- min: '%d chars at least',
- emptyWarning: '%s can not be empty',
- upperLimitWarning: '%s: %s over limit %d',
- lowerLimitWarning: '%s: %s below limit %d',
+ skip: "(press enter to skip)",
+ max: "upper %d chars",
+ min: "%d chars at least",
+ emptyWarning: "%s can not be empty",
+ upperLimitWarning: "%s: %s over limit %d",
+ lowerLimitWarning: "%s: %s below limit %d",
};
let rules: QualifiedRules;
@@ -69,38 +69,38 @@ afterEach(() => {
mockShowValidation.mockClear();
});
-describe('conventional-changlog', () => {
+describe("conventional-changlog", () => {
beforeEach(() => {
rules = {
- 'body-leading-blank': [RuleConfigSeverity.Warning, 'always'],
- 'body-max-line-length': [RuleConfigSeverity.Error, 'always', 100],
- 'footer-leading-blank': [RuleConfigSeverity.Warning, 'always'],
- 'footer-max-line-length': [RuleConfigSeverity.Error, 'always', 100],
- 'header-max-length': [RuleConfigSeverity.Error, 'always', 100],
- 'subject-case': [
+ "body-leading-blank": [RuleConfigSeverity.Warning, "always"],
+ "body-max-line-length": [RuleConfigSeverity.Error, "always", 100],
+ "footer-leading-blank": [RuleConfigSeverity.Warning, "always"],
+ "footer-max-line-length": [RuleConfigSeverity.Error, "always", 100],
+ "header-max-length": [RuleConfigSeverity.Error, "always", 100],
+ "subject-case": [
RuleConfigSeverity.Error,
- 'never',
- ['sentence-case', 'start-case', 'pascal-case', 'upper-case'],
+ "never",
+ ["sentence-case", "start-case", "pascal-case", "upper-case"],
],
- 'subject-empty': [RuleConfigSeverity.Error, 'never'],
- 'subject-full-stop': [RuleConfigSeverity.Error, 'never', '.'],
- 'type-case': [RuleConfigSeverity.Error, 'always', 'lower-case'],
- 'type-empty': [RuleConfigSeverity.Error, 'never'],
- 'type-enum': [
+ "subject-empty": [RuleConfigSeverity.Error, "never"],
+ "subject-full-stop": [RuleConfigSeverity.Error, "never", "."],
+ "type-case": [RuleConfigSeverity.Error, "always", "lower-case"],
+ "type-empty": [RuleConfigSeverity.Error, "never"],
+ "type-enum": [
RuleConfigSeverity.Error,
- 'always',
+ "always",
[
- 'build',
- 'chore',
- 'ci',
- 'docs',
- 'feat',
- 'fix',
- 'perf',
- 'refactor',
- 'revert',
- 'style',
- 'test',
+ "build",
+ "chore",
+ "ci",
+ "docs",
+ "feat",
+ "fix",
+ "perf",
+ "refactor",
+ "revert",
+ "style",
+ "test",
],
],
};
@@ -111,93 +111,93 @@ describe('conventional-changlog', () => {
description: "Select the type of change that you're committing:",
enum: {
feat: {
- description: 'A new feature',
- title: 'Features',
- emoji: '✨',
+ description: "A new feature",
+ title: "Features",
+ emoji: "✨",
},
fix: {
- description: 'A bug fix',
- title: 'Bug Fixes',
- emoji: '🐛',
+ description: "A bug fix",
+ title: "Bug Fixes",
+ emoji: "🐛",
},
docs: {
- description: 'Documentation only changes',
- title: 'Documentation',
- emoji: '📚',
+ description: "Documentation only changes",
+ title: "Documentation",
+ emoji: "📚",
},
style: {
description:
- 'Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)',
- title: 'Styles',
- emoji: '💎',
+ "Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)",
+ title: "Styles",
+ emoji: "💎",
},
refactor: {
description:
- 'A code change that neither fixes a bug nor adds a feature',
- title: 'Code Refactoring',
- emoji: '📦',
+ "A code change that neither fixes a bug nor adds a feature",
+ title: "Code Refactoring",
+ emoji: "📦",
},
perf: {
- description: 'A code change that improves performance',
- title: 'Performance Improvements',
- emoji: '🚀',
+ description: "A code change that improves performance",
+ title: "Performance Improvements",
+ emoji: "🚀",
},
test: {
- description: 'Adding missing tests or correcting existing tests',
- title: 'Tests',
- emoji: '🚨',
+ description: "Adding missing tests or correcting existing tests",
+ title: "Tests",
+ emoji: "🚨",
},
build: {
description:
- 'Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)',
- title: 'Builds',
- emoji: '🛠',
+ "Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm)",
+ title: "Builds",
+ emoji: "🛠",
},
ci: {
description:
- 'Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)',
- title: 'Continuous Integrations',
- emoji: '⚙️',
+ "Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs)",
+ title: "Continuous Integrations",
+ emoji: "⚙️",
},
chore: {
description: "Other changes that don't modify src or test files",
- title: 'Chores',
- emoji: '♻️',
+ title: "Chores",
+ emoji: "♻️",
},
revert: {
- description: 'Reverts a previous commit',
- title: 'Reverts',
- emoji: '🗑',
+ description: "Reverts a previous commit",
+ title: "Reverts",
+ emoji: "🗑",
},
},
},
scope: {
description:
- 'What is the scope of this change (e.g. component or file name)',
+ "What is the scope of this change (e.g. component or file name)",
},
subject: {
description:
- 'Write a short, imperative tense description of the change',
+ "Write a short, imperative tense description of the change",
},
body: {
- description: 'Provide a longer description of the change',
+ description: "Provide a longer description of the change",
},
isBreaking: {
- description: 'Are there any breaking changes?',
+ description: "Are there any breaking changes?",
},
breakingBody: {
description:
- 'A BREAKING CHANGE commit requires a body. Please enter a longer description of the commit itself',
+ "A BREAKING CHANGE commit requires a body. Please enter a longer description of the commit itself",
},
breaking: {
- description: 'Describe the breaking changes',
+ description: "Describe the breaking changes",
},
isIssueAffected: {
- description: 'Does this change affect any open issues?',
+ description: "Does this change affect any open issues?",
},
issuesBody: {
description:
- 'If issues are closed, the commit requires a body. Please enter a longer description of the commit itself',
+ "If issues are closed, the commit requires a body. Please enter a longer description of the commit itself",
},
issues: {
description: 'Add issue references (e.g. "fix #123", "re #123".)',
@@ -205,39 +205,39 @@ describe('conventional-changlog', () => {
},
};
});
- test('should process works well', () => {
+ test("should process works well", () => {
const answers = {
- type: 'refactor',
- scope: 'prompt',
- subject: 'refactor prompt based on inquirer',
- body: 'inspired by commitizen/cz-conventional-changelog',
+ type: "refactor",
+ scope: "prompt",
+ subject: "refactor prompt based on inquirer",
+ body: "inspired by commitizen/cz-conventional-changelog",
isBreaking: true,
- breaking: 'refactor types',
+ breaking: "refactor types",
isIssueAffected: true,
- issues: 'https://github.com/conventional-changelog/commitlint/issues/94',
+ issues: "https://github.com/conventional-changelog/commitlint/issues/94",
};
return process(rules, prompts, InquirerFactory(answers)).then(
(commitMessage) => {
expect(commitMessage).toBe(
- 'refactor(prompt): refactor prompt based on inquirer\n\ninspired by commitizen/cz-conventional-changelog\n\nBREAKING CHANGE: refactor types\nhttps://github.com/conventional-changelog/commitlint/issues/94'
+ "refactor(prompt): refactor prompt based on inquirer\n\ninspired by commitizen/cz-conventional-changelog\n\nBREAKING CHANGE: refactor types\nhttps://github.com/conventional-changelog/commitlint/issues/94",
);
- }
+ },
);
});
- test('should show validation and stop process when subject is empty', () => {
+ test("should show validation and stop process when subject is empty", () => {
const answers = {
- type: 'refactor',
- scope: 'prompt',
- body: 'inspired by commitizen/cz-conventional-changelog',
+ type: "refactor",
+ scope: "prompt",
+ body: "inspired by commitizen/cz-conventional-changelog",
isBreaking: true,
- breaking: 'refactor types',
+ breaking: "refactor types",
isIssueAffected: true,
- issues: 'https://github.com/conventional-changelog/commitlint/issues/94',
+ issues: "https://github.com/conventional-changelog/commitlint/issues/94",
};
return process(rules, prompts, InquirerFactory(answers)).then(() => {
expect(mockShowValidation).toHaveBeenCalledWith(
- 'subject can not be empty'
+ "subject can not be empty",
);
expect(mockShowTitle).toHaveBeenCalledTimes(3);
});
diff --git a/@commitlint/cz-commitlint/src/Process.ts b/@commitlint/cz-commitlint/src/Process.ts
index 4023477bff..48ec039d6f 100644
--- a/@commitlint/cz-commitlint/src/Process.ts
+++ b/@commitlint/cz-commitlint/src/Process.ts
@@ -1,27 +1,27 @@
-import {QualifiedRules, UserPromptConfig} from '@commitlint/types';
-import type {Answers, DistinctQuestion} from 'inquirer';
+import { QualifiedRules, UserPromptConfig } from "@commitlint/types";
+import type { Answers, DistinctQuestion } from "inquirer";
import {
combineCommitMessage as combineBody,
getQuestions as getBodyQuestions,
-} from './SectionBody.js';
+} from "./SectionBody.js";
import {
combineCommitMessage as combineFooter,
getQuestions as getFooterQuestions,
-} from './SectionFooter.js';
+} from "./SectionFooter.js";
import {
combineCommitMessage as combineHeader,
getQuestions as getHeaderQuestions,
-} from './SectionHeader.js';
-import {setPromptConfig} from './store/prompts.js';
-import {setRules} from './store/rules.js';
+} from "./SectionHeader.js";
+import { setPromptConfig } from "./store/prompts.js";
+import { setRules } from "./store/rules.js";
export default async function (
rules: QualifiedRules,
prompts: UserPromptConfig,
inquirer: {
prompt(questions: DistinctQuestion[]): Promise;
- }
+ },
): Promise {
setRules(rules);
setPromptConfig(prompts);
@@ -35,5 +35,5 @@ export default async function (
const body = combineBody(answers);
const footer = combineFooter(answers);
- return [header, body, footer].filter(Boolean).join('\n');
+ return [header, body, footer].filter(Boolean).join("\n");
}
diff --git a/@commitlint/cz-commitlint/src/Question.test.ts b/@commitlint/cz-commitlint/src/Question.test.ts
index fd9ea3eb7f..d04ba708fb 100644
--- a/@commitlint/cz-commitlint/src/Question.test.ts
+++ b/@commitlint/cz-commitlint/src/Question.test.ts
@@ -1,19 +1,19 @@
-import {describe, test, expect, vi} from 'vitest';
-import chalk from 'chalk';
-import inquirer, {Answers, InputQuestionOptions} from 'inquirer';
+import { describe, test, expect, vi } from "vitest";
+import chalk from "chalk";
+import inquirer, { Answers, InputQuestionOptions } from "inquirer";
-import Question from './Question.js';
+import Question from "./Question.js";
const MESSAGES = {
- skip: '(press enter to skip)',
- max: 'upper %d chars',
- min: '%d chars at least',
- emptyWarning: '%s can not be empty',
- upperLimitWarning: '%s: %s over limit %d',
- lowerLimitWarning: '%s: %s below limit %d',
+ skip: "(press enter to skip)",
+ max: "upper %d chars",
+ min: "%d chars at least",
+ emptyWarning: "%s can not be empty",
+ upperLimitWarning: "%s: %s over limit %d",
+ lowerLimitWarning: "%s: %s below limit %d",
};
const QUESTION_CONFIG = {
- title: 'please input',
+ title: "please input",
messages: MESSAGES,
};
@@ -22,347 +22,347 @@ const caseFn = (input: string | string[], delimiter?: string) =>
.map((segment) => segment[0].toUpperCase() + segment.slice(1))
.join(delimiter);
-describe('name', () => {
- test('should throw error when name is not a meaningful string', () => {
+describe("name", () => {
+ test("should throw error when name is not a meaningful string", () => {
expect(
() =>
- new Question('' as any, {
+ new Question("" as any, {
...QUESTION_CONFIG,
- })
+ }),
).toThrow();
expect(
() =>
new Question(
function () {
- return 'scope';
+ return "scope";
} as any,
{
...QUESTION_CONFIG,
- }
- )
+ },
+ ),
).toThrow();
});
- test('should set name when name is valid', () => {
+ test("should set name when name is valid", () => {
expect(
- new Question('test' as any, {
+ new Question("test" as any, {
...QUESTION_CONFIG,
- }).question
- ).toHaveProperty('name', 'test');
+ }).question,
+ ).toHaveProperty("name", "test");
});
});
-describe('type', () => {
+describe("type", () => {
test('should return "list" type when enumList is array and multipleSelectDefaultDelimiter is undefined', () => {
- const question = new Question('scope', {
+ const question = new Question("scope", {
...QUESTION_CONFIG,
- enumList: ['cli', 'core'],
+ enumList: ["cli", "core"],
}).question;
- expect(question).toHaveProperty('type', 'list');
- expect(question).toHaveProperty('choices', ['cli', 'core']);
- expect(question).not.toHaveProperty('transformer');
+ expect(question).toHaveProperty("type", "list");
+ expect(question).toHaveProperty("choices", ["cli", "core"]);
+ expect(question).not.toHaveProperty("transformer");
});
test('should return "checkbox" type when enumList is array and multipleSelectDefaultDelimiter is defined', () => {
- const question = new Question('scope', {
+ const question = new Question("scope", {
...QUESTION_CONFIG,
- enumList: ['cli', 'core'],
- multipleSelectDefaultDelimiter: ',',
+ enumList: ["cli", "core"],
+ multipleSelectDefaultDelimiter: ",",
}).question;
- expect(question).toHaveProperty('type', 'checkbox');
- expect(question).toHaveProperty('choices', ['cli', 'core']);
- expect(question).not.toHaveProperty('transformer');
+ expect(question).toHaveProperty("type", "checkbox");
+ expect(question).toHaveProperty("choices", ["cli", "core"]);
+ expect(question).not.toHaveProperty("transformer");
});
test('should contain "skip" list item when enumList is array and skip is true', () => {
- const question = new Question('scope', {
+ const question = new Question("scope", {
...QUESTION_CONFIG,
- enumList: ['cli', 'core'],
+ enumList: ["cli", "core"],
skip: true,
}).question;
- expect(question).toHaveProperty('type', 'list');
- expect(question).toHaveProperty('choices', [
- 'cli',
- 'core',
+ expect(question).toHaveProperty("type", "list");
+ expect(question).toHaveProperty("choices", [
+ "cli",
+ "core",
new inquirer.Separator(),
{
- name: 'empty',
- value: '',
+ name: "empty",
+ value: "",
},
]);
- expect(question).not.toHaveProperty('transformer');
+ expect(question).not.toHaveProperty("transformer");
});
test('should return "confirm" type when name is start with "is"', () => {
- const question = new Question('isSubmit' as any, {
+ const question = new Question("isSubmit" as any, {
...QUESTION_CONFIG,
}).question;
- expect(question).toHaveProperty('type', 'confirm');
- expect(question).not.toHaveProperty('choices');
- expect(question).not.toHaveProperty('transformer');
+ expect(question).toHaveProperty("type", "confirm");
+ expect(question).not.toHaveProperty("choices");
+ expect(question).not.toHaveProperty("transformer");
});
test('should return "input" type in other cases', () => {
- const question = new Question('body', {
+ const question = new Question("body", {
...QUESTION_CONFIG,
}).question;
- expect(question).toHaveProperty('type', 'input');
- expect(question).not.toHaveProperty('choices');
- expect(question).toHaveProperty('transformer', expect.any(Function));
+ expect(question).toHaveProperty("type", "input");
+ expect(question).not.toHaveProperty("choices");
+ expect(question).toHaveProperty("transformer", expect.any(Function));
});
});
-describe('message', () => {
- test('should display title when it is not input', () => {
- const question = new Question('body', {
+describe("message", () => {
+ test("should display title when it is not input", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
- enumList: ['cli', 'core'],
+ enumList: ["cli", "core"],
}).question;
- expect(question).toHaveProperty('message', expect.any(Function));
- expect((question.message as any)()).toBe('please input:');
+ expect(question).toHaveProperty("message", expect.any(Function));
+ expect((question.message as any)()).toBe("please input:");
});
- test('should display skip hint when it is input and can skip', () => {
- const question = new Question('body' as any, {
+ test("should display skip hint when it is input and can skip", () => {
+ const question = new Question("body" as any, {
...QUESTION_CONFIG,
skip: true,
}).question;
- expect(question).toHaveProperty('message', expect.any(Function));
+ expect(question).toHaveProperty("message", expect.any(Function));
expect((question.message as any)()).toBe(
- 'please input (press enter to skip):\n'
+ "please input (press enter to skip):\n",
);
});
- test('should not display skip hint when it is input and without skip string', () => {
- const question = new Question('scope', {
+ test("should not display skip hint when it is input and without skip string", () => {
+ const question = new Question("scope", {
...QUESTION_CONFIG,
messages: {},
skip: true,
} as any).question;
- expect(question).toHaveProperty('message', expect.any(Function));
- expect((question.message as any)()).toBe('please input:\n');
+ expect(question).toHaveProperty("message", expect.any(Function));
+ expect((question.message as any)()).toBe("please input:\n");
});
- test('should display upper limit hint when it is input and has max length', () => {
- const question = new Question('scope', {
+ test("should display upper limit hint when it is input and has max length", () => {
+ const question = new Question("scope", {
...QUESTION_CONFIG,
maxLength: 80,
} as any).question;
- expect(question).toHaveProperty('message', expect.any(Function));
- expect((question.message as any)()).toBe('please input: upper 80 chars\n');
+ expect(question).toHaveProperty("message", expect.any(Function));
+ expect((question.message as any)()).toBe("please input: upper 80 chars\n");
});
- test('should display lower limit hint when it is input and has min length', () => {
- const question = new Question('scope', {
+ test("should display lower limit hint when it is input and has min length", () => {
+ const question = new Question("scope", {
...QUESTION_CONFIG,
minLength: 10,
} as any).question;
- expect(question).toHaveProperty('message', expect.any(Function));
+ expect(question).toHaveProperty("message", expect.any(Function));
expect((question.message as any)()).toBe(
- 'please input: 10 chars at least\n'
+ "please input: 10 chars at least\n",
);
});
- test('should display hints with correct format', () => {
- const question = new Question('scope', {
+ test("should display hints with correct format", () => {
+ const question = new Question("scope", {
...QUESTION_CONFIG,
minLength: 10,
maxLength: 80,
skip: true,
} as any).question;
- expect(question).toHaveProperty('message', expect.any(Function));
+ expect(question).toHaveProperty("message", expect.any(Function));
expect((question.message as any)()).toBe(
- 'please input (press enter to skip): 10 chars at least, upper 80 chars\n'
+ "please input (press enter to skip): 10 chars at least, upper 80 chars\n",
);
});
- test('should execute function beforeQuestionStart when init message', () => {
+ test("should execute function beforeQuestionStart when init message", () => {
const mockFn = vi.fn();
class CustomQuestion extends Question {
beforeQuestionStart(answers: Answers): void {
mockFn(answers);
}
}
- const question = new CustomQuestion('body', {
+ const question = new CustomQuestion("body", {
...QUESTION_CONFIG,
} as any).question;
- expect(question).toHaveProperty('message', expect.any(Function));
+ expect(question).toHaveProperty("message", expect.any(Function));
const answers = {
- header: 'This is header',
- footer: 'This is footer',
+ header: "This is header",
+ footer: "This is footer",
};
(question.message as any)(answers);
expect(mockFn).toHaveBeenCalledWith(answers);
});
});
-describe('filter', () => {
- test('should auto fix case and full-stop', () => {
- const question = new Question('body', {
+describe("filter", () => {
+ test("should auto fix case and full-stop", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
caseFn,
- fullStopFn: (input: string) => input + '!',
+ fullStopFn: (input: string) => input + "!",
}).question;
- expect(question.filter?.('xxxx', {})).toBe('Xxxx!');
+ expect(question.filter?.("xxxx", {})).toBe("Xxxx!");
});
- test('should transform each item with same case when input is array', () => {
- const question = new Question('body', {
+ test("should transform each item with same case when input is array", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
caseFn,
- fullStopFn: (input: string) => input + '!',
+ fullStopFn: (input: string) => input + "!",
}).question;
- expect(question.filter?.(['xxxx', 'yyyy'], {})).toBe('Xxxx,Yyyy!');
+ expect(question.filter?.(["xxxx", "yyyy"], {})).toBe("Xxxx,Yyyy!");
});
- test('should concat items with multipleSelectDefaultDelimiter when input is array', () => {
- const question = new Question('body', {
+ test("should concat items with multipleSelectDefaultDelimiter when input is array", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
caseFn,
- fullStopFn: (input: string) => input + '!',
- multipleSelectDefaultDelimiter: '|',
+ fullStopFn: (input: string) => input + "!",
+ multipleSelectDefaultDelimiter: "|",
}).question;
- expect(question.filter?.(['xxxx', 'yyyy'], {})).toBe('Xxxx|Yyyy!');
+ expect(question.filter?.(["xxxx", "yyyy"], {})).toBe("Xxxx|Yyyy!");
});
- test('should split the string to items when multipleValueDelimiters is defined', () => {
- const question = new Question('body', {
+ test("should split the string to items when multipleValueDelimiters is defined", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
caseFn,
- fullStopFn: (input: string) => input + '!',
+ fullStopFn: (input: string) => input + "!",
multipleValueDelimiters: /,|\|/g,
}).question;
- expect(question.filter?.('xxxx,yyyy|zzzz', {})).toBe('Xxxx,Yyyy|Zzzz!');
- expect(question.filter?.('xxxx-yyyy-zzzz', {})).toBe('Xxxx-yyyy-zzzz!');
+ expect(question.filter?.("xxxx,yyyy|zzzz", {})).toBe("Xxxx,Yyyy|Zzzz!");
+ expect(question.filter?.("xxxx-yyyy-zzzz", {})).toBe("Xxxx-yyyy-zzzz!");
});
- test('should works well when does not pass caseFn/fullStopFn', () => {
- const question = new Question('body', {
+ test("should works well when does not pass caseFn/fullStopFn", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
}).question;
- expect(question.filter?.('xxxx', {})).toBe('xxxx');
+ expect(question.filter?.("xxxx", {})).toBe("xxxx");
});
});
-describe('validate', () => {
- test('should display empty warning when can not skip but string is empty', () => {
- const question = new Question('body', {
+describe("validate", () => {
+ test("should display empty warning when can not skip but string is empty", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
skip: false,
}).question;
- expect(question.validate?.('')).toBe('body can not be empty');
+ expect(question.validate?.("")).toBe("body can not be empty");
});
- test('should ignore empty validation when can skip', () => {
- const question = new Question('body', {
+ test("should ignore empty validation when can skip", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
skip: true,
}).question;
- expect(question.validate?.('')).toBe(true);
+ expect(question.validate?.("")).toBe(true);
});
- test('should display upper limit warning when char count is over upper limit', () => {
- const question = new Question('body', {
+ test("should display upper limit warning when char count is over upper limit", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
maxLength: 5,
}).question;
- expect(question.validate?.('xxxxxx')).toBe('body: body over limit 1');
+ expect(question.validate?.("xxxxxx")).toBe("body: body over limit 1");
});
- test('should display lower limit warning when char count is less than lower limit', () => {
- const question = new Question('body', {
+ test("should display lower limit warning when char count is less than lower limit", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
minLength: 5,
}).question;
- expect(question.validate?.('xxx')).toBe('body: body below limit 2');
+ expect(question.validate?.("xxx")).toBe("body: body below limit 2");
});
- test('should validate the final submit string', () => {
- const question = new Question('body', {
+ test("should validate the final submit string", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
- caseFn: () => '',
+ caseFn: () => "",
skip: false,
}).question;
- expect(question.validate?.('xxxx')).not.toBe(true);
+ expect(question.validate?.("xxxx")).not.toBe(true);
});
});
-describe('transformer', () => {
- test('should auto transform case and full-stop', () => {
- const question = new Question('body', {
+describe("transformer", () => {
+ test("should auto transform case and full-stop", () => {
+ const question = new Question("body", {
...QUESTION_CONFIG,
caseFn,
- fullStopFn: (input: string) => input + '!',
+ fullStopFn: (input: string) => input + "!",
}).question;
expect(
- (question as InputQuestionOptions)?.transformer?.('xxxx', {}, {})
- ).toBe('Xxxx!');
+ (question as InputQuestionOptions)?.transformer?.("xxxx", {}, {}),
+ ).toBe("Xxxx!");
});
- test('should char count with green color when in the limit range', () => {
- let question = new Question('body', {
+ test("should char count with green color when in the limit range", () => {
+ let question = new Question("body", {
...QUESTION_CONFIG,
maxLength: 5,
}).question;
expect(
- (question as InputQuestionOptions)?.transformer?.('xxx', {}, {})
+ (question as InputQuestionOptions)?.transformer?.("xxx", {}, {}),
).toEqual(chalk.green(`(3) xxx`));
- question = new Question('body', {
+ question = new Question("body", {
...QUESTION_CONFIG,
minLength: 2,
}).question;
expect(
- (question as InputQuestionOptions)?.transformer?.('xxx', {}, {})
+ (question as InputQuestionOptions)?.transformer?.("xxx", {}, {}),
).toEqual(chalk.green(`(3) xxx`));
});
- test('should char count with red color when over the limit range', () => {
- let question = new Question('body', {
+ test("should char count with red color when over the limit range", () => {
+ let question = new Question("body", {
...QUESTION_CONFIG,
maxLength: 5,
}).question;
expect(
- (question as InputQuestionOptions)?.transformer?.('xxxxxx', {}, {})
+ (question as InputQuestionOptions)?.transformer?.("xxxxxx", {}, {}),
).toEqual(chalk.red(`(6) xxxxxx`));
- question = new Question('body', {
+ question = new Question("body", {
...QUESTION_CONFIG,
minLength: 2,
}).question;
expect(
- (question as InputQuestionOptions)?.transformer?.('x', {}, {})
+ (question as InputQuestionOptions)?.transformer?.("x", {}, {}),
).toEqual(chalk.red(`(1) x`));
});
});
-describe('inquirer question', () => {
+describe("inquirer question", () => {
test('should pass "when" and "default" field to inquirer question', () => {
const when = (answers: Answers) => !!answers.header;
- const question = new Question('body', {
+ const question = new Question("body", {
...QUESTION_CONFIG,
when,
- defaultValue: 'update',
+ defaultValue: "update",
}).question;
- expect(question).toHaveProperty('default', 'update');
- expect(question).toHaveProperty('when', when);
+ expect(question).toHaveProperty("default", "update");
+ expect(question).toHaveProperty("when", when);
});
});
diff --git a/@commitlint/cz-commitlint/src/Question.ts b/@commitlint/cz-commitlint/src/Question.ts
index a641a4436a..c6a7ab24ad 100644
--- a/@commitlint/cz-commitlint/src/Question.ts
+++ b/@commitlint/cz-commitlint/src/Question.ts
@@ -1,9 +1,13 @@
-import {PromptMessages, PromptName} from '@commitlint/types';
-import chalk from 'chalk';
-import inquirer, {Answers, ChoiceCollection, DistinctQuestion} from 'inquirer';
+import { PromptMessages, PromptName } from "@commitlint/types";
+import chalk from "chalk";
+import inquirer, {
+ Answers,
+ ChoiceCollection,
+ DistinctQuestion,
+} from "inquirer";
-import {CaseFn} from './utils/case-fn.js';
-import {FullStopFn} from './utils/full-stop-fn.js';
+import { CaseFn } from "./utils/case-fn.js";
+import { FullStopFn } from "./utils/full-stop-fn.js";
export type QuestionConfig = {
title: string;
@@ -11,7 +15,7 @@ export type QuestionConfig = {
maxLength?: number;
minLength?: number;
defaultValue?: string;
- when?: DistinctQuestion['when'];
+ when?: DistinctQuestion["when"];
skip?: boolean;
enumList?: ChoiceCollection<{
name: string;
@@ -49,15 +53,15 @@ export default class Question {
minLength,
multipleValueDelimiters,
multipleSelectDefaultDelimiter,
- }: QuestionConfig
+ }: QuestionConfig,
) {
- if (!name || typeof name !== 'string')
- throw new Error('Question: name is required');
+ if (!name || typeof name !== "string")
+ throw new Error("Question: name is required");
this._maxLength = maxLength ?? Infinity;
this._minLength = minLength ?? 0;
this.messages = messages;
- this.title = title ?? '';
+ this.title = title ?? "";
this.skip = skip ?? false;
this.fullStopFn = fullStopFn ?? ((_: string) => _);
this.caseFn =
@@ -69,25 +73,25 @@ export default class Question {
if (enumList && Array.isArray(enumList)) {
this._question = {
- type: multipleSelectDefaultDelimiter ? 'checkbox' : 'list',
+ type: multipleSelectDefaultDelimiter ? "checkbox" : "list",
choices: skip
? [
...enumList,
new inquirer.Separator(),
{
- name: 'empty',
- value: '',
+ name: "empty",
+ value: "",
},
- ]
+ ]
: [...enumList],
};
} else if (/^is[A-Z]/.test(name)) {
this._question = {
- type: 'confirm',
+ type: "confirm",
};
} else {
this._question = {
- type: 'input',
+ type: "input",
transformer: this.transformer.bind(this),
};
}
@@ -103,7 +107,7 @@ export default class Question {
}
getMessage(key: string): string {
- return this.messages[key] ?? '';
+ return this.messages[key] ?? "";
}
get question(): Readonly {
@@ -132,19 +136,19 @@ export default class Question {
protected validate(input: string): boolean | string {
const output = this.filter(input);
- const questionName = this.question.name ?? '';
+ const questionName = this.question.name ?? "";
if (!this.skip && output.length === 0) {
- return this.getMessage('emptyWarning').replace(/%s/g, questionName);
+ return this.getMessage("emptyWarning").replace(/%s/g, questionName);
}
if (output.length > this.maxLength) {
- return this.getMessage('upperLimitWarning')
+ return this.getMessage("upperLimitWarning")
.replace(/%s/g, questionName)
.replace(/%d/g, `${output.length - this.maxLength}`);
}
if (output.length < this.minLength) {
- return this.getMessage('lowerLimitWarning')
+ return this.getMessage("lowerLimitWarning")
.replace(/%s/g, questionName)
.replace(/%d/g, `${this.minLength - output.length}`);
}
@@ -158,13 +162,13 @@ export default class Question {
toCased = this.caseFn(input, this.multipleSelectDefaultDelimiter);
} else if (this.multipleValueDelimiters) {
const segments = input.split(this.multipleValueDelimiters);
- const casedString = this.caseFn(segments, ',');
- const casedSegments = casedString.split(',');
+ const casedString = this.caseFn(segments, ",");
+ const casedSegments = casedString.split(",");
toCased = input.replace(
- new RegExp(`[^${this.multipleValueDelimiters.source}]+`, 'g'),
+ new RegExp(`[^${this.multipleValueDelimiters.source}]+`, "g"),
(segment) => {
return casedSegments[segments.indexOf(segment)];
- }
+ },
);
} else {
toCased = this.caseFn(input);
@@ -183,38 +187,38 @@ export default class Question {
output.length <= this.maxLength && output.length >= this.minLength
? chalk.green
: chalk.red;
- return color('(' + output.length + ') ' + output);
+ return color("(" + output.length + ") " + output);
}
protected decorateMessage(_answers: Answers): string {
if (this.beforeQuestionStart) {
this.beforeQuestionStart(_answers);
}
- if (this.question.type === 'input') {
+ if (this.question.type === "input") {
const countLimitMessage = (() => {
const messages = [];
- if (this.minLength > 0 && this.getMessage('min')) {
+ if (this.minLength > 0 && this.getMessage("min")) {
messages.push(
- this.getMessage('min').replace(/%d/g, this.minLength + '')
+ this.getMessage("min").replace(/%d/g, this.minLength + ""),
);
}
- if (this.maxLength < Infinity && this.getMessage('max')) {
+ if (this.maxLength < Infinity && this.getMessage("max")) {
messages.push(
- this.getMessage('max').replace(/%d/g, this.maxLength + '')
+ this.getMessage("max").replace(/%d/g, this.maxLength + ""),
);
}
- return messages.join(', ');
+ return messages.join(", ");
})();
- const skipMessage = this.skip && this.getMessage('skip');
+ const skipMessage = this.skip && this.getMessage("skip");
return (
this.title +
- (skipMessage ? ` ${skipMessage}` : '') +
- ':' +
- (countLimitMessage ? ` ${countLimitMessage}` : '') +
- '\n'
+ (skipMessage ? ` ${skipMessage}` : "") +
+ ":" +
+ (countLimitMessage ? ` ${countLimitMessage}` : "") +
+ "\n"
);
} else {
return `${this.title}:`;
diff --git a/@commitlint/cz-commitlint/src/SectionBody.test.ts b/@commitlint/cz-commitlint/src/SectionBody.test.ts
index 5846ff6129..0d7e2bf9c9 100644
--- a/@commitlint/cz-commitlint/src/SectionBody.test.ts
+++ b/@commitlint/cz-commitlint/src/SectionBody.test.ts
@@ -1,96 +1,96 @@
-import {describe, test, expect} from 'vitest';
-import {RuleConfigSeverity} from '@commitlint/types';
+import { describe, test, expect } from "vitest";
+import { RuleConfigSeverity } from "@commitlint/types";
-import {combineCommitMessage, getQuestions} from './SectionBody.js';
-import {setRules} from './store/rules.js';
+import { combineCommitMessage, getQuestions } from "./SectionBody.js";
+import { setRules } from "./store/rules.js";
-describe('getQuestions', () => {
- test('should exclude question when body must be empty', () => {
+describe("getQuestions", () => {
+ test("should exclude question when body must be empty", () => {
setRules({
- 'body-empty': [RuleConfigSeverity.Error, 'always'],
+ "body-empty": [RuleConfigSeverity.Error, "always"],
});
const questions = getQuestions();
expect(questions).toHaveLength(0);
});
- test('should only return body question', () => {
+ test("should only return body question", () => {
setRules({});
const questions = getQuestions();
expect(questions).toHaveLength(1);
expect(questions).toEqual([
expect.objectContaining({
- name: 'body',
+ name: "body",
}),
]);
});
});
-describe('combineCommitMessage', () => {
- test('should wrap message to multi lines when max-line-length set', () => {
+describe("combineCommitMessage", () => {
+ test("should wrap message to multi lines when max-line-length set", () => {
setRules({
- 'body-max-line-length': [RuleConfigSeverity.Error, 'always', 10],
+ "body-max-line-length": [RuleConfigSeverity.Error, "always", 10],
});
const commitMessage = combineCommitMessage({
- body: 'This is the body message.',
+ body: "This is the body message.",
});
- expect(commitMessage).toBe('This is\nthe body\nmessage.');
+ expect(commitMessage).toBe("This is\nthe body\nmessage.");
});
- test('should auto apply leading blank', () => {
+ test("should auto apply leading blank", () => {
setRules({
- 'body-leading-blank': [RuleConfigSeverity.Error, 'always'],
+ "body-leading-blank": [RuleConfigSeverity.Error, "always"],
});
const commitMessage = combineCommitMessage({
- body: 'This is the body message.',
+ body: "This is the body message.",
});
- expect(commitMessage).toBe('\nThis is the body message.');
+ expect(commitMessage).toBe("\nThis is the body message.");
});
- test('should return correct string when leading-blank and max-line-length both set', () => {
+ test("should return correct string when leading-blank and max-line-length both set", () => {
setRules({
- 'body-max-line-length': [RuleConfigSeverity.Error, 'always', 10],
- 'body-leading-blank': [RuleConfigSeverity.Error, 'always'],
+ "body-max-line-length": [RuleConfigSeverity.Error, "always", 10],
+ "body-leading-blank": [RuleConfigSeverity.Error, "always"],
});
const commitMessage = combineCommitMessage({
- body: 'This is the body message.',
+ body: "This is the body message.",
});
- expect(commitMessage).toBe('\nThis is\nthe body\nmessage.');
+ expect(commitMessage).toBe("\nThis is\nthe body\nmessage.");
});
- test('should use breakingBody when body message is empty but commit has BREAK CHANGE', () => {
+ test("should use breakingBody when body message is empty but commit has BREAK CHANGE", () => {
setRules({});
const commitMessage = combineCommitMessage({
- breakingBody: 'This is breaking body message.',
+ breakingBody: "This is breaking body message.",
});
- expect(commitMessage).toBe('This is breaking body message.');
+ expect(commitMessage).toBe("This is breaking body message.");
});
- test('should use issueBody when body message is empty but commit has issue note', () => {
+ test("should use issueBody when body message is empty but commit has issue note", () => {
setRules({});
const commitMessage = combineCommitMessage({
- issuesBody: 'This is issue body message.',
+ issuesBody: "This is issue body message.",
});
- expect(commitMessage).toBe('This is issue body message.');
+ expect(commitMessage).toBe("This is issue body message.");
});
- test('should use issueBody when body message is empty string but commit has issue note', () => {
+ test("should use issueBody when body message is empty string but commit has issue note", () => {
setRules({});
const commitMessage = combineCommitMessage({
- body: '',
- issuesBody: 'This is issue body message.',
+ body: "",
+ issuesBody: "This is issue body message.",
});
- expect(commitMessage).toBe('This is issue body message.');
+ expect(commitMessage).toBe("This is issue body message.");
});
- test('should return empty message when body is empty', () => {
+ test("should return empty message when body is empty", () => {
setRules({});
const commitMessage = combineCommitMessage({
- body: '',
+ body: "",
});
- expect(commitMessage).toBe('');
+ expect(commitMessage).toBe("");
});
});
diff --git a/@commitlint/cz-commitlint/src/SectionBody.ts b/@commitlint/cz-commitlint/src/SectionBody.ts
index 68fa78a433..07f1c22cd0 100644
--- a/@commitlint/cz-commitlint/src/SectionBody.ts
+++ b/@commitlint/cz-commitlint/src/SectionBody.ts
@@ -1,26 +1,26 @@
-import {Answers, DistinctQuestion} from 'inquirer';
-import wrap from 'word-wrap';
+import { Answers, DistinctQuestion } from "inquirer";
+import wrap from "word-wrap";
-import Question from './Question.js';
-import getRuleQuestionConfig from './services/getRuleQuestionConfig.js';
-import {getRule} from './store/rules.js';
-import getLeadingBlankFn from './utils/leading-blank-fn.js';
-import {getMaxLength} from './utils/rules.js';
+import Question from "./Question.js";
+import getRuleQuestionConfig from "./services/getRuleQuestionConfig.js";
+import { getRule } from "./store/rules.js";
+import getLeadingBlankFn from "./utils/leading-blank-fn.js";
+import { getMaxLength } from "./utils/rules.js";
export function getQuestions(): Array {
// body
- const questionConfig = getRuleQuestionConfig('body');
+ const questionConfig = getRuleQuestionConfig("body");
if (!questionConfig) return [];
- else return [new Question('body', questionConfig).question];
+ else return [new Question("body", questionConfig).question];
}
export function combineCommitMessage(answers: Answers): string {
- const maxLineLength = getMaxLength(getRule('body', 'max-line-length'));
- const leadingBlankFn = getLeadingBlankFn(getRule('body', 'leading-blank'));
- const {body, breakingBody, issuesBody} = answers;
+ const maxLineLength = getMaxLength(getRule("body", "max-line-length"));
+ const leadingBlankFn = getLeadingBlankFn(getRule("body", "leading-blank"));
+ const { body, breakingBody, issuesBody } = answers;
- const commitBody = body || breakingBody || issuesBody || '';
+ const commitBody = body || breakingBody || issuesBody || "";
if (commitBody) {
return leadingBlankFn(
@@ -28,11 +28,11 @@ export function combineCommitMessage(answers: Answers): string {
? wrap(commitBody, {
width: maxLineLength,
trim: true,
- indent: '',
- })
- : commitBody.trim()
+ indent: "",
+ })
+ : commitBody.trim(),
);
} else {
- return '';
+ return "";
}
}
diff --git a/@commitlint/cz-commitlint/src/SectionFooter.test.ts b/@commitlint/cz-commitlint/src/SectionFooter.test.ts
index 6e1c497958..e16c9fadc8 100644
--- a/@commitlint/cz-commitlint/src/SectionFooter.test.ts
+++ b/@commitlint/cz-commitlint/src/SectionFooter.test.ts
@@ -1,24 +1,24 @@
-import {describe, test, expect, beforeEach} from 'vitest';
-import {RuleConfigSeverity} from '@commitlint/types';
+import { describe, test, expect, beforeEach } from "vitest";
+import { RuleConfigSeverity } from "@commitlint/types";
-import {combineCommitMessage, getQuestions} from './SectionFooter.js';
-import {setPromptConfig} from './store/prompts.js';
-import {setRules} from './store/rules.js';
+import { combineCommitMessage, getQuestions } from "./SectionFooter.js";
+import { setPromptConfig } from "./store/prompts.js";
+import { setRules } from "./store/rules.js";
beforeEach(() => {
setRules({});
setPromptConfig({});
});
-describe('getQuestions', () => {
- test('should only ask questions that listed in prompt question config', () => {
+describe("getQuestions", () => {
+ test("should only ask questions that listed in prompt question config", () => {
setPromptConfig({
questions: {
footer: {
description:
- '