From c7ae04af2cbd13b448e9a62acb16d7adab226cba Mon Sep 17 00:00:00 2001 From: Jim Cummins Date: Sat, 5 Dec 2026 08:01:42 -0600 Subject: [PATCH 1/2] feat: run adapters as programs through the adapter protocol - Adapters can declare "commitizenAdapter": { "protocol": [1], "bin": "..." } in package.json. commitizen runs the bin with the same Node.js and gets the commit message back through CZ_MESSAGE_FILE. Adapters without the field load with require() as before. - configLoader now comes from @commitizen/config, so adapters can read their config without depending on commitizen. require('commitizen').configLoader works as before. - Ctrl-C handling listens on stdin only when it is a terminal, so a protocol adapter gets the input. - README: "Writing an adapter" and "Security: risks and how to reduce them" sections; npx examples use `npx --no -- cz` so npx never downloads an unrelated package named cz. Adds SECURITY.md. - Renovate: no inquirer major updates, since adapters rely on inquirer 8. - Example protocol adapter in examples/protocol-adapter. --- .npmignore | 1 + CONTRIBUTING.md | 9 + README.md | 89 +++++- SECURITY.md | 17 ++ bin/git-cz.js | 15 +- examples/protocol-adapter/README.md | 24 ++ examples/protocol-adapter/bin.js | 38 +++ examples/protocol-adapter/package.json | 13 + package.json | 4 +- pnpm-lock.yaml | 14 +- renovate.json | 12 + src/cli/strategies/git-cz.js | 2 +- src/commitizen/adapter.js | 14 +- src/commitizen/configLoader.js | 14 +- src/commitizen/protocol.js | 168 ++++++++++++ src/common/util.js | 7 +- src/configLoader.js | 12 - src/configLoader/findup.js | 34 --- src/configLoader/getContent.js | 83 ------ src/configLoader/getNormalizedConfig.js | 29 -- src/configLoader/loader.js | 60 ---- test/fixtures/invalid-charset.json | Bin 98 -> 0 bytes test/fixtures/invalid-json-rc | 4 - test/fixtures/invalid-json.json | 4 - .../protocol-adapter-invalid/index.js | 1 + .../protocol-adapter-invalid/package.json | 8 + test/fixtures/protocol-adapter-v99/bin.js | 1 + .../protocol-adapter-v99/package.json | 9 + test/fixtures/protocol-adapter/bin.js | 24 ++ test/fixtures/protocol-adapter/package.json | 9 + test/fixtures/valid-json-rc | 4 - test/fixtures/valid-json-rc-bom | 4 - test/tests/configLoader.js | 152 ---------- test/tests/index.js | 2 +- test/tests/protocol.js | 259 ++++++++++++++++++ test/tests/util.js | 7 +- 36 files changed, 719 insertions(+), 428 deletions(-) create mode 100644 SECURITY.md create mode 100644 examples/protocol-adapter/README.md create mode 100755 examples/protocol-adapter/bin.js create mode 100644 examples/protocol-adapter/package.json create mode 100644 src/commitizen/protocol.js delete mode 100644 src/configLoader.js delete mode 100644 src/configLoader/findup.js delete mode 100644 src/configLoader/getContent.js delete mode 100644 src/configLoader/getNormalizedConfig.js delete mode 100644 src/configLoader/loader.js delete mode 100644 test/fixtures/invalid-charset.json delete mode 100644 test/fixtures/invalid-json-rc delete mode 100644 test/fixtures/invalid-json.json create mode 100644 test/fixtures/protocol-adapter-invalid/index.js create mode 100644 test/fixtures/protocol-adapter-invalid/package.json create mode 100644 test/fixtures/protocol-adapter-v99/bin.js create mode 100644 test/fixtures/protocol-adapter-v99/package.json create mode 100644 test/fixtures/protocol-adapter/bin.js create mode 100644 test/fixtures/protocol-adapter/package.json delete mode 100644 test/fixtures/valid-json-rc delete mode 100644 test/fixtures/valid-json-rc-bom delete mode 100644 test/tests/configLoader.js create mode 100644 test/tests/protocol.js diff --git a/.npmignore b/.npmignore index 5f430ff8..8ca0c606 100644 --- a/.npmignore +++ b/.npmignore @@ -8,3 +8,4 @@ test/tools/trigger-appveyor-tests.sh jsconfig.json travis_after_all.py /.nyc_output +/examples diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ca7d65b7..5ef217cf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -85,3 +85,12 @@ Some tests deliberately contain lines with only whitespace, to check how multiline commit messages behave across operating systems. If your editor strips trailing whitespace on save, turn that off for `test/` before editing those files, or the tests will change in ways you didn't intend. + +### A commitizen config in your home directory can change test results + +Config loading comes from `@commitizen/config`, which falls back to `.czrc`, +`.cz.json` or `package.json` in your home directory when a project has none. +Unlike commitizen's old built-in loader, it doesn't skip that step while tests +run. If you have one of those files in your home directory, the `init` tests +may see an adapter as already configured. Rename the file while you run the +tests. diff --git a/README.md b/README.md index f9ecae31..1b34fd06 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,11 @@ Simply use `git cz` or just `cz` instead of `git commit` when committing. You ca _Alternatively_, if you are using **npm 5.2+** you can [use `npx`](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) instead of installing globally: ```sh -npx cz +npx --no -- cz ``` +`--no` stops npx from downloading anything when commitizen isn't installed in the project. Without it, npx would fetch an unrelated npm package that is also named `cz`. With pnpm, use `pnpm exec cz`. + or as an npm script: ```json @@ -44,7 +46,7 @@ When you're working in a Commitizen-friendly repository, you'll be prompted to f ### If your repo is NOT Commitizen friendly: -If you're **not** working in a Commitizen-friendly repository, then `git cz` will work just the same as `git commit`, but `npx cz` will use the [streamich/git-cz](https://github.com/streamich/git-cz) adapter. To fix this, you need to first [make your repo Commitizen friendly](#making-your-repo-commitizen-friendly) +If you're **not** working in a Commitizen-friendly repository, then `git cz` will work just the same as `git commit`. To fix this, you need to first [make your repo Commitizen friendly](#making-your-repo-commitizen-friendly) ## Making your repo Commitizen friendly @@ -162,7 +164,7 @@ For `husky` users, add the following configuration to the project's `package.jso ```json "husky": { "hooks": { - "prepare-commit-msg": "exec < /dev/tty && npx cz --hook || true" + "prepare-commit-msg": "exec < /dev/tty && npx --no -- cz --hook || true" } } ``` @@ -283,7 +285,84 @@ We know that every project and build process has different requirements, so we'v - [cz-vinyl](https://github.com/Exlint/cz-vinyl) - [commit-jazzer](https://github.com/Zilero232/commit-jazzer) -To create an adapter, just fork one of these great adapters and modify it to suit your needs. We pass you an instance of [Inquirer.js](https://github.com/SBoudrias/Inquirer.js/), but you can capture input using whatever means necessary. Just call the `commit` callback with a string and we'll be happy. Publish it to npm, and you'll be all set! +### Writing an adapter + +An adapter can work in one of two ways. + +**As a program (adapter protocol).** Commitizen runs your adapter as its own +Node.js program, so you can use any prompt library, ES modules and top-level +`await`, and you don't need to depend on `commitizen`. Declare it in the +adapter's `package.json`: + +```json +{ + "main": "./bin.js", + "commitizenAdapter": { + "protocol": [1], + "bin": "./bin.js" + } +} +``` + +Commitizen runs `bin` with the same Node.js and your terminal, and sets: + +| Variable | Meaning | +|---|---| +| `CZ_PROTOCOL` | The protocol version, currently `1`. | +| `CZ_MESSAGE_FILE` | An empty file. Write the commit message to it. | +| `CZ_CONFIG_FILE` | A JSON file with the project's commitizen config (`config.commitizen`, `.czrc` or `.cz.json`). | +| `CZ_GIT_ROOT` | The repository root. | + +Exit with 0 after writing the message and commitizen commits it, including +`--hook` and `--retry` support. Exit with 0 without writing anything to cancel, +or exit non-zero to abort; commitizen exits with the same status. `main` must +point at a file that exists, because commitizen resolves the adapter path the +same way for every adapter. See [examples/protocol-adapter](examples/protocol-adapter) +for a complete adapter with no dependencies. + +**As a module (original API).** Export a `prompter(cz, commit)` function. +Commitizen loads the module with `require()` and passes an instance of +[Inquirer.js](https://github.com/SBoudrias/Inquirer.js/) 8, though you can +capture input using whatever means necessary. Call the `commit` callback with a +string and we'll be happy. Existing adapters keep working this way. + +Publish your adapter to npm, and you'll be all set! + +## Security: risks and how to reduce them + +Commitizen runs code from your project's dependencies, and sometimes from the repository itself. Plain `git commit` doesn't. This section explains the risks and what you can do about each. + +### Risks + +- **An adapter runs with your full permissions.** Commitizen runs the adapter named in `config.commitizen.path`, either inside its own process (a `prompter` adapter) or as a separate program (a protocol adapter). Either way it runs as you. It can read your files, SSH keys and environment variables (including tokens), change your working tree and staged files, and run git. Commitizen can't limit what an adapter does. +- **A repository can bring its own adapter.** `config.commitizen.path` can name a file inside the repository, such as `./tools/adapter.js`. Running `git cz` in a repository you've just cloned can then run that repository's code, just as `npm test` would. +- **An adapter can change what gets committed.** Commitizen commits whatever is staged when the adapter finishes. +- **Some adapters send data elsewhere.** Adapters that integrate with issue trackers or AI services may send your branch name, staged changes or message to that service. +- **Commit messages are kept for `--retry`.** Commitizen saves the last message for each repository in `commitizen.json` in your user cache directory (for example `~/Library/Caches/commitizen` on macOS or `~/.cache/commitizen` on Linux). +- **Installing runs code.** Depending on your package manager, installing an adapter can run install scripts from the adapter and any of its dependencies. A compromised release of any of them runs on your machine before you ever use commitizen. +- **`npx cz` can download an unrelated package.** If commitizen isn't installed in the project, `npx cz` looks for an npm package named `cz`, which isn't commitizen. + +### Reducing the risk + +- **Choose adapters as carefully as any dev dependency you run**, such as a test runner or linter. Prefer widely used, maintained adapters, and read what an adapter sends to other services before giving it tokens. +- **Check a repository before running `git cz` in it.** Look at `config.commitizen` in its `package.json`, `.czrc` or `.cz.json`. A path starting with `./` runs code from the repository. +- **Check your commit** with `git show --stat HEAD` when trying out an adapter you haven't reviewed. +- **Keep secrets out of commit messages.** They end up in git history anyway. +- **Run the commitizen installed in your project**, not one npx downloads: `npx --no -- cz`, `pnpm exec cz` or `node_modules/.bin/cz`. `--no` makes npx fail instead of downloading. +- **Commit your lockfile and install exact versions** (`--save-exact`, as in the examples above), so everyone runs the versions you reviewed. +- **Delay new releases.** Most attacks through npm are found and removed within days. A minimum release age makes your package manager ignore versions newer than that, and avoid install scripts where you can: + +| Package manager | `commitizen init` | Install scripts from dependencies | Minimum release age | +|---|---|---|---| +| npm | default | Run by default. Use `--ignore-scripts` or `ignore-scripts=true` in `.npmrc`. | [`min-release-age`](https://docs.npmjs.com/cli/v11/using-npm/config#min-release-age) (days), npm 11.10+ | +| Yarn 1 | `--yarn` | Run by default. Use `--ignore-scripts`. | Not available | +| Yarn 2+ | `--yarn` | Run by default. Set `enableScripts: false` in `.yarnrc.yml`. | [`npmMinimalAgeGate`](https://yarnpkg.com/configuration/yarnrc#npmMinimalAgeGate), Yarn 4.10+ | +| pnpm | `--pnpm` | Not run: commitizen passes `--ignore-scripts`, and pnpm 10+ runs dependency scripts only for packages you allow. | [`minimumReleaseAge`](https://pnpm.io/settings#minimumreleaseage) (minutes); on by default (1 day) in pnpm 11 | +| Bun | Not supported; install the adapter yourself and set `config.commitizen.path` | Run only for packages in `trustedDependencies` (and Bun's built-in list). | [`minimumReleaseAge`](https://bun.com/docs/pm/cli/install) in `bunfig.toml` (seconds) | + +Commitizen itself passes the commit message to git as a single argument, never through a shell, so a message can't run commands. + +To report a security problem in commitizen itself, use [GitHub's private vulnerability reporting](https://github.com/commitizen/cz-cli/security/advisories/new) rather than a public issue. ## Retrying failed commits @@ -294,7 +373,7 @@ Please note that the retry cache may be cleared when upgrading Commitizen versio It is important to note that if you are running `cz` from an npm script (let's say it is called `commit`) you will need to do one of the following: - Pass `-- --retry` as an argument for your script. i.e: `npm run commit -- --retry` -- Use [npx](https://www.npmjs.com/package/npx) to find and call the `cz` executable directly. i.e: `npx cz --retry` +- Use [npx](https://www.npmjs.com/package/npx) to find and call the `cz` executable directly. i.e: `npx --no -- cz --retry` Note that the last two options **do not** require you to pass `--` before the args but the first **does**. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 00000000..741da11a --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,17 @@ +# Security policy + +## Reporting a vulnerability + +Please report security problems privately through [GitHub's private vulnerability reporting](https://github.com/commitizen/cz-cli/security/advisories/new), not in a public issue or pull request. + +Include what you found, the commitizen version, and steps to reproduce it if you can. We'll reply in the advisory, and credit you when the fix is published unless you'd rather not be named. + +## Supported versions + +Fixes are released for the latest major version only. Please upgrade before reporting a problem in an older version. + +## What counts as a vulnerability + +Commitizen runs the adapter your project configures, with your permissions, so an adapter doing something harmful isn't a vulnerability in commitizen itself. Report those to the adapter's maintainers. See [Security: risks and how to reduce them](README.md#security-risks-and-how-to-reduce-them) for what commitizen does and doesn't protect against. + +Problems in commitizen's own code, such as running code or commands it shouldn't, are in scope. diff --git a/bin/git-cz.js b/bin/git-cz.js index 7f39ddd8..41a166c6 100644 --- a/bin/git-cz.js +++ b/bin/git-cz.js @@ -5,12 +5,15 @@ process.on('uncaughtException', function (err) { process.exit(1); }); -// catch SIGINT signal -process.stdin.on('data', function (key) { - if (key == '\u0003') { - process.exit(130); // 128 + SIGINT - } -}); +// catch SIGINT signal. Only a terminal can send Ctrl-C as data; listening on a +// pipe would read input meant for the adapter. +if (process.stdin.isTTY) { + process.stdin.on('data', function (key) { + if (key == '\u0003') { + process.exit(130); // 128 + SIGINT + } + }); +} require('../dist/cli/git-cz.js').bootstrap({ cliPath: path.join(__dirname, '../') diff --git a/examples/protocol-adapter/README.md b/examples/protocol-adapter/README.md new file mode 100644 index 00000000..e8e2eece --- /dev/null +++ b/examples/protocol-adapter/README.md @@ -0,0 +1,24 @@ +# Example protocol adapter + +A complete commitizen adapter using the adapter protocol, with no dependencies. +It asks for a type and a subject and writes `type: subject` as the commit +message. If the project's commitizen config has a `types` array, it offers +those types instead of the defaults. + +- [package.json](package.json) declares the protocol in `commitizenAdapter`. +- [bin.js](bin.js) is the whole adapter. Under commitizen it writes the message + to `CZ_MESSAGE_FILE`; run on its own (`node bin.js`) it prints it. + +To try it in a repository, point the commitizen config at this directory: + +```json +{ + "config": { + "commitizen": { + "path": "/absolute/path/to/cz-cli/examples/protocol-adapter" + } + } +} +``` + +then stage a change and run `git cz`. diff --git a/examples/protocol-adapter/bin.js b/examples/protocol-adapter/bin.js new file mode 100755 index 00000000..c38528be --- /dev/null +++ b/examples/protocol-adapter/bin.js @@ -0,0 +1,38 @@ +#!/usr/bin/env node +// A complete commitizen adapter using the adapter protocol, with no +// dependencies. commitizen runs this file and commits whatever it writes to +// CZ_MESSAGE_FILE. Run on its own, it prints the message instead. +import fs from 'node:fs'; +import { createInterface } from 'node:readline/promises'; + +const config = process.env.CZ_CONFIG_FILE + ? JSON.parse(fs.readFileSync(process.env.CZ_CONFIG_FILE, 'utf8')) + : {}; +const types = config.types || ['feat', 'fix', 'docs', 'chore']; + +const rl = createInterface({ input: process.stdin, output: process.stdout }); +const lines = rl[Symbol.asyncIterator](); + +async function ask(question) { + process.stdout.write(question); + const { value, done } = await lines.next(); + // Ctrl-C or end of input: exit non-zero, so commitizen commits nothing. + if (done) process.exit(130); + return value.trim(); +} + +const type = await ask(`Type (${types.join(', ')}): `); +const subject = await ask('Subject: '); +rl.close(); + +if (!types.includes(type) || subject === '') { + console.error(`A type from ${types.join(', ')} and a subject are required.`); + process.exit(1); +} + +const message = `${type}: ${subject}\n`; +if (process.env.CZ_MESSAGE_FILE) { + fs.writeFileSync(process.env.CZ_MESSAGE_FILE, message); +} else { + process.stdout.write(message); +} diff --git a/examples/protocol-adapter/package.json b/examples/protocol-adapter/package.json new file mode 100644 index 00000000..ecc3ed23 --- /dev/null +++ b/examples/protocol-adapter/package.json @@ -0,0 +1,13 @@ +{ + "name": "cz-example-protocol-adapter", + "version": "0.0.0", + "private": true, + "description": "Minimal commitizen adapter using the adapter protocol", + "type": "module", + "main": "./bin.js", + "bin": "./bin.js", + "commitizenAdapter": { + "protocol": [1], + "bin": "./bin.js" + } +} diff --git a/package.json b/package.json index 586ae255..ef23075c 100644 --- a/package.json +++ b/package.json @@ -66,13 +66,13 @@ "yarn-cli": "npm:yarn@1.22.22" }, "dependencies": { + "@commitizen/config": "1.0.1", "cachedir": "2.4.0", "cz-conventional-changelog": "3.3.0", "dedent": "1.7.2", "detect-indent": "7.0.2", "inquirer": "8.2.7", - "minimist": "1.2.8", - "strip-json-comments": "5.1.0" + "minimist": "1.2.8" }, "nyc": { "extends": "@istanbuljs/nyc-config-babel", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a2a03eb9..eede68a3 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -185,6 +185,9 @@ importers: .: dependencies: + '@commitizen/config': + specifier: 1.0.1 + version: 1.0.1 cachedir: specifier: 2.4.0 version: 2.4.0 @@ -203,9 +206,6 @@ importers: minimist: specifier: 1.2.8 version: 1.2.8 - strip-json-comments: - specifier: 5.1.0 - version: 5.1.0 devDependencies: '@babel/cli': specifier: 8.1.4 @@ -837,6 +837,10 @@ packages: resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==} engines: {node: '>=0.1.90'} + '@commitizen/config@1.0.1': + resolution: {integrity: sha512-nkXmq73uBNg/PJ7PNVNUZmNIhOWgPYPxxt2QZug57hjGwLU92t169eW87cG5hPtYnJVOhBW4O/aKy05PkCFYHQ==} + engines: {node: ^22.23.5 || ^24.22.3 || >=26.13.1} + '@commitlint/config-validator@21.3.0': resolution: {integrity: sha512-7xpkUIhTOrkZAZ89Qdflb3FuZNFe1wFLF17qqxCUJUtw6X6jLZk1ziIj+fzAeW64KaMW/T5MHHa/KaQCoCghqw==} engines: {node: '>=22.12.0'} @@ -3820,6 +3824,10 @@ snapshots: '@colors/colors@1.5.0': optional: true + '@commitizen/config@1.0.1': + dependencies: + strip-json-comments: 5.1.0 + '@commitlint/config-validator@21.3.0': dependencies: '@commitlint/types': 21.3.0 diff --git a/renovate.json b/renovate.json index ebeed649..926cd26c 100644 --- a/renovate.json +++ b/renovate.json @@ -1,5 +1,17 @@ { "extends": [ "github>commitizen/commitizen-renovate-config" + ], + "packageRules": [ + { + "description": "Adapters receive commitizen's inquirer 8 instance and many rely on its API, so inquirer stays on major version 8.", + "matchPackageNames": [ + "inquirer" + ], + "matchUpdateTypes": [ + "major" + ], + "enabled": false + } ] } diff --git a/src/cli/strategies/git-cz.js b/src/cli/strategies/git-cz.js index abecba8e..b7ddd34f 100644 --- a/src/cli/strategies/git-cz.js +++ b/src/cli/strategies/git-cz.js @@ -39,7 +39,7 @@ function gitCz (rawGitArgs, environment, adapterConfig) { let resolvedAdapterConfigPath = resolveAdapterPath(adapterConfig.path); let resolvedAdapterRootPath = findPackageRoot(resolvedAdapterConfigPath); - let prompter = getPrompter(adapterConfig.path); + let prompter = getPrompter(adapterConfig.path, adapterConfig); let shouldStageAllFiles = rawGitArgs.includes('-a') || rawGitArgs.includes('--all'); isClean(process.cwd(), function (error, stagingIsClean) { diff --git a/src/commitizen/adapter.js b/src/commitizen/adapter.js index 8f2363c0..6cf12c72 100644 --- a/src/commitizen/adapter.js +++ b/src/commitizen/adapter.js @@ -4,6 +4,7 @@ import fs from 'node:fs'; import detectIndent from 'detect-indent'; import { findNearestNodeModules, isFunction } from '../common/util'; +import { createProtocolPrompter, getProtocolDeclaration } from './protocol'; export { addPathToAdapterConfig, @@ -147,12 +148,21 @@ function getInstallStringMappings({ save, dev, saveDev, exact, saveExact, force } /** - * Gets the prompter from an adapter given an adapter path + * Gets the prompter from an adapter given an adapter path. + * + * For an adapter that declares the adapter protocol in its package.json, the + * prompter runs the adapter's program and `config` (the commitizen config) is + * passed to it. Other adapters are loaded with require(), as always. */ -function getPrompter (adapterPath) { +function getPrompter (adapterPath, config) { // Resolve the adapter path let resolvedAdapterPath = resolveAdapterPath(adapterPath); + let declaration = getProtocolDeclaration(resolvedAdapterPath); + if (declaration) { + return createProtocolPrompter(declaration, config, getGitRootPath()); + } + // Load the adapter let adapter = require(resolvedAdapterPath); diff --git a/src/commitizen/configLoader.js b/src/commitizen/configLoader.js index 02355d78..49bc4457 100644 --- a/src/commitizen/configLoader.js +++ b/src/commitizen/configLoader.js @@ -1,10 +1,4 @@ -import { loader } from '../configLoader'; - -export { load }; - -// Configuration sources in priority order. -var configs = ['.czrc', '.cz.json', 'package.json']; - -function load (config, cwd) { - return loader(configs, config, cwd); -} +// The config loader lives in @commitizen/config so adapters can use it without +// depending on commitizen. It stays exported here as +// require('commitizen').configLoader for the adapters that already use it. +export { load } from '@commitizen/config'; diff --git a/src/commitizen/protocol.js b/src/commitizen/protocol.js new file mode 100644 index 00000000..7d198c6b --- /dev/null +++ b/src/commitizen/protocol.js @@ -0,0 +1,168 @@ +import childProcess from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +import { findPackageRoot } from '../common/util'; + +export { + SUPPORTED_PROTOCOLS, + chooseProtocol, + createProtocolPrompter, + getProtocolDeclaration +}; + +/** + * ADAPTER PROTOCOL + * + * A protocol adapter is a program, not a module commitizen loads. Its + * package.json declares: + * + * "commitizenAdapter": { "protocol": [1], "bin": "./bin.js" } + * + * commitizen runs `bin` with the same Node.js, with the terminal inherited, and + * these environment variables: + * + * CZ_PROTOCOL the protocol version commitizen chose + * CZ_MESSAGE_FILE an empty file; the adapter writes the commit message here + * CZ_CONFIG_FILE JSON of the commitizen config (what configLoader.load() returns) + * CZ_GIT_ROOT the repository root + * + * Exit 0 with a message commits it. Exit 0 with an empty message cancels. + * Any other exit aborts with that exit status. + * + * Adapters without the declaration are loaded with require() and called as + * prompter(inquirer, commit), exactly as before. + */ + +// Protocol versions this version of commitizen can run, oldest first. +const SUPPORTED_PROTOCOLS = [1]; + +/** + * Returns the adapter's protocol declaration ({ protocol, bin, root }), or + * undefined for a legacy adapter. `resolvedAdapterPath` is the file that + * resolveAdapterPath() found. + */ +function getProtocolDeclaration (resolvedAdapterPath) { + let root; + let packageJson; + try { + root = findPackageRoot(path.dirname(resolvedAdapterPath)); + packageJson = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); + } catch (error) { + // No readable package.json: a legacy adapter such as a single local file. + return undefined; + } + + let declaration = packageJson.commitizenAdapter; + if (!declaration || typeof declaration !== 'object') { + return undefined; + } + + let name = packageJson.name || root; + if (!Array.isArray(declaration.protocol) || typeof declaration.bin !== 'string') { + throw new Error( + `The adapter ${name} has an invalid "commitizenAdapter" field in its package.json. ` + + 'It needs "protocol" (an array of versions) and "bin" (a path to the adapter program).' + ); + } + + return { name, root, protocol: declaration.protocol, bin: declaration.bin }; +} + +/** + * Picks the highest protocol version both commitizen and the adapter support, + * or throws if there is none. + */ +function chooseProtocol (declaration) { + let shared = SUPPORTED_PROTOCOLS.filter(function (version) { + return declaration.protocol.includes(version); + }); + + if (shared.length === 0) { + throw new Error( + `The adapter ${declaration.name} speaks protocol version(s) ${declaration.protocol.join(', ')}, ` + + `but this version of commitizen supports ${SUPPORTED_PROTOCOLS.join(', ')}. ` + + 'Upgrade whichever of the two is older.' + ); + } + + return shared[shared.length - 1]; +} + +/** + * Returns a prompter(inquirer, commit) that runs a protocol adapter's program. + * Because it has the legacy prompter shape, commit, --hook and --retry work the + * same for both kinds of adapter. The prompter returns a promise that resolves + * once the adapter has finished (commitizen itself ignores it). + */ +function createProtocolPrompter (declaration, config, gitRootPath) { + let version = chooseProtocol(declaration); + let binPath = path.resolve(declaration.root, declaration.bin); + + function prompter (inquirer, commit) { + return new Promise(function (resolve) { + run(commit, resolve); + }); + } + + function run (commit, resolve) { + let workDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'commitizen-')); + let messageFile = path.join(workDirectory, 'COMMIT_MESSAGE'); + let configFile = path.join(workDirectory, 'config.json'); + fs.writeFileSync(messageFile, ''); + fs.writeFileSync(configFile, JSON.stringify(config || {})); + + // The adapter owns the terminal while it runs. Stop this process reading + // stdin (bin/git-cz listens for Ctrl-C) so it doesn't take the input. + process.stdin.pause(); + + let child = childProcess.spawn(process.execPath, [binPath], { + stdio: 'inherit', + env: { + ...process.env, + CZ_PROTOCOL: String(version), + CZ_MESSAGE_FILE: messageFile, + CZ_CONFIG_FILE: configFile, + CZ_GIT_ROOT: gitRootPath + } + }); + + let finished = false; + + function finish (status, message) { + finished = true; + fs.rmSync(workDirectory, { recursive: true, force: true }); + + if (status !== 0) { + // The adapter has already reported its own error. + process.exitCode = status; + } else if (message.trim() === '') { + console.log('No commit message from the adapter; nothing was committed.'); + } else { + commit(message); + } + resolve(); + } + + child.on('error', function (error) { + console.error(`Could not run the adapter ${declaration.name} (${binPath}): ${error.message}`); + finish(1); + }); + + child.on('close', function (code, signal) { + // A child that fails to start emits 'error' and may then emit 'close'. + if (finished) { + return; + } + if (signal || code !== 0) { + finish(code || 1); + } else { + finish(0, fs.readFileSync(messageFile, 'utf8')); + } + }); + } + + prompter.protocol = version; + return prompter; +} diff --git a/src/common/util.js b/src/common/util.js index 617cadc1..3e712c0d 100644 --- a/src/common/util.js +++ b/src/common/util.js @@ -6,8 +6,7 @@ export { findPackageRoot, getParsedJsonFromFile, getParsedPackageJsonFromPath, - isFunction, - isInTest + isFunction } /** @@ -45,10 +44,6 @@ function isFunction (functionToCheck) { } } -function isInTest () { - return typeof global.it === 'function'; -} - /** * Walks up from `start` (inclusive) to the nearest directory containing a * package.json and returns it. Throws if there is none. diff --git a/src/configLoader.js b/src/configLoader.js deleted file mode 100644 index 6582d12f..00000000 --- a/src/configLoader.js +++ /dev/null @@ -1,12 +0,0 @@ -/* istanbul ignore file */ -import findup from './configLoader/findup'; -import getContent from './configLoader/getContent'; -import getNormalizedConfig from './configLoader/getNormalizedConfig'; -import loader from './configLoader/loader'; - -export { - findup, - getContent, - getNormalizedConfig, - loader -}; diff --git a/src/configLoader/findup.js b/src/configLoader/findup.js deleted file mode 100644 index 7b3ecf09..00000000 --- a/src/configLoader/findup.js +++ /dev/null @@ -1,34 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -export default findup; - -// Before, "findup-sync" package was used, -// but it does not provide filter callback -function findup (patterns, options, fn) { - /* jshint -W083 */ - - var lastpath; - var file; - - // Node's fs.globSync has no `nocase` option. Callers pass literal file - // names, so matching follows the file system's own case sensitivity. - options = { cwd: path.resolve(options.cwd) }; - - do { - file = patterns.filter(function (pattern) { - var configPath = fs.globSync(pattern, options)[0]; - - if (configPath) { - return fn(path.join(options.cwd, configPath)); - } - })[0]; - - if (file) { - return path.join(options.cwd, file); - } - - lastpath = options.cwd; - options.cwd = path.resolve(options.cwd, '..'); - } while (options.cwd !== lastpath); -} diff --git a/src/configLoader/getContent.js b/src/configLoader/getContent.js deleted file mode 100644 index 17820dd4..00000000 --- a/src/configLoader/getContent.js +++ /dev/null @@ -1,83 +0,0 @@ -import fs from 'node:fs'; -import path from 'node:path'; - -import stripJSONComments from 'strip-json-comments'; -import { isUtf8 } from 'node:buffer'; - -import { getNormalizedConfig } from '../configLoader'; - -export default getConfigContent; - -/** - * Read the content of a configuration file - * - if not js or json: strip any comments - * - if js or json: require it - * @param {String} configPath - full path to configuration file - * @return {Object} - */ -function readConfigContent (configPath) { - const parsedPath = path.parse(configPath) - const isRcFile = parsedPath.ext !== '.js' && parsedPath.ext !== '.json'; - const jsonString = readConfigFileContent(configPath); - const parse = isRcFile ? - (contents) => JSON.parse(stripJSONComments(contents)) : - (contents) => JSON.parse(contents); - - try { - const parsed = parse(jsonString); - - Object.defineProperty(parsed, 'configPath', { - value: configPath - }); - - return parsed; - } catch (error) { - error.message = [ - `Parsing JSON at ${configPath} for commitizen config failed:`, - error.mesasge - ].join('\n'); - - throw error; - } -} - -/** - * Get content of the configuration file - * @param {String} configPath - partial path to configuration file - * @param {String} directory - directory path which will be joined with config argument - * @return {Object} - */ -function getConfigContent (configPath, baseDirectory) { - if (!configPath) { - return; - } - - const resolvedPath = path.resolve(baseDirectory, configPath); - const configBasename = path.basename(resolvedPath); - - if (!fs.existsSync(resolvedPath)) { - return getNormalizedConfig(resolvedPath); - } - - const content = readConfigContent(resolvedPath); - return getNormalizedConfig(configBasename, content); -}; - -/** - * Read proper content from config file. - * If the chartset of the config file is not utf-8, one error will be thrown. - * @param {String} configPath - * @return {String} - */ -function readConfigFileContent (configPath) { - - let rawBufContent = fs.readFileSync(configPath); - - if (!isUtf8(rawBufContent)) { - throw new Error(`The config file at "${configPath}" contains invalid charset, expect utf8`); - } - - const content = rawBufContent.toString("utf8"); - // Strip a UTF-8 byte order mark, if present. - return content.charCodeAt(0) === 0xFEFF ? content.slice(1) : content; -} diff --git a/src/configLoader/getNormalizedConfig.js b/src/configLoader/getNormalizedConfig.js deleted file mode 100644 index aabb74c5..00000000 --- a/src/configLoader/getNormalizedConfig.js +++ /dev/null @@ -1,29 +0,0 @@ -export default getNormalizedConfig; - -// Given a config and content, plucks the actual -// settings that we're interested in -function getNormalizedConfig (config, content) { - - if (content && (config === 'package.json')) { - - // PACKAGE.JSON - - // Use the npm config key, be good citizens - if (content.config && content.config.commitizen) { - return content.config.commitizen; - } else if (content.czConfig) { // Old method, will be deprecated in 3.0.0 - - // Suppress during test - /* istanbul ignore if */ - if (typeof global.it !== 'function') - { - console.error("\n********\nWARNING: This repository's package.json is using czConfig. czConfig will be deprecated in Commitizen 3. \nPlease use this instead:\n{\n \"config\": {\n \"commitizen\": {\n \"path\": \"./path/to/adapter\"\n }\n }\n}\nFor more information, see: http://commitizen.github.io/cz-cli/\n********\n"); - } - return content.czConfig; - } - } else { - // .cz.json or .czrc - return content; - } - -} diff --git a/src/configLoader/loader.js b/src/configLoader/loader.js deleted file mode 100644 index a7d8d787..00000000 --- a/src/configLoader/loader.js +++ /dev/null @@ -1,60 +0,0 @@ -import path from 'node:path'; - -import { findup, getContent } from '../configLoader'; -import { isInTest } from '../common/util.js'; - -export default loader; - -/** - * Command line config helpers - * Shamelessly ripped from with slight modifications: - * https://github.com/jscs-dev/node-jscs/blob/master/lib/cli-config.js - */ - -/** - * Get content of the configuration file - * @param {String} config - partial path to configuration file - * @param {String} [cwd = process.cwd()] - directory path which will be joined with config argument - * @return {Object|undefined} - */ -function loader (configs, config, cwd) { - var content; - var directory = cwd || process.cwd(); - - // If config option is given, attempt to load it - if (config) { - return getContent(config, directory); - } - - content = getContent( - findup(configs, { nocase: true, cwd: directory }, function (configPath) { - if (path.basename(configPath) === 'package.json') { - // return !!this.getContent(configPath); - } - - return true; - }) - ); - - if (content) { - return content; - } - /* istanbul ignore if */ - if (!isInTest()) { - // Try to load standard configs from home dir - var directoryArr = [process.env.USERPROFILE, process.env.HOMEPATH, process.env.HOME]; - for (var i = 0, dirLen = directoryArr.length; i < dirLen; i++) { - if (!directoryArr[i]) { - continue; - } - - for (var j = 0, len = configs.length; j < len; j++) { - content = getContent(configs[j], directoryArr[i]); - - if (content) { - return content; - } - } - } - } -} diff --git a/test/fixtures/invalid-charset.json b/test/fixtures/invalid-charset.json deleted file mode 100644 index 9c8d9573398c73b575867e84e6e1e30b97dff84e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 98 zcmezWubP32K>-St7>XJ48FCp?8I%~TfMQAvSzwVoAWH{DT?s=5Ln1>7TwNwmodQE9 ULmopJP&^07N&(7oG1M{u02NCQ1^@s6 diff --git a/test/fixtures/invalid-json-rc b/test/fixtures/invalid-json-rc deleted file mode 100644 index 491e8429..00000000 --- a/test/fixtures/invalid-json-rc +++ /dev/null @@ -1,4 +0,0 @@ -{ - "some": "json" - "that": "is invalid" -} diff --git a/test/fixtures/invalid-json.json b/test/fixtures/invalid-json.json deleted file mode 100644 index 491e8429..00000000 --- a/test/fixtures/invalid-json.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "some": "json" - "that": "is invalid" -} diff --git a/test/fixtures/protocol-adapter-invalid/index.js b/test/fixtures/protocol-adapter-invalid/index.js new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/test/fixtures/protocol-adapter-invalid/index.js @@ -0,0 +1 @@ + diff --git a/test/fixtures/protocol-adapter-invalid/package.json b/test/fixtures/protocol-adapter-invalid/package.json new file mode 100644 index 00000000..c3971903 --- /dev/null +++ b/test/fixtures/protocol-adapter-invalid/package.json @@ -0,0 +1,8 @@ +{ + "name": "cz-test-protocol-adapter-invalid", + "version": "1.0.0", + "main": "index.js", + "commitizenAdapter": { + "protocol": 1 + } +} diff --git a/test/fixtures/protocol-adapter-v99/bin.js b/test/fixtures/protocol-adapter-v99/bin.js new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/test/fixtures/protocol-adapter-v99/bin.js @@ -0,0 +1 @@ + diff --git a/test/fixtures/protocol-adapter-v99/package.json b/test/fixtures/protocol-adapter-v99/package.json new file mode 100644 index 00000000..d177a67b --- /dev/null +++ b/test/fixtures/protocol-adapter-v99/package.json @@ -0,0 +1,9 @@ +{ + "name": "cz-test-protocol-adapter-v99", + "version": "1.0.0", + "main": "bin.js", + "commitizenAdapter": { + "protocol": [99], + "bin": "./bin.js" + } +} diff --git a/test/fixtures/protocol-adapter/bin.js b/test/fixtures/protocol-adapter/bin.js new file mode 100644 index 00000000..1a565a87 --- /dev/null +++ b/test/fixtures/protocol-adapter/bin.js @@ -0,0 +1,24 @@ +// Scripted protocol adapter for tests. FAKE_ADAPTER picks what it does. +const fs = require('node:fs'); + +switch (process.env.FAKE_ADAPTER) { + case 'echo': + // Commit a message that reports what commitizen passed in. + fs.writeFileSync( + process.env.CZ_MESSAGE_FILE, + JSON.stringify({ + protocol: process.env.CZ_PROTOCOL, + gitRoot: process.env.CZ_GIT_ROOT, + config: JSON.parse(fs.readFileSync(process.env.CZ_CONFIG_FILE, 'utf8')), + messageFile: process.env.CZ_MESSAGE_FILE + }) + ); + break; + case 'cancel': + break; + case 'fail': + process.exit(3); + break; + default: + fs.writeFileSync(process.env.CZ_MESSAGE_FILE, 'feat: from a protocol adapter\n'); +} diff --git a/test/fixtures/protocol-adapter/package.json b/test/fixtures/protocol-adapter/package.json new file mode 100644 index 00000000..0426e132 --- /dev/null +++ b/test/fixtures/protocol-adapter/package.json @@ -0,0 +1,9 @@ +{ + "name": "cz-test-protocol-adapter", + "version": "1.0.0", + "main": "bin.js", + "commitizenAdapter": { + "protocol": [1], + "bin": "./bin.js" + } +} diff --git a/test/fixtures/valid-json-rc b/test/fixtures/valid-json-rc deleted file mode 100644 index aa1bfa87..00000000 --- a/test/fixtures/valid-json-rc +++ /dev/null @@ -1,4 +0,0 @@ -{ - "some": "json" - // with comments -} diff --git a/test/fixtures/valid-json-rc-bom b/test/fixtures/valid-json-rc-bom deleted file mode 100644 index 355c6146..00000000 --- a/test/fixtures/valid-json-rc-bom +++ /dev/null @@ -1,4 +0,0 @@ -{ - "some": "json" - // with a UTF-8 byte order mark and comments -} diff --git a/test/tests/configLoader.js b/test/tests/configLoader.js deleted file mode 100644 index 34a23330..00000000 --- a/test/tests/configLoader.js +++ /dev/null @@ -1,152 +0,0 @@ -import fs from 'node:fs'; -import os from 'node:os'; -import path from 'node:path'; -import { expect } from 'chai'; -import { randomUUID as uuidv4 } from 'node:crypto'; - -import { findup, getContent, getNormalizedConfig, loader } from '../../src/configLoader'; - -const fixturesPath = path.resolve(__dirname, '..', 'fixtures'); - -describe('configLoader', function () { - - it('errors appropriately for invalid json', function () { - expect(() => getContent('invalid-json.json', fixturesPath)) - .to.throw(/parsing json at/i); - expect(() => getContent('invalid-json-rc', fixturesPath)) - .to.throw(/parsing json at/i); - expect(() => getContent('invalid-charset.json', fixturesPath)) - .to.throw(/contains invalid charset/i); - }); - - it('parses json files with comments', function () { - expect(getContent('valid-json-rc', fixturesPath)) - .to.deep.equal({ 'some': 'json' }); - }); - - it('parses rc files that start with a UTF-8 byte order mark', function () { - expect(getContent('valid-json-rc-bom', fixturesPath)) - .to.deep.equal({ 'some': 'json' }); - }); - - it('returns undefined when no config path is given', function () { - expect(getContent(undefined, fixturesPath)).to.equal(undefined); - expect(getContent('', fixturesPath)).to.equal(undefined); - }); - - it('returns undefined when the config file does not exist', function () { - expect(getContent(`${uuidv4()}.json`, fixturesPath)).to.equal(undefined); - }); - - it('normalizes package.json configs', function () { - - let config = 'package.json'; - - let npmStyleConfig = { - config: { - commitizen: 'myNpmConfig' - } - }; - - let oldStyleConfig = { - czConfig: 'myOldConfig' - }; - - expect(getNormalizedConfig(config, npmStyleConfig)).to.equal('myNpmConfig'); - expect(getNormalizedConfig(config, oldStyleConfig)).to.equal('myOldConfig'); - - }); - - it('returns undefined for a package.json with neither config.commitizen nor czConfig', function () { - expect(getNormalizedConfig('package.json', { name: 'demo' })).to.equal(undefined); - }); - - it('returns undefined for a package.json with no content', function () { - expect(getNormalizedConfig('package.json')).to.equal(undefined); - }); - - it('normalizes .cz.json configs', function () { - - let config = '.cz.json'; - - let czJsonStyleConfig = { - path: './path/to/adapter' - }; - - expect(getNormalizedConfig(config, czJsonStyleConfig)).to.deep.equal({ path: './path/to/adapter' }); - - }); - - it('normalizes .czrc configs', function () { - - let config = '.czrc'; - - let czrcStyleConfig = { - path: './path/to/adapter' - }; - - expect(getNormalizedConfig(config, czrcStyleConfig)).to.deep.equal({ path: './path/to/adapter' }); - - }); - - describe('loader', function () { - it('loads an explicitly provided config path directly', function () { - expect(loader(['ignored'], 'valid-json-rc', fixturesPath)).to.deep.equal({ some: 'json' }); - }); - - it('discovers a config file in the given directory', function () { - expect(loader(['valid-json-rc'], undefined, fixturesPath)).to.deep.equal({ some: 'json' }); - }); - - it('returns undefined when nothing is found (and not falling through to $HOME during tests)', function () { - const emptyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cz-loader-')); - try { - expect(loader(['.czrc', '.cz.json'], undefined, emptyDir)).to.equal(undefined); - } finally { - fs.rmSync(emptyDir, { recursive: true, force: true }); - } - }); - - it('defaults the search directory to process.cwd()', function () { - // The test process runs from the repo root, which is itself - // commitizen-friendly, so package.json discovery should succeed. - expect(loader(['package.json'], undefined, undefined)).to.have.property('path'); - }); - }); - - describe('findup', function () { - let base; - - beforeEach(function () { - base = fs.mkdtempSync(path.join(os.tmpdir(), 'cz-findup-')); - fs.mkdirSync(path.join(base, 'a', 'b', 'c'), { recursive: true }); - }); - - afterEach(function () { - fs.rmSync(base, { recursive: true, force: true }); - }); - - it('walks up parent directories to find a matching file', function () { - const marker = path.join(base, 'a', '.czmarker'); - fs.writeFileSync(marker, '{}'); - - const found = findup(['.czmarker'], { cwd: path.join(base, 'a', 'b', 'c') }, () => true); - - expect(found).to.equal(marker); - }); - - it('returns undefined when the file is never found on the way up to the root', function () { - const found = findup(['does-not-exist-' + uuidv4()], { cwd: path.join(base, 'a', 'b', 'c') }, () => true); - expect(found).to.equal(undefined); - }); - - it('skips matches rejected by the filter callback', function () { - fs.writeFileSync(path.join(base, 'a', 'b', 'c', '.czmarker'), '{}'); - - const found = findup(['.czmarker'], { cwd: path.join(base, 'a', 'b', 'c') }, () => false); - - expect(found).to.equal(undefined); - }); - }); - -}); diff --git a/test/tests/index.js b/test/tests/index.js index 648f1ab9..3bc8d8b8 100644 --- a/test/tests/index.js +++ b/test/tests/index.js @@ -4,10 +4,10 @@ import './cache'; import './cli'; import './commit'; import './commitizen-commit'; -import './configLoader'; import './git'; import './init'; import './init-unit'; import './parsers'; +import './protocol'; import './staging'; import './util'; diff --git a/test/tests/protocol.js b/test/tests/protocol.js new file mode 100644 index 00000000..e002b1fb --- /dev/null +++ b/test/tests/protocol.js @@ -0,0 +1,259 @@ +import childProcess from 'node:child_process'; +import { EventEmitter } from 'node:events'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { expect } from 'chai'; +import sinon from 'sinon'; + +import * as adapter from '../../src/commitizen/adapter'; +import commit from '../../src/commitizen/commit'; +import { + SUPPORTED_PROTOCOLS, + chooseProtocol, + createProtocolPrompter, + getProtocolDeclaration +} from '../../src/commitizen/protocol'; + +const fixtures = path.resolve(__dirname, '..', 'fixtures'); +const protocolAdapter = path.join(fixtures, 'protocol-adapter'); + +// Runs the fixture adapter in the given FAKE_ADAPTER mode. Resolves with the +// messages passed to commit() and the exit code commitizen would use. +function runFixture (mode, config) { + const committed = []; + const previousMode = process.env.FAKE_ADAPTER; + process.env.FAKE_ADAPTER = mode; + const prompter = createProtocolPrompter( + getProtocolDeclaration(path.join(protocolAdapter, 'bin.js')), + config, + '/the/git/root' + ); + return prompter(undefined, (message) => committed.push(message)).then(() => { + const exitCode = process.exitCode; + process.exitCode = undefined; + if (previousMode === undefined) { + delete process.env.FAKE_ADAPTER; + } else { + process.env.FAKE_ADAPTER = previousMode; + } + return { committed, exitCode }; + }); +} + +describe('adapter protocol', function () { + + describe('getProtocolDeclaration', function () { + it('reads the declaration from the adapter package.json', function () { + expect(getProtocolDeclaration(path.join(protocolAdapter, 'bin.js'))).to.deep.equal({ + name: 'cz-test-protocol-adapter', + root: protocolAdapter, + protocol: [1], + bin: './bin.js' + }); + }); + + it('returns undefined for a legacy adapter', function () { + const legacy = require.resolve('cz-conventional-changelog'); + expect(getProtocolDeclaration(legacy)).to.equal(undefined); + }); + + it('returns undefined when there is no package.json', function () { + const existsSync = sinon.stub(fs, 'existsSync').returns(false); + try { + expect(getProtocolDeclaration(path.join(protocolAdapter, 'bin.js'))).to.equal(undefined); + } finally { + existsSync.restore(); + } + }); + + it('ignores a commitizenAdapter field that is not an object', function () { + const readFileSync = sinon.stub(fs, 'readFileSync') + .returns(JSON.stringify({ name: 'x', commitizenAdapter: true })); + try { + expect(getProtocolDeclaration(path.join(protocolAdapter, 'bin.js'))).to.equal(undefined); + } finally { + readFileSync.restore(); + } + }); + + it('throws for an invalid declaration', function () { + expect(() => getProtocolDeclaration(path.join(fixtures, 'protocol-adapter-invalid', 'index.js'))) + .to.throw(/cz-test-protocol-adapter-invalid has an invalid "commitizenAdapter" field/); + }); + + it('names the adapter by its directory when package.json has no name', function () { + const readFileSync = sinon.stub(fs, 'readFileSync') + .returns(JSON.stringify({ commitizenAdapter: { protocol: 1 } })); + try { + expect(() => getProtocolDeclaration(path.join(protocolAdapter, 'bin.js'))) + .to.throw(`The adapter ${protocolAdapter} has an invalid`); + } finally { + readFileSync.restore(); + } + }); + }); + + describe('chooseProtocol', function () { + it('supports protocol 1', function () { + expect(SUPPORTED_PROTOCOLS).to.deep.equal([1]); + }); + + it('picks the highest version both sides support', function () { + expect(chooseProtocol({ name: 'a', protocol: [1, 2] })).to.equal(1); + }); + + it('throws when there is no shared version', function () { + expect(() => chooseProtocol({ name: 'cz-future', protocol: [2, 3] })) + .to.throw('The adapter cz-future speaks protocol version(s) 2, 3, but this version of commitizen supports 1.'); + }); + }); + + describe('createProtocolPrompter', function () { + this.timeout(10000); + + it('commits the message the adapter writes', function () { + return runFixture('commit').then(({ committed, exitCode }) => { + expect(committed).to.deep.equal(['feat: from a protocol adapter\n']); + expect(exitCode).to.equal(undefined); + }); + }); + + it('passes the protocol version, git root and config, and cleans up', function () { + const config = { path: './adapter', maxHeaderWidth: 72 }; + return runFixture('echo', config).then(({ committed }) => { + const received = JSON.parse(committed[0]); + expect(received).to.include({ protocol: '1', gitRoot: '/the/git/root' }); + expect(received.config).to.deep.equal(config); + expect(fs.existsSync(path.dirname(received.messageFile))).to.equal(false); + }); + }); + + it('passes an empty config when there is none', function () { + return runFixture('echo').then(({ committed }) => { + expect(JSON.parse(committed[0]).config).to.deep.equal({}); + }); + }); + + it('commits nothing when the adapter writes no message', function () { + const log = sinon.stub(console, 'log'); + return runFixture('cancel').then(({ committed, exitCode }) => { + log.restore(); + expect(committed).to.deep.equal([]); + expect(exitCode).to.equal(undefined); + expect(log.calledWithMatch(/nothing was committed/)).to.equal(true); + }, (error) => { + log.restore(); + throw error; + }); + }); + + it('exits with the adapter exit status when it fails', function () { + return runFixture('fail').then(({ committed, exitCode }) => { + expect(committed).to.deep.equal([]); + expect(exitCode).to.equal(3); + }); + }); + + it('exits with 1 when the adapter is killed by a signal', function () { + // A fake child: real signal delivery differs on Windows and under nyc, + // which wraps child Node.js processes. + const child = new EventEmitter(); + const spawn = sinon.stub(childProcess, 'spawn').returns(child); + const committed = []; + const prompter = createProtocolPrompter( + getProtocolDeclaration(path.join(protocolAdapter, 'bin.js')), + {}, + '/the/git/root' + ); + const done = prompter(undefined, (message) => committed.push(message)); + spawn.restore(); + child.emit('close', null, 'SIGTERM'); + return done.then(() => { + const exitCode = process.exitCode; + process.exitCode = undefined; + expect(exitCode).to.equal(1); + expect(committed).to.deep.equal([]); + }); + }); + + it('reports an adapter that cannot be started, once', function () { + const child = new EventEmitter(); + const spawn = sinon.stub(childProcess, 'spawn').returns(child); + const error = sinon.stub(console, 'error'); + const committed = []; + const prompter = createProtocolPrompter( + { name: 'cz-broken', root: '/nowhere', protocol: [1], bin: './bin.js' }, + {}, + '/the/git/root' + ); + const done = prompter(undefined, (message) => committed.push(message)); + child.emit('error', new Error('spawn failed')); + child.emit('close', 0, null); + return done.then(() => { + spawn.restore(); + error.restore(); + const exitCode = process.exitCode; + process.exitCode = undefined; + expect(exitCode).to.equal(1); + expect(committed).to.deep.equal([]); + expect(error.calledOnceWithMatch(/Could not run the adapter cz-broken/)).to.equal(true); + }, (failure) => { + spawn.restore(); + error.restore(); + throw failure; + }); + }); + + it('throws for an adapter whose protocol commitizen does not support', function () { + const declaration = getProtocolDeclaration(path.join(fixtures, 'protocol-adapter-v99', 'bin.js')); + expect(() => createProtocolPrompter(declaration, {}, '/')).to.throw(/speaks protocol version\(s\) 99/); + }); + }); + + describe('getPrompter', function () { + it('returns a protocol prompter for a protocol adapter', function () { + const prompter = adapter.getPrompter(protocolAdapter, {}); + expect(prompter).to.be.a('function'); + expect(prompter.protocol).to.equal(1); + }); + + it('still loads legacy adapters with require()', function () { + const prompter = adapter.getPrompter('cz-conventional-changelog'); + expect(prompter).to.be.a('function'); + expect(prompter.protocol).to.equal(undefined); + }); + }); + + describe('committing through commitizen', function () { + this.timeout(20000); + let repoPath; + + beforeEach(function () { + repoPath = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cz-protocol-'))); + childProcess.execSync('git init --quiet', { cwd: repoPath }); + fs.writeFileSync(path.join(repoPath, 'file.txt'), 'hello'); + childProcess.execSync('git add file.txt', { cwd: repoPath }); + }); + + afterEach(function () { + fs.rmSync(repoPath, { recursive: true, force: true }); + }); + + it('makes a git commit with the adapter message', function (done) { + const prompter = createProtocolPrompter( + getProtocolDeclaration(path.join(protocolAdapter, 'bin.js')), + {}, + repoPath + ); + commit(undefined, repoPath, prompter, { disableAppendPaths: true, quiet: true, emitData: false }, function (error) { + if (error) { + return done(error); + } + const message = childProcess.execSync('git log -1 --format=%B', { cwd: repoPath, encoding: 'utf8' }); + expect(message.trim()).to.equal('feat: from a protocol adapter'); + done(); + }); + }); + }); +}); diff --git a/test/tests/util.js b/test/tests/util.js index 66afc0c5..03be90eb 100644 --- a/test/tests/util.js +++ b/test/tests/util.js @@ -10,8 +10,7 @@ import { findPackageRoot, getParsedJsonFromFile, getParsedPackageJsonFromPath, - isFunction, - isInTest + isFunction } from '../../src/common/util'; describe('common util', function () { @@ -79,10 +78,6 @@ describe('common util', function () { }); }); - it('isInTest is true while the mocha "it" global is present', function () { - expect(isInTest()).to.equal(true); - }); - describe('directory finders', function () { let root; From 9b40f4ced9850622941ee8fed1b928d907f09c5f Mon Sep 17 00:00:00 2001 From: Jim Cummins Date: Sat, 5 Dec 2026 09:38:43 -0600 Subject: [PATCH 2/2] test: use a local legacy adapter so commitizen 4.3.2's baked-in coverage can't skew CI --- test/fixtures/legacy-adapter/index.js | 6 ++++++ test/fixtures/legacy-adapter/package.json | 6 ++++++ test/tests/protocol.js | 13 ++++++++++--- 3 files changed, 22 insertions(+), 3 deletions(-) create mode 100644 test/fixtures/legacy-adapter/index.js create mode 100644 test/fixtures/legacy-adapter/package.json diff --git a/test/fixtures/legacy-adapter/index.js b/test/fixtures/legacy-adapter/index.js new file mode 100644 index 00000000..61f4f3ca --- /dev/null +++ b/test/fixtures/legacy-adapter/index.js @@ -0,0 +1,6 @@ +// A legacy adapter: a module commitizen loads with require(). +module.exports = { + prompter: function (cz, commit) { + commit('feat: from a legacy adapter'); + } +}; diff --git a/test/fixtures/legacy-adapter/package.json b/test/fixtures/legacy-adapter/package.json new file mode 100644 index 00000000..535daed0 --- /dev/null +++ b/test/fixtures/legacy-adapter/package.json @@ -0,0 +1,6 @@ +{ + "name": "cz-test-legacy-adapter", + "version": "1.0.0", + "private": true, + "main": "index.js" +} diff --git a/test/tests/protocol.js b/test/tests/protocol.js index e002b1fb..177c4002 100644 --- a/test/tests/protocol.js +++ b/test/tests/protocol.js @@ -17,6 +17,11 @@ import { const fixtures = path.resolve(__dirname, '..', 'fixtures'); const protocolAdapter = path.join(fixtures, 'protocol-adapter'); +// A local legacy adapter. Loading a real one (cz-conventional-changelog 3.3.0) +// would also load commitizen 4.3.2, whose published dist contains coverage +// counters for /home/runner/work/cz-cli/cz-cli/src, which on GitHub's Ubuntu +// runners is this checkout, and would corrupt the coverage report. +const legacyAdapter = path.join(fixtures, 'legacy-adapter'); // Runs the fixture adapter in the given FAKE_ADAPTER mode. Resolves with the // messages passed to commit() and the exit code commitizen would use. @@ -54,8 +59,7 @@ describe('adapter protocol', function () { }); it('returns undefined for a legacy adapter', function () { - const legacy = require.resolve('cz-conventional-changelog'); - expect(getProtocolDeclaration(legacy)).to.equal(undefined); + expect(getProtocolDeclaration(path.join(legacyAdapter, 'index.js'))).to.equal(undefined); }); it('returns undefined when there is no package.json', function () { @@ -219,9 +223,12 @@ describe('adapter protocol', function () { }); it('still loads legacy adapters with require()', function () { - const prompter = adapter.getPrompter('cz-conventional-changelog'); + const prompter = adapter.getPrompter(legacyAdapter); expect(prompter).to.be.a('function'); expect(prompter.protocol).to.equal(undefined); + const committed = []; + prompter(undefined, (message) => committed.push(message)); + expect(committed).to.deep.equal(['feat: from a legacy adapter']); }); });