Compare commits

..
61 Commits
Author SHA1 Message Date
greenkeeper[bot]andPierre Vanduynslager aed4ea2edc fix(package): update yargs to version 13.1.0 2019-02-15 12:11:12 -05:00
greenkeeper[bot]andPierre Vanduynslager 448a0ff977 chore(package): update xo to version 0.24.0 2019-01-30 17:27:04 -05:00
Kevin LluchandPierre Vanduynslager 1b7d8b2d21 docs: add semantic-release-ado to community plugins 2019-01-29 16:15:23 -05:00
Austin Cawley-EdwardsandPierre Vanduynslager 952e3fdf64 docs: fix typo in CircleCI recipe 2019-01-22 11:32:41 -05:00
David AghassiandPierre Vanduynslager 6a8eede96f docs: cleaned up wording and typos in docs 2019-01-12 14:27:56 -05:00
David AghassiandPierre Vanduynslager 4652cef1e6 docs: corrected typos in jsdocs 2019-01-12 14:27:56 -05:00
greenkeeper[bot]andPierre Vanduynslager b7aeabad93 fix(package): update marked to version 0.6.0 2019-01-10 16:14:04 -05:00
greenkeeper[bot]andPierre Vanduynslager 3819ca56a9 chore(package): update ava to version 1.0.1 2018-12-27 14:43:11 -05:00
greenkeeper[bot]andPierre Vanduynslager 1aefd98d31 fix(package): update aggregate-error to version 2.0.0 2018-12-26 13:22:26 -05:00
Pierre Vanduynslager 1243f79064 fix: correctly handle skipped releases 2018-12-16 16:28:52 -05:00
Pierre Vanduynslager 70c68ef3ed feat: allow publish plugins to return false in order to signify no release was done 2018-12-14 16:16:27 -05:00
Pierre VanduynslagerandGregor Martynus 048292baa5 docs: fix broken link in CircleCI recipe 2018-12-14 10:48:58 -08:00
Pierre VanduynslagerandGregor Martynus 0f642ffe4d docs: remove mentions of travis-deploy-once 2018-12-14 10:48:58 -08:00
greenkeeper[bot]andPierre Vanduynslager 89ad3a0b61 chore(package): update p-retry to version 3.0.0 2018-12-12 11:59:37 -05:00
Pierre Vanduynslager 649b53087a docs: mention that debug option is CLI only 2018-12-11 13:33:06 -05:00
Pierre Vanduynslager 862ec4c087 fix: allow to set ci option via API and config file 2018-12-11 13:33:06 -05:00
Pierre Vanduynslager 6b110b6e9e docs: switch to spectrum.chat 2018-12-03 17:48:15 -05:00
Pierre Vanduynslager e4c6649714 docs: syntax fixes in plugins list 2018-11-30 03:25:05 -05:00
Pierre Vanduynslager 6220641aba docs: add @semantic-release/apm to plugins list 2018-11-30 03:25:05 -05:00
Evan SirokyandPierre Vanduynslager a45273e921 docs: add maven-semantic-release to list of community plugins 2018-11-30 03:12:00 -05:00
Pierre Vanduynslager d1091133b9 chore(package): update nyc and sinon 2018-11-30 02:10:04 -05:00
Pierre Vanduynslager cd69583746 test: delete unused test helper file 2018-11-30 01:24:16 -05:00
Pierre Vanduynslager ffe1062830 fix: remove unnecessary branch parameter from push function 2018-11-29 20:08:25 -05:00
Pierre Vanduynslager 7a9922a492 fix: rename default branch 2018-11-28 17:32:05 -05:00
Andy EdwardsandPierre Vanduynslager d6d1bc954e docs: grammar corrections 2018-11-27 16:04:50 -05:00
Pierre Vanduynslager eafbb343dd fix: correctly resolve plugins installed globally with npx
This bug affects only plugins defined with the `plugins` option and wrapped in an Array to add a configuration
2018-11-26 18:39:28 -05:00
Pierre Vanduynslager 2b082acc73 fix: push only tags to remote repo 2018-11-21 12:32:01 -05:00
Pierre Vanduynslager aa022e0ac2 test: clarify variables name 2018-11-21 12:32:01 -05:00
Pierre Vanduynslager f2ede5bdde docs: typo in JS docs 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager 9742712957 test: verify errors have message and details 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager 5937f13bdf test: fix typo 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager 43dbd10046 refactor: prefer filter shorter form 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager 9f5645cfa0 refactor: harmonize git utils function names 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager e594638a96 test: prefer array spread 2018-11-19 18:34:16 -05:00
Kostis (Codefresh)andPierre Vanduynslager 244f014a91 docs: add Codefresh in list of CIs with pipelines 2018-11-18 14:59:12 -05:00
Waldir PimentaandPierre Vanduynslager 218d830af0 docs: fix quote marks (#986) 2018-11-16 13:06:48 -05:00
Pierre Vanduynslager 90da6a0bc1 feat: add logs about prepare, publish, success and fail plugins skipped in dry-run mode 2018-11-14 11:27:06 -05:00
Pierre Vanduynslager 90b497464e test: test that dry-run also skips prepare step 2018-11-14 11:27:06 -05:00
Pierre Vanduynslager c86518a050 fix: do not underline log messages 2018-11-14 11:27:06 -05:00
Pierre Vanduynslager e92c84ec08 fix: indicate in logs if running in dry-run mode 2018-11-14 11:27:06 -05:00
Pierre Vanduynslager 5180001ae6 feat: support multiple plugins for the analyzeCommits step
In case multiple plugins with a `analyzeCommits` step are configured, all of them will be executed and the highest release type (`major` > `minor`, `patch`) will be used.
2018-11-12 15:06:46 -05:00
Pierre Vanduynslager 728ea34dda fix: remove redundant log 2018-11-12 15:06:46 -05:00
Pierre Vanduynslager 83af7acf69 docs: mention default analyzeCommits plugin 2018-11-12 15:06:46 -05:00
Pierre Vanduynslager 8e564ebc9d docs: update FAQ to reflect new plugins option 2018-11-09 17:08:49 -05:00
Pierre Vanduynslager dff1f1056f docs: mention postversion npm script hook to run build scripts 2018-11-09 17:08:49 -05:00
Pierre Vanduynslager ae4995c867 style: fix prettier errors 2018-11-07 12:19:19 -05:00
greenkeeper[bot]andPierre Vanduynslager 669c9ed300 fix(package): update find-versions to version 3.0.0 2018-11-06 12:59:37 -05:00
Pierre Vanduynslager 3c8177aed8 fix: add debug logs for config file path 2018-11-02 15:00:12 -04:00
Pierre Vanduynslager 6d0bd8c9b1 fix: add debug logs for plugins resolved options 2018-11-02 15:00:12 -04:00
Pierre Vanduynslager a99355effa fix: remove dependency to git-url-parse 2018-10-27 09:35:45 -04:00
Pierre Vanduynslager cc06d8999a test: fix errors ordering in assertions 2018-10-27 09:35:45 -04:00
Lucas CorreiaandPierre Vanduynslager 3411520ea7 fix: include release notes in JS API result for dry mode 2018-10-20 12:37:11 -04:00
Pierre Vanduynslager 3d5db1f8b0 fix: remove debugging console.error 2018-10-20 04:24:21 -04:00
Cedric van PuttenandPierre Vanduynslager cfc10039f3 docs: add semantic-release-expo to plugins list 2018-10-18 11:10:52 -04:00
Pierre Vanduynslager 0578c8b91c fix: do not log outated branch error for missing permission cases 2018-10-17 15:33:16 -04:00
Pierre Vanduynslager e29110103b docs: add section existing tags in configuration docs 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager 88539222f4 docs: add troubleshooting section for reference already exists Git error 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager d45861b989 docs: clarify the "npm missing permission" troubleshooting section 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager 2ba0b81f39 docs: remove troubleshooting section related to legacy error messages 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager e93a663490 docs: fix markdown link in configuration docs 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager 58c25beeb6 fix: fix logs for plugins loaded with plugins option 2018-10-09 16:33:37 -04:00
46 changed files with 586 additions and 697 deletions
+2 -2
View File
@@ -7,11 +7,11 @@ node_js:
- 10
- 8
# Trigger a push build on caribou and greenkeeper branches + PRs build on every branches
# Trigger a push build on master and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
only:
- caribou
- master
- /^greenkeeper.*$/
# Retry install on fail to avoid failing a build on network/disk/external errors
+5 -5
View File
@@ -1,14 +1,14 @@
<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 href="https://spectrum.chat/semantic-release">
<img alt="Join the community on Spectrum" src="https://withspectrum.github.io/badge/badge.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">
<img alt="Travis" src="https://img.shields.io/travis/semantic-release/semantic-release/master.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">
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/semantic-release/semantic-release/master.svg">
</a>
<a href="https://greenkeeper.io">
<img alt="Greenkeeper" src="https://badges.greenkeeper.io/semantic-release/semantic-release.svg">
@@ -124,7 +124,7 @@ After running the tests, the command `semantic-release` will execute the followi
## Get help
- [Stack Overflow](https://stackoverflow.com/questions/tagged/semantic-release)
- [Gitter chat](https://gitter.im/semantic-release/semantic-release)
- [Spectrum community](https://spectrum.chat/semantic-release)
- [Twitter](https://twitter.com/SemanticRelease)
## Badge
+2 -2
View File
@@ -3,7 +3,7 @@
// Bad news: We have to write plain ES5 in this file
// Good news: It's the only file of the entire project
/* eslint-disable no-var, promise/prefer-await-to-then, prefer-destructuring */
/* eslint-disable no-var */
var semver = require('semver');
var execa = require('execa');
@@ -16,7 +16,7 @@ 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.`
See https://github.com/semantic-release/semantic-release/blob/master/docs/support/node-version.md for more details and solutions.`
);
process.exit(1);
}
+3 -6
View File
@@ -1,4 +1,4 @@
const {argv, env, stderr} = require('process');
const {argv, env, stderr} = require('process'); // eslint-disable-line node/prefer-global/process
const util = require('util');
const hideSensitive = require('./lib/hide-sensitive');
@@ -47,21 +47,18 @@ Usage:
return 0;
}
// Set the `noCi` options as yargs sets the `ci` options instead (because arg starts with `--no`)
if (opts.ci === false) {
opts.noCi = true;
}
if (opts.debug) {
// Debug must be enabled before other requires in order to work
require('debug').enable('semantic-release:*');
}
await require('.')(opts);
return 0;
} catch (error) {
if (error.name !== 'YError') {
stderr.write(hideSensitive(env)(util.inspect(error, {colors: true})));
}
return 1;
}
};
-2
View File
@@ -1,2 +0,0 @@
codecov:
branch: caribou
+21 -7
View File
@@ -26,23 +26,27 @@
- [@semantic-release/exec](https://github.com/semantic-release/exec)
- `verifyConditions`: Execute a shell command to verify if the release should happen
- `analyzeCommits`: Execute a shell command to determine the type of release
- `verifyRelease`: Execute a shell command to verifying a release that was determined before and is about to be published.
- `verifyRelease`: Execute a shell command to verifying a release that was determined before and is about to be published
- `generateNotes`: Execute a shell command to generate the release note
- `prepare`: Execute a shell command to prepare the release
- `publish`: Execute a shell command to publish the release
- `success`: Execute a shell command to notify of a new release
- `fail`: Execute a shell command to notify of a failed release
- [@semantic-release/apm](https://github.com/semantic-release/apm)
- `verifyConditions`: Verify the presence of the `ATOM_ACCESS_TOKEN` environment variable and the [`apm`](https://github.com/atom/apm) CLI
- `prepare`: Update the `package.json` version with [`npm version`](https://docs.npmjs.com/cli/version)
- `publish`: Publish the [Atom package](https://flight-manual.atom.io/hacking-atom/sections/publishing)
## Community plugins
[Open a Pull Request](https://github.com/semantic-release/semantic-release/blob/caribou/CONTRIBUTING.md#submitting-a-pull-request) to add your plugin to the list.
[Open a Pull Request](https://github.com/semantic-release/semantic-release/blob/master/CONTRIBUTING.md#submitting-a-pull-request) to add your plugin to the list.
- [semantic-release-docker](https://github.com/felixfbecker/semantic-release-docker)
- `verifyConditions`: Verify that all needed configuration is present and login to the Docker registry.
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag.
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag
- [semantic-release-gcr](https://github.com/carlos-cubas/semantic-release-gcr)
- `verifyConditions`: Verify that all needed configuration is present and login to the Docker registry.
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag.
- `verifyConditions`: Verify that all needed configuration is present and login to the Docker registry
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag
- [semantic-release-vsce](https://github.com/raix/semantic-release-vsce)
- `verifyConditions`: Verify the presence and the validity of the vsce authentication and release configuration
- `prepare`: Create a `.vsix` for distribution
@@ -51,11 +55,21 @@
- `verifyConditions`: Check the dependencies format against a regexp before a release
- [semantic-release-chrome](https://github.com/GabrielDuarteM/semantic-release-chrome)
- `verifyConditions`: Verify the presence of the authentication (set via environment variables)
- `prepare`: Write the correct version to the manifest.json and creates a zip file of the whole dist folder
- `prepare`: Write the correct version to the `manifest.json` and creates a zip file of the whole dist folder
- `publish`: Uploads the generated zip file to the webstore, and publish the item
- [semantic-release-firefox](https://github.com/felixfbecker/semantic-release-firefox)
- `verifyConditions`: Verify the presence of the authentication (set via environment variables)
- `prepare`: Write the correct version to the manifest.json, creates a xpi file of the dist folder and a zip of the sources
- `prepare`: Write the correct version to the `manifest.json`, creates a `xpi` file of the dist folder and a zip of the sources
- `publish`: Submit the generated archives to the webstore for review, and publish the item including release notes
- [semantic-release-gerrit](https://github.com/pascalMN/semantic-release-gerrit)
- `generateNotes`: Generate release notes with Gerrit reviews URL
- [semantic-release-expo](https://github.com/bycedric/semantic-release-expo)
- `verifyConditions`: Verify Expo manifest(s) are readable and valid.
- `prepare`: Update version, ios build number and android version code in the Expo manifest(s).
- [maven-semantic-release](https://github.com/conveyal/maven-semantic-release)
- `verifyConditions`: Verifies that the `pom.xml` file and other files exist and are setup to allow releases
- `verifyRelease`: Checks and warns (does not error by default) if the version numbers found on maven central and within the Git project differ by quite a bit
- `prepare`: Changes the version number in the `pom.xml` (or all `pom.xml` files in maven projects with multiple `pom.xml` files) and optionally creates a commit with this version number and pushes it to `master`
- `publish`: Runs `mvn deploy` to deploy to maven central and optionally will update to next snapshot version and merge changes to development branch
- [semantic-release-ado](https://github.com/lluchmk/semantic-release-ado)
- `prepare`: Stores the version number as an Azure DevOps pipeline variable availabe to downstream steps on the job
-1
View File
@@ -3,7 +3,6 @@
## 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)
## Git hosted services
+1 -1
View File
@@ -4,7 +4,7 @@
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [CircleCi Project Settings](https://circleci.com/docs/2.0/env-vars/#adding-environment-variables-in-the-app)..
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).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/getting-started.md#getting-started).
## Multiple Node jobs configuration
+1 -1
View File
@@ -158,6 +158,6 @@ Commit the encrypted private key and the `.circleci/config.yml` file to your rep
```bash
$ git add git_deploy_key.enc .circleci/config.yml
$ git commit -m "ci(cicle): Add the encrypted private ssh key"
$ git commit -m "ci(circle): Add the encrypted private ssh key"
$ git push
```
-95
View File
@@ -1,95 +0,0 @@
# Using semantic-release with [Travis CI build stages](https://docs.travis-ci.com/user/build-stages)
## 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).
## Multiple Node jobs configuration
### `.travis.yml` configuration for multiple Node jobs
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
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).
**Advanced configuration**: Running the tests in the `script` step of the `release` stage is not necessary as the previous stage(s) already ran them. To increase speed, the `script` step of the `release` stage can be overwritten to skip the tests. Note that other commands such as build or compilation might still be required.
```yaml
language: node_js
node_js:
- 8
- 6
jobs:
include:
# Define the release stage that runs semantic-release
- stage: release
node_js: lts/*
# Advanced: optionally overwrite your default `script` step to skip the tests
# script: skip
deploy:
provider: script
skip_cleanup: true
script:
- npx semantic-release
```
### `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": "^15.0.0"
}
}
```
## 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). See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
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).
**Advanced configuration**: Running the tests in the `script` step of the `release` stage is not necessary as the previous stage(s) already ran them. To increase speed, the `script` step of the `release` stage can be overwritten to skip the tests. Note that other commands such as build or compilation might still be required.
```yaml
language: go
go:
- 1.6
- 1.7
jobs:
include:
# Define the release stage that runs semantic-release
- stage: release
# Advanced: optionally overwrite your default `script` step to skip the tests
# script:
# - make
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/*
- npx semantic-release
```
+38 -72
View File
@@ -4,62 +4,22 @@
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).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/getting-started.md#getting-started).
## Single Node job configuration
## Node.js projects 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--83).
### `.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).
```yaml
language: node_js
node_js: 8
deploy:
provider: script
skip_cleanup: true
script:
- npx 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"
}
}
```
## 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
### `.travis.yml` configuration for multiple Node.js jobs
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. 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).
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
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).
**Advanced configuration**: Running the tests in the `script` step of the `release` stage is not necessary as the previous stage(s) already ran them. To increase speed, the `script` step of the `release` stage can be overwritten to skip the tests. Note that other commands such as build or compilation might still be required.
```yaml
language: node_js
@@ -67,15 +27,20 @@ node_js:
- 8
- 6
deploy:
provider: script
skip_cleanup: true
script:
- npx travis-deploy-once "npx semantic-release"
jobs:
include:
# Define the release stage that runs semantic-release
- stage: release
node_js: lts/*
# Advanced: optionally overwrite your default `script` step to skip the tests
# script: skip
deploy:
provider: script
skip_cleanup: true
script:
- npx 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.
@@ -83,13 +48,12 @@ A `package.json` is required only for [local](../usage/installation.md#local-ins
```json
{
"devDependencies": {
"semantic-release": "^15.0.0",
"travis-deploy-once": "^5.0.0"
"semantic-release": "^15.0.0"
}
}
```
## Non-JavaScript projects configuration
## Non-Node.js 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).
@@ -97,14 +61,16 @@ This recipe cover the Travis specifics only. See [Non JavaScript projects recipe
### `.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 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). 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).
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
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).
**Advanced configuration**: Running the tests in the `script` step of the `release` stage is not necessary as the previous stage(s) already ran them. To increase speed, the `script` step of the `release` stage can be overwritten to skip the tests. Note that other commands such as build or compilation might still be required.
```yaml
language: go
@@ -112,18 +78,18 @@ go:
- 1.6
- 1.7
os:
- linux
- osx
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/*
# Run semantic-release only on one job, after all other are successful
- npx travis-deploy-once "npx semantic-release"
jobs:
include:
# Define the release stage that runs semantic-release
- stage: release
# Advanced: optionally overwrite your default `script` step to skip the tests
# script:
# - make
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/*
- npx 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).
+33 -20
View File
@@ -12,7 +12,25 @@ However, the [`@semantic-release/git`](https://github.com/semantic-release/git)
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.
As the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin uses the [npm CLI](https://docs.npmjs.com/cli/npm) to update the `package.json` version and publish the package, all [npm hook scripts](https://docs.npmjs.com/misc/scripts#description) will be executed.
You can run your build script in:
- the `prepublishOnly` or `prepack` hook so it will be executed during the `publish` step of `@semantic-release/npm`
- the `postversion` hook so it will be executed during the `prepare` step of `@semantic-release/npm`, which allow for example to update files before committing them with the [`@semantic-release/git`](https://github.com/semantic-release/git) plugin
If using npm hook scripts is not possible, and alternative solution is to [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin to run your script in the `prepare` step:
```json
{
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/npm",
["@semantic-release/exec", {
"prepareCmd": "./my-build-script.sh ${nextRelease.version}",
}],
]
}
```
## Is there a way to preview which version would currently get published?
@@ -59,28 +77,23 @@ To publish a non-Node package (without a `package.json`) you would need to:
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
In addition you will need to configure the **semantic-release** [plugins](../usage/plugins.md#plugins) to:
- Disable the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin
- Define plugins for the [verifyConditions](../usage/plugins.md#verifyconditions-plugin), [prepare](../usage/plugins.md#prepare-plugin) and [publish](../usage/plugins.md#publish-plugin) steps to release on your package registry. The [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin is recommended for situation where a release can be done with a shell command.
In addition you will need to configure the **semantic-release** [plugins](../usage/plugins.md#plugins) to disable the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin which is used by default and use a plugin for your project type.
Here is a basic example to create [GitHub releases](https://help.github.com/articles/about-releases) and use shell command to publish:
If there is no specific plugin for your project type you can use the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin to publish the release with a shell command.
Here is a basic example to create [GitHub releases](https://help.github.com/articles/about-releases) and use a shell command to publish:
```json
{
"verifyConditions": ["@semantic-release/github"],
"prepare": [
{
"path": "@semantic-release/exec",
"cmd": "set-version ${nextRelease.version}"
}
],
"publish": [
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/github",
{
"path": "@semantic-release/exec",
"cmd": "publish-package"
}
],
["@semantic-release/exec", {
"prepareCmd" : "set-version ${nextRelease.version}",
"publishCmd" : "publish-package"
}]
]
}
```
@@ -114,7 +127,7 @@ See the [GitLab CI recipes](../recipes/gitlab-ci.md#using-semantic-release-with-
## 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).
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).
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.
@@ -132,7 +145,7 @@ If you have introduced a breaking bug in a release you have 2 options:
In both cases **semantic-release** will publish a new release, so your package users' will get the fixed/reverted version.
Depending on the package manager you are using, you might be able to un-publish or deprecate a release, in order to prevent users to download it by accident. For example npm allows you to [un-publish](https://docs.npmjs.com/cli/unpublish) in [next 72 hours](https://www.npmjs.com/policies/unpublish) after releasing or to [deprecate](https://docs.npmjs.com/cli/deprecate) a release.
Depending on the package manager you are using, you might be able to un-publish or deprecate a release, in order to prevent users from downloading it by accident. For example npm allows you to [un-publish](https://docs.npmjs.com/cli/unpublish) [within 72 hours](https://www.npmjs.com/policies/unpublish) after releasing. You may also [deprecate](https://docs.npmjs.com/cli/deprecate) a release if you would rather avoid un-publishing.
In any case **do not remove the Git tag associated with the buggy version**, otherwise **semantic-release** will later try to republish that version. Publishing a version after un-publishing is not supported by most package managers.
+5 -5
View File
@@ -4,17 +4,17 @@
- ["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)
- ["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)
- ["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)
- ["Introduction to SemVer" - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2)
- ["Introduction to Semantic Release" - liv](https://blog.greenkeeper.io/introduction-to-semantic-release-33f73b117c8)
## Tutorials
- [How to Write a JavaScript Library - Automating Releases with semantic-release egghead.io](https://egghead.io/lessons/javascript-automating-releases-with-semantic-release)
- ["How to Write a JavaScript Library - Automating Releases with semantic-release" egghead.io](https://egghead.io/lessons/javascript-automating-releases-with-semantic-release)
+35 -35
View File
@@ -1,49 +1,26 @@
# 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>
```
## You do not have permission to publish 'package-name'
When running semantic-release you may encounter the following error:
When running semantic-release you might encounter the following error:
```
An error occurred while running semantic-release: { Error: Command failed: npm publish ./. --registry https://registry.npmjs.org/
```bash
npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! You do not have permission to publish "<package-name>". Are you logged in as the correct user? : <package-name>
```
This message is a little unclear, and might not have anything to with your `NPM_TOKEN` or authentication method. It might instead be related to the package name itself. If there is already a package with the same name as yours or, there is a very close match, it could trigger this error.
This is most likely related to a misconfiguration of the [npm registry authentication](https://github.com/semantic-release/npm#npm-registry-authentication) or to your user [missing permission](https://docs.npmjs.com/cli/team) for publishing.
Best way to be sure, is to search [npmjs.org](https://www.npmjs.com/)) using your package name. If there is a name conflict, rename your package in your `package.json`
It might also happen if the package name you are trying to publish already exists (in the case of npm, you may be trying to publish a new version of a package that is not yours, hence the permission error).
To verify if your package name is available you can use [npm-name-cli](https://github.com/sindresorhus/npm-name-cli):
```bash
$ npm install --global npm-name-cli
$ npm-name <package-name>
```
If the package name is not available, change it in your `package.json` or consider using an [npm scope](https://docs.npmjs.com/misc/scope).
## Squashed commits are ignored by **semantic-release**
@@ -54,3 +31,26 @@ When [squashing commits](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-Hist
When squashing commits make sure to rewrite the resulting commit message to be compliant with the project's commit message convention.
**Note**: if the resulting squashed commit would encompasses multiple changes (for example multiple unrelated features or fixes) then it's probably not a good idea to squash those commits together. A commit should contain exactly one self-contained functional change and a functional change should be contained in exactly one commit. See [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit).
## `reference already exists` error when pushing tag
**semantic-release** read [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging) that are present in the history of your release branch in order to determine the last release published. Then it determines the next version to release based on the commits pushed since then and create the corresponding tag.
If a tag with the name already in your repository, Git will throw and error as tags must be unique across the repository.
This situation happens when you have a version tag identical to the new one **semantic-release** is trying to create that is not in the history of the current branch.
If an actual release with that version number was published you need to merge all the commits up to that release into your release branch.
If there is no published release with that version number, the tag must be deleted.
```bash
# Verify if the commit exists in the repository
$ git rev-list -1 <tag name>
# If a commit sha is returned, then the tag exists
# Verify the branches having the tagged commit in their history
$ git branch --contains <tag name>
# Delete the tag
$ git tag -d <tag name>
$ git push origin :refs/tags/<tag name>
```
+2 -2
View File
@@ -2,7 +2,7 @@
## 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).
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), [Codefresh Pipelines](https://codefresh.io/docs/docs/configure-ci-cd-pipeline/introduction-to-codefresh-pipelines), [Wercker Workflows](http://devcenter.wercker.com/docs/workflows) or [GoCD Pipelines](https://docs.gocd.org/current/introduction/concepts_in_go.html#pipeline).
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
@@ -26,7 +26,7 @@ Most **semantic-release** [plugins](plugins.md) require setting up authenticatio
| `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 each plugin documentation for the environment variables to set up.
See each plugin's documentation for the environment variables required.
The authentication token/credentials have to be made available in the CI service via environment variables.
+32 -5
View File
@@ -1,11 +1,11 @@
# Configuration
**semantic-release** configuration consist of:
**semantic-release** configuration consists of:
- Git repository options ([URL](#repositoryurl), [release branch](#branch) and [tag format](#tagformat))
- [plugins](#plugins) definition
- run mode ([debug](#debug), [dry run](#dryrun) and [local (no CI)](#ci))
All those options can be configured directly or by extending a [shareable configuration](shareable-configurations.md).
All of these options can be configured directly or by extending a [shareable configuration](shareable-configurations.md).
Additionally, metadata of Git tags generated by **semantic-release** can be customized via standard [Git environment variables](#git-environment-variables).
@@ -16,7 +16,7 @@ Additionally, metadata of Git tags generated by **semantic-release** can be cust
- A `release.config.js` file that exports an object
- A `release` key in the project's `package.json` file
Alternatively some options can be set via CLI arguments.
Alternatively, some options can be set via CLI arguments.
The following three examples are the same.
@@ -105,7 +105,7 @@ Define the list of plugins to use. Plugins will run in series, in the order defi
Plugins configuration can defined by wrapping the name and an options object in an array.
See [Plugins configuration](plugins.md#configuration) for more details.
See [Plugins configuration](plugins.md#plugins) for more details.
### dryRun
@@ -131,7 +131,9 @@ Type: `Boolean`<br>
Default: `false`<br>
CLI argument: `--debug`
Output debugging information. It can also be enabled by setting the `DEBUG` environment variable to `semantic-release:*`.
Output debugging information. This can also be enabled by setting the `DEBUG` environment variable to `semantic-release:*`.
**Note**: The `debug` is used only supported via CLI argument. To enable debug mode from the [JS API](../developer-guide/js-api.md#javascript-api) use `require('debug').enable('semantic-release:*')`.
## Git environment variables
@@ -141,3 +143,28 @@ Output debugging information. It can also be enabled by setting the `DEBUG` envi
| `GIT_AUTHOR_EMAIL` | The author email associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot email address. |
| `GIT_COMMITTER_NAME` | The committer name associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot. |
| `GIT_COMMITTER_EMAIL` | The committer email associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot email address. |
## Existing version tags
**semantic-release** uses [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging) to determine the commits added since the last release. If a release has been published before setting up **semantic-release** you must make sure the most recent commit included in the last published release is in the [release branch](#branch) history and is tagged with the version released, formatted according to the [tag format](#tagformat) configured (defaults to `vx.y.z`).
If the previous releases were published with [`npm publish`](https://docs.npmjs.com/cli/publish) this should already be the case.
For example, if your release branch is `master`, the last release published on your project is `1.1.0` and the last commit included has the sha `1234567`, you must make sure this commit is in `master` history and is tagged with `v1.1.0`.
```bash
# Make sure the commit 1234567 is in the release branch history
$ git branch --contains 1234567
# If the commit is not in the branch history it means that either:
# - you use a different branch than the one your release from before
# - or the commit sha has been rewritten (with git rebase)
# In both cases you need to configure your repository to have the last release commit in the history of the release branch
# List the tags for the commit 1234567
$ git tag --contains 1234567
# If v1.1.0 is not in the list you add it with
$ git tag v1.1.0 1234567
$ git push origin v1.1.0
```
+12 -10
View File
@@ -4,16 +4,18 @@ Each [release step](../../README.md#release-steps) is implemented by configurabl
A plugin is a npm module that can implement one or more of the following steps:
| Step | Accept multiple | Required | Description |
|--------------------|-----------------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `verifyConditions` | Yes | No | Responsible for verifying conditions necessary to proceed with the release: configuration is correct, authentication token are valid, etc... |
| `analyzeCommits` | No | Yes | Responsible for determining the type of the next release (`major`, `minor` or `patch`). |
| `verifyRelease` | Yes | No | Responsible for verifying the parameters (version, type, dist-tag etc...) of the release that is about to be published. |
| `generateNotes` | Yes | No | Responsible for generating the content of the release note. If multiple `generateNotes` plugins are defined, the release notes will be the result of the concatenation of each plugin output. |
| `prepare` | Yes | No | Responsible for preparing the release, for example creating or updating files such as `package.json`, `CHANGELOG.md`, documentation or compiled assets and pushing a commit. |
| `publish` | Yes | No | Responsible for publishing the release. |
| `success` | Yes | No | Responsible for notifying of a new release. |
| `fail` | Yes | No | Responsible for notifying of a failed release. |
| Step | Required | Description |
|--------------------|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `verifyConditions` | No | Responsible for verifying conditions necessary to proceed with the release: configuration is correct, authentication token are valid, etc... |
| `analyzeCommits` | Yes | Responsible for determining the type of the next release (`major`, `minor` or `patch`). If multiple plugins with a `analyzeCommits` step are defined, the release type will be the highest one among plugins output. |
| `verifyRelease` | No | Responsible for verifying the parameters (version, type, dist-tag etc...) of the release that is about to be published. |
| `generateNotes` | No | Responsible for generating the content of the release note. If multiple plugins with a `generateNotes` step are defined, the release notes will be the result of the concatenation of each plugin output. |
| `prepare` | No | Responsible for preparing the release, for example creating or updating files such as `package.json`, `CHANGELOG.md`, documentation or compiled assets and pushing a commit. |
| `publish` | No | Responsible for publishing the release. |
| `success` | No | Responsible for notifying of a new release. |
| `fail` | No | Responsible for notifying of a failed release. |
**Note:** If no plugin with a `analyzeCommits` step is defined `@semantic-release/commit-analyzer` will be used.
See [available plugins](../extending/plugins-list.md).
+1 -1
View File
@@ -1,6 +1,6 @@
# Shareable configurations
A sharable configuration is an [npm](https://www.npmjs.com/) package that exports a **semantic-release** configuration object. It allows for use of the same configuration across several projects.
A shareable configuration is an [npm](https://www.npmjs.com/) package that exports a **semantic-release** configuration object. It allows for use of the same configuration across several projects.
The shareable configurations to use can be set with the [extends](configuration.md#extends) option.
+37 -26
View File
@@ -13,7 +13,7 @@ const getLastRelease = require('./lib/get-last-release');
const {extractErrors} = require('./lib/utils');
const getGitAuthUrl = require('./lib/get-git-auth-url');
const getLogger = require('./lib/get-logger');
const {fetch, verifyAuth, isBranchUpToDate, gitHead: getGitHead, tag, push} = require('./lib/git');
const {fetch, verifyAuth, isBranchUpToDate, getGitHead, tag, push} = require('./lib/git');
const getError = require('./lib/get-error');
const {COMMIT_NAME, COMMIT_EMAIL} = require('./lib/definitions/constants');
@@ -24,7 +24,7 @@ async function run(context, plugins) {
const {isCi, branch: ciBranch, isPr} = envCi({env, cwd});
if (!isCi && !options.dryRun && !options.noCi) {
logger.log('This run was not triggered in a known CI environment, running in dry-run mode.');
logger.warn('This run was not triggered in a known CI environment, running in dry-run mode.');
options.dryRun = true;
} else {
// When running on CI, set the commits author and commiter info and prevent the `git` CLI to prompt for username/password. See #703.
@@ -52,21 +52,29 @@ async function run(context, plugins) {
);
return false;
}
logger.success(`Run automated release from branch ${ciBranch}`);
logger[options.dryRun ? 'warn' : 'success'](
`Run automated release from branch ${ciBranch}${options.dryRun ? ' in dry-run mode' : ''}`
);
await verify(context);
options.repositoryUrl = await getGitAuthUrl(context);
try {
await verifyAuth(options.repositoryUrl, options.branch, {cwd, env});
} catch (error) {
if (!(await isBranchUpToDate(options.branch, {cwd, env}))) {
logger.log(
`The local branch ${options.branch} is behind the remote one, therefore a new version won't be published.`
);
return false;
try {
await verifyAuth(options.repositoryUrl, options.branch, {cwd, env});
} catch (error) {
if (!(await isBranchUpToDate(options.branch, {cwd, env}))) {
logger.log(
`The local branch ${options.branch} is behind the remote one, therefore a new version won't be published.`
);
return false;
}
throw error;
}
} catch (error) {
logger.error(`The command "${error.cmd}" failed with the error message ${error.stderr}.`);
throw getError('EGITNOPERMISSION', {options});
}
@@ -86,32 +94,37 @@ async function run(context, plugins) {
logger.log('There are no relevant changes, so no new version is released.');
return false;
}
context.nextRelease = nextRelease;
nextRelease.version = getNextVersion(context);
nextRelease.gitTag = template(options.tagFormat)({version: nextRelease.version});
await plugins.verifyRelease(context);
if (options.dryRun) {
const notes = await plugins.generateNotes(context);
logger.log(`Release note for version ${nextRelease.version}:`);
if (notes) {
context.stdout.write(marked(notes));
}
} else {
nextRelease.notes = await plugins.generateNotes(context);
await plugins.prepare(context);
nextRelease.notes = await plugins.generateNotes(context);
await plugins.prepare(context);
if (options.dryRun) {
logger.warn(`Skip ${nextRelease.gitTag} tag creation in dry-run mode`);
} else {
// Create the tag before calling the publish plugins as some require the tag to exists
await tag(nextRelease.gitTag, {cwd, env});
await push(options.repositoryUrl, options.branch, {cwd, env});
await push(options.repositoryUrl, {cwd, env});
logger.success(`Created tag ${nextRelease.gitTag}`);
}
context.releases = await plugins.publish(context);
context.releases = await plugins.publish(context);
await plugins.success(context);
await plugins.success(context);
logger.success(`Published release ${nextRelease.version}`);
logger.success(`Published release ${nextRelease.version}`);
if (options.dryRun) {
logger.log(`Release note for version ${nextRelease.version}:`);
if (nextRelease.notes) {
context.stdout.write(marked(nextRelease.notes));
}
}
return pick(context, ['lastRelease', 'commits', 'nextRelease', 'releases']);
@@ -158,9 +171,7 @@ module.exports = async (opts = {}, {cwd = process.cwd(), env = process.env, stdo
unhook();
return result;
} catch (error) {
if (!options.dryRun) {
await callFail(context, plugins, error);
}
await callFail(context, plugins, error);
throw error;
}
} catch (error) {
+1 -1
View File
@@ -1,4 +1,4 @@
const RELEASE_TYPE = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'];
const RELEASE_TYPE = ['prerelease', 'prepatch', 'patch', 'preminor', 'minor', 'premajor', 'major'];
const FIRST_RELEASE = '1.0.0';
+4 -7
View File
@@ -1,12 +1,11 @@
const url = require('url');
const {inspect} = require('util');
const {toLower, isString} = require('lodash');
const pkg = require('../../package.json');
const {RELEASE_TYPE} = require('./constants');
const homepage = url.format({...url.parse(pkg.homepage), hash: null});
const [homepage] = pkg.homepage.split('#');
const stringify = obj => (isString(obj) ? obj : inspect(obj, {breakLength: Infinity, depth: 2, maxArrayLength: 5}));
const linkify = file => `${homepage}/blob/caribou/${file}`;
const linkify = file => `${homepage}/blob/master/${file}`;
module.exports = {
ENOGITREPO: ({cwd}) => ({
@@ -55,13 +54,11 @@ Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
}),
EPLUGINCONF: ({type, multiple, required, pluginConf}) => ({
EPLUGINCONF: ({type, required, pluginConf}) => ({
message: `The \`${type}\` plugin configuration is invalid.`,
details: `The [${type} plugin configuration](${linkify(`docs/usage/plugins.md#${toLower(type)}-plugin`)}) ${
required ? 'is required and ' : ''
}must be ${
multiple ? 'a single or an array of plugins' : 'a single plugin'
} definition. A plugin definition is an npm module name, optionnaly wrapped in an array with an object.
} must be a single or an array of plugins definition. A plugin definition is an npm module name, optionnaly wrapped in an array with an object.
Your configuration for the \`${type}\` plugin is \`${stringify(pluginConf)}\`.`,
}),
+21 -15
View File
@@ -1,34 +1,40 @@
const {isString, isPlainObject} = require('lodash');
const {gitHead} = require('../git');
const {getGitHead} = require('../git');
const hideSensitive = require('../hide-sensitive');
const {hideSensitiveValues} = require('../utils');
const {RELEASE_TYPE, RELEASE_NOTES_SEPARATOR} = require('./constants');
module.exports = {
verifyConditions: {
multiple: true,
required: false,
dryRun: true,
pipelineConfig: () => ({settleAll: true}),
},
analyzeCommits: {
default: ['@semantic-release/commit-analyzer'],
multiple: false,
required: true,
dryRun: true,
outputValidator: output => !output || RELEASE_TYPE.includes(output),
preprocess: ({commits, ...inputs}) => ({
...inputs,
commits: commits.filter(commit => !/\[skip\s+release\]|\[release\s+skip\]/i.test(commit.message)),
}),
postprocess: ([result]) => result,
postprocess: results =>
RELEASE_TYPE[
results.reduce((highest, result) => {
const typeIndex = RELEASE_TYPE.indexOf(result);
return typeIndex > highest ? typeIndex : highest;
}, -1)
],
},
verifyRelease: {
multiple: true,
required: false,
dryRun: true,
pipelineConfig: () => ({settleAll: true}),
},
generateNotes: {
multiple: true,
required: false,
dryRun: true,
outputValidator: output => !output || isString(output),
pipelineConfig: () => ({
getNextInput: ({nextRelease, ...context}, notes) => ({
@@ -42,45 +48,45 @@ module.exports = {
postprocess: (results, {env}) => hideSensitive(env)(results.filter(Boolean).join(RELEASE_NOTES_SEPARATOR)),
},
prepare: {
multiple: true,
required: false,
pipelineConfig: ({generateNotes}, logger) => ({
dryRun: false,
pipelineConfig: ({generateNotes}) => ({
getNextInput: async context => {
const newGitHead = await gitHead({cwd: context.cwd});
const newGitHead = await getGitHead({cwd: context.cwd});
// If previous prepare plugin has created a commit (gitHead changed)
if (context.nextRelease.gitHead !== newGitHead) {
context.nextRelease.gitHead = newGitHead;
// Regenerate the release notes
logger.log('Call plugin %s', 'generateNotes');
context.nextRelease.notes = await generateNotes(context);
}
// Call the next prepare plugin with the updated `nextRelease`
return context;
},
}),
},
publish: {
multiple: true,
required: false,
dryRun: false,
outputValidator: output => !output || isPlainObject(output),
pipelineConfig: () => ({
// Add `nextRelease` and plugin properties to published release
transform: (release, step, {nextRelease}) => ({
...(isPlainObject(release) ? release : {}),
...nextRelease,
...(release === false ? {} : nextRelease),
...release,
...step,
}),
}),
},
success: {
multiple: true,
required: false,
dryRun: false,
pipelineConfig: () => ({settleAll: true}),
preprocess: ({releases, env, ...inputs}) => ({...inputs, env, releases: hideSensitiveValues(env, releases)}),
},
fail: {
multiple: true,
required: false,
dryRun: false,
pipelineConfig: () => ({settleAll: true}),
preprocess: ({errors, env, ...inputs}) => ({...inputs, env, errors: hideSensitiveValues(env, errors)}),
},
+24 -12
View File
@@ -6,6 +6,7 @@ const debug = require('debug')('semantic-release:config');
const {repoUrl} = require('./git');
const PLUGINS_DEFINITIONS = require('./definitions/plugins');
const plugins = require('./plugins');
const {validatePlugin, parseConfig} = require('./plugins/utils');
const CONFIG_NAME = 'release';
const CONFIG_FILES = [
@@ -20,9 +21,16 @@ const CONFIG_FILES = [
module.exports = async (context, opts) => {
const {cwd, env} = context;
const {config} = (await cosmiconfig(CONFIG_NAME, {searchPlaces: CONFIG_FILES}).search(cwd)) || {};
const {config, filepath} = (await cosmiconfig(CONFIG_NAME, {searchPlaces: CONFIG_FILES}).search(cwd)) || {};
debug('load config from: %s', filepath);
// Merge config file options and CLI/API options
let options = {...config, ...opts};
if (options.ci === false) {
options.noCi = true;
}
const pluginsPath = {};
let extendPaths;
({extends: extendPaths, ...options} = options);
@@ -34,17 +42,21 @@ module.exports = async (context, opts) => {
// 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.entries(extendsOpts).reduce((pluginsPath, [option, value]) => {
if (PLUGINS_DEFINITIONS[option] || option === 'plugins') {
castArray(value)
.filter(plugin => isString(plugin) || (isPlainObject(plugin) && isString(plugin.path)))
.map(plugin => (isString(plugin) ? plugin : plugin.path))
.forEach(plugin => {
pluginsPath[plugin] = extendPath;
});
}
return pluginsPath;
}, pluginsPath);
Object.entries(extendsOpts)
.filter(([, value]) => Boolean(value))
.reduce((pluginsPath, [option, value]) => {
castArray(value).forEach(plugin => {
if (option === 'plugins' && validatePlugin(plugin)) {
pluginsPath[parseConfig(plugin)[0]] = extendPath;
} else if (
PLUGINS_DEFINITIONS[option] &&
(isString(plugin) || (isPlainObject(plugin) && isString(plugin.path)))
) {
pluginsPath[isString(plugin) ? plugin : plugin.path] = extendPath;
}
});
return pluginsPath;
}, pluginsPath);
return {...result, ...extendsOpts};
}, {}),
+13 -12
View File
@@ -1,6 +1,5 @@
const {parse, format} = require('url');
const {parse, format} = require('url'); // eslint-disable-line node/no-deprecated-api
const {isNil} = require('lodash');
const gitUrlParse = require('git-url-parse');
const hostedGitInfo = require('hosted-git-info');
const {verifyAuth} = require('./git');
@@ -27,17 +26,14 @@ const GIT_TOKENS = {
*/
module.exports = async ({cwd, env, options: {repositoryUrl, branch}}) => {
const info = hostedGitInfo.fromUrl(repositoryUrl, {noGitPlus: true});
const {protocol, ...parsed} = parse(repositoryUrl);
if (info && info.getDefaultRepresentation() === 'shortcut') {
// Expand shorthand URLs (such as `owner/repo` or `gitlab:owner/repo`)
repositoryUrl = info.https();
} else {
const {protocols} = gitUrlParse(repositoryUrl);
} else if (protocol && protocol.includes('http')) {
// Replace `git+https` and `git+http` with `https` or `http`
if (protocols.includes('http') || protocols.includes('https')) {
repositoryUrl = format({...parse(repositoryUrl), protocol: protocols.includes('https') ? 'https' : 'http'});
}
repositoryUrl = format({...parsed, protocol: protocol.includes('https') ? 'https' : 'http', href: null});
}
// Test if push is allowed without transforming the URL (e.g. is ssh keys are set up)
@@ -46,11 +42,16 @@ module.exports = async ({cwd, env, options: {repositoryUrl, branch}}) => {
} catch (error) {
const envVar = Object.keys(GIT_TOKENS).find(envVar => !isNil(env[envVar]));
const gitCredentials = `${GIT_TOKENS[envVar] || ''}${env[envVar] || ''}`;
const {protocols, ...parsed} = gitUrlParse(repositoryUrl);
const protocol = protocols.includes('https') ? 'https' : protocols.includes('http') ? 'http' : 'https';
// If credentials are set via anvironment variables, convert the URL to http/https and add basic auth, otherwise return `repositoryUrl` as is
return gitCredentials ? {...parsed, protocols: [protocol], user: gitCredentials}.toString(protocol) : repositoryUrl;
if (gitCredentials) {
// If credentials are set via environment variables, convert the URL to http/https and add basic auth, otherwise return `repositoryUrl` as is
const [match, auth, host, path] = /^(?!.+:\/\/)(?:(.*)@)?(.*?):(.*)$/.exec(repositoryUrl) || [];
return format({
...parse(match ? `ssh://${auth ? `${auth}@` : ''}${host}/${path}` : repositoryUrl),
auth: gitCredentials,
protocol: protocol && /http[^s]/.test(protocol) ? 'http' : 'https',
});
}
}
return repositoryUrl;
+4 -4
View File
@@ -2,7 +2,7 @@ const {escapeRegExp, template} = require('lodash');
const semver = require('semver');
const pLocate = require('p-locate');
const debug = require('debug')('semantic-release:get-last-release');
const {gitTags, isRefInHistory, gitTagHead} = require('./git');
const {getTags, isRefInHistory, getTagHead} = require('./git');
/**
* Last release.
@@ -28,9 +28,9 @@ module.exports = async ({cwd, env, options: {tagFormat}, logger}) => {
// Generate a regex to parse tags formatted with `tagFormat`
// by replacing the `version` variable in the template by `(.+)`.
// The `tagFormat` is compiled with space as the `version` as it's an invalid tag character,
// so it's guaranteed to no be present in the `tagFormat`.
// so it's guaranteed to not be present in the `tagFormat`.
const tagRegexp = `^${escapeRegExp(template(tagFormat)({version: ' '})).replace(' ', '(.+)')}`;
const tags = (await gitTags({cwd, env}))
const tags = (await getTags({cwd, env}))
.map(tag => ({gitTag: tag, version: (tag.match(tagRegexp) || new Array(2))[1]}))
.filter(
tag => tag.version && semver.valid(semver.clean(tag.version)) && !semver.prerelease(semver.clean(tag.version))
@@ -43,7 +43,7 @@ module.exports = async ({cwd, env, options: {tagFormat}, logger}) => {
if (tag) {
logger.log(`Found git tag ${tag.gitTag} associated with version ${tag.version}`);
return {gitHead: await gitTagHead(tag.gitTag, {cwd, env}), ...tag};
return {gitHead: await getTagHead(tag.gitTag, {cwd, env}), ...tag};
}
logger.log('No git tag version found');
+1 -1
View File
@@ -3,7 +3,7 @@ const figures = require('figures');
module.exports = ({stdout, stderr}) =>
new Signale({
config: {displayTimestamp: true, underlineMessage: true, displayLabel: false},
config: {displayTimestamp: true, underlineMessage: false, displayLabel: false},
disabled: false,
interactive: false,
scope: 'semantic-release',
+17 -20
View File
@@ -4,12 +4,12 @@ const debug = require('debug')('semantic-release:git');
/**
* Get the commit sha for a given tag.
*
* @param {string} tagName Tag name for which to retrieve the commit sha.
* @param {String} tagName Tag name for which to retrieve the commit sha.
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @return {string} The commit sha of the tag in parameter or `null`.
*/
async function gitTagHead(tagName, execaOpts) {
async function getTagHead(tagName, execaOpts) {
try {
return await execa.stdout('git', ['rev-list', '-1', tagName], execaOpts);
} catch (error) {
@@ -25,20 +25,20 @@ async function gitTagHead(tagName, execaOpts) {
* @return {Array<String>} List of git tags.
* @throws {Error} If the `git` command fails.
*/
async function gitTags(execaOpts) {
async function getTags(execaOpts) {
return (await execa.stdout('git', ['tag'], execaOpts))
.split('\n')
.map(tag => tag.trim())
.filter(tag => Boolean(tag));
.filter(Boolean);
}
/**
* Verify if the `ref` is in the direct history of the current branch.
*
* @param {string} ref The reference to look for.
* @param {String} ref The reference to look for.
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @return {boolean} `true` if the reference is in the history of the current branch, falsy otherwise.
* @return {Boolean} `true` if the reference is in the history of the current branch, falsy otherwise.
*/
async function isRefInHistory(ref, execaOpts) {
try {
@@ -73,9 +73,9 @@ async function fetch(repositoryUrl, execaOpts) {
*
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @return {string} the sha of the HEAD commit.
* @return {String} the sha of the HEAD commit.
*/
function gitHead(execaOpts) {
function getGitHead(execaOpts) {
return execa.stdout('git', ['rev-parse', 'HEAD'], execaOpts);
}
@@ -143,22 +143,21 @@ async function tag(tagName, execaOpts) {
* Push to the remote repository.
*
* @param {String} repositoryUrl The remote repository URL.
* @param {String} branch The branch to push.
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @throws {Error} if the push failed.
*/
async function push(repositoryUrl, branch, execaOpts) {
await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`], execaOpts);
async function push(repositoryUrl, execaOpts) {
await execa('git', ['push', '--tags', repositoryUrl], execaOpts);
}
/**
* Verify a tag name is a valid Git reference.
*
* @param {string} tagName the tag name to verify.
* @param {String} tagName the tag name to verify.
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @return {boolean} `true` if valid, falsy otherwise.
* @return {Boolean} `true` if valid, falsy otherwise.
*/
async function verifyTagName(tagName, execaOpts) {
try {
@@ -177,22 +176,20 @@ async function verifyTagName(tagName, execaOpts) {
* @return {Boolean} `true` is the HEAD of the current local branch is the same as the HEAD of the remote branch, falsy otherwise.
*/
async function isBranchUpToDate(branch, execaOpts) {
const remoteHead = await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch], execaOpts);
try {
return await isRefInHistory(
(await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch], execaOpts)).match(/^(\w+)?/)[1],
execaOpts
);
return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts);
} catch (error) {
debug(error);
}
}
module.exports = {
gitTagHead,
gitTags,
getTagHead,
getTags,
isRefInHistory,
fetch,
gitHead,
getGitHead,
repoUrl,
isGitRepo,
verifyAuth,
+13 -10
View File
@@ -19,8 +19,12 @@ module.exports = (context, pluginsPath) => {
if (isPlainObject(plugin)) {
Object.entries(plugin).forEach(([type, func]) => {
if (PLUGINS_DEFINITIONS[type]) {
Reflect.defineProperty(func, 'pluginName', {value: 'Inline plugin', writable: false, enumerable: true});
plugins[type] = [...(PLUGINS_DEFINITIONS[type].multiple ? plugins[type] || [] : []), [func, config]];
Reflect.defineProperty(func, 'pluginName', {
value: isPlainObject(name) ? 'Inline plugin' : name,
writable: false,
enumerable: true,
});
plugins[type] = [...(plugins[type] || []), [func, config]];
}
});
} else {
@@ -41,10 +45,7 @@ module.exports = (context, pluginsPath) => {
options = {...plugins, ...options};
const pluginsConf = Object.entries(PLUGINS_DEFINITIONS).reduce(
(
pluginsConf,
[type, {multiple, required, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]
) => {
(pluginsConf, [type, {required, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]) => {
let pluginOpts;
if (isNil(options[type]) && def) {
@@ -52,14 +53,16 @@ module.exports = (context, pluginsPath) => {
} else {
// If an object is passed and the path is missing, merge it with step options
if (isPlainObject(options[type]) && !options[type].path) {
options[type] = castArray(plugins[type]).map(
plugin => (plugin ? [plugin[0], Object.assign(plugin[1], options[type])] : plugin)
options[type] = castArray(plugins[type]).map(plugin =>
plugin ? [plugin[0], Object.assign(plugin[1], options[type])] : plugin
);
}
if (!validateStep({multiple, required}, options[type])) {
errors.push(getError('EPLUGINCONF', {type, multiple, required, pluginConf: options[type]}));
if (!validateStep({required}, options[type])) {
errors.push(getError('EPLUGINCONF', {type, required, pluginConf: options[type]}));
return pluginsConf;
}
pluginOpts = options[type];
}
+20 -12
View File
@@ -1,4 +1,5 @@
const {isPlainObject, isFunction, noop, cloneDeep, omit} = require('lodash');
const debug = require('debug')('semantic-release:plugins');
const getError = require('../get-error');
const {extractErrors} = require('../utils');
const PLUGINS_DEFINITIONS = require('../definitions/plugins');
@@ -14,6 +15,8 @@ module.exports = (context, type, pluginOpt, pluginsPath) => {
const pluginName = name.pluginName ? name.pluginName : isFunction(name) ? `[Function: ${name.name}]` : name;
const plugin = loadPlugin(context, name, pluginsPath);
debug(`options for ${pluginName}/${type}: %O`, config);
let func;
if (isFunction(plugin)) {
func = plugin.bind(null, cloneDeep({...options, ...config}));
@@ -24,20 +27,25 @@ module.exports = (context, type, pluginOpt, pluginsPath) => {
}
const validator = async input => {
const {outputValidator} = PLUGINS_DEFINITIONS[type] || {};
const {dryRun, outputValidator} = PLUGINS_DEFINITIONS[type] || {};
try {
logger.log(`Start step "${type}" of plugin "${pluginName}"`);
const result = await func({
...cloneDeep(omit(input, ['stdout', 'stderr', 'logger'])),
stdout,
stderr,
logger: logger.scope(logger.scopeName, pluginName),
});
if (outputValidator && !outputValidator(result)) {
throw getError(`E${type.toUpperCase()}OUTPUT`, {result, pluginName});
if (!input.options.dryRun || dryRun) {
logger.log(`Start step "${type}" of plugin "${pluginName}"`);
const result = await func({
...cloneDeep(omit(input, ['stdout', 'stderr', 'logger'])),
stdout,
stderr,
logger: logger.scope(logger.scopeName, pluginName),
});
if (outputValidator && !outputValidator(result)) {
throw getError(`E${type.toUpperCase()}OUTPUT`, {result, pluginName});
}
logger.success(`Completed step "${type}" of plugin "${pluginName}"`);
return result;
}
logger.success(`Completed step "${type}" of plugin "${pluginName}"`);
return result;
logger.warn(`Skip step "${type}" of plugin "${pluginName}" in dry-run mode`);
} catch (error) {
logger.error(`Failed step "${type}" of plugin "${pluginName}"`);
extractErrors(error).forEach(err => Object.assign(err, {pluginName}));
+3 -1
View File
@@ -4,7 +4,7 @@ const AggregateError = require('aggregate-error');
const {extractErrors} = require('../utils');
/**
* A Function that execute a list of function sequencially. If at least one Function ins the pipeline throw an Error or rejects, the pipeline function rejects as well.
* A Function that execute a list of function sequencially. If at least one Function ins the pipeline throws an Error or rejects, the pipeline function rejects as well.
*
* @typedef {Function} Pipeline
* @param {Any} input Argument to pass to the first step in the pipeline.
@@ -44,6 +44,7 @@ module.exports = (steps, {settleAll = false, getNextInput = identity, transform
throw error;
}
}
// Prepare input for the next step, passing the input of the last iteration (or initial parameter for the first iteration) and the result of the current one
return getNextInput(lastInput, result);
},
@@ -52,5 +53,6 @@ module.exports = (steps, {settleAll = false, getNextInput = identity, transform
if (errors.length > 0) {
throw new AggregateError(errors);
}
return results;
};
+22 -22
View File
@@ -2,28 +2,26 @@ const {dirname} = require('path');
const {isString, isFunction, castArray, isArray, isPlainObject, isNil} = require('lodash');
const resolveFrom = require('resolve-from');
const validateStepArrayDefinition = conf =>
isArray(conf) &&
(conf.length === 1 || conf.length === 2) &&
(isString(conf[0]) || isFunction(conf[0])) &&
(isNil(conf[1]) || isPlainObject(conf[1]));
const validateSteps = conf => {
return conf.every(conf => {
if (
isArray(conf) &&
(conf.length === 1 || conf.length === 2) &&
(isString(conf[0]) || isFunction(conf[0])) &&
(isNil(conf[1]) || isPlainObject(conf[1]))
) {
return true;
}
const validateSingleStep = conf => {
if (validateStepArrayDefinition(conf)) {
return true;
}
conf = castArray(conf);
conf = castArray(conf);
if (conf.length !== 1) {
return false;
}
if (conf.length !== 1) {
return false;
}
const [name, config] = parseConfig(conf[0]);
return (isString(name) || isFunction(name)) && isPlainObject(config);
};
const validateMultipleStep = conf => {
return conf.every(conf => validateSingleStep(conf));
const [name, config] = parseConfig(conf[0]);
return (isString(name) || isFunction(name)) && isPlainObject(config);
});
};
function validatePlugin(conf) {
@@ -37,12 +35,13 @@ function validatePlugin(conf) {
);
}
function validateStep({multiple, required}, conf) {
function validateStep({required}, conf) {
conf = castArray(conf).filter(Boolean);
if (required) {
return conf.length >= 1 && (multiple ? validateMultipleStep : validateSingleStep)(conf);
return conf.length >= 1 && validateSteps(conf);
}
return conf.length === 0 || (multiple ? validateMultipleStep : validateSingleStep)(conf);
return conf.length === 0 || validateSteps(conf);
}
function loadPlugin({cwd}, name, pluginsPath) {
@@ -62,6 +61,7 @@ function parseConfig(plugin) {
} else {
path = plugin;
}
return [path, config || {}];
}
+11 -15
View File
@@ -23,32 +23,31 @@
"@semantic-release/error": "^2.2.0",
"@semantic-release/github": "^5.1.0",
"@semantic-release/npm": "^5.0.5",
"@semantic-release/release-notes-generator": "^7.1.0",
"aggregate-error": "^1.0.0",
"@semantic-release/release-notes-generator": "^7.1.2",
"aggregate-error": "^2.0.0",
"cosmiconfig": "^5.0.1",
"debug": "^4.0.0",
"env-ci": "^3.0.0",
"execa": "^1.0.0",
"figures": "^2.0.0",
"find-versions": "^2.0.0",
"find-versions": "^3.0.0",
"get-stream": "^4.0.0",
"git-log-parser": "^1.2.0",
"git-url-parse": "^10.0.1",
"hook-std": "^1.1.0",
"hosted-git-info": "^2.7.1",
"lodash": "^4.17.4",
"marked": "^0.5.0",
"marked-terminal": "^3.0.0",
"marked": "^0.6.0",
"marked-terminal": "^3.2.0",
"p-locate": "^3.0.0",
"p-reduce": "^1.0.0",
"read-pkg-up": "^4.0.0",
"resolve-from": "^4.0.0",
"semver": "^5.4.1",
"signale": "^1.2.1",
"yargs": "^12.0.0"
"yargs": "^13.1.0"
},
"devDependencies": {
"ava": "^0.25.0",
"ava": "^1.0.1",
"clear-module": "^3.0.0",
"codecov": "^3.0.0",
"commitizen": "^3.0.0",
@@ -61,13 +60,13 @@
"js-yaml": "^3.10.0",
"mockserver-client": "^5.1.1",
"nock": "^10.0.0",
"nyc": "^12.0.1",
"p-retry": "^2.0.0",
"nyc": "^13.1.0",
"p-retry": "^3.0.0",
"proxyquire": "^2.0.0",
"sinon": "^6.0.0",
"sinon": "^7.1.1",
"stream-buffers": "^3.0.2",
"tempy": "^0.2.1",
"xo": "^0.23.0"
"xo": "^0.24.0"
},
"engines": {
"node": ">=8.3"
@@ -113,9 +112,6 @@
"publishConfig": {
"tag": "next"
},
"release": {
"branch": "caribou"
},
"repository": {
"type": "git",
"url": "git+https://github.com/semantic-release/semantic-release.git"
+1 -13
View File
@@ -163,18 +163,6 @@ test.serial('Do not set properties in option for which arg is not in command lin
t.false('e' in run.args[0][0]);
});
test.serial('Set "noCi" options to "true" with "--no-ci"', async t => {
const run = stub().resolves(true);
const argv = ['', '', '--no-ci'];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
t.is(run.args[0][0].noCi, true);
t.is(exitCode, 0);
});
test.serial('Display help', async t => {
const run = stub().resolves(true);
const argv = ['', '', '--help'];
@@ -186,7 +174,7 @@ test.serial('Display help', async t => {
t.is(exitCode, 0);
});
test.serial('Returns error code and prints help if called with a command', async t => {
test.serial('Return error code and prints help if called with a command', async t => {
const run = stub().resolves(true);
const argv = ['', '', 'pre'];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
+12 -1
View File
@@ -22,7 +22,7 @@ test('The "generateNotes" plugin output, if defined, must be a string', t => {
t.true(plugins.generateNotes.outputValidator('string'));
});
test('The "publish" plugin output, if defined, must be an object', t => {
test('The "publish" plugin output, if defined, must be an object or "false"', t => {
t.false(plugins.publish.outputValidator(1));
t.false(plugins.publish.outputValidator('string'));
@@ -30,6 +30,7 @@ test('The "publish" plugin output, if defined, must be an object', t => {
t.true(plugins.publish.outputValidator());
t.true(plugins.publish.outputValidator(null));
t.true(plugins.publish.outputValidator(''));
t.true(plugins.publish.outputValidator(false));
});
test('The "generateNotes" plugins output are concatenated with separator and sensitive data is hidden', t => {
@@ -51,3 +52,13 @@ test('The "generateNotes" plugins output are concatenated with separator and sen
`Note 1: Exposing token ${SECRET_REPLACEMENT}${RELEASE_NOTES_SEPARATOR}Note 2: Exposing token ${SECRET_REPLACEMENT}`
);
});
test('The "analyzeCommits" plugins output are reduced to the highest release type', t => {
t.is(plugins.analyzeCommits.postprocess(['major', 'minor']), 'major');
t.is(plugins.analyzeCommits.postprocess(['', 'minor']), 'minor');
t.is(plugins.analyzeCommits.postprocess([undefined, 'patch']), 'patch');
t.is(plugins.analyzeCommits.postprocess([null, 'patch']), 'patch');
t.is(plugins.analyzeCommits.postprocess(['wrong_type', 'minor']), 'minor');
t.is(plugins.analyzeCommits.postprocess([]), undefined);
t.is(plugins.analyzeCommits.postprocess(['wrong_type']), undefined);
});
+16 -2
View File
@@ -67,6 +67,18 @@ test('Default values, reading repositoryUrl (http url) from package.json if not
t.is(result.tagFormat, `v\${version}`);
});
test('Convert "ci" option to "noCi"', async t => {
const pkg = {repository: 'https://host.null/owner/module.git', release: {ci: false}};
// Create a git repository, set the current working directory at the root of the repo
const {cwd} = await gitRepo();
// Create package.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), pkg);
const {options: result} = await t.context.getConfig({cwd});
t.is(result.noCi, true);
});
test('Read options from package.json', async t => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd} = await gitRepo();
@@ -212,7 +224,7 @@ test('Read configuration from file path in "extends"', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: false,
plugins: ['plugin-1', ['plugin-2', {plugin2Opt: 'value'}]],
};
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
@@ -227,6 +239,8 @@ test('Read configuration from file path in "extends"', async t => {
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: './shareable.json',
generateNotes: './shareable.json',
'plugin-1': './shareable.json',
'plugin-2': './shareable.json',
});
});
@@ -466,7 +480,7 @@ test('Throw an Error if one of the shareable config cannot be found', async t =>
await outputJson(path.resolve(cwd, 'package.json'), {release: pkhOptions});
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
const error = await t.throws(t.context.getConfig({cwd}), Error);
const error = await t.throwsAsync(t.context.getConfig({cwd}), Error);
t.is(error.message, "Cannot find module 'non-existing-path'");
t.is(error.code, 'MODULE_NOT_FOUND');
+13
View File
@@ -101,6 +101,19 @@ test('Return the "https" formatted URL if "gitCredentials" is defined and reposi
);
});
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL without user', async t => {
const {cwd} = await gitRepo();
t.is(
await getAuthUrl({
cwd,
env: {...env, GIT_CREDENTIALS: 'user:pass'},
options: {branch: 'master', repositoryUrl: 'host.null:owner/repo.git'},
}),
'https://user:pass@host.null/owner/repo.git'
);
});
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "https" URL', async t => {
const {cwd} = await gitRepo();
+32 -19
View File
@@ -1,14 +1,14 @@
import test from 'ava';
import tempy from 'tempy';
import {
gitTagHead,
getTagHead,
isRefInHistory,
fetch,
gitHead,
getGitHead,
repoUrl,
tag,
push,
gitTags,
getTags,
isGitRepo,
verifyTagName,
isBranchUpToDate,
@@ -33,7 +33,7 @@ test('Get the last commit sha', async t => {
// Add commits to the master branch
const commits = await gitCommits(['First'], {cwd});
const result = await gitHead({cwd});
const result = await getGitHead({cwd});
t.is(result, commits[0].hash);
});
@@ -42,7 +42,7 @@ test('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
const {cwd} = await gitRepo();
await t.throws(gitHead({cwd}), Error);
await t.throwsAsync(getGitHead({cwd}), Error);
});
test('Unshallow and fetch repository', async t => {
@@ -67,7 +67,7 @@ test('Do not throw error when unshallow a complete repository', async t => {
const {cwd, repositoryUrl} = await gitRepo();
// Add commits to the master branch
await gitCommits(['First'], {cwd});
await t.notThrows(fetch(repositoryUrl, {cwd}));
await t.notThrowsAsync(fetch(repositoryUrl, {cwd}));
});
test('Fetch all tags on a detached head repository', async t => {
@@ -84,7 +84,7 @@ test('Fetch all tags on a detached head repository', async t => {
await fetch(repositoryUrl, {cwd});
t.deepEqual((await gitTags({cwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0'].sort());
t.deepEqual((await getTags({cwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0'].sort());
});
test('Verify if the commit `sha` is in the direct history of the current branch', async t => {
@@ -100,7 +100,7 @@ test('Verify if the commit `sha` is in the direct history of the current branch'
t.true(await isRefInHistory(commits[0].hash, {cwd}));
t.falsy(await isRefInHistory(otherCommits[0].hash, {cwd}));
await t.throws(isRefInHistory('non-existant-sha', {cwd}));
await t.throwsAsync(isRefInHistory('non-existant-sha', {cwd}));
});
test('Get the commit sha for a given tag or falsy if the tag does not exists', async t => {
@@ -111,8 +111,8 @@ test('Get the commit sha for a given tag or falsy if the tag does not exists', a
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0', undefined, {cwd});
t.is(await gitTagHead('v1.0.0', {cwd}), commits[0].hash);
t.falsy(await gitTagHead('missing_tag', {cwd}));
t.is(await getTagHead('v1.0.0', {cwd}), commits[0].hash);
t.falsy(await getTagHead('missing_tag', {cwd}));
});
test('Return git remote repository url from config', async t => {
@@ -151,13 +151,27 @@ test('Add tag on head commit', async t => {
await t.is(await gitCommitTag(commits[0].hash, {cwd}), 'tag_name');
});
test('Push tag and commit to remote repository', async t => {
test('Push tag to remote repository', async t => {
// Create a git repository with a remote, set the current working directory at the root of the repo
const {cwd, repositoryUrl} = await gitRepo(true);
const commits = await gitCommits(['Test commit'], {cwd});
await tag('tag_name', {cwd});
await push(repositoryUrl, 'master', {cwd});
await push(repositoryUrl, {cwd});
t.is(await gitRemoteTagHead(repositoryUrl, 'tag_name', {cwd}), commits[0].hash);
});
test('Push tag to remote repository with remote branch ahaed', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const commits = await gitCommits(['First'], {cwd});
await gitPush(repositoryUrl, 'master', {cwd});
const tmpRepo = await gitShallowClone(repositoryUrl);
await gitCommits(['Second'], {cwd: tmpRepo});
await gitPush('origin', 'master', {cwd: tmpRepo});
await tag('tag_name', {cwd});
await push(repositoryUrl, {cwd});
t.is(await gitRemoteTagHead(repositoryUrl, 'tag_name', {cwd}), commits[0].hash);
});
@@ -192,7 +206,7 @@ test('Return falsy for invalid tag names', async t => {
test('Throws error if obtaining the tags fails', async t => {
const cwd = tempy.directory();
await t.throws(gitTags({cwd}));
await t.throwsAsync(getTags({cwd}));
});
test('Return "true" if repository is up to date', async t => {
@@ -204,19 +218,18 @@ test('Return "true" if repository is up to date', async t => {
});
test('Return falsy if repository is not up to date', async t => {
let {cwd, repositoryUrl} = await gitRepo(true);
const repoDir = cwd;
const {cwd, repositoryUrl} = await gitRepo(true);
await gitCommits(['First'], {cwd});
await gitCommits(['Second'], {cwd});
await gitPush(repositoryUrl, 'master', {cwd});
t.true(await isBranchUpToDate('master', {cwd}));
cwd = await gitShallowClone(repositoryUrl);
await gitCommits(['Third'], {cwd});
await gitPush('origin', 'master', {cwd});
const tmpRepo = await gitShallowClone(repositoryUrl);
await gitCommits(['Third'], {cwd: tmpRepo});
await gitPush('origin', 'master', {cwd: tmpRepo});
t.falsy(await isBranchUpToDate('master', {cwd: repoDir}));
t.falsy(await isBranchUpToDate('master', {cwd}));
});
test('Return "true" if local repository is ahead', async t => {
+1 -1
View File
@@ -26,7 +26,7 @@ import getStream from 'get-stream';
export async function gitRepo(withRemote, branch = 'master') {
let cwd = tempy.directory();
await execa('git', ['init'].concat(withRemote ? ['--bare'] : []), {cwd});
await execa('git', ['init', ...(withRemote ? ['--bare'] : [])], {cwd});
const repositoryUrl = fileUrl(cwd);
if (withRemote) {
-16
View File
@@ -1,16 +0,0 @@
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}`}});
}
+40 -30
View File
@@ -1,5 +1,5 @@
import test from 'ava';
import {escapeRegExp, isString} from 'lodash';
import {escapeRegExp, isString, sortBy} from 'lodash';
import proxyquire from 'proxyquire';
import {spy, stub} from 'sinon';
import {WritableStreamBuffer} from 'stream-buffers';
@@ -25,10 +25,12 @@ test.beforeEach(t => {
t.context.log = spy();
t.context.error = spy();
t.context.success = spy();
t.context.warn = spy();
t.context.logger = {
log: t.context.log,
error: t.context.error,
success: t.context.success,
warn: t.context.warn,
scope: () => t.context.logger,
};
});
@@ -335,7 +337,7 @@ test('Call all "success" plugins even if one errors out', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await t.throws(
await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
);
@@ -370,18 +372,15 @@ test('Log all "verifyConditions" errors', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const errors = [
...(await t.throws(
...(await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
)),
];
t.deepEqual(errors, [error1, error2, error3]);
t.deepEqual(t.context.error.args[t.context.error.args.length - 2], ['ERR2 error 2']);
t.deepEqual(t.context.error.args[t.context.error.args.length - 1], ['ERR3 error 3']);
t.deepEqual(t.context.error.args[t.context.error.args.length - 3], [
'An error occurred while running semantic-release: %O',
error1,
]);
t.deepEqual(sortBy(errors, ['message']), sortBy([error1, error2, error3], ['message']));
t.true(t.context.error.calledWith('An error occurred while running semantic-release: %O', error1));
t.true(t.context.error.calledWith('ERR2 error 2'));
t.true(t.context.error.calledWith('ERR3 error 3'));
t.true(t.context.error.calledAfter(t.context.log));
t.is(fail.callCount, 1);
t.deepEqual(fail.args[0][0], config);
@@ -418,20 +417,20 @@ test('Log all "verifyRelease" errors', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const errors = [
...(await t.throws(
...(await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
)),
];
t.deepEqual(errors, [error1, error2]);
t.deepEqual(t.context.error.args[t.context.error.args.length - 2], ['ERR1 error 1']);
t.deepEqual(t.context.error.args[t.context.error.args.length - 1], ['ERR2 error 2']);
t.deepEqual(sortBy(errors, ['message']), sortBy([error1, error2], ['message']));
t.true(t.context.error.calledWith('ERR1 error 1'));
t.true(t.context.error.calledWith('ERR2 error 2'));
t.is(fail.callCount, 1);
t.deepEqual(fail.args[0][0], config);
t.deepEqual(fail.args[0][1].errors, [error1, error2]);
});
test('Dry-run skips publish and success', async t => {
test('Dry-run skips prepare, publish and success', async t => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd, repositoryUrl} = await gitRepo(true);
// Add commits to the master branch
@@ -449,6 +448,7 @@ test('Dry-run skips publish and success', async t => {
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves(notes);
const prepare = stub().resolves();
const publish = stub().resolves();
const success = stub().resolves();
@@ -460,7 +460,7 @@ test('Dry-run skips publish and success', async t => {
analyzeCommits,
verifyRelease,
generateNotes,
prepare: stub().resolves(),
prepare,
publish,
success,
};
@@ -478,13 +478,17 @@ test('Dry-run skips publish and success', async t => {
})
);
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.warn.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(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 1);
t.is(generateNotes.callCount, 1);
t.is(prepare.callCount, 0);
t.true(t.context.warn.calledWith(`Skip step "prepare" of plugin "[Function: ${prepare.name}]" in dry-run mode`));
t.is(publish.callCount, 0);
t.true(t.context.warn.calledWith(`Skip step "publish" of plugin "[Function: ${publish.name}]" in dry-run mode`));
t.is(success.callCount, 0);
t.true(t.context.warn.calledWith(`Skip step "success" of plugin "[Function: ${success.name}]" in dry-run mode`));
});
test('Dry-run skips fail', async t => {
@@ -515,15 +519,16 @@ test('Dry-run skips fail', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const errors = [
...(await t.throws(
...(await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
)),
];
t.deepEqual(errors, [error1, error2]);
t.deepEqual(t.context.error.args[t.context.error.args.length - 2], ['ERR1 error 1']);
t.deepEqual(t.context.error.args[t.context.error.args.length - 1], ['ERR2 error 2']);
t.deepEqual(sortBy(errors, ['message']), sortBy([error1, error2], ['message']));
t.true(t.context.error.calledWith('ERR1 error 1'));
t.true(t.context.error.calledWith('ERR2 error 2'));
t.is(fail.callCount, 0);
t.true(t.context.warn.calledWith(`Skip step "fail" of plugin "[Function: ${fail.name}]" in dry-run mode`));
});
test('Force a dry-run if not on a CI and "noCi" is not explicitly set', async t => {
@@ -574,7 +579,7 @@ test('Force a dry-run if not on a CI and "noCi" is not explicitly set', async t
})
);
t.is(t.context.log.args[1][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
t.true(t.context.warn.calledWith('This run was not triggered in a known CI environment, running in dry-run mode.'));
t.is(verifyConditions.callCount, 1);
t.is(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 1);
@@ -688,7 +693,7 @@ test('Allow local releases with "noCi" option', async t => {
t.is(success.callCount, 1);
});
test('Accept "undefined" value returned by the "generateNotes" plugins', async t => {
test('Accept "undefined" value returned by "generateNotes" and "false" by "publish"', async t => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd, repositoryUrl} = await gitRepo(true);
// Add commits to the master branch
@@ -706,7 +711,8 @@ test('Accept "undefined" value returned by the "generateNotes" plugins', async t
const generateNotes1 = stub().resolves();
const notes2 = 'Release notes 2';
const generateNotes2 = stub().resolves(notes2);
const publish = stub().resolves();
const publish = stub().resolves(false);
const success = stub().resolves();
const options = {
branch: 'master',
@@ -717,7 +723,7 @@ test('Accept "undefined" value returned by the "generateNotes" plugins', async t
generateNotes: [generateNotes1, generateNotes2],
prepare: stub().resolves(),
publish,
success: stub().resolves(),
success,
fail: stub().resolves(),
};
@@ -749,6 +755,9 @@ test('Accept "undefined" value returned by the "generateNotes" plugins', async t
t.is(publish.callCount, 1);
t.deepEqual(publish.args[0][1].lastRelease, lastRelease);
t.is(publish.args[0][1].nextRelease.notes, notes2);
t.is(success.callCount, 1);
t.deepEqual(success.args[0][1].releases, [{pluginName: '[Function: proxy]'}]);
});
test('Returns false if triggered by a PR', async t => {
@@ -948,7 +957,7 @@ test('Log both plugins errors and errors thrown by "fail" plugin', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await t.throws(
await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
);
@@ -973,7 +982,7 @@ test('Call "fail" only if a plugin returns a SemanticReleaseError', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await t.throws(
await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
);
@@ -990,7 +999,7 @@ test('Throw SemanticReleaseError if repositoryUrl is not set and cannot be found
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const errors = [
...(await t.throws(
...(await t.throwsAsync(
semanticRelease({}, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
)),
];
@@ -1027,7 +1036,7 @@ test('Throw an Error if plugin returns an unexpected value', async t => {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const error = await t.throws(
const error = await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()}),
Error
);
@@ -1057,7 +1066,7 @@ test('Hide sensitive information passed to "fail" plugin', async t => {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await t.throws(
await t.throwsAsync(
semanticRelease(options, {cwd, env, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()}),
Error
);
@@ -1089,6 +1098,7 @@ test('Hide sensitive information passed to "success" plugin', async t => {
verifyConditions: false,
verifyRelease: false,
prepare: false,
generateNotes: stub().resolves(`Exposing token ${env.MY_TOKEN}`),
publish: stub().resolves({
name: `Name: Exposing token ${env.MY_TOKEN}`,
url: `URL: Exposing token ${env.MY_TOKEN}`,
+39 -39
View File
@@ -6,7 +6,7 @@ import {writeJson, readJson} from 'fs-extra';
import execa from 'execa';
import {WritableStreamBuffer} from 'stream-buffers';
import {SECRET_REPLACEMENT} from '../lib/definitions/constants';
import {gitHead as getGitHead, gitTagHead, gitRepo, gitCommits, gitRemoteTagHead, gitPush} from './helpers/git-utils';
import {gitHead, gitTagHead, gitRepo, gitCommits, gitRemoteTagHead, gitPush} from './helpers/git-utils';
import gitbox from './helpers/gitbox';
import mockServer from './helpers/mockserver';
import npmRegistry from './helpers/npm-registry';
@@ -108,12 +108,12 @@ test('Release patch, minor and major versions', async t => {
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
let gitHead = await getGitHead({cwd});
let head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -150,12 +150,12 @@ test('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
gitHead = await getGitHead({cwd});
head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -192,12 +192,12 @@ test('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
gitHead = await getGitHead({cwd});
head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -234,12 +234,12 @@ test('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
gitHead = await getGitHead({cwd});
head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -258,7 +258,7 @@ test('Exit with 1 if a plugin is not found', async t => {
release: {analyzeCommits: 'non-existing-path', success: false, fail: false},
});
const {code, stderr} = await t.throws(execa(cli, [], {env, cwd}));
const {code, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
@@ -276,7 +276,7 @@ test('Exit with 1 if a shareable config is not found', async t => {
release: {extends: 'non-existing-path', success: false, fail: false},
});
const {code, stderr} = await t.throws(execa(cli, [], {env, cwd}));
const {code, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
@@ -297,7 +297,7 @@ test('Exit with 1 if a shareable config reference a not found plugin', async t =
});
await writeJson(path.resolve(cwd, 'shareable.json'), shareable);
const {code, stderr} = await t.throws(execa(cli, [], {env, cwd}));
const {code, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
@@ -388,12 +388,12 @@ test('Allow local releases with "noCi" option', async t => {
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
const gitHead = await getGitHead({cwd});
const head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -442,12 +442,12 @@ test('Pass options via CLI arguments', async t => {
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
const gitHead = await getGitHead({cwd});
const head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
});
test('Run via JS API', async t => {
@@ -500,12 +500,12 @@ test('Run via JS API', async t => {
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
const gitHead = await getGitHead({cwd});
const head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
+11 -11
View File
@@ -62,7 +62,7 @@ test('Wrap plugin in a function that add the "pluginName" to the error"', async
'./plugin-error': './test/fixtures',
});
const error = await t.throws(plugin());
const error = await t.throwsAsync(plugin({options: {}}));
t.is(error.pluginName, './plugin-error');
});
@@ -72,7 +72,7 @@ test('Wrap plugin in a function that add the "pluginName" to multiple errors"',
'./plugin-errors': './test/fixtures',
});
const errors = [...(await t.throws(plugin()))];
const errors = [...(await t.throwsAsync(plugin({options: {}})))];
for (const error of errors) {
t.is(error.pluginName, './plugin-errors');
}
@@ -107,7 +107,7 @@ test('Wrap "analyzeCommits" plugin in a function that validate the output of the
{}
);
const error = await t.throws(plugin());
const error = await t.throwsAsync(plugin({options: {}}));
t.is(error.code, 'EANALYZECOMMITSOUTPUT');
t.is(error.name, 'SemanticReleaseError');
@@ -125,7 +125,7 @@ test('Wrap "generateNotes" plugin in a function that validate the output of the
{}
);
const error = await t.throws(plugin());
const error = await t.throwsAsync(plugin({options: {}}));
t.is(error.code, 'EGENERATENOTESOUTPUT');
t.is(error.name, 'SemanticReleaseError');
@@ -143,7 +143,7 @@ test('Wrap "publish" plugin in a function that validate the output of the plugin
{}
);
const error = await t.throws(plugin());
const error = await t.throwsAsync(plugin({options: {}}));
t.is(error.code, 'EPUBLISHOUTPUT');
t.is(error.name, 'SemanticReleaseError');
@@ -157,7 +157,7 @@ test('Plugin is called with "pluginConfig" (with object definition) and input',
const pluginConf = {path: pluginFunction, conf: 'confValue'};
const options = {global: 'globalValue'};
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin({param: 'param'});
await plugin({options: {}, param: 'param'});
t.true(
pluginFunction.calledWithMatch(
@@ -172,7 +172,7 @@ test('Plugin is called with "pluginConfig" (with array definition) and input', a
const pluginConf = [pluginFunction, {conf: 'confValue'}];
const options = {global: 'globalValue'};
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin({param: 'param'});
await plugin({options: {}, param: 'param'});
t.true(
pluginFunction.calledWithMatch(
@@ -189,7 +189,7 @@ test('Prevent plugins to modify "pluginConfig"', async t => {
const pluginConf = {path: pluginFunction, conf: {subConf: 'originalConf'}};
const options = {globalConf: {globalSubConf: 'originalGlobalConf'}};
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin();
await plugin({options: {}});
t.is(pluginConf.conf.subConf, 'originalConf');
t.is(options.globalConf.globalSubConf, 'originalGlobalConf');
@@ -199,7 +199,7 @@ 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 input = {param: {subParam: 'originalSubParam'}, options: {}};
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, '', pluginFunction, {});
await plugin(input);
@@ -220,7 +220,7 @@ test('Always pass a defined "pluginConfig" for plugin defined with string', asyn
'./test/fixtures/plugin-result-config',
{}
);
const pluginResult = await plugin();
const pluginResult = await plugin({options: {}});
t.deepEqual(pluginResult.pluginConfig, {});
});
@@ -233,7 +233,7 @@ test('Always pass a defined "pluginConfig" for plugin defined with path', async
{path: './test/fixtures/plugin-result-config'},
{}
);
const pluginResult = await plugin();
const pluginResult = await plugin({options: {}});
t.deepEqual(pluginResult.pluginConfig, {});
});
+5 -5
View File
@@ -83,7 +83,7 @@ test('Stop execution and throw error if a step rejects', async t => {
const step2 = stub().rejects(new Error('test error'));
const step3 = stub().resolves(3);
const error = await t.throws(pipeline([step1, step2, step3])(0), Error);
const error = await t.throwsAsync(pipeline([step1, step2, step3])(0), Error);
t.is(error.message, 'test error');
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
@@ -98,7 +98,7 @@ test('Throw all errors from the first step throwing an AggregateError', async t
const step2 = stub().rejects(new AggregateError([error1, error2]));
const step3 = stub().resolves(3);
const errors = await t.throws(pipeline([step1, step2, step3])(0));
const errors = await t.throwsAsync(pipeline([step1, step2, step3])(0));
t.deepEqual([...errors], [error1, error2]);
t.true(step1.calledWith(0));
@@ -113,7 +113,7 @@ test('Execute all even if a Promise rejects', async t => {
const step2 = stub().rejects(error1);
const step3 = stub().rejects(error2);
const errors = await t.throws(pipeline([step1, step2, step3], {settleAll: true})(0));
const errors = await t.throwsAsync(pipeline([step1, step2, step3], {settleAll: true})(0));
t.deepEqual([...errors], [error1, error2]);
t.true(step1.calledWith(0));
@@ -129,7 +129,7 @@ test('Throw all errors from all steps throwing an AggregateError', async t => {
const step1 = stub().rejects(new AggregateError([error1, error2]));
const step2 = stub().rejects(new AggregateError([error3, error4]));
const errors = await t.throws(pipeline([step1, step2], {settleAll: true})(0));
const errors = await t.throwsAsync(pipeline([step1, step2], {settleAll: true})(0));
t.deepEqual([...errors], [error1, error2, error3, error4]);
t.true(step1.calledWith(0));
@@ -145,7 +145,7 @@ test('Execute each function in series passing a transformed input even if a step
const step4 = stub().resolves(4);
const getNextInput = (prevResult, result) => prevResult + result;
const errors = await t.throws(pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput})(0));
const errors = await t.throwsAsync(pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput})(0));
t.deepEqual([...errors], [error2, error3]);
t.true(step1.calledWith(0));
+9 -29
View File
@@ -63,14 +63,14 @@ test('Export plugins based on "plugins" config (array)', async t => {
{}
);
await plugins.verifyConditions({});
await plugins.verifyConditions({options: {}});
t.true(plugin1.verifyConditions.calledOnce);
t.true(plugin2.verifyConditions.calledOnce);
await plugins.publish({});
await plugins.publish({options: {}});
t.true(plugin1.publish.calledOnce);
await plugins.verifyRelease({});
await plugins.verifyRelease({options: {}});
t.true(plugin2.verifyRelease.notCalled);
// Verify the module returns a function for each plugin
@@ -88,10 +88,10 @@ test('Export plugins based on "plugins" config (single definition)', async t =>
const plugin1 = {verifyConditions: stub(), publish: stub()};
const plugins = getPlugins({cwd, logger: t.context.logger, options: {plugins: plugin1}}, {});
await plugins.verifyConditions({});
await plugins.verifyConditions({options: {}});
t.true(plugin1.verifyConditions.calledOnce);
await plugins.publish({});
await plugins.publish({options: {}});
t.true(plugin1.publish.calledOnce);
// Verify the module returns a function for each plugin
@@ -105,26 +105,6 @@ test('Export plugins based on "plugins" config (single definition)', async t =>
t.is(typeof plugins.fail, 'function');
});
test('Use only last definition of single plugin steps declared in "plugins" config', async t => {
const plugin1 = {analyzeCommits: stub()};
const plugin2 = {analyzeCommits: stub()};
const plugins = getPlugins({cwd, logger: t.context.logger, options: {plugins: [plugin1, plugin2]}}, {});
await plugins.analyzeCommits({commits: []});
t.true(plugin1.analyzeCommits.notCalled);
t.true(plugin2.analyzeCommits.calledOnce);
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.prepare, 'function');
t.is(typeof plugins.publish, 'function');
t.is(typeof plugins.success, 'function');
t.is(typeof plugins.fail, 'function');
});
test('Merge global options, "plugins" options and step options', async t => {
const plugin1 = [{verifyConditions: stub(), publish: stub()}, {pluginOpt1: 'plugin1'}];
const plugin2 = [{verifyConditions: stub()}, {pluginOpt2: 'plugin2'}];
@@ -138,14 +118,14 @@ test('Merge global options, "plugins" options and step options', async t => {
{}
);
await plugins.verifyConditions({});
await plugins.verifyConditions({options: {}});
t.deepEqual(plugin1[0].verifyConditions.args[0][0], {globalOpt: 'global', pluginOpt1: 'plugin1'});
t.deepEqual(plugin2[0].verifyConditions.args[0][0], {globalOpt: 'global', pluginOpt2: 'plugin2'});
await plugins.publish({});
await plugins.publish({options: {}});
t.deepEqual(plugin1[0].publish.args[0][0], {globalOpt: 'global', pluginOpt1: 'plugin1'});
await plugins.verifyRelease({});
await plugins.verifyRelease({options: {}});
t.deepEqual(plugin3[0].args[0][0], {globalOpt: 'global', pluginOpt3: 'plugin3'});
});
@@ -268,7 +248,7 @@ test('Merge global options with plugin options', async t => {
{}
);
const [result] = await plugins.verifyRelease();
const [result] = await plugins.verifyRelease({options: {}});
t.deepEqual(result.pluginConfig, {localOpt: 'local', globalOpt: 'global', otherOpt: 'locally-defined'});
});
+3 -95
View File
@@ -25,7 +25,7 @@ test('validatePlugin', t => {
t.false(validatePlugin({path: 1}), 'Object definition, wrong path');
});
test('validateStep: multiple/optional plugin configuration', t => {
test('validateStep: optional plugin configuration', t => {
const type = {multiple: true, required: false};
// Empty config
@@ -107,8 +107,8 @@ test('validateStep: multiple/optional plugin configuration', t => {
);
});
test('validateStep: multiple/required plugin configuration', t => {
const type = {multiple: true, required: true};
test('validateStep: required plugin configuration', t => {
const type = {required: true};
// Empty config
t.false(validateStep(type));
@@ -189,98 +189,6 @@ test('validateStep: multiple/required plugin configuration', t => {
);
});
test('validateStep: single/required plugin configuration', t => {
const type = {multiple: false, required: true};
// Empty config
t.false(validateStep(type));
t.false(validateStep(type, []));
// Single value definition
t.true(validateStep(type, 'plugin-path.js'));
t.true(validateStep(type, () => {}));
t.true(validateStep(type, ['plugin-path.js']));
t.true(validateStep(type, [() => {}]));
t.false(validateStep(type, {}));
t.false(validateStep(type, [{}]));
// Array type definition
t.true(validateStep(type, [['plugin-path.js']]));
t.true(validateStep(type, [['plugin-path.js', {options: 'value'}]]));
t.true(validateStep(type, [[() => {}, {options: 'value'}]]));
t.false(validateStep(type, [['plugin-path.js', 1]]));
// Object type definition
t.true(validateStep(type, {path: 'plugin-path.js'}));
t.true(validateStep(type, {path: 'plugin-path.js', options: 'value'}));
t.true(validateStep(type, {path: () => {}, options: 'value'}));
t.false(validateStep(type, {path: null}));
// Considered as one Array definition and not as an Array of 2 definitions in case of single plugin type
t.true(validateStep(type, [() => {}, {options: 'value'}]));
t.true(validateStep(type, ['plugin-path.js', {options: 'value'}]));
// Multiple definitions
t.false(
validateStep(type, [
'plugin-path.js',
() => {},
['plugin-path.js'],
['plugin-path.js', {options: 'value'}],
[() => {}, {options: 'value'}],
{path: 'plugin-path.js'},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
});
test('validateStep: single/optional plugin configuration', t => {
const type = {multiple: false, required: false};
// Empty config
t.true(validateStep(type));
t.true(validateStep(type, []));
// Single value definition
t.true(validateStep(type, 'plugin-path.js'));
t.true(validateStep(type, () => {}));
t.true(validateStep(type, ['plugin-path.js']));
t.true(validateStep(type, [() => {}]));
t.false(validateStep(type, {}));
t.false(validateStep(type, [{}]));
// Array type definition
t.true(validateStep(type, [['plugin-path.js']]));
t.true(validateStep(type, [['plugin-path.js', {options: 'value'}]]));
t.true(validateStep(type, [[() => {}, {options: 'value'}]]));
t.false(validateStep(type, [['plugin-path.js', 1]]));
// Object type definition
t.true(validateStep(type, {path: 'plugin-path.js'}));
t.true(validateStep(type, {path: 'plugin-path.js', options: 'value'}));
t.true(validateStep(type, {path: () => {}, options: 'value'}));
t.false(validateStep(type, {path: null}));
// Considered as one Array definition and not as an Array of 2 definitions in case of single plugin type
t.true(validateStep(type, [() => {}, {options: 'value'}]));
t.true(validateStep(type, ['plugin-path.js', {options: 'value'}]));
// Multiple definitions
t.false(
validateStep(type, [
'plugin-path.js',
() => {},
['plugin-path.js'],
['plugin-path.js', {options: 'value'}],
[() => {}, {options: 'value'}],
{path: 'plugin-path.js'},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
});
test('loadPlugin', t => {
const cwd = process.cwd();
const func = () => {};
+20 -6
View File
@@ -7,59 +7,73 @@ test('Throw a AggregateError', async t => {
const {cwd} = await gitRepo();
const options = {};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ENOREPOURL');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
t.is(errors[1].name, 'SemanticReleaseError');
t.is(errors[1].code, 'EINVALIDTAGFORMAT');
t.truthy(errors[1].message);
t.truthy(errors[1].details);
t.is(errors[2].name, 'SemanticReleaseError');
t.is(errors[2].code, 'ETAGNOVERSION');
t.truthy(errors[2].message);
t.truthy(errors[2].details);
});
test('Throw a SemanticReleaseError if does not run on a git repository', async t => {
const cwd = tempy.directory();
const options = {};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ENOGITREPO');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
});
test('Throw a SemanticReleaseError if the "tagFormat" is not valid', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `?\${version}`};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EINVALIDTAGFORMAT');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
});
test('Throw a SemanticReleaseError if the "tagFormat" does not contains the "version" variable', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const options = {repositoryUrl, tagFormat: 'test'};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ETAGNOVERSION');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
});
test('Throw a SemanticReleaseError if the "tagFormat" contains multiple "version" variables', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `\${version}v\${version}`};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ETAGNOVERSION');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
});
test('Return "true" if all verification pass', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `v\${version}`};
await t.notThrows(verify({cwd, options}));
await t.notThrowsAsync(verify({cwd, options}));
});