Compare commits

..
108 Commits
Author SHA1 Message Date
Pierre VanduynslagerandGregor Martynus 0d2d1f2376 fix: fix the --no-ci arg parsing
The `noCi` is no properly set based on the `--no-ci` CLI arg and it is overwritten by the `noCi` option
2018-01-24 22:22:16 -08:00
Pierre VanduynslagerandGregor Martynus 7e860c7915 docs(travis): recommend to use the deploy step instead of script
The `script` step can be used with Build Stage if `semantic-release` is the only `script` ran in the `release` stage.

See https://github.com/travis-ci/travis-ci/issues/1066
2018-01-21 15:00:05 -08:00
Pierre VanduynslagerandGregor Martynus e0fa20b8a0 ci(travis): use Build Stages 2018-01-21 15:00:05 -08:00
Pierre Vanduynslager fa2ca8a34b fix(package): update lodash to version 4.17.4 2018-01-20 17:23:45 -05:00
greenkeeper[bot]andPierre Vanduynslager 51c02b9dbc fix(package): update cosmiconfig to version 4.0.0 2018-01-17 10:37:44 -05:00
mpuelsandGregor Martynus 0c1f0a1ba7 docs: typo 2018-01-15 14:15:45 -08:00
Pierre VanduynslagerandGregor Martynus cc0c312a9d fix: set node minimum version to 8.3
The minimum Node version supported is 8.3 as we use Object properties spread.
2018-01-13 12:49:19 -08:00
greenkeeper[bot]andPierre Vanduynslager 93173e2c28 fix(package): update execa to version 0.9.0 2018-01-12 09:18:29 -05:00
greenkeeper[bot]andPierre Vanduynslager 48ade92b81 chore(package): update prettier to version 1.10.0 2018-01-11 11:01:04 -05:00
Pierre Vanduynslager 49ad198e35 docs(contrib): add atomic commits requirement 2018-01-07 20:48:19 -05:00
Pierre Vanduynslager adbcca6c52 docs: add issue template 2018-01-06 19:21:00 -05:00
Pierre Vanduynslager e0b4e6ac78 docs: add CONTRIBUTING guidelines 2018-01-06 19:21:00 -05:00
Pierre Vanduynslager 53f3de6786 feat: allow to exclude commits from analysis 2018-01-06 00:11:20 -05:00
Pierre Vanduynslager fd54eead6f docs: update Yarn FAQ 2018-01-05 23:10:49 -05:00
Pierre Vanduynslager ba79c8590a docs: typos. clarifications 2018-01-05 18:58:22 -05:00
Pierre Vanduynslager 75778bcea4 docs: troubleshooting 2018-01-05 18:58:22 -05:00
Pierre Vanduynslager d6c398fd8b docs: add heading anchor 2018-01-05 18:58:22 -05:00
Pierre Vanduynslager fdb995f77d docs: publish with gitbook 2018-01-05 16:05:30 -05:00
Pierre Vanduynslager ed89361d7c docs: documentation improvements
**Refactor and clarify the documentation in `README.md`**
- Add Highlights
- Add a Table of contents
- Clarify the way semantic-release works
- Clarify relationship with the CI environments
- Describe local install for Node projects (with a `package.json`) and global install for non-JavaScript projects
- Explain CI general configuration (environment variables and a run after all jobs are successful)
- Clarify configuration (via config file or CLI arguments)
- Clarify plugin roles and configuration
- Add doc for shareable configuration
- Add recipes
- Add resources (Videos, articles, tutorials)
- Add a Support section
- Add a Team section

**Add the following FAQs**
- How can I use a npm build script that requires the `package.json`’s version ?
- Can I use Semantic-release with Yarn?
- Can I use Semantic-release to publish non-JavaScript packages?
- Can I use Semantic-release with any CI service?
- Can I use Semantic-release with any GitLab?
- Can I use Semantic-release with any Git hosted environment?
- Can I skip the release to the npm registry?
- Can I use .npmrc options?
- How can I set the access level of the published npm package?
- Can I use Semantic-release to publish a package on Artifactory?
- Can I set the initial release version of my package to 0.0.1?
- Why does semantic-release require Node version >= 8?

**Clarify Nove 8 requirement and solutions**
- Add Node version requirement explanation and solutions
- [X] Display a link to the documentation when running on Node < 8 version

**Add recipes**
- Travis
- GitLab CI
- Travis with build stages - To be done in #573
- CircleCI workflows - To be done in #573
2018-01-05 16:05:30 -05:00
simluandPierre Vanduynslager f4d9ebeef7 fix(security): Updated marked dependency
The marked dependency defined in package-lock.json has a known moderate severity security vulnerability in version range < 0.3.9 and should be updated.
2018-01-05 15:48:41 -05:00
Pierre Vanduynslager 5bc46a08cf feat: allow to release from local machine 2018-01-02 14:31:43 -05:00
Pierre Vanduynslager 5cc62e49ee test: add missing mockserver mocks 2018-01-01 20:20:19 -05:00
Pierre Vanduynslager 95de6a5c80 test: update test for @semantic-release/github@3.0.1 2018-01-01 20:20:19 -05:00
greenkeeper[bot]andPierre Vanduynslager 7eded2f018 chore(package): update @semantic-release/github to version 3.0.1 2018-01-01 20:20:19 -05:00
Pierre Vanduynslager 3c80fd2bf1 docs: update badges
Include npm version badges for both `@latest` and `@next` dist-tag
2017-12-31 00:39:27 -05:00
Pierre Vanduynslager e145134a62 ci: fix travis-deploy-once install cmd 2017-12-31 00:08:21 -05:00
Pierre Vanduynslager 8d575654c2 feat: make semantic-release CI agnostic
- Remove `@semantic-release/condition-travis` from the default plugins
- Verify the current branch in the core
- Verify the build is not triggered by a PR in the core
- Run in dry-run mode if not triggered on CI
- Dry-run mode runs the `verifyConditions` plugins, allowing to detect configuration error locally
- Return without error when no version has to be released due to no changes
- Return without error if the build is triggered from a PR
- Return without error if the current branch is not the configured branch
- CLI return with exit code 1 if there is a `semanticReleaseError`, allowing to fail builds in case of config error, missing token etc...

BREAKING CHANGE: `semantic-release` doesn't make sure it runs only on one Travis job anymore.
The CI configuration has to be done such that `semantic-release`
- runs only once per build
- runs only after all tests are successful on every jobs of the build
- runs on Node >=8

