Repository: commitizen/cz-cli
Branch: master
Commit: 3c08866d9a87
Files: 70
Total size: 108.7 KB
Directory structure:
gitextract_tp2funuz/
├── .editorconfig
├── .eslintrc
├── .github/
│ └── workflows/
│ └── release.yml
├── .gitignore
├── .npmignore
├── .npmrc
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── azure-pipelines.yml
├── babel.config.js
├── bin/
│ ├── commitizen
│ ├── commitizen.cmd
│ ├── commitizen.js
│ ├── git-cz
│ ├── git-cz.cmd
│ └── git-cz.js
├── jobs/
│ └── build.yml
├── jsconfig.json
├── logo/
│ └── generate.sh
├── package.json
├── renovate.json
├── src/
│ ├── cli/
│ │ ├── commitizen.js
│ │ ├── git-cz.js
│ │ ├── parsers/
│ │ │ ├── commitizen.js
│ │ │ └── git-cz.js
│ │ ├── parsers.js
│ │ ├── strategies/
│ │ │ ├── git-cz.js
│ │ │ └── git.js
│ │ └── strategies.js
│ ├── commitizen/
│ │ ├── adapter.js
│ │ ├── cache.js
│ │ ├── commit.js
│ │ ├── configLoader.js
│ │ ├── init.js
│ │ └── staging.js
│ ├── commitizen.js
│ ├── common/
│ │ └── util.js
│ ├── configLoader/
│ │ ├── findup.js
│ │ ├── getContent.js
│ │ ├── getNormalizedConfig.js
│ │ └── loader.js
│ ├── configLoader.js
│ ├── git/
│ │ ├── add.js
│ │ ├── commit.js
│ │ ├── init.js
│ │ ├── log.js
│ │ └── whatChanged.js
│ ├── git.js
│ ├── index.js
│ └── npm.js
└── test/
├── config.js
├── fixtures/
│ ├── invalid-charset.json
│ ├── invalid-json-rc
│ ├── invalid-json.json
│ └── valid-json-rc
├── mochareporters.json
├── tester.js
├── tests/
│ ├── adapter.js
│ ├── cli.js
│ ├── commit.js
│ ├── configLoader.js
│ ├── index.js
│ ├── init.js
│ ├── parsers.js
│ ├── staging.js
│ └── util.js
└── tools/
├── clean.js
├── files.js
└── repo.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
insert_final_newline = true
charset = utf-8
trim_trailing_whitespace = true
end_of_line = lf
[*.{js,json}]
indent_style = space
indent_size = 2
================================================
FILE: .eslintrc
================================================
{
"extends": "standard",
"rules": {
"brace-style": 0,
"comma-dangle": 0,
"indent": 0,
"operator-linebreak": 0,
"padded-blocks": 0,
"quotes": 0,
"semi": 0
}
}
================================================
FILE: .github/workflows/release.yml
================================================
name: Release
"on":
push:
branches:
- master
jobs:
release:
name: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
cache: npm
node-version: lts/*
- run: npm clean-install
- run: npx semantic-release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }}
================================================
FILE: .gitignore
================================================
node_modules/
.tmp/
coverage/
artifacts/
/dist
npm-debug.log
.nyc_output
test/tools/trigger-appveyor-tests.sh
logo/*.png
================================================
FILE: .npmignore
================================================
/meta
/src
/test
test/tools/trigger-appveyor-tests.sh
/coverage
/.travis.yml
/appveyor.yml
jsconfig.json
travis_after_all.py
/.nyc_output
================================================
FILE: .npmrc
================================================
save-exact = true
================================================
FILE: CONTRIBUTING.md
================================================
# Contribution guide
## Developing commitizen
You consider contributing changes to commitizen – thank you!
Please consider these guidelines when filing a pull request:
* Commits follow the [Angular commit convention](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines)
* JavaScript is written using ES2015 features
* 2 spaces indentation
* Features and bug fixes should be covered by test cases
## Creating releases
commitizen uses [semantic-release](https://github.com/semantic-release/semantic-release)
to release new versions automatically.
* Commits of type `fix` will trigger bugfix releases, think `0.0.1`
* Commits of type `feat` will trigger feature releases, think `0.1.0`
* Commits with `BREAKING CHANGE` in body or footer will trigger breaking releases, think `1.0.0`
All other commit types will trigger no new release.
## Gotchas
### Atom removes lines with just spaces, breaking tests
When using Atom, if you edit some of our tests, atom will remove the whitespace on some lines. Unfortunately we wanted this whitespace to
able to test multiline commits and their difference across operating
systems. Atom has decided to keep the stripping of whitespace as a
default. Although we understand this decision, it has the unfortunate
side effect of editing parts of the file that you might not have
intended. We think this should be left up to more configurable tools
like eslint.
For now, in order to work around this, you can take the steps outlined
[here](https://github.com/atom/whitespace/issues/10#issuecomment-85183781) to temporarily disable automatic whitespace removal in Atom.
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
## Commitizen for contributors
When you commit with Commitizen, you'll be prompted to fill out any required commit fields at commit time. No more waiting until later for a git commit hook to run and reject your commit (though [that](https://github.com/kentcdodds/validate-commit-msg) can still be helpful). No more digging through [CONTRIBUTING.md](CONTRIBUTING.md) to find what the preferred format is. Get instant feedback on your commit message formatting and be prompted for required fields.
[](#backers) [](#sponsors) [](https://travis-ci.org/commitizen/cz-cli) [](https://dev.azure.com/commitizen/cz-cli/_build/latest?definitionId=2)
[](https://codecov.io/github/commitizen/cz-cli?branch=master) [](https://www.npmjs.com/package/commitizen) [](https://www.npmjs.com/package/commitizen) [](https://github.com/semantic-release/semantic-release) [](https://stackoverflow.com/tags/commitizen)
## Installing the command line tool
Commitizen is currently tested against Node.js 12, 14, & 16, although it may work in
older versions of Node.js. You should also have npm 6 or greater.
Installation is as simple as running the following command (if you see `EACCES` error, reading [fixing npm permissions](https://docs.npmjs.com/getting-started/fixing-npm-permissions) may help):
```sh
npm install -g commitizen
```
## Using the command line tool
### If your repo is [Commitizen friendly](#making-your-repo-commitizen-friendly):
Simply use `git cz` or just `cz` instead of `git commit` when committing. You can also use `git-cz`, which is an alias for `cz`.
_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
```
or as an npm script:
```json
...
"scripts": {
"commit": "cz"
}
```
When you're working in a Commitizen-friendly repository, you'll be prompted to fill in any required fields, and your commit messages will be formatted according to the standards defined by project maintainers.
[](https://github.com/commitizen/cz-cli/raw/master/meta/screenshots/add-commit.png)
### 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)
## Making your repo Commitizen friendly
For this example, we'll be setting up our repo to use [AngularJS's commit message convention](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines), also known as [conventional-changelog](https://github.com/ajoslin/conventional-changelog).
First, install the Commitizen CLI tools:
```sh
npm install commitizen -g
```
Next, initialize your project to use the cz-conventional-changelog adapter by typing:
```sh
# npm
commitizen init cz-conventional-changelog --save-dev --save-exact
# yarn
commitizen init cz-conventional-changelog --yarn --dev --exact
# pnpm
commitizen init cz-conventional-changelog --pnpm --save-dev --save-exact
```
Note that if you want to force install over the top of an old adapter, you can apply the `--force` argument. For more information on this, just run `commitizen help`.
The above command does three things for you:
1. Installs the cz-conventional-changelog adapter npm module
2. Saves it to `package.json`'s `dependencies` or `devDependencies`
3. Adds the `config.commitizen` key to the root of your `package.json` file as shown here:
```json
...
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
}
```
Alternatively, Commitizen configs may be added to a `.czrc` file:
```json
{
"path": "cz-conventional-changelog"
}
```
This just tells Commitizen which adapter we actually want our contributors to use when they try to commit to this repo.
`commitizen.path` is resolved via [require.resolve](https://nodejs.org/api/globals.html#globals_require_resolve) and supports:
- npm modules
- directories relative to `process.cwd()` containing an `index.js` file
- file base names relative to `process.cwd()` with `.js` extension
- full relative file names
- absolute paths
Please note that in the previous version of Commitizen we used czConfig. **czConfig has been deprecated**, and you should migrate to the new format before Commitizen 3.0.0.
### Optional: Install and run Commitizen locally
Installing and running Commitizen locally allows you to make sure that developers are running the exact same version of Commitizen on every machine.
Install Commitizen with `npm install --save-dev commitizen`.
On **npm 5.2+** you can [use `npx`](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) to initialize the conventional changelog adapter:
```
npx commitizen init cz-conventional-changelog --save-dev --save-exact
```
For **previous versions of npm (< 5.2)** you can execute `./node_modules/.bin/commitizen` or `./node_modules/.bin/cz` in order to actually use the commands.
You can then initialize the conventional changelog adapter using: `./node_modules/.bin/commitizen init cz-conventional-changelog --save-dev --save-exact`
And you can then add some nice npm scripts in your `package.json` file pointing to the local version of Commitizen:
```json
...
"scripts": {
"commit": "cz"
}
```
This will be more convenient for your users because then if they want to do a commit, all they need to do is run `npm run commit` and they will get the prompts needed to start a commit!
> **NOTE:** If you are using `precommit` hooks thanks to something like [`husky`](https://www.npmjs.com/package/husky), you will need to name your script something other than `"commit"`
> (e.g. `"cm": "cz"`). The reason is because npm scripts has a "feature" where it automatically runs scripts with the name _prexxx_ where _xxx_ is the name of another script. In essence,
> npm and husky will run `"precommit"` scripts twice if you name the script `"commit"`, and the workaround is to prevent the npm-triggered _precommit_ script.
#### Optional: Running Commitizen on `git commit`
This example shows how to incorporate Commitizen into the existing `git commit` workflow by using git hooks and the `--hook` command-line option. This is useful for project maintainers
who wish to ensure the proper commit format is enforced on contributions from those unfamiliar with Commitizen.
Once either of these methods is implemented, users running `git commit` will be presented with an interactive Commitizen session that helps them write useful commit messages.
> **NOTE:** This example assumes that the project has been set up to [use Commitizen locally](https://github.com/commitizen/cz-cli#optional-install-and-run-commitizen-locally).
##### Traditional git hooks
Update `.git/hooks/prepare-commit-msg` with the following code:
```sh
#!/bin/bash
exec < /dev/tty && node_modules/.bin/cz --hook || true
```
##### Husky
For `husky` users, add the following configuration to the project's `package.json` file:
```json
"husky": {
"hooks": {
"prepare-commit-msg": "exec < /dev/tty && npx cz --hook || true"
}
}
```
> **Why `exec < /dev/tty`?** By default, git hooks are not interactive. This command allows the user to use their terminal to interact with Commitizen during the hook.
#### Congratulations! Your repo is Commitizen friendly. Time to flaunt it!
Add the "Commitizen friendly" badge to your README using the following markdown:
```
[](http://commitizen.github.io/cz-cli/)
```
Your badge will look like this:
[](http://commitizen.github.io/cz-cli/)
It may also make sense to change your `README.md` or `CONTRIBUTING.md` files to include or link to the Commitizen project so that your new contributors may learn more about installing and using Commitizen.
## Conventional commit messages as a global utility
Install `commitizen` globally, if you have not already.
```sh
npm install -g commitizen
```
Install your preferred `commitizen` adapter globally (for example [`cz-conventional-changelog`](https://www.npmjs.com/package/cz-conventional-changelog)).
```sh
npm install -g cz-conventional-changelog
```
Create a `.czrc` file in your `home` directory, with `path` referring to the preferred, globally-installed, `commitizen` adapter
```sh
echo '{ "path": "cz-conventional-changelog" }' > ~/.czrc
```
You are all set! Now `cd` into any `git` repository and use `git cz` instead of `git commit`, and you will find the `commitizen` prompt.
Pro tip: You can use all the `git commit` `options` with `git cz`. For example: `git cz -a`.
> If your repository is a [Node.js](https://nodejs.org/en/) project, making it [Commitizen friendly](#making-your-repo-commitizen-friendly) is super easy.
If your repository is already [Commitizen friendly](#making-your-repo-commitizen-friendly), the local `commitizen` adapter will be used, instead of globally installed one.
## Commitizen for multi-repo projects
As a project maintainer of many projects, you may want to standardize on a single commit message format for all of them. You can create your own node module which acts as a front-end for Commitizen.
### 1. Create your own entry point script
```js
// my-cli.js
#!/usr/bin/env node
"use strict";
const path = require('path');
const bootstrap = require('commitizen/dist/cli/git-cz').bootstrap;
bootstrap({
cliPath: path.join(__dirname, '../../node_modules/commitizen'),
// this is new
config: {
"path": "cz-conventional-changelog"
}
});
```
### 2. Add the script to your `package.json` file
```json
// package.json
{
"name": "company-commit",
"bin": "./my-cli.js",
"dependencies": {
"commitizen": "^2.7.6",
"cz-conventional-changelog": "^1.1.5"
}
}
```
### 3. Publish it to npm and use it!
```sh
npm install --save-dev company-commit
./node_modules/.bin/company-commit
```
## Adapters
We know that every project and build process has different requirements, so we've tried to keep Commitizen open for extension. You can do this by choosing from any of the pre-built adapters or even by building your own. Here are some of the great adapters available to you:
- [cz-conventional-changelog](https://www.npmjs.com/package/cz-conventional-changelog)
- [cz-conventional-changelog-for-jira](https://www.npmjs.com/package/@digitalroute/cz-conventional-changelog-for-jira)
- [cz-conventional-changelog-with-jiraid-detection](https://www.npmjs.com/package/cz-conventional-changelog-with-jiraid-detection)
- [cz-jira-smart-commit](https://www.npmjs.com/package/cz-jira-smart-commit)
- [@endemolshinegroup/cz-jira-smart-commit](https://github.com/EndemolShineGroup/cz-jira-smart-commit)
- [@endemolshinegroup/cz-github](https://github.com/EndemolShineGroup/cz-github)
- [rb-conventional-changelog](https://www.npmjs.com/package/rb-conventional-changelog)
- [@mapbox/cz-mapbox-changelog](https://www.npmjs.com/package/@mapbox/cz-mapbox-changelog)
- [cz-customizable](https://github.com/leonardoanalista/cz-customizable)
- [cz-commitlint](https://github.com/conventional-changelog/commitlint/tree/master/@commitlint/cz-commitlint)
- [commitlint](https://github.com/conventional-changelog/commitlint/tree/master/@commitlint/prompt)
- [vscode-commitizen](https://github.com/KnisterPeter/vscode-commitizen)
- [cz-emoji](https://github.com/ngryman/cz-emoji)
- [cz-adapter-eslint](https://www.npmjs.com/package/cz-adapter-eslint)
- [commitiquette](https://github.com/martinmcwhorter/commitiquette)
- [cz-format-extension](https://github.com/tyankatsu0105/cz-format-extension)
- [cz-emoji-conventional](https://www.npmjs.com/package/cz-emoji-conventional)
- [cz-git](https://github.com/Zhengqbbb/cz-git)
- [cz-vinyl](https://github.com/Exlint/cz-vinyl)
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!
## Retrying failed commits
As of version 2.7.1, you may attempt to retry the last commit using the `git cz --retry` command. This can be helpful when you have tests set up to run via a git precommit hook. In this scenario, you may have attempted a Commitizen commit, painstakingly filled out all of the commitizen fields, but your tests fail. In previous Commitizen versions, after fixing your tests, you would be forced to fill out all of the fields again. Enter the retry command. Commitizen will retry the last commit that you attempted in this repo without you needing to fill out the fields again.
Please note that the retry cache may be cleared when upgrading Commitizen versions, upgrading adapters, or if you delete the `commitizen.json` file in your home or temp directory. Additionally, the commit cache uses the filesystem path of the repo, so if you move a repo or change its path, you will not be able to retry a commit. This is an edge case but might be confusing if you have scenarios where you are moving folders that contain repos.
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`
Note that the last two options **do not** require you to pass `--` before the args but the first **does**.
## Commitizen for project maintainers
As a project maintainer, making your repo Commitizen friendly allows you to select pre-existing commit message conventions or to create your own custom commit message convention. When a contributor to your repo uses Commitizen, they will be prompted for the correct fields at commit time.
## Go further
Commitizen is great on its own, but it shines when you use it with some other amazing open source tools. Kent C. Dodds shows you how to accomplish this in his Egghead.io series, [How to Write an Open Source JavaScript Library](https://app.egghead.io/playlists/how-to-write-an-open-source-javascript-library). Many of the concepts can be applied to non-JavaScript projects as well.
## Philosophy
### About Commitizen
Commitizen is an open source project that helps contributors be good open source citizens. It accomplishes this by prompting them to follow commit message conventions at commit time. It also empowers project maintainers to create or use predefined commit message conventions in their repos to better communicate their expectations to potential contributors.
### Commitizen or Commit Hooks
Both! Commitizen is not meant to be a replacement for git commit hooks. Rather, it is meant to work side-by-side with them to ensure a consistent and positive experience for your contributors. Commitizen treats the commit command as a declarative action. The contributor is declaring that they wish to contribute to your project. It is up to you as the maintainer to define what rules they should be following.
We accomplish this by letting you define which adapter you'd like to use in your project. Adapters just allow multiple projects to share the same commit message conventions. A good example of an adapter is the cz-conventional-changelog adapter.
## Related projects
- [conventional-changelog](https://github.com/conventional-changelog/conventional-changelog) – Generate a changelog from conventional commit history
- [commitlint](https://github.com/conventional-changelog/commitlint) - Lint commit messages
## Authors and Contributors
@JimTheDev (Jim Cummins, author)
@kentcdodds
@accraze
@kytwb
@Den-dp
Special thanks to @stevelacy, whose [gulp-git](https://www.npmjs.com/package/gulp-git) project makes commitizen possible.
## Contributors
This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)].
## Backers
Thank you to all our backers! 🙏 [[Become a backer](https://opencollective.com/commitizen#backer)]
## Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [[Become a sponsor](https://opencollective.com/commitizen#sponsor)]
[commitizen-friendly]: #making-your-repo-commitizen-friendly
================================================
FILE: azure-pipelines.yml
================================================
# Node.js
# Build a general Node.js project with npm.
# Add steps that analyze code, save build artifacts, deploy, and more:
# https://docs.microsoft.com/azure/devops/pipelines/languages/javascript
jobs:
- template: jobs/build.yml # Template reference
parameters:
name: macOS
pool:
vmImage: 'macOS-latest'
- template: jobs/build.yml # Template reference
parameters:
name: Linux
pool:
vmImage: 'ubuntu-latest'
- template: jobs/build.yml # Template reference
parameters:
name: Windows
pool:
vmImage: 'windows-latest'
sign: true # Extra step on Windows only
================================================
FILE: babel.config.js
================================================
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "10",
},
},
],
],
plugins: ["@babel/plugin-proposal-object-rest-spread", "istanbul"],
};
================================================
FILE: bin/commitizen
================================================
#!/usr/bin/env node
require('./commitizen.js');
================================================
FILE: bin/commitizen.cmd
================================================
@node "%~dpn0" %*
================================================
FILE: bin/commitizen.js
================================================
require('../dist/cli/commitizen.js').bootstrap();
================================================
FILE: bin/git-cz
================================================
#!/usr/bin/env node
require('./git-cz.js');
================================================
FILE: bin/git-cz.cmd
================================================
@node "%~dpn0" %*
================================================
FILE: bin/git-cz.js
================================================
var path = require('path');
process.on('uncaughtException', function (err) {
console.error(err.message || err);
process.exit(1);
});
// catch SIGINT signal
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, '../')
});
================================================
FILE: jobs/build.yml
================================================
# File: jobs/build.yml
parameters:
name: ''
pool: ''
sign: false
jobs:
- job: ${{ parameters.name }}
pool: ${{ parameters.pool }}
strategy:
maxParallel: 3
matrix:
node-16:
node_version: ^16.13.0
node-14:
node_version: ^14.18.0
node-12:
node_version: ^12.6.0
steps:
- task: NodeTool@0
displayName: " Install Node.js"
inputs:
versionSpec: $(node_version)
- script: git config --global user.email "example@example.com"
- script: git config --global user.name "Example Git User"
- script: |
curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm@6
pnpm config set store-dir $(pnpm_config_cache)
displayName: "Setup pnpm"
- script: npm install
- script: npm run build
- script: npm test && npm run write-coverage
- script: bash logo/generate.sh
- task: PublishTestResults@2
displayName: 'Publish Test Results'
inputs:
testResultsFiles: '**/junit-*.xml'
testRunTitle: TestRun ${{ parameters.name }} $(node_version)
- task: PublishCodeCoverageResults@1
displayName: 'Publish code coverage results'
inputs:
codeCoverageTool: 'cobertura'
summaryFileLocation: '**/coverage/cobertura-coverage.xml'
- task: PublishBuildArtifacts@1
displayName: Publish packages
condition: and(succeeded(), eq(variables['system.pullrequest.isfork'], false))
inputs:
pathtoPublish: '$(Build.ArtifactStagingDirectory)'
================================================
FILE: jsconfig.json
================================================
{
"compilerOptions": {
"target": "ES6",
"module": "commonjs",
"experimentalDecorators" : true
}
}
================================================
FILE: logo/generate.sh
================================================
#!/bin/bash
set -o nounset
set -o errexit
#####################################################
# Script to create PNG files from SVG source files. #
# Dependencies: cairosvg (https://cairosvg.org/) #
# #
# Rationale: Generating from SVG instead of storing #
# image files decreases size of repo and avoids #
# security vulnerabilites associated with binary #
# image files. #
#####################################################
convert () {
COLOR=$1
# echo "converting file $COLOR..."
FILE=logo/commitizen-logo-${COLOR}.svg
if [ ! -f ${FILE} ]; then
# echo "file $FILE missing!"
exit 1
fi
# echo "conversion in progress..."
for SIZE in 16 48 96 256 512 1024; do
cairosvg ${FILE} -f png -W ${SIZE} -H ${SIZE} -d 300 -o logo/commitizen_logo_${COLOR}_${SIZE}x${SIZE}.png
done
# echo "done"
return 0
}
if [[ $(which cairosvg) == "" ]]; then
# We're not going to mess with installation on OSX or Windows in our build pipelines.
if [[ "$OSTYPE" == "darwin"* ]]; then
echo "cairosvg not found in PATH. Please see https://cairosvg.org/documentation/#installation"
exit 0
elif [[ "$OSTYPE" == "msys"* ]]; then
echo "cairosvg not found in PATH. Please see https://cairosvg.org/documentation/#installation"
exit 0
fi
pip3 install cairosvg
fi
for COLOR in black blue white color; do
FILE=logo/commitizen-logo-${COLOR}.svg
if [ ! -f ${FILE} ]; then
# echo "generating file $FILE..."
sed 's|fill=\".*\"|fill=\"'${COLOR}'\"|g' ${FILE}
convert ${COLOR}
# echo "removing generated file $FILE..."
rm $FILE
# echo "success!"
else
# echo "file found: $FILE"
convert ${COLOR}
fi
done
exit 0
================================================
FILE: package.json
================================================
{
"name": "commitizen",
"version": "0.0.0",
"description": "Git commit, but play nice with conventions.",
"main": "dist/index.js",
"scripts": {
"check-coverage": "nyc check-coverage --statements 80 --branches 80 --functions 80 --lines 80 ",
"commit": "node bin/git-cz",
"build": "babel src --out-dir dist",
"build:watch": "babel --watch src --out-dir dist",
"prepare": "not-in-install && npm run build || true",
"report-coverage": "nyc report --reporter=lcov | codecov",
"write-coverage": "nyc report --reporter=lcov --reporter=cobertura --reporter=html",
"semantic-release": "npx semantic-release",
"start": "npm run test:watch",
"test-actual": "mocha --reporter=mocha-multi-reporters --reporter-options configFile=./test/mochareporters.json test/tests/index.js",
"test": "nyc --require @babel/register npm run test-actual",
"test:watch": "nodemon -q --ignore test/.tmp/ --ignore test/artifacts/ --ignore coverage/ --exec \"npm run test\" --"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
},
"ghooks": {
"pre-commit": "npm run test && npm run check-coverage"
}
},
"homepage": "https://github.com/commitizen/cz-cli",
"repository": {
"type": "git",
"url": "https://github.com/commitizen/cz-cli.git"
},
"keywords": [
"commit",
"pretty",
"format",
"conventional changelog",
"commitizen"
],
"bugs": {
"url": "https://github.com/commitizen/cz-cli/issues"
},
"bin": {
"cz": "./bin/git-cz",
"git-cz": "./bin/git-cz",
"commitizen": "./bin/commitizen"
},
"author": "Jim Cummins (https://github.com/jimthedev)",
"license": "MIT",
"devDependencies": {
"@babel/cli": "7.19.3",
"@babel/core": "7.20.5",
"@babel/plugin-proposal-object-rest-spread": "7.20.2",
"@babel/preset-env": "7.20.2",
"@babel/register": "7.18.9",
"@istanbuljs/nyc-config-babel": "3.0.0",
"babel-plugin-istanbul": "6.1.1",
"chai": "4.3.7",
"codecov": "3.8.3",
"conventional-changelog-conventionalcommits": "4.6.3",
"cz-conventional-changelog-default-export": "0.0.0-semantically-released.1",
"ghooks": "2.0.4",
"in-publish": "2.0.1",
"mocha": "9.2.2",
"mocha-junit-reporter": "1.23.3",
"mocha-multi-reporters": "1.5.1",
"nodemon": "2.0.20",
"nyc": "15.1.0",
"proxyquire": "2.1.3",
"semantic-release": "19.0.5",
"semver": "7.3.8",
"sinon": "12.0.1",
"uuid": "8.3.2"
},
"dependencies": {
"cachedir": "2.3.0",
"cz-conventional-changelog": "3.3.0",
"dedent": "0.7.0",
"detect-indent": "6.1.0",
"find-node-modules": "^2.1.2",
"find-root": "1.1.0",
"fs-extra": "9.1.0",
"glob": "7.2.3",
"inquirer": "8.2.5",
"is-utf8": "^0.2.1",
"lodash": "4.17.21",
"minimist": "1.2.7",
"strip-bom": "4.0.0",
"strip-json-comments": "3.1.1"
},
"nyc": {
"extends": "@istanbuljs/nyc-config-babel",
"exclude": [
"src/cli",
"test"
]
},
"engineStrict": true,
"engines": {
"node": ">= 12"
},
"collective": {
"type": "opencollective",
"url": "https://opencollective.com/commitizen"
},
"release": {
"preset": "conventionalcommits"
}
}
================================================
FILE: renovate.json
================================================
{
"extends": [
"github>commitizen/commitizen-renovate-config"
]
}
================================================
FILE: src/cli/commitizen.js
================================================
import { init } from '../commitizen';
import { commitizen as commitizenParser } from './parsers';
let { parse } = commitizenParser;
export {
bootstrap
};
/**
* This is the main cli entry point.
* environment may be used for debugging.
*/
function bootstrap (environment = {}, argv = process.argv) {
// Get cli args
let rawGitArgs = argv.slice(2, argv.length);
// Parse the args
let parsedArgs = parse(rawGitArgs);
let command = parsedArgs._[0];
// Do actions based on commands
if (command === "init") {
let adapterNpmName = parsedArgs._[1];
if (adapterNpmName) {
console.log(`Attempting to initialize using the npm package ${adapterNpmName}`);
try {
init(process.cwd(), adapterNpmName, parsedArgs);
} catch (e) {
console.error(`Error: ${e}`);
}
} else {
console.error('Error: You must provide an adapter name as the second argument.');
}
} else {
console.log(`
Commitizen has two command line tools:
1) cz -- used for making commits according to convention
note: you can run 'git cz' if installed with -g
2) git-cz -- alias for 'cz'
3) commitizen -- used for installing adapters into your project
Generally if you're using someone else's repo and they've already set up an
adapter, you're going to just be running:
cz
However, if you create a new repo and you want to make it easier for future
contributors to follow your commit message conventions using commitizen then
you'll need to run a command like this one to add this adapter to your config:
commitizen init cz-conventional-changelog --save
You should swap out cz-conventional-changelog for the NPM package name of the
adapter you wish you install in your project's package.json.
Detailed usage:
1) commitizen
init [args]
description: Install a commitizen adapter from npm and adds it to your
config.commitizen in your package.json file.
args:
--save Install the adapter to package.json dependencies
--save-dev Install the adapter to devDependencies
--save-exact Install an exact version instead of a range
--force Force install the adapter, even if a previous one exists.
2) cz
description: Runs the commitizen prompter, asking you questions so that you
follow the commit conventions of the repository of the current
directory.
note: cz may even be run as 'git cz' if installed with -g.
`);
}
}
================================================
FILE: src/cli/git-cz.js
================================================
import { configLoader } from '../commitizen';
import { git as useGitStrategy, gitCz as useGitCzStrategy } from './strategies';
export {
bootstrap
};
/**
* This is the main cli entry point.
* environment may be used for debugging.
*/
function bootstrap (environment = {}, argv = process.argv) {
// Get cli args
let rawGitArgs = argv.slice(2, argv.length);
let adapterConfig = environment.config || configLoader.load();
// Choose a strategy based on the existance the adapter config
if (typeof adapterConfig !== 'undefined') {
// This tells commitizen we're in business
useGitCzStrategy(rawGitArgs, environment, adapterConfig);
} else {
// This tells commitizen that it is not needed, just use git
useGitStrategy(rawGitArgs, environment);
}
}
================================================
FILE: src/cli/parsers/commitizen.js
================================================
import minimist from 'minimist';
export {
parse
};
/**
* Takes args, parses with minimist and some ugly vudoo, returns output
*
* TODO: Aww shit this is ugly. Rewrite with mega leet tests plz, kthnx.
*/
function parse (rawGitArgs) {
var args = minimist(rawGitArgs, {
boolean: true
});
return args;
}
================================================
FILE: src/cli/parsers/git-cz.js
================================================
export {
parse
};
const reShortMessage = /^-([a-zA-Z]*)m(.*)$/;
const reLongMessage = /^--message(=.*)?$/;
/**
* Strip message declaration from git arguments
*/
function parse (rawGitArgs) {
let result = [];
let skipNext = false;
for (const arg of rawGitArgs) {
let match;
if (skipNext) {
skipNext = false;
continue;
}
match = reShortMessage.exec(arg);
if (match) {
if (match[1]) {
result.push(`-${match[1]}`);
}
if (!match[2]) {
skipNext = true;
}
continue;
}
match = reLongMessage.exec(arg);
if (match) {
if (!match[1]) {
skipNext = true;
}
continue;
}
result.push(arg);
}
return result;
}
================================================
FILE: src/cli/parsers.js
================================================
import * as commitizen from './parsers/commitizen';
import * as gitCz from './parsers/git-cz';
export {
commitizen,
gitCz
};
================================================
FILE: src/cli/strategies/git-cz.js
================================================
import inquirer from 'inquirer';
import findRoot from 'find-root';
import { getParsedPackageJsonFromPath } from '../../common/util';
import { gitCz as gitCzParser, commitizen as commitizenParser } from '../parsers';
import { commit, staging, adapter } from '../../commitizen';
import * as gitStrategy from './git';
// destructure for shorter apis
let { parse } = gitCzParser;
let { getPrompter, resolveAdapterPath, getGitRootPath } = adapter;
let { isClean } = staging;
export default gitCz;
function gitCz (rawGitArgs, environment, adapterConfig) {
// See if any override conditions exist.
// In these very specific scenarios we may want to use a different
// commit strategy than git-cz. For example, in the case of --amend
let parsedCommitizenArgs = commitizenParser.parse(rawGitArgs);
if (parsedCommitizenArgs.amend) {
// console.log('override --amend in place');
gitStrategy.default(rawGitArgs, environment);
return;
}
// Now, if we've made it past overrides, proceed with the git-cz strategy
let parsedGitCzArgs = parse(rawGitArgs);
// Determine if we need to process this commit as a retry instead of a
// normal commit.
let retryLastCommit = rawGitArgs && rawGitArgs[0] === '--retry';
// Determine if we need to process this commit using interactive hook mode
// for husky prepare-commit-message
let hookMode = !(typeof parsedCommitizenArgs.hook === 'undefined');
let resolvedAdapterConfigPath = resolveAdapterPath(adapterConfig.path);
let resolvedAdapterRootPath = findRoot(resolvedAdapterConfigPath);
let prompter = getPrompter(adapterConfig.path);
let shouldStageAllFiles = rawGitArgs.includes('-a') || rawGitArgs.includes('--all');
isClean(process.cwd(), function (error, stagingIsClean) {
if (error) {
throw error;
}
if (stagingIsClean && !parsedGitCzArgs.includes('--allow-empty')) {
throw new Error('No files added to staging! Did you forget to run git add?');
}
// OH GOD IM SORRY FOR THIS SECTION
let adapterPackageJson = getParsedPackageJsonFromPath(resolvedAdapterRootPath);
let cliPackageJson = getParsedPackageJsonFromPath(environment.cliPath);
console.log(`cz-cli@${cliPackageJson.version}, ${adapterPackageJson.name}@${adapterPackageJson.version}\n`);
commit(inquirer, getGitRootPath(), prompter, {
args: parsedGitCzArgs,
disableAppendPaths: true,
emitData: true,
quiet: false,
retryLastCommit,
hookMode
}, function (error) {
if (error) {
throw error;
}
process.exit(0);
});
}, shouldStageAllFiles);
}
================================================
FILE: src/cli/strategies/git.js
================================================
import childProcess from 'child_process';
export default git;
// We don't have a config, so either we use raw args to try to commit
// or if debug is enabled then we do a strict check for a config file.
function git (rawGitArgs, environment) {
if (environment.debug === true) {
console.error('COMMITIZEN DEBUG: No cz friendly config was detected. I looked for .czrc, .cz.json, or czConfig in package.json.');
} else {
var vanillaGitArgs = ["commit"].concat(rawGitArgs);
var child = childProcess.spawn('git', vanillaGitArgs, {
stdio: 'inherit'
});
child.on('error', function (e, code) {
console.error(e);
throw e;
});
}
}
================================================
FILE: src/cli/strategies.js
================================================
import git from './strategies/git';
import gitCz from './strategies/git-cz';
export {
git,
gitCz
};
================================================
FILE: src/commitizen/adapter.js
================================================
import childProcess from 'child_process';
import path from 'path';
import fs from 'fs';
import findNodeModules from 'find-node-modules';
import _ from 'lodash';
import detectIndent from 'detect-indent';
import { isFunction } from '../common/util';
export {
addPathToAdapterConfig,
getNearestNodeModulesDirectory,
getNearestProjectRootDirectory,
getInstallStringMappings,
getPrompter,
generateInstallAdapterCommand,
resolveAdapterPath,
getGitRootPath,
};
/**
* ADAPTER
*
* Adapter is generally responsible for actually installing adapters to an
* end user's project. It does not perform checks to determine if there is
* a previous commitizen adapter installed or if the proper fields were
* provided. It defers that responsibility to init.
*/
/**
* Modifies the package.json, sets config.commitizen.path to the path of the adapter
* Must be passed an absolute path to the cli's root
*/
function addPathToAdapterConfig (cliPath, repoPath, adapterNpmName) {
let commitizenAdapterConfig = {
config: {
commitizen: {
path: `./node_modules/${adapterNpmName}`
}
}
};
let packageJsonPath = path.join(getNearestProjectRootDirectory(repoPath), 'package.json');
let packageJsonString = fs.readFileSync(packageJsonPath, 'utf-8');
// tries to detect the indentation and falls back to a default if it can't
let indent = detectIndent(packageJsonString).indent || ' ';
let packageJsonContent = JSON.parse(packageJsonString);
let newPackageJsonContent = '';
if (_.get(packageJsonContent, 'config.commitizen.path') !== adapterNpmName) {
newPackageJsonContent = _.merge(packageJsonContent, commitizenAdapterConfig);
}
fs.writeFileSync(packageJsonPath, JSON.stringify(newPackageJsonContent, null, indent) + '\n');
}
/*
* Get additional options for install command
*/
function getInstallOptions(stringMappings) {
return Array.from(stringMappings.values()).filter(Boolean).join(" ")
}
/*
* Get specific install command for passed package manager
*/
function getInstallCommand(packageManager) {
const fallbackCommand = 'install';
const commandByPackageManager = {
npm: 'install',
yarn: 'add',
pnpm: 'add',
};
return commandByPackageManager[packageManager] || fallbackCommand;
}
/**
* Generates an npm install command given a map of strings and a package name
*/
function generateInstallAdapterCommand(stringMappings, adapterNpmName, packageManager = "npm") {
return `${packageManager} ${getInstallCommand(packageManager)} ${adapterNpmName} ${getInstallOptions(stringMappings)}`;
}
/**
* Gets the nearest npm_modules directory
*/
function getNearestNodeModulesDirectory (options) {
// Get the nearest node_modules directories to the current working directory
let nodeModulesDirectories = findNodeModules(options);
// Make sure we find a node_modules folder
/* istanbul ignore else */
if (nodeModulesDirectories && nodeModulesDirectories.length > 0) {
return nodeModulesDirectories[0];
} else {
console.error(`Error: Could not locate node_modules in your project's root directory. Did you forget to npm init or npm install?`)
}
}
/**
* Gets the nearest project root directory
*/
function getNearestProjectRootDirectory (repoPath, options) {
return path.join(repoPath, getNearestNodeModulesDirectory(options), '/../');
}
/**
* Gets a map of arguments where the value is the corresponding (to passed package manager) string
*/
function getInstallStringMappings({ save, dev, saveDev, exact, saveExact, force }, packageManager) {
const npm = new Map()
.set('save', save && !saveDev ? '--save' : undefined)
.set('saveDev', saveDev ? '--save-dev' : undefined)
.set('saveExact', saveExact ? '--save-exact' : undefined)
.set('force', force ? '--force' : undefined);
const yarn = new Map()
.set('dev', dev ? '--dev' : undefined)
.set('exact', exact ? '--exact' : undefined)
.set('force', force ? '--force' : undefined);
const pnpm = new Map()
.set('save', save && !saveDev ? '--save-prod' : undefined)
.set('dev', saveDev ? '--save-dev' : undefined)
.set('exact', saveExact ? '--save-exact' : undefined);
const map = { npm, yarn, pnpm };
return map[packageManager] || npm;
}
/**
* Gets the prompter from an adapter given an adapter path
*/
function getPrompter (adapterPath) {
// Resolve the adapter path
let resolvedAdapterPath = resolveAdapterPath(adapterPath);
// Load the adapter
let adapter = require(resolvedAdapterPath);
/* istanbul ignore next */
if (adapter && adapter.prompter && isFunction(adapter.prompter)) {
return adapter.prompter;
} else if (adapter && adapter.default && adapter.default.prompter && isFunction(adapter.default.prompter)) {
return adapter.default.prompter;
} else {
throw new Error(`Could not find prompter method in the provided adapter module: ${adapterPath}`);
}
}
/**
* Given a resolvable module name or path, which can be a directory or file, will
* return a located adapter path or will throw.
*/
function resolveAdapterPath (inboundAdapterPath) {
// Check if inboundAdapterPath is a path or node module name
let parsed = path.parse(inboundAdapterPath);
let isPath = parsed.dir.length > 0 && parsed.dir.charAt(0) !== "@";
// Resolve from the root of the git repo if inboundAdapterPath is a path
let absoluteAdapterPath = isPath ?
path.resolve(getGitRootPath(), inboundAdapterPath) :
inboundAdapterPath;
try {
// try to resolve the given path
return require.resolve(absoluteAdapterPath);
} catch (error) {
error.message = "Could not resolve " + absoluteAdapterPath + ". " + error.message;
throw error;
}
}
function getGitRootPath () {
return childProcess.spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8' }).stdout.trim();
}
================================================
FILE: src/commitizen/cache.js
================================================
import fs from 'fs';
import _ from 'lodash';
export {
getCacheValueSync,
readCacheSync,
setCacheValueSync,
};
/**
* Reads the entire cache
*/
function readCacheSync (cachePath) {
return JSON.parse(fs.readFileSync(cachePath, 'utf8'));
}
/**
* Sets a cache value and writes the file to disk
*/
function setCacheValueSync (cachePath, key, value) {
var originalCache;
try {
originalCache = readCacheSync(cachePath);
} catch (e) {
originalCache = {};
}
var newCache = _.assign(originalCache, {
[key]: value
});
fs.writeFileSync(cachePath, JSON.stringify(newCache, null, ' '));
return newCache;
}
/**
* Gets a single value from the cache given a key
*/
function getCacheValueSync (cachePath, repoPath) {
try {
let cache = readCacheSync(cachePath);
return cache[repoPath];
} catch (e) {
}
}
================================================
FILE: src/commitizen/commit.js
================================================
import path from 'path';
import cacheDir from 'cachedir';
import { ensureDir } from 'fs-extra';
import { commit as gitCommit } from '../git';
import * as cache from './cache';
export default commit;
/**
* Takes all of the final inputs needed in order to make dispatch a git commit
*/
function dispatchGitCommit (repoPath, template, options, overrideOptions, done) {
// Commit the user input -- side effect that we'll test
gitCommit(repoPath, template, { ...options, ...overrideOptions }, function (error) {
done(error, template);
});
}
/**
* Asynchronously commits files using commitizen
*/
function commit (inquirer, repoPath, prompter, options, done) {
var cacheDirectory = cacheDir('commitizen');
var cachePath = path.join(cacheDirectory, 'commitizen.json');
ensureDir(cacheDirectory, function (error) {
if (error) {
console.error("Couldn't create commitizen cache directory: ", error);
// TODO: properly handle error?
} else {
if (options.retryLastCommit) {
console.log('Retrying last commit attempt.');
// We want to use the last commit instead of the current commit,
// so lets override some options using the values from cache.
let {
options: retryOptions,
overrideOptions: retryOverrideOptions,
template: retryTemplate
} = cache.getCacheValueSync(cachePath, repoPath);
dispatchGitCommit(repoPath, retryTemplate, retryOptions, retryOverrideOptions, done);
} else {
// Get user input -- side effect that is hard to test
prompter(inquirer, function (error, template, overrideOptions) {
// Allow adapters to error out
// (error: Error?, template: String, overrideOptions: Object)
if (!(error instanceof Error)) {
overrideOptions = template;
template = error;
error = null;
}
if (error) {
return done(error);
}
// We don't want to add retries to the cache, only actual commands
cache.setCacheValueSync(cachePath, repoPath, { template, options, overrideOptions });
dispatchGitCommit(repoPath, template, options, overrideOptions, done);
});
}
}
});
}
================================================
FILE: src/commitizen/configLoader.js
================================================
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);
}
================================================
FILE: src/commitizen/init.js
================================================
import childProcess from 'child_process';
import path from 'path';
import * as configLoader from './configLoader';
import * as adapter from './adapter';
let {
addPathToAdapterConfig,
generateInstallAdapterCommand,
getInstallStringMappings,
} = adapter;
export default init;
const CLI_PATH = path.normalize(path.join(__dirname, '../../'));
/**
* CZ INIT
*
* Init is generally responsible for initializing an adapter in
* a user's project. The goal is to be able to run
* `commitizen init` and be prompted for certain fields which
* will help you install the proper adapter for your project.
*
* Init does not actually create the adapter (it defers to adapter
* for this). Instead, it is specifically designed to help gather
* and validate the information needed to install the adapter
* properly without interfering with a previous adapter config.
*/
/**
* The defaults for init
*/
const defaultInitOptions = {
save: false,
saveDev: true,
saveExact: false,
force: false,
// for --yarn use
// @see https://github.com/commitizen/cz-cli/issues/527#issuecomment-392653897
yarn: false,
dev: true,
exact: false, // should add trailing comma, thus next developer doesn't got blamed for this line
pnpm: false, // reuses `save`, `saveDev`, `saveExact`
};
/**
* Runs npm install for the adapter then modifies the config.commitizen as needed
*/
function init (repoPath, adapterNpmName, {
save = false,
saveDev = true,
saveExact = false,
force = false,
yarn = false,
dev = false,
exact = false,
pnpm = false,
includeCommitizen = false
} = defaultInitOptions) {
// Don't let things move forward if required args are missing
checkRequiredArguments(repoPath, adapterNpmName);
// Load the current adapter config
let adapterConfig = loadAdapterConfig(repoPath);
const packageManager = yarn ? 'yarn' : pnpm ? 'pnpm' : 'npm';
// Get the npm string mappings based on the arguments provided
const stringMappings = getInstallStringMappings({ save, dev, saveDev, saveExact, force }, packageManager);
// Generate a string that represents the npm install command
const installAdapterCommand = generateInstallAdapterCommand(stringMappings, adapterNpmName, packageManager);
const installCommitizenCommand = generateInstallAdapterCommand(stringMappings, 'commitizen', packageManager);
// Check for previously installed adapters
if (adapterConfig && adapterConfig.path && adapterConfig.path.length > 0 && !force) {
throw new Error(`A previous adapter is already configured. Use --force to override
adapterConfig.path: ${adapterConfig.path}
repoPath: ${repoPath}
CLI_PATH: ${CLI_PATH}
installAdapterCommand: ${installAdapterCommand}
adapterNpmName: ${adapterNpmName}
`);
}
try {
childProcess.execSync(installAdapterCommand, { cwd: repoPath });
if(includeCommitizen) {
childProcess.execSync(installCommitizenCommand, { cwd: repoPath });
}
addPathToAdapterConfig(CLI_PATH, repoPath, adapterNpmName);
} catch (e) {
console.error(e);
}
}
/**
* Checks to make sure that the required arguments are passed
* Throws an exception if any are not.
*/
function checkRequiredArguments (path, adapterNpmName) {
if (!path) {
throw new Error("Path is required when running init.");
}
if (!adapterNpmName) {
throw new Error("The adapter's npm name is required when running init.");
}
}
/**
* CONFIG
* Loads and returns the adapter config at key config.commitizen, if it exists
*/
function loadAdapterConfig (cwd) {
let config = configLoader.load(null, cwd);
if (config) {
return config;
} else {
}
}
================================================
FILE: src/commitizen/staging.js
================================================
import { exec } from 'child_process';
export { isClean };
/**
* Asynchrounously determines if the staging area is clean
*/
function isClean (repoPath, done, stageAllFiles) {
exec(`git diff --cached --no-ext-diff --name-only ${!!stageAllFiles ? '&& git diff --no-ext-diff --name-only' : ''}`, {
maxBuffer: Infinity,
cwd: repoPath
}, function (error, stdout) {
if (error) {
return done(error);
}
let output = stdout || '';
done(null, output.trim().length === 0);
});
}
================================================
FILE: src/commitizen.js
================================================
/* istanbul ignore file */
import * as adapter from './commitizen/adapter';
import * as cache from './commitizen/cache';
import commit from './commitizen/commit';
import * as configLoader from './commitizen/configLoader';
import init from './commitizen/init';
import * as staging from './commitizen/staging';
export {
adapter,
cache,
commit,
configLoader,
init,
staging
};
================================================
FILE: src/common/util.js
================================================
import fs from 'fs';
import path from 'path';
export {
getParsedJsonFromFile,
getParsedPackageJsonFromPath,
isFunction,
isInTest
}
/**
* Gets the parsed contents of a json file
*/
function getParsedJsonFromFile (filePath, fileName, encoding = 'utf8') {
try {
var packageJsonContents = fs.readFileSync(path.join(filePath, fileName), encoding);
return JSON.parse(packageJsonContents);
} catch (e) {
console.error(e);
}
}
/**
* A helper method for getting the contents of package.json at a given path
*/
function getParsedPackageJsonFromPath (path) {
return getParsedJsonFromFile(path, 'package.json');
}
/**
* Test if the passed argument is a function
*/
function isFunction (functionToCheck) {
if (typeof functionToCheck === "undefined")
{
return false;
} else if (functionToCheck === null) {
return false;
} else {
var getType = {};
var functionType = getType.toString.call(functionToCheck);
return functionToCheck && (functionType === '[object Function]' || functionType === '[object AsyncFunction]');
}
}
function isInTest () {
return typeof global.it === 'function';
}
================================================
FILE: src/configLoader/findup.js
================================================
import path from 'path';
import glob from 'glob';
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;
options = Object.create(options);
options.maxDepth = 1;
options.cwd = path.resolve(options.cwd);
do {
file = patterns.filter(function (pattern) {
var configPath = glob.sync(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);
}
================================================
FILE: src/configLoader/getContent.js
================================================
import fs from 'fs';
import path from 'path';
import stripJSONComments from 'strip-json-comments';
import isUTF8 from 'is-utf8';
import stripBom from 'strip-bom';
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`);
}
return stripBom(rawBufContent.toString("utf8"));
}
================================================
FILE: src/configLoader/getNormalizedConfig.js
================================================
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
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;
}
}
================================================
FILE: src/configLoader/loader.js
================================================
import path from '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;
}
}
}
}
}
================================================
FILE: src/configLoader.js
================================================
/* 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
};
================================================
FILE: src/git/add.js
================================================
import childProcess from 'child_process';
export {
addPath,
addFile
}
/**
* Synchronously adds a path to git staging
*/
function addPath (repoPath) {
childProcess.spawnSync('git', ['add', '.'], { cwd: repoPath });
}
/**
* Synchronously adds a file to git staging
*/
function addFile (repoPath, filename) {
childProcess.spawnSync('git', ['add', filename], { cwd: repoPath });
}
================================================
FILE: src/git/commit.js
================================================
import { execSync, spawn } from 'child_process';
import path from 'path';
import { writeFileSync, openSync, closeSync } from 'fs';
import dedent from 'dedent';
export { commit };
/**
* Asynchronously git commit at a given path with a message
*/
function commit (repoPath, message, options, done) {
let called = false;
// commit the file by spawning a git process, unless the --hook
// option was provided. in that case, write the commit message into
// the .git/COMMIT_EDITMSG file
if (!options.hookMode) {
let args = ['commit', '-m', dedent(message), ...(options.args || [])];
let child = spawn('git', args, {
cwd: repoPath,
stdio: options.quiet ? 'ignore' : 'inherit'
});
child.on('error', function (err) {
if (called) return;
called = true;
done(err);
});
child.on('exit', function (code, signal) {
if (called) return;
called = true;
if (code) {
if (code === 128) {
console.warn(`
Git exited with code 128. Did you forget to run:
git config --global user.email "you@example.com"
git config --global user.name "Your Name"
`)
}
done(Object.assign(new Error(`git exited with error code ${code}`), { code, signal }));
} else {
done(null);
}
});
} else {
const gitDirPath = execSync(
'git rev-parse --absolute-git-dir',
{ cwd: repoPath, encoding: 'utf8' },
).trim();
const commitFilePath = path.join(gitDirPath, 'COMMIT_EDITMSG');
try {
const fd = openSync(commitFilePath, 'w');
try {
writeFileSync(fd, dedent(message));
done(null);
} catch (e) {
done(e);
} finally {
closeSync(fd);
}
} catch (e) {
// windows doesn't allow opening existing hidden files
// in 'w' mode... but it does let you do 'r+'!
try {
const fd = openSync(commitFilePath, 'r+');
try {
writeFileSync(fd, dedent(message));
done(null);
} catch (e) {
done(e);
} finally {
closeSync(fd);
}
} catch (e) {
done(e);
}
}
}
}
================================================
FILE: src/git/init.js
================================================
import childProcess from 'child_process';
export { init };
/**
* Synchronously creates a new git repo at a path
*/
function init (repoPath) {
childProcess.spawnSync('git', ['init'], { cwd: repoPath });
}
================================================
FILE: src/git/log.js
================================================
import { exec } from 'child_process';
export { log };
/**
* Asynchronously gets the git log output
*/
function log (repoPath, done) {
exec('git log', {
maxBuffer: Infinity,
cwd: repoPath
}, function (error, stdout, stderr) {
if (error) {
throw error;
}
done(stdout);
});
}
================================================
FILE: src/git/whatChanged.js
================================================
import { exec } from 'child_process';
export { whatChanged };
/**
* Asynchronously gets the git whatchanged output
*/
function whatChanged (repoPath, done) {
exec('git whatchanged', {
maxBuffer: Infinity,
cwd: repoPath
}, function (error, stdout, stderr) {
if (error) {
throw error;
}
done(stdout);
});
}
================================================
FILE: src/git.js
================================================
/* istanbul ignore file */
import { addPath, addFile } from './git/add';
import { commit } from './git/commit';
import { init } from './git/init';
import { log } from './git/log';
import { whatChanged } from './git/whatChanged';
export {
addPath,
addFile,
commit,
init,
log,
whatChanged
};
================================================
FILE: src/index.js
================================================
var commitizen = require('./commitizen');
module.exports = commitizen;
================================================
FILE: src/npm.js
================================================
// this file left blank until npm init is implemented
================================================
FILE: test/config.js
================================================
import path from 'path';
/**
* Modify the testConfig to your liking
*/
let config = {
paths: {
/**
* Where to place the artifacts for the last test run.
* These are cleared at the beginning of the next test
* run.
*/
tmp: path.join(__dirname, '/.tmp'),
/**
* Where to temporarily store the artifacts for the end
* user repo.
*/
endUserRepo: path.join(__dirname, '/.tmp/enduser-app')
},
/**
* This should be set to a large enough timeout that it is
* longer than the longest test.
*
* Usage (in a given test):
* this.timeout = config.maxTimeout;
*
* Note that only certain long tests should use this
* max timeout value (such as installing packages).
*
* Most tests should use the default timeout.
*/
maxTimeout: 240000,
/**
* Whether or not to keep the artifacts of the tests after
* they've run.
*
* Possible options:
* Positive integer Keeps latests (n) run artifacts
* false (default) Keeps no artifacts
* true | 'all' Keeps all artifacts, Warning. See below.
*
* Artifacts are stored in test/artifacts.
*
* Each run of the test suite is given a unique id and each
* test is given a unique id.
*
* WARNING:
* 'all' or true may be useful for debugging but you should have
* the value set to false or a positive integer by default as the
* artifacts folder will continue to grow unless you manually clear
* it. Use at your own risk.
*/
preserve: 1
};
export { config };
================================================
FILE: test/fixtures/invalid-json-rc
================================================
{
"some": "json"
"that": "is invalid"
}
================================================
FILE: test/fixtures/invalid-json.json
================================================
{
"some": "json"
"that": "is invalid"
}
================================================
FILE: test/fixtures/valid-json-rc
================================================
{
"some": "json"
// with comments
}
================================================
FILE: test/mochareporters.json
================================================
{
"reporterEnabled": "spec, mocha-junit-reporter",
"mochaJunitReporterReporterOptions": {
"mochaFile": "../../junit-testresults.xml",
"includePending": true,
"outputs": true
}
}
================================================
FILE: test/tester.js
================================================
import * as repo from './tools/repo';
import * as clean from './tools/clean';
import * as files from './tools/files';
import * as util from '../src/common/util';
import { config as userConfig } from './config';
import _ from 'lodash';
// Clone the user's config so we don't get caught w/our pants down
let patchedConfig = _.cloneDeep(userConfig);
function bootstrap () {
// Return the patched config
return {
config: patchedConfig,
repo,
clean,
util,
files
}
}
export {
bootstrap
};
================================================
FILE: test/tests/adapter.js
================================================
import { expect } from 'chai';
import path from 'path';
// TODO: augment these tests with tests using the actual cli call
// For now we're just using the library, which is probably fine
// in the short term
import { adapter, init as commitizenInit } from '../../src/commitizen';
import { isFunction } from '../../src/common/util';
// Bootstrap our tester
import { bootstrap } from '../tester';
// Destructure some things based on the bootstrap process
let { config, repo, clean } = bootstrap();
before(function () {
// Creates the temp path
clean.before(config.paths.tmp);
});
beforeEach(function () {
this.timeout(config.maxTimeout); // this could take a while
repo.createEndUser(config.paths.endUserRepo);
});
describe('adapter', function () {
it('resolves adapter paths', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-conventional-changelog'),
npmName: 'cz-conventional-changelog'
};
// Install an adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog');
// TEST
expect(function () { adapter.resolveAdapterPath('IAMANIMPOSSIBLEPATH'); }).to.throw(Error);
expect(function () { adapter.resolveAdapterPath(adapterConfig.path); }).not.to.throw(Error);
expect(function () { adapter.resolveAdapterPath(path.join(adapterConfig.path, 'index.js')); }).not.to.throw(Error);
// This line is only here to make sure that cz-conventional-changelog
// was installed for the purposes of running tests, it is not needed
// for testing any other adapters.
expect(function () { adapter.resolveAdapterPath('cz-conventional-changelog'); }).not.to.throw(Error);
});
it('resolves scoped adapter paths', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/@commitizen/cz-conventional-changelog'),
npmName: '@commitizen/cz-conventional-changelog'
};
// Install an adapter
commitizenInit(config.paths.endUserRepo, '@commitizen/cz-conventional-changelog');
// TEST
expect(function () { adapter.resolveAdapterPath('IAMANIMPOSSIBLEPATH'); }).to.throw(Error);
expect(function () { adapter.resolveAdapterPath(adapterConfig.path); }).not.to.throw(Error);
expect(function () { adapter.resolveAdapterPath(path.join(adapterConfig.path, 'index.js')); }).not.to.throw(Error);
});
it.skip('gets adapter prompter functions', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-conventional-changelog'),
npmName: 'cz-conventional-changelog'
};
// Install an adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', {includeCommitizen: true});
// TEST
expect(function () { adapter.getPrompter('IAMANIMPOSSIBLEPATH'); }).to.throw(Error);
expect(function () { adapter.getPrompter(adapterConfig.path); }).not.to.throw(Error);
expect(isFunction(adapter.getPrompter(adapterConfig.path))).to.be.true;
});
it('gets adapter prompter functions for default export adapters', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-conventional-changelog-default-export'),
npmName: 'cz-conventional-changelog-default-export'
};
// Install an adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog-default-export');
// TEST
expect(function () { adapter.getPrompter('IAMANIMPOSSIBLEPATH'); }).to.throw(Error);
expect(function () { adapter.getPrompter(adapterConfig.path); }).not.to.throw(Error);
expect(isFunction(adapter.getPrompter(adapterConfig.path))).to.be.true;
});
});
afterEach(function () {
this.timeout(config.maxTimeout); // this could take a while
// All this should do is archive the tmp path to the artifacts
clean.afterEach(config.paths.tmp, config.preserve);
});
after(function () {
this.timeout(config.maxTimeout); // this could take a while
// Once everything is done, the artifacts should be cleaned up based on
// the preserve setting in the config
clean.after(config.paths.tmp, config.preserve);
});
================================================
FILE: test/tests/cli.js
================================================
import { expect } from 'chai';
import proxyquire from 'proxyquire';
import sinon from 'sinon';
describe('git-cz', () => {
let bootstrap;
let fakeStrategies, fakeCommitizen;
beforeEach(() => {
fakeStrategies = {
git: sinon.spy(),
gitCz: sinon.spy()
}
fakeCommitizen = {
configLoader: {
load: sinon.stub()
}
}
bootstrap = proxyquire('../../src/cli/git-cz', {
'./strategies': fakeStrategies,
'../commitizen': fakeCommitizen
}).bootstrap;
});
describe('bootstrap', () => {
describe('when config is provided', () => {
it('passes config to useGitCzStrategy', () => {
const config = sinon.spy();
bootstrap({ config });
expect(fakeStrategies.gitCz.args[0][2]).to.equal(config);
});
});
describe('when config is not provided', () => {
describe('and the config is returned from configLoader.load', () => {
it('uses config from configLoader.load()', () => {
const config = sinon.stub();
fakeCommitizen.configLoader.load.returns(config);
bootstrap({});
expect(fakeStrategies.gitCz.args[0][2]).to.equal(config);
});
});
describe('and the config is not returned from configLoader.load', () => {
it('tells commitizen to use the git strategy', () => {
bootstrap({});
expect(fakeStrategies.git.called).to.equal(true);
});
});
});
describe('when argv is overridden', () => {
it('uses the overridden argv', () => {
bootstrap({}, ['node', 'git-cz', 'index.js']);
expect(fakeStrategies.git.args[0][0][0]).to.equal('index.js');
});
})
});
});
================================================
FILE: test/tests/commit.js
================================================
import { expect } from 'chai';
import os from 'os';
import fs from 'fs';
import path from 'path';
import inquirer from 'inquirer';
// Bootstrap our tester
import { bootstrap } from '../tester';
// Get our source files
import { addFile as gitAddFile, init as gitInit, log, whatChanged } from '../../src/git';
import { commit as commitizenCommit, init as commitizenInit } from '../../src/commitizen';
// Destructure some things for cleaner tests
let { config, repo, clean, files } = bootstrap();
let { writeFilesToPath } = files;
before(function () {
// Creates the temp path
clean.before(config.paths.tmp);
});
beforeEach(function () {
this.timeout(config.maxTimeout); // this could take a while
/* istanbul ignore next */
repo.createEndUser(config.paths.endUserRepo);
});
describe('commit', function () {
it('should commit simple messages', function (done) {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
let dummyCommitMessage = `sip sip sippin on some sizzurp`;
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'),
npmName: 'cz-jira-smart-commit'
};
// Quick setup the repos, adapter, and grab a simple prompter
let prompter = quickPrompterSetup(repoConfig, adapterConfig, dummyCommitMessage);
// TEST
// Pass in inquirer but it never gets used since we've mocked out a different
// version of prompter.
commitizenCommit(inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function () {
log(repoConfig.path, function (logOutput) {
expect(logOutput).to.have.string(dummyCommitMessage);
done();
});
});
});
it('should commit message with quotes', function (done) {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
let dummyCommitMessage = `sip \`sip\` sippin' on some "sizzurp"`;
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'),
npmName: 'cz-jira-smart-commit'
};
// Quick setup the repos, adapter, and grab a simple prompter
let prompter = quickPrompterSetup(repoConfig, adapterConfig, dummyCommitMessage);
// TEST
// Pass in inquirer but it never gets used since we've mocked out a different
// version of prompter.
commitizenCommit(inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function () {
log(repoConfig.path, function (logOutput) {
expect(logOutput).to.have.string(dummyCommitMessage);
done();
});
});
});
it('should commit multiline messages', function (done) {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Git on *nix retains spaces on lines with only spaces
// Git on win32 removes spaces from lines with only spaces
let dummyCommitMessage =
`sip sip sippin on jnkjnkjn
${(os.platform === 'win32') ? '' : ' '}
some sizzurp`;
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-conventional-changelog'),
npmName: 'cz-conventional-changelog'
};
// Quick setup the repos, adapter, and grab a simple prompter
let prompter = quickPrompterSetup(repoConfig, adapterConfig, dummyCommitMessage);
// TEST
// Pass in inquirer but it never gets used since we've mocked out a different
// version of prompter.
commitizenCommit(inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true }, function () {
log(repoConfig.path, function (logOutput) {
expect(logOutput).to.have.string(dummyCommitMessage);
done();
});
});
});
it('should allow to override git commit options', function (done) {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
let dummyCommitMessage = `sip sip sippin on some sizzurp`;
let author = `A U Thor `;
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'),
npmName: 'cz-jira-smart-commit'
};
let options = {
args: [`--author="${author}"`, '--no-edit']
};
// Quick setup the repos, adapter, and grab a simple prompter
let prompter = quickPrompterSetup(repoConfig, adapterConfig, dummyCommitMessage, options);
// TEST
// Pass in inquirer but it never gets used since we've mocked out a different
// version of prompter.
commitizenCommit(inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function () {
log(repoConfig.path, function (logOutput) {
expect(logOutput).to.have.string(author);
expect(logOutput).to.have.string(dummyCommitMessage);
done();
});
});
});
it('should respect original behavior of -a option', function (done) {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
let dummyCommitMessage = `sip sip sippin on some sizzurp`;
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
dummyfilecopy: {
contents: `duck-duck-goose`,
filename: `mydummyfilecopy.txt`,
add: false,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'),
npmName: 'cz-jira-smart-commit'
};
let options = {
args: ['-a']
};
// Quick setup the repos, adapter, and grab a simple prompter
let prompter = quickPrompterSetup(repoConfig, adapterConfig, dummyCommitMessage, options);
// TEST
// Pass in inquirer but it never gets used since we've mocked out a different
// version of prompter.
commitizenCommit(inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function () {
log(repoConfig.path, function (logOutput) {
expect(logOutput).to.have.string(dummyCommitMessage);
});
whatChanged(repoConfig.path, function (whatChangedOutput) {
expect(whatChangedOutput).to.have.string('A\t' + repoConfig.files.dummyfile.filename);
expect(whatChangedOutput).to.not.have.string('A\t' + repoConfig.files.dummyfilecopy.filename);
done();
});
});
});
it('should save directly to .git/COMMIT_EDITMSG with --hook option', function (done) {
this.timeout(config.maxTimeout);
// SETUP
let dummyCommitMessage = `doggies!`;
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: 'arf arf!',
filename: 'woof.txt'
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'),
npmName: 'cz-jira-smart-commit'
}
// Quick setup the repos, adapter, and grab a simple prompter
let prompter = quickPrompterSetup(repoConfig, adapterConfig, dummyCommitMessage);
// TEST
// This is a successful commit directly to .git/COMMIT_EDITMSG
commitizenCommit(inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true, hookMode: true }, function (err) {
const commitFilePath = path.join(repoConfig.path, '.git/COMMIT_EDITMSG')
const commitFile = fs.openSync(commitFilePath, 'r+')
let commitContents = fs.readFileSync(commitFile, { flags: 'r+' }).toString();
fs.closeSync(commitFile);
expect(commitContents).to.have.string(dummyCommitMessage);
expect(err).to.be.a('null');
done();
});
});
it('should throw error if staging area is empty', function (done) {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
let dummyCommitMessage = `one does not simply ignore the tests`;
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-gray-duck`,
filename: `mydummiestfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`,
}
}
};
// Describe an adapter
let adapterConfig = {
path: path.join(repoConfig.path, '/node_modules/cz-jira-smart-commit'),
npmName: 'cz-jira-smart-commit'
};
// Quick setup the repos, adapter, and grab a simple prompter
let prompter = quickPrompterSetup(repoConfig, adapterConfig, dummyCommitMessage);
// TEST
// Make an initial commit
commitizenCommit(inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function (error) {
// Should pass, as the files are added to the staging area
expect(error).to.be.null;
log(repoConfig.path, function (logOutput) {
expect(logOutput).to.have.string(dummyCommitMessage);
});
whatChanged(repoConfig.path, function (whatChangedOutput) {
expect(whatChangedOutput).to.have.string('A\t' + repoConfig.files.dummyfile.filename);
// Make changes and don't add them to the staging area
writeFilesToPath({
dummymodified: {
contents: repoConfig.files.dummyfile.contents + '-modified',
filename: repoConfig.files.dummyfile.filename,
add: false,
}
}, repoConfig.path);
// Define a dummy prompter
let prompter = function (cz, commit) {
commit(`${dummyCommitMessage} #2`, {});
};
commitizenCommit(inquirer, repoConfig.path, prompter, { disableAppendPaths: true, quiet: true, emitData: true }, function (error) {
// Should fail, as staging are is empty
expect(error).to.be.instanceOf(Error);
done();
});
});
});
});
});
afterEach(function () {
this.timeout(config.maxTimeout); // this could take a while
// All this should do is archive the tmp path to the artifacts
clean.afterEach(config.paths.tmp, config.preserve);
});
after(function () {
this.timeout(config.maxTimeout); // this could take a while
// Once everything is done, the artifacts should be cleaned up based on
// the preserve setting in the config
clean.after(config.paths.tmp, config.preserve);
});
/**
* This is just a helper for testing. NOTE that prompter
* prompter is overriden for testing purposes.
*/
function quickPrompterSetup (repoConfig, adapterConfig, commitMessage, options = {}) {
commitizenInit(repoConfig.path, adapterConfig.npmName);
// NOTE:
// In our real code we'd use this here but since we're testing,
// we'll provide prompter. We'd normally use:
// let prompter = getPrompter(adapterConfig.path);
let prompter = function (cz, commit) {
commit(commitMessage, options);
}
gitInit(repoConfig.path);
writeFilesToPath(repoConfig.files, repoConfig.path);
for (let key in repoConfig.files) {
let file = repoConfig.files[key];
if (file.add !== false) {
gitAddFile(repoConfig.path, file.filename);
}
}
// NOTE: In the real world we would not be returning
// this we would instead be just making the commented
// out getPrompter() call to get user input (above).
return prompter;
}
================================================
FILE: test/tests/configLoader.js
================================================
import path from 'path';
import { expect } from 'chai';
import { getContent, getNormalizedConfig } 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('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('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' });
});
});
================================================
FILE: test/tests/index.js
================================================
import './adapter';
import './cli';
import './commit';
import './configLoader';
import './init';
import './parsers';
import './staging';
import './util';
================================================
FILE: test/tests/init.js
================================================
import { expect } from 'chai';
import semver from 'semver';
// TODO: augment these tests with tests using the actual cli call
// For now we're just using the library, which is probably fine
// in the short term
import { init as commitizenInit } from '../../src/commitizen';
// Bootstrap our tester
import { bootstrap } from '../tester';
// Destructure some things based on the bootstrap process
let { config, repo, clean, util } = bootstrap();
before(function () {
// Creates the temp path
clean.before(config.paths.tmp);
});
beforeEach(function () {
this.timeout(config.maxTimeout); // this could take a while
repo.createEndUser(config.paths.endUserRepo);
});
describe('init', function () {
it('installs an adapter with --save-dev', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Install an adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog');
// TEST
// Check resulting json
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
expect(packageJson).to.have.nested.property('devDependencies.cz-conventional-changelog');
});
it('installs an adapter with --save', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Install an adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { save: true, saveDev: false });
// TEST
// Check resulting json
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
expect(packageJson).to.have.nested.property('dependencies.cz-conventional-changelog');
});
it('errors on previously installed adapter', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { saveDev: true });
// TEST
// Adding a second adapter
expect(function () {
commitizenInit(config.paths.endUserRepo, 'cz-jira-smart-commit', { saveDev: true });
}).to.throw(/already configured/);
// Check resulting json
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
expect(packageJson).not.to.have.nested.property('devDependencies', 'cz-jira-smart-commit');
expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-conventional-changelog');
// TODO: Eventually may need to offer both path and package keys. package = npm package name
// Path for local development
});
it('succeeds if force is true', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { saveDev: true });
// TEST
// Adding a second adapter
expect(function () {
commitizenInit(config.paths.endUserRepo, 'cz-jira-smart-commit', { saveDev: true, force: true });
}).to.not.throw();
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
expect(packageJson.devDependencies).to.have.property('cz-jira-smart-commit');
expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-jira-smart-commit');
});
it('installs an adapter without --save-exact', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog');
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
// TEST
expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog');
let range = packageJson.devDependencies['cz-conventional-changelog'];
// It should satisfy the requirements of a range
expect(semver.validRange(range)).to.not.equal(null);
// // But you CAN NOT increment a range
// expect(semver.inc(range, 'major')).to.equal(null);
// TODO: We need to figure out how to check if the repo has save exact set
// in the config before we can re-enable this. The --save-exact setting
// in our package.json breaks this test
});
it('installs an adapter with --save-exact', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { saveExact: true });
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
// TEST
expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog');
let range = packageJson.devDependencies['cz-conventional-changelog'];
// It should satisfy the requirements of a range
expect(semver.validRange(range)).to.not.equal(null);
// But you CAN increment a single version
expect(semver.inc(range, 'major')).not.to.equal(null);
});
it('installs an commitizen with includeCommitizen', function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { includeCommitizen: true });
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
// TEST
expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog');
expect(packageJson.devDependencies).to.have.property('commitizen');
let range = packageJson.devDependencies['cz-conventional-changelog'];
// It should satisfy the requirements of a range
expect(semver.validRange(range)).to.not.equal(null);
// But you CAN increment a single version
expect(semver.inc(range, 'major')).not.to.equal(null);
});
const supportedPackageManagers = ['yarn', 'pnpm'];
supportedPackageManagers.forEach((packageManger) => {
describe(`alternative package managers: ${packageManger}`, () => {
it(`installs an adapter with ${packageManger}`, function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Install an adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { [packageManger]: true });
// TEST
// Check resulting json
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
if (packageManger === 'yarn') {
expect(packageJson).to.have.nested.property('dependencies.cz-conventional-changelog');
} else {
expect(packageJson).to.have.nested.property('devDependencies.cz-conventional-changelog');
}
});
it(`installs an adapter with ${packageManger} --dev`, function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Install an adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { [packageManger]: true, dev: true });
// TEST
// Check resulting json
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
expect(packageJson).to.have.nested.property('devDependencies.cz-conventional-changelog');
});
it(`errors (with ${packageManger}) on previously installed adapter`, function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { [packageManger]: true, dev: true });
// TEST
// Adding a second adapter
expect(function () {
commitizenInit(config.paths.endUserRepo, 'cz-jira-smart-commit', { [packageManger]: true, dev: true });
}).to.throw(/already configured/);
// Check resulting json
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
expect(packageJson).not.to.have.nested.property('devDependencies', 'cz-jira-smart-commit');
expect(packageJson).to.have.nested.property(
'config.commitizen.path',
'./node_modules/cz-conventional-changelog'
);
// TODO: Eventually may need to offer both path and package keys. package = npm package name
// Path for local development
});
it(`succeeds (with ${packageManger}) if force is true`, function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { [packageManger]: true, dev: true });
// TEST
// Adding a second adapter
expect(function () {
commitizenInit(config.paths.endUserRepo, 'cz-jira-smart-commit', {
[packageManger]: true,
dev: true,
force: true,
});
}).to.not.throw();
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
expect(packageJson.devDependencies).to.have.property('cz-jira-smart-commit');
expect(packageJson).to.have.nested.property('config.commitizen.path', './node_modules/cz-jira-smart-commit');
});
it(`installs (with ${packageManger}) an adapter without --save-exact`, function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', { [packageManger]: true, dev: true });
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
// TEST
expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog');
let range = packageJson.devDependencies['cz-conventional-changelog'];
// It should satisfy the requirements of a range
expect(semver.validRange(range)).to.not.equal(null);
// // But you CAN NOT increment a range
// expect(semver.inc(range, 'major')).to.equal(null);
// TODO: We need to figure out how to check if the repo has save exact set
// in the config before we can re-enable this. The --save-exact setting
// in our package.json breaks this test
});
it(`installs an adapter with ${packageManger} --exact`, function () {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Add a first adapter
commitizenInit(config.paths.endUserRepo, 'cz-conventional-changelog', {
[packageManger]: true,
dev: true,
exact: true,
});
let packageJson = util.getParsedPackageJsonFromPath(config.paths.endUserRepo);
// TEST
expect(packageJson.devDependencies).to.have.property('cz-conventional-changelog');
let range = packageJson.devDependencies['cz-conventional-changelog'];
// It should satisfy the requirements of a range
expect(semver.validRange(range)).to.not.equal(null);
// But you CAN increment a single version
expect(semver.inc(range, 'major')).not.to.equal(null);
});
});
});
});
afterEach(function () {
this.timeout(config.maxTimeout); // this could take a while
// All this should do is archive the tmp path to the artifacts
clean.afterEach(config.paths.tmp, config.preserve);
});
after(function () {
this.timeout(config.maxTimeout); // this could take a while
// Once everything is done, the artifacts should be cleaned up based on
// the preserve setting in the config
clean.after(config.paths.tmp, config.preserve);
});
================================================
FILE: test/tests/parsers.js
================================================
import { expect } from 'chai';
import { gitCz as gitCzParser, commitizen as commitizenParser } from '../../src/cli/parsers';
describe('parsers', () => {
describe('git-cz', () => {
it('should parse --message "Hello, World!"', () => {
expect(gitCzParser.parse(['--amend', '--message', 'Hello, World!'])).to.deep.equal(['--amend']);
});
it('should parse --message="Hello, World!"', () => {
expect(gitCzParser.parse(['--amend', '--message=Hello, World!'])).to.deep.equal(['--amend']);
});
it('should parse -amwip', () => {
expect(gitCzParser.parse(['-amwip'])).to.deep.equal(['-a']);
});
it('should parse -am=wip', () => {
expect(gitCzParser.parse(['-am=wip'])).to.deep.equal(['-a']);
});
it('should parse -am wip', () => {
expect(gitCzParser.parse(['-am', 'wip'])).to.deep.equal(['-a']);
});
it('should parse -a -m wip -n', () => {
expect(gitCzParser.parse(['-a', '-m', 'wip', '-n'])).to.deep.equal(['-a', '-n']);
});
it('should parse -a -m=wip -n', () => {
expect(gitCzParser.parse(['-a', '-m=wip', '-n'])).to.deep.equal(['-a', '-n']);
});
});
describe('commitizen', () => {
it('should parse out the --amend option', () => {
expect(commitizenParser.parse(['--amend'])).to.deep.equal({ _: [], amend: true })
});
it('should parse out the --hook option', () => {
expect(commitizenParser.parse(['--hook'])).to.deep.equal({ _: [], hook: true })
});
});
});
================================================
FILE: test/tests/staging.js
================================================
import { expect } from 'chai';
// Bootstrap our tester
import { bootstrap } from '../tester';
// Get our source files
import { init as gitInit, addPath as gitAdd } from '../../src/git';
import { staging } from '../../src/commitizen';
// Destructure some things for cleaner tests
let { config, repo, clean, files } = bootstrap();
let { writeFilesToPath } = files;
before(function () {
// Creates the temp path
clean.before(config.paths.tmp);
});
beforeEach(function () {
this.timeout(config.maxTimeout); // this could take a while
repo.createEndUser(config.paths.endUserRepo);
});
describe('staging', function () {
it('should determine if a repo is clean', function (done) {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-goose`,
filename: `mydummyfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
gitInit(repoConfig.path);
staging.isClean('./@this-actually-does-not-exist', function (stagingError) {
expect(stagingError).to.be.an.instanceof(Error);
staging.isClean(repoConfig.path, function (stagingIsCleanError, stagingIsClean) {
expect(stagingIsCleanError).to.be.null;
expect(stagingIsClean).to.be.true;
writeFilesToPath(repoConfig.files, repoConfig.path);
gitAdd(repoConfig.path);
staging.isClean(repoConfig.path, function (afterWriteStagingIsCleanError, afterWriteStagingIsClean) {
expect(afterWriteStagingIsCleanError).to.be.null;
expect(afterWriteStagingIsClean).to.be.false;
writeFilesToPath({
dummymodified: {
contents: repoConfig.files.dummyfile.contents + '-modified',
filename: repoConfig.files.dummyfile.filename,
}
}, repoConfig.path);
staging.isClean(repoConfig.path, function (afterWriteStagingIsCleanError, afterWriteStagingIsClean) {
expect(afterWriteStagingIsCleanError).to.be.null;
expect(afterWriteStagingIsClean).to.be.false;
done();
});
});
});
});
});
it('should determine if --all flag adds files to staging area', function (done) {
this.timeout(config.maxTimeout); // this could take a while
// SETUP
// Describe a repo and some files to add and commit
let repoConfig = {
path: config.paths.endUserRepo,
files: {
dummyfile: {
contents: `duck-duck-gray-duck`,
filename: `mydummiestfile.txt`,
},
gitignore: {
contents: `node_modules/`,
filename: `.gitignore`
}
}
};
gitInit(repoConfig.path);
staging.isClean(repoConfig.path, function (stagingIsCleanError, stagingIsClean) {
expect(stagingIsCleanError).to.be.null;
expect(stagingIsClean).to.be.true;
writeFilesToPath(repoConfig.files, repoConfig.path);
staging.isClean(repoConfig.path, function (afterWriteStagingIsCleanError, afterWriteStagingIsClean) {
expect(afterWriteStagingIsCleanError).to.be.null;
expect(afterWriteStagingIsClean).to.be.true;
done();
});
}, true);
});
});
afterEach(function () {
this.timeout(config.maxTimeout); // this could take a while
// All this should do is archive the tmp path to the artifacts
clean.afterEach(config.paths.tmp, config.preserve);
});
after(function () {
this.timeout(config.maxTimeout); // this could take a while
// Once everything is done, the artifacts should be cleaned up based on
// the preserve setting in the config
clean.after(config.paths.tmp, config.preserve);
});
================================================
FILE: test/tests/util.js
================================================
import { expect } from 'chai';
import { isFunction } from '../../src/common/util';
describe('common util', function () {
it('isFunction determines if a function is passed', function () {
// Truthies
expect(isFunction(function () {})).to.be.true;
expect(isFunction(new Function())).to.be.true;
// Falsies
expect(isFunction(undefined)).to.be.false;
expect(isFunction(null)).to.be.false;
expect(isFunction(49)).to.be.false;
expect(isFunction([])).to.be.false;
expect(isFunction({})).to.be.false;
expect(isFunction("asdf")).to.be.false;
expect(isFunction(true)).to.be.false;
expect(isFunction(false)).to.be.false;
expect(isFunction(Symbol('test'))).to.be.false;
});
});
================================================
FILE: test/tools/clean.js
================================================
import * as path from 'path';
import fs from 'fs-extra';
import { v4 as uuidv4} from 'uuid';
export {
before,
after,
afterEach
};
// Unique id for each 'run' of the entire test suite
let testSuiteRunId = uuidv4();
// At the beginning of a run purge .tmp
function before (tmpPath) {
cleanPath(tmpPath);
// clean(tmpPath, 'all');
}
function afterEach (tmpPath, preserve) {
if (preserve !== false) {
archive(tmpPath, testSuiteRunId);
}
cleanPath(tmpPath);
}
// After should listen to the user via the config
// Before should always purge .tmp irregardless of config
function after (tmpPath, preserve) {
clean(tmpPath, preserve);
}
/**
* Copies the .tmp folder to the artifacts folder,
* then clears the .tmp folder
*
* Generally should be run in afterEach()
*/
function archive (tmpPath, testSuiteRunId) {
let destinationPath = path.resolve(tmpPath + '/../artifacts/' + testSuiteRunId + '/' + uuidv4());
fs.mkdirSync(destinationPath, { recursive: true });
fs.copySync(tmpPath, destinationPath);
}
/**
* Cleans up the artifacts folder
*
* Generally called in after()
*/
function clean (tmpPath, preserve) {
/**
* If preserve is a normal integer over 0 thats how many results to keep.
* If string 'all' then keep all
* Else: don't preserve anything
*/
if (preserve === 'all') {
/**
* Preserve all artifacts
* Don't purge any artifacts
*
* BEWARE: this can fill the disk up over time
*/
return;
} else if (isNormalNonZeroInteger(preserve)) {
/**
* Preserve a specific number of artifacts
*
* 1 = keep only th last run
* 2 = keep the last run and the one before it, purging any that happened beforehand
*/
// Set the path
let artifactsBasePath = path.resolve(tmpPath + '/../artifacts');
// The the files in this path
let artifactFolders = fs.readdirSync(artifactsBasePath);
// Reverse chronologially sort the files
artifactFolders.sort(function (a, b) {
return fs.statSync(path.resolve(artifactsBasePath, b)).mtime.getTime() - fs.statSync(path.resolve(artifactsBasePath, a)).mtime.getTime();
});
// Keep only the number of files defined in the config setting 'preserve'.
keep(artifactsBasePath, artifactFolders, preserve);
}
// Always purge tmp, it needs to be empty for next run
cleanPath(tmpPath);
}
function isNormalNonZeroInteger (str) {
if (Number.isInteger(str) && str > 0) { // Check for integers above 0
return str;
} else { // Check for strings that cast to ints that are above 0
var n = ~~Number(str);
return String(n) === str && n > 0;
}
}
/**
* Given a reverse chronological array of paths
* This deletes all files except for n of them
*
* n is the (1 indexed) count of files to keep.
*/
function keep (basePath, paths, n) {
for (let i = paths.length; i > n; i--) {
fs.removeSync(path.resolve(basePath, paths[i - 1]));
}
}
function cleanPath (tmpPath) {
fs.removeSync(tmpPath);
fs.mkdirSync(tmpPath);
}
================================================
FILE: test/tools/files.js
================================================
import fs from 'fs';
import path from 'path';
import _ from 'lodash';
export {
writeFilesToPath
};
/**
* Opinionated writing of files to a path.
*
* Expects files to be an object where each sub
* object has properties filename and contents.
*/
function writeFilesToPath (files, directoryPath) {
_.forOwn(files, function (key, value) {
fs.writeFileSync(path.resolve(directoryPath, files[value].filename), files[value].contents);
});
}
================================================
FILE: test/tools/repo.js
================================================
import childProcess from 'child_process';
import fs from 'fs';
export {
createEmpty,
createEndUser
};
/**
* Create an empty repo
*/
function createEmpty (path) {
fs.mkdirSync(path, { recursive: true });
childProcess.spawnSync('npm', ['init', '--force', '--yes'], { cwd: path, shell: true });
}
/**
* Create a new repo to hold an end user app
*/
function createEndUser (path) {
createEmpty(path);
}