This can easily be done with [travis-deploy-once](https://github.com/semantic-release/travis-deploy-once).

Migration Guide

Modify your `.travis.yml` to use `travis-deploy-once`.
Replace:
```yaml
after_success:
  - npm run semantic-release
```
by:
Replace
```yaml
after_success:
  - npm install -g travis-deploy-once@4
  - travis-deploy-once "npm run semantic-release"
```
2017-12-30 23:15:25 -05:00
Pierre Vanduynslager 996305d69c feat: move npm workaround for missing gitHead to the npm plugin 2017-12-30 21:17:04 -05:00
Pierre Vanduynslager 754b420fd6 feat: support sharable configuration
Adds the options `extends`, which can be defined via configuration file or CLI arguments to a single path or an array of paths of shareable configuration.
A shareable configuration is a file or a module that can be loaded with `require`.
Options is defined by merging in the following order of priority:
- CLI/API
- Configuration file
- Shareable configuration (from right to left)

Options set in a shareable configuration can be unset by setting it to `null` or `undefined` in the main configuration file. If a default value applies to this property it will be used.
2017-12-22 14:22:30 -05:00
Pierre Vanduynslager 2fc538b607 test: add test for missing custom plugin modules 2017-12-22 14:22:30 -05:00
Pierre Vanduynslager f707b1a90a feat: allow to define plugin options globally 2017-12-22 14:22:30 -05:00
greenkeeper[bot]andPierre Vanduynslager d28b7e3e07 fix(package): update @semantic-release/github to version 3.0.0 2017-12-22 13:26:00 -05:00
greenkeeper[bot]andPierre Vanduynslager e00dd160c7 chore(package): update @semantic-release/github to version 2.2.3 2017-12-17 00:25:54 -05:00
Pierre Vanduynslager 3316f1a79e test: add a delay after starting the npm registry
Attempt at improving test reliability on CI
2017-12-14 11:44:24 -05:00
Pierre Vanduynslager 8942093c18 test: limit information stored in context
Store only objects set in `beforeEach` used in `test`.
Avoid logging useless info on test failure.
2017-12-14 11:44:24 -05:00
greenkeeper[bot]andPierre Vanduynslager 1b8aa95a6e chore(package): update prettier to version 1.9.2 2017-12-12 00:01:12 -05:00
greenkeeper[bot]andPierre Vanduynslager 624ee88abd chore(package): update fs-extra to version 5.0.0 2017-12-11 15:02:29 -05:00
Pierre Vanduynslager 4053d8f7fb fix: log plugin type in addition of path 2017-12-10 04:03:32 -05:00
greenkeeper[bot]andPierre Vanduynslager 88f33ec482 chore(package): update mockserver-client to version 5.1.1 2017-12-06 16:29:19 -05:00
Pierre Vanduynslager 0761ef378a style: update to prettier@1.9.0 2017-12-05 10:03:18 -05:00
greenkeeper[bot]andPierre Vanduynslager f30fb6c8af chore(package): update prettier to version 1.9.0 2017-12-05 10:03:18 -05:00
Hutson BettsandGregor Martynus 0113db2e06 docs(README): add node support policy
Add a _Node Support Policy_ section to the project's `README.md` file
to indicate what this project, and its core team, are promising in terms
of Node runtime support.

Establishing a support policy provides reassurance to the community that
they can expect a level of functionality from `semantic-release`, while
providing guidance to the core maintainers, and everyone else that
contributes, the level of support they should espire to.

Closes #485
2017-12-01 15:39:21 -08:00
Pierre Vanduynslager eec4e68615 test: Isolate environment variables passed to semantic-release
`npm` is called through `semantic-release` and in the integration test to make some assertion.
By isolating the the environment variables passed to `semantic-release` it's easier to avoid a mistake that would pass the test environment that contains is own auth variables.
2017-11-29 18:06:14 -05:00
Pierre Vanduynslager 8371a03da0 test: Verify Error instance type and SemanticReleaseError name 2017-11-29 18:06:14 -05:00
Pierre Vanduynslager 2491032a99 test: Add test to check unexpected plugin return values 2017-11-29 18:06:14 -05:00
Pierre Vanduynslager 02ddf34f21 Fix: Remove redundant test of commitAnalyzer plugin output 2017-11-29 18:06:14 -05:00
Pierre Vanduynslager 685959107b chore: Clean up mistakenly added configs 2017-11-29 18:06:14 -05:00
Pierre Vanduynslager 613a646363 fix: Typo in error messages 2017-11-29 18:06:14 -05:00
Pierre Vanduynslager d7b323dd00 fix: Accept undefined values for the getLastRelease and generateNotes plugins
Adapt tests and default value to the plugin definitions (`definitions.js`)
2017-11-29 18:06:14 -05:00
Pierre Vanduynslager a7359bffb6 test: Improve docker start/stop script
- Simplify the loop that check availability
- Increase timeout
- Remove the container after stopping
2017-11-29 18:06:14 -05:00
Pierre Vanduynslager fcb832bbe1 fix: remove name from log as it's not an existing option anymore 2017-11-29 18:06:14 -05:00
greenkeeper[bot]andPierre Vanduynslager 89f5e07408 chore(package): update ava to version 0.24.0 2017-11-27 15:22:17 -05:00
Pierre Vanduynslager ce3841f553 test: Ignore the ~/.npmrc file during tests
When the test are run npm read the ~/.npmrc and ./.npmrc files and set some environment variables starting with `npm_`.
When the test create temporary folders and created a `.npmrc` the values there are ignored as the environment variables take precedence.
This commit remove this environment variable (from the local `process.env`) before starting the integrations test and restore them after. This way the `./.npmrc` files created in temp directory for the test are correctly used.
2017-11-25 14:50:44 -05:00
Pierre Vanduynslager 40c58c9b42 ci: Run npm registry in Docker 2017-11-25 14:50:44 -05:00
Pierre Vanduynslager 0c67ba517f feat: Make semantic-release language agnostic
- Do not rely on `package.json` anymore
- Use `cosmiconfig` to load the configation. `semantic-release` can be configured:
  - via CLI options (including plugin names but not plugin options)
  - in the `release` property of `package.json` (as before)
  - in a `.releaserc.yml` or `.releaserc.js` or `.releaserc.js` or `release.config.js` file
  - in a `.releaserc` file containing `json`, `yaml` or `javascript` module
- Add the `repositoryUrl` options (used across `semantic-release` and plugins). The value is determined from CLi option, or option configuration, or package.json or the git remote url
- Verifies that `semantic-release` runs from a git repository
- `pkg` and `env` are not passed to plugin anymore
- `semantic-release` can be run both locally and globally. If ran globally with non default plugins, the plugins can be installed both globally or locally.

BREAKING CHANGE: `pkg` and `env` are not passed to plugin anymore.
Plugins relying on a `package.json` must verify the presence of a valid `package.json` and load it.
Plugins can use `process.env` instead of `env`.
2017-11-24 21:56:15 -05:00
Pierre Vanduynslager 5bec59b26b feat: Expect plugins to return Promises
BREAKING CHANGE: Each plugin is expected to return an async function or a Promise returning function. The callback parameter is not passed to plugins anymore.
2017-11-24 21:56:15 -05:00
Pierre Vanduynslager d4c7605f68 fix: Use default plugin if the path property is missing from a single plugin configuration 2017-11-22 19:47:09 -05:00
Pierre Vanduynslager facdadaddb ci: Lint with XO 2017-11-21 20:55:47 -05:00
Pierre Vanduynslager d548edcf37 feat: Extract npm and github publish to plugins
- Add a new plugin type: `publish`
- Add support for multi-plugin. A plugin module can now return an object with a property for each plugin type
- Uses by default [npm](https://github.com/semantic-release/npm) and [github](https://github.com/semantic-release/github) in addition of Travis for the verify condition plugin
- Uses by default [npm](https://github.com/semantic-release/npm) and [github](https://github.com/semantic-release/github) for the publish plugin
- `gitTag` if one can be found is passed to `generateNotes` for both `lastRelease` and `nextRelease`
- `semantic-release` now verifies the plugin configuration (in the `release` property of `package.json`) and throws an error if it's invalid
- `semantic-release` now verifies each plugin output and will throw an error if a plugin returns an unexpected value.

BREAKING CHANGE: `githubToken`, `githubUrl` and `githubApiPathPrefix` have to be set at the [github](https://github.com/semantic-release/github) plugin level. They can be set via `GH_TOKEN`, `GH_URL` and `GH_PREFIX` environment variables.

BREAKING CHANGE: the `npm` parameter is not passed to any plugin anymore. Each plugin have to read `.npmrc` if they needs to (with https://github.com/kevva/npm-conf for example).
2017-11-21 16:41:04 -05:00
Pierre Vanduynslager 991a7b5f97 refactor: Simplify file tree 2017-11-21 16:41:04 -05:00
Gregor MartynusandGitHub 332608378a docs(README) fix plugin anchor links (#504) 2017-11-21 10:15:01 -08:00
Matt ZiemerandGregor Martynus 018835f56d docs(README): typo (#516) 2017-11-21 10:03:16 -08:00
greenkeeper[bot]andPierre Vanduynslager c8748ad0e2 chore(package): update dependencies 2017-11-21 12:50:10 -05:00
Josh DuffandPierre Vanduynslager a4951b7c30 fix(docs): remove unnecessary backticks in readme 2017-11-10 12:31:53 -05:00
Pierre Vanduynslager 17a600672f style: Update style for Prettier 1.8.0 2017-11-07 00:34:16 -05:00
greenkeeper[bot]andPierre Vanduynslager 470697c01d chore(package): update prettier to version 1.8.0 2017-11-07 00:34:16 -05:00
Gregor MartynusandGitHub 94b00e21c7 chore(airtable-crm): initial configuration 2017-11-03 16:02:10 -07:00
Pierre VanduynslagerandGregor Martynus d0180c4348 feat: Additional commit information
Add `author`, `commiter`, `gitTags` and `committerDate` to the commit object passed to plugin
2017-10-29 20:01:16 -07:00
greenkeeper[bot]andPierre Vanduynslager 186950acc0 fix(package): update @semantic-release/commit-analyzer to version 4.0.0 2017-10-29 21:19:27 -04:00
Pierre VanduynslagerandGregor Martynus c90765e10d fix: Include Error properties in logs 2017-10-29 14:37:05 -07:00
Pierre VanduynslagerandGregor Martynus ad2e1d76b7 test: Fix typos: only in tests and useless console.log() 2017-10-29 14:37:05 -07:00
Pierre VanduynslagerandGregor Martynus 65d344bae8 fix: Check SemanticReleaseError by error.semanticRelease property 2017-10-29 14:37:05 -07:00
greenkeeper[bot]andGregor Martynus 8a1dd7b324 fix(package): update @semantic-release/release-notes-generator to version 5.0.0 2017-10-28 22:17:45 -07:00
Pierre-Denis VanduynslagerandGregor Martynus e2a8a5cd32 feat: Refactor CLI to run with one command, improve logs, modularize, add tests
- Run with one command and do not rely on error exit codes to stop the process when a release is not necessary
- Break `index.js` in smaller modules in order to improve testability and simplify the code
- Add several missing unit and integration tests to reach 100% coverage
- Integration tests now test end to end, including publishing to Github (with http://www.mock-server.com on Docker)
- Use `tj/commander.js` to print an help message, verify and parse CLI arguments
- Semantic-release can now be called via Javascript API: `require('semantic-release')(options)`
- Remove npmlog dependency and add more log messages
- Logger is now passed to plugins
- Add debug logs with `visionmedia/debug`. `debug` is enabled for both semantic-release and plugins with `--debug`
- Use `kevva/npm-conf` in place of the deprecated `npm/npmconf`
- Pass lastRelease, nextRelease and commits to generate-notes plugin
- In dry-run mode, print the release note instead of publishing it to Github as draft, and skip the CI verifications
- The dry-run mode does not require npm and Github TOKEN to be set anymore and can be run locally

BREAKING CHANGE: Semantic-Release must now be executed with `semantic-release` instead of `semantic-release pre && npm publish && semantic-release post`.
BREAKING CHANGE: The `semantic-release` command now returns with exit code 0 on expected exception (no release has to be done, running on a PR, gitHead not found, other CI job failed etc...). It only returns with 1 when there is an unexpected error (code error in a plugin, plugin not found, git command cannot be run etc..).
BREAKING CHANGE: Calling the `semantic-release` command with unexpected argument(s) now exit with 1 and print an help message.
BREAKING CHANGE: Semantic-Release does not rely on `npmlog` anymore and the log level cannot be configured. Debug logs can be activated with CLI option `--debug` or with environment variable `DEBUG=semantic-release:*`
BREAKING CHANGE: The CLI options `--debug` doesn't enable the dry-run mode anymore but activate the debugs. The dry run mode is now set with the CLI command `--dry-run` or `-d`.
2017-10-27 18:07:13 -07:00
Gregor Martynus 1bd095d26c chore(CODE_OF_CONDUCT): Contributor Covenant 2017-10-25 17:38:56 -07:00
greenkeeper[bot]andPierre Vanduynslager 16a02e523e fix(package): update github to version 12.0.0 2017-10-25 10:35:57 -04:00
greenkeeper[bot]andGregor Martynus 51e7579c69 chore(package): update ava to version 0.23.0 2017-10-24 14:11:22 -07:00
greenkeeper[bot]andPierre Vanduynslager acddd5a12f chore(package): update codecov to version 3.0.0 2017-10-23 11:04:25 -04:00
Jacob WejendorpandPierre Vanduynslager f6aacd2fe0 fix: Log error messages on reject 2017-10-23 10:43:56 -04:00
Pierre-Denis VanduynslagerandGregor Martynus b0bc49063b fix: handle errors when verifyConditions and verifyRelease are a pipeline 2017-10-18 14:00:20 -07:00
Pierre-Denis VanduynslagerandGregor Martynus 580ad9c3d2 feat: Allow to recover from ENOTINHISTORY with a tag and handle detached head repo
- Tag sha will now be used also if there is a gitHead in last release and it's not in the history
- Use `git merge-base` to determine if a commit is in history, allowing to use CI creating detached head repo
- Mention recovery solution by creating a version tag in `ENOTINHISTORY` and `ENOGITHEAD` error messages
- Do not mention branches containing missing commit in `ENOTINHISTORY` and `ENOGITHEAD` error messages as it's not available by default on most CI
2017-10-11 20:54:10 -07:00
Pierre-Denis VanduynslagerandGregor Martynus 8e9d9f77f3 fix: Always pass pluginConfig to plugins as a defined object 2017-10-06 10:28:37 -07:00
Pierre-Denis Vanduynslager 90417c6ffe fix: Exit with 1 if unexpected error happens 2017-10-06 00:30:08 -04:00
Pierre-Denis Vanduynslager 85dd69b3a2 feat: Retrieve version gitHead from git tags and unshallow the repo if necessary
Add several fixes and improvements in the identification of the last release gitHead:
- If there is no last release, unshallow the repo in order to retrieve all existing commits
- If git head is not present in last release, try to retrieve it from git tag with format ‘v\<version\>’ or ‘\<version\>’
- If the last release git head cannot be determined and  found in commit history, unshallow the repo and try again
- Throw a ENOGITHEAD error if the gitHead for the last release cannot be found in the npm metadata nor in the git tags, preventing to make release based on the all the commits in the repo as before
- Add integration test for the scenario with a packed repo from which `npm republish` fails to read the git head

Fix #447, Fix #393, Fix #280, Fix #276
2017-10-02 19:43:46 -04:00
Pierre-Denis Vanduynslager cbb51a495b ci(codecov): Set default branch in codecov.yml 2017-09-30 16:00:50 -04:00
Pierre-Denis Vanduynslager a58d12d5e7 chore: Update badges 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager 42b3382b0e ci(travis): Update .travis.yml
- Avoid double build on PR
- Add git fetch depth
- Remove cache
- Retry npm install
2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager cc3c8f2548 ci: Use codecov for code coverage 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager abf92ad03d refactor: Use ES6, Test with AVA
- Use async/await instead of callbacks
- Use execa to run command line
- Use AVA for tests
- Add several assertions in the unit tests
- Add documentation (comments) in the tests
- Run tests with a real git repo instead of mocking child_process and add test helpers to create repos, commits and checkout
- Simplify test directory structure
- Simplify code readability (mostly with async/await)
- Use eslint for for linting, prettier for formatting
2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager 7fe0890350 chore: Remove editorconfig 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager f10f157d79 chore: More generic .gitignore (Windows, Mac OS, Linux) 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager 40e296b00d chore: Remove lockfiles 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager 266a3f72dc chore: Add license file 2017-09-30 13:30:41 -04:00
greenkeeper[bot]andGregor Martynus 42456a32b3 chore(package): update coveralls to version 3.0.0 2017-09-28 10:25:35 -07:00
greenkeeper[bot]andPierre Vanduynslager 3a4334fbfd fix(package): update @semantic-release/error to version 2.0.0 2017-09-25 13:16:40 -04:00
Richard LittauerandPierre Vanduynslager 41d9b7e984 docs: fix grammatical error in README
Just a small fix to make this sentence parse.
2017-09-22 03:11:24 -04:00
Pierre VanduynslagerandGregor Martynus 9951cf7e00 fix(package): Set minimum node version to 4 (#442) 2017-09-21 11:24:18 -07:00
greenkeeper[bot]andGregor Martynus 2d14c53b11 fix(package): update @semantic-release/last-release-npm to version 2.0.0 2017-09-21 11:08:42 -07:00
greenkeeper[bot]andPierre Vanduynslager 277d9ab4e2 chore(package): update cz-conventional-changelog to version 2.0.0
https://greenkeeper.io/
2017-09-19 18:03:30 -04:00
Stephan SchneiderandPierre Vanduynslager 4612a056a3 chore(package): update commitizen config 2017-09-19 16:42:09 -04:00
greenkeeper[bot]andGregor 8c44c3176a fix(package): update @semantic-release/commit-analyzer to version 3.0.1 2017-09-17 20:31:46 -07:00
greenkeeper[bot] dd60b461a6 fix(package): update @semantic-release/release-notes-generator to version 4.0.0 2017-09-17 19:51:43 +00:00
Richard LittauerandGregor Martynus 88b5895f80 docs(README): update commit lint suggestion (#429)
validate-commit-msg is deprecated, and points to commitlint.
2017-09-14 21:22:18 -07:00
Patrick HeneiseandGregor Martynus 1ceae83ad9 docs(troubleshooting): initial version (#399) 2017-09-13 12:10:50 -07:00
Gregor 12b35396d8 fix(package): @semantic-release/condition-travis@6.0.0
This also introduces the new build leader detecation from https://github.com/semantic-release/travis-deploy-once/releases/tag/v2.0.0
2017-08-19 14:15:28 -07:00
Gregor 33dfcffe2c fix(bin): addapt build leader error to new leader detection algorithm 2017-08-19 14:15:28 -07:00
Stephan BönnemannandGregor Martynus f534c57215 fix: remove support for node < 8
BREAKING CHANGE: Remove support for publishing a package with node < 8. [Details](https://github.com/semantic-release/semantic-release#why-does-semantic-release-require-node-version-8).
2017-08-19 14:15:28 -07:00
Stephan BönnemannandGregor Martynus 9c5288460d chore: add package-lock 2017-08-19 14:15:28 -07:00
108 changed files with 5813 additions and 1599 deletions
-11
View File
@@ -1,11 +0,0 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
+48
View File
@@ -0,0 +1,48 @@
<!--
Please fill the informations requested or use one of the following url:
- Bug report: https://github.com/semantic-release/semantic-release/issues/new?template=bug-report.md
- Feature request: https://github.com/semantic-release/semantic-release/issues/new?template=feature-request.md
- New plugin request: https://github.com/semantic-release/semantic-release/issues/new?template=plugin-request.md
-->
<!--------------------- FOR BUG REPORT ONLY --------------------->
## Current behavior
<!-- Describe how the issue manifests. -->
## Expected behavior
<!-- Describe what the desired behavior would be. -->
## Environment
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
- CI environment: <!-- CI service name -->
- Plugins used: <!-- List semantic-release plugin used if any -->
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
- CI logs: <!-- link to your CI logs or semantic-release logs -->
<!--------------------- FOR FEATURE REQUEST ONLY --------------------->
## New feature motivation
<!-- Describe the context, the use-case and the advantages of the feature request. -->
## New feature description
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
## New feature implementation
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
<!--------------------- FOR NEW PLUGIN REQUEST ONLY --------------------->
## New plugin motivation
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
## Third-party documentation
<!-- Provide explanation and documentation links for the platform to integrate with. -->
+17
View File
@@ -0,0 +1,17 @@
# Bug report
## Current behavior
<!-- Describe how the issue manifests. -->
## Expected behavior
<!-- Describe what the desired behavior would be. -->
## Environment
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
- CI environment: <!-- CI service name -->
- Plugins used: <!-- List semantic-release plugin used if any -->
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
- CI logs: <!-- link to your CI logs or semantic-release logs -->
@@ -0,0 +1,13 @@
# Feature request
## New feature motivation
<!-- Describe the context, the use-case and the advantages of the feature request. -->
## New feature description
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
## New feature implementation
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
@@ -0,0 +1,9 @@
# New plugin request
## New plugin motivation
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
## Third-party documentation
<!-- Provide explanation and documentation links for the platform to integrate with. -->
+1
View File
@@ -0,0 +1 @@
base: app0ZOxG0FnHmOiuU
+131 -7
View File
@@ -1,9 +1,133 @@
coverage
node_modules
test/registry/couch
test/registry/data
test/tmp
# Created by https://www.gitignore.io/api/macos,windows,linux,node
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### macOS ###
*.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk
### Node ###
# Logs
logs
*.log
*.dump
.DS_Store
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Typescript v1 declaration files
typings/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
### Windows ###
# Windows thumbnail cache files
Thumbs.db
ehthumbs.db
ehthumbs_vista.db
# Folder config file
Desktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msm
*.msp
# Windows shortcuts
*.lnk
# Lockfiles
package-lock.json
yarn.lock
# Gitbook
_book
+1
View File
@@ -0,0 +1 @@
package-lock=false
+29 -18
View File
@@ -1,21 +1,32 @@
sudo: false
language: node_js
cache:
directories:
- $HOME/.npm
notifications:
email: false
node_js:
- 8 # stable
- 6 # LTS
- 4 # maintenance
before_script:
- npm prune
after_success:
- npm run coverage:upload
- npm run semantic-release
services:
- couchdb
- docker
node_js:
- 9
- 8
# Trigger a push build on caribou and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
except:
- /^v\d+\.\d+\.\d+$/
only:
- caribou
- /^greenkeeper.*$/
# Retry install on fail to avoid failing a build on network/disk/external errors
install:
- travis_retry npm install
script:
- npm run test
after_success:
- npm run codecov
jobs:
include:
- stage: release
node_js: lts/*
script:
- npm run semantic-release
+1
View File
@@ -0,0 +1 @@
--install.no-lockfile true
+46
View File
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at semantic-release+coc@martynus.net. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
+251
View File
@@ -0,0 +1,251 @@
# Contributing to semantic-release
✨ Thanks for contributing to **semantic-release**! ✨
As a contributor, here are the guidelines we would like you to follow:
- [Code of conduct](#code-of-conduct)
- [How can I contribute?](#how-can-i-contribute)
- [Using the issue tracker](#using-the-issue-tracker)
- [Submitting a Pull Request](#submitting-a-pull-request)
- [Coding rules](#coding-rules)
- [Working with the code](#working-with-the-code)
We also recommend to read [How to Contribute to Open Source](https://opensource.guide/how-to-contribute).
## Code of conduct
Help us keep **semantic-release** open and inclusive. Please read and follow our [Code of conduct](CODE_OF_CONDUCT.md).
## How can I contribute?
### Improve documentation
As a **semantic-release** user you are the perfect candidate to help us improve our documentation: typo corrections, clarifications, more examples, new [recipes](docs/recipes/README.md) etc. Take a look at the [documentation issues that need help](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22+label%3Adocs+).
Please follow the [Documentation guideline](#documentation).
### Give feedback on issues
Some issues are created without information requested in the [Bug report guideline](#bug-report). Help making them easier to resolve by adding any relevant informations.
Issues with the [design label](https://github.com/issues?q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3Adesign) are meant to discuss the implementation of new features. Participating in the discussion is a good opportunity to get involved and influence the future direction of **semantic-release**.
### Fix bugs and implement features
Confirmed bug and ready to implement features are marked with the [help wanted label](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22). Post a comment on an issue to indicate you would like to work on it and to request help from the [@semantic-release/maintainers](https://github.com/orgs/semantic-release/teams/contributors) and the community.
## Using the issue tracker
The issue tracker is the channel for [bug reports](#bug-report), [features requests](#feature-request) and [submitting pull requests](#submitting-a-pull-request) only. Please use the [Support](docs/support/README.md) and [Get help](README.md#get-help) sections for support, troubleshooting and questions.
Before opening an Issue or a Pull Request, please use the [GitHub issue search](https://github.com/issues?utf8=%E2%9C%93&q=user%3Asemantic-release) to make the bug or feature request hasn't been already reported or fixed.
### Bug report
A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report and fill the information requested in the [Bug report template](https://github.com/semantic-release/semantic-release/issues/new?template=bug-report.md).
### Feature request
Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible and fill the information requested in the [Feature request template](https://github.com/semantic-release/semantic-release/issues/new?template=feature-request.md).
### New plugin request
[Plugins](docs/usage/plugins.md) are a great way to extend **semantic-release** capabilities, integrate with other systems and support new project type. Please provide as much detail and context as possible and fill the information requested in the [New plugin request template](https://github.com/semantic-release/semantic-release/issues/new?template=plugin-request.md).
## Submitting a Pull Request
Good pull requests whether patches, improvements or new features are a fantastic help. They should remain focused in scope and avoid containing unrelated commits.
**Please ask first** before embarking on any significant pull request (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project.
If you never created a pull request before, welcome 🎉 😄. [Here is a great tutorial](https://opensource.guide/how-to-contribute/#opening-a-pull-request) on how to send one :)
Here is a summary of the steps to follow:
1. [Set up the workspace](#set-up-the-workspace)
2. If you cloned a while ago, get the latest changes from upstream and update dependencies:
```bash
$ git checkout master
$ git pull upstream master
$ rm -rf node_modules
$ npm install
```
3. Create a new topic branch (off the main project development branch) to contain your feature, change, or fix:
```bash
$ git checkout -b <topic-branch-name>
```
4. Make your code changes, following the [Coding rules](#coding-rules)
5. Push your topic branch up to your fork:
```bash
$ git push origin <topic-branch-name>
```
6. [Open a Pull Request](https://help.github.com/articles/creating-a-pull-request/#creating-the-pull-request) with a clear title and description.
**Tips**:
- For ambitious tasks, open a Pull Request as soon as possible with the `[WIP]` prefix i nthe title, in order to get feedback and help from the community.
- [Allow semantic-release maintainers to make changes to you Pull Request branch](https://help.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork) this way we can rebase it and make some minor changes if necessary. All changes we make will be done in new commit and we'll ask for your approval before merging them.
## Coding rules
### Source code
To ensure consistency and quality throughout the source code, all code modification must have:
- No [linting](#lint) errors
- A [test](#tests) for every possible cases introduced by your code change
- **100%** test coverage
- [Valid commit message(s)](#commit-message-guidelines)
- Documentation for new features
- Updated documentation for modified features
### Documentation
To ensure consistency and quality all documentation modification must:
- Refer to brand in [bold](https://help.github.com/articles/basic-writing-and-formatting-syntax/#styling-text) with proper capitalization, i.e. **GitHub**, **semantic-release**, **npm**
- Prefer [tables](https://help.github.com/articles/organizing-information-with-tables) over [lists](https://help.github.com/articles/basic-writing-and-formatting-syntax/#lists) when listing key values, i.e. List of options with their description
- Use [links](https://help.github.com/articles/basic-writing-and-formatting-syntax/#links) when, the first you are referring to:
- a **semantic-release** concept described somewhere else in the documentation, i.e. How to [contribute](CONTRIBUTING.md)
- a third-party product/brand/service, i.e. Integrate with [GitHub](https://github.com)
- an external concept or feature, i.e. Create a [GitHub release](https://help.github.com/articles/creating-releases)
- a package or module, i.e. The [`@semantic-release/github`](https://github.com/semantic-release/github) module
- Use the the [single backtick `code` quoting](https://help.github.com/articles/basic-writing-and-formatting-syntax/#quoting-code) for:
- commands inside sentences, i.e. the `semantic-release` command
- programming language keywords, i.e. `function`, `async`, `String`
- packages or modules, i.e. The [`@semantic-release/github`](https://github.com/semantic-release/github) module
- Use the the [triple backtick `code` formatting](https://help.github.com/articles/creating-and-highlighting-code-blocks) for:
- code examples
- configuration examples
- sequence of command lines
### Commit message guidelines
#### Atomic commits
If possible, make [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit), which means:
- a commit should contain exactly one self-contained functional change
- a functional change should be contained in exactly one commit
- a commit should not create an inconsistent state (such as test errors, linting errors, partial fix, feature with documentation etc...)
A complex feature can be broken down into multiple commits as long as each one keep a consistent state and consist of a self-contained change.
#### Commit message format
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special format that includes a **type**, a **scope** and a **subject**:
```commit
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```
The **header** is mandatory and the **scope** of the header is optional.
The **footer** can contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages).
#### Revert
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.
#### Type
The type must be one of the following:
| Type | Description |
|--------------|-------------------------------------------------------------------------------------------------------------|
| **build** | Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm) |
| **ci** | Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs) |
| **docs** | Documentation only changes |
| **feat** | A new feature |
| **fix** | A bug fix |
| **perf** | A code change that improves performance |
| **refactor** | A code change that neither fixes a bug nor adds a feature |
| **style** | Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) |
| **test** | Adding missing tests or correcting existing tests |
#### Subject
The subject contains succinct description of the change:
- use the imperative, present tense: "change" not "changed" nor "changes"
- don't capitalize first letter
- no dot (.) at the end
#### Body
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
The body should include the motivation for the change and contrast this with previous behavior.
#### Footer
The footer should contain any information about **Breaking Changes** and is also the place to reference GitHub issues that this commit **Closes**.
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
#### Examples
```commit
`fix(pencil): stop graphite breaking when too much pressure applied`
```
```commit
`feat(pencil): add 'graphiteWidth' option`
Fix #42
```
```commit
perf(pencil): remove graphiteWidth option`
BREAKING CHANGE: The graphiteWidth option has been removed.
The default graphite width of 10mm is always used for performance reasons.
```
## Working with the code
### Set up the workspace
[Fork](https://guides.github.com/activities/forking/#fork) the project, [clone](https://guides.github.com/activities/forking/#clone) your fork, configure the remotes and install the dependencies:
```bash
# Clone your fork of the repo into the current directory
$ git clone https://github.com/semantic-release/<repo-name>
# Navigate to the newly cloned directory
$ cd <repo-name>
# Assign the original repo to a remote called "upstream"
$ git remote add upstream https://github.com/semantic-release/<repo-name>
# Install the dependencies
$ npm install
```
### Lint
All the [semantic-release](https://github.com/semantic-release) repository use [XO](https://github.com/sindresorhus/xo) for linting and [Prettier](https://prettier.io) for formatting. Prettier formatting will be automatically verified and fixed by XO.
Before pushing your code changes make sure there is no linting errors with `npm run lint`.
**Tips**:
- Most linting errors can be automatically fixed with `npm run lint --fix`.
- Install the [XO plugin](https://github.com/sindresorhus/xo#editor-plugins) for your editor to see linting error directly in your editor and automatically fix them on save.
### Tests
Running the integration test require to install [Docker](https://docs.docker.com/engine/installation) on your machine.
All the [semantic-release](https://github.com/semantic-release) repository use [AVA](https://github.com/avajs/ava) for writing and running tests.
Before pushing your code changes make sure all **test pass** and the **coverage is 100%**:
```bash
$ npm run test
```
**Tips:** During development you can:
- run only a subset of test files with `ava <glob>`, for example `ava test/mytestfile.test.js`
- run in watch mode with `ava -w` to automatically run a test file when you modify it
- run only the test you are working on by adding [`.only` to the test definition](https://github.com/avajs/ava#running-specific-tests)
### Commits
All the [semantic-release](https://github.com/semantic-release) repository use [Commitizen](https://github.com/commitizen/cz-cli) to help you create [valid commit messages](#commit-message-guidelines).
After staging your changes with `git add`, run `npm run cm` to start the interactive commit message CLI.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2017 Contributors
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.
+120 -274
View File
@@ -1,272 +1,127 @@
# :package::rocket: semantic-release
<h1 align="center" style="border-bottom: none;">📦🚀 semantic-release</h1>
<h3 align="center">Fully automated version management and package publishing</h3>
<p align="center">
<a href="https://gitter.im/semantic-release/semantic-release">
<img alt="Gitter" src="https://badges.gitter.im/semantic-release/semantic-release.svg">
</a>
<a href="https://travis-ci.org/semantic-release/semantic-release">
<img alt="Travis" src="https://img.shields.io/travis/semantic-release/semantic-release/caribou.svg">
</a>
<a href="https://codecov.io/gh/semantic-release/semantic-release">
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/semantic-release/semantic-release/caribou.svg">
</a>
<a href="https://greenkeeper.io">
<img alt="Greenkeeper" src="https://badges.greenkeeper.io/semantic-release/semantic-release.svg">
</a>
<a href="#badge">
<img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg">
</a>
</p>
<p align="center">
<a href="https://www.npmjs.com/package/semantic-release">
<img alt="npm latest version" src="https://img.shields.io/npm/v/semantic-release/latest.svg">
</a>
<a href="https://www.npmjs.com/package/semantic-release">
<img alt="npm next version" src="https://img.shields.io/npm/v/semantic-release/next.svg">
</a>
</p>
**fully automated package publishing**
**semantic-release** automates the whole package release workflow including: determining the next version number, generating the release notes and publishing the package.
> **Trust us, this will change your workflow for the better.**
This removes the immediate connection between human emotions and version numbers, strictly following the [Semantic Versioning](http://semver.org) specification.
> [egghead.io](https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release)
> Trust us, this will change your workflow for the better. [egghead.io](https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release)
[![Join the chat at https://gitter.im/semantic-release/semantic-release](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/semantic-release/semantic-release?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
## Highlights
[![Dependency Status](https://david-dm.org/semantic-release/semantic-release/caribou.svg)](https://david-dm.org/semantic-release/semantic-release/caribou)
[![devDependency Status](https://david-dm.org/semantic-release/semantic-release/caribou/dev-status.svg)](https://david-dm.org/semantic-release/semantic-release/caribou#info=devDependencies)
[![Build Status](https://travis-ci.org/semantic-release/semantic-release.svg?branch=caribou)](https://travis-ci.org/semantic-release/semantic-release)
[![Coverage Status](https://coveralls.io/repos/semantic-release/semantic-release/badge.svg?branch=caribou&service=github)](https://coveralls.io/github/semantic-release/semantic-release?branch=caribou)
Out of the box this is just about _commit-messages_, but you can do so much more.
* **Detect breaking changes** using the test suite of your last release: [cracks](https://github.com/semantic-release/cracks)
* Detect breaking changes using your dependents test suites: [Help out! Implement the **dont-break** plugin](https://github.com/semantic-release/semantic-release/issues/65)
* Detect breaking changes diffing your JSDoc interface: [Help out! Implement the **india** plugin](https://github.com/semantic-release/semantic-release/issues/66)
* Abort releases with **insufficient test coverage**: [Help out! Implement the **istanbul** plugin](https://github.com/semantic-release/semantic-release/issues/68)
* Abort releases with **vulnerable dependencies** in the tree: [Help out! Implement the **nsp** plugin](https://github.com/semantic-release/semantic-release/issues/67)
* Everything you can imagine: [Build Plugins!](https://github.com/semantic-release/semantic-release#plugins)
&nbsp; | Commands | Comment
--- | --- | ---
| **manual/before** | <pre><code><div>npm version major</div><div>git push origin master --tags</div><div>npm publish</div></code></pre> | You **manually decide** what the **next version** is. You have to remember what major, minor and patch means. You have to remember to push both commits and tags. You have to wait for the CI to pass. |
| **semantic-release/after** | <pre><code><div>git commit -m "fix: &lt;message&gt;"</div><div>git push</div></code></pre> | You **describe the changes** youve made. A new version is automatically published with the correct version number.
This removes the immediate connection between human emotions and version numbers, so strictly following the [SemVer](http://semver.org/) spec is not a problem anymore  and thats ultimately `semantic-release`s goal.
<table>
<tr>
<th colspan="2">
“How to Write a JavaScript Library - Automating Releases with semantic-release”  egghead.io
</th>
</tr>
<tr>
<td colspan="2">
<a href="https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release"><img src="https://cloud.githubusercontent.com/assets/908178/9730739/7b1da5d8-5610-11e5-88b6-5c75fdda7ee2.png" alt="egghead.io session"></a>
</td>
</tr>
<tr>
<td colspan="2">
A free egghead.io tutorial series on how to write an open source library featuring semantic-release.
</td>
</tr>
<tr>
<th>
“We fail to follow SemVer and why it neednt matter”
</th>
<th>
“semantic-release Q&A with Kent C. Dodds”
</th>
</tr>
<tr>
<td>
<a href="https://www.youtube.com/watch?v=tc2UgG5L7WM&amp;index=6&amp;list=PLFZ5NyC0xHDaaTy6tY9p0C0jd_rRRl5Zm"><img alt="JSConfBP Talk" src="https://cloud.githubusercontent.com/assets/908178/9428178/c337ed26-49a2-11e5-8ad0-a602500a65bf.png"></a>
</td>
<td>
<a href="https://www.youtube.com/watch?v=g6y3DnhkjrI"><img alt="Hangout on Air with Kent C. Dodds" src="https://cloud.githubusercontent.com/assets/908178/9428179/c3387318-49a2-11e5-9f5f-dccd3fbb0c1d.png"></a>
</td>
</tr>
<tr>
<td>
This talk gives you a complete introduction to the underlying concepts of this module. 38:30
</td>
<td>
A “Hangouts on Air” conversation with hands on questions and answers about how to use semantic-release. 53:52
</td>
</tr>
</table>
- Fully automated release
- Enforce [Semantic Versioning](https://semver.org) specification
- New features and fixes are immediately available to users
- Use formalized commit message convention to document changes in the codebase
- Integrate with your [continuous integration workflow](docs/recipes/README.md#ci-configurations)
- Avoid potential errors associated with manual releases
- Support any [package managers and languages](docs/recipes/README.md#package-managers-and-languages) via [plugins](docs/usage/plugins.md)
- Simple and reusable configuration via [shareable configurations](docs/usage/shareable-configurations.md)
## How does it work?
Instead of writing [meaningless commit messages](http://whatthecommit.com/), we can take our time to think about the changes in the codebase and write them down. Following formalized conventions it is then possible to generate a helpful changelog and to derive the next semantic version number from them.
When `semantic-release` is set up it will do that after every successful continuous integration build of your master branch (or any other branch you specify) and publish the new version for you. This way no human is directly involved in the release process and your releases are guaranteed to be [unromantic and unsentimental](http://sentimentalversioning.org/).
If you fear the loss of control over timing and marketing implications of software releases you should know that `semantic-release` supports [release channels](https://github.com/npm/npm/issues/2718) using `npm`s [dist-tags](https://docs.npmjs.com/cli/dist-tag). This way you can keep control over what your users end up using by default, you can decide when to promote an automatically released version to the stable channel, and you can choose which versions to write blogposts and tweets about. You can use the same mechanism to [support older versions of your software](https://gist.github.com/boennemann/54042374e49c7ade8910), for example with important security fixes.
This is what happens in series:
| 1. `git push` | 2. `semantic-release pre` | 3. `npm publish` | 4. `semantic-release post` |
| :--- | :--- | :--- | :---- |
| New code is pushed and triggers a CI build. | Based on all commits that happened since the last release, the new version number gets written to the `package.json`. | The new version gets published to `npm`. | A changelog gets generated and a [release](https://help.github.com/articles/about-releases/) (including a git tag) on GitHub gets created. |
_Note:_ The current release/tag implementation is tied to GitHub, but could be opened up to Bitbucket, GitLab, et al. Feel free to send PRs for these services.
## Default Commit Message Format
This module ships with the [AngularJS Commit Message Conventions](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit) and changelog generator, but you can [define your own](#plugins) style.
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special
format that includes a **type**, a **scope** and a **subject** ([full explanation](https://github.com/stevemao/conventional-changelog-angular/blob/master/convention.md)):
```
<type>(<scope>): <subject>
<BLANK LINE>
<body>
<BLANK LINE>
<footer>
```
You can simplify using this convention for yourself and contributors by using [commitizen](https://github.com/commitizen/cz-cli) and [validate-commit-msg](https://github.com/kentcdodds/validate-commit-msg) or [semantic-git-commit-cli](https://github.com/JPeer264/node-semantic-git-commit-cli).
### Patch Release
```
fix(pencil): stop graphite breaking when too much pressure applied
```
### ~~Minor~~ Feature Release
```
feat(pencil): add 'graphiteWidth' option
```
### ~~Major~~ Breaking Release
```
perf(pencil): remove graphiteWidth option
BREAKING CHANGE: The graphiteWidth option has been removed. The default graphite width of 10mm is always used for performance reason.
```
## Setup
[![NPM](https://nodei.co/npm/semantic-release.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/semantic-release/)
```bash
npm install -g semantic-release-cli
cd your-module
semantic-release-cli setup
```
![dialogue](https://cloud.githubusercontent.com/assets/908178/9428123/3628dfec-499f-11e5-8bdd-8f3042dd95ed.png)
_[This is what happens under the hood.](https://github.com/semantic-release/cli#what-it-does)_
## Options
You can pass options either via command line (in [kebab-case](https://lodash.com/docs#kebabCase)) or in the `release` field of your `package.json` (in [camelCase](https://lodash.com/docs#camelCase)). The following two examples are the same, but CLI arguments take precedence.
| CLI | package.json |
| --- | --- |
| <pre><code>semantic-release pre --no-debug</code><pre> | <pre><code><div>//package.json</div><div>"release": {</div><div> "debug": false</div><div>}</div></code></pre><pre><code>semantic-release pre</code></pre> |
These options are currently available:
- `branch`: The branch on which releases should happen. Default: `'master'`
- `debug`: If true doesnt actually publish to npm or write things to file. Default: `!process.env.CI`
- `githubToken`: The token used to authenticate with GitHub. Default: `process.env.GH_TOKEN`
- `githubUrl`: Optional. Pass your GitHub Enterprise endpoint.
- `githubApiPathPrefix`: Optional. The path prefix for your GitHub Enterprise API.
_A few notes on `npm` config_:
1. The `npm` token can only be defined in the environment as `NPM_TOKEN`, because thats where `npm` itself is going to read it from.
2. In order to publish to a different `npm` registry you can specify that inside the `package.json`s [`publishConfig`](https://docs.npmjs.com/files/package.json#publishconfig) field.
3. If you want to use another dist-tag for your publishes than `'latest'` you can specify that inside the `package.json`s [`publishConfig`](https://docs.npmjs.com/files/package.json#publishconfig) field.
4. `semantic-release` generally tries to orientate itself towards `npm` it inherits the loglevel for example.
## Plugins
There are numerous steps where you can customize `semantic-release`s behaviour using plugins. A plugin is a regular [option](#options), but passed inside the `release` block of `package.json`:
```json
{
"release": {
"analyzeCommits": "npm-module-name",
"generateNotes": "./path/to/a/local/module",
"verifyConditions": {
"path": "./path/to/a/module",
"additional": "config"
}
}
```
```
semantic-release pre --analyze-commits="npm-module-name"
```
A plugin itself is an async function that always receives three arguments.
```js
module.exports = function (pluginConfig, config, callback) {}
```
- `pluginConfig`: If the user of your plugin specifies additional plugin config in the `package.json` (see the `verifyConditions` example above) then its this object.
- `config`: A config object containing a lot of information to act upon.
- `env`: All environment variables
- `npm`: Select npm configuration bits like `registry`, `tag` and `auth`
- `options`: `semantic-release` options like `debug`, or `branch`
- `pkg`: Parsed `package.json`
- For certain plugins the `config` object contains even more information. See below.
- `callback`: If an error occurs pass it as first argument. Otherwise pass your result as second argument.
### `analyzeCommits`
This plugin is responsible for determining the type of the next release. It additionally receives a `commits` array inside `config`. One commit is an object with a `message` and `hash` property. Call the callback with `'major'`, `'premajor'`, `'minor'`, `'preminor'`, `'patch'`, `'prepatch'`, `'prerelease'`, or `null` if nothing changed.
While it may be tempting to use `'prepatch'`, `'preminor'` & `'prerelease'` as part of a release process, this is strongly discouraged. A better approach is to use [dist-tags](https://docs.npmjs.com/cli/dist-tag) to create release channels (such as 'latest', 'next', 'stable') and to return only `'major'`, `'premajor'` and `'minor'` from the commit analyzer.
Have a look at the [default implementation](https://github.com/semantic-release/commit-analyzer/).
### `generateNotes`
This plugin is responsible for generating release notes. Call the callback with the notes as a string. Have a look at the [default implementation](https://github.com/semantic-release/release-notes-generator/).
### `verifyConditions`
This plugins is responsible for verifying that a release should happen in the first place. For example, the [default implementation](https://github.com/semantic-release/condition-travis/) verifies that the publish is happening on Travis, that its the right branch, and that all other build jobs succeeded. There are more use cases for this, e.g. verifying that test coverage is above a certain threshold or that there are no [vulnerabilities](https://nodesecurity.io/) in your dependencies. Be creative.
Passing an array of plugins will run them in series.
### `verifyRelease`
This plugin is responsible for verifying a release that was determined before and is about to be published. There is no default implementation. It additionally receives `nextRelease`, `lastRelease` and `commits` inside `config`. While `commits` is the same as with analyzeCommits, `nextRelease` contains a `type` (e.g. `'major'`) and the new version (e.g. `'1.0.0'`) and `lastRelease` contains the old `version`, the `gitHead` at the time of the release and the npm dist-`tag` (e.g. `'latest'`). Using this information you could [detect breaking changes](https://github.com/semantic-release/cracks) or hold back certain types of releases. Again: Be creative.
Passing an array of plugins will run them in series.
### `getLastRelease`
This plugin is responsible for determining a packages last release version. The [default implementation](https://github.com/semantic-release/last-release-npm) uses the last published version on a npm registry.
## ITYM*FAQ*LT
> I think you might frequently ask questions like these
### Why is the `package.json`s version not updated in my repository?
The `npm` docs even state:
> The most important things in your package.json are the name and version fields. Those are actually required, and your package wont install without them.
> [npm docs](https://docs.npmjs.com/files/package.json#version)
While this entirely true the version number doesnt have to be checked into source control. `semantic-release` takes care of the version field right before `npm publish` uses it and this is the only point where it _really_ is required.
### Is there a way to preview which version would currently get published?
If you run `npm run semantic-release` locally a dry run gets performed, which logs the version that would currently get published.
### Can I run this on my own machine rather than on a CI server?
Of course you can, but this doesnt necessarily mean you should. Running your tests on an independent machine before releasing software is a crucial part of this workflow. Also it is a pain to set this up locally, with tokens lying around and everything. That said, you can run the scripts with `--debug=false` explicitly. You have to export `GH_TOKEN=<your_token>` and `NPM_TOKEN=<your_other_token>`.
### Can I manually trigger the release of a specific version?
You can trigger a release by pushing to your GitHub repository. You deliberately cannot trigger a _specific_ version release, because this is the whole point of `semantic-release`. Start your packages with `1.0.0` and semver on.
### Is it _really_ a good idea to release on every push?
It is indeed a great idea because it _forces_ you to follow best practices. If you dont feel comfortable making every passing feature or fix on your master branch addressable via `npm` you might not treat your master right. Have a look at [branch workflows](https://guides.github.com/introduction/flow/index.html). If you still think you should have control over the exact point in time of your release, e.g. because you are following a release schedule, you can release only on the `production`/`deploy`/`release` branch and push your code there in certain intervals, or better yet use [dist-tags](https://docs.npmjs.com/cli/dist-tag).
### Why should I trust `semantic-release` with my releases?
`semantic-release` has a full unit- and integration-test-suite that tests _actual_ `npm` publishes against the [npm-registry-couchapp](https://github.com/npm/npm-registry-couchapp/) on all major node.js versions from `^0.10` on. A new version wont get published if it doesnt pass on all these engines.
### Commit message format
**semantic-release** uses the commit messages to determine the type of changes in the codebase. Following formalized conventions for commit messages, **semantic-release** automatically determines the next [semantic version](https://semver.org) number, generates a changelog and publish the release.
By default **semantic-release** uses [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines). The commit message format can be changed with the [`preset` or `config` options](docs/usage/configuration.md#options) of the [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer#options) and [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator#options) plugins.
Tools such as [commitizen](https://github.com/commitizen/cz-cli), [commitlint](https://github.com/marionebl/commitlint) or [semantic-git-commit-cli](https://github.com/JPeer264/node-semantic-git-commit-cli) can be used to help contributor and enforce valid commits message.
Here is an example of the release type that will be done based on a commit messages:
| Commit message | Release type |
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
| `fix(pencil): stop graphite breaking when too much pressure applied` | Patch Release |
| `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
| `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release |
### Automation with CI
**semantic-release** is meant to be executed on the CI environment after every successful build on the release branch. This way no human is directly involved in the release process and the releases are guaranteed to be [unromantic and unsentimental](http://sentimentalversioning.org).
### Triggering a release
When pushing new commits to the release branch (i.e. `master`) with `git push` or by merging a pull request or merging from another branch, a CI build is triggered and runs the `semantic-release` command to make a release if there is relevant codebase changes since the last release.
By default a release will be done for each push to the release branch that contains relevant code changes. If you need more control over the timing of releases you have a couple of options:
- Publish releases on a distribution channel (for example npms [dist-tags](https://docs.npmjs.com/cli/dist-tag)). This way you can keep control over what your users end up using by default, and you can decide when to make an automatically released version available to the stable channel, and promote it.
- Develop on a `dev` branch and merge it to the release branch (i.e. `master`) once you are ready to publish. **semantic-release** will run only on pushes to the release branch.
### Release steps
After running the tests the command `semantic-release` will execute the following steps:
| Step | Description |
|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Verify Conditions | Verify all the conditions to proceed with the release with the [verify conditions plugins](docs/usage/plugins.md#verifyconditions-plugin). |
| Get last release | Obtain last release with the [get last release plugin](docs/usage/plugins.md#getlastrelease-plugin). |
| Analyze commits | Determine the type of release to do with the [analyze commits plugin](docs/usage/plugins.md#analyzecommits-plugin) based on the commits added since the last release. |
| Verify release | Verify the release conformity with the [verify release plugins](docs/usage/plugins.md#verifyrelease-plugin). |
| Generate notes | Generate release notes with the [generate notes plugin](docs/usage/plugins.md#generatenotes-plugin) for the commits added since the last release. |
| Publish | Publish the release with the [publish plugins](docs/usage/plugins.md#publish-plugin). |
## Documentation
- Usage
- [Installation](docs/usage/installation.md#installation)
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
- [Configuration](docs/usage/configuration.md#configuration)
- [Plugins](docs/usage/plugins.md)
- [Shareable configurations](docs/usage/shareable-configurations.md)
- Extending
- [Plugins](docs/extending/plugins-list.md)
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
- Recipes
- [CI configurations](docs/recipes/README.md)
- [Package managers and languages](docs/recipes/README.md)
- Developer guide
- [Plugins](docs/developer-guide/plugin.md)
- [Shareable configuration](docs/developer-guide/shareable-configuration.md)
- Resources
- [Videos](docs/resources.md#videos)
- [Articles](docs/resources.md#articles)
- [Tutorials](docs/resources.md#tutorials)
- Support
- [Frequently Asked Questions](docs/support/FAQ.md)
- [Troubleshooting](docs/support/troubleshooting.md)
- [Node version requirement](docs/support/node-version.md)
- [Node Support Policy](docs/support/node-support-policy.md)
## Get help
- [Stack Overflow](https://stackoverflow.com/questions/tagged/semantic-release)
- [Gitter chat](https://gitter.im/semantic-release/semantic-release)
- [Twitter](https://twitter.com/SemanticRelease)
## Badge
Use this in one of your projects? Include one of these badges in your README.md to let people know that your package is published using `semantic-release`.
Let people know that your package is published using **semantic-release** by including this badge in your readme.
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
@@ -274,21 +129,12 @@ Use this in one of your projects? Include one of these badges in your README.md
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
```
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=plastic)](https://github.com/semantic-release/semantic-release)
## Team
```md
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=plastic)](https://github.com/semantic-release/semantic-release)
```
| [![Stephan Bönnemann](https://github.com/boennemann.png?size=100)](https://github.com/boennemann) | [![Rolf Erik Lekang](https://github.com/relekang.png?size=100)](https://github.com/relekang) | [![Johannes Jörg Schmidt](https://github.com/jo.png?size=100)](https://github.com/jo) | [![Gregor Martynus](https://github.com/gr2m.png?size=100)](https://github.com/gr2m) | [![Pierre Vanduynslager](https://github.com/finnp.png?size=100)](https://github.com/finnp) | [![Pierre Vanduynslager](https://github.com/pvdlg.png?size=100)](https://github.com/pvdlg) | [![Christoph Witzko](https://github.com/christophwitzko.png?size=100)](https://github.com/christophwitzko) |
|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------|
| [Stephan Bönnemann](https://github.com/boennemann) | [Rolf Erik Lekang](https://github.com/relekang) | [Johannes Jörg Schmidt](https://github.com/jo) | [Gregor Martynus](https://github.com/gr2m) | [Finn Pauls](https://github.com/finnp) | [Pierre Vanduynslager](https://github.com/pvdlg) | [Christoph Witzko](https://github.com/christophwitzko) |
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](https://github.com/semantic-release/semantic-release)
```md
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](https://github.com/semantic-release/semantic-release)
```
## License
MIT License
2015 © Stephan Bönnemann and [contributors](https://github.com/semantic-release/semantic-release/graphs/contributors)
[![](https://cloud.githubusercontent.com/assets/908178/6091690/cc86f58c-aeb8-11e4-94cb-15f15f486cde.png)](https://twitter.com/trodrigues/status/509301317467373571)
<p align="center">
<img alt="Kill all humans" src="media/bender.png">
</p>
+39
View File
@@ -0,0 +1,39 @@
# Summary
## About
- [Highlights](README.md#highlights)
- [How does it work?](README.md#how-does-it-work)
## Usage
- [Installation](docs/usage/installation.md#installation)
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
- [Configuration](docs/usage/configuration.md#configuration)
- [Plugins](docs/usage/plugins.md)
- [Shareable configurations](docs/usage/shareable-configurations.md)
## Extending
- [Plugins](docs/extending/plugins-list.md)
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
## Recipes
- [CI configurations](docs/recipes/README.md)
- [CircleCI 2.0 workflows](docs/recipes/circleci-workflows.md)
- [Travis CI](docs/recipes/travis.md)
- [Travis CI with build stages](docs/recipes/travis-build-stages.md)
- [GitLab CI](docs/recipes/gitlab-ci.md)
- [Package managers and languages](docs/recipes/README.md)
## Developer guide
- [Plugin](docs/developer-guide/plugin.md)
- [Shareable configuration](docs/developer-guide/shareable-configuration.md)
## Resources
- [Videos](docs/resources.md#videos)
- [Articles](docs/resources.md#articles)
- [Tutorials](docs/resources.md#tutorials)
## Support
- [Frequently Asked Questions](docs/support/FAQ.md)
- [Troubleshooting](docs/support/troubleshooting.md)
- [Node version requirement](docs/support/node-version.md)
- [Node Support Policy](docs/support/node-support-policy.md)
+17 -159
View File
@@ -1,165 +1,23 @@
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var url = require('url')
// Bad news: We have to write plain ES5 in this file
// Good news: It's the only file of the entire project
var _ = require('lodash')
var log = require('npmlog')
var nopt = require('nopt')
var npmconf = require('npmconf')
var normalizeData = require('normalize-package-data')
/* eslint-disable no-var */
log.heading = 'semantic-release'
var env = process.env
var pkg = JSON.parse(fs.readFileSync('./package.json'))
var originalPkg = _.cloneDeep(pkg)
normalizeData(pkg)
var knownOptions = {
branch: String,
debug: Boolean,
'github-token': String,
'github-url': String,
'analyze-commits': [path, String],
'generate-notes': [path, String],
'verify-conditions': [path, String],
'verify-release': [path, String]
var semver = require('semver');
var pkg = require('../package.json');
if (!semver.satisfies(process.version, pkg.engines.node)) {
console.error(
`[semantic-release]: node version ${pkg.engines.node} is required. Found ${process.version}.
See https://github.com/semantic-release/semantic-release/blob/caribou/docs/support/node-version.md for more details and solutions.`
);
process.exit(1);
}
var options = _.defaults(
_.mapKeys(nopt(knownOptions), function (value, key) {
return _.camelCase(key)
}),
pkg.release,
{
branch: 'master',
fallbackTags: {
next: 'latest'
},
debug: !env.CI,
githubToken: env.GH_TOKEN || env.GITHUB_TOKEN,
githubUrl: env.GH_URL
}
)
var plugins = require('../src/lib/plugins')(options)
npmconf.load({}, function (err, conf) {
if (err) {
log.error('init', 'Failed to load npm config.', err)
process.exit(1)
}
var npm = {
auth: {
token: env.NPM_TOKEN
},
cafile: conf.get('cafile'),
loglevel: conf.get('loglevel'),
registry: require('../src/lib/get-registry')(pkg, conf),
tag: (pkg.publishConfig || {}).tag || conf.get('tag') || 'latest'
}
// normalize trailing slash
npm.registry = url.format(url.parse(npm.registry))
log.level = npm.loglevel
var config = {
env: env,
pkg: pkg,
options: options,
plugins: plugins,
npm: npm
}
var hide = {}
if (options.githubToken) hide.githubToken = '***'
log.verbose('init', 'options:', _.assign({}, options, hide))
log.verbose('init', 'Verifying config.')
var errors = require('../src/lib/verify')(config)
errors.forEach(function (err) {
log.error('init', err.message + ' ' + err.code)
})
if (errors.length) process.exit(1)
if (options.argv.remain[0] === 'pre') {
log.verbose('pre', 'Running pre-script.')
log.verbose('pre', 'Veriying conditions.')
plugins.verifyConditions(config, function (err) {
if (err) {
log[options.debug ? 'warn' : 'error']('pre', err.message)
if (!options.debug) process.exit(1)
}
var nerfDart = require('nerf-dart')(npm.registry)
var wroteNpmRc = false
if (env.NPM_OLD_TOKEN && env.NPM_EMAIL) {
// Using the old auth token format is not considered part of the public API
// This might go away anytime (i.e. once we have a better testing strategy)
conf.set('_auth', '${NPM_OLD_TOKEN}', 'project') // eslint-disable-line no-template-curly-in-string
conf.set('email', '${NPM_EMAIL}', 'project') // eslint-disable-line no-template-curly-in-string
wroteNpmRc = true
} else if (env.NPM_TOKEN) {
conf.set(nerfDart + ':_authToken', '${NPM_TOKEN}', 'project') // eslint-disable-line no-template-curly-in-string
wroteNpmRc = true
}
conf.save('project', function (err) {
if (err) return log.error('pre', 'Failed to save npm config.', err)
if (wroteNpmRc) log.verbose('pre', 'Wrote authToken to .npmrc.')
require('../src/pre')(config, function (err, release) {
if (err) {
log.error('pre', 'Failed to determine new version.')
var args = ['pre', (err.code ? err.code + ' ' : '') + err.message]
if (err.stack) args.push(err.stack)
log.error.apply(log, args)
process.exit(1)
}
var message = 'Determined version ' + release.version + ' as "' + npm.tag + '".'
log.verbose('pre', message)
if (options.debug) {
log.error('pre', message + ' Not publishing in debug mode.', release)
process.exit(1)
}
try {
var shrinkwrap = JSON.parse(fs.readFileSync('./npm-shrinkwrap.json'))
shrinkwrap.version = release.version
fs.writeFileSync('./npm-shrinkwrap.json', JSON.stringify(shrinkwrap, null, 2))
log.verbose('pre', 'Wrote version ' + release.version + 'to npm-shrinkwrap.json.')
} catch (e) {
log.silly('pre', 'Couldn\'t find npm-shrinkwrap.json.')
}
fs.writeFileSync('./package.json', JSON.stringify(_.assign(originalPkg, {
version: release.version
}), null, 2))
log.verbose('pre', 'Wrote version ' + release.version + ' to package.json.')
})
})
})
} else if (options.argv.remain[0] === 'post') {
log.verbose('post', 'Running post-script.')
require('../src/post')(config, function (err, published, release) {
if (err) {
log.error('post', 'Failed to publish release notes.', err)
process.exit(1)
}
log.verbose('post', (published ? 'Published' : 'Generated') + ' release notes.', release)
})
} else {
log.error('post', 'Command "' + options.argv.remain[0] + '" not recognized. Use either "pre" or "post"')
}
})
// Node 8+ from this point on
require('../cli')().catch(() => {
process.exitCode = 1;
});
+8
View File
@@ -0,0 +1,8 @@
{
"plugins" : ["github", "anchors"],
"pluginsConfig": {
"github": {
"url": "https://github.com/semantic-release/semantic-release"
}
}
}
Executable
+65
View File
@@ -0,0 +1,65 @@
const program = require('commander');
const {pickBy, isUndefined} = require('lodash');
const logger = require('./lib/logger');
function list(values) {
return values.split(',').map(value => value.trim());
}
module.exports = async () => {
program
.name('semantic-release')
.description('Run automated package publishing')
.option('-b, --branch <branch>', 'Branch to release from')
.option('-r, --repositoryUrl <repositoryUrl>', 'Git repository URL')
.option('-e, --extends <paths>', 'Comma separated list of shareable config paths or packages name', list)
.option(
'--verify-conditions <paths>',
'Comma separated list of paths or packages name for the verifyConditions plugin(s)',
list
)
.option('--get-last-release <path>', 'Path or package name for the getLastRelease plugin')
.option('--analyze-commits <path>', 'Path or package name for the analyzeCommits plugin')
.option(
'--verify-release <paths>',
'Comma separated list of paths or packages name for the verifyRelease plugin(s)',
list
)
.option('--generate-notes <path>', 'Path or package name for the generateNotes plugin')
.option('--publish <paths>', 'Comma separated list of paths or packages name for the publish plugin(s)', list)
.option(
'--no-ci',
'Skip Continuous Integration environment verifications, allowing to make releases from a local machine'
)
.option('--debug', 'Output debugging information')
.option(
'-d, --dry-run',
'Dry-run mode, skipping verifyConditions, publishing and release, printing next version and release notes'
)
.parse(process.argv);
if (program.debug) {
// Debug must be enabled before other requires in order to work
require('debug').enable('semantic-release:*');
}
try {
if (program.args.length > 0) {
program.outputHelp();
process.exitCode = 1;
} else {
const opts = program.opts();
// Set the `noCi` options as commander.js sets the `ci` options instead (becasue args starts with `--no`)
opts.noCi = opts.ci === false ? true : undefined;
// Remove option with undefined values, as commander.js sets non defined options as `undefined`
await require('.')(pickBy(opts, value => !isUndefined(value)));
}
} catch (err) {
process.exitCode = 1;
if (err.semanticRelease) {
logger.log(`%s ${err.message}`, err.code);
} else {
logger.error('An error occurred while running semantic-release: %O', err);
}
}
};
+2
View File
@@ -0,0 +1,2 @@
codecov:
branch: caribou
+8
View File
@@ -0,0 +1,8 @@
# semantic-release documentation
- [Usage](usage/README.md) - **semantic-release** installation and configuration
- [Extending][extending/README.md]- Extending **semantic-release** with plugins and shareable configurations
- [Recipes](recipes/README.md) - Community written recipes for common **semantic-release** use-cases
- [Developer Guide](developer-guide/README.md) - The essentials of writing a **semantic-release** plugin or shareable configurations
- [Resources](resources.md) - Videos, articles and tutorials
- [Support](support/README.md) - FAQ and troubleshooting
+4
View File
@@ -0,0 +1,4 @@
# Developer guide
- [Plugins](plugin.md)
- [Shareable configuration](shareable-configuration.md)
+1
View File
@@ -0,0 +1 @@
# Plugin developer guide
@@ -0,0 +1 @@
# Shareable configuration developer guide
+4
View File
@@ -0,0 +1,4 @@
# Extending semantic-release
- [Plugins list](plugins-list.md)
- [Shareable configuration list](shareable-configurations-list.md)
+33
View File
@@ -0,0 +1,33 @@
# Plugins list
## Default plugins
- [@semantic-release/github](https://github.com/semantic-release/github)
- [verifyConditions](https://github.com/semantic-release/github#verifyconditions): Verify the presence and the validity of the GitHub authentication and release configuration
- [publish](https://github.com/semantic-release/github#publish): Publish a [GitHub release](https://help.github.com/articles/about-releases)
- [@semantic-release/npm](https://github.com/semantic-release/npm)
- [verifyConditions](https://github.com/semantic-release/npm#verifyconditions): Verify the presence and the validity of the npm authentication and release configuration
- [getLastRelease](https://github.com/semantic-release/npm#getlastrelease): Determine the last release of the package on the npm registry
- [publish](https://github.com/semantic-release/npm#publish): Publish the package on the npm registry
## Official plugins
- [@semantic-release/gitlab](https://github.com/semantic-release/gitlab)
- [verifyConditions](https://github.com/semantic-release/gitlab#verifyconditions): Verify the presence and the validity of the GitLab authentication and release configuration
- [publish](https://github.com/semantic-release/gitlab#publish): Publish a [GitLab release](https://docs.gitlab.com/ce/workflow/releases.html)
- [@semantic-release/git](https://github.com/semantic-release/git)
- [verifyConditions](https://github.com/semantic-release/git#verifyconditions): Verify the presence and the validity of the Git authentication and release configuration
- [getLastRelease](https://github.com/semantic-release/git#getlastrelease): Determine the last release via Git tags on the repository
- [publish](https://github.com/semantic-release/git#publish): Push a release commit and tag, including configurable files
- [@semantic-release/changelog](https://github.com/semantic-release/changelog)
- [verifyConditions](https://github.com/semantic-release/changelog#verifyconditions): Verify the presence and the validity of the configuration
- [publish](https://github.com/semantic-release/changelog#publish): Create or update the changelog file in the local project repository
- [@semantic-release/exec](https://github.com/semantic-release/exec)
- [verifyConditions](https://github.com/semantic-release/exec#verifyconditions): Execute a shell command to verify if the release should happen
- [getLastRelease](https://github.com/semantic-release/exec#getlastrelease): Execute a shell command to determine the last release
- [analyzeCommits](https://github.com/semantic-release/exec#analyzecommits): Execute a shell command to determine the type of release
- [verifyRelease](https://github.com/semantic-release/exec#verifyrelease): Execute a shell command to verifying a release that was determined before and is about to be published.
- [generateNotes](https://github.com/semantic-release/exec#analyzecommits): Execute a shell command to generate the release note
- [publish](https://github.com/semantic-release/exec#publish): Execute a shell command to publish the release.
## Community plugins
@@ -0,0 +1,7 @@
# Shareable configurations list
## Official configurations
- [@semantic-release/apm-config](https://github.com/semantic-release/apm-config) - semantic-release shareable configuration for releasing atom packages
- [@semantic-release/gitlab-config](https://github.com/semantic-release/gitlab-config) - semantic-release shareable configuration for GitLab
## Community configurations
+9
View File
@@ -0,0 +1,9 @@
# Recipes
## CI configurations
- [CircleCI 2.0 workflows](circleci-workflows.md)
- [Travis CI](travis.md)
- [Travis CI with build stages](travis-build-stages.md)
- [GitLab CI](gitlab-ci.md)
## Package managers and languages
+1
View File
@@ -0,0 +1 @@
# CircleCI 2.0 workflows
+71
View File
@@ -0,0 +1,71 @@
# Using semantic-release with [GitLab CI](https://about.gitlab.com/features/gitlab-ci-cd)
## Environment variables
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured with [Secret variables](https://docs.gitlab.com/ce/ci/variables/README.html#secret-variables).
## Node project configuration
GitLab CI supports [Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html) allowing to test on multiple Node versions and publishing a release only when all test pass.
**Note**: The publish pipeline must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--8).
### `.gitlab-ci.yml` configuration for Node projects
This example is a minimal configuration for **semantic-release** with a build running Node 4, 6 and 8 on Linux. See [GitLab CI - Configuration of your jobs with .gitlab-ci.yml](https://docs.gitlab.com/ee/ci/yaml/README.html) for additional configuration options.
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
```yaml
# The release pipeline will run only if all jobs in the test pipeline are successful
stages:
- test
- release
before_script:
- npm install
node:4:
image: node:4
stage: test
script:
- npm test
node:6:
image: node:6
stage: test
script:
- npm test
node:8:
image: node:8
stage: test
script:
- npm test
publish:
image: node:8
stage: release
script:
# Only for a local semantic-release installation
- npm run semantic-release
# Only for a global semantic-release installation
- npm install -g semantic-release
- semantic-release
```
### `package.json` configuration
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
"devDependencies": {
"semantic-release": "^12.0.0"
},
"scripts": {
"semantic-release": "semantic-release"
}
}
```
+1
View File
@@ -0,0 +1 @@
# Using semantic-release with [Travis CI build stages](https://docs.travis-ci.com/user/build-stages)
+165
View File
@@ -0,0 +1,165 @@
# Using semantic-release with [Travis CI](https://travis-ci.org)
## Environment variables
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [Travis Repository Settings](https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-Settings) or with the [travis env set CLI](https://github.com/travis-ci/travis.rb#env).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/ci-configuration.md#automatic-setup-with-semantic-release-cli).
## Single Node job configuration
For projects that require to be tested only with a single [Node version](https://docs.travis-ci.com/user/getting-started/#Selecting-a-different-programming-language) on [one Operating System](https://docs.travis-ci.com/user/getting-started/#Selecting-infrastructure-(optional)).
**Note**: [Node 8 is the minimal version required](../support/FAQ.md#why-does-semantic-release-require-node-version--8).
### `.travis.yml` configuration for single Node job
This example is a minimal configuration for semantic-release with a build running Node 8 on Linux. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) semantic-release installation.
```yaml
language: node_js
node_js: 8
script:
# Run tests
- npm run test
deploy:
provider: script
skip_cleanup: true
script:
# Only for a local semantic-release installation
- npm run semantic-release
# Only for a global semantic-release installation
- npm install -g semantic-release && semantic-release
```
### `package.json` configuration for single Node job
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
"devDependencies": {
"semantic-release": "^11.0.0"
},
"scripts": {
"semantic-release": "semantic-release"
}
}
```
## Multiple Node jobs configuration
For projects that require to be tested with multiple [Node versions](https://docs.travis-ci.com/user/languages/javascript-with-nodejs/#Specifying-Node.js-versions) and/or on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
**Note**: At least one job must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--83).
### `.travis.yml` configuration for multiple Node jobs
This example is a minimal configuration for **semantic-release** with a build running Node 4, 6 and 8 on Linux and OSX. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example uses [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once) in order to command [Run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
```yaml
language: node_js
node_js:
- 8
- 6
- 4
os:
- linux
- osx
script:
# Run tests
- npm run test
deploy:
provider: script
skip_cleanup: true
script:
# Only for a local semantic-release installation
- npm run travis-deploy-once "npm run semantic-release"
# Only for a global semantic-release installation
- npm install -g travis-deploy-once semantic-release && travis-deploy-once "semantic-release"
```
**Note**: See the `travis-deploy-once` [`pro`](https://github.com/semantic-release/travis-deploy-once#-p---pro) and [`travis-url`](https://github.com/semantic-release/travis-deploy-once#-u---travis-url) options for using with [Travis Pro](https://docs.travis-ci.com/user/travis-pro) and [Travis Enterprise](https://enterprise.travis-ci.com).
### `package.json` configuration for multiple Node jobs
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
"devDependencies": {
"semantic-release": "^12.0.0",
"travis-deploy-once": "^4.0.0"
},
"scripts": {
"semantic-release": "semantic-release",
"travis-deploy-once": "travis-deploy-once"
}
}
```
## Non-JavaScript projects configuration
For projects that require to be tested with one or multiple version of a Non-JavaScript [language](https://docs.travis-ci.com/user/languages), optionally on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
This recipe cover the Travis specifics only. See [Non JavaScript projects recipe](../support/FAQ.md#can-i-use-semantic-release-to-publish-non-javascript-packages) for more information on the **semantic-release** configuration.
### `.travis.yml` configuration for non-JavaScript projects
This example is a minimal configuration for semantic-release with a build running [Go 1.6 and 1.7](https://docs.travis-ci.com/user/languages/go) on Linux and OSX. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example uses [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once) in order to [run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
```yaml
language: go
go:
- 1.6
- 1.7
os:
- linux
- osx
script:
# Run tests
- go test -v ./...
deploy:
provider: script
skip_cleanup: true
script:
# Use nvm to install and use the Node LTS version (nvm is installed on all Travis images)
- nvm install lts/*
# Install travis-deploy-once and semantic-release
- npm install -g travis-deploy-once semantic-release
# Run semantic-release only on job, after all other are successful
- travis-deploy-once "semantic-release"
```
**Note**: See the `travis-deploy-once` [`pro`](https://github.com/semantic-release/travis-deploy-once#-p---pro) and [`travis-url`](https://github.com/semantic-release/travis-deploy-once#-u---travis-url) options for using with [Travis Pro](https://docs.travis-ci.com/user/travis-pro) and [Travis Enterprise](https://enterprise.travis-ci.com).
+19
View File
@@ -0,0 +1,19 @@
# Resources
## Videos
- ["Introducing Reliable Dependency and Release Management for npm Packages" - Gregor Martynus](https://www.youtube.com/watch?v=R2RJWLcfzwc)
- ["Kill all humans" - Jan Lehnardt](https://www.youtube.com/watch?v=ZXyx_1kN1L8&t=2s)
- [Publishing JavaScript Packages" - JavaScript Air](https://javascriptair.com/episodes/2016-07-20)
- ["Managing Dependencies like a boss 😎" - JavaScript Air](https://javascriptair.com/episodes/2016-08-17)
- ["Dependency Hell Just Froze Over" - Stephan Bönnemann](https://www.youtube.com/watch?v=PA139CERNbc)
- [“semantic-release Q&A with Kent C. Dodds”](https://www.youtube.com/watch?v=g6y3DnhkjrI)
- [“We fail to follow SemVer and why it neednt matter” - Stephan Bönnemann](https://www.youtube.com/watch?v=tc2UgG5L7WM)
## Articles
- [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2)
## Tutorials
- [“How to Write a JavaScript Library - Automating Releases with semantic-release” egghead.io](https://egghead.io/lessons/javascript-automating-releases-with-semantic-release)
+158
View File
@@ -0,0 +1,158 @@
# Frequently Asked Questions
## Why is the `package.json`s version not updated in my repository?
**semantic-release** takes care of updating the `package.json`s version before publishing to [npm](https://www.npmjs.com).
By default, only the published package will contains the version, which is the only place where it is *really* required, but the updated `package.json` will not be pushed to the Git repository
However, the [`@semantic-release/git`](https://github.com/semantic-release/git) plugin can be used to push the updated `package.json` as well as other files to the Git repository.
## How can I use a npm build script that requires the `package.json`s version ?
The `package.json`s version will be updated by the `semantic-release` command just before publishing to [npm](https://www.npmjs.com), therefore it won't be available for scripts ran before the `semantic-release` command.
As semantic-release uses the [npm CLI](https://docs.npmjs.com/cli/npm) to publish, all [npm hook scripts](https://docs.npmjs.com/misc/scripts#hook-scripts) will be executed. Therefore you can run your build script in the [`prepublishOnly`](https://docs.npmjs.com/misc/scripts#prepublish-and-prepare) hook. It will be executed after the `semantic-release` command update the `package.json`s version and before publishing.
## Is there a way to preview which version would currently get published?
Yes with the [dry-run options](../usage/configuration.md#dryrun) which prints to the console the next version to be published and the release notes.
## Can I use semantic-release with Yarn?
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation and run multiple CI jobs with different versions, the `yarn install` command will fail on jobs running with Node < 8 as **semantic-release** requires [Node >= 8.3](#why-does-semantic-release-require-node-version--83) and specifies it in its `package.json`s [`engines`](https://docs.npmjs.com/files/package.json#engines) key.
The recommended solution is to use the [Yarn](https://yarnpkg.com) [--ignore-engines](https://yarnpkg.com/en/docs/cli/install#toc-yarn-install-ignore-engines) option to install the project dependencies on the CI environment, so Yarn will ignore the **semantic-release**'s `engines` key:
```bash
$ yarn install --ignore-engines
```
**Note**: Several CI services use Yarn by default if your repository contains a `yarn.lock` file. So you should override the install step to specify `yarn install --ignore-engines`.
Alternatively you can use a [global](../usage/installation.md#global-installation) **semantic-release** installation and make sure to install and run the `semantic-release` command only in a CI jobs running with Node >= 8.3.
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can switch to Node 8 before installing and running the `semantic-release` command:
```bash
$ nvm install 8 && yarn install -g semantic-release && semantic-release
```
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
## Can I use semantic-release to publish non-JavaScript packages?
Yes, **semantic-release** is a Node CLI application but it can be used to publish any type of packages.
To publish a non-Node package (without a `package.json`) you would need to:
- Use a [global](../usage/installation.md#global-installation) **semantic-release** installation
- Set **semantic-release** [options](../usage/configuration.md#options) via [CLI arguments or rc file](../usage/configuration.md#configuration)
- Make sure your CI job executing the `semantic-release` command has access to [Node >= 8](#why-does-semantic-release-require-node-version--83) to execute the `semantic-release` command
See the [CI configuration recipes](../usage/ci-configuration.md) for more details on specific CI environments.
## Can I use semantic-release with any CI service?
Yes, **semantic-release** can be used with any CI service, as long as it provides:
- A way to set [authentication](../usage/ci-configuration.md#authentication) via environment variables
- A way to guarantee that the `semantic-release` command is [executed only after all the tests of all the jobs in the CI build pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
See the [CI configuration recipes](../usage/ci-configuration.md) for more details on specific CI environments.
## Can I run semantic-release on my local machine rather than on a CI server?
Yes, you can by explicitly setting the [`--no-ci` CLI option](../usage/configuration.md#options) option. You will also have to set the required [authentication](../usage/ci-configuration.md#authentication) via environment variables on your local machine, for example:
```bash
$ NPM_TOKEN=<your_npm_token> GH_TOKEN=<your_github_token> npm run semantic-release --no-ci
```
However this is not the recommended approach, as running unit and integration tests on an independent machine before publishing software is a crucial part of the release workflow.
## Can I use semantic-release with GitLab?
Yes, with the [`@semantic-release/gitlab-config`](https://github.com/semantic-release/gitlab-config) shareable configuration.
See the [GitLab CI recipes](../recipes/gitlab-ci.md#using-semantic-release-with-gitlab-ci) for the CI configuration.
## Can I use semantic-release with any Git hosted environment?
By default **semantic-release** uses the [`@semantic-release/github`](https://github.com/semantic-release/github) plugin to publish a [GitHub release](https://help.github.com/articles/about-releases). For other Git hosted environment the [`@semantic-release/git`](https://github.com/semantic-release/git) and [`@semantic-release/changelog`](https://github.com/semantic-release/changelog) plugins can be used via [plugins configuration](../usage/plugins.md#configuration).
See the [`@semantic-release/git`](https://github.com/semantic-release/git#semantic-releasegit) [`@semantic-release/changelog`](https://github.com/semantic-release/changelog#semantic-releasechangelog) plugins documentation for more details.
## Can I skip the release to the npm registry?
Yes, the publishing to the npm registry can be disabled with the [`npmPublish`](https://github.com/semantic-release/npm#options) option of the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin. In addition the [`tarballDir`](https://github.com/semantic-release/npm#options) option allow to generate the package tarball in order to publish it to your repository with the [`@semantic-release/git`](https://github.com/semantic-release/git) or to a [GitHub release](https://help.github.com/articles/about-releases) with the [`@semantic-release/github`](https://github.com/semantic-release/github) plugin.
See the [`@semantic-release/npm`](https://github.com/semantic-release/npm#semantic-releasenpm) plugin documentation for more details.
## Can I use `.npmrc` options?
Yes, all the [npm configuration options](https://docs.npmjs.com/misc/config) are supported via the [`.npmrc`](https://docs.npmjs.com/files/npmrc) file at the root of your repository.
See the [`@semantic-release/npm`](https://github.com/semantic-release/npm#npm-configuration) plugin documentation for more details.
## How can I set the access level of the published npm package?
The [npm `access` option](https://docs.npmjs.com/misc/config#access) can be set in the [`.npmrc`](https://docs.npmjs.com/files/npmrc) file at the root of your repository:
```rc
access=public
```
Or with the `publishConfig.access` key in your project's `package.json`:
```json
{
"publishConfig": {
"access": "public"
}
}
```
## Can I use semantic-release to publish a package on Artifactory?
Any npm compatible registry is supported with the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin. For Artifactory versions prior to 5.4, the legacy authentication has to be used (with `NPM_USERNAME`, `NPM_PASSWORD` and `NPM_EMAIL` [environment variables](https://github.com/semantic-release/npm#environment-variables)).
See [npm registry authentication](https://github.com/semantic-release/npm#npm-registry-authentication) for more details.
See [Artifactory - npm Registry](https://www.jfrog.com/confluence/display/RTF/Npm+Registry#NpmRegistry-AuthenticatingthenpmClient) documentation for Artifactiry configuration.
## Can I manually trigger the release of a specific version?
You can trigger a release by pushing to your Git repository. You deliberately cannot trigger a *specific* version release, because this is the whole point of semantic-release.
### Can I exclude commits from the analysis?
Yes, every commits that contains `[skip release]` or `[release skip]` in their message will be excluded from the commit analysis and won't participate in the release type determination.
## Is it *really* a good idea to release on every push?
It is indeed a great idea because it *forces* you to follow best practices. If you dont feel comfortable releasing every feature or fix on your `master` you might not treat your `master` branch as intended.
From [Understanding the GitHub Flow](https://guides.github.com/introduction/flow/index.html):
> Branching is a core concept in Git, and the entire GitHub Flow is based upon it. There's only one rule: anything in the master branch is always deployable.
If you need more control over the timing of releases, see [Triggering a release](../../README.md#triggering-a-release) for different options.
## Can I set the initial release version of my package to `0.0.1`?
This is not supported by **semantic-release** as it's not considered a good practice, mostly because [Semantic Versioning](https://semver.org) rules applies differently to major version zero.
In early development phase when your package is not ready for production yet we recommend to publish releases on a distribution channel (for example npms [dist-tags](https://docs.npmjs.com/cli/dist-tag)) or to develop on a `dev` branch and merge it to `master` periodically. See [Triggering a release](../../README.md#triggering-a-release) for more details on those solutions.
See [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2) for more details on [Semantic Versioning](https://semver.org) and the recommendation to start at version `1.0.0`.
## Can I trust semantic-release with my releases?
**semantic-release** has a full unit and integration test suite that tests `npm` publishes against the [npm-registry-couchapp](https://github.com/npm/npm-registry-couchapp).
In addition the [verify conditions step](../../README.md#release-steps) verifies that all necessary conditions for proceeding with a release are met, and a new release will be performed [only if all your tests pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
## Why does semantic-release require Node version >= 8.3?
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which **requires Node version 8.3 or higher**.
See [Node version requirement](../support/node-version.md#node-version-requirement) for more details and solutions.
+6
View File
@@ -0,0 +1,6 @@
# Support
- [Frequently Asked Questions](FAQ.md)
- [Troubleshooting](troubleshooting.md)
- [Node version requirement](node-version.md)
- [Node Support Policy](node-support-policy.md)
+13
View File
@@ -0,0 +1,13 @@
# Node Support Policy
We only support [Long-Term Support](https://github.com/nodejs/Release) versions of Node starting with [Node 8.9.0 (LTS)](https://nodejs.org/en/blog/release/v8.9.0).
We specifically limit our support to LTS versions of Node, not because this package won't work on other versions, but because we have a limited amount of time, and supporting LTS offers the greatest return on that investment.
It's possible this package will work correctly on newer versions of Node. It may even be possible to use this package on older versions of Node, though that's more unlikely as we'll make every effort to take advantage of features available in the oldest LTS version we support.
As each Node LTS version reaches its end-of-life we will remove that version from the node engines property of our package's package.json file. Removing a Node version is considered a breaking change and will entail the publishing of a new major version of this package. We will not accept any requests to support an end-of-life version of Node. Any merge requests or issues supporting an end-of-life version of Node will be closed.
We will accept code that allows this package to run on newer, non-LTS, versions of Node. Furthermore, we will attempt to ensure our own changes work on the latest version of Node. To help in that commitment, our continuous integration setup runs against all LTS versions of Node in addition the most recent Node release; called current.
JavaScript package managers should allow you to install this package with any version of Node, with, at most, a warning if your version of Node does not fall within the range specified by our node engines property. If you encounter issues installing this package, please report the issue to your package manager.
+52
View File
@@ -0,0 +1,52 @@
# Node version requirement
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which requires **requires Node version 8.3 or higher**.
**semantic-release** is meant to be used in a CI environment as a development support tool, not as a production dependency. Therefore the only constraint is to run the `semantic-release` in a CI environment providing Node 8 or higher.
See our [Node Support Policy](node-support-policy.md) for our long-term promise regarding Node version support.
## Recommended solution
### Run at least one CI job with Node >= 8.3
The recommended approach is to run the `semantic-release` command from a CI job running on Node 8.3 or higher. This can either be a job used by your project to test on Node >= 8.3 or a dedicated job for the release steps.
See [CI configuration](../usage/ci-configuration.md) and [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
## Alternative solutions
### Use `npx`
[`npx`](https://github.com/zkat/npx) is a CLI to execute npm binaries. It is bundled with [npm](https://www.npmjs.com/package/npm) >= 5.4, or can be installed via `npm install -g npx`.
`npx` can be used to download the latest [Node 8 package published on npm](https://www.npmjs.com/package/node) and use it to execute the `semantic-release` command.
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation:
```bash
$ npm install -g npx && npx -p node@8 -c "npm run semantic-release"
```
If you are using a [global](../usage/installation.md#global-installation) **semantic-release** installation:
```bash
# For global semantic-release install
$ npm install -g semantic-release npx && npx -p node@8 -c "semantic-release"
```
### Use `nvm`
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can use it to switch to Node 8 before running the `semantic-release` command.
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation:
```bash
$ nvm install 8 && npm run semantic-release
```
If you are using a [global](../usage/installation.md#global-installation) **semantic-release** installation:
```bash
$ nvm install 8 && npm install -g semantic-release && semantic-release
```
+31
View File
@@ -0,0 +1,31 @@
# Troubleshooting
## ENOTINHISTORY Commit not in history
This error happens when the commit associated with the last release cannot be found in the branch history.
Multiple situation can cause this issue:
- The package name configured in your `package.json` already exists and **semantic-release** obtains the last release of that package, which is unrelated to yours
- The commit history has been rewritten since the last release (with `git rebase` and `git push -f`)
If the package name configured in your `package.json` already exits, you should change it, and commit the `package.json`. Then **semantic-release** will proceed normally and make the initial release.
If you can identify the commit in your branch history that should be associated with the release version mentioned in the error message you can recover by tagging this commit:
```bash
$ git tag -f v<version of the last release> <commit sha1 corresponding to last release>
$ git push -f --tags origin <your release branch>
```
## ENOGITHEAD There is no commit associated with last release
This error happens when there is no commit associated with the last release that can be found in the package metadata on the npm registry.
This usually happen when the last release has been made without access to the git repository informations.
You can recover from that issue by identifying the commit in your branch history that should have been associated with the release version mentioned in the error message and tagging this commit:
```bash
$ git tag -f v<version of the last release> <commit sha1 corresponding to last release>
$ git push -f --tags origin <your release branch>
```
+7
View File
@@ -0,0 +1,7 @@
# Usage
- [Installation](installation.md#installation)
- [CI Configuration](ci-configuration.md#ci-configuration)
- [Configuration](configuration.md#configuration)
- [Plugins](plugins.md)
- [Shareable configurations](shareable-configurations.md)
+37
View File
@@ -0,0 +1,37 @@
# CI configuration
## Run `semantic-release` only after all tests succeeded
The `semantic-release` command must be executed only after all the tests in the CI build pass. If the build runs multiple jobs (for example to test on multiple Operating Systems or Node versions) the CI has to be configured to guarantee that the `semantic-release` command is executed only after all jobs are successful. This can be achieved with [Travis Build Stages](https://docs.travis-ci.com/user/build-stages), [CircleCI Workflows](https://circleci.com/docs/2.0/workflows), [Codeship Deployment Pipelines](https://documentation.codeship.com/basic/builds-and-configuration/deployment-pipelines), [GitLab Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html#introduction-to-pipelines-and-jobs), [Wercker Workflows](http://devcenter.wercker.com/docs/workflows), [GoCD Pipelines](https://docs.gocd.org/current/introduction/concepts_in_go.html#pipeline) or specific tools like [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once).
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
## Authentication
Most **semantic-release** [plugins](plugins.md) require to set up authentication in order to publish to your package manager's registry or to access your project's Git hosted service. The authentication token/credentials have to be made available in the CI serice via environment variables.
See each plugin documentation for the environment variable to set up.
The default [npm](https://github.com/semantic-release/npm#environment-variables) and [github](https://github.com/semantic-release/github#environment-variables) plugins require the following environment variables:
| Variable | Description |
|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `NPM_TOKEN` | npm token created via [npm token create](https://docs.npmjs.com/getting-started/working_with_tokens#how-to-create-new-tokens).<br/>**Note**: Only the `auth-only` [level of npm two-factor authentication](https://docs.npmjs.com/getting-started/using-two-factor-authentication#levels-of-authentication) is supported. |
| `GH_TOKEN` | GitHub authentication token.<br/>**Note**: Only the [personal token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line) authentication is supported. |
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on how to configure environment variables in your CI service.
## Automatic setup with `semantic-release-cli`
[`semantic-release-cli`](https://github.com/semantic-release/cli) allow to easily [install](installation.md) **semantic-release** in your Node project and set up the CI configuration:
```bash
npm install -g semantic-release-cli
cd your-module
semantic-release-cli setup
```
![dialogue](media/semantic-release-cli.png)
See the [semantic-release-cli](https://github.com/semantic-release/cli#what-it-does) documentation for more details.
+168
View File
@@ -0,0 +1,168 @@
# Configuration
In order to customize **semantic-release**s behavior, [options](#options) and [plugins](plugins.md) can be set via:
- A `.releaserc` file, written in YAML or JSON, with optional extensions: .`yaml`/`.yml`/`.json`/`.js`
- A `release.config.js` file that exports an object
- A `release` key in the project's `package.json` file
- CLI arguments
The following two examples are the same.
Via CLI argument:
```bash
$ semantic-release --branch next
```
Via `release` key in the project's `package.json` file:
```json
"release": {
"branch": "next"
}
```
```bash
$ semantic-release
```
**Note**: CLI arguments take precedence over options configured in the configuration file.
**Note**: Plugins options cannot be defined via CLI arguments and must be defined in the configuration file.
## Options
### extends
Type: `Array`, `String`
CLI arguments: `-e`, `--extends`
List of modules or file paths containing a [shareable configuration](shareable-configurations.md). If multiple shareable configuration are set, they will be imported in the order defined with each configuration option taking precedence over the options defined in a previous shareable configuration.
**Note**: Options defined via CLI arguments or in the configuration file will take precedence over the ones defined in any shareable configuration.
### branch
Type: `String`
Default: `master`
CLI arguments: `-b`, `--branch`
The branch on which releases should happen.
### repositoryUrl
Type: `String`
Default: `repository` property in `package.json` or [git origin url](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes)
CLI arguments: `-r`, `--repository-url`
The git repository URL
Any valid git url format is supported (See [Git protocols](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols)).
**Note**: If the [Github plugin](https://github.com/semantic-release/github) is used the URL must be a valid Github URL that include the `owner`, the `repository` name and the `host`. **The Github shorthand URL is not supported.**
### dryRun
Type: `Boolean`
Default: `false` if running in a CI environment, `false` otherwise
CLI arguments: `-d`, `--dry-run`
Dry-run mode, skip publishing, print next version and release notes.
### noCi
Type: `Boolean`
Default: `false`
CLI arguments: `--no-ci`
Skip Continuous Integration environment verifications, allowing to make releases from a local machine.
### debug
Type: `Boolean`
Default: `false`
CLI argument: `--debug`
Output debugging information. It can also be enabled by set the `DEBUG` environment variable to `semantic-release`.
### verifyConditions
Type: `Array`, `String`, `Object`
Default: `['@semantic-release/npm', '@semantic-release/github']`
CLI argument: `--verify-conditions`
Define the list of [verify conditions plugins](plugins.md#verifyconditions-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
### getLastRelease
Type: `String`, `Object`
Default: `['@semantic-release/npm']`
CLI argument: `--get-last-release`
Define the [get last release plugin](plugins.md#getlastrelease-plugin).
See [Plugins configuration](plugins.md#configuration) for more details.
### analyzeCommits
Type: `String`, `Object`
Default: `['@semantic-release/commit-analyzer']`
CLI argument: `--analyze-commits`
Define the [analyze commits plugin](plugins.md#analyzecommits-plugin).
See [Plugins configuration](plugins.md#configuration) for more details.
### verifyRelease
Type: `Array`, `String`, `Object`
Default: `[]`
CLI argument: `--verify-release`
Define the list of [verify release plugins](plugins.md#verifyrelease-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
### generateNotes
Type: `String`, `Object`
Default: `['@semantic-release/release-notes-generator']`
CLI argument: `--generate-notes`
Define the [generate notes plugin](plugins.md#generatenotes-plugin).
See [Plugins configuration](plugins.md#configuration) for more details.
### publish
Type: `Array`, `String`, `Object`
Default: `['@semantic-release/npm', '@semantic-release/github']`
CLI argument: `--publish`
Define the list of [publish plugins](plugins.md#publish-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
+33
View File
@@ -0,0 +1,33 @@
# Installation
## Local installation
For [Node modules projects](https://docs.npmjs.com/getting-started/creating-node-modules) we recommend to install **semantic-release** locally and to run the `semantic-release` command with a [npm script](https://docs.npmjs.com/misc/scripts):
```bash
$ npm install --save-dev semantic-release
```
In your `package.json`:
```json
"scripts": {
"semantic-release": "semantic-release"
}
```
Then in the CI environment:
```bash
$ npm run semantic-release
```
## Global installation
For other type of projects we recommend to install **semantic-release** globally directly in the CI environment:
```bash
$ npm install -g semantic-release
$ semantic-release
```
**Note:**: For a global installation, it's recommended to specify the major **semantic-release** version to install (for example with with `npm install -g semantic-release@12`). This way your build will not automatically use the next major **semantic-release** release that could possibly break your build. You will have to upgrade manually when a new major version is released.
+82
View File
@@ -0,0 +1,82 @@
# Plugins
Each [release steps](../../README.md#release-steps) is implemented within a plugin or a list of plugins that can be configured, allowing to support different [commit message format](../../README.md#commit-message-format), release not generator and publishing platforms.
## Plugin types
### verifyConditions plugin
Plugin responsible for verifying all the conditions to proceed with the release: configuration is correct, authentication token are valid, etc...
Default implementation: [npm](https://github.com/semantic-release/npm#verifyconditions) and [github](https://github.com/semantic-release/github#verifyconditions).
### getLastRelease plugin
Plugin responsible for determining the version of the package last release.
Default implementation: [@semantic-release/npm](https://github.com/semantic-release/npm#getlastrelease).
### analyzeCommits plugin
Plugin responsible for determining the type of the next release (`major`, `minor` or `patch`).
Default implementation: [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer).
### verifyRelease plugin
Plugin responsible for verifying the parameters (version, type, dist-tag etc...) of the release that is about to be published match certain expectations. For example the [cracks plugin](https://github.com/semantic-release/cracks) allows to verify that if a release contains breaking changes, its type must be `major`.
Default implementation: none.
### generateNotes plugin
Plugin responsible for generating release notes.
Default implementation: [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator).
### publish plugin
Plugin responsible for publishing the release.
Default implementation: [npm](https://github.com/semantic-release/npm#publish) and [github](https://github.com/semantic-release/github#publish).
## Configuration
Plugin can be configured by specifying the plugin's module name or file path directly as a `String` or within the `path` key of an `Object`.
Plugins specific options can be set similarly to the other **semantic-release** [options](configuration.md#options) or within the plugin `Object`. Plugins options defined along the other **semantic-release** [options](configuration.md#options) will apply to all plugins, while the one defined within the plugin `Object` will apply only to this specific plugin.
For example:
```json
{
"release": {
"verifyConditions": [
{
"path": "@semantic-release/exec",
"cmd": "verify-conditions.sh"
},
"@semantic-release/npm",
"@semantic-release/github"
],
"analyzeCommits": "custom-plugin",
"verifyRelease": [
{
"path": "@semantic-release/exec",
"cmd": "verify-release.sh"
},
],
"generateNotes": "./build/my-plugin.js",
"githubUrl": "https://my-ghe.com",
"githubApiPathPrefix": "/api-prefix"
}
}
```
With this configuration:
- the `custom-plugin` npm module will be used to [analyze commits](#analyzecommits-plugin)
- the `./build/my-plugin.js` script will be used to [generate release notes](#generatenotes-plugin)
- the [`@semantic-release/exec`](https://github.com/semantic-release/exec), [`@semantic-release/npm`](https://github.com/semantic-release/npm) and [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugins will be used to [verify conditions](#verifyconditions-plugin)
- the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin will be used to [verify the release](#verifyrelease-plugin)
- the `cmd` option will be set to `verify-conditions.sh` only for the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin used to [verify conditions](#verifyconditions-plugin)
- the `cmd` option will be set to `verify-release.sh` only for the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin used to [verify the release](#verifyrelease-plugin)
- the `githubUrl` and `githubApiPathPrefix` options will be set to respectively `https://my-ghe.com` and `/api-prefix` for all plugins
+5
View File
@@ -0,0 +1,5 @@
# Shareable configurations
A sharable configuration is an [npm](https://www.npmjs.com/) package that exports a **semantic-release** configuration object. It allows to easily use the same configuration across several projects.
The shareable configurations to use can be set with the [extends](configuration.md#extends) option.
+96
View File
@@ -0,0 +1,96 @@
const marked = require('marked');
const TerminalRenderer = require('marked-terminal');
const envCi = require('env-ci');
const getConfig = require('./lib/get-config');
const getNextVersion = require('./lib/get-next-version');
const getCommits = require('./lib/get-commits');
const logger = require('./lib/logger');
const {gitHead: getGitHead, isGitRepo} = require('./lib/git');
module.exports = async opts => {
const {isCi, branch, isPr} = envCi();
const config = await getConfig(opts, logger);
const {plugins, options} = config;
if (!isCi && !options.dryRun && !options.noCi) {
logger.log('This run was not triggered in a known CI environment, running in dry-run mode.');
options.dryRun = true;
}
if (isCi && isPr && !options.noCi) {
logger.log("This run was triggered by a pull request and therefore a new version won't be published.");
return;
}
if (!await isGitRepo()) {
logger.error('Semantic-release must run from a git repository.');
return;
}
if (branch !== options.branch) {
logger.log(
`This test run was triggered on the branch ${branch}, while semantic-release is configured to only publish from ${
options.branch
}, therefore a new version wont be published.`
);
return;
}
logger.log('Run automated release from branch %s', options.branch);
logger.log('Call plugin %s', 'verify-conditions');
await plugins.verifyConditions({options, logger});
logger.log('Call plugin %s', 'get-last-release');
const {commits, lastRelease} = await getCommits(
await plugins.getLastRelease({options, logger}),
options.branch,
logger
);
logger.log('Call plugin %s', 'analyze-commits');
const type = await plugins.analyzeCommits({
options,
logger,
lastRelease,
commits: commits.filter(commit => !/\[skip\s+release\]|\[release\s+skip\]/i.test(commit.message)),
});
if (!type) {
logger.log('There are no relevant changes, so no new version is released.');
return;
}
const version = getNextVersion(type, lastRelease, logger);
const nextRelease = {type, version, gitHead: await getGitHead(), gitTag: `v${version}`};
logger.log('Call plugin %s', 'verify-release');
await plugins.verifyRelease({options, logger, lastRelease, commits, nextRelease});
const generateNotesParam = {options, logger, lastRelease, commits, nextRelease};
if (options.dryRun) {
logger.log('Call plugin %s', 'generate-notes');
const notes = await plugins.generateNotes(generateNotesParam);
marked.setOptions({renderer: new TerminalRenderer()});
logger.log('Release note for version %s:\n', nextRelease.version);
process.stdout.write(`${marked(notes)}\n`);
} else {
logger.log('Call plugin %s', 'generateNotes');
nextRelease.notes = await plugins.generateNotes(generateNotesParam);
logger.log('Call plugin %s', 'publish');
await plugins.publish({options, logger, lastRelease, commits, nextRelease}, async prevInput => {
const newGitHead = await getGitHead();
// If previous publish plugin has created a commit (gitHead changed)
if (prevInput.nextRelease.gitHead !== newGitHead) {
nextRelease.gitHead = newGitHead;
// Regenerate the release notes
logger.log('Call plugin %s', 'generateNotes');
nextRelease.notes = await plugins.generateNotes(generateNotesParam);
}
// Call the next publish plugin with the updated `nextRelease`
return {options, logger, lastRelease, commits, nextRelease};
});
logger.log('Published release: %s', nextRelease.version);
}
return true;
};
+9
View File
@@ -0,0 +1,9 @@
function debugShell(message, shell, debug) {
debug(message);
debug('cmd: %O', shell.cmd);
debug('stdout: %O', shell.stdout);
debug('stderr: %O', shell.stderr);
debug('code: %O', shell.code);
}
module.exports = {debugShell};
+97
View File
@@ -0,0 +1,97 @@
const gitLogParser = require('git-log-parser');
const getStream = require('get-stream');
const debug = require('debug')('semantic-release:get-commits');
const SemanticReleaseError = require('@semantic-release/error');
const {unshallow, gitCommitTag, gitTagHead, isCommitInHistory} = require('./git');
/**
* Commit message.
*
* @typedef {Object} Commit
* @property {string} hash The commit hash.
* @property {string} message The commit message.
*/
/**
* Last release.
*
* @typedef {Object} LastRelease
* @property {string} version The version number of the last release.
* @property {string} [gitHead] The commit sha used to make the last release.
* @property {string} [gitTag] The tag used to make the last release.
*/
/**
* Result object.
*
* @typedef {Object} Result
* @property {Array<Commit>} commits The list of commits since the last release.
* @property {LastRelease} lastRelease The updated lastRelease.
*/
/**
* Retrieve the list of commits on the current branch since the last released version, or all the commits of the current branch if there is no last released version.
*
* The commit correspoding to the last released version is determined as follow:
* - Use `lastRelease.gitHead` if defined and present in `branch` history.
* - If `lastRelease.gitHead` is not in the `branch` history, unshallow the repository and try again.
* - If `lastRelease.gitHead` is still not in the `branch` history, search for a tag named `v<version>` or `<version>` and verify if it's associated commit sha is present in `branch` history.
*
* @param {LastRelease} lastRelease The lastRelease object obtained from the getLastRelease plugin.
* @param {string} branch The branch to release from.
* @param {Object} logger Global logger.
*
* @return {Promise<Result>} The list of commits on the branch `branch` since the last release and the updated lastRelease with the gitHead used to retrieve the commits.
*
* @throws {SemanticReleaseError} with code `ENOTINHISTORY` if `lastRelease.gitHead` or the commit sha derived from `config.lastRelease.version` is not in the direct history of `branch`.
*/
module.exports = async ({version, gitHead} = {}, branch, logger) => {
if (gitHead) {
// If gitHead doesn't exists in release branch
if (!await isCommitInHistory(gitHead)) {
// Unshallow the repository
await unshallow();
}
// If gitHead still doesn't exists in release branch
if (!await isCommitInHistory(gitHead)) {
// Try to find the commit corresponding to the version, using got tags
const tagHead = (await gitTagHead(`v${version}`)) || (await gitTagHead(version));
// If tagHead doesn't exists in release branch
if (!tagHead || !await isCommitInHistory(tagHead)) {
// Then the commit corresponding to the version cannot be found in the bracnh hsitory
logger.error(notInHistoryMessage(gitHead, branch, version));
throw new SemanticReleaseError('Commit not in history', 'ENOTINHISTORY');
}
gitHead = tagHead;
}
debug('Use gitHead: %s', gitHead);
} else {
logger.log('No previous release found, retrieving all commits');
// If there is no gitHead nor a version, there is no previous release. Unshallow the repo in order to retrieve all commits
await unshallow();
}
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
const commits = (await getStream.array(gitLogParser.parse({_: `${gitHead ? gitHead + '..' : ''}HEAD`}))).map(
commit => {
commit.message = commit.message.trim();
commit.gitTags = commit.gitTags.trim();
return commit;
}
);
logger.log('Found %s commits since last release', commits.length);
debug('Parsed commits: %o', commits);
return {commits, lastRelease: {version, gitHead, gitTag: await gitCommitTag(gitHead)}};
};
function notInHistoryMessage(gitHead, branch, version) {
return `The commit the last release of this package was derived from is not in the direct history of the "${branch}" branch.
This means semantic-release can not extract the commits between now and then.
This is usually caused by force pushing, releasing from an unrelated branch, or using an already existing package name.
You can recover from this error by restoring the commit "${gitHead}" or by creating a tag for the version "${version}" on the commit corresponding to this release:
$ git tag -f v${version || '<version>'} <commit sha1 corresponding to last release>
$ git push -f --tags origin ${branch}
`;
}
+73
View File
@@ -0,0 +1,73 @@
const readPkgUp = require('read-pkg-up');
const {castArray, pickBy, isUndefined, isNull, isString, isPlainObject} = require('lodash');
const cosmiconfig = require('cosmiconfig');
const resolveFrom = require('resolve-from');
const SemanticReleaseError = require('@semantic-release/error');
const debug = require('debug')('semantic-release:config');
const {repoUrl} = require('./git');
const PLUGINS_DEFINITION = require('./plugins/definitions');
const plugins = require('./plugins');
module.exports = async (opts, logger) => {
const {config} = (await cosmiconfig('release', {rcExtensions: true}).load(process.cwd())) || {};
// Merge config file options and CLI/API options
let options = {...config, ...opts};
const pluginsPath = {};
let extendPaths;
({extends: extendPaths, ...options} = options);
if (extendPaths) {
// If `extends` is defined, load and merge each shareable config with `options`
options = {
...castArray(extendPaths).reduce((result, extendPath) => {
const extendsOpts = require(resolveFrom.silent(__dirname, extendPath) ||
resolveFrom(process.cwd(), extendPath));
// For each plugin defined in a shareable config, save in `pluginsPath` the extendable config path,
// so those plugin will be loaded relatively to the config file
Object.keys(extendsOpts).reduce((pluginsPath, option) => {
if (PLUGINS_DEFINITION[option]) {
castArray(extendsOpts[option])
.filter(plugin => isString(plugin) || (isPlainObject(plugin) && isString(plugin.path)))
.map(plugin => (isString(plugin) ? plugin : plugin.path))
.forEach(plugin => {
pluginsPath[plugin] = extendPath;
});
}
return pluginsPath;
}, pluginsPath);
return {...result, ...extendsOpts};
}, {}),
...options,
};
}
// Set default options values if not defined yet
options = {
branch: 'master',
repositoryUrl: (await pkgRepoUrl()) || (await repoUrl()),
// Remove `null` and `undefined` options so they can be replaced with default ones
...pickBy(options, option => !isUndefined(option) && !isNull(option)),
};
debug('options values: %O', Object.keys(options));
debug('name: %O', options.name);
debug('branch: %O', options.branch);
debug('repositoryUrl: %O', options.repositoryUrl);
debug('analyzeCommits: %O', options.analyzeCommits);
debug('generateNotes: %O', options.generateNotes);
debug('verifyConditions: %O', options.verifyConditions);
debug('verifyRelease: %O', options.verifyRelease);
debug('publish: %O', options.publish);
if (!options.repositoryUrl) {
throw new SemanticReleaseError('The repositoryUrl option is required', 'ENOREPOURL');
}
return {options, plugins: await plugins(options, pluginsPath, logger)};
};
async function pkgRepoUrl() {
const {pkg} = await readPkgUp();
return pkg && pkg.repository ? pkg.repository.url : undefined;
}
+14
View File
@@ -0,0 +1,14 @@
const semver = require('semver');
module.exports = (type, lastRelease, logger) => {
let version;
if (lastRelease.version) {
version = semver.inc(lastRelease.version, type);
logger.log('The next release version is %s', version);
} else {
version = '1.0.0';
logger.log('There is no previous release, the next release version is %s', version);
}
return version;
};
+91
View File
@@ -0,0 +1,91 @@
const execa = require('execa');
const debug = require('debug')('semantic-release:get-version-head');
const {debugShell} = require('./debug');
/**
* Get the commit sha for a given tag.
*
* @param {string} tagName Tag name for which to retrieve the commit sha.
*
* @return {string} The commit sha of the tag in parameter or `null`.
*/
async function gitTagHead(tagName) {
try {
const shell = await execa('git', ['rev-list', '-1', tagName]);
debugShell('Get git tag head', shell, debug);
return shell.stdout;
} catch (err) {
debug(err);
return null;
}
}
/**
* Get the tag associated with a commit sha.
*
* @param {string} gitHead The commit sha for which to retrieve the associated tag.
*
* @return {string} The tag associatedwith the sha in parameter or `undefined`.
*/
async function gitCommitTag(gitHead) {
try {
const shell = await execa('git', ['describe', '--tags', '--exact-match', gitHead]);
debugShell('Get git commit tag', shell, debug);
return shell.stdout;
} catch (err) {
debug(err);
return undefined;
}
}
/**
* Verify if the commit `sha` is in the direct history of the current branch.
*
* @param {string} sha The sha of the commit to look for.
*
* @return {boolean} `true` if the commit `sha` is in the history of the current branch, `false` otherwise.
*/
async function isCommitInHistory(sha) {
const shell = await execa('git', ['merge-base', '--is-ancestor', sha, 'HEAD'], {reject: false});
debugShell('Check if commit is in history', shell, debug);
return shell.code === 0;
}
/**
* Unshallow the git repository (retriving every commits and tags).
*/
async function unshallow() {
await execa('git', ['fetch', '--unshallow', '--tags'], {reject: false});
}
/**
* @return {string} the sha of the HEAD commit.
*/
async function gitHead() {
try {
const shell = await execa('git', ['rev-parse', 'HEAD']);
debugShell('Get git head', shell, debug);
return shell.stdout;
} catch (err) {
debug(err);
throw new Error(err.stderr);
}
}
/**
* @return {string|undefined} The value of the remote git URL.
*/
async function repoUrl() {
return (await execa.stdout('git', ['remote', 'get-url', 'origin'], {reject: false})) || undefined;
}
/**
* @return {Boolean} `true` if the current working directory is in a git repository, `false` otherwise.
*/
async function isGitRepo() {
const shell = await execa('git', ['rev-parse', '--git-dir'], {reject: false});
debugShell('Check if the current working directory is a git repository', shell, debug);
return shell.code === 0;
}
module.exports = {gitTagHead, gitCommitTag, isCommitInHistory, unshallow, gitHead, repoUrl, isGitRepo};
+23
View File
@@ -0,0 +1,23 @@
const chalk = require('chalk');
/**
* Logger with `log` and `error` function.
*/
module.exports = {
log(...args) {
const [format, ...rest] = args;
console.log(
`${chalk.grey('[Semantic release]:')}${
typeof format === 'string' ? ` ${format.replace(/%[^%]/g, seq => chalk.magenta(seq))}` : ''
}`,
...(typeof format === 'string' ? [] : [format]).concat(rest)
);
},
error(...args) {
const [format, ...rest] = args;
console.error(
`${chalk.grey('[Semantic release]:')}${typeof format === 'string' ? ` ${chalk.red(format)}` : ''}`,
...(typeof format === 'string' ? [] : [format]).concat(rest)
);
},
};
+72
View File
@@ -0,0 +1,72 @@
const {isString, isObject, isFunction, isArray} = require('lodash');
const semver = require('semver');
const RELEASE_TYPE = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'];
const validatePluginConfig = conf => isString(conf) || isString(conf.path) || isFunction(conf);
module.exports = {
verifyConditions: {
default: ['@semantic-release/npm', '@semantic-release/github'],
config: {
validator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
message:
'The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
},
},
getLastRelease: {
default: '@semantic-release/npm',
config: {
validator: conf => Boolean(conf) && validatePluginConfig(conf),
message:
'The "getLastRelease" plugin is mandatory, and must be a single plugin definition. A plugin definition is either a string or an object with a path property.',
},
output: {
validator: output =>
!output ||
(isObject(output) && !output.version) ||
(isString(output.version) && Boolean(semver.valid(semver.clean(output.version))) && Boolean(output.gitHead)),
message:
'The "getLastRelease" plugin output if defined, must be an object with a valid semver version in the "version" property and the corresponding git reference in "gitHead" property.',
},
},
analyzeCommits: {
default: '@semantic-release/commit-analyzer',
config: {
validator: conf => Boolean(conf) && validatePluginConfig(conf),
message:
'The "analyzeCommits" plugin is mandatory, and must be a single plugin definition. A plugin definition is either a string or an object with a path property.',
},
output: {
validator: output => !output || RELEASE_TYPE.includes(output),
message: 'The "analyzeCommits" plugin output, if defined, must be a valid semver release type.',
},
},
verifyRelease: {
default: false,
config: {
validator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
message:
'The "verifyRelease" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
},
},
generateNotes: {
default: '@semantic-release/release-notes-generator',
config: {
validator: conf => !conf || validatePluginConfig(conf),
message:
'The "generateNotes" plugin, if defined, must be a single plugin definition. A plugin definition is either a string or an object with a path property.',
},
output: {
validator: output => !output || isString(output),
message: 'The "generateNotes" plugin output, if defined, must be a string.',
},
},
publish: {
default: ['@semantic-release/npm', '@semantic-release/github'],
config: {
validator: conf => Boolean(conf) && (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
message:
'The "publish" plugin is mandatory, and must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
},
},
};
+31
View File
@@ -0,0 +1,31 @@
const {isArray, isObject, omit} = require('lodash');
const SemanticReleaseError = require('@semantic-release/error');
const PLUGINS_DEFINITION = require('./definitions');
const pipeline = require('./pipeline');
const normalize = require('./normalize');
module.exports = (options, pluginsPath, logger) =>
Object.keys(PLUGINS_DEFINITION).reduce((plugins, pluginType) => {
const {config, output, default: def} = PLUGINS_DEFINITION[pluginType];
let pluginConfs;
if (options[pluginType]) {
// If an object is passed and the path is missing, set the default one for single plugins
if (isObject(options[pluginType]) && !options[pluginType].path && !isArray(def)) {
options[pluginType].path = def;
}
if (config && !config.validator(options[pluginType])) {
throw new SemanticReleaseError(config.message, 'EPLUGINCONF');
}
pluginConfs = options[pluginType];
} else {
pluginConfs = def;
}
const globalOpts = omit(options, Object.keys(PLUGINS_DEFINITION));
plugins[pluginType] = isArray(pluginConfs)
? pipeline(pluginConfs.map(conf => normalize(pluginType, pluginsPath, globalOpts, conf, logger, output)))
: normalize(pluginType, pluginsPath, globalOpts, pluginConfs, logger, output);
return plugins;
}, {});
+48
View File
@@ -0,0 +1,48 @@
const {dirname} = require('path');
const {inspect} = require('util');
const SemanticReleaseError = require('@semantic-release/error');
const {isString, isObject, isFunction, noop, cloneDeep} = require('lodash');
const resolveFrom = require('resolve-from');
module.exports = (pluginType, pluginsPath, globalOpts, pluginOpts, logger, validator) => {
if (!pluginOpts) {
return noop;
}
const {path, ...config} = isString(pluginOpts) || isFunction(pluginOpts) ? {path: pluginOpts} : pluginOpts;
if (!isFunction(pluginOpts)) {
if (pluginsPath[path]) {
logger.log('Load plugin %s from %s in shareable config %s', pluginType, path, pluginsPath[path]);
} else {
logger.log('Load plugin %s from %s', pluginType, path);
}
}
const basePath = pluginsPath[path]
? dirname(resolveFrom.silent(__dirname, pluginsPath[path]) || resolveFrom(process.cwd(), pluginsPath[path]))
: __dirname;
const plugin = isFunction(path)
? path
: require(resolveFrom.silent(basePath, path) || resolveFrom(process.cwd(), path));
let func;
if (isFunction(plugin)) {
func = plugin.bind(null, cloneDeep({...globalOpts, ...config}));
} else if (isObject(plugin) && plugin[pluginType] && isFunction(plugin[pluginType])) {
func = plugin[pluginType].bind(null, cloneDeep({...globalOpts, ...config}));
} else {
throw new SemanticReleaseError(
`The ${pluginType} plugin must be a function, or an object with a function in the property ${pluginType}.`,
'EPLUGINCONF'
);
}
return async input => {
const result = await func(cloneDeep(input));
if (validator && !validator.validator(result)) {
throw new Error(`${validator.message} Received: ${inspect(result)}`);
}
return result;
};
};
+19
View File
@@ -0,0 +1,19 @@
const {identity} = require('lodash');
const pReduce = require('p-reduce');
module.exports = steps => async (input, getNextInput = identity) => {
const results = [];
await pReduce(
steps,
async (prevResult, nextStep) => {
// Call the next step with the input computed at the end of the previous iteration
const result = await nextStep(prevResult);
// Save intermediary result
results.push(result);
// Prepare input for next step, passing the result of the previous iteration and the current one
return getNextInput(prevResult, result);
},
input
);
return results;
};
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 142 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

+92 -44
View File
@@ -1,7 +1,7 @@
{
"name": "semantic-release",
"description": "automated semver compliant package publishing",
"version": "0.0.0-placeholder",
"description": "Automated semver compliant package publishing",
"version": "0.0.0-development",
"author": "Stephan Bönnemann <stephan@boennemann.me> (http://boennemann.me)",
"bin": {
"semantic-release": "bin/semantic-release.js"
@@ -9,50 +9,69 @@
"bugs": {
"url": "https://github.com/semantic-release/semantic-release/issues"
},
"czConfig": {
"path": "node_modules/cz-conventional-changelog/"
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
},
"contributors": [
"Gregor Martynus (https://twitter.com/gr2m)",
"Pierre Vanduynslager (https://twitter.com/@pvdlg_)"
],
"dependencies": {
"@semantic-release/commit-analyzer": "^2.0.0",
"@semantic-release/condition-travis": "^5.0.2",
"@semantic-release/error": "^1.0.0",
"@semantic-release/last-release-npm": "^1.2.1",
"@semantic-release/release-notes-generator": "^3.0.1",
"git-head": "^1.2.1",
"github": "^8.0.0",
"lodash": "^4.0.0",
"nerf-dart": "^1.0.0",
"nopt": "^4.0.0",
"normalize-package-data": "^2.3.4",
"npmconf": "^2.1.2",
"npmlog": "^4.0.0",
"parse-github-repo-url": "^1.3.0",
"require-relative": "^0.8.7",
"run-auto": "^2.0.0",
"run-series": "^1.1.3",
"semver": "^5.2.0"
"@semantic-release/commit-analyzer": "^5.0.0",
"@semantic-release/error": "^2.1.0",
"@semantic-release/github": "^3.0.1",
"@semantic-release/npm": "^2.0.0",
"@semantic-release/release-notes-generator": "^6.0.0",
"chalk": "^2.3.0",
"commander": "^2.11.0",
"cosmiconfig": "^4.0.0",
"debug": "^3.1.0",
"env-ci": "^1.0.0",
"execa": "^0.9.0",
"get-stream": "^3.0.0",
"git-log-parser": "^1.2.0",
"lodash": "^4.17.4",
"marked": "^0.3.9",
"marked-terminal": "^2.0.0",
"p-reduce": "^1.0.0",
"read-pkg-up": "^3.0.0",
"resolve-from": "^4.0.0",
"semver": "^5.4.1"
},
"devDependencies": {
"coveralls": "^2.11.4",
"cz-conventional-changelog": "^1.1.4",
"mkdirp": "^0.5.1",
"mock-spawn": "^0.2.6",
"nixt": "^0.5.0",
"ava": "^0.24.0",
"codecov": "^3.0.0",
"commitizen": "^2.9.6",
"cz-conventional-changelog": "^2.0.0",
"delay": "^2.0.0",
"dockerode": "^2.5.2",
"eslint-config-prettier": "^2.5.0",
"eslint-plugin-prettier": "^2.3.0",
"file-url": "^2.0.2",
"fs-extra": "^5.0.0",
"got": "^8.0.0",
"js-yaml": "^3.10.0",
"mockserver-client": "^5.1.1",
"nock": "^9.0.2",
"npm-registry-couchapp": "^2.6.12",
"nyc": "^10.0.0",
"proxyquire": "^1.7.3",
"rimraf": "^2.5.0",
"standard": "^9.0.0",
"tap": "^10.0.1"
"nyc": "^11.2.1",
"p-retry": "^1.0.0",
"prettier": "~1.10.0",
"proxyquire": "^1.8.0",
"sinon": "^4.0.0",
"tempy": "^0.2.1",
"xo": "^0.18.2"
},
"engines": {
"node": ">=0.10",
"npm": ">=2"
"node": ">=8.3"
},
"files": [
"bin",
"src"
"docs",
"lib",
"index.js",
"cli.js"
],
"homepage": "https://github.com/semantic-release/semantic-release#readme",
"keywords": [
@@ -67,7 +86,26 @@
"version"
],
"license": "MIT",
"main": "bin/semantic-release.js",
"main": "index.js",
"nyc": {
"include": [
"lib/**/*.js",
"index.js",
"cli.js"
],
"reporter": [
"json",
"text",
"html"
],
"all": true
},
"prettier": {
"printWidth": 120,
"singleQuote": true,
"bracketSpacing": false,
"trailingComma": "es5"
},
"publishConfig": {
"tag": "next"
},
@@ -79,12 +117,22 @@
"url": "git+https://github.com/semantic-release/semantic-release.git"
},
"scripts": {
"coverage": "nyc report",
"coverage:upload": "npm run coverage -s -- --reporter=text-lcov | coveralls",
"pretest": "standard",
"semantic-release": "./bin/semantic-release.js pre && npm publish && ./bin/semantic-release.js post",
"test": "npm run test:unit && npm run test:integration",
"test:integration": "tap --no-cov test/scenarios/*.js",
"test:unit": "nyc tap --no-cov test/specs/*.js"
"cm": "git-cz",
"codecov": "codecov -f coverage/coverage-final.json",
"lint": "xo",
"pretest": "npm run lint",
"semantic-release": "./bin/semantic-release.js",
"test": "nyc ava -v"
},
"xo": {
"extends": [
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": 2
}
}
}
-79
View File
@@ -1,79 +0,0 @@
var childProcess = require('child_process')
var log = require('npmlog')
var SemanticReleaseError = require('@semantic-release/error')
module.exports = function (config, cb) {
var lastRelease = config.lastRelease
var options = config.options
var branch = options.branch
var from = lastRelease.gitHead
var range = (from ? from + '..' : '') + 'HEAD'
if (!from) return extract()
childProcess.exec('git branch --no-color --contains ' + from, function (err, stdout) {
var inHistory = false
var branches
if (!err && stdout) {
branches = stdout.split('\n')
.map(function (result) {
if (branch === result.replace('*', '').trim()) {
inHistory = true
return null
}
return result.trim()
})
.filter(function (branch) {
return !!branch
})
}
if (!inHistory) {
log.error('commits',
'The commit the last release of this package was derived from is not in the direct history of the "' + branch + '" branch.\n' +
'This means semantic-release can not extract the commits between now and then.\n' +
'This is usually caused by force pushing, releasing from an unrelated branch, or using an already existing package name.\n' +
'You can recover from this error by publishing manually or restoring the commit "' + from + '".' + (branches && branches.length
? '\nHere is a list of branches that still contain the commit in question: \n * ' + branches.join('\n * ')
: ''
))
return cb(new SemanticReleaseError('Commit not in history', 'ENOTINHISTORY'))
}
extract()
})
function extract () {
var child = childProcess.spawn('git', ['log', '-E', '--format=%H==SPLIT==%B==END==', range])
var stdout = ''
var err = ''
child.stdout.on('data', function (data) {
stdout += data
})
child.stderr.on('data', function (data) {
err += data
})
child.on('close', function (code) {
if (err || code) return cb(err)
cb(null, String(stdout).split('==END==\n')
.filter(function (raw) {
return !!raw.trim()
})
.map(function (raw) {
var data = raw.split('==SPLIT==')
return {
hash: data[0],
message: data[1]
}
})
)
})
}
}
-12
View File
@@ -1,12 +0,0 @@
module.exports = function (pkg, conf) {
if (pkg.publishConfig && pkg.publishConfig.registry) return pkg.publishConfig.registry
if (pkg.name[0] !== '@') return conf.get('registry') || 'https://registry.npmjs.org/'
var scope = pkg.name.split('/')[0]
var scopedRegistry = conf.get(scope + '/registry')
if (scopedRegistry) return scopedRegistry
return conf.get('registry') || 'https://registry.npmjs.org/'
}
-4
View File
@@ -1,4 +0,0 @@
/* istanbul ignore next */
module.exports = function (config, options, cb) {
cb(null)
}
-42
View File
@@ -1,42 +0,0 @@
var relative = require('require-relative')
var series = require('run-series')
var exports = module.exports = function (options) {
var plugins = {
analyzeCommits: exports.normalize(options.analyzeCommits, '@semantic-release/commit-analyzer'),
generateNotes: exports.normalize(options.generateNotes, '@semantic-release/release-notes-generator'),
getLastRelease: exports.normalize(options.getLastRelease, '@semantic-release/last-release-npm')
}
;['verifyConditions', 'verifyRelease'].forEach(function (plugin) {
if (!Array.isArray(options[plugin])) {
plugins[plugin] = exports.normalize(
options[plugin],
plugin === 'verifyConditions'
? '@semantic-release/condition-travis'
: './plugin-noop'
)
return
}
plugins[plugin] = function (pluginOptions, cb) {
var tasks = options[plugin].map(function (step) {
return exports.normalize(step, './plugin-noop').bind(null, pluginOptions)
})
series(tasks, cb)
}
})
return plugins
}
exports.normalize = function (pluginConfig, fallback) {
if (typeof pluginConfig === 'string') return relative(pluginConfig).bind(null, {})
if (pluginConfig && (typeof pluginConfig.path === 'string')) {
return relative(pluginConfig.path).bind(null, pluginConfig)
}
return require(fallback).bind(null, pluginConfig)
}
-21
View File
@@ -1,21 +0,0 @@
var SemanticReleaseError = require('@semantic-release/error')
module.exports = function (config, cb) {
var plugins = config.plugins
var lastRelease = config.lastRelease
plugins.analyzeCommits(config, function (err, type) {
if (err) return cb(err)
if (!type) {
return cb(new SemanticReleaseError(
'There are no relevant changes, so no new version is released.',
'ENOCHANGE'
))
}
if (!lastRelease.version) return cb(null, 'initial')
cb(null, type)
})
}
-40
View File
@@ -1,40 +0,0 @@
var SemanticReleaseError = require('@semantic-release/error')
module.exports = function (config) {
var pkg = config.pkg
var options = config.options
var env = config.env
var errors = []
if (!pkg.name) {
errors.push(new SemanticReleaseError(
'No "name" found in package.json.',
'ENOPKGNAME'
))
}
if (!pkg.repository || !pkg.repository.url) {
errors.push(new SemanticReleaseError(
'No "repository" found in package.json.',
'ENOPKGREPO'
))
}
if (options.debug) return errors
if (!options.githubToken) {
errors.push(new SemanticReleaseError(
'No github token specified.',
'ENOGHTOKEN'
))
}
if (!(env.NPM_TOKEN || (env.NPM_OLD_TOKEN && env.NPM_EMAIL))) {
errors.push(new SemanticReleaseError(
'No npm token specified.',
'ENONPMTOKEN'
))
}
return errors
}
-71
View File
@@ -1,71 +0,0 @@
var url = require('url')
var gitHead = require('git-head')
var GitHubApi = require('github')
var parseSlug = require('parse-github-repo-url')
module.exports = function (config, cb) {
var pkg = config.pkg
var options = config.options
var plugins = config.plugins
var ghConfig = options.githubUrl ? url.parse(options.githubUrl) : {}
var github = new GitHubApi({
port: ghConfig.port,
protocol: (ghConfig.protocol || '').split(':')[0] || null,
host: ghConfig.hostname,
pathPrefix: options.githubApiPathPrefix || null
})
plugins.generateNotes(config, function (err, log) {
if (err) return cb(err)
gitHead(function (err, hash) {
if (err) return cb(err)
var ghRepo = parseSlug(pkg.repository.url)
var tag = {
owner: ghRepo[0],
repo: ghRepo[1],
ref: 'refs/tags/v' + pkg.version,
sha: hash
}
var release = {
owner: ghRepo[0],
repo: ghRepo[1],
tag_name: 'v' + pkg.version,
name: 'v' + pkg.version,
target_commitish: options.branch,
draft: !!options.debug,
body: log
}
if (options.debug && !options.githubToken) {
return cb(null, false, release)
}
github.authenticate({
type: 'token',
token: options.githubToken
})
if (options.debug) {
return github.repos.createRelease(release, function (err) {
if (err) return cb(err)
cb(null, true, release)
})
}
github.gitdata.createReference(tag, function (err) {
if (err) return cb(err)
github.repos.createRelease(release, function (err) {
if (err) return cb(err)
cb(null, true, release)
})
})
})
})
}
-45
View File
@@ -1,45 +0,0 @@
var _ = require('lodash')
var auto = require('run-auto')
var semver = require('semver')
var getCommits = require('./lib/commits')
var getType = require('./lib/type')
module.exports = function (config, cb) {
var plugins = config.plugins
auto({
lastRelease: plugins.getLastRelease.bind(null, config),
commits: ['lastRelease', function (results, cb) {
getCommits(_.assign({
lastRelease: results.lastRelease
}, config),
cb)
}],
type: ['commits', 'lastRelease', function (results, cb) {
getType(_.assign({
commits: results.commits,
lastRelease: results.lastRelease
}, config),
cb)
}]
}, function (err, results) {
if (err) return cb(err)
var nextRelease = {
type: results.type,
version: results.type === 'initial'
? '1.0.0'
: semver.inc(results.lastRelease.version, results.type)
}
plugins.verifyRelease(_.assign({
commits: results.commits,
lastRelease: results.lastRelease,
nextRelease: nextRelease
}, config), function (err) {
if (err) return cb(err)
cb(null, nextRelease)
})
})
}
+2
View File
@@ -0,0 +1,2 @@
module.exports = () => {};
+8
View File
@@ -0,0 +1,8 @@
module.exports = {
verifyConditions: () => {},
getLastRelease: () => {},
analyzeCommits: () => {},
verifyRelease: () => {},
generateNotes: () => {},
publish: () => {},
};
+14
View File
@@ -0,0 +1,14 @@
const SemanticReleaseError = require('@semantic-release/error');
class InheritedError extends SemanticReleaseError {
constructor(message, code, newProperty) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.code = code;
}
}
module.exports = () => {
throw new InheritedError('Inherited error', 'EINHERITED');
};
+5
View File
@@ -0,0 +1,5 @@
module.exports = () => {
const error = new Error('a');
error.errorProperty = 'errorProperty';
throw error;
};
+1
View File
@@ -0,0 +1 @@
module.exports = () => {};
+1
View File
@@ -0,0 +1 @@
module.exports = (pluginConfig, options) => ({pluginConfig, options});
+464
View File
@@ -0,0 +1,464 @@
import test from 'ava';
import {stub} from 'sinon';
import getCommits from '../lib/get-commits';
import {
gitRepo,
gitCommits,
gitCheckout,
gitTagVersion,
gitShallowClone,
gitTags,
gitLog,
gitDetachedHead,
} from './helpers/git-utils';
// Save the current working diretory
const cwd = process.cwd();
test.beforeEach(t => {
// Stub the logger functions
t.context.log = stub();
t.context.error = stub();
t.context.logger = {log: t.context.log, error: t.context.error};
});
test.afterEach.always(() => {
// Restore the current working directory
process.chdir(cwd);
});
test.serial('Get all commits when there is no last release', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module
const result = await getCommits({}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
t.falsy(result.lastRelease.gitTag);
});
test.serial('Get all commits with gitTags', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second'])).concat(commits);
// Retrieve the commits with the commits module
const result = await getCommits({}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[0].gitTags, '(HEAD -> master)');
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
t.is(result.commits[1].gitTags, '(tag: v1.0.0)');
});
test.serial('Get all commits when there is no last release, including the ones not in the shallow clone', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second']);
// Create a shallow clone with only 1 commit
await gitShallowClone(repo);
// Verify the shallow clone contains only one commit
t.is((await gitLog()).length, 1);
// Retrieve the commits with the commits module
const result = await getCommits({}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
t.falsy(result.lastRelease.gitTag);
});
test.serial('Get all commits since gitHead (from lastRelease)', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second', 'Third']);
// Retrieve the commits with the commits module, since commit 'First'
const result = await getCommits({gitHead: commits[commits.length - 1].hash}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead, commits[commits.length - 1].hash);
t.falsy(result.lastRelease.version);
t.falsy(result.lastRelease.gitTag);
});
test.serial('Get all commits since gitHead (from lastRelease) on a detached head repo', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second', 'Third']);
// Create a detached head repo at commit 'feat: Second'
await gitDetachedHead(repo, commits[1].hash);
// Retrieve the commits with the commits module, since commit 'First'
const result = await getCommits({gitHead: commits[commits.length - 1].hash}, 'master', t.context.logger);
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
t.is(result.commits.length, 1);
t.is(result.commits[0].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[0].message, commits[1].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead, commits[commits.length - 1].hash);
t.falsy(result.lastRelease.version);
t.falsy(result.lastRelease.gitTag);
});
test.serial('Get all commits since gitHead (from tag) ', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
const result = await getCommits({version: '1.0.0', gitHead: 'missing_ref'}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.gitTag, '1.0.0');
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get all commits since gitHead (from tag) on a detached head repo', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Create a detached head repo at commit 'feat: Second'
await gitDetachedHead(repo, commits[1].hash);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag 1.0.0)
const result = await getCommits({version: '1.0.0', gitHead: 'missing_ref'}, 'master', t.context.logger);
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
t.is(result.commits.length, 1);
t.is(result.commits[0].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[0].message, commits[1].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.gitTag, '1.0.0');
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get all commits since gitHead (from tag formatted like v<version>) ', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
const result = await getCommits({version: '1.0.0', gitHead: 'missing_ref'}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.gitTag, 'v1.0.0');
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get all commits since gitHead, when gitHead is missing from the shallow clone', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second', 'Third']);
// Create a shallow clone with only 1 commit and no tags
await gitShallowClone(repo);
// Retrieve the commits with the commits module, since commit 'First'
const result = await getCommits(
{version: '1.0.0', gitHead: commits[commits.length - 1].hash},
'master',
t.context.logger
);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.version, '1.0.0');
t.falsy(result.lastRelease.gitTag);
});
test.serial('Get all commits since gitHead from tag, when tags is missing from the shallow clone', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Create a shallow clone with only 1 commit and no tags
await gitShallowClone(repo);
// Verify the shallow clone does not contains any tags
t.is((await gitTags()).length, 0);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
const result = await getCommits({version: '1.0.0', gitHead: 'missing_ref'}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.gitTag, 'v1.0.0');
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Return empty array if lastRelease.gitHead is the last commit', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module, since commit 'Second' (therefore none)
const result = await getCommits({gitHead: commits[0].hash, version: '1.0.0'}, 'master', t.context.logger);
// Verify no commit is retrieved
t.deepEqual(result.commits, []);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[0].hash);
t.is(result.lastRelease.version, '1.0.0');
t.falsy(result.lastRelease.gitTag);
});
test.serial('Return empty array if there is no commits', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Retrieve the commits with the commits module
const result = await getCommits({}, 'master', t.context.logger);
// Verify no commit is retrieved
t.deepEqual(result.commits, []);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
});
test.serial('Throws ENOTINHISTORY error if gitHead is not in history', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module
const error = await t.throws(getCommits({gitHead: 'notinhistory'}, 'master', t.context.logger));
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.is(error.name, 'SemanticReleaseError');
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.args[0][0], /history of the "master" branch/);
// Verify the log function has been called with a message mentionning the missing gitHead
t.regex(t.context.error.args[0][0], /restoring the commit "notinhistory"/);
});
test.serial('Throws ENOTINHISTORY error if gitHead is not in branch history but present in others', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First', 'Second']);
// Create the new branch 'other-branch' from master
await gitCheckout('other-branch');
// Add commits to the 'other-branch' branch
const commitsBranch = await gitCommits(['Third', 'Fourth']);
await gitCheckout('master', false);
// Retrieve the commits with the commits module
const error = await t.throws(
getCommits({version: '1.0.1', gitHead: commitsBranch[0].hash}, 'master', t.context.logger)
);
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.is(error.name, 'SemanticReleaseError');
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.args[0][0], /history of the "master" branch/);
// Verify the log function has been called with a message mentionning the missing gitHead
t.regex(t.context.error.args[0][0], new RegExp(`restoring the commit "${commitsBranch[0].hash}"`));
});
test.serial('Throws ENOTINHISTORY error if gitHead is not in detached head but present in other branch', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commit to the master branch
await gitCommits(['First']);
// Create the new branch 'other-branch' from master
await gitCheckout('other-branch');
// Add commits to the 'other-branch' branch
const commitsBranch = await gitCommits(['Second', 'Third']);
await gitCheckout('master', false);
// Add new commit to master branch
const commitsMaster = await gitCommits(['Fourth']);
// Create a detached head repo at commit 'Fourth'
await gitDetachedHead(repo, commitsMaster[0].hash);
// Retrieve the commits with the commits module, since commit 'Second'
const error = await t.throws(
getCommits({version: '1.0.1', gitHead: commitsBranch[0].hash}, 'master', t.context.logger)
);
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.is(error.name, 'SemanticReleaseError');
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.args[0][0], /history of the "master" branch/);
// Verify the log function has been called with a message mentionning the missing gitHead
t.regex(t.context.error.args[0][0], new RegExp(`restoring the commit "${commitsBranch[0].hash}"`));
});
test.serial('Throws ENOTINHISTORY error when a tag is not in branch history but present in others', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First', 'Second']);
// Create the new branch 'other-branch' from master
await gitCheckout('other-branch');
// Add commits to the 'other-branch' branch
await gitCommits(['Third']);
// Create the tag corresponding to version 1.0.0
const shaTag = await gitTagVersion('v1.0.0');
await gitCheckout('master', false);
// Add new commit to the master branch
await gitCommits(['Forth']);
// Retrieve the commits with the commits module
const error = await t.throws(getCommits({version: '1.0.0', gitHead: shaTag}, 'master', t.context.logger));
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.is(error.name, 'SemanticReleaseError');
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.args[0][0], /history of the "master" branch/);
// Verify the log function has been called with a message mentionning the missing gitHead
t.regex(t.context.error.args[0][0], new RegExp(`restoring the commit "${shaTag}"`));
});
+452
View File
@@ -0,0 +1,452 @@
import {format} from 'util';
import test from 'ava';
import {writeFile, outputJson} from 'fs-extra';
import {omit} from 'lodash';
import proxyquire from 'proxyquire';
import {stub} from 'sinon';
import yaml from 'js-yaml';
import {gitRepo, gitCommits, gitShallowClone, gitAddConfig} from './helpers/git-utils';
// Save the current process.env
const envBackup = Object.assign({}, process.env);
// Save the current working diretory
const cwd = process.cwd();
test.beforeEach(t => {
t.context.plugins = stub().returns({});
t.context.getConfig = proxyquire('../lib/get-config', {'./plugins': t.context.plugins});
});
test.afterEach.always(() => {
// Restore process.env
process.env = envBackup;
// Restore the current working directory
process.chdir(cwd);
});
test.serial('Default values, reading repositoryUrl from package.json', async t => {
const pkg = {repository: 'git@package.com:owner/module.git'};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
await gitCommits(['First']);
// Add remote.origin.url config
await gitAddConfig('remote.origin.url', 'git@repo.com:owner/module.git');
// Create package.json in repository root
await outputJson('./package.json', pkg);
const {options} = await t.context.getConfig();
// Verify the default options are set
t.is(options.branch, 'master');
t.is(options.repositoryUrl, 'git@package.com:owner/module.git');
});
test.serial('Default values, reading repositoryUrl from repo if not set in package.json', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add remote.origin.url config
await gitAddConfig('remote.origin.url', 'git@repo.com:owner/module.git');
const {options} = await t.context.getConfig();
// Verify the default options are set
t.is(options.branch, 'master');
t.is(options.repositoryUrl, 'git@repo.com:owner/module.git');
});
test.serial('Default values, reading repositoryUrl (http url) from package.json if not set in repo', async t => {
const pkg = {repository: 'git+https://hostname.com/owner/module.git'};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await outputJson('./package.json', pkg);
const {options} = await t.context.getConfig();
// Verify the default options are set
t.is(options.branch, 'master');
t.is(options.repositoryUrl, pkg.repository);
});
test.serial('Read options from package.json', async t => {
const release = {
analyzeCommits: 'analyzeCommits',
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await outputJson('./package.json', {release});
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from package.json
t.deepEqual(options, release);
// Verify the plugins module is called with the plugin options from package.json
t.deepEqual(t.context.plugins.args[0][0], release);
});
test.serial('Read options from .releaserc.yml', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await writeFile('.releaserc.yml', yaml.safeDump(release));
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from package.json
t.deepEqual(options, release);
// Verify the plugins module is called with the plugin options from package.json
t.deepEqual(t.context.plugins.args[0][0], release);
});
test.serial('Read options from .releaserc.json', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await outputJson('.releaserc.json', release);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from package.json
t.deepEqual(options, release);
// Verify the plugins module is called with the plugin options from package.json
t.deepEqual(t.context.plugins.args[0][0], release);
});
test.serial('Read options from .releaserc.js', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await writeFile('.releaserc.js', `module.exports = ${JSON.stringify(release)}`);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from package.json
t.deepEqual(options, release);
// Verify the plugins module is called with the plugin options from package.json
t.deepEqual(t.context.plugins.args[0][0], release);
});
test.serial('Read options from release.config.js', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await writeFile('release.config.js', `module.exports = ${JSON.stringify(release)}`);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from package.json
t.deepEqual(options, release);
// Verify the plugins module is called with the plugin options from package.json
t.deepEqual(t.context.plugins.args[0][0], release);
});
test.serial('Prioritise CLI/API parameters over file configuration and git repo', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_pkg'},
branch: 'branch_pkg',
};
const options = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_cli'},
branch: 'branch_cli',
repositoryUrl: 'http://cli-url.com/owner/package',
};
const pkg = {release, repository: 'git@hostname.com:owner/module.git'};
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
await gitCommits(['First']);
// Create a clone
await gitShallowClone(repo);
// Create package.json in repository root
await outputJson('./package.json', pkg);
const result = await t.context.getConfig(options);
// Verify the options contains the plugin config from CLI/API
t.deepEqual(result.options, options);
// Verify the plugins module is called with the plugin options from CLI/API
t.deepEqual(t.context.plugins.args[0][0], options);
});
test.serial('Read configuration from file path in "extends"', async t => {
const release = {extends: './shareable.json'};
const shareable = {
analyzeCommits: 'analyzeCommits',
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json and shareable.json in repository root
await outputJson('./package.json', {release});
await outputJson('./shareable.json', shareable);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from shareable.json
t.deepEqual(options, shareable);
// Verify the plugins module is called with the plugin options from shareable.json
t.deepEqual(t.context.plugins.args[0][0], shareable);
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: './shareable.json',
generateNotes: './shareable.json',
getLastRelease: './shareable.json',
});
});
test.serial('Read configuration from module path in "extends"', async t => {
const release = {extends: 'shareable'};
const shareable = {
analyzeCommits: 'analyzeCommits',
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json and shareable.json in repository root
await outputJson('./package.json', {release});
await outputJson('./node_modules/shareable/index.json', shareable);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from shareable.json
t.deepEqual(options, shareable);
// Verify the plugins module is called with the plugin options from shareable.json
t.deepEqual(t.context.plugins.args[0][0], shareable);
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: 'shareable',
generateNotes: 'shareable',
getLastRelease: 'shareable',
});
});
test.serial('Read configuration from an array of paths in "extends"', async t => {
const release = {extends: ['./shareable1.json', './shareable2.json']};
const shareable1 = {
analyzeCommits: 'analyzeCommits1',
getLastRelease: {path: 'getLastRelease1', param: 'getLastRelease_param1'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
const shareable2 = {
analyzeCommits: 'analyzeCommits2',
generateNotes: 'generateNotes2',
getLastRelease: {path: 'getLastRelease2', param: 'getLastRelease_param2'},
branch: 'test_branch',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json and shareable.json in repository root
await outputJson('./package.json', {release});
await outputJson('./shareable1.json', shareable1);
await outputJson('./shareable2.json', shareable2);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from shareable1.json and shareable2.json
t.deepEqual(options, {...shareable1, ...shareable2});
// Verify the plugins module is called with the plugin options from shareable1.json and shareable2.json
t.deepEqual(t.context.plugins.args[0][0], {...shareable1, ...shareable2});
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits1: './shareable1.json',
analyzeCommits2: './shareable2.json',
generateNotes2: './shareable2.json',
getLastRelease1: './shareable1.json',
getLastRelease2: './shareable2.json',
});
});
test.serial('Prioritize configuration from config file over "extends"', async t => {
const release = {
extends: './shareable.json',
branch: 'test_pkg',
generateNotes: 'generateNotes',
publish: [{path: 'publishPkg', param: 'publishPkg_param'}],
};
const shareable = {
analyzeCommits: 'analyzeCommits',
generateNotes: 'generateNotesShareable',
publish: [{path: 'publishShareable', param: 'publishShareable_param'}],
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json and shareable.json in repository root
await outputJson('./package.json', {release});
await outputJson('./shareable.json', shareable);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from package.json and shareable.json
t.deepEqual(options, omit({...shareable, ...release}, 'extends'));
// Verify the plugins module is called with the plugin options from package.json and shareable.json
t.deepEqual(t.context.plugins.args[0][0], omit({...shareable, ...release}, 'extends'));
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: './shareable.json',
generateNotesShareable: './shareable.json',
publishShareable: './shareable.json',
});
});
test.serial('Prioritize configuration from cli/API options over "extends"', async t => {
const opts = {
extends: './shareable2.json',
branch: 'branch_opts',
publish: [{path: 'publishOpts', param: 'publishOpts_param'}],
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
const release = {
extends: './shareable1.json',
branch: 'branch_pkg',
generateNotes: 'generateNotes',
publish: [{path: 'publishPkg', param: 'publishPkg_param'}],
};
const shareable1 = {
analyzeCommits: 'analyzeCommits1',
generateNotes: 'generateNotesShareable1',
publish: [{path: 'publishShareable', param: 'publishShareable_param1'}],
branch: 'test_branch1',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
const shareable2 = {
analyzeCommits: 'analyzeCommits2',
publish: [{path: 'publishShareable', param: 'publishShareable_param2'}],
branch: 'test_branch2',
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json, shareable1.json and shareable2.json in repository root
await outputJson('./package.json', {release});
await outputJson('./shareable1.json', shareable1);
await outputJson('./shareable2.json', shareable2);
const {options} = await t.context.getConfig(opts);
// Verify the options contains the plugin config from package.json and shareable2.json
t.deepEqual(options, omit({...shareable2, ...release, ...opts}, 'extends'));
// Verify the plugins module is called with the plugin options from package.json and shareable2.json
t.deepEqual(t.context.plugins.args[0][0], omit({...shareable2, ...release, ...opts}, 'extends'));
});
test.serial('Allow to unset properties defined in shareable config with "null"', async t => {
const release = {
extends: './shareable.json',
getLastRelease: null,
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
const shareable = {
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json and shareable.json in repository root
await outputJson('./package.json', {release});
await outputJson('./shareable.json', shareable);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from shareable.json
t.deepEqual(options, {...omit(shareable, 'getLastRelease'), ...omit(release, ['extends', 'getLastRelease'])});
// Verify the plugins module is called with the plugin options from shareable.json
t.deepEqual(t.context.plugins.args[0][0], {
...omit(shareable, 'getLastRelease'),
...omit(release, ['extends', 'getLastRelease']),
});
t.deepEqual(t.context.plugins.args[0][1], {
generateNotes: './shareable.json',
getLastRelease: './shareable.json',
});
});
test.serial('Allow to unset properties defined in shareable config with "undefined"', async t => {
const release = {
extends: './shareable.json',
getLastRelease: undefined,
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
};
const shareable = {
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json and release.config.js in repository root
// await outputJson('./package.json', {release});
await writeFile('release.config.js', `module.exports = ${format(release)}`);
await outputJson('./shareable.json', shareable);
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from shareable.json
t.deepEqual(options, {...omit(shareable, 'getLastRelease'), ...omit(release, ['extends', 'getLastRelease'])});
// Verify the plugins module is called with the plugin options from shareable.json
t.deepEqual(t.context.plugins.args[0][0], {
...omit(shareable, 'getLastRelease'),
...omit(release, ['extends', 'getLastRelease']),
});
t.deepEqual(t.context.plugins.args[0][1], {
generateNotes: './shareable.json',
getLastRelease: './shareable.json',
});
});
test.serial('Throw an Error if one of the shareable config cannot be found', async t => {
const release = {extends: ['./shareable1.json', 'non-existing-path']};
const shareable = {analyzeCommits: 'analyzeCommits'};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json and shareable.json in repository root
await outputJson('./package.json', {release});
await outputJson('./shareable1.json', shareable);
const error = await t.throws(t.context.getConfig(), Error);
t.is(error.message, "Cannot find module 'non-existing-path'");
t.is(error.code, 'MODULE_NOT_FOUND');
});
+29
View File
@@ -0,0 +1,29 @@
import test from 'ava';
import {stub} from 'sinon';
import getNextVersion from '../lib/get-next-version';
test.beforeEach(t => {
// Stub the logger functions
t.context.log = stub();
t.context.logger = {log: t.context.log};
});
test('Increase version for patch release', t => {
const version = getNextVersion('patch', {version: '1.0.0'}, t.context.logger);
t.is(version, '1.0.1');
});
test('Increase version for minor release', t => {
const version = getNextVersion('minor', {version: '1.0.0'}, t.context.logger);
t.is(version, '1.1.0');
});
test('Increase version for major release', t => {
const version = getNextVersion('major', {version: '1.0.0'}, t.context.logger);
t.is(version, '2.0.0');
});
test('Return 1.0.0 if there is no previous release', t => {
const version = getNextVersion('minor', {}, t.context.logger);
t.is(version, '1.0.0');
});
+128
View File
@@ -0,0 +1,128 @@
import test from 'ava';
import fileUrl from 'file-url';
import {gitTagHead, gitCommitTag, isCommitInHistory, unshallow, gitHead, repoUrl} from '../lib/git';
import {
gitRepo,
gitCommits,
gitCheckout,
gitTagVersion,
gitShallowClone,
gitLog,
gitAddConfig,
} from './helpers/git-utils';
// Save the current working diretory
const cwd = process.cwd();
test.afterEach.always(() => {
// Restore the current working directory
process.chdir(cwd);
});
test.serial('Get the last commit sha', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First']);
const result = await gitHead();
t.is(result.substring(0, 7), commits[0].hash);
});
test.serial('Throw error if the last commit sha cannot be found', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
await t.throws(gitHead(), Error);
});
test.serial('Unshallow repository', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
await gitCommits(['First', 'Second']);
// Create a shallow clone with only 1 commit
await gitShallowClone(repo);
// Verify the shallow clone contains only one commit
t.is((await gitLog()).length, 1);
await unshallow();
// Verify the shallow clone contains all the commits
t.is((await gitLog()).length, 2);
});
test.serial('Do not throw error when unshallow a complete repository', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First']);
await t.notThrows(unshallow());
});
test.serial('Verify if the commit `sha` is in the direct history of the current branch', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First']);
// Create the new branch 'other-branch' from master
await gitCheckout('other-branch');
// Add commits to the 'other-branch' branch
const otherCommits = await gitCommits(['Second']);
await gitCheckout('master', false);
t.true(await isCommitInHistory(commits[0].hash));
t.false(await isCommitInHistory(otherCommits[0].hash));
});
test.serial('Get the tag associated with a commit sha or "null" if the commit does not exists', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
t.is(await gitCommitTag(commits[0].hash), 'v1.0.0');
t.falsy(await gitCommitTag('missing_sha'));
});
test.serial('Get the commit sha for a given tag or "null" if the tag does not exists', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
t.is((await gitTagHead('v1.0.0')).substring(0, 7), commits[0].hash);
t.falsy(await gitTagHead('missing_tag'));
});
test.serial('Return git remote repository url from config', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add remote.origin.url config
await gitAddConfig('remote.origin.url', 'git@hostname.com:owner/package.git');
t.is(await repoUrl(), 'git@hostname.com:owner/package.git');
});
test.serial('Return git remote repository url set while cloning', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
await gitCommits(['First']);
// Create a clone
await gitShallowClone(repo);
t.is(await repoUrl(), fileUrl(repo));
});
test.serial('Return "undefined" if git repository url is not set', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
t.is(await repoUrl(), undefined);
});
+155
View File
@@ -0,0 +1,155 @@
import tempy from 'tempy';
import execa from 'execa';
import fileUrl from 'file-url';
import pReduce from 'p-reduce';
/**
* Commit message informations.
*
* @typedef {Object} Commit
* @property {string} branch The commit branch.
* @property {string} hash The commit hash.
* @property {string} message The commit message.
*/
/**
* Create a temporary git repository and change the current working directory to the repository root.
*
* @return {string} The path of the repository.
*/
export async function gitRepo() {
const dir = tempy.directory();
process.chdir(dir);
await execa('git', ['init']);
await gitCheckout('master');
return dir;
}
/**
* Create commits on the current git repository.
*
* @param {Array<string>} messages commit messages.
*
* @returns {Array<Commit>} The created commits, in reverse order (to match `git log` order).
*/
export async function gitCommits(messages) {
return (await pReduce(
messages,
async (commits, msg) => {
const {stdout} = await execa('git', ['commit', '-m', msg, '--allow-empty', '--no-gpg-sign']);
const [, branch, hash, message] = /^\[(\w+)\(?.*?\)?(\w+)\] (.+)$/.exec(stdout);
commits.push({branch, hash, message});
return commits;
},
[]
)).reverse();
}
/**
* Amend a commit (rewriting the sha) on the current git repository.
*
* @param {string} messages commit message.
*
* @returns {Array<Commit>} the created commits.
*/
export async function gitAmmendCommit(msg) {
const {stdout} = await execa('git', ['commit', '--amend', '-m', msg, '--allow-empty']);
const [, branch, hash, message] = /^\[(\w+)\(?.*?\)?(\w+)\] (.+)(.|\s)+$/.exec(stdout);
return {branch, hash, message};
}
/**
* Checkout a branch on the current git repository.
*
* @param {string} branch Branch name.
* @param {boolean} create `true` to create the branche ans switch, `false` to only switch.
*/
export async function gitCheckout(branch, create = true) {
await execa('git', create ? ['checkout', '-b', branch] : ['checkout', branch]);
}
/**
* @return {string} The sha of the head commit in the current git repository.
*/
export async function gitHead() {
return (await execa('git', ['rev-parse', 'HEAD'])).stdout;
}
/**
* Create a tag on the head commit in the current git repository.
*
* @param {string} tagName The tag name to create.
* @param {string} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit.
*
* @return {string} The commit sha of the created tag.
*/
export async function gitTagVersion(tagName, sha) {
await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName]);
return (await execa('git', ['rev-list', '-1', '--tags', tagName])).stdout;
}
/**
* @return {Array<string>} The list of tags from the current git repository.
*/
export async function gitTags() {
return (await execa('git', ['tag'])).stdout.split('\n').filter(tag => Boolean(tag));
}
/**
* @return {Array<string>} The list of commit sha from the current git repository.
*/
export async function gitLog() {
return (await execa('git', ['log', '--format=format:%H'])).stdout.split('\n').filter(sha => Boolean(sha));
}
/**
* Create a shallow clone of a git repository and change the current working directory to the cloned repository root.
* The shallow will contain a limited number of commit and no tags.
*
* @param {string} origin The path of the repository to clone.
* @param {number} [depth=1] The number of commit to clone.
* @return {string} The path of the cloned repository.
*/
export async function gitShallowClone(origin, branch = 'master', depth = 1) {
const dir = tempy.directory();
process.chdir(dir);
await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, fileUrl(origin), dir]);
return dir;
}
/**
* Create a git repo with a detached head from another git repository and change the current working directory to the new repository root.
*
* @param {string} origin The path of the repository to clone.
* @param {number} head A commit sha of the origin repo that will become the detached head of the new one.
* @return {string} The path of the new repository.
*/
export async function gitDetachedHead(origin, head) {
const dir = tempy.directory();
process.chdir(dir);
await execa('git', ['init']);
await execa('git', ['remote', 'add', 'origin', origin]);
await execa('git', ['fetch']);
await execa('git', ['checkout', head]);
return dir;
}
/**
* Pack heads and tags of the current git repository.
*/
export async function gitPackRefs() {
await execa('git', ['pack-refs', '--all']);
}
/**
* Add a new Git configuration.
*
* @param {string} name Config name.
* @param {string} value Config value.
*/
export async function gitAddConfig(name, value) {
await execa('git', ['config', '--add', name, value]);
}
+16
View File
@@ -0,0 +1,16 @@
import nock from 'nock';
/**
* Retun a `nock` object setup to respond to a github authentication request. Other expectation and responses can be chained.
*
* @param {String} [githubToken='GH_TOKEN'] The github token to return in the authentication response.
* @param {String} [githubUrl='https://api.github.com'] The url on which to intercept http requests.
* @return {Object} A `nock` object ready to respond to a github authentication request.
*/
export default function authenticate({
githubToken = 'GH_TOKEN',
githubUrl = 'https://api.github.com',
githubApiPathPrefix = '',
} = {}) {
return nock(`${githubUrl}/${githubApiPathPrefix}`, {reqheaders: {Authorization: `token ${githubToken}`}});
}
+107
View File
@@ -0,0 +1,107 @@
import Docker from 'dockerode';
import getStream from 'get-stream';
import got from 'got';
import pRetry from 'p-retry';
import {mockServerClient} from 'mockserver-client';
const IMAGE = 'jamesdbloom/mockserver:latest';
const MOCK_SERVER_PORT = 1080;
const MOCK_SERVER_HOST = 'localhost';
const docker = new Docker();
let container;
/**
* Download the `mockserver` Docker image, create a new container and start it.
*
* @return {Promise} Promise that resolves when the container is started.
*/
async function start() {
await getStream(await docker.pull(IMAGE));
container = await docker.createContainer({
Tty: true,
Image: IMAGE,
PortBindings: {[`${MOCK_SERVER_PORT}/tcp`]: [{HostPort: `${MOCK_SERVER_PORT}`}]},
});
await container.start();
try {
// Wait for the mock server to be ready
await pRetry(() => got.put(`http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}/status`, {cache: false}), {
retries: 7,
minTimeout: 1000,
factor: 2,
});
} catch (err) {
throw new Error(`Couldn't start mock-server after 2 min`);
}
}
/**
* Stop and remote the `mockserver` Docker container.
*
* @return {Promise} Promise that resolves when the container is stopped.
*/
async function stop() {
await container.stop();
await container.remove();
}
/**
* @type {Object} A `mockserver` client configured to connect to the current instance.
*/
const client = mockServerClient(MOCK_SERVER_HOST, MOCK_SERVER_PORT);
/**
* @type {string} the url of the `mockserver` instance
*/
const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`;
/**
* Set up the `mockserver` instance response for a specific request.
*
* @param {string} path URI for which to respond.
* @param {Object} request Request expectation. The http request made on `path` has to match those criteria in order to be valid.
* @param {Object} request.body The JSON body the expected request must match.
* @param {Object} request.headers The headers the expected request must match.
* @param {Object} response The http response to return when receiving a request on `path`.
* @param {String} [response.method='POST'] The http method for which to respond.
* @param {number} [response.statusCode=200] The status code to respond.
* @param {Object} response.body The JSON object to respond in the response body.
* @return {Object} An object representation the expectation. Pass to the `verify` function to validate the `mockserver` has been called with a `request` matching the expectations.
*/
async function mock(
path,
{body: requestBody, headers: requestHeaders},
{method = 'POST', statusCode = 200, body: responseBody}
) {
await client.mockAnyResponse({
httpRequest: {path, method},
httpResponse: {
statusCode,
headers: [{name: 'Content-Type', values: ['application/json; charset=utf-8']}],
body: JSON.stringify(responseBody),
},
times: {remainingTimes: 1, unlimited: false},
});
return {
method,
path,
headers: requestHeaders,
body: requestBody
? {type: 'JSON', json: JSON.stringify(requestBody), matchType: 'ONLY_MATCHING_FIELDS'}
: undefined,
};
}
/**
* Verify the `mockserver` has been called with a requestion matching expectations. The `expectation` is created with the `mock` function.
*
* @param {Object} expectation The expectation created with `mock` function.
* @return {Promise} A Promise that resolves if the expectation is met or reject otherwise.
*/
async function verify(expectation) {
return client.verify(expectation);
}
export default {start, stop, mock, verify, url};
+80
View File
@@ -0,0 +1,80 @@
import Docker from 'dockerode';
import getStream from 'get-stream';
import got from 'got';
import delay from 'delay';
import pRetry from 'p-retry';
const IMAGE = 'npmjs/npm-docker-couchdb:1.6.1';
const SERVER_PORT = 15986;
const COUCHDB_PORT = 5984;
const SERVER_HOST = 'localhost';
const NPM_USERNAME = 'integration';
const NPM_PASSWORD = 'suchsecure';
const NPM_EMAIL = 'integration@test.com';
const docker = new Docker();
let container;
/**
* Download the `npm-docker-couchdb` Docker image, create a new container and start it.
*
* @return {Promise} Promise that resolves when the container is started.
*/
async function start() {
await getStream(await docker.pull(IMAGE));
container = await docker.createContainer({
Tty: true,
Image: IMAGE,
PortBindings: {[`${COUCHDB_PORT}/tcp`]: [{HostPort: `${SERVER_PORT}`}]},
});
await container.start();
await delay(3000);
try {
// Wait for the registry to be ready
await pRetry(() => got(`http://${SERVER_HOST}:${SERVER_PORT}/registry/_design/app`, {cache: false}), {
retries: 7,
minTimeout: 1000,
factor: 2,
});
} catch (err) {
throw new Error(`Couldn't start npm-docker-couchdb after 2 min`);
}
// Create user
await got(`http://${SERVER_HOST}:${SERVER_PORT}/_users/org.couchdb.user:${NPM_USERNAME}`, {
json: true,
auth: 'admin:admin',
method: 'PUT',
body: {
_id: `org.couchdb.user:${NPM_USERNAME}`,
name: NPM_USERNAME,
roles: [],
type: 'user',
password: NPM_PASSWORD,
email: NPM_EMAIL,
},
});
}
const url = `http://${SERVER_HOST}:${SERVER_PORT}/registry/_design/app/_rewrite/`;
const authEnv = {
npm_config_registry: url, // eslint-disable-line camelcase
NPM_USERNAME,
NPM_PASSWORD,
NPM_EMAIL,
};
/**
* Stop and remote the `npm-docker-couchdb` Docker container.
*
* @return {Promise} Promise that resolves when the container is stopped.
*/
async function stop() {
await container.stop();
await container.remove();
}
export default {start, stop, authEnv, url};
+553
View File
@@ -0,0 +1,553 @@
import test from 'ava';
import proxyquire from 'proxyquire';
import {stub} from 'sinon';
import tempy from 'tempy';
import DEFINITIONS from '../lib/plugins/definitions';
import {gitHead as getGitHead} from '../lib/git';
import {gitRepo, gitCommits, gitTagVersion} from './helpers/git-utils';
// Save the current process.env
const envBackup = Object.assign({}, process.env);
// Save the current working diretory
const cwd = process.cwd();
stub(process.stdout, 'write');
stub(process.stderr, 'write');
test.beforeEach(t => {
// Stub the logger functions
t.context.log = stub();
t.context.error = stub();
t.context.logger = {log: t.context.log, error: t.context.error};
});
test.afterEach.always(() => {
// Restore process.env
process.env = envBackup;
// Restore the current working directory
process.chdir(cwd);
});
test.serial('Plugins are called with expected values', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second'])).concat(commits);
const lastRelease = {version: '1.0.0', gitHead: commits[commits.length - 1].hash, gitTag: 'v1.0.0'};
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
const notes = 'Release notes';
const verifyConditions1 = stub().resolves();
const verifyConditions2 = stub().resolves();
const getLastRelease = stub().resolves(lastRelease);
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves(notes);
const publish = stub().resolves();
const config = {branch: 'master', repositoryUrl: 'git@hostname.com:owner/module.git', globalOpt: 'global'};
const options = {
...config,
verifyConditions: [verifyConditions1, verifyConditions2],
getLastRelease,
analyzeCommits,
verifyRelease,
generateNotes,
publish,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options));
t.is(verifyConditions1.callCount, 1);
t.deepEqual(verifyConditions1.args[0][0], config);
t.deepEqual(verifyConditions1.args[0][1], {options, logger: t.context.logger});
t.is(verifyConditions2.callCount, 1);
t.deepEqual(verifyConditions2.args[0][1], {options, logger: t.context.logger});
t.is(getLastRelease.callCount, 1);
t.deepEqual(getLastRelease.args[0][0], config);
t.deepEqual(getLastRelease.args[0][1], {options, logger: t.context.logger});
t.is(analyzeCommits.callCount, 1);
t.deepEqual(analyzeCommits.args[0][0], config);
t.deepEqual(analyzeCommits.args[0][1].options, options);
t.deepEqual(analyzeCommits.args[0][1].logger, t.context.logger);
t.deepEqual(analyzeCommits.args[0][1].lastRelease, lastRelease);
t.deepEqual(analyzeCommits.args[0][1].commits[0].hash.substring(0, 7), commits[0].hash);
t.deepEqual(analyzeCommits.args[0][1].commits[0].message, commits[0].message);
t.is(verifyRelease.callCount, 1);
t.deepEqual(verifyRelease.args[0][0], config);
t.deepEqual(verifyRelease.args[0][1].options, options);
t.deepEqual(verifyRelease.args[0][1].logger, t.context.logger);
t.deepEqual(verifyRelease.args[0][1].lastRelease, lastRelease);
t.deepEqual(verifyRelease.args[0][1].commits[0].hash.substring(0, 7), commits[0].hash);
t.deepEqual(verifyRelease.args[0][1].commits[0].message, commits[0].message);
t.deepEqual(verifyRelease.args[0][1].nextRelease, nextRelease);
t.is(generateNotes.callCount, 1);
t.deepEqual(generateNotes.args[0][0], config);
t.deepEqual(generateNotes.args[0][1].options, options);
t.deepEqual(generateNotes.args[0][1].logger, t.context.logger);
t.deepEqual(generateNotes.args[0][1].lastRelease, lastRelease);
t.deepEqual(generateNotes.args[0][1].commits[0].hash.substring(0, 7), commits[0].hash);
t.deepEqual(generateNotes.args[0][1].commits[0].message, commits[0].message);
t.deepEqual(generateNotes.args[0][1].nextRelease, nextRelease);
t.is(publish.callCount, 1);
t.deepEqual(publish.args[0][0], config);
t.deepEqual(publish.args[0][1].options, options);
t.deepEqual(publish.args[0][1].logger, t.context.logger);
t.deepEqual(publish.args[0][1].lastRelease, lastRelease);
t.deepEqual(publish.args[0][1].commits[0].hash.substring(0, 7), commits[0].hash);
t.deepEqual(publish.args[0][1].commits[0].message, commits[0].message);
t.deepEqual(publish.args[0][1].nextRelease, Object.assign({}, nextRelease, {notes}));
});
test.serial('Use new gitHead, and recreate release notes if a publish plugin create a commit', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second'])).concat(commits);
const lastRelease = {version: '1.0.0', gitHead: commits[commits.length - 1].hash, gitTag: 'v1.0.0'};
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
const notes = 'Release notes';
const generateNotes = stub().resolves(notes);
const publish1 = stub().callsFake(async () => {
await gitCommits(['Third']);
});
const publish2 = stub().resolves();
const options = {
branch: 'master',
repositoryUrl: 'git@hostname.com:owner/module.git',
verifyConditions: stub().resolves(),
getLastRelease: stub().resolves(lastRelease),
analyzeCommits: stub().resolves(nextRelease.type),
verifyRelease: stub().resolves(),
generateNotes,
publish: [publish1, publish2],
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options));
t.is(generateNotes.callCount, 2);
t.deepEqual(generateNotes.args[0][1].nextRelease, nextRelease);
t.is(publish1.callCount, 1);
t.deepEqual(publish1.args[0][1].nextRelease, Object.assign({}, nextRelease, {notes}));
nextRelease.gitHead = await getGitHead();
t.deepEqual(generateNotes.secondCall.args[1].nextRelease, Object.assign({}, nextRelease, {notes}));
t.is(publish2.callCount, 1);
t.deepEqual(publish2.args[0][1].nextRelease, Object.assign({}, nextRelease, {notes}));
});
test.serial('Dry-run skips publish', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second'])).concat(commits);
const lastRelease = {version: '1.0.0', gitHead: commits[commits.length - 1].hash, gitTag: 'v1.0.0'};
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
const notes = 'Release notes';
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves(lastRelease);
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves(notes);
const publish = stub().resolves();
const options = {
dryRun: true,
branch: 'master',
repositoryUrl: 'git@hostname.com:owner/module.git',
verifyConditions,
getLastRelease,
analyzeCommits,
verifyRelease,
generateNotes,
publish,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options));
t.not(t.context.log.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
t.is(verifyConditions.callCount, 1);
t.is(getLastRelease.callCount, 1);
t.is(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 1);
t.is(generateNotes.callCount, 1);
t.is(publish.callCount, 0);
});
test.serial('Force a dry-run if not on a CI and "noCi" is not explicitly set', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second'])).concat(commits);
const lastRelease = {version: '1.0.0', gitHead: commits[commits.length - 1].hash, gitTag: 'v1.0.0'};
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
const notes = 'Release notes';
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves(lastRelease);
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves(notes);
const publish = stub().resolves();
const options = {
dryRun: false,
branch: 'master',
repositoryUrl: 'git@hostname.com:owner/module.git',
verifyConditions,
getLastRelease,
analyzeCommits,
verifyRelease,
generateNotes,
publish,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: false, branch: 'master'}),
});
t.truthy(await semanticRelease(options));
t.is(t.context.log.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
t.is(verifyConditions.callCount, 1);
t.is(getLastRelease.callCount, 1);
t.is(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 1);
t.is(generateNotes.callCount, 1);
t.is(publish.callCount, 0);
});
test.serial('Allow local releases with "noCi" option', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second'])).concat(commits);
const lastRelease = {version: '1.0.0', gitHead: commits[commits.length - 1].hash, gitTag: 'v1.0.0'};
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
const notes = 'Release notes';
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves(lastRelease);
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves(notes);
const publish = stub().resolves();
const options = {
noCi: true,
branch: 'master',
repositoryUrl: 'git@hostname.com:owner/module.git',
verifyConditions,
getLastRelease,
analyzeCommits,
verifyRelease,
generateNotes,
publish,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: false, branch: 'master', isPr: true}),
});
t.truthy(await semanticRelease(options));
t.not(t.context.log.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
t.not(
t.context.log.args[0][0],
"This run was triggered by a pull request and therefore a new version won't be published."
);
t.is(verifyConditions.callCount, 1);
t.is(getLastRelease.callCount, 1);
t.is(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 1);
t.is(generateNotes.callCount, 1);
t.is(publish.callCount, 1);
});
test.serial('Accept "undefined" values for the "getLastRelease" and "generateNotes" plugins', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
await gitCommits(['Second']);
const lastRelease = {gitHead: undefined, gitTag: undefined, version: undefined};
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves();
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves();
const publish = stub().resolves();
const options = {
branch: 'master',
repositoryUrl: 'git@hostname.com:owner/module.git',
verifyConditions: [verifyConditions],
getLastRelease,
analyzeCommits,
verifyRelease,
generateNotes,
publish,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options));
t.is(getLastRelease.callCount, 1);
t.is(analyzeCommits.callCount, 1);
t.deepEqual(analyzeCommits.args[0][1].lastRelease, lastRelease);
t.is(verifyRelease.callCount, 1);
t.deepEqual(verifyRelease.args[0][1].lastRelease, lastRelease);
t.is(generateNotes.callCount, 1);
t.deepEqual(generateNotes.args[0][1].lastRelease, lastRelease);
t.is(publish.callCount, 1);
t.deepEqual(publish.args[0][1].lastRelease, lastRelease);
t.falsy(publish.args[0][1].nextRelease.notes);
});
test.serial('Returns falsy value if not running from a git repository', async t => {
// Set the current working directory to a temp directory
process.chdir(tempy.directory());
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.falsy(await semanticRelease({repositoryUrl: 'git@hostname.com:owner/module.git'}));
t.is(t.context.error.args[0][0], 'Semantic-release must run from a git repository.');
});
test.serial('Returns falsy value if triggered by a PR', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: true}),
});
t.falsy(await semanticRelease({repositoryUrl: 'git@hostname.com:owner/module.git'}));
t.is(
t.context.log.args[7][0],
"This run was triggered by a pull request and therefore a new version won't be published."
);
});
test.serial('Returns falsy value if not running from the configured branch', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves();
const analyzeCommits = stub().resolves();
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves();
const publish = stub().resolves();
const options = {
branch: 'master',
repositoryUrl: 'git@hostname.com:owner/module.git',
verifyConditions: [verifyConditions],
getLastRelease,
analyzeCommits,
verifyRelease,
generateNotes,
publish,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'other-branch', isPr: false}),
});
t.falsy(await semanticRelease(options));
t.is(
t.context.log.args[0][0],
'This test run was triggered on the branch other-branch, while semantic-release is configured to only publish from master, therefore a new version wont be published.'
);
});
test.serial('Returns falsy value if there is no relevant changes', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First']);
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves();
const analyzeCommits = stub().resolves();
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves();
const publish = stub().resolves();
const options = {
branch: 'master',
repositoryUrl: 'git@hostname.com:owner/module.git',
verifyConditions: [verifyConditions],
getLastRelease,
analyzeCommits,
verifyRelease,
generateNotes,
publish,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.falsy(await semanticRelease(options));
t.is(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 0);
t.is(generateNotes.callCount, 0);
t.is(publish.callCount, 0);
t.is(t.context.log.args[6][0], 'There are no relevant changes, so no new version is released.');
});
test.serial('Exclude commits with [skip release] or [release skip] from analysis', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits([
'Test commit',
'Test commit [skip release]',
'Test commit [release skip]',
'Test commit [Release Skip]',
'Test commit [Skip Release]',
'Test commit [skip release]',
'Test commit\n\n commit body\n[skip release]',
'Test commit\n\n commit body\n[release skip]',
]);
const verifyConditions1 = stub().resolves();
const verifyConditions2 = stub().resolves();
const getLastRelease = stub().resolves({});
const analyzeCommits = stub().resolves();
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves();
const publish = stub().resolves();
const config = {branch: 'master', repositoryUrl: 'git@hostname.com:owner/module.git', globalOpt: 'global'};
const options = {
...config,
verifyConditions: [verifyConditions1, verifyConditions2],
getLastRelease,
analyzeCommits,
verifyRelease,
generateNotes,
publish,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await semanticRelease(options);
t.is(analyzeCommits.callCount, 1);
t.is(analyzeCommits.args[0][1].commits.length, 1);
t.deepEqual(analyzeCommits.args[0][1].commits[0].hash.substring(0, 7), commits[commits.length - 1].hash);
t.deepEqual(analyzeCommits.args[0][1].commits[0].message, commits[commits.length - 1].message);
});
test.serial('Throw SemanticReleaseError if repositoryUrl is not set and cannot be found from repo config', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const error = await t.throws(semanticRelease());
// Verify error code and type
t.is(error.code, 'ENOREPOURL');
t.is(error.name, 'SemanticReleaseError');
});
test.serial('Throw an Error if plugin returns an unexpected value', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
await gitCommits(['Second']);
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves('string');
const options = {
branch: 'master',
repositoryUrl: 'git@hostname.com:owner/module.git',
verifyConditions: [verifyConditions],
getLastRelease,
};
const semanticRelease = proxyquire('..', {
'./lib/logger': t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const error = await t.throws(semanticRelease(options), Error);
// Verify error message
t.regex(error.message, new RegExp(DEFINITIONS.getLastRelease.output.message));
t.regex(error.message, /Received: 'string'/);
});
+907
View File
@@ -0,0 +1,907 @@
import test from 'ava';
import {writeJson, readJson} from 'fs-extra';
import {stub} from 'sinon';
import execa from 'execa';
import {gitRepo, gitCommits, gitHead, gitTagVersion, gitPackRefs, gitAmmendCommit} from './helpers/git-utils';
import mockServer from './helpers/mockserver';
import npmRegistry from './helpers/npm-registry';
import semanticRelease from '..';
/* eslint camelcase: ["error", {properties: "never"}] */
// Environment variables used with semantic-release cli (similar to what a user would setup)
const env = {
GH_TOKEN: 'github_token',
GITHUB_URL: mockServer.url,
NPM_EMAIL: 'integration@test.com',
NPM_USERNAME: 'integration',
NPM_PASSWORD: 'suchsecure',
};
// Environment variables used only for the local npm command used to do verification
const testEnv = Object.assign({}, process.env, {
npm_config_registry: npmRegistry.url,
NPM_EMAIL: 'integration@test.com',
LEGACY_TOKEN: Buffer.from(`${process.env.NPM_USERNAME}:${process.env.NPM_PASSWORD}`, 'utf8').toString('base64'),
});
// Save the current process.env
const envBackup = Object.assign({}, process.env);
const cli = require.resolve('../bin/semantic-release');
const pluginError = require.resolve('./fixtures/plugin-error');
const pluginInheritedError = require.resolve('./fixtures/plugin-error-inherited');
// Save the current working diretory
const cwd = process.cwd();
// Disable logs during tests
stub(process.stdout, 'write');
stub(process.stderr, 'write');
test.before(async () => {
// Start the local NPM registry
await npmRegistry.start();
// Start Mock Server
await mockServer.start();
});
test.beforeEach(() => {
// Delete env paramaters that could have been set on the machine running the tests
delete process.env.NPM_TOKEN;
delete process.env.NPM_USERNAME;
delete process.env.NPM_PASSWORD;
delete process.env.NPM_EMAIL;
delete process.env.GH_TOKEN;
delete process.env.GITHUB_TOKEN;
delete process.env.GH_URL;
delete process.env.GITHUB_URL;
delete process.env.GH_PREFIX;
delete process.env.GITHUB_PREFIX;
process.env.TRAVIS = 'true';
process.env.CI = 'true';
process.env.TRAVIS_BRANCH = 'master';
process.env.TRAVIS_PULL_REQUEST = 'false';
// Delete all `npm_config` environment variable set by CI as they take precedence over the `.npmrc` because the process that runs the tests is started before the `.npmrc` is created
for (let i = 0, keys = Object.keys(process.env); i < keys.length; i++) {
if (keys[i].startsWith('npm_config')) {
delete process.env[keys[i]];
}
}
});
test.afterEach.always(() => {
// Restore process.env
process.env = envBackup;
// Restore the current working directory
process.chdir(cwd);
});
test.after.always(async () => {
// Stop the local NPM registry
await npmRegistry.stop();
// Stop Mock Server
await mockServer.stop();
});
test.serial('Release patch, minor and major versions', async t => {
const packageName = 'test-release';
const owner = 'test-owner';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
publishConfig: {registry: npmRegistry.url},
});
// Create a npm-shrinkwrap.json file
await execa('npm', ['shrinkwrap'], {env: testEnv});
/* No release */
let verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
t.log('Commit a chore');
await gitCommits(['chore: Init repository']);
t.log('$ semantic-release');
let {stdout, code} = await execa(cli, [], {env});
t.regex(stdout, /There are no relevant changes, so no new version is released/);
t.is(code, 0);
/* Initial release */
let version = '1.0.0';
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
let getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
let createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json and npm-shrinkwrap.json have been updated
t.is((await readJson('./package.json')).version, version);
t.is((await readJson('./npm-shrinkwrap.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/* Patch release */
version = '1.0.1';
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a fix');
await gitCommits(['fix: bar']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json and npm-shrinkwrap.json have been updated
t.is((await readJson('./package.json')).version, version);
t.is((await readJson('./npm-shrinkwrap.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/* Minor release */
version = '1.1.0';
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: baz']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json and npm-shrinkwrap.json have been updated
t.is((await readJson('./package.json')).version, version);
t.is((await readJson('./npm-shrinkwrap.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/* Major release */
version = '2.0.0';
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a breaking change');
await gitCommits(['feat: foo\n\n BREAKING CHANGE: bar']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json and npm-shrinkwrap.json have been updated
t.is((await readJson('./package.json')).version, version);
t.is((await readJson('./npm-shrinkwrap.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Release versions from a packed git repository, using tags to determine last release gitHead', async t => {
const packageName = 'test-git-packed';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git@github.com:${owner}/${packageName}.git`},
publishConfig: {registry: npmRegistry.url},
});
/* Initial release */
let version = '1.0.0';
let verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
let createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
let createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ git pack-refs --all');
await gitPackRefs();
t.log('$ semantic-release');
let {stdout, code} = await execa(cli, [], {env});
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version
let releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env: testEnv})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
// Create a tag version so the tag can be used later to determine the commit associated with the version
await gitTagVersion(`v${version}`);
t.log(`Create git tag v${version}`);
/* Patch release */
version = '1.0.1';
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a fix');
await gitCommits(['fix: bar']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version
releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env: testEnv})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Exit with 1 if a plugin is not found', async t => {
const packageName = 'test-plugin-not-found';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {analyzeCommits: 'non-existing-path'},
});
const {code, stderr} = await t.throws(execa(cli, [], {env}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
test.serial('Exit with 1 if a shareable config is not found', async t => {
const packageName = 'test-config-not-found';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {extends: 'non-existing-path'},
});
const {code, stderr} = await t.throws(execa(cli, [], {env}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
test.serial('Exit with 1 if a shareable config reference a not found plugin', async t => {
const packageName = 'test-config-ref-not-found';
const owner = 'test-repo';
const shareable = {getLastRelease: 'non-existing-path'};
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {extends: './shareable.json'},
});
await writeJson('./shareable.json', shareable);
const {code, stderr} = await t.throws(execa(cli, [], {env}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
test.serial('Create a tag as a recovery solution for "ENOTINHISTORY" error', async t => {
const packageName = 'test-recovery';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
publishConfig: {registry: npmRegistry.url},
});
/* Initial release */
let version = '1.0.0';
let verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
let getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
let createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
let {stderr, stdout, code} = await execa(cli, [], {env});
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
const head = await gitHead();
t.is(releasedGitHead, head);
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
// Create a tag version so the tag can be used later to determine the commit associated with the version
await gitTagVersion(`v${version}`);
t.log(`Create git tag v${version}`);
/* Rewrite sha of commit used for release */
t.log('Amend release commit');
const {hash} = await gitAmmendCommit('feat: Initial commit');
/* Patch release */
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
t.log('Commit a fix');
await gitCommits(['fix: bar']);
t.log('$ semantic-release');
({stderr, stdout, code} = await execa(cli, [], {env, reject: false}));
t.log('Log "ENOTINHISTORY" message');
t.is(code, 1);
t.regex(
stderr,
new RegExp(
`You can recover from this error by restoring the commit "${head}" or by creating a tag for the version "${version}" on the commit corresponding to this release`
)
);
/* Create a tag to recover and redo release */
t.log(`Create git tag v${version} to recover`);
await gitTagVersion(`v${version}`, hash);
version = '1.0.1';
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('$ semantic-release');
({stderr, stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env: testEnv})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Dry-run', async t => {
const packageName = 'test-dry-run';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
publishConfig: {registry: npmRegistry.url},
});
/* Initial release */
const verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
const version = '1.0.0';
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release -d');
const {stdout, code} = await execa(cli, ['-d'], {env});
t.regex(stdout, new RegExp(`There is no previous release, the next release version is ${version}`));
t.regex(stdout, new RegExp(`Release note for version ${version}`));
t.regex(stdout, /Initial commit/);
t.is(code, 0);
// Verify package.json and has not been modified
t.is((await readJson('./package.json')).version, '0.0.0-dev');
await mockServer.verify(verifyMock);
});
test.serial('Allow local releases with "noCi" option', async t => {
delete process.env.TRAVIS;
delete process.env.CI;
const packageName = 'test-no-ci';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
publishConfig: {registry: npmRegistry.url},
});
/* Initial release */
const version = '1.0.0';
const verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
const getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
const createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{
body: {ref: `refs/tags/v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {ref: `refs/tags/${version}`}}
);
const createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release --no-ci');
const {stdout, code} = await execa(cli, ['--no-ci'], {env});
console.log(stdout);
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json and has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Pass options via CLI arguments', async t => {
const packageName = 'test-cli';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
publishConfig: {registry: npmRegistry.url},
});
/* Initial release */
const version = '1.0.0';
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
const {stdout, code} = await execa(
cli,
['--verify-conditions', '@semantic-release/npm', '--publish', '@semantic-release/npm', '--debug'],
{env}
);
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json and has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
});
test.serial('Run via JS API', async t => {
const packageName = 'test-js-api';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
publishConfig: {registry: npmRegistry.url},
});
/* Initial release */
const version = '1.0.0';
const verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
const getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
const createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{
body: {ref: `refs/tags/v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {ref: `refs/tags/${version}`}}
);
const createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
process.env = Object.assign(process.env, env);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ Call semantic-release via API');
await semanticRelease();
// Verify package.json and has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Log unexpected errors from plugins and exit with 1', async t => {
const packageName = 'test-unexpected-error';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {verifyConditions: pluginError},
});
/* Initial release */
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
const {stderr, code} = await execa(cli, [], {env, reject: false});
// Verify the type and message are logged
t.regex(stderr, /Error: a/);
// Verify the the stacktrace is logged
t.regex(stderr, new RegExp(pluginError));
// Verify the Error properties are logged
t.regex(stderr, /errorProperty: 'errorProperty'/);
t.is(code, 1);
});
test.serial('Log errors inheriting SemanticReleaseError and exit with 1', async t => {
const packageName = 'test-inherited-error';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {verifyConditions: pluginInheritedError},
});
/* Initial release */
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
const {stdout, code} = await execa(cli, [], {env, reject: false});
// Verify the type and message are logged
t.regex(stdout, /EINHERITED Inherited error/);
t.is(code, 1);
});
test.serial('CLI returns error code and prints help if called with a command', async t => {
t.log('$ semantic-release pre');
const {stdout, code} = await execa(cli, ['pre'], {env, reject: false});
t.regex(stdout, /Usage: semantic-release/);
t.is(code, 1);
});
test.serial('CLI prints help if called with --help', async t => {
t.log('$ semantic-release --help');
const {stdout, code} = await execa(cli, ['--help'], {env});
t.regex(stdout, /Usage: semantic-release/);
t.is(code, 0);
});
test.serial('CLI returns error code with invalid option', async t => {
t.log('$ semantic-release --unknown-option');
const {stderr, code} = await execa(cli, ['--unknown-option'], {env, reject: false});
t.regex(stderr, /unknown option/);
t.is(code, 1);
});
-12
View File
@@ -1,12 +0,0 @@
var nixt = require('nixt')
module.exports = function (cwd, uri) {
return nixt()
.cwd(cwd)
.env('NPM_OLD_TOKEN', 'aW50ZWdyYXRpb246c3VjaHNlY3VyZQ==')
.env('NPM_EMAIL', 'integration@test.com')
.env('GH_TOKEN', 'ghtoken')
.env('CI', 'true')
.env('npm_config_registry', uri)
.clone()
}
-36
View File
@@ -1,36 +0,0 @@
var exec = require('child_process').exec
var join = require('path').join
var writeFileSync = require('fs').writeFileSync
var mkdirp = require('mkdirp')
module.exports = function (name, registry, cb) {
var cwd = join(__dirname, '../tmp', name)
mkdirp.sync(cwd)
writeFileSync(join(cwd, 'package.json'), JSON.stringify({
name: name,
repository: {
url: 'git+https://github.com/semantic-release/test'
},
release: {
verifyConditions: '../../../src/lib/plugin-noop'
}
}, null, 2))
exec(
'git init && ' +
'git config user.email "integration@test" && ' +
'git config user.name "Integration Test" && ' +
'git add . && ' +
'git commit -m "chore: root"'
, {cwd: cwd}, function (err, stdout, stderr) {
if (err) {
console.log(stdout, stderr)
return cb(err)
}
cb(null, cwd)
})
}
+51
View File
@@ -0,0 +1,51 @@
import test from 'ava';
import {stub} from 'sinon';
import logger from '../lib/logger';
test.beforeEach(t => {
t.context.log = stub(console, 'log');
t.context.error = stub(console, 'error');
});
test.afterEach.always(t => {
t.context.log.restore();
t.context.error.restore();
});
test.serial('Basic log', t => {
logger.log('test log');
logger.error('test error');
t.regex(t.context.log.args[0][0], /.*test log/);
t.regex(t.context.error.args[0][0], /.*test error/);
});
test.serial('Log object', t => {
const obj = {a: 1, b: '2'};
logger.log(obj);
logger.error(obj);
t.is(t.context.log.args[0][1], obj);
t.is(t.context.error.args[0][1], obj);
});
test.serial('Log with string formatting', t => {
logger.log('test log %s', 'log value');
logger.error('test error %s', 'error value');
t.regex(t.context.log.args[0][0], /.*test log/);
t.regex(t.context.error.args[0][0], /.*test error/);
t.is(t.context.log.args[0][1], 'log value');
t.is(t.context.error.args[0][1], 'error value');
});
test.serial('Log with error stacktrace and properties', t => {
const error = new Error('error message');
logger.error(error);
const otherError = new Error('other error message');
logger.error('test error %O', otherError);
t.is(t.context.error.args[0][1], error);
t.regex(t.context.error.args[1][0], /.*test error/);
t.is(t.context.error.args[1][1], otherError);
});
-30
View File
@@ -1,30 +0,0 @@
var mockSpawn = require('mock-spawn')()
mockSpawn.setStrategy(function (command, args, opts) {
return function (cb) {
this.stdout.write(
/\.\.HEAD/.test(args.join(' '))
? rawCommits[0]
: rawCommits.join()
)
cb(0)
}
})
const rawCommits = [
'hash-one==SPLIT==commit-one==END==\n',
'hash-two==SPLIT==commit-two==END==\n'
]
module.exports = {
exec: function (command, options, cb) {
if (typeof cb === 'undefined' && typeof options === 'function') {
cb = options
}
if (/contains/.test(command)) {
if (/notinhistory/.test(command)) return cb(new Error())
return cb(null, 'whatever\nmaster\n')
}
},
spawn: mockSpawn,
'@noCallThru': true
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (cb) {
cb(null, 'bar')
}
-17
View File
@@ -1,17 +0,0 @@
module.exports = function () {
return {
authenticate: function () {
return true
},
gitdata: {
createReference: function (release, cb) {
cb(null)
}
},
repos: {
createRelease: function (release, cb) {
cb(null)
}
}
}
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (config, options, cb) {
cb(new Error('a'))
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (config, options, cb) {
cb(new Error('b'))
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (config, options, cb) {
cb(null, 'a')
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (config, options, cb) {
cb(null, 'b')
}
-28
View File
@@ -1,28 +0,0 @@
const nock = require('nock')
const availableModule = {
'dist-tags': {
latest: '1.33.7',
foo: '0.8.15'
},
versions: {
'0.8.15': {
gitHead: 'bar'
},
'1.33.7': {
gitHead: 'HEAD'
}
}
}
module.exports = nock('http://registry.npmjs.org')
.get('/available')
.reply(200, availableModule)
.get('/tagged')
.reply(200, availableModule)
.get('/untagged')
.reply(200, availableModule)
.get('/@scoped%2Favailable')
.reply(200, availableModule)
.get('/unavailable')
.reply(404, {})
+101
View File
@@ -0,0 +1,101 @@
import test from 'ava';
import definitions from '../../lib/plugins/definitions';
test('The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(definitions.verifyConditions.config.validator({}));
t.false(definitions.verifyConditions.config.validator({path: null}));
t.true(definitions.verifyConditions.config.validator({path: 'plugin-path.js'}));
t.true(definitions.verifyConditions.config.validator());
t.true(definitions.verifyConditions.config.validator('plugin-path.js'));
t.true(definitions.verifyConditions.config.validator(() => {}));
t.true(definitions.verifyConditions.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "getLastRelease" plugin is mandatory, and must be a single plugin definition', t => {
t.false(definitions.getLastRelease.config.validator({}));
t.false(definitions.getLastRelease.config.validator({path: null}));
t.false(definitions.getLastRelease.config.validator([]));
t.false(definitions.getLastRelease.config.validator());
t.true(definitions.getLastRelease.config.validator({path: 'plugin-path.js'}));
t.true(definitions.getLastRelease.config.validator('plugin-path.js'));
t.true(definitions.getLastRelease.config.validator(() => {}));
});
test('The "analyzeCommits" plugin is mandatory, and must be a single plugin definition', t => {
t.false(definitions.analyzeCommits.config.validator({}));
t.false(definitions.analyzeCommits.config.validator({path: null}));
t.false(definitions.analyzeCommits.config.validator([]));
t.false(definitions.analyzeCommits.config.validator());
t.true(definitions.analyzeCommits.config.validator({path: 'plugin-path.js'}));
t.true(definitions.analyzeCommits.config.validator('plugin-path.js'));
t.true(definitions.analyzeCommits.config.validator(() => {}));
});
test('The "verifyRelease" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(definitions.verifyRelease.config.validator({}));
t.false(definitions.verifyRelease.config.validator({path: null}));
t.true(definitions.verifyRelease.config.validator({path: 'plugin-path.js'}));
t.true(definitions.verifyRelease.config.validator());
t.true(definitions.verifyRelease.config.validator('plugin-path.js'));
t.true(definitions.verifyRelease.config.validator(() => {}));
t.true(definitions.verifyRelease.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "generateNotes" plugin, if defined, must be a single plugin definition', t => {
t.false(definitions.generateNotes.config.validator({}));
t.false(definitions.generateNotes.config.validator({path: null}));
t.false(definitions.generateNotes.config.validator([]));
t.true(definitions.generateNotes.config.validator());
t.true(definitions.generateNotes.config.validator({path: 'plugin-path.js'}));
t.true(definitions.generateNotes.config.validator('plugin-path.js'));
t.true(definitions.generateNotes.config.validator(() => {}));
});
test('The "publish" plugin is mandatory, and must be a single or an array of plugins definition', t => {
t.false(definitions.publish.config.validator({}));
t.false(definitions.publish.config.validator({path: null}));
t.false(definitions.publish.config.validator());
t.true(definitions.publish.config.validator({path: 'plugin-path.js'}));
t.true(definitions.publish.config.validator('plugin-path.js'));
t.true(definitions.publish.config.validator(() => {}));
t.true(definitions.publish.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "getLastRelease" plugin output if defined, must be an object with a valid semver version in the "version" property and the corresponding git reference in "gitHead" property', t => {
t.false(definitions.getLastRelease.output.validator('string'));
t.false(definitions.getLastRelease.output.validator(1));
t.false(definitions.getLastRelease.output.validator({version: 'v1.0.0'}));
t.false(definitions.getLastRelease.output.validator({version: 'invalid'}));
t.true(definitions.getLastRelease.output.validator());
t.true(definitions.getLastRelease.output.validator({}));
t.true(definitions.getLastRelease.output.validator({version: 'v1.0.0', gitHead: '123'}));
t.true(definitions.getLastRelease.output.validator({version: '1.0.0', gitHead: '123'}));
t.true(definitions.getLastRelease.output.validator({version: null}));
});
test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', t => {
t.false(definitions.analyzeCommits.output.validator('invalid'));
t.false(definitions.analyzeCommits.output.validator(1));
t.false(definitions.analyzeCommits.output.validator({}));
t.true(definitions.analyzeCommits.output.validator());
t.true(definitions.analyzeCommits.output.validator(null));
t.true(definitions.analyzeCommits.output.validator('major'));
});
test('The "generateNotes" plugin output, if defined, must be a string', t => {
t.false(definitions.generateNotes.output.validator(1));
t.false(definitions.generateNotes.output.validator({}));
t.true(definitions.generateNotes.output.validator());
t.true(definitions.generateNotes.output.validator(null));
t.true(definitions.generateNotes.output.validator(''));
t.true(definitions.generateNotes.output.validator('string'));
});
+143
View File
@@ -0,0 +1,143 @@
import test from 'ava';
import {noop} from 'lodash';
import {stub} from 'sinon';
import normalize from '../../lib/plugins/normalize';
test.beforeEach(t => {
// Stub the logger functions
t.context.log = stub();
t.context.logger = {log: t.context.log};
});
test('Normalize and load plugin from string', t => {
const plugin = normalize('verifyConditions', {}, {}, './test/fixtures/plugin-noop', t.context.logger);
t.is(typeof plugin, 'function');
t.deepEqual(t.context.log.args[0], ['Load plugin %s from %s', 'verifyConditions', './test/fixtures/plugin-noop']);
});
test('Normalize and load plugin from object', t => {
const plugin = normalize('publish', {}, {}, {path: './test/fixtures/plugin-noop'}, t.context.logger);
t.is(typeof plugin, 'function');
t.deepEqual(t.context.log.args[0], ['Load plugin %s from %s', 'publish', './test/fixtures/plugin-noop']);
});
test('Normalize and load plugin from a base file path', t => {
const plugin = normalize(
'verifyConditions',
{'./plugin-noop': './test/fixtures'},
{},
'./plugin-noop',
t.context.logger
);
t.is(typeof plugin, 'function');
t.deepEqual(t.context.log.args[0], [
'Load plugin %s from %s in shareable config %s',
'verifyConditions',
'./plugin-noop',
'./test/fixtures',
]);
});
test('Normalize and load plugin from function', t => {
const plugin = normalize('', {}, {}, () => {}, t.context.logger);
t.is(typeof plugin, 'function');
});
test('Normalize and load plugin that retuns multiple functions', t => {
const plugin = normalize('verifyConditions', {}, {}, './test/fixtures/multi-plugin', t.context.logger);
t.is(typeof plugin, 'function');
t.deepEqual(t.context.log.args[0], ['Load plugin %s from %s', 'verifyConditions', './test/fixtures/multi-plugin']);
});
test('Wrap plugin in a function that validate the output of the plugin', async t => {
const pluginFunction = stub().resolves(1);
const plugin = normalize('', {}, {}, pluginFunction, t.context.logger, {
validator: output => output === 1,
message: 'The output must be 1.',
});
await t.notThrows(plugin());
pluginFunction.resolves(2);
const error = await t.throws(plugin(), Error);
t.is(error.message, 'The output must be 1. Received: 2');
});
test('Plugin is called with "pluginConfig" (omitting "path", adding global config) and input', async t => {
const pluginFunction = stub().resolves();
const conf = {path: pluginFunction, conf: 'confValue'};
const globalConf = {global: 'globalValue'};
const plugin = normalize('', {}, globalConf, conf, t.context.logger);
await plugin('param');
t.true(pluginFunction.calledWith({conf: 'confValue', global: 'globalValue'}, 'param'));
});
test('Prevent plugins to modify "pluginConfig"', async t => {
const pluginFunction = stub().callsFake(pluginConfig => {
pluginConfig.conf.subConf = 'otherConf';
});
const conf = {path: pluginFunction, conf: {subConf: 'originalConf'}};
const globalConf = {globalConf: {globalSubConf: 'originalGlobalConf'}};
const plugin = normalize('', {}, globalConf, conf, t.context.logger);
await plugin();
t.is(conf.conf.subConf, 'originalConf');
t.is(globalConf.globalConf.globalSubConf, 'originalGlobalConf');
});
test('Prevent plugins to modify its input', async t => {
const pluginFunction = stub().callsFake((pluginConfig, options) => {
options.param.subParam = 'otherParam';
});
const input = {param: {subParam: 'originalSubParam'}};
const plugin = normalize('', {}, {}, pluginFunction, t.context.logger);
await plugin(input);
t.is(input.param.subParam, 'originalSubParam');
});
test('Return noop if the plugin is not defined', t => {
const plugin = normalize();
t.is(plugin, noop);
});
test('Always pass a defined "pluginConfig" for plugin defined with string', async t => {
// Call the normalize function with the path of a plugin that returns its config
const plugin = normalize('', {}, {}, './test/fixtures/plugin-result-config', t.context.logger);
const pluginResult = await plugin();
t.deepEqual(pluginResult.pluginConfig, {});
});
test('Always pass a defined "pluginConfig" for plugin defined with path', async t => {
// Call the normalize function with the path of a plugin that returns its config
const plugin = normalize('', {}, {}, {path: './test/fixtures/plugin-result-config'}, t.context.logger);
const pluginResult = await plugin();
t.deepEqual(pluginResult.pluginConfig, {});
});
test('Throws an error if the plugin return an object without the expected plugin function', t => {
const error = t.throws(() => normalize('inexistantPlugin', {}, {}, './test/fixtures/multi-plugin', t.context.logger));
t.is(error.code, 'EPLUGINCONF');
t.is(error.name, 'SemanticReleaseError');
t.is(
error.message,
'The inexistantPlugin plugin must be a function, or an object with a function in the property inexistantPlugin.'
);
});
test('Throws an error if the plugin is not found', t => {
const error = t.throws(() => normalize('inexistantPlugin', {}, {}, 'non-existing-path', t.context.logger), Error);
t.is(error.message, "Cannot find module 'non-existing-path'");
t.is(error.code, 'MODULE_NOT_FOUND');
});
+40
View File
@@ -0,0 +1,40 @@
import test from 'ava';
import {stub} from 'sinon';
import pipeline from '../../lib/plugins/pipeline';
test('Execute each function in series passing the same input', async t => {
const step1 = stub().resolves(1);
const step2 = stub().resolves(2);
const step3 = stub().resolves(3);
const result = await pipeline([step1, step2, step3])(0);
t.deepEqual(result, [1, 2, 3]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
t.true(step3.calledWith(0));
});
test('Execute each function in series passing a transformed input', async t => {
const step1 = stub().resolves(1);
const step2 = stub().resolves(2);
const step3 = stub().resolves(3);
const result = await pipeline([step1, step2, step3])(0, (prevResult, result) => prevResult + result);
t.deepEqual(result, [1, 2, 3]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(1));
t.true(step3.calledWith(3));
});
test('Stop execution and throw error is a step rejects', async t => {
const step1 = stub().resolves(1);
const step2 = stub().throws(new Error('test error'));
const step3 = stub().resolves(3);
const error = await t.throws(pipeline([step1, step2, step3])(0), Error);
t.is(error.message, 'test error');
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
t.true(step3.notCalled);
});
+156
View File
@@ -0,0 +1,156 @@
import path from 'path';
import test from 'ava';
import {copy, outputFile} from 'fs-extra';
import {stub} from 'sinon';
import tempy from 'tempy';
import getPlugins from '../../lib/plugins';
// Save the current working diretory
const cwd = process.cwd();
test.beforeEach(t => {
// Stub the logger functions
t.context.log = stub();
t.context.logger = {log: t.context.log};
});
test.afterEach.always(() => {
// Restore the current working directory
process.chdir(cwd);
});
test('Export default plugins', t => {
const plugins = getPlugins({}, {}, t.context.logger);
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.publish, 'function');
});
test('Export plugins based on config', t => {
const plugins = getPlugins(
{
verifyConditions: ['./test/fixtures/plugin-noop', {path: './test/fixtures/plugin-noop'}],
getLastRelease: './test/fixtures/plugin-noop',
analyzeCommits: {path: './test/fixtures/plugin-noop'},
verifyRelease: () => {},
},
{},
t.context.logger
);
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.publish, 'function');
});
test.serial('Export plugins loaded from the dependency of a shareable config module', async t => {
const temp = tempy.directory();
await copy(
'./test/fixtures/plugin-noop.js',
path.join(temp, 'node_modules/shareable-config/node_modules/custom-plugin/index.js')
);
await outputFile(path.join(temp, 'node_modules/shareable-config/index.js'), '');
process.chdir(temp);
const plugins = getPlugins(
{
verifyConditions: ['custom-plugin', {path: 'custom-plugin'}],
getLastRelease: 'custom-plugin',
analyzeCommits: {path: 'custom-plugin'},
verifyRelease: () => {},
},
{'custom-plugin': 'shareable-config'},
t.context.logger
);
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.publish, 'function');
});
test.serial('Export plugins loaded from the dependency of a shareable config file', async t => {
const temp = tempy.directory();
await copy('./test/fixtures/plugin-noop.js', path.join(temp, 'plugin/plugin-noop.js'));
await outputFile(path.join(temp, 'shareable-config.js'), '');
process.chdir(temp);
const plugins = getPlugins(
{
verifyConditions: ['./plugin/plugin-noop', {path: './plugin/plugin-noop'}],
getLastRelease: './plugin/plugin-noop',
analyzeCommits: {path: './plugin/plugin-noop'},
verifyRelease: () => {},
},
{'./plugin/plugin-noop': './shareable-config.js'},
t.context.logger
);
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.publish, 'function');
});
test('Use default when only options are passed for a single plugin', t => {
const plugins = getPlugins({getLastRelease: {}, analyzeCommits: {}}, {}, t.context.logger);
// Verify the module returns a function for each plugin
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
});
test('Merge global options with plugin options', async t => {
const plugins = getPlugins(
{
globalOpt: 'global',
otherOpt: 'globally-defined',
getLastRelease: {path: './test/fixtures/plugin-result-config', localOpt: 'local', otherOpt: 'locally-defined'},
},
{},
t.context.logger
);
const result = await plugins.getLastRelease();
t.deepEqual(result.pluginConfig, {localOpt: 'local', globalOpt: 'global', otherOpt: 'locally-defined'});
});
test('Throw an error if plugin configuration is missing a path for plugin pipeline', t => {
const error = t.throws(() => getPlugins({verifyConditions: {}}, {}, t.context.logger));
t.is(error.name, 'SemanticReleaseError');
t.is(error.code, 'EPLUGINCONF');
t.is(
error.message,
'The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.'
);
});
test('Throw an error if an array of plugin configuration is missing a path for plugin pipeline', t => {
const error = t.throws(() =>
getPlugins({verifyConditions: [{path: '@semantic-release/npm'}, {}]}, {}, t.context.logger)
);
t.is(error.name, 'SemanticReleaseError');
t.is(error.code, 'EPLUGINCONF');
t.is(
error.message,
'The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.'
);
});
-11
View File
@@ -1,11 +0,0 @@
var exec = require('child_process').exec
var opts = {
cwd: __dirname
}
module.exports = {
start: exec.bind(null, './start.sh', opts),
stop: exec.bind(null, './stop.sh', opts),
uri: 'http://localhost:' + (process.env.TRAVIS === 'true' ? 5984 : 15986) + '/registry/_design/app/_rewrite/'
}
-19
View File
@@ -1,19 +0,0 @@
[couchdb]
database_dir = data
view_index_dir = data
delayed_commits = false
[couch_httpd_auth]
public_fields = appdotnet, avatar, avatarMedium, avatarLarge, date, email, fields, freenode, fullname, github, homepage, name, roles, twitter, type, _id, _rev
users_db_public = true
[httpd]
port = 15986
bind_address = 127.0.0.1
secure_rewrites = false
[log]
file = couch/couch.log
[admins]
admin = -pbkdf2-89582b49cd2e8443e29a841f5a76d367956a8e58,1afa2f1531a17ac97f2ac9e334293753,10
-41
View File
@@ -1,41 +0,0 @@
#!/bin/bash
# exit if an error occurs
set -e
cd $(dirname $0)
mkdir -p couch
if [[ $TRAVIS = true ]]
then
COUCH=http://admin:password@127.0.0.1:5984
curl -X PUT http://127.0.0.1:5984/_config/admins/admin -d '"password"'
curl -X PUT $COUCH/_config/couchdb/delayed_commits -d '"false"'
curl -X PUT $COUCH/_config/couch_httpd_auth/users_db_public -d '"true"'
curl -X PUT $COUCH/_config/couch_httpd_auth/public_fields -d '"appdotnet, avatar, avatarMedium, avatarLarge, date, email, fields, freenode, fullname, github, homepage, name, roles, twitter, type, _id, _rev"'
curl -X PUT $COUCH/_config/httpd/secure_rewrites -d '"false"'
else
COUCH=http://admin:password@127.0.0.1:15986
couchdb -b -a local.ini -p couch/pid -o couch/stdout.log -e couch/stderr.log
# wait for couch to start
sleep 1
fi
# create "registry" database
curl -X PUT $COUCH/registry
# create sample npm user
curl -X PUT $COUCH/_users/org.couchdb.user:integration -H Content-Type:application/json --data-binary '{"_id": "org.couchdb.user:integration", "name": "integration", "roles": [], "type": "user", "password": "suchsecure", "email": "integration@test.com"}'
# npm-registry-couchpp needs this variable set to run
export DEPLOY_VERSION=nope
# setup npm-registry-couchapp
npm explore npm-registry-couchapp -- npm start --npm-registry-couchapp:couch=$COUCH/registry
npm explore npm-registry-couchapp -- npm run load --npm-registry-couchapp:couch=$COUCH/registry
export NO_PROMPT=yes
npm explore npm-registry-couchapp -- npm run copy --npm-registry-couchapp:couch=$COUCH/registry
-13
View File
@@ -1,13 +0,0 @@
#!/bin/bash
# close couchdb background process
couchdb -d
# delete data and logs
cd $(dirname $0)
cat couch/{couch,stdout,stderr}.log
cat couch/pid | xargs kill
rm -rf couch
rm -rf data

Some files were not shown because too many files have changed in this diff Show More