Compare commits
264
Commits
@@ -0,0 +1 @@
|
||||
* text=auto eol=lf
|
||||
@@ -1 +0,0 @@
|
||||
base: app0ZOxG0FnHmOiuU
|
||||
@@ -131,3 +131,6 @@ yarn.lock
|
||||
|
||||
# Gitbook
|
||||
_book
|
||||
|
||||
# Mockserver
|
||||
CertificateAuthorityCertificate.pem
|
||||
|
||||
+7
-28
@@ -1,32 +1,11 @@
|
||||
language: node_js
|
||||
version: ~> 1.0
|
||||
|
||||
services:
|
||||
- docker
|
||||
|
||||
node_js:
|
||||
- 10
|
||||
- 8
|
||||
|
||||
# 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:
|
||||
- master
|
||||
- /^greenkeeper.*$/
|
||||
|
||||
# Retry install on fail to avoid failing a build on network/disk/external errors
|
||||
install:
|
||||
- travis_retry npm install
|
||||
|
||||
script:
|
||||
- npm run test
|
||||
|
||||
after_success:
|
||||
- npm run codecov
|
||||
|
||||
jobs:
|
||||
include:
|
||||
- stage: release
|
||||
node_js: lts/*
|
||||
script:
|
||||
- npm run semantic-release
|
||||
import:
|
||||
- .travis/node.yml
|
||||
- .travis/node-versions.yml
|
||||
- .travis/semantic-release.yml
|
||||
- .travis/greenkeeper.yml
|
||||
- .travis/codecov.yml
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
after_success:
|
||||
- npm run codecov
|
||||
@@ -0,0 +1,3 @@
|
||||
branches:
|
||||
only:
|
||||
- /^greenkeeper.*$/
|
||||
@@ -0,0 +1,3 @@
|
||||
node_js:
|
||||
- 12
|
||||
- 10.18
|
||||
@@ -0,0 +1,11 @@
|
||||
language: node_js
|
||||
|
||||
cache:
|
||||
npm: false
|
||||
|
||||
# Retry install on fail to avoid failing a build on network/disk/external errors
|
||||
install:
|
||||
- travis_retry npm install
|
||||
|
||||
script:
|
||||
- npm run test
|
||||
@@ -0,0 +1,15 @@
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- next
|
||||
- beta
|
||||
- /^\d+\.(\d+|x)(\.x)?$/
|
||||
|
||||
jobs:
|
||||
include:
|
||||
- stage: release
|
||||
node_js: lts/*
|
||||
install:
|
||||
- travis_retry npm install
|
||||
script:
|
||||
- npm run semantic-release
|
||||
+6
-6
@@ -107,11 +107,11 @@ To ensure consistency and quality, all documentation modifications must:
|
||||
- a third-party product/brand/service, i.e. Integrate with [GitHub](https://github.com)
|
||||
- an external concept or feature, i.e. Create a [GitHub release](https://help.github.com/articles/creating-releases)
|
||||
- a package or module, i.e. The [`@semantic-release/github`](https://github.com/semantic-release/github) module
|
||||
- Use the the [single backtick `code` quoting](https://help.github.com/articles/basic-writing-and-formatting-syntax/#quoting-code) for:
|
||||
- Use the [single backtick `code` quoting](https://help.github.com/articles/basic-writing-and-formatting-syntax/#quoting-code) for:
|
||||
- commands inside sentences, i.e. the `semantic-release` command
|
||||
- programming language keywords, i.e. `function`, `async`, `String`
|
||||
- packages or modules, i.e. The [`@semantic-release/github`](https://github.com/semantic-release/github) module
|
||||
- Use the the [triple backtick `code` formatting](https://help.github.com/articles/creating-and-highlighting-code-blocks) for:
|
||||
- Use the [triple backtick `code` formatting](https://help.github.com/articles/creating-and-highlighting-code-blocks) for:
|
||||
- code examples
|
||||
- configuration examples
|
||||
- sequence of command lines
|
||||
@@ -183,17 +183,17 @@ The footer should contain any information about **Breaking Changes** and is also
|
||||
#### Examples
|
||||
|
||||
```commit
|
||||
`fix(pencil): stop graphite breaking when too much pressure applied`
|
||||
fix(pencil): stop graphite breaking when too much pressure applied
|
||||
```
|
||||
|
||||
```commit
|
||||
`feat(pencil): add 'graphiteWidth' option`
|
||||
feat(pencil): add 'graphiteWidth' option
|
||||
|
||||
Fix #42
|
||||
```
|
||||
|
||||
```commit
|
||||
perf(pencil): remove graphiteWidth option`
|
||||
perf(pencil): remove graphiteWidth option
|
||||
|
||||
BREAKING CHANGE: The graphiteWidth option has been removed.
|
||||
|
||||
@@ -224,7 +224,7 @@ All the [semantic-release](https://github.com/semantic-release) repositories use
|
||||
Before pushing your code changes make sure there are no linting errors with `npm run lint`.
|
||||
|
||||
**Tips**:
|
||||
- Most linting errors can be automatically fixed with `npm run lint --fix`.
|
||||
- Most linting errors can be automatically fixed with `npm run lint -- --fix`.
|
||||
- Install the [XO plugin](https://github.com/sindresorhus/xo#editor-plugins) for your editor to see linting errors directly in your editor and automatically fix them on save.
|
||||
|
||||
### Tests
|
||||
|
||||
@@ -24,6 +24,9 @@
|
||||
<a href="https://www.npmjs.com/package/semantic-release">
|
||||
<img alt="npm next version" src="https://img.shields.io/npm/v/semantic-release/next.svg">
|
||||
</a>
|
||||
<a href="https://www.npmjs.com/package/semantic-release">
|
||||
<img alt="npm beta version" src="https://img.shields.io/npm/v/semantic-release/beta.svg">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**semantic-release** automates the whole package release workflow including: determining the next version number, generating the release notes and publishing the package.
|
||||
@@ -39,6 +42,7 @@ This removes the immediate connection between human emotions and version numbers
|
||||
- New features and fixes are immediately available to users
|
||||
- Notify maintainers and users of new releases
|
||||
- Use formalized commit message convention to document changes in the codebase
|
||||
- Publish on different distribution channels (such as [npm dist-tags](https://docs.npmjs.com/cli/dist-tag)) based on git merges
|
||||
- Integrate with your [continuous integration workflow](docs/recipes/README.md#ci-configurations)
|
||||
- Avoid potential errors associated with manual releases
|
||||
- Support any [package managers and languages](docs/recipes/README.md#package-managers-and-languages) via [plugins](docs/usage/plugins.md)
|
||||
@@ -52,7 +56,7 @@ This removes the immediate connection between human emotions and version numbers
|
||||
|
||||
By default **semantic-release** uses [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines). The commit message format can be changed with the [`preset` or `config` options](docs/usage/configuration.md#options) of the [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer#options) and [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator#options) plugins.
|
||||
|
||||
Tools such as [commitizen](https://github.com/commitizen/cz-cli), [commitlint](https://github.com/conventional-changelog/commitlint) or [semantic-git-commit-cli](https://github.com/JPeer264/node-semantic-git-commit-cli) can be used to help contributors and enforce valid commit messages.
|
||||
Tools such as [commitizen](https://github.com/commitizen/cz-cli) or [commitlint](https://github.com/conventional-changelog/commitlint) can be used to help contributors and enforce valid commit messages.
|
||||
|
||||
Here is an example of the release type that will be done based on a commit messages:
|
||||
|
||||
@@ -68,11 +72,12 @@ Here is an example of the release type that will be done based on a commit messa
|
||||
|
||||
### Triggering a release
|
||||
|
||||
For each new commits added to the release branch (i.e. `master`) with `git push` or by merging a pull request or merging from another branch, a CI build is triggered and runs the `semantic-release` command to make a release if there are codebase changes since the last release that affect the package functionalities.
|
||||
For each new commits added to one of the release branches (for example `master`, `next`, `beta`), with `git push` or by merging a pull request or merging from another branch, a CI build is triggered and runs the `semantic-release` command to make a release if there are codebase changes since the last release that affect the package functionalities.
|
||||
|
||||
If you need more control over the timing of releases you have a couple of options:
|
||||
- Publish releases on a distribution channel (for example npm’s [dist-tags](https://docs.npmjs.com/cli/dist-tag)). This way you can keep control over what your users end up using by default, and you can decide when to make an automatically released version available to the stable channel, and promote it.
|
||||
- Develop on a `dev` branch and merge it to the release branch (i.e. `master`) once you are ready to publish. **semantic-release** will run only on pushes to the release branch.
|
||||
**semantic-release** offers various ways to control the timing, the content and the audience of published releases. See example workflows in the following recipes:
|
||||
- [Using distribution channels](docs/recipes/distribution-channels.md#publishing-on-distribution-channels)
|
||||
- [Maintenance releases](docs/recipes/maintenance-releases.md#publishing-maintenance-releases)
|
||||
- [Pre-releases](docs/recipes/pre-releases.md#publishing-pre-releases)
|
||||
|
||||
### Release steps
|
||||
|
||||
@@ -90,6 +95,14 @@ After running the tests, the command `semantic-release` will execute the followi
|
||||
| Publish | Publish the release. |
|
||||
| Notify | Notify of new releases or errors. |
|
||||
|
||||
## Requirements
|
||||
|
||||
In order to use **semantic-release** you need:
|
||||
- To host your code in a [Git repository](https://git-scm.com)
|
||||
- Use a Continuous Integration service that allows you to [securely set up credentials](docs/usage/ci-configuration.md#authentication)
|
||||
- Git CLI version [2.7.1 or higher](docs/support/FAQ.md#why-does-semantic-release-require-git-version--271) installed in your Continuous Integration environment
|
||||
- [Node.js](https://nodejs.org) version [10.18 or higher](docs/support/FAQ.md#why-does-semantic-release-require-node-version--1018) installed in your Continuous Integration environment
|
||||
|
||||
## Documentation
|
||||
|
||||
- Usage
|
||||
@@ -98,17 +111,20 @@ After running the tests, the command `semantic-release` will execute the followi
|
||||
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
|
||||
- [Configuration](docs/usage/configuration.md#configuration)
|
||||
- [Plugins](docs/usage/plugins.md)
|
||||
- [Workflow configuration](docs/usage/workflow-configuration.md)
|
||||
- [Shareable configurations](docs/usage/shareable-configurations.md)
|
||||
- Extending
|
||||
- [Plugins](docs/extending/plugins-list.md)
|
||||
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
|
||||
- Recipes
|
||||
- [CI configurations](docs/recipes/README.md)
|
||||
- [Git hosted services](docs/recipes/README.md)
|
||||
- [Release workflow](docs/recipes/README.md)
|
||||
- [Package managers and languages](docs/recipes/README.md)
|
||||
- Developer guide
|
||||
- [JavaScript API](docs/developer-guide/js-api.md)
|
||||
- [Plugins](docs/developer-guide/plugin.md)
|
||||
- [Shareable configuration](docs/developer-guide/shareable-configuration.md)
|
||||
- [Plugins development](docs/developer-guide/plugin.md)
|
||||
- [Shareable configuration development](docs/developer-guide/shareable-configuration.md)
|
||||
- Support
|
||||
- [Resources](docs/support/resources.md)
|
||||
- [Frequently Asked Questions](docs/support/FAQ.md)
|
||||
@@ -134,9 +150,16 @@ Let people know that your package is published using **semantic-release** by inc
|
||||
|
||||
## Team
|
||||
|
||||
| [](https://github.com/boennemann) | [](https://github.com/relekang) | [](https://github.com/jo) | [](https://github.com/gr2m) | [](https://github.com/finnp) | [](https://github.com/pvdlg) | [](https://github.com/christophwitzko) |
|
||||
|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------|
|
||||
| [Stephan Bönnemann](https://github.com/boennemann) | [Rolf Erik Lekang](https://github.com/relekang) | [Johannes Jörg Schmidt](https://github.com/jo) | [Gregor Martynus](https://github.com/gr2m) | [Finn Pauls](https://github.com/finnp) | [Pierre Vanduynslager](https://github.com/pvdlg) | [Christoph Witzko](https://github.com/christophwitzko) |
|
||||
| [](https://github.com/gr2m) | [](https://github.com/pvdlg) | [](https://github.com/travi) |
|
||||
| ----------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------- |
|
||||
| [Gregor Martynus](https://github.com/gr2m) | [Pierre Vanduynslager](https://github.com/pvdlg) | [Matt Travi](https://github.com/travi) |
|
||||
|
||||
## Alumni
|
||||
|
||||
| [](https://github.com/boennemann) | [](https://github.com/relekang) | [](https://github.com/jo) | [](https://github.com/finnp) | [](https://github.com/christophwitzko) |
|
||||
| ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
||||
| [Stephan Bönnemann](https://github.com/boennemann) | [Rolf Erik Lekang](https://github.com/relekang) | [Johannes Jörg Schmidt](https://github.com/jo) | [Finn Pauls](https://github.com/finnp) | [Christoph Witzko](https://github.com/christophwitzko) |
|
||||
|
||||
|
||||
<p align="center">
|
||||
<img alt="Kill all humans" src="media/bender.png">
|
||||
|
||||
+8
-7
@@ -1,10 +1,12 @@
|
||||
# Summary
|
||||
|
||||
## Usage
|
||||
- [Getting started](docs/usage/getting-started.md#getting-started)
|
||||
- [Installation](docs/usage/installation.md#installation)
|
||||
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
|
||||
- [Configuration](docs/usage/configuration.md#configuration)
|
||||
- [Plugins](docs/usage/plugins.md)
|
||||
- [Workflow configuration](docs/usage/workflow-configuration.md)
|
||||
- [Shareable configurations](docs/usage/shareable-configurations.md)
|
||||
|
||||
## Extending
|
||||
@@ -12,19 +14,18 @@
|
||||
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
|
||||
|
||||
## Recipes
|
||||
- [CI configurations](docs/recipes/README.md)
|
||||
- [CircleCI 2.0 workflows](docs/recipes/circleci-workflows.md)
|
||||
- [CI configurations](docs/recipes/README.md#ci-configurations)
|
||||
- [CircleCI 2.0](docs/recipes/circleci-workflows.md)
|
||||
- [Travis CI](docs/recipes/travis.md)
|
||||
- [Travis CI with build stages](docs/recipes/travis-build-stages.md)
|
||||
- [GitLab CI](docs/recipes/gitlab-ci.md)
|
||||
- [Git hosted services](docs/recipes/README.md)
|
||||
- [Git hosted services](docs/recipes/README.md#git-hosted-services)
|
||||
- [Git authentication with SSH keys](docs/recipes/git-auth-ssh-keys.md)
|
||||
- [Package managers and languages](docs/recipes/README.md)
|
||||
- [Package managers and languages](docs/recipes/README.md#package-managers-and-languages)
|
||||
|
||||
## Developer guide
|
||||
- [JavaScript API](docs/developer-guide/js-api.md)
|
||||
- [Plugin](docs/developer-guide/plugin.md)
|
||||
- [Shareable configuration](docs/developer-guide/shareable-configuration.md)
|
||||
- [Plugin development](docs/developer-guide/plugin.md)
|
||||
- [Shareable configuration development](docs/developer-guide/shareable-configuration.md)
|
||||
|
||||
## Support
|
||||
- [Resources](docs/support/resources.md)
|
||||
|
||||
@@ -10,7 +10,7 @@ var execa = require('execa');
|
||||
var findVersions = require('find-versions');
|
||||
var pkg = require('../package.json');
|
||||
|
||||
var MIN_GIT_VERSION = '2.0.0';
|
||||
var MIN_GIT_VERSION = '2.7.1';
|
||||
|
||||
if (!semver.satisfies(process.version, pkg.engines.node)) {
|
||||
console.error(
|
||||
@@ -21,24 +21,23 @@ See https://github.com/semantic-release/semantic-release/blob/master/docs/suppor
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
execa
|
||||
.stdout('git', ['--version'])
|
||||
.then(stdout => {
|
||||
execa('git', ['--version'])
|
||||
.then(({stdout}) => {
|
||||
var gitVersion = findVersions(stdout)[0];
|
||||
if (semver.lt(gitVersion, MIN_GIT_VERSION)) {
|
||||
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. Found ${gitVersion}.`);
|
||||
process.exit(1);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
.catch((error) => {
|
||||
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. No git binary found.`);
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Node 8+ from this point on
|
||||
// Node 10+ from this point on
|
||||
require('../cli')()
|
||||
.then(exitCode => {
|
||||
.then((exitCode) => {
|
||||
process.exitCode = exitCode;
|
||||
})
|
||||
.catch(() => {
|
||||
|
||||
@@ -5,21 +5,21 @@ const hideSensitive = require('./lib/hide-sensitive');
|
||||
const stringList = {
|
||||
type: 'string',
|
||||
array: true,
|
||||
coerce: values =>
|
||||
coerce: (values) =>
|
||||
values.length === 1 && values[0].trim() === 'false'
|
||||
? []
|
||||
: values.reduce((values, value) => values.concat(value.split(',').map(value => value.trim())), []),
|
||||
: values.reduce((values, value) => values.concat(value.split(',').map((value) => value.trim())), []),
|
||||
};
|
||||
|
||||
module.exports = async () => {
|
||||
const cli = require('yargs')
|
||||
.command('$0', 'Run automated package publishing', yargs => {
|
||||
.command('$0', 'Run automated package publishing', (yargs) => {
|
||||
yargs.demandCommand(0, 0).usage(`Run automated package publishing
|
||||
|
||||
Usage:
|
||||
semantic-release [options] [plugins]`);
|
||||
})
|
||||
.option('b', {alias: 'branch', describe: 'Git branch to release from', type: 'string', group: 'Options'})
|
||||
.option('b', {alias: 'branches', describe: 'Git branches to release from', ...stringList, group: 'Options'})
|
||||
.option('r', {alias: 'repository-url', describe: 'Git repository URL', type: 'string', group: 'Options'})
|
||||
.option('t', {alias: 'tag-format', describe: 'Git tag format', type: 'string', group: 'Options'})
|
||||
.option('p', {alias: 'plugins', describe: 'Plugins', ...stringList, group: 'Options'})
|
||||
@@ -41,18 +41,18 @@ Usage:
|
||||
.exitProcess(false);
|
||||
|
||||
try {
|
||||
const {help, version, ...opts} = cli.parse(argv.slice(2));
|
||||
const {help, version, ...options} = cli.parse(argv.slice(2));
|
||||
|
||||
if (Boolean(help) || Boolean(version)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (opts.debug) {
|
||||
if (options.debug) {
|
||||
// Debug must be enabled before other requires in order to work
|
||||
require('debug').enable('semantic-release:*');
|
||||
}
|
||||
|
||||
await require('.')(opts);
|
||||
await require('.')(options);
|
||||
return 0;
|
||||
} catch (error) {
|
||||
if (error.name !== 'YError') {
|
||||
|
||||
@@ -12,7 +12,14 @@ const stderrBuffer = WritableStreamBuffer();
|
||||
try {
|
||||
const result = await semanticRelease({
|
||||
// Core options
|
||||
branch: 'master',
|
||||
branches: [
|
||||
'+([0-9])?(.{+([0-9]),x}).x',
|
||||
'master',
|
||||
'next',
|
||||
'next-major',
|
||||
{name: 'beta', prerelease: true},
|
||||
{name: 'alpha', prerelease: true}
|
||||
],
|
||||
repositoryUrl: 'https://github.com/me/my-package.git',
|
||||
// Shareable config
|
||||
extends: 'my-shareable-config',
|
||||
@@ -123,11 +130,12 @@ Type: `Object`
|
||||
|
||||
Information related to the last release found:
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|----------------------------------------------------------------------------------------------------|
|
||||
| version | `String` | The version of the last release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the last release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the last release. |
|
||||
| Name | Type | Description |
|
||||
|---------|----------|-------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| version | `String` | The version of the last release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the last release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the last release. |
|
||||
| channel | `String` | The distribution channel on which the last release was initially made available (`undefined` for the default distribution channel). |
|
||||
|
||||
**Notes**: If no previous release is found, `lastRelease` will be an empty `Object`.
|
||||
|
||||
@@ -137,6 +145,7 @@ Example:
|
||||
gitHead: 'da39a3ee5e6b4b0d3255bfef95601890afd80709',
|
||||
version: '1.0.0',
|
||||
gitTag: 'v1.0.0',
|
||||
channel: 'next'
|
||||
}
|
||||
```
|
||||
|
||||
@@ -206,13 +215,14 @@ Type: `Object`
|
||||
|
||||
Information related to the newly published release:
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|---------------------------------------------------------------------------------------------------|
|
||||
| type | `String` | The [semver](https://semver.org) type of the release (`patch`, `minor` or `major`). |
|
||||
| version | `String` | The version of the new release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the new release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the new release. |
|
||||
| notes | `String` | The release notes for the new release. |
|
||||
| Name | Type | Description |
|
||||
|---------|----------|-------------------------------------------------------------------------------------------------------------------------------|
|
||||
| type | `String` | The [semver](https://semver.org) type of the release (`patch`, `minor` or `major`). |
|
||||
| version | `String` | The version of the new release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the new release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the new release. |
|
||||
| notes | `String` | The release notes for the new release. |
|
||||
| channel | `String` | The distribution channel on which the next release will be made available (`undefined` for the default distribution channel). |
|
||||
|
||||
Example:
|
||||
```js
|
||||
@@ -222,6 +232,7 @@ Example:
|
||||
version: '1.1.0',
|
||||
gitTag: 'v1.1.0',
|
||||
notes: 'Release notes for version 1.1.0...',
|
||||
channel : 'next'
|
||||
}
|
||||
```
|
||||
|
||||
@@ -229,19 +240,20 @@ Example:
|
||||
|
||||
Type: `Array<Object>`
|
||||
|
||||
The list of releases published, one release per [publish plugin](../usage/plugins.md#publish-plugin).<br>
|
||||
The list of releases published or made available to a distribution channel.<br>
|
||||
Each release object has the following properties:
|
||||
|
||||
| Name | Type | Description |
|
||||
|------------|----------|-----------------------------------------------------------------------------------------------|
|
||||
| name | `String` | **Optional.** The release name, only if set by the corresponding `publish` plugin. |
|
||||
| url | `String` | **Optional.** The release URL, only if set by the corresponding `publish` plugin. |
|
||||
| type | `String` | The [semver](https://semver.org) type of the release (`patch`, `minor` or `major`). |
|
||||
| version | `String` | The version of the release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the release. |
|
||||
| notes | `String` | The release notes for the release. |
|
||||
| pluginName | `String` | The name of the plugin that published the release. |
|
||||
| Name | Type | Description |
|
||||
|------------|----------|----------------------------------------------------------------------------------------------------------------|
|
||||
| name | `String` | **Optional.** The release name, only if set by the corresponding `publish` plugin. |
|
||||
| url | `String` | **Optional.** The release URL, only if set by the corresponding `publish` plugin. |
|
||||
| type | `String` | The [semver](https://semver.org) type of the release (`patch`, `minor` or `major`). |
|
||||
| version | `String` | The version of the release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the release. |
|
||||
| notes | `String` | The release notes for the release. |
|
||||
| pluginName | `String` | The name of the plugin that published the release. |
|
||||
| channel | `String` | The distribution channel on which the release is available (`undefined` for the default distribution channel). |
|
||||
|
||||
Example:
|
||||
```js
|
||||
@@ -255,6 +267,7 @@ Example:
|
||||
gitTag: 'v1.1.0',
|
||||
notes: 'Release notes for version 1.1.0...',
|
||||
pluginName: '@semantic-release/github'
|
||||
channel: 'next'
|
||||
},
|
||||
{
|
||||
name: 'npm package (@latest dist-tag)',
|
||||
@@ -265,6 +278,7 @@ Example:
|
||||
gitTag: 'v1.1.0',
|
||||
notes: 'Release notes for version 1.1.0...',
|
||||
pluginName: '@semantic-release/npm'
|
||||
channel: 'next'
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
@@ -1 +1,106 @@
|
||||
# Plugin developer guide
|
||||
# Plugin Developer Guide
|
||||
|
||||
To create a plugin for `semantic-release`, you need to decide which parts of the release lifecycle are important to that plugin. For example, it is best to always have a `verify` step because you may be receiving inputs from a user and want to make sure they exist. A plugin can abide by any of the following lifecycles:
|
||||
|
||||
- `verify`
|
||||
- `prepare`
|
||||
- `publish`
|
||||
- `success`
|
||||
- `fail`
|
||||
|
||||
`semantic-release` will require the plugin via `node` and look through the required object for methods named like the lifecyles stated above. For example, if your plugin only had a `verify` and `success` step, the `main` file for your object would need to `export` an object with `verify` and `success` functions.
|
||||
|
||||
In addition to the lifecycle methods, each lifecyle is passed two objects:
|
||||
|
||||
1. `pluginConfig` - an object containing the options that a user may pass in via their `release.config.js` file (or similar)
|
||||
2. `context` - provided by `semantic-release` for access to things like `env` variables set on the running process.
|
||||
|
||||
For each lifecycle you create, you will want to ensure it can accept `pluginConfig` and `context` as parameters.
|
||||
|
||||
## Creating a Plugin Project
|
||||
|
||||
It is recommended that you generate a new project with `yarn init`. This will provide you with a basic node project to get started with. From there, create an `index.js` file, and make sure it is specified as the `main` in the `package.json`. We will use this file to orchestrate the lifecycle methods later on.
|
||||
|
||||
Next, create a `src` or `lib` folder in the root of the project. This is where we will store our logic and code for how our lifecycle methods work. Finally, create a `test` folder so you can write tests related to your logic.
|
||||
|
||||
We recommend you setup a linting system to ensure good javascript practices are enforced. ESLint is usually the system of choice, and the configuration can be whatever you or your team fancies.
|
||||
|
||||
## Exposing Lifecycle Methods
|
||||
|
||||
In your `index.js` file, you can start by writing the following code
|
||||
|
||||
```javascript
|
||||
const verifyConditions = require('./src/verify');
|
||||
|
||||
let verified;
|
||||
|
||||
/**
|
||||
* Called by semantic-release during the verification step
|
||||
* @param {*} pluginConfig The semantic-release plugin config
|
||||
* @param {*} context The context provided by semantic-release
|
||||
*/
|
||||
async function verify(pluginConfig, context) {
|
||||
await verifyConditions(pluginConfig, context);
|
||||
verified = true;
|
||||
}
|
||||
|
||||
module.exports = { verify };
|
||||
```
|
||||
|
||||
Then, in your `src` folder, create a file called `verify.js` and add the following
|
||||
|
||||
```javascript
|
||||
const AggregateError = require('aggregate-error');
|
||||
|
||||
/**
|
||||
* A method to verify that the user has given us a slack webhook url to post to
|
||||
*/
|
||||
module.exports = async (pluginConfig, context) => {
|
||||
const { logger } = context;
|
||||
const errors = [];
|
||||
|
||||
// Throw any errors we accumulated during the validation
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
As of right now, this code won't do anything. However, if you were to run this plugin via `semantic-release`, it would run when the `verify` step occurred.
|
||||
|
||||
Following this structure, you can create different steps and checks to run through out the release process.
|
||||
|
||||
## Supporting Options
|
||||
|
||||
Let's say we want to verify that an `option` is passed. An `option` is a configuration object that is specific to your plugin. For example, the user may set an `option` in their release config like:
|
||||
|
||||
```js
|
||||
{
|
||||
prepare: {
|
||||
path: "@semantic-release/my-special-plugin"
|
||||
message: "My cool release message"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This `message` option will be passed to the `pluginConfig` object mentioned earlier. We can use the validation method we created to verify this option exists so we can perform logic based on that knowledge. In our `verify` file, we can add the following:
|
||||
|
||||
```js
|
||||
const { message } = pluginConfig;
|
||||
|
||||
if (message.length) {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
## Supporting Environment Variables
|
||||
|
||||
Similar to `options`, environment variables exist to allow users to pass tokens and set special URLs. These are set on the `context` object instead of the `pluginConfig` object. Let's say we wanted to check for `GITHUB_TOKEN` in the environment because we want to post to GitHub on the user's behalf. To do this, we can add the following to our `verify` command:
|
||||
|
||||
```js
|
||||
const { env } = context;
|
||||
|
||||
if (env.GITHUB_TOKEN) {
|
||||
//...
|
||||
}
|
||||
```
|
||||
@@ -65,10 +65,10 @@
|
||||
- `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
|
||||
- `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
|
||||
- `publish`: Submit the generated archives to the webstore for review, and publish the item including release notes
|
||||
- [semantic-release-firefox-add-on](https://github.com/tophat/semantic-release-firefox-add-on)
|
||||
- `verifyConditions`: Verify that all required options are present and authentication is set via environment variables
|
||||
- `prepare`: Write the correct version to the `manifest.json`
|
||||
- `publish`: Creates an unsigned `.xpi` file, and submits it to the Mozilla Add On store for signing. Once the package is signed, downloads the signed `.xpi` to a local directory
|
||||
- [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)
|
||||
@@ -91,3 +91,25 @@
|
||||
- [semantic-release-github-pages](https://github.com/qiwi/semantic-release-gh-pages-plugin)
|
||||
- `verifyConditions`: Verify the presence of the auth token set via environment variables.
|
||||
- `publish`: Pushes commit to the documentation branch.
|
||||
- [leiningen-semantic-release](https://github.com/NoxHarmonium/leiningen-semantic-release)
|
||||
- `verifyConditions`: Checks the project.clj is syntactically valid.
|
||||
- `prepare`: Update the project.clj version and package the output jar file.
|
||||
- `publish`: Publish the jar (and generated Maven metadata) to a maven repository (or clojars).
|
||||
- [@saithodev/semantic-release-gitea](https://github.com/saitho/semantic-release-gitea)
|
||||
- `verifyConditions`: Verify the presence and the validity of the authentication and the assets option configuration.
|
||||
- `publish`: Publish a Gitea release, optionally uploading file assets.
|
||||
- `addChannel`: Update a Gitea release's pre-release field.
|
||||
- [@google/semantic-release-replace-plugin](https://github.com/google/semantic-release-replace-plugin)
|
||||
- `prepare`: Replace version strings in files using regex and glob.
|
||||
- [semantic-release-rubygem](https://github.com/Gusto/semantic-release-rubygem)
|
||||
- `verifyConditions`: Locate and validate a `.gemspec` file, locate and validate a `lib/**/version.rb` file, verify the presence of the `GEM_HOST_API_KEY` environment variable, and create a credentials file with the API key.
|
||||
- `prepare`: Update the version in the `lib/**/version.rb` version file and [build](https://guides.rubygems.org/command-reference/#gem-build) the gem.
|
||||
- `publish`: [Push the Ruby gem](https://guides.rubygems.org/command-reference/#gem-push) to the gem server.
|
||||
- [semantic-release-npm-deprecate-old-versions](https://github.com/ghusse/semantic-release-npm-deprecate-old-versions)
|
||||
- `verifyConditions`: Validates configuration.
|
||||
- `publish`: Deprecates old versions, based on the declaration of supported versions in the config.
|
||||
- [amanda-mitchell/semantic-release-npm-multiple](https://github.com/amanda-mitchell/semantic-release-npm-multiple)
|
||||
- **Note**: this is a thin wrapper around the built-in npm plugin that can target multiple registries
|
||||
- `verifyConditions`: Verify the presence and the validity of the npm authentication and release configuration for multiple registries
|
||||
- `prepare`: Update the package.json version and create the npm package tarball
|
||||
- `publish`: Publish the package on the npm registry for multiple registries
|
||||
|
||||
@@ -5,3 +5,17 @@
|
||||
- [@semantic-release/gitlab-config](https://github.com/semantic-release/gitlab-config) - semantic-release shareable configuration for GitLab
|
||||
|
||||
## Community configurations
|
||||
- [@jedmao/semantic-release-npm-github-config](https://github.com/jedmao/semantic-release-npm-github-config)
|
||||
- Provides an informative [git](https://github.com/semantic-release/git) commit message for the release commit that does not trigger continuous integration and conforms to the [conventional commits specification](https://www.conventionalcommits.org/) (e.g., "chore(release): 1.2.3 [skip ci]\n\nnotes").
|
||||
- Creates a tarball that gets uploaded with each [GitHub release](https://github.com/semantic-release/github).
|
||||
- Publishes the same tarball to [npm](https://github.com/semantic-release/npm).
|
||||
- Commits the version change in `package.json`.
|
||||
- Creates or updates a [changelog](https://github.com/semantic-release/changelog) file.
|
||||
- [semantic-release-npm-github-publish](https://github.com/oleg-koval/semantic-release-npm-github-publish)
|
||||
- Based on [angular preset](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular).
|
||||
- Adds more keywords for the `chore` **PATCH** release.
|
||||
- Generates or updates a [changelog](https://github.com/semantic-release/changelog) file including all **PATCH** keywords (not included in default angular package).
|
||||
- Updates GitHub release with release-notes.
|
||||
- Bumps a version in package.json.
|
||||
- Publishes the new version to [NPM](https://npmjs.org).
|
||||
|
||||
|
||||
@@ -4,8 +4,15 @@
|
||||
- [CircleCI 2.0 workflows](circleci-workflows.md)
|
||||
- [Travis CI](travis.md)
|
||||
- [GitLab CI](gitlab-ci.md)
|
||||
- [GitHub Actions](github-actions.md)
|
||||
- [Jenkins CI](jenkins-ci.md)
|
||||
|
||||
## Git hosted services
|
||||
- [Git authentication with SSH keys](git-auth-ssh-keys.md)
|
||||
|
||||
## Release workflow
|
||||
- [Publishing on distribution channels](distribution-channels.md)
|
||||
- [Publishing maintenance releases](maintenance-releases.md)
|
||||
- [Publishing pre-releases](pre-releases.md)
|
||||
|
||||
## Package managers and languages
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
# Publishing on distribution channels
|
||||
|
||||
This recipe will walk you through a simple example that uses distribution channels to make releases available only to a subset of users, in order to collect feedbacks before distributing the release to all users.
|
||||
|
||||
This example uses the **semantic-release** default configuration:
|
||||
- [branches](../usage/configuration.md#branches): `['+([0-9])?(.{+([0-9]),x}).x', 'master', 'next', 'next-major', {name: 'beta', prerelease: true}, {name: 'alpha', prerelease: true}]`
|
||||
- [plugins](../usage/configuration.md#plugins): `['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator', '@semantic-release/npm', '@semantic-release/github']`
|
||||
|
||||
## Initial release
|
||||
|
||||
We'll start by making the first commit of the project, with the code for the initial release and the message `feat: initial commit` to `master`. When pushing that commit, **semantic-release** will release the version `1.0.0` and make it available on the default distribution channel which is the dist-tag `@latest` for npm.
|
||||
|
||||
The Git history of the repository is:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
```
|
||||
|
||||
## Releasing a bug fix
|
||||
|
||||
We can now continue to commit changes and release updates to our users. For example we can commit a bug fix with the message `fix: a fix` to `master`. When pushing that commit, **semantic-release** will release the version `1.0.1` on the dist-tag `@latest`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
* fix: a fix # => v1.0.1 on @latest
|
||||
```
|
||||
|
||||
## Releasing a feature on next
|
||||
|
||||
We now want to develop an important feature, which is a breaking change. Considering the scope of this feature we want to make it available, at first, only to our most dedicated users in order to get feedback. Once we get that feedback we can make improvements and ultimately make the new feature available to all users.
|
||||
|
||||
To implement that workflow we can create the branch `next` and commit our feature to this branch. When pushing that commit, **semantic-release** will release the version `2.0.0` on the dist-tag `@next`. That means only the users installing our module with `npm install example-module@next` will receive the version `2.0.0`. Other users installing with `npm install example-module` will still receive the version `1.0.1`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
* fix: a fix # => v1.0.1 on @latest
|
||||
| \
|
||||
| * feat: a big feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0 on @next
|
||||
```
|
||||
|
||||
## Releasing a bug fix on next
|
||||
|
||||
One of our users starts to use the new `2.0.0` release and reports a bug. We develop a bug fix and commit it to the `next` branch with the message `fix: fix something on the big feature`. When pushing that commit, **semantic-release** will release the version `2.0.1` on the dist-tag `@next`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
* fix: a fix # => v1.0.1 on @latest
|
||||
| \
|
||||
| * feat: a big feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0 on @next
|
||||
| * fix: fix something on the big feature # => v2.0.1 on @next
|
||||
```
|
||||
|
||||
## Releasing a feature on latest
|
||||
|
||||
We now want to develop a smaller, non-breaking feature. Its scope is small enough that we don't need to have a phase of feedback and we can release it to all users right away.
|
||||
|
||||
If we were to commit that feature on `next` only a subset of users would get it, and we would need to wait for the end of our feedback period in order to make both the big and the small feature available to all users.
|
||||
|
||||
Instead, we develop that small feature commit it to `master` with the message `feat: a small feature`. When pushing that commit, **semantic-release** will release the version `1.1.0` on the dist-tag `@latest` so all users can benefit from it right away.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
* fix: a fix # => v1.0.1 on @latest
|
||||
| \
|
||||
| * feat: a big feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0 on @next
|
||||
| * fix: fix something on the big feature # => v2.0.1 on @next
|
||||
* | feat: a small feature # => v1.1.0 on @latest
|
||||
```
|
||||
|
||||
## Porting a feature to next
|
||||
|
||||
Most of our users now have access to the small feature, but we still need to make it available to our users using the `@next` dist-tag. To do so we need to merge our changes made on `master` (the commit `feat: a small feature`) into `next`. As `master` and `next` branches have diverged, this merge might require to resolve conflicts.
|
||||
|
||||
Once the conflicts are resolved and the merge commit is pushed to `next`, **semantic-release** will release the version `2.1.0` on the dist-tag `@next` which contains both our small and big feature.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
* fix: a fix # => v1.0.1 on @latest
|
||||
| \
|
||||
| * feat: a big feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0 on @next
|
||||
| * fix: fix something on the big feature # => v2.0.1 on @next
|
||||
* | feat: a small feature # => v1.1.0 on @latest
|
||||
| * Merge branch master into next # => v2.1.0 on @next
|
||||
```
|
||||
|
||||
## Adding a version to latest
|
||||
|
||||
After a period of feedback from our users using the `@next` dist-tag we feel confident to make our big feature available to all users. To do so we merge the `next` branch into `master`. There should be no conflict as `next` is strictly ahead of `master`.
|
||||
|
||||
Once the merge commit is pushed to `next`, **semantic-release** will add the version `2.1.0` to the dist-tag `@latest` so all users will receive it when installing out module with `npm install example-module`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
* fix: a fix # => v1.0.1 on @latest
|
||||
| \
|
||||
| * feat: a big feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0 on @next
|
||||
| * fix: fix something on the big feature # => v2.0.1 on @next
|
||||
* | feat: a small feature # => v1.1.0 on @latest
|
||||
| * Merge branch master into next # => v2.1.0 on @next
|
||||
| /|
|
||||
* | Merge branch next into master # => v2.1.0 on @latest
|
||||
```
|
||||
|
||||
We can now continue to push new fixes and features on `master`, or a new breaking change on `next` as we did before.
|
||||
@@ -0,0 +1,90 @@
|
||||
# Using semantic-release with [GitHub Actions](https://help.github.com/en/categories/automating-your-workflow-with-github-actions)
|
||||
|
||||
## Environment variables
|
||||
|
||||
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured with [Secret Variables](https://help.github.com/en/articles/virtual-environments-for-github-actions#creating-and-using-secrets-encrypted-variables).
|
||||
|
||||
In this example an [`NPM_TOKEN`](https://docs.npmjs.com/creating-and-viewing-authentication-tokens) is required to publish a package to the npm registry. GitHub Actions [automatically populate](https://help.github.com/en/articles/virtual-environments-for-github-actions#github_token-secret) a [`GITHUB_TOKEN`](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line) environment variable which can be used in Workflows.
|
||||
|
||||
## Node project configuration
|
||||
|
||||
[GitHub Actions](https://github.com/features/actions) support [Workflows](https://help.github.com/en/articles/configuring-workflows), allowing to run tests on multiple Node versions and publish a release only when all test pass.
|
||||
|
||||
**Note**: The publish pipeline must run on [Node version >= 10.18](../support/FAQ.md#why-does-semantic-release-require-node-version--1018).
|
||||
|
||||
### `.github/workflows/release.yml` configuration for Node projects
|
||||
|
||||
The following is a minimal configuration for [`semantic-release`](https://github.com/semantic-release/semantic-release) with a build running on Node 12 when a new commit is pushed to a `master` branch. See [Configuring a Workflow](https://help.github.com/en/articles/configuring-a-workflow) for additional configuration options.
|
||||
|
||||
```yaml
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-18.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npx semantic-release
|
||||
```
|
||||
|
||||
## Pushing `package.json` changes to a `master` branch
|
||||
|
||||
To keep `package.json` updated in the `master` branch, [`@semantic-release/git`](https://github.com/semantic-release/git) plugin can be used.
|
||||
|
||||
**Note**: Automatically populated `GITHUB_TOKEN` cannot be used if branch protection is enabled for the target branch. It is **not** advised to mitigate this limitation by overriding an automatically populated `GITHUB_TOKEN` variable with a [Personal Access Tokens](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line), as it poses a security risk. Since Secret Variables are available for Workflows triggered by any branch, it becomes a potential vector of attack, where a Workflow triggered from a non-protected branch can expose and use a token with elevated permissions, yielding branch protection insignificant. One can use Personal Access Tokens in trusted environments, where all developers should have the ability to perform administrative actions in the given repository and branch protection is enabled solely for convenience purposes, to remind about required reviews or CI checks.
|
||||
|
||||
If the risk is acceptible, some extra configuration is needed. The [actions/checkout `persist-credentials`](https://github.com/marketplace/actions/checkout#usage) option needs to be `false`, otherwise the generated `GITHUB_TOKEN` will interfere with the custom one. Example:
|
||||
|
||||
```yaml
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false # <--- this
|
||||
```
|
||||
|
||||
## Trigger semantic-release on demand
|
||||
|
||||
### Using GUI:
|
||||
You can use [Manual Triggers](https://github.blog/changelog/2020-07-06-github-actions-manual-triggers-with-workflow_dispatch/) for GitHub Actions.
|
||||
|
||||
### Using HTTP:
|
||||
Use [`repository_dispatch`](https://docs.github.com/en/actions/reference/events-that-trigger-workflows#repository_dispatch) event to have control on when to generate a release by making an HTTP request, e.g.:
|
||||
|
||||
```yaml
|
||||
name: Release
|
||||
on:
|
||||
repository_dispatch:
|
||||
types: [semantic-release]
|
||||
jobs:
|
||||
# ...
|
||||
```
|
||||
|
||||
To trigger a release, call (with a [Personal Access Tokens](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line) stored in `GITHUB_TOKEN` environment variable):
|
||||
|
||||
```
|
||||
$ curl -v -H "Accept: application/vnd.github.everest-preview+json" -H "Authorization: token ${GITHUB_TOKEN}" https://api.github.com/repos/[org-name-or-username]/[repository]/dispatches -d '{ "event_type": "semantic-release" }'
|
||||
```
|
||||
|
||||
### Using 3rd party apps:
|
||||
If you'd like to use a GitHub app to manage this instead of creating a personal access token, you could consider using a project like:
|
||||
|
||||
* [Actions Panel](https://www.actionspanel.app/) - A declaratively configured way for triggering GitHub Actions
|
||||
* [Action Button](https://github-action-button.web.app/#details) - A simple badge based mechanism for triggering GitHub Actions
|
||||
@@ -2,17 +2,19 @@
|
||||
|
||||
## Environment variables
|
||||
|
||||
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured with [Secret variables](https://docs.gitlab.com/ce/ci/variables/README.html#secret-variables).
|
||||
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured with [Protected variables](https://docs.gitlab.com/ce/ci/variables/README.html#protected-environment-variables).
|
||||
|
||||
**Note**: Make sure to configure your release branch as [protected](https://docs.gitlab.com/ce/user/project/protected_branches.html) in order for the CI/CD build to access the protected variables.
|
||||
|
||||
## Node project configuration
|
||||
|
||||
GitLab CI supports [Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html) allowing to test on multiple Node versions and publishing a release only when all test pass.
|
||||
|
||||
**Note**: The publish pipeline must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--83).
|
||||
**Note**: The publish pipeline must run a [Node >= 10.18 version](../support/FAQ.md#why-does-semantic-release-require-node-version--1018).
|
||||
|
||||
### `.gitlab-ci.yml` configuration for Node projects
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [GitLab CI - Configuration of your jobs with .gitlab-ci.yml](https://docs.gitlab.com/ee/ci/yaml/README.html) for additional configuration options.
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 10 and 12. See [GitLab CI - Configuration of your jobs with .gitlab-ci.yml](https://docs.gitlab.com/ee/ci/yaml/README.html) for additional configuration options.
|
||||
|
||||
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
|
||||
|
||||
@@ -25,25 +27,60 @@ stages:
|
||||
before_script:
|
||||
- npm install
|
||||
|
||||
node:6:
|
||||
image: node:6
|
||||
node:10:
|
||||
image: node:10
|
||||
stage: test
|
||||
script:
|
||||
- npm test
|
||||
|
||||
node:8:
|
||||
image: node:8
|
||||
node:12:
|
||||
image: node:12
|
||||
stage: test
|
||||
script:
|
||||
- npm test
|
||||
|
||||
publish:
|
||||
image: node:8
|
||||
image: node:12
|
||||
stage: release
|
||||
script:
|
||||
- npx semantic-release
|
||||
```
|
||||
|
||||
### `.gitlab-ci.yml` configuration for all projects
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 10 and 12. See [GitLab CI - Configuration of your jobs with .gitlab-ci.yml](https://docs.gitlab.com/ee/ci/yaml/README.html) for additional configuration options.
|
||||
|
||||
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
|
||||
|
||||
|
||||
```yaml
|
||||
# The release pipeline will run only on the master branch a commit is triggered
|
||||
stages:
|
||||
- release
|
||||
|
||||
release:
|
||||
image: node:10-buster-slim
|
||||
stage: release
|
||||
before_script:
|
||||
- apt-get update && apt-get install -y --no-install-recommends git-core ca-certificates
|
||||
- npm install -g semantic-release @semantic-release/gitlab
|
||||
script:
|
||||
- semantic-release
|
||||
only:
|
||||
- master
|
||||
|
||||
release:
|
||||
image: node:12-buster-slim
|
||||
stage: release
|
||||
before_script:
|
||||
- apt-get update && apt-get install -y --no-install-recommends git-core ca-certificates
|
||||
- npm install -g semantic-release @semantic-release/gitlab
|
||||
script:
|
||||
- semantic-release
|
||||
only:
|
||||
- master
|
||||
```
|
||||
|
||||
### `package.json` configuration
|
||||
|
||||
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
# Using semantic-release with [Jenkins CI](https://www.jenkins.io/doc/book/pipeline/)
|
||||
|
||||
## Environment variables
|
||||
|
||||
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [Jenkins Project Settings](https://www.jenkins.io/doc/pipeline/tour/environment/)..
|
||||
|
||||
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/getting-started.md#getting-started).
|
||||
|
||||
## Node.js project configuration
|
||||
|
||||
### `Jenkinsfile (Declarative Pipeline)` configuration for a Node.js job
|
||||
|
||||
**Note**: The publish pipeline must run a [Node >= 10.18 version](../support/FAQ.md#why-does-semantic-release-require-node-version--1018).
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 10.18. See [Jenkins documentation](https://www.jenkins.io/doc/) for additional configuration options.
|
||||
|
||||
The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
|
||||
|
||||
```yaml
|
||||
// The release stage in the pipeline will run only if the test stage in the pipeline is successful
|
||||
pipeline {
|
||||
agent any
|
||||
environment {
|
||||
GH_TOKEN = credentials('some-id')
|
||||
}
|
||||
stages {
|
||||
stage('Test') {
|
||||
steps {
|
||||
sh '''
|
||||
# Configure your test steps here (checkout, npm install, tests etc)
|
||||
npm install
|
||||
npm test
|
||||
'''
|
||||
}
|
||||
}
|
||||
stage('Release') {
|
||||
tools {
|
||||
nodejs "node 10.18"
|
||||
}
|
||||
steps {
|
||||
sh '''
|
||||
# Run optional required steps before releasing
|
||||
npx semantic-release
|
||||
'''
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `package.json` configuration for a Node job
|
||||
|
||||
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
|
||||
|
||||
```json
|
||||
{
|
||||
"devDependencies": {
|
||||
"semantic-release": "^15.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,156 @@
|
||||
# Publishing maintenance releases
|
||||
|
||||
This recipe will walk you through a simple example that uses Git branches and distribution channels to publish fixes and features for old versions of a package.
|
||||
|
||||
This example uses the **semantic-release** default configuration:
|
||||
- [branches](../usage/configuration.md#branches): `['+([0-9])?(.{+([0-9]),x}).x', 'master', 'next', 'next-major', {name: 'beta', prerelease: true}, {name: 'alpha', prerelease: true}]`
|
||||
- [plugins](../usage/configuration.md#plugins): `['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator', '@semantic-release/npm', '@semantic-release/github']`
|
||||
|
||||
## Initial release
|
||||
|
||||
We'll start by making the first commit of the project, with the code for the initial release and the message `feat: initial commit`. When pushing that commit, on `master` **semantic-release** will release the version `1.0.0` and make it available on the default distribution channel which is the dist-tag `@latest` for npm.
|
||||
|
||||
The Git history of the repository is:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
```
|
||||
|
||||
## Releasing a breaking change
|
||||
|
||||
We now decide to drop Node.js 6 support for our package, and require Node.js 8 or higher, which is a breaking change.
|
||||
|
||||
We commit that change with the message `feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required` to `master`. When pushing that commit, **semantic-release** will release the version `2.0.0` on the dist-tag `@latest`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
* feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required # => v2.0.0 on @latest
|
||||
```
|
||||
|
||||
## Releasing a feature for version 1.x users
|
||||
|
||||
One of our users request a new feature, however they cannot migrate to Node.js 8 or higher due to corporate policies.
|
||||
|
||||
If we were to push that feature on `master` and release it, the new version would require Node.js 8 or higher as the release would also contains the commit `feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required`.
|
||||
|
||||
Instead, we create the branch `1.x` from the tag `v1.0.0` with the command `git checkout -b 1.x v1.0.0` and we commit that feature with the message `feat: a feature` to the branch `1.x`. When pushing that commit, **semantic-release** will release the version `1.1.0` on the dist-tag `@release-1.x` so users who can't migrate to Node.js 8 or higher can benefit from it.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
* | feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required # => v2.0.0 on @latest
|
||||
| * feat: a feature # => v1.1.0 on @1.x
|
||||
```
|
||||
|
||||
## Releasing a bug fix for version 1.0.x users
|
||||
|
||||
Another user currently using version `1.0.0` reports a bug. They cannot migrate to Node.js 8 or higher and they also cannot migrate to `1.1.0` as they do not use the feature developed in `feat: a feature` and their corporate policies require to go through a costly quality insurance process for each `minor` upgrades.
|
||||
|
||||
In order to deliver the bug fix in a `patch` release, we create the branch `1.0.x` from the tag `v1.0.0` with the command `git checkout -b 1.0.x v1.0.0` and we commit that fix with the message `fix: a fix` to the branch `1.0.x`. When pushing that commit, **semantic-release** will release the version `1.0.1` on the dist-tag `@release-1.0.x` so users who can't migrate to `1.1.x` or `2.x` can benefit from it.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
* | feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required # => v2.0.0 on @latest
|
||||
| | \
|
||||
| * | feat: a feature # => v1.1.0 on @1.x
|
||||
| | * fix: a fix # => v1.0.1 on @1.0.x
|
||||
```
|
||||
|
||||
## Porting a bug fix from 1.0.x to 1.x
|
||||
|
||||
Now that we have released a fix in version `1.0.1` we want to make it available to `1.1.x` users as well.
|
||||
|
||||
To do so we need to merge the changes made on `1.0.x` (the commit `fix: a fix`) into the `1.x` branch. As `1.0.x` and `1.x` branches have diverged, this merge might require to resolve conflicts.
|
||||
|
||||
Once the conflicts are resolved and the merge commit is pushed to the branch `1.x`, **semantic-release** will release the version `1.1.1` on the dist-tag `@release-1.x` which contains both our feature and bug fix.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
* | feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required # => v2.0.0 on @latest
|
||||
| | \
|
||||
| * | feat: a feature # => v1.1.0 on @1.x
|
||||
| | * fix: a fix # => v1.0.1 on @1.0.x
|
||||
| | /|
|
||||
| * | Merge branch 1.0.x into 1.x # => v1.1.1 on @1.x
|
||||
```
|
||||
|
||||
## Porting bug fixes and features to master
|
||||
|
||||
Finally we want to make both our feature and bug fix available to users using the `@latest` dist-tag.
|
||||
|
||||
To do so we need to merge the changes made on `1.x` (the commits `feat: a feature` and `fix: a fix`) into `master`. As `1.x` and `master` branches have diverged, this merge might require to resolve conflicts.
|
||||
|
||||
Once the conflicts are resolved and the merge commit is pushed to `master`, **semantic-release** will release the version `2.1.0` on the dist-tag `@latest` which now contains the breaking change feature, the feature and the bug fix.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
* | feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required # => v2.0.0 on @latest
|
||||
| | \
|
||||
| * | feat: a feature # => v1.1.0 on @1.x
|
||||
| | * fix: a fix # => v1.0.1 on @1.0.x
|
||||
| | /|
|
||||
| * | Merge branch 1.0.x into 1.x # => v1.1.1 on @1.x
|
||||
| /| |
|
||||
* | | Merge branch 1.x into master # => v2.1.0 on @latest
|
||||
```
|
||||
|
||||
## Releasing a bug fix for version 2.1.0 users
|
||||
|
||||
One of our users using the version `2.1.0` version reports a bug.
|
||||
|
||||
We can simply commit the bug fix with the message `fix: another fix` to `master`. When pushing that commit, **semantic-release** will release the version `2.1.1` on the dist-tag `@latest`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
* | feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required # => v2.0.0 on @latest
|
||||
| | \
|
||||
| * | feat: a feature # => v1.1.0 on @1.x
|
||||
| | * fix: a fix # => v1.0.1 on @1.0.x
|
||||
| | /|
|
||||
| * | Merge branch 1.0.x into 1.x # => v1.1.1 on @1.x
|
||||
| /| |
|
||||
* | | Merge branch 1.x into master # => v2.1.0 on @latest
|
||||
* | | fix: another fix # => v2.1.1 on @latest
|
||||
```
|
||||
|
||||
## Porting a bug fix from master to 1.x
|
||||
|
||||
The bug fix `fix: another fix` also affects version `1.1.1` users, so we want to port it to the `1.x` branch.
|
||||
|
||||
To do so we need to cherry pick our fix commit made on `master` (`fix: another fix`) into `1.x` with `git checkout 1.x && git cherry-pick <sha of fix: another fix>`. As `master` and `1.x` branches have diverged, the cherry picking might require to resolve conflicts.
|
||||
|
||||
Once the conflicts are resolved and the commit is pushed to `1.x`, **semantic-release** will release the version `1.1.2` on the dist-tag `@release-1.x` which contains `feat: a feature`, `fix: a fix` and `fix: another fix` but not `feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
* | feat: drop Node.js 6 support \n\n BREAKING CHANGE: Node.js >= 8 required # => v2.0.0 on @latest
|
||||
| | \
|
||||
| * | feat: a feature # => v1.1.0 on @1.x
|
||||
| | * fix: a fix # => v1.0.1 on @1.0.x
|
||||
| | /|
|
||||
| * | Merge branch 1.0.x into 1.x # => v1.1.1 on @1.x
|
||||
| /| |
|
||||
* | | Merge branch 1.x into master # => v2.1.0 on @latest
|
||||
* | | fix: another fix # => v2.1.1 on @latest
|
||||
| | |
|
||||
| * | fix: another fix # => v1.1.2 on @1.x
|
||||
```
|
||||
@@ -0,0 +1,196 @@
|
||||
# Publishing pre-releases
|
||||
|
||||
This recipe will walk you through a simple example that uses pre-releases to publish beta versions while working on a future major release and then make only one release on the default distribution.
|
||||
|
||||
This example uses the **semantic-release** default configuration:
|
||||
- [branches](../usage/configuration.md#branches): `['+([0-9])?(.{+([0-9]),x}).x', 'master', 'next', 'next-major', {name: 'beta', prerelease: true}, {name: 'alpha', prerelease: true}]`
|
||||
- [plugins](../usage/configuration.md#plugins): `['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator', '@semantic-release/npm', '@semantic-release/github']`
|
||||
|
||||
## Initial release
|
||||
|
||||
We'll start by making the first commit of the project, with the code for the initial release and the message `feat: initial commit`. When pushing that commit, on `master` **semantic-release** will release the version `1.0.0` and make it available on the default distribution channel which is the dist-tag `@latest` for npm.
|
||||
|
||||
The Git history of the repository is:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
```
|
||||
|
||||
## Working on a future release
|
||||
|
||||
We now decide to work on a future major release, which will be composed of multiple features, some of them being breaking changes. We want to publish our package for each new feature developed for test purpose, however we do not want to increment our package version or make it available to our users until all the features are developed and tested.
|
||||
|
||||
To implement that workflow we can create the branch `beta` and commit our first feature there. When pushing that commit, **semantic-release** will publish the pre-release version `2.0.0-beta.1` on the dist-tag `@beta`. That allow us to run integration tests by installing our module with `npm install example-module@beta`. Other users installing with `npm install example-module` will still receive the version `1.0.0`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
```
|
||||
|
||||
We can continue to work on our future release by committing and pushing other features or bug fixes on the `beta` branch. With each push, **semantic-release** will publish a new pre-release on the dist-tag `@beta`, which allow us to run our integration tests.
|
||||
|
||||
With another feature, the Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
| * feat: second feature # => v2.0.0-beta.2 on @beta
|
||||
```
|
||||
|
||||
## Releasing a bug fix on the default distribution channel
|
||||
|
||||
In the meantime we can also continue to commit changes and release updates to our users.
|
||||
|
||||
For example, we can commit a bug fix with the message `fix: a fix` to `master`. When pushing that commit, **semantic-release** will release the version `1.0.1` on the dist-tag `@latest`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
| * feat: second feature # => v2.0.0-beta.2 on @beta
|
||||
* | fix: a fix # => v1.0.1 on @latest
|
||||
```
|
||||
|
||||
## Working on another future release
|
||||
|
||||
We now decide to work on another future major release, in parallel of the beta one, which will also be composed of multiple features, some of them being breaking changes.
|
||||
|
||||
To implement that workflow we can create the branch `alpha` from the branch `beta` and commit our first feature there. When pushing that commit, **semantic-release** will publish the pre-release version `3.0.0-alpha.1` on the dist-tag `@alpha`. That allow us to run integration tests by installing our module with `npm install example-module@alpha`. Other users installing with `npm install example-module` will still receive the version `1.0.0`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
| * feat: second feature # => v2.0.0-beta.2 on @beta
|
||||
* | fix: a fix # => v1.0.1 on @latest
|
||||
| | \
|
||||
| | * feat: first feature of other release \n\n BREAKING CHANGE: it breaks something # => v3.0.0-alpha.1 on @alpha
|
||||
```
|
||||
|
||||
We can continue to work on our future release by committing and pushing other features or bug fixes on the `alpha` branch. With each push, **semantic-release** will publish a new pre-release on the dist-tag `@alpha`, which allow us to run our integration tests.
|
||||
|
||||
With another feature, the Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
| * feat: second feature # => v2.0.0-beta.2 on @beta
|
||||
* | fix: a fix # => v1.0.1 on @latest
|
||||
| | \
|
||||
| | * feat: first feature of other release \n\n BREAKING CHANGE: it breaks something # => v3.0.0-alpha.1 on @alpha
|
||||
| | * feat: second feature of other release # => v3.0.0-alpha.2 on @alpha
|
||||
```
|
||||
|
||||
## Publishing the 2.0.0 beta release to the default distribution channel
|
||||
|
||||
Once we've developed and pushed all the feature we want to include in the future version `2.0.0` in the `beta` branch and all our tests are successful we can release it to our users.
|
||||
|
||||
To do so we need to merge our changes made on `beta` into `master`. As `beta` and `master` branches have diverged, this merge might require to resolve conflicts.
|
||||
|
||||
Once the conflicts are resolved and the merge commit is pushed to `master`, **semantic-release** will release the version `2.0.0` on the dist-tag `@latest`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
| * feat: second feature # => v2.0.0-beta.2 on @beta
|
||||
* | fix: a fix # => v1.0.1 on @latest
|
||||
| | \
|
||||
| | * feat: first feature of other release \n\n BREAKING CHANGE: it breaks something # => v3.0.0-alpha.1 on @alpha
|
||||
| | * feat: second feature of other release # => v3.0.0-alpha.2 on @alpha
|
||||
| /| |
|
||||
* | | Merge branch beta into master # => v2.0.0 on @latest
|
||||
```
|
||||
|
||||
## Publishing the 3.0.0 alpha release to the beta distribution channel
|
||||
|
||||
Now that we published our the version `2.0.0` that was previously in beta, we decide to promote the version `3.0.0` in alpha to beta.
|
||||
|
||||
To do so we need to merge our changes made on `alpha` into `beta`. There should be no conflict as `alpha` is strictly ahead of `master`.
|
||||
|
||||
Once the merge commit is pushed to `beta`, **semantic-release** will publish the pre-release version `3.0.0-beta.1` on the dist-tag `@beta`, which allow us to run our integration tests.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
| * feat: second feature # => v2.0.0-beta.2 on @beta
|
||||
* | fix: a fix # => v1.0.1 on @latest
|
||||
| | \
|
||||
| | * feat: first feature of other release \n\n BREAKING CHANGE: it breaks something # => v3.0.0-alpha.1 on @alpha
|
||||
| | * feat: second feature of other release # => v3.0.0-alpha.2 on @alpha
|
||||
| /| |
|
||||
* | | Merge branch beta into master # => v2.0.0 on @latest
|
||||
| | /|
|
||||
| * | Merge branch alpha into beta # => v3.0.0-beta.1 on @beta
|
||||
```
|
||||
|
||||
## Publishing the 3.0.0 beta release to the default distribution channel
|
||||
|
||||
Once we've developed and pushed all the feature we want to include in the future version `3.0.0` in the `beta` branch and all our tests are successful we can release it to our users.
|
||||
|
||||
To do so we need to merge our changes made on `beta` into `master`. As `beta` and `master` branches have diverged, this merge might require to resolve conflicts.
|
||||
|
||||
Once the conflicts are resolved and the merge commit is pushed to `master`, **semantic-release** will release the version `3.0.0` on the dist-tag `@latest`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
| * feat: second feature # => v2.0.0-beta.2 on @beta
|
||||
* | fix: a fix # => v1.0.1 on @latest
|
||||
| | \
|
||||
| | * feat: first feature of other release \n\n BREAKING CHANGE: it breaks something # => v3.0.0-alpha.1 on @alpha
|
||||
| | * feat: second feature of other release # => v3.0.0-alpha.2 on @alpha
|
||||
| /| |
|
||||
* | | Merge branch beta into master # => v2.0.0 on @latest
|
||||
| | /|
|
||||
| * | Merge branch alpha into beta # => v3.0.0-beta.1 on @beta
|
||||
| /| |
|
||||
* | | Merge branch beta into master # => v3.0.0 on @latest
|
||||
```
|
||||
|
||||
## Working on a third future release
|
||||
|
||||
We can now start to work on a new future major release, version `4.0.0`, on the `@beta` distribution channel.
|
||||
|
||||
To do so we first need to update the `beta` branch with all the changes from `master` (the commits `fix: a fix`). As `beta` and `master` branches have diverged, this merge might require to resolve conflicts.
|
||||
|
||||
We can now commit our new feature on `beta`. When pushing that commit, **semantic-release** will publish the pre-release version `3.1.0-beta.1` on the dist-tag `@beta`. That allow us to run integration tests by installing our module with `npm install example-module@beta`. Other users installing with `npm install example-module` will still receive the version `3.0.0`.
|
||||
|
||||
The Git history of the repository is now:
|
||||
|
||||
```
|
||||
* feat: initial commit # => v1.0.0 on @latest
|
||||
| \
|
||||
| * feat: first feature \n\n BREAKING CHANGE: it breaks something # => v2.0.0-beta.1 on @beta
|
||||
| * feat: second feature # => v2.0.0-beta.2 on @beta
|
||||
* | fix: a fix # => v1.0.1 on @latest
|
||||
| | \
|
||||
| | * feat: first feature of other release \n\n BREAKING CHANGE: it breaks something # => v3.0.0-alpha.1 on @alpha
|
||||
| | * feat: second feature of other release # => v3.0.0-alpha.2 on @alpha
|
||||
| /| |
|
||||
* | | Merge branch beta into master # => v2.0.0 on @latest
|
||||
| | /|
|
||||
| * | Merge branch alpha into beta # => v3.0.0-beta.1 on @beta
|
||||
| /| |
|
||||
* | | Merge branch beta into master # => v3.0.0 on @latest
|
||||
| \| |
|
||||
| * | Merge branch master into beta
|
||||
| * | feat: new feature # => v3.1.0-beta.1 on @beta
|
||||
```
|
||||
@@ -92,4 +92,6 @@ jobs:
|
||||
# Use nvm to install and use the Node LTS version (nvm is installed on all Travis images)
|
||||
- nvm install lts/*
|
||||
- npx semantic-release
|
||||
on:
|
||||
all_branches: true
|
||||
```
|
||||
|
||||
+18
-12
@@ -2,12 +2,14 @@
|
||||
|
||||
## Why is the `package.json`’s version not updated in my repository?
|
||||
|
||||
**semantic-release** takes care of updating the `package.json`’s version before publishing to [npm](https://www.npmjs.com).
|
||||
[`@semantic-release/npm`](https://github.com/semantic-release/npm) takes care of updating the `package.json`’s version before publishing to [npm](https://www.npmjs.com).
|
||||
|
||||
By default, only the published package will contains the version, which is the only place where it is *really* required, but the updated `package.json` will not be pushed to the Git repository
|
||||
By default, only the published package will contain the version, which is the only place where it is *really* required, but the updated `package.json` will not be pushed to the Git repository
|
||||
|
||||
However, the [`@semantic-release/git`](https://github.com/semantic-release/git) plugin can be used to push the updated `package.json` as well as other files to the Git repository.
|
||||
|
||||
If you wish to only update the `package.json` and push via Git you can set the project to `"private": true,` within your `package.json` to prevent publishing to [npm](https://www.npmjs.com). This can be useful for using **semantic-release** with a non-node project.
|
||||
|
||||
## How can I use a npm build script that requires the `package.json`’s version ?
|
||||
|
||||
The `package.json`’s version will be updated by the `semantic-release` command just before publishing to [npm](https://www.npmjs.com), therefore it won't be available for scripts ran before the `semantic-release` command.
|
||||
@@ -38,7 +40,7 @@ Yes with the [dry-run options](../usage/configuration.md#dryrun) which prints to
|
||||
|
||||
## Can I use semantic-release with Yarn?
|
||||
|
||||
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation and run multiple CI jobs with different versions, the `yarn install` command will fail on jobs running with Node < 8 as **semantic-release** requires [Node >= 8.3](#why-does-semantic-release-require-node-version--83) and specifies it in its `package.json`s [`engines`](https://docs.npmjs.com/files/package.json#engines) key.
|
||||
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation and run multiple CI jobs with different versions, the `yarn install` command will fail on jobs running with Node < 8 as **semantic-release** requires [Node >= 10.18](#why-does-semantic-release-require-node-version--1018) and specifies it in its `package.json`s [`engines`](https://docs.npmjs.com/files/package.json#engines) key.
|
||||
|
||||
The recommended solution is to use the [Yarn](https://yarnpkg.com) [--ignore-engines](https://yarnpkg.com/en/docs/cli/install#toc-yarn-install-ignore-engines) option to install the project dependencies on the CI environment, so Yarn will ignore the **semantic-release**'s `engines` key:
|
||||
|
||||
@@ -48,7 +50,7 @@ $ yarn install --ignore-engines
|
||||
|
||||
**Note**: Several CI services use Yarn by default if your repository contains a `yarn.lock` file. So you should override the install step to specify `yarn install --ignore-engines`.
|
||||
|
||||
Alternatively you can use a [global](../usage/installation.md#global-installation) **semantic-release** installation and make sure to install and run the `semantic-release` command only in a CI jobs running with Node >= 8.3.
|
||||
Alternatively you can use a [global](../usage/installation.md#global-installation) **semantic-release** installation and make sure to install and run the `semantic-release` command only in a CI jobs running with Node >= 10.18.
|
||||
|
||||
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can switch to Node 8 before installing and running the `semantic-release` command:
|
||||
|
||||
@@ -73,7 +75,7 @@ Yes, **semantic-release** is a Node CLI application but it can be used to publis
|
||||
To publish a non-Node package (without a `package.json`) you would need to:
|
||||
- Use a [global](../usage/installation.md#global-installation) **semantic-release** installation
|
||||
- Set **semantic-release** [options](../usage/configuration.md#options) via [CLI arguments or rc file](../usage/configuration.md#configuration)
|
||||
- Make sure your CI job executing the `semantic-release` command has access to [Node >= 8](#why-does-semantic-release-require-node-version--83) to execute the `semantic-release` command
|
||||
- Make sure your CI job executing the `semantic-release` command has access to [Node >= 10.18](#why-does-semantic-release-require-node-version--1018) to execute the `semantic-release` command
|
||||
|
||||
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
|
||||
|
||||
@@ -141,11 +143,11 @@ See the [`@semantic-release/npm`](https://github.com/semantic-release/npm#semant
|
||||
|
||||
If you have introduced a breaking bug in a release you have 2 options:
|
||||
- If you have a fix immediately ready, commit and push it (or merge it via a pull request) to the release branch
|
||||
- Otherwise [revert the commit](https://git-scm.com/docs/git-revert) that introduced the bug and push the revert commit (or merge it via a pull request) to the release branch
|
||||
- Otherwise, [revert the commit](https://git-scm.com/docs/git-revert) that introduced the bug and push the revert commit (or merge it via a pull request) to the release branch
|
||||
|
||||
In both cases **semantic-release** will publish a new release, so your package users' will get the fixed/reverted version.
|
||||
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 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.
|
||||
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 release. 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.
|
||||
|
||||
@@ -222,7 +224,7 @@ If you need more control over the timing of releases, see [Triggering a release]
|
||||
|
||||
This is not supported by **semantic-release** as it's not considered a good practice, mostly because [Semantic Versioning](https://semver.org) rules applies differently to major version zero.
|
||||
|
||||
In early development phase when your package is not ready for production yet we recommend to publish releases on a distribution channel (for example npm’s [dist-tags](https://docs.npmjs.com/cli/dist-tag)) or to develop on a `dev` branch and merge it to `master` periodically. See [Triggering a release](../../README.md#triggering-a-release) for more details on those solutions.
|
||||
If your project is under heavy development, with frequent breaking changes, and is not production ready yet we recommend [publishing pre-releases](../recipes/pre-releases.md#publishing-pre-releases).
|
||||
|
||||
See [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2) for more details on [Semantic Versioning](https://semver.org) and the recommendation to start at version `1.0.0`.
|
||||
|
||||
@@ -232,11 +234,15 @@ See [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/i
|
||||
|
||||
In addition the [verify conditions step](../../README.md#release-steps) verifies that all necessary conditions for proceeding with a release are met, and a new release will be performed [only if all your tests pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
|
||||
|
||||
## Why does semantic-release require Node version >= 8.3?
|
||||
## Why does semantic-release require Node version >= 10.18?
|
||||
|
||||
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which **requires Node version 8.3 or higher**.
|
||||
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which **requires Node version 10.18 or higher**.
|
||||
|
||||
See [Node version requirement](../support/node-version.md#node-version-requirement) for more details and solutions.
|
||||
See [Node version requirement](./node-version.md#node-version-requirement) for more details and solutions.
|
||||
|
||||
## Why does semantic-release require Git version >= 2.7.1?
|
||||
|
||||
**semantic-release** uses Git CLI commands to read information about the repository such as branches, commit history and tags. Certain commands and options (such as [the `--merged` option of the `git tag` command](https://git-scm.com/docs/git-tag/2.7.0#git-tag---no-mergedltcommitgt) or bug fixes related to `git ls-files`) used by **semantic-release** are only available in Git version 2.7.1 and higher.
|
||||
|
||||
## What is npx?
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Node version requirement
|
||||
|
||||
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which requires **requires Node version 8.3 or higher**.
|
||||
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which requires **requires Node version 10 or higher**.
|
||||
|
||||
**semantic-release** is meant to be used in a CI environment as a development support tool, not as a production dependency. Therefore the only constraint is to run the `semantic-release` in a CI environment providing Node 8 or higher.
|
||||
|
||||
@@ -8,9 +8,9 @@ See our [Node Support Policy](node-support-policy.md) for our long-term promise
|
||||
|
||||
## Recommended solution
|
||||
|
||||
### Run at least one CI job with Node >= 8.3
|
||||
### Run at least one CI job with Node >= 10.18
|
||||
|
||||
The recommended approach is to run the `semantic-release` command from a CI job running on Node 8.3 or higher. This can either be a job used by your project to test on Node >= 8.3 or a dedicated job for the release steps.
|
||||
The recommended approach is to run the `semantic-release` command from a CI job running on Node 10.18 or higher. This can either be a job used by your project to test on Node >= 10.18 or a dedicated job for the release steps.
|
||||
|
||||
See [CI configuration](../usage/ci-configuration.md) and [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
|
||||
- ["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)
|
||||
- ["Series - Semantic Release Automation" - Abdelrahman Wahdan](https://dev.to/abdelrahmanahmed/semantic-release-and-how-to-automate-it-part-1-4pa2)
|
||||
|
||||
## Tutorials
|
||||
|
||||
|
||||
@@ -54,3 +54,16 @@ $ git branch --contains <tag name>
|
||||
$ git tag -d <tag name>
|
||||
$ git push origin :refs/tags/<tag name>
|
||||
```
|
||||
|
||||
## release not found release branch after `git push --force`
|
||||
|
||||
**semantic-release** is using both [git tags](https://git-scm.com/docs/git-tag) and [git notes](https://git-scm.com/docs/git-notes) to store information about which releases happened in which branch.
|
||||
|
||||
After a git history rewrite due to a `git push --force`, the git tags and notes referencing the commits that were rewritten are lost.
|
||||
|
||||
To recover from that situation, do the following:
|
||||
|
||||
1. Delete the tag(s) for the release(s) that have been lost from the git history. You can delete each tag from remote using `git push origin :[TAG NAME]`, e.g. `git push origin :v2.0.0-beta.1`. You can delete tags locally using `git tag -d [TAG NAME]`, e.g. `git tag -d v2.0.0-beta.1`.
|
||||
2. Re-create the tags locally: `git tag [TAG NAME] [COMMIT HASH]`, where `[COMMIT HASH]` is the new commit that created the release for the lost tag. E.g. `git tag v2.0.0-beta.1 abcdef0`
|
||||
3. Re-create the git notes for each release tag, e.g. `git notes --ref semantic-release add -f -m '{"channels":["beta"]}' v3.0.0-beta.1`. If the release was also published in the default channel (usually `master`), then set the first channel to `null`, e.g. `git notes --ref semantic-release add -f -m '{"channels":[null, "beta"]}'
|
||||
4. Push the local notes: `git push --force origin refs/notes/semantic-release`. The `--force` is needed after the rebase. Be careful.
|
||||
|
||||
@@ -5,4 +5,5 @@
|
||||
- [CI Configuration](ci-configuration.md#ci-configuration)
|
||||
- [Configuration](configuration.md#configuration)
|
||||
- [Plugins](plugins.md)
|
||||
- [Workflow configuration](workflow-configuration.md)
|
||||
- [Shareable configurations](shareable-configurations.md)
|
||||
|
||||
@@ -2,23 +2,37 @@
|
||||
|
||||
## 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), [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).
|
||||
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.
|
||||
Here is a few example of the CI services that can be used to achieve this:
|
||||
- [Travis Build Stages](https://docs.travis-ci.com/user/build-stages)
|
||||
- [CircleCI Workflows](https://circleci.com/docs/2.0/workflows)
|
||||
- [GitHub Actions](https://github.com/features/actions)
|
||||
- [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)
|
||||
- [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.
|
||||
|
||||
## Authentication
|
||||
|
||||
### Push access to the remote repository
|
||||
|
||||
**semantic-release** requires push access to the project Git repository in order to create [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). The Git authentication can be set with one of the following environment variables:
|
||||
|
||||
| Variable | Description |
|
||||
|---------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `GH_TOKEN` or `GITHUB_TOKEN` | A GitHub [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line). |
|
||||
| `GL_TOKEN` or `GITLAB_TOKEN` | A GitLab [personal access token](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html). |
|
||||
| `BB_TOKEN` or `BITBUCKET_TOKEN` | A Bitbucket [personal access token](https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html). |
|
||||
| `GIT_CREDENTIALS` | [URL encoded](https://en.wikipedia.org/wiki/Percent-encoding) Git username and password in the format `<username>:<password>`. The username and password must each be individually URL encoded, not the `:` separating them. |
|
||||
| Variable | Description |
|
||||
|-------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `GH_TOKEN` or `GITHUB_TOKEN` | A GitHub [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line). |
|
||||
| `GL_TOKEN` or `GITLAB_TOKEN` | A GitLab [personal access token](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html). |
|
||||
| `BB_TOKEN` or `BITBUCKET_TOKEN` | A Bitbucket [personal access token](https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html). |
|
||||
| `BB_TOKEN_BASIC_AUTH` or `BITBUCKET_TOKEN_BASIC_AUTH` | A Bitbucket [personal access token](https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html) with basic auth support. For clearification `user:token` has to be the value of this env. |
|
||||
| `GIT_CREDENTIALS` | [URL encoded](https://en.wikipedia.org/wiki/Percent-encoding) Git username and password in the format `<username>:<password>`. The username and password must each be individually URL encoded, not the `:` separating them. |
|
||||
|
||||
Alternatively the Git authentication can be set up via [SSH keys](../recipes/git-auth-ssh-keys.md).
|
||||
|
||||
### Authentication for plugins
|
||||
|
||||
Most **semantic-release** [plugins](plugins.md) require setting up authentication in order to publish to a package manager registry. The default [@semantic-release/npm](https://github.com/semantic-release/npm#environment-variables) and [@semantic-release/github](https://github.com/semantic-release/github#environment-variables) plugins require the following environment variables:
|
||||
|
||||
| Variable | Description |
|
||||
@@ -31,3 +45,5 @@ 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.
|
||||
|
||||
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on how to configure environment variables in your CI service.
|
||||
|
||||
**Note**: The environment variables `GH_TOKEN`, `GITHUB_TOKEN`, `GL_TOKEN` and `GITLAB_TOKEN` can be used for both the Git authentication and the API authentication required by [@semantic-release/github](https://github.com/semantic-release/github) and [@semantic-release/gitlab](https://github.com/semantic-release/gitlab).
|
||||
|
||||
+33
-27
@@ -1,17 +1,17 @@
|
||||
# Configuration
|
||||
|
||||
**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))
|
||||
- Git repository ([URL](#repositoryurl) and options [release branches](#branches) and [tag format](#tagformat))
|
||||
- Plugins [declaration](#plugins) and options
|
||||
- Run mode ([debug](#debug), [dry run](#dryrun) and [local (no CI)](#ci))
|
||||
|
||||
All of these options can be configured directly or by extending a [shareable configuration](shareable-configurations.md).
|
||||
All of these options can be configured through config file, CLI arguments 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).
|
||||
|
||||
## Configuration file
|
||||
|
||||
**semantic-release**’s [options](#options), mode and [plugins](plugins.md) can be set via:
|
||||
**semantic-release**’s [options](#options), mode and [plugins](plugins.md) can be set via either:
|
||||
- A `.releaserc` file, written in YAML or JSON, with optional extensions: .`yaml`/`.yml`/`.json`/`.js`
|
||||
- A `release.config.js` file that exports an object
|
||||
- A `release` key in the project's `package.json` file
|
||||
@@ -20,34 +20,25 @@ Alternatively, some options can be set via CLI arguments.
|
||||
|
||||
The following three examples are the same.
|
||||
|
||||
Via `release` key in the project's `package.json` file:
|
||||
|
||||
- Via `release` key in the project's `package.json` file:
|
||||
```json
|
||||
{
|
||||
"release": {
|
||||
"branch": "next"
|
||||
"branches": ["master", "next"]
|
||||
}
|
||||
}
|
||||
```
|
||||
```bash
|
||||
$ semantic-release
|
||||
```
|
||||
|
||||
Via `.releaserc` file:
|
||||
|
||||
- Via `.releaserc` file:
|
||||
```json
|
||||
{
|
||||
"branch": "next"
|
||||
"branches": ["master", "next"]
|
||||
}
|
||||
```
|
||||
```bash
|
||||
$ semantic-release
|
||||
```
|
||||
|
||||
Via CLI argument:
|
||||
|
||||
- Via CLI argument:
|
||||
```bash
|
||||
$ semantic-release --branch next
|
||||
$ semantic-release --branches next
|
||||
```
|
||||
|
||||
**Note**: CLI arguments take precedence over options configured in the configuration file.
|
||||
@@ -67,13 +58,25 @@ List of modules or file paths containing a [shareable configuration](shareable-c
|
||||
|
||||
**Note**: Options defined via CLI arguments or in the configuration file will take precedence over the ones defined in any shareable configuration.
|
||||
|
||||
### branch
|
||||
### branches
|
||||
|
||||
Type: `String`<br>
|
||||
Default: `master`<br>
|
||||
CLI arguments: `-b`, `--branch`
|
||||
Type: `Array`, `String`, `Object`<br>
|
||||
Default: `['+([0-9])?(.{+([0-9]),x}).x', 'master', 'next', 'next-major', {name: 'beta', prerelease: true}, {name: 'alpha', prerelease: true}]`<br>
|
||||
CLI arguments: `--branches`
|
||||
|
||||
The branch on which releases should happen.
|
||||
The branches on which releases should happen. By default **semantic-release** will release:
|
||||
- regular releases to the default distribution channel from the branch `master`
|
||||
- regular releases to a distribution channel matching the branch name from any existing branch with a name matching a maintenance release range (`N.N.x` or `N.x.x` or `N.x` with `N` being a number)
|
||||
- regular releases to the `next` distribution channel from the branch `next` if it exists
|
||||
- regular releases to the `next-major` distribution channel from the branch `next-major` if it exists
|
||||
- prereleases to the `beta` distribution channel from the branch `beta` if it exists
|
||||
- prereleases to the `alpha` distribution channel from the branch `alpha` if it exists
|
||||
|
||||
**Note**: If your repository does not have a release branch, then **semantic-release** will fail with an `ERELEASEBRANCHES` error message. If you are using the default configuration, you can fix this error by pushing a `master` branch.
|
||||
|
||||
**Note**: Once **semantic-release** is configured, any user with the permission to push commits on one of those branches will be able to publish a release. It is recommended to protect those branches, for example with [GitHub protected branches](https://docs.github.com/github/administering-a-repository/about-protected-branches).
|
||||
|
||||
See [Workflow configuration](workflow-configuration.md#workflow-configuration) for more details.
|
||||
|
||||
### repositoryUrl
|
||||
|
||||
@@ -113,7 +116,9 @@ Type: `Boolean`<br>
|
||||
Default: `false` if running in a CI environment, `true` otherwise<br>
|
||||
CLI arguments: `-d`, `--dry-run`
|
||||
|
||||
Dry-run mode, skip publishing, print next version and release notes.
|
||||
The objective of the dry-run mode is to get a preview of the pending release. Dry-run mode skips the following steps: prepare, publish, success and fail. In addition to this it prints the next version and release notes to the console.
|
||||
|
||||
**Note**: The Dry-run mode verifies the repository push permission, even though nothing will be pushed. The verification is done to help user to figure out potential configuration issues.
|
||||
|
||||
### ci
|
||||
|
||||
@@ -146,7 +151,8 @@ Output debugging information. This can also be enabled by setting the `DEBUG` en
|
||||
|
||||
## 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`).
|
||||
**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 branches](#branches) 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.
|
||||
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
# Getting started
|
||||
|
||||
In order to use **semantic-release** you must follow these steps:
|
||||
- [Install](./installation.md#installation) **semantic-release** in your project
|
||||
- Configure your Continuous Integration service to [run **semantic-release**](./ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
|
||||
- Configure your Git repository and package manager repository [authentication](ci-configuration.md#authentication) in your Continuous Integration service
|
||||
- Configure **semantic-release** [options and plugins](./configuration.md#configuration)
|
||||
|
||||
1. [Install](./installation.md#installation) **semantic-release** in your project
|
||||
2. Configure your Continuous Integration service to [run **semantic-release**](./ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
|
||||
3. Configure your Git repository and package manager repository [authentication](ci-configuration.md#authentication) in your Continuous Integration service
|
||||
4. Configure **semantic-release** [options and plugins](./configuration.md#configuration)
|
||||
|
||||
Alternatively those steps can be easily done with the [**semantic-release** interactive CLI](https://github.com/semantic-release/cli):
|
||||
|
||||
```bash
|
||||
npm install -g semantic-release-cli
|
||||
|
||||
cd your-module
|
||||
semantic-release-cli setup
|
||||
npx semantic-release-cli setup
|
||||
```
|
||||
|
||||

|
||||
|
||||
@@ -24,6 +24,6 @@ For other type of projects we recommend installing **semantic-release** directly
|
||||
$ npx semantic-release
|
||||
```
|
||||
|
||||
**Note:** For a global installation, it's recommended to specify the major **semantic-release** version to install (for example with with `npx semantic-release@15`, or `npm install -g semantic-release@15`). This way your build will not automatically use the next major **semantic-release** release that could possibly break your build. You will have to upgrade manually when a new major version is released.
|
||||
**Note**: For a global installation, it's recommended to specify the major **semantic-release** version to install (for example with with `npx semantic-release@15`). This way your build will not automatically use the next major **semantic-release** release that could possibly break your build. You will have to upgrade manually when a new major version is released.
|
||||
|
||||
**Note:** `npx` is a tool bundled with `npm@>=5.2.0`. It is used to conveniently install the semantic-release binary and to execute it. See [What is npx](../support/FAQ.md#what-is-npx) for more details.
|
||||
**Note**: `npx` is a tool bundled with `npm@>=5.2.0`. It is used to conveniently install the semantic-release binary and to execute it. See [What is npx](../support/FAQ.md#what-is-npx) for more details.
|
||||
|
||||
+15
-12
@@ -19,22 +19,25 @@ A plugin is a npm module that can implement one or more of the following steps:
|
||||
|
||||
## Plugins installation
|
||||
|
||||
These five plugins are already part of **semantic-release** and don't have to be installed separately:
|
||||
### Default plugins
|
||||
|
||||
These four plugins are already part of **semantic-release** and are listed in order of execution. They do not have to be installed separately:
|
||||
```
|
||||
"@semantic-release/commit-analyzer"
|
||||
"@semantic-release/error"
|
||||
"@semantic-release/github"
|
||||
"@semantic-release/npm"
|
||||
"@semantic-release/commit-analyzer"
|
||||
"@semantic-release/release-notes-generator"
|
||||
"@semantic-release/npm"
|
||||
"@semantic-release/github"
|
||||
```
|
||||
|
||||
### Additional plugins
|
||||
|
||||
[Additional plugins](../extending/plugins-list.md) have to be installed via npm:
|
||||
|
||||
```bash
|
||||
$ npm install @semantic-release/git @semantic-release/changelog -D
|
||||
```
|
||||
|
||||
## Plugins configuration
|
||||
## Plugins declaration and execution order
|
||||
|
||||
Each plugin must be configured with the [`plugins` options](./configuration.md#plugins) by specifying the list of plugins by npm module name.
|
||||
|
||||
@@ -44,9 +47,9 @@ Each plugin must be configured with the [`plugins` options](./configuration.md#p
|
||||
}
|
||||
```
|
||||
|
||||
## Plugin ordering
|
||||
**Note:** If the `plugins` option is defined, it overrides the default plugin list, rather than merging with it.
|
||||
|
||||
For each [release step](../../README.md#release-steps) the plugins that implement that step will be executed in the order in which the are defined.
|
||||
For each [release step](../../README.md#release-steps) the plugins that implement that step will be executed in the order in which they are defined.
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -62,15 +65,15 @@ For each [release step](../../README.md#release-steps) the plugins that implemen
|
||||
With this configuration **semantic-release** will:
|
||||
- execute the `verifyConditions` implementation of `@semantic-release/npm` then `@semantic-release/git`
|
||||
- execute the `analyzeCommits` implementation of `@semantic-release/commit-analyzer`
|
||||
- execute the `prepare` implementation of `@semantic-release/npm` then `@semantic-release/git`
|
||||
- execute the `generateNotes` implementation of `@semantic-release/release-notes-generator`
|
||||
- execute the `prepare` implementation of `@semantic-release/npm` then `@semantic-release/git`
|
||||
- execute the `publish` implementation of `@semantic-release/npm`
|
||||
|
||||
## Plugin options
|
||||
## Plugin options configuration
|
||||
|
||||
A plugin options can specified by wrapping the name and an options object in an array. Options configured this way will be passed only to that specific plugin.
|
||||
A plugin configuration can be specified by wrapping the name and an options object in an array. Options configured this way will be passed only to that specific plugin.
|
||||
|
||||
Global plugin options can defined at the root of the **semantic-release** configuration object. Options configured this way will be passed to all plugins.
|
||||
Global plugin configuration can be defined at the root of the **semantic-release** configuration object. Options configured this way will be passed to all plugins.
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
# Workflow configuration
|
||||
|
||||
**semantic-release** allow to manage and automate complex release workflow, based on multiple Git branches and distribution channels. This allow to:
|
||||
- Distributes certain releases to a particular group of users via distribution channels
|
||||
- Manage the availability of releases on distribution channels via branches merge
|
||||
- Maintain multiple lines of releases in parallel
|
||||
- Work on large future releases outside the normal flow of one version increment per Git push
|
||||
|
||||
See [Release workflow recipes](../recipes/README.md#release-workflow) for detailed examples.
|
||||
|
||||
The release workflow is configured via the [branches option](./configuration.md#branches) which accepts a single or an array of branch definitions.
|
||||
Each branch can be defined either as a string, a [glob](https://github.com/micromatch/micromatch#matching-features) or an object. For string and glob definitions each [property](#branches-properties) will be defaulted.
|
||||
|
||||
A branch can defined as one of three types:
|
||||
- [release](#release-branches): to make releases on top of the last version released
|
||||
- [maintenance](#maintenance-branches): to make release on top of an old release
|
||||
- [pre-release](#pre-release-branches): to make pre-releases
|
||||
|
||||
The type of the branch is automatically determined based on naming convention and/or [properties](#branches-properties).
|
||||
|
||||
## Branches properties
|
||||
|
||||
| Property | Branch type | Description | Default |
|
||||
|--------------|-------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------|
|
||||
| `name` | All | **Required.** The Git branch holding the commits to analyze and the code to release. See [name](#name). | - The value itself if defined as a `String` or the matching branches name if defined as a glob. |
|
||||
| `channel` | All | The distribution channel on which to publish releases from this branch. Set to `false` to force the default distribution channel instead of using the default. See [channel](#channel). | `undefined` for the first release branch, the value of `name` for subsequent ones. |
|
||||
| `range` | [maintenance](#maintenance-branches) only | **Required unless `name` is formatted like `N.N.x` or `N.x` (`N` is a number).** The range of [semantic versions](https://semver.org) to support on this branch. See [range](#range). | The value of `name`. |
|
||||
| `prerelease` | [pre-release](#pre-release-branches) only | **Required.** The pre-release detonation to append to [semantic versions](https://semver.org) released from this branch. See [prerelease](#prerelease). | - |
|
||||
|
||||
### name
|
||||
|
||||
A `name` is required for any type of branch.
|
||||
It can be defined as a [glob](https://github.com/micromatch/micromatch#matching-features) in which case the definition will be expanded to one per matching branch existing in the repository.
|
||||
|
||||
If `name` doesn't match to any branch existing in the repository, the definition will be ignored. For example the default configuration includes the definition `next` and `next-major` which will become active only when the branches `next` and/or `next-major` are created in the repository. This allow to define your workflow once with all potential branches you might use and have the effective configuration evolving as you create new branches.
|
||||
|
||||
For example the configuration `['+([0-9])?(.{+([0-9]),x}).x', 'master', 'next']` will be expanded as:
|
||||
```js
|
||||
{
|
||||
branches: [
|
||||
{name: '1.x', range: '1.x', channel: '1.x'}, // Only after the `1.x` is created in the repo
|
||||
{name: '2.x', range: '2.x', channel: '2.x'}, // Only after the `2.x` is created in the repo
|
||||
{name: 'master'},
|
||||
{name: 'next', channel: 'next'}, // Only after the `next` is created in the repo
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### channel
|
||||
|
||||
The `channel` can be defined for any branch type. By default releases will be done on the default distribution channel (for example the `@latest` [dist-tag](https://docs.npmjs.com/cli/dist-tag) for npm) for the first [release branch](#release-branches) and on a distribution channel named based on the branch `name` for any other branch.
|
||||
If the `channel` property is set to `false` the default channel will be used.
|
||||
|
||||
The value of `channel`, if defined as a string, is generated with [Lodash template](https://lodash.com/docs#template) with the variable `name` available.
|
||||
|
||||
For example the configuration `['master', {name: 'next', channel: 'channel-${name}'}]` will be expanded as:
|
||||
```js
|
||||
{
|
||||
branches: [
|
||||
{name: 'master'}, // `channel` is undefined so the default distribution channel will be used
|
||||
{name: 'next', channel: 'channel-next'}, // `channel` is built with the template `channel-${name}`
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### range
|
||||
|
||||
A `range` only applies to maintenance branches, is required and must be formatted like `N.N.x` or `N.x` (`N` is a number). In case the `name` is formatted as a range (for example `1.x` or `1.5.x`) the branch will be considered a maintenance branch and the `name` value will be used for the `range`.
|
||||
|
||||
For example the configuration `['1.1.x', '1.2.x', 'master']` will be expanded as:
|
||||
```js
|
||||
{
|
||||
branches: [
|
||||
{name: '1.1.x', range: '1.1.x', channel: '1.1.x'},
|
||||
{name: '1.2.x', range: '1.2.x', channel: '1.2.x'},
|
||||
{name: 'master'},
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### prerelease
|
||||
|
||||
A `prerelease` property applies only to pre-release branches and the `prerelease` value must be valid per the [Semantic Versioning Specification](https://semver.org/#spec-item-9). It will determine the name of versions (for example if `prerelease` is set to `beta` the version be formatted like `2.0.0-beta.1`, `2.0.0-beta.2` etc...).
|
||||
If the `prerelease` property is set to `true` the `name` value will be used.
|
||||
|
||||
The value of `prerelease`, if defined as a string, is generated with [Lodash template](https://lodash.com/docs#template) with the variable `name` available.
|
||||
|
||||
For example the configuration `['master', {name: 'pre/rc', prerelease: '${name.replace(/^pre\\//g, "")}'}, {name: 'beta', prerelease: true}]` will be expanded as:
|
||||
```js
|
||||
{
|
||||
branches: [
|
||||
{name: 'master'},
|
||||
{name: 'pre/rc', channel: 'pre/rc', prerelease: 'rc'}, // `prerelease` is built with the template `${name.replace(/^pre\\//g, "")}`
|
||||
{name: 'beta', channel: 'beta', prerelease: 'beta'}, // `prerelease` is set to `beta` as it is the value of `name`
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Branch types
|
||||
|
||||
### Release branches
|
||||
|
||||
A release branch is the base type of branch used by **semantic-release** that allows to publish releases with a [semantic version](https://semver.org), optionally on a specific distribution channel. Distribution channels (for example [npm dist-tags](https://docs.npmjs.com/cli/dist-tag) or [Chrome release channels](https://www.chromium.org/getting-involved/dev-channel)) are a way to distribute new releases only to a subset of users in order to get early feedback. Later on, those releases can be added to the general distribution channel to be made available to all users.
|
||||
|
||||
**semantic-release** will automatically add releases to the corresponding distribution channel when code is [merged from a release branch to another](#merging-into-a-release-branch).
|
||||
|
||||
A project must define a minimum of 1 release branch and can have a maximum of 3. The order of the release branch definitions is significant, as versions released on a given branch must always be higher than the last release made on the previous branch. This allow to avoid situation that would lead to an attempt to publish releases with the same version number but different codebase. When multiple release branches are configured and a commit that would create a version conflict is pushed, **semantic-release** will not perform the release and will throw an `EINVALIDNEXTVERSION` error, listing the problematic commits and the valid branches on which to move them.
|
||||
|
||||
**Note:** With **semantic-release** as with most package managers, a release version must be unique, independently of the distribution channel on which it is available.
|
||||
|
||||
See [publishing on distribution channels recipe](../recipes/distribution-channels.md) for a detailed example.
|
||||
|
||||
#### Pushing to a release branch
|
||||
|
||||
With the configuration `"branches": ["master", "next"]`, if the last release published from `master` is `1.0.0` and the last one from `next` is `2.0.0` then:
|
||||
- Only versions in range `1.x.x` can be published from `master`, so only `fix` and `feat` commits can be pushed to `master`
|
||||
- Once `next` get merged into `master` the release `2.0.0` will be made available on the channel associated with `master` and both `master` and `next` will accept any commit type
|
||||
|
||||
This verification prevent scenario such as:
|
||||
1. Create a `feat` commit on `next` which triggers the release of version `1.0.0` on the `next` channel
|
||||
2. Merge `next` into `master` which adds `1.0.0` on the default channel
|
||||
3. Create a `feat` commit on `next` which triggers the release of version `1.1.0` on the `next` channel
|
||||
4. Create a `feat` commit on `master` which would attempt to release the version `1.1.0` on the default channel
|
||||
|
||||
In step 4 **semantic-release** will throw an `EINVALIDNEXTVERSION` error to prevent the attempt at releasing version `1.1.0` which was already released on step 3 with a different codebase. The error will indicate that the commit should be created on `next` instead. Alternatively if the `next` branch is merged into `master`, the version `1.1.0` will be made available on the default channel and the `feat` commit would be allowed on `master` to release `1.2.0`.
|
||||
|
||||
#### Merging into a release branch
|
||||
|
||||
When merging commits associated with a release from one release branch to another, **semantic-release** will make the corresponding version available on the channel associated with the target branch.
|
||||
|
||||
When merging commits not associated with a release, commits from a [maintenance branch](#maintenance-branches) or commits from a [pre-release branch](#pre-release-branches) **semantic-release** will treat them as [pushed commits](#pushing-to-a-release-branch) and publish a new release if necessary.
|
||||
|
||||
### Maintenance branches
|
||||
|
||||
A maintenance branch is a type of branch used by **semantic-release** that allows to publish releases with a [semantic version](https://semver.org) on top of the codebase of an old release. This is useful when you need to provide fixes or features to users who cannot upgrade to the last version of your package.
|
||||
|
||||
A maintenance branch is characterized by a range which defines the versions that can be published from it. The [`range`](#range) value of each maintenance branch must be unique across the project.
|
||||
|
||||
**semantic-release** will always publish releases to a distribution channel specific to the range, so only the users who choose to use that particular line of versions will receive new releases.
|
||||
|
||||
Maintenance branches are always considered lower than [release branches](#release-branches) and similarly to them, when a commit that would create a version conflict is pushed, **semantic-release** will not perform the release and will throw an `EINVALIDNEXTVERSION` error, listing the problematic commits and the valid branches on which to move them.
|
||||
|
||||
**semantic-release** will automatically add releases to the corresponding distribution channel when code is [merged from a release or maintenance branch to another maintenance branch](#merging-into-a-maintenance-branch), however only versions within the branch `range` can be merged. If a merged version is outside the maintenance branch `range`, **semantic-release** will not add to the corresponding channel and will throw an `EINVALIDMAINTENANCEMERGE` error.
|
||||
|
||||
See [publishing maintenance releases recipe](../recipes/maintenance-releases.md) for a detailed example.
|
||||
|
||||
#### Pushing to a maintenance branch
|
||||
|
||||
With the configuration `"branches": ["1.0.x", "1.x", "master"]`, if the last release published from `master` is `1.5.0` then:
|
||||
- Only versions in range `>=1.0.0 <1.1.0` can be published from `1.0.x`, so only `fix` commits can be pushed to `1.0.x`
|
||||
- Only versions in range `>=1.1.0 <1.5.0` can be published from `1.x`, so only `fix` and `feat` commits can be pushed to `1.x` as long the resulting release is lower than `1.5.0`
|
||||
- Once `2.0.0` is released from `master`, versions in range `>=1.1.0 <2.0.0` can be published from `1.x`, so any number of `fix` and `feat` commits can be pushed to `1.x`
|
||||
|
||||
#### Merging into a maintenance branch
|
||||
|
||||
With the configuration `"branches": ["1.0.x", "1.x", "master"]`, if the last release published from `master` is `1.0.0` then:
|
||||
- Creating the branch `1.0.x` from `master` will make the `1.0.0` release available on the `1.0.x` distribution channel
|
||||
- Pushing a `fix` commit on the `1.0.x` branch will release the version `1.0.1` on the `1.0.x` distribution channel
|
||||
- Creating the branch `1.x` from `master` will make the `1.0.0` release available on the `1.x` distribution channel
|
||||
- Merging the branch `1.0.x` into `1.x` will make the version `1.0.1` available on the `1.x` distribution channel
|
||||
|
||||
### Pre-release branches
|
||||
|
||||
A pre-release branch is a type of branch used by **semantic-release** that allows to publish releases with a [pre-release version](https://semver.org/#spec-item-9).
|
||||
Using a pre-release version allow to publish multiple releases with the same version. Those release will be differentiated via there identifiers (in `1.0.0-alpha.1` the identifier is `alpha.1`).
|
||||
This is useful when you need to work on a future major release that will include many breaking changes but you do not want to increment the version number for each breaking change commit.
|
||||
|
||||
A pre-release branch is characterized by the `prerelease` property that defines the static part of the version released (in `1.0.0-alpha.1` the static part fo the identifier is `alpha`). The [`prerelease`](#prerelease) value of each pre-release branch must be unique across the project.
|
||||
|
||||
**semantic-release** will always publish pre-releases to a specific distribution channel, so only the users who choose to use that particular line of versions will receive new releases.
|
||||
|
||||
When merging commits associated with an existing release, **semantic-release** will treat them as [pushed commits](#pushing-to-a-pre-release-branch) and publish a new release if necessary, but it will never add those releases to the distribution channel corresponding to the pre-release branch.
|
||||
|
||||
See [publishing pre-releases recipe](../recipes/pre-releases.md) for a detailed example.
|
||||
|
||||
#### Pushing to a pre-release branch
|
||||
|
||||
With the configuration `"branches": ["master", {"name": "beta", "prerelease": true}]`, if the last release published from `master` is `1.0.0` then:
|
||||
- Pushing a `BREAKING CHANGE` commit on the `beta` branch will release the version `2.0.0-beta.1` on the `beta` distribution channel
|
||||
- Pushing either a `fix`, `feat` or a `BREAKING CHANGE` commit on the `beta` branch will release the version `2.0.0-beta.2` (then `2.0.0-beta.3`, `2.0.0-beta.4`, etc...) on the `beta` distribution channel
|
||||
|
||||
#### Merging into a pre-release branch
|
||||
|
||||
With the configuration `"branches": ["master", {"name": "beta", "prerelease": true}]`, if the last release published from `master` is `1.0.0` and the last one published from `beta` is `2.0.0-beta.1` then:
|
||||
- Pushing a `fix` commit on the `master` branch will release the version `1.0.1` on the default distribution channel
|
||||
- Merging the branch `master` into `beta` will release the version `2.0.0-beta.2` on the `beta` distribution channel
|
||||
@@ -1,8 +1,10 @@
|
||||
const {template, pick} = require('lodash');
|
||||
const {pick} = require('lodash');
|
||||
const marked = require('marked');
|
||||
const TerminalRenderer = require('marked-terminal');
|
||||
const envCi = require('env-ci');
|
||||
const hookStd = require('hook-std');
|
||||
const semver = require('semver');
|
||||
const AggregateError = require('aggregate-error');
|
||||
const pkg = require('./package.json');
|
||||
const hideSensitive = require('./lib/hide-sensitive');
|
||||
const getConfig = require('./lib/get-config');
|
||||
@@ -10,18 +12,22 @@ const verify = require('./lib/verify');
|
||||
const getNextVersion = require('./lib/get-next-version');
|
||||
const getCommits = require('./lib/get-commits');
|
||||
const getLastRelease = require('./lib/get-last-release');
|
||||
const {extractErrors} = require('./lib/utils');
|
||||
const getReleaseToAdd = require('./lib/get-release-to-add');
|
||||
const {extractErrors, makeTag} = require('./lib/utils');
|
||||
const getGitAuthUrl = require('./lib/get-git-auth-url');
|
||||
const getBranches = require('./lib/branches');
|
||||
const getLogger = require('./lib/get-logger');
|
||||
const {fetch, verifyAuth, isBranchUpToDate, getGitHead, tag, push} = require('./lib/git');
|
||||
const {verifyAuth, isBranchUpToDate, getGitHead, tag, push, pushNotes, getTagHead, addNote} = require('./lib/git');
|
||||
const getError = require('./lib/get-error');
|
||||
const {COMMIT_NAME, COMMIT_EMAIL} = require('./lib/definitions/constants');
|
||||
|
||||
marked.setOptions({renderer: new TerminalRenderer()});
|
||||
|
||||
/* eslint complexity: off */
|
||||
async function run(context, plugins) {
|
||||
const {cwd, env, options, logger} = context;
|
||||
const {isCi, branch: ciBranch, isPr} = envCi({env, cwd});
|
||||
const {isCi, branch, prBranch, isPr} = context.envCi;
|
||||
const ciBranch = isPr ? prBranch : branch;
|
||||
|
||||
if (!isCi && !options.dryRun && !options.noCi) {
|
||||
logger.warn('This run was not triggered in a known CI environment, running in dry-run mode.');
|
||||
@@ -44,30 +50,35 @@ async function run(context, plugins) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (ciBranch !== options.branch) {
|
||||
// Verify config
|
||||
await verify(context);
|
||||
|
||||
options.repositoryUrl = await getGitAuthUrl({...context, branch: {name: ciBranch}});
|
||||
context.branches = await getBranches(options.repositoryUrl, ciBranch, context);
|
||||
context.branch = context.branches.find(({name}) => name === ciBranch);
|
||||
|
||||
if (!context.branch) {
|
||||
logger.log(
|
||||
`This test run was triggered on the branch ${ciBranch}, while semantic-release is configured to only publish from ${
|
||||
options.branch
|
||||
}, therefore a new version won’t be published.`
|
||||
`This test run was triggered on the branch ${ciBranch}, while semantic-release is configured to only publish from ${context.branches
|
||||
.map(({name}) => name)
|
||||
.join(', ')}, therefore a new version won’t be published.`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
logger[options.dryRun ? 'warn' : 'success'](
|
||||
`Run automated release from branch ${ciBranch}${options.dryRun ? ' in dry-run mode' : ''}`
|
||||
`Run automated release from branch ${ciBranch} on repository ${options.repositoryUrl}${
|
||||
options.dryRun ? ' in dry-run mode' : ''
|
||||
}`
|
||||
);
|
||||
|
||||
await verify(context);
|
||||
|
||||
options.repositoryUrl = await getGitAuthUrl(context);
|
||||
|
||||
try {
|
||||
try {
|
||||
await verifyAuth(options.repositoryUrl, options.branch, {cwd, env});
|
||||
await verifyAuth(options.repositoryUrl, context.branch.name, {cwd, env});
|
||||
} catch (error) {
|
||||
if (!(await isBranchUpToDate(options.branch, {cwd, env}))) {
|
||||
if (!(await isBranchUpToDate(options.repositoryUrl, context.branch.name, {cwd, env}))) {
|
||||
logger.log(
|
||||
`The local branch ${options.branch} is behind the remote one, therefore a new version won't be published.`
|
||||
`The local branch ${context.branch.name} is behind the remote one, therefore a new version won't be published.`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
@@ -75,29 +86,97 @@ async function run(context, plugins) {
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`The command "${error.cmd}" failed with the error message ${error.stderr}.`);
|
||||
throw getError('EGITNOPERMISSION', {options});
|
||||
logger.error(`The command "${error.command}" failed with the error message ${error.stderr}.`);
|
||||
throw getError('EGITNOPERMISSION', context);
|
||||
}
|
||||
|
||||
logger.success(`Allowed to push to the Git repository`);
|
||||
|
||||
await plugins.verifyConditions(context);
|
||||
|
||||
await fetch(options.repositoryUrl, {cwd, env});
|
||||
const errors = [];
|
||||
context.releases = [];
|
||||
const releaseToAdd = getReleaseToAdd(context);
|
||||
|
||||
if (releaseToAdd) {
|
||||
const {lastRelease, currentRelease, nextRelease} = releaseToAdd;
|
||||
|
||||
nextRelease.gitHead = await getTagHead(nextRelease.gitHead, {cwd, env});
|
||||
currentRelease.gitHead = await getTagHead(currentRelease.gitHead, {cwd, env});
|
||||
if (context.branch.mergeRange && !semver.satisfies(nextRelease.version, context.branch.mergeRange)) {
|
||||
errors.push(getError('EINVALIDMAINTENANCEMERGE', {...context, nextRelease}));
|
||||
} else {
|
||||
const commits = await getCommits({...context, lastRelease, nextRelease});
|
||||
nextRelease.notes = await plugins.generateNotes({...context, commits, lastRelease, nextRelease});
|
||||
|
||||
if (options.dryRun) {
|
||||
logger.warn(`Skip ${nextRelease.gitTag} tag creation in dry-run mode`);
|
||||
} else {
|
||||
await addNote({channels: [...currentRelease.channels, nextRelease.channel]}, nextRelease.gitHead, {cwd, env});
|
||||
await push(options.repositoryUrl, {cwd, env});
|
||||
await pushNotes(options.repositoryUrl, {cwd, env});
|
||||
logger.success(
|
||||
`Add ${nextRelease.channel ? `channel ${nextRelease.channel}` : 'default channel'} to tag ${
|
||||
nextRelease.gitTag
|
||||
}`
|
||||
);
|
||||
}
|
||||
|
||||
context.branch.tags.push({
|
||||
version: nextRelease.version,
|
||||
channel: nextRelease.channel,
|
||||
gitTag: nextRelease.gitTag,
|
||||
gitHead: nextRelease.gitHead,
|
||||
});
|
||||
|
||||
const releases = await plugins.addChannel({...context, commits, lastRelease, currentRelease, nextRelease});
|
||||
context.releases.push(...releases);
|
||||
await plugins.success({...context, lastRelease, commits, nextRelease, releases});
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
|
||||
context.lastRelease = getLastRelease(context);
|
||||
if (context.lastRelease.gitHead) {
|
||||
context.lastRelease.gitHead = await getTagHead(context.lastRelease.gitHead, {cwd, env});
|
||||
}
|
||||
|
||||
if (context.lastRelease.gitTag) {
|
||||
logger.log(
|
||||
`Found git tag ${context.lastRelease.gitTag} associated with version ${context.lastRelease.version} on branch ${context.branch.name}`
|
||||
);
|
||||
} else {
|
||||
logger.log(`No git tag version found on branch ${context.branch.name}`);
|
||||
}
|
||||
|
||||
context.lastRelease = await getLastRelease(context);
|
||||
context.commits = await getCommits(context);
|
||||
|
||||
const nextRelease = {type: await plugins.analyzeCommits(context), gitHead: await getGitHead({cwd, env})};
|
||||
|
||||
const nextRelease = {
|
||||
type: await plugins.analyzeCommits(context),
|
||||
channel: context.branch.channel || null,
|
||||
gitHead: await getGitHead({cwd, env}),
|
||||
};
|
||||
if (!nextRelease.type) {
|
||||
logger.log('There are no relevant changes, so no new version is released.');
|
||||
return false;
|
||||
return context.releases.length > 0 ? {releases: context.releases} : false;
|
||||
}
|
||||
|
||||
context.nextRelease = nextRelease;
|
||||
nextRelease.version = getNextVersion(context);
|
||||
nextRelease.gitTag = template(options.tagFormat)({version: nextRelease.version});
|
||||
nextRelease.gitTag = makeTag(options.tagFormat, nextRelease.version);
|
||||
nextRelease.name = nextRelease.gitTag;
|
||||
|
||||
if (context.branch.type !== 'prerelease' && !semver.satisfies(nextRelease.version, context.branch.range)) {
|
||||
throw getError('EINVALIDNEXTVERSION', {
|
||||
...context,
|
||||
validBranches: context.branches.filter(
|
||||
({type, accept}) => type !== 'prerelease' && accept.includes(nextRelease.type)
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
await plugins.verifyRelease(context);
|
||||
|
||||
@@ -109,16 +188,21 @@ async function run(context, plugins) {
|
||||
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 tag(nextRelease.gitTag, nextRelease.gitHead, {cwd, env});
|
||||
await addNote({channels: [nextRelease.channel]}, nextRelease.gitHead, {cwd, env});
|
||||
await push(options.repositoryUrl, {cwd, env});
|
||||
await pushNotes(options.repositoryUrl, {cwd, env});
|
||||
logger.success(`Created tag ${nextRelease.gitTag}`);
|
||||
}
|
||||
|
||||
context.releases = await plugins.publish(context);
|
||||
const releases = await plugins.publish(context);
|
||||
context.releases.push(...releases);
|
||||
|
||||
await plugins.success(context);
|
||||
await plugins.success({...context, releases});
|
||||
|
||||
logger.success(`Published release ${nextRelease.version}`);
|
||||
logger.success(
|
||||
`Published release ${nextRelease.version} on ${nextRelease.channel ? nextRelease.channel : 'default'} channel`
|
||||
);
|
||||
|
||||
if (options.dryRun) {
|
||||
logger.log(`Release note for version ${nextRelease.version}:`);
|
||||
@@ -131,7 +215,7 @@ async function run(context, plugins) {
|
||||
}
|
||||
|
||||
function logErrors({logger, stderr}, err) {
|
||||
const errors = extractErrors(err).sort(error => (error.semanticRelease ? -1 : 0));
|
||||
const errors = extractErrors(err).sort((error) => (error.semanticRelease ? -1 : 0));
|
||||
for (const error of errors) {
|
||||
if (error.semanticRelease) {
|
||||
logger.error(`${error.code} ${error.message}`);
|
||||
@@ -145,7 +229,7 @@ function logErrors({logger, stderr}, err) {
|
||||
}
|
||||
|
||||
async function callFail(context, plugins, err) {
|
||||
const errors = extractErrors(err).filter(err => err.semanticRelease);
|
||||
const errors = extractErrors(err).filter((err) => err.semanticRelease);
|
||||
if (errors.length > 0) {
|
||||
try {
|
||||
await plugins.fail({...context, errors});
|
||||
@@ -155,16 +239,22 @@ async function callFail(context, plugins, err) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = async (opts = {}, {cwd = process.cwd(), env = process.env, stdout, stderr} = {}) => {
|
||||
module.exports = async (cliOptions = {}, {cwd = process.cwd(), env = process.env, stdout, stderr} = {}) => {
|
||||
const {unhook} = hookStd(
|
||||
{silent: false, streams: [process.stdout, process.stderr, stdout, stderr].filter(Boolean)},
|
||||
hideSensitive(env)
|
||||
);
|
||||
const context = {cwd, env, stdout: stdout || process.stdout, stderr: stderr || process.stderr};
|
||||
const context = {
|
||||
cwd,
|
||||
env,
|
||||
stdout: stdout || process.stdout,
|
||||
stderr: stderr || process.stderr,
|
||||
envCi: envCi({env, cwd}),
|
||||
};
|
||||
context.logger = getLogger(context);
|
||||
context.logger.log(`Running ${pkg.name} version ${pkg.version}`);
|
||||
try {
|
||||
const {plugins, options} = await getConfig(context, opts);
|
||||
const {plugins, options} = await getConfig(context, cliOptions);
|
||||
context.options = options;
|
||||
try {
|
||||
const result = await run(context, plugins);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
const {isString, remove, omit, mapValues, template} = require('lodash');
|
||||
const micromatch = require('micromatch');
|
||||
const {getBranches} = require('../git');
|
||||
|
||||
module.exports = async (repositoryUrl, {cwd}, branches) => {
|
||||
const gitBranches = await getBranches(repositoryUrl, {cwd});
|
||||
|
||||
return branches.reduce(
|
||||
(branches, branch) => [
|
||||
...branches,
|
||||
...remove(gitBranches, (name) => micromatch(gitBranches, branch.name).includes(name)).map((name) => ({
|
||||
name,
|
||||
...mapValues(omit(branch, 'name'), (value) => (isString(value) ? template(value)({name}) : value)),
|
||||
})),
|
||||
],
|
||||
[]
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
const {template, escapeRegExp} = require('lodash');
|
||||
const semver = require('semver');
|
||||
const pReduce = require('p-reduce');
|
||||
const debug = require('debug')('semantic-release:get-tags');
|
||||
const {getTags, getNote} = require('../../lib/git');
|
||||
|
||||
module.exports = async ({cwd, env, options: {tagFormat}}, branches) => {
|
||||
// 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`.
|
||||
const tagRegexp = `^${escapeRegExp(template(tagFormat)({version: ' '})).replace(' ', '(.+)')}`;
|
||||
|
||||
return pReduce(
|
||||
branches,
|
||||
async (branches, branch) => {
|
||||
const branchTags = await pReduce(
|
||||
await getTags(branch.name, {cwd, env}),
|
||||
async (branchTags, tag) => {
|
||||
const [, version] = tag.match(tagRegexp) || [];
|
||||
return version && semver.valid(semver.clean(version))
|
||||
? [...branchTags, {gitTag: tag, version, channels: (await getNote(tag, {cwd, env})).channels || [null]}]
|
||||
: branchTags;
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
debug('found tags for branch %s: %o', branch.name, branchTags);
|
||||
return [...branches, {...branch, tags: branchTags}];
|
||||
},
|
||||
[]
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,70 @@
|
||||
const {isString, isRegExp} = require('lodash');
|
||||
const AggregateError = require('aggregate-error');
|
||||
const pEachSeries = require('p-each-series');
|
||||
const DEFINITIONS = require('../definitions/branches');
|
||||
const getError = require('../get-error');
|
||||
const {fetch, fetchNotes, verifyBranchName} = require('../git');
|
||||
const expand = require('./expand');
|
||||
const getTags = require('./get-tags');
|
||||
const normalize = require('./normalize');
|
||||
|
||||
module.exports = async (repositoryUrl, ciBranch, context) => {
|
||||
const {cwd, env} = context;
|
||||
|
||||
const remoteBranches = await expand(
|
||||
repositoryUrl,
|
||||
context,
|
||||
context.options.branches.map((branch) => (isString(branch) || isRegExp(branch) ? {name: branch} : branch))
|
||||
);
|
||||
|
||||
await pEachSeries(remoteBranches, async ({name}) => {
|
||||
await fetch(repositoryUrl, name, ciBranch, {cwd, env});
|
||||
});
|
||||
|
||||
await fetchNotes(repositoryUrl, {cwd, env});
|
||||
|
||||
const branches = await getTags(context, remoteBranches);
|
||||
|
||||
const errors = [];
|
||||
const branchesByType = Object.entries(DEFINITIONS).reduce(
|
||||
(branchesByType, [type, {filter}]) => ({[type]: branches.filter(filter), ...branchesByType}),
|
||||
{}
|
||||
);
|
||||
|
||||
const result = Object.entries(DEFINITIONS).reduce((result, [type, {branchesValidator, branchValidator}]) => {
|
||||
branchesByType[type].forEach((branch) => {
|
||||
if (branchValidator && !branchValidator(branch)) {
|
||||
errors.push(getError(`E${type.toUpperCase()}BRANCH`, {branch}));
|
||||
}
|
||||
});
|
||||
|
||||
const branchesOfType = normalize[type](branchesByType);
|
||||
|
||||
if (!branchesValidator(branchesOfType)) {
|
||||
errors.push(getError(`E${type.toUpperCase()}BRANCHES`, {branches: branchesOfType}));
|
||||
}
|
||||
|
||||
return {...result, [type]: branchesOfType};
|
||||
}, {});
|
||||
|
||||
const duplicates = [...branches]
|
||||
.map((branch) => branch.name)
|
||||
.sort()
|
||||
.filter((_, idx, array) => array[idx] === array[idx + 1] && array[idx] !== array[idx - 1]);
|
||||
|
||||
if (duplicates.length > 0) {
|
||||
errors.push(getError('EDUPLICATEBRANCHES', {duplicates}));
|
||||
}
|
||||
|
||||
await pEachSeries(branches, async (branch) => {
|
||||
if (!(await verifyBranchName(branch.name))) {
|
||||
errors.push(getError('EINVALIDBRANCHNAME', branch));
|
||||
}
|
||||
});
|
||||
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
|
||||
return [...result.maintenance, ...result.release, ...result.prerelease];
|
||||
};
|
||||
@@ -0,0 +1,106 @@
|
||||
const {sortBy, isNil} = require('lodash');
|
||||
const semverDiff = require('semver-diff');
|
||||
const {FIRST_RELEASE, RELEASE_TYPE} = require('../definitions/constants');
|
||||
const {
|
||||
tagsToVersions,
|
||||
isMajorRange,
|
||||
getUpperBound,
|
||||
getLowerBound,
|
||||
highest,
|
||||
lowest,
|
||||
getLatestVersion,
|
||||
getFirstVersion,
|
||||
getRange,
|
||||
} = require('../utils');
|
||||
|
||||
function maintenance({maintenance, release}) {
|
||||
return sortBy(
|
||||
maintenance.map(({name, range, channel, ...rest}) => ({
|
||||
...rest,
|
||||
name,
|
||||
range: range || name,
|
||||
channel: isNil(channel) ? name : channel,
|
||||
})),
|
||||
'range'
|
||||
).map(({name, range, tags, ...rest}, idx, branches) => {
|
||||
const versions = tagsToVersions(tags);
|
||||
// Find the lower bound based on Maintenance branches
|
||||
const maintenanceMin =
|
||||
// If the current branch has a major range (1.x or 1.x.x) and the previous doesn't
|
||||
isMajorRange(range) && branches[idx - 1] && !isMajorRange(branches[idx - 1].range)
|
||||
? // Then the lowest bound is the upper bound of the previous branch range
|
||||
getUpperBound(branches[idx - 1].range)
|
||||
: // Otherwise the lowest bound is the lowest bound of the current branch range
|
||||
getLowerBound(range);
|
||||
// The actual lower bound is the highest version between the current branch last release and `maintenanceMin`
|
||||
const min = highest(getLatestVersion(versions) || FIRST_RELEASE, maintenanceMin);
|
||||
// Determine the first release of the default branch not present in any maintenance branch
|
||||
const base =
|
||||
(release[0] &&
|
||||
(getFirstVersion(tagsToVersions(release[0].tags), branches) ||
|
||||
getLatestVersion(tagsToVersions(release[0].tags)))) ||
|
||||
FIRST_RELEASE;
|
||||
// The upper bound is the lowest version between the `base` version and the upper bound of the current branch range
|
||||
const max = lowest(base, getUpperBound(range));
|
||||
const diff = semverDiff(min, max);
|
||||
return {
|
||||
...rest,
|
||||
type: 'maintenance',
|
||||
name,
|
||||
tags,
|
||||
range: getRange(min, max),
|
||||
accept: diff ? RELEASE_TYPE.slice(0, RELEASE_TYPE.indexOf(diff)) : [],
|
||||
mergeRange: getRange(maintenanceMin, getUpperBound(range)),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function release({release}) {
|
||||
if (release.length === 0) {
|
||||
return release;
|
||||
}
|
||||
|
||||
// The intial lastVersion is the last release from the base branch of `FIRST_RELEASE` (1.0.0)
|
||||
let lastVersion = getLatestVersion(tagsToVersions(release[0].tags)) || FIRST_RELEASE;
|
||||
|
||||
return release.map(({name, tags, channel, ...rest}, idx) => {
|
||||
const versions = tagsToVersions(tags);
|
||||
// The new lastVersion is the highest version between the current branch last release and the previous branch lastVersion
|
||||
lastVersion = highest(getLatestVersion(versions), lastVersion);
|
||||
// The upper bound is:
|
||||
// - None if the current branch is the last one of the release branches
|
||||
// - Otherwise, The upper bound is the lowest version that is present on the current branch but none of the previous ones
|
||||
const bound =
|
||||
release.length - 1 === idx
|
||||
? undefined
|
||||
: getFirstVersion(tagsToVersions(release[idx + 1].tags), release.slice(0, idx + 1));
|
||||
|
||||
const diff = bound ? semverDiff(lastVersion, bound) : null;
|
||||
return {
|
||||
...rest,
|
||||
channel: idx === 0 ? channel : isNil(channel) ? name : channel,
|
||||
tags,
|
||||
type: 'release',
|
||||
name,
|
||||
range: getRange(lastVersion, bound),
|
||||
accept: bound ? RELEASE_TYPE.slice(0, RELEASE_TYPE.indexOf(diff)) : RELEASE_TYPE,
|
||||
main: idx === 0,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function prerelease({prerelease}) {
|
||||
return prerelease.map(({name, prerelease, channel, tags, ...rest}) => {
|
||||
const preid = prerelease === true ? name : prerelease;
|
||||
return {
|
||||
...rest,
|
||||
channel: isNil(channel) ? name : channel,
|
||||
type: 'prerelease',
|
||||
name,
|
||||
prerelease: preid,
|
||||
tags,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {maintenance, release, prerelease};
|
||||
@@ -0,0 +1,23 @@
|
||||
const {isNil, uniqBy} = require('lodash');
|
||||
const semver = require('semver');
|
||||
const {isMaintenanceRange} = require('../utils');
|
||||
|
||||
const maintenance = {
|
||||
filter: ({name, range}) => (!isNil(range) && range !== false) || isMaintenanceRange(name),
|
||||
branchValidator: ({range}) => (isNil(range) ? true : isMaintenanceRange(range)),
|
||||
branchesValidator: (branches) => uniqBy(branches, ({range}) => semver.validRange(range)).length === branches.length,
|
||||
};
|
||||
|
||||
const prerelease = {
|
||||
filter: ({prerelease}) => !isNil(prerelease) && prerelease !== false,
|
||||
branchValidator: ({name, prerelease}) =>
|
||||
Boolean(prerelease) && Boolean(semver.valid(`1.0.0-${prerelease === true ? name : prerelease}.1`)),
|
||||
branchesValidator: (branches) => uniqBy(branches, 'prerelease').length === branches.length,
|
||||
};
|
||||
|
||||
const release = {
|
||||
filter: (branch) => !maintenance.filter(branch) && !prerelease.filter(branch),
|
||||
branchesValidator: (branches) => branches.length <= 3 && branches.length > 0,
|
||||
};
|
||||
|
||||
module.exports = {maintenance, prerelease, release};
|
||||
@@ -1,7 +1,9 @@
|
||||
const RELEASE_TYPE = ['prerelease', 'prepatch', 'patch', 'preminor', 'minor', 'premajor', 'major'];
|
||||
const RELEASE_TYPE = ['patch', 'minor', 'major'];
|
||||
|
||||
const FIRST_RELEASE = '1.0.0';
|
||||
|
||||
const FIRSTPRERELEASE = '1';
|
||||
|
||||
const COMMIT_NAME = 'semantic-release-bot';
|
||||
|
||||
const COMMIT_EMAIL = 'semantic-release-bot@martynus.net';
|
||||
@@ -12,12 +14,16 @@ const SECRET_REPLACEMENT = '[secure]';
|
||||
|
||||
const SECRET_MIN_SIZE = 5;
|
||||
|
||||
const GIT_NOTE_REF = 'semantic-release';
|
||||
|
||||
module.exports = {
|
||||
RELEASE_TYPE,
|
||||
FIRST_RELEASE,
|
||||
FIRSTPRERELEASE,
|
||||
COMMIT_NAME,
|
||||
COMMIT_EMAIL,
|
||||
RELEASE_NOTES_SEPARATOR,
|
||||
SECRET_REPLACEMENT,
|
||||
SECRET_MIN_SIZE,
|
||||
GIT_NOTE_REF,
|
||||
};
|
||||
|
||||
+121
-16
@@ -1,11 +1,14 @@
|
||||
const {inspect} = require('util');
|
||||
const {toLower, isString} = require('lodash');
|
||||
const {toLower, isString, trim} = require('lodash');
|
||||
const pkg = require('../../package.json');
|
||||
const {RELEASE_TYPE} = require('./constants');
|
||||
|
||||
const [homepage] = pkg.homepage.split('#');
|
||||
const stringify = obj => (isString(obj) ? obj : inspect(obj, {breakLength: Infinity, depth: 2, maxArrayLength: 5}));
|
||||
const linkify = file => `${homepage}/blob/master/${file}`;
|
||||
const stringify = (object) =>
|
||||
isString(object) ? object : inspect(object, {breakLength: Infinity, depth: 2, maxArrayLength: 5});
|
||||
const linkify = (file) => `${homepage}/blob/master/${file}`;
|
||||
const wordsList = (words) =>
|
||||
`${words.slice(0, -1).join(', ')}${words.length > 1 ? ` or ${words[words.length - 1]}` : trim(words[0])}`;
|
||||
|
||||
module.exports = {
|
||||
ENOGITREPO: ({cwd}) => ({
|
||||
@@ -26,19 +29,18 @@ Please make sure to add the \`repositoryUrl\` to the [semantic-release configura
|
||||
'docs/usage/configuration.md'
|
||||
)}).`,
|
||||
}),
|
||||
EGITNOPERMISSION: ({options}) => ({
|
||||
message: 'The push permission to the Git repository is required.',
|
||||
details: `**semantic-release** cannot push the version tag to the branch \`${
|
||||
options.branch
|
||||
}\` on remote Git repository with URL \`${options.repositoryUrl}\`.
|
||||
EGITNOPERMISSION: ({options: {repositoryUrl}, branch: {name}}) => ({
|
||||
message: 'Cannot push to the Git repository.',
|
||||
details: `**semantic-release** cannot push the version tag to the branch \`${name}\` on the remote Git repository with URL \`${repositoryUrl}\`.
|
||||
|
||||
Please refer to the [authentication configuration documentation](${linkify(
|
||||
'docs/usage/ci-configuration.md#authentication'
|
||||
)}) to configure the Git credentials on your CI environment and make sure the [repositoryUrl](${linkify(
|
||||
'docs/usage/configuration.md#repositoryurl'
|
||||
)}) is configured with a [valid Git URL](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols).`,
|
||||
This can be caused by:
|
||||
- a misconfiguration of the [repositoryUrl](${linkify('docs/usage/configuration.md#repositoryurl')}) option
|
||||
- the repository being unavailable
|
||||
- or missing push permission for the user configured via the [Git credentials on your CI environment](${linkify(
|
||||
'docs/usage/ci-configuration.md#authentication'
|
||||
)})`,
|
||||
}),
|
||||
EINVALIDTAGFORMAT: ({tagFormat}) => ({
|
||||
EINVALIDTAGFORMAT: ({options: {tagFormat}}) => ({
|
||||
message: 'Invalid `tagFormat` option.',
|
||||
details: `The [tagFormat](${linkify(
|
||||
'docs/usage/configuration.md#tagformat'
|
||||
@@ -46,7 +48,7 @@ Please refer to the [authentication configuration documentation](${linkify(
|
||||
|
||||
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
|
||||
}),
|
||||
ETAGNOVERSION: ({tagFormat}) => ({
|
||||
ETAGNOVERSION: ({options: {tagFormat}}) => ({
|
||||
message: 'Invalid `tagFormat` option.',
|
||||
details: `The [tagFormat](${linkify(
|
||||
'docs/usage/configuration.md#tagformat'
|
||||
@@ -83,7 +85,7 @@ Please refer to the \`${pluginName}\` and [semantic-release plugins configuratio
|
||||
EANALYZECOMMITSOUTPUT: ({result, pluginName}) => ({
|
||||
message: 'The `analyzeCommits` plugin returned an invalid value. It must return a valid semver release type.',
|
||||
details: `The \`analyzeCommits\` plugin must return a valid [semver](https://semver.org) release type. The valid values are: ${RELEASE_TYPE.map(
|
||||
type => `\`${type}\``
|
||||
(type) => `\`${type}\``
|
||||
).join(', ')}.
|
||||
|
||||
The \`analyzeCommits\` function of the \`${pluginName}\` returned \`${stringify(result)}\` instead.
|
||||
@@ -124,4 +126,107 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the
|
||||
'docs/developer-guide/plugin.md'
|
||||
)})`,
|
||||
}),
|
||||
EADDCHANNELOUTPUT: ({result, pluginName}) => ({
|
||||
message: 'A `addChannel` plugin returned an invalid value. It must return an `Object`.',
|
||||
details: `The \`addChannel\` plugins must return an \`Object\`.
|
||||
|
||||
The \`addChannel\` function of the \`${pluginName}\` returned \`${stringify(result)}\` instead.
|
||||
|
||||
We recommend to report the issue to the \`${pluginName}\` authors, providing the following informations:
|
||||
- The **semantic-release** version: \`${pkg.version}\`
|
||||
- The **semantic-release** logs from your CI job
|
||||
- The value returned by the plugin: \`${stringify(result)}\`
|
||||
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
|
||||
'docs/developer-guide/plugin.md'
|
||||
)})`,
|
||||
}),
|
||||
EINVALIDBRANCH: ({branch}) => ({
|
||||
message: 'A branch is invalid in the `branches` configuration.',
|
||||
details: `Each branch in the [branches configuration](${linkify(
|
||||
'docs/usage/configuration.md#branches'
|
||||
)}) must be either a string, a regexp or an object with a \`name\` property.
|
||||
|
||||
Your configuration for the problematic branch is \`${stringify(branch)}\`.`,
|
||||
}),
|
||||
EINVALIDBRANCHNAME: ({branch}) => ({
|
||||
message: 'A branch name is invalid in the `branches` configuration.',
|
||||
details: `Each branch in the [branches configuration](${linkify(
|
||||
'docs/usage/configuration.md#branches'
|
||||
)}) must be a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description).
|
||||
|
||||
Your configuration for the problematic branch is \`${stringify(branch)}\`.`,
|
||||
}),
|
||||
EDUPLICATEBRANCHES: ({duplicates}) => ({
|
||||
message: 'The `branches` configuration has duplicate branches.',
|
||||
details: `Each branch in the [branches configuration](${linkify(
|
||||
'docs/usage/configuration.md#branches'
|
||||
)}) must havea unique name.
|
||||
|
||||
Your configuration contains duplicates for the following branch names: \`${stringify(duplicates)}\`.`,
|
||||
}),
|
||||
EMAINTENANCEBRANCH: ({branch}) => ({
|
||||
message: 'A maintenance branch is invalid in the `branches` configuration.',
|
||||
details: `Each maintenance branch in the [branches configuration](${linkify(
|
||||
'docs/usage/configuration.md#branches'
|
||||
)}) must have a \`range\` property formatted like \`N.x\`, \`N.x.x\` or \`N.N.x\` (\`N\` is a number).
|
||||
|
||||
Your configuration for the problematic branch is \`${stringify(branch)}\`.`,
|
||||
}),
|
||||
EMAINTENANCEBRANCHES: ({branches}) => ({
|
||||
message: 'The maintenance branches are invalid in the `branches` configuration.',
|
||||
details: `Each maintenance branch in the [branches configuration](${linkify(
|
||||
'docs/usage/configuration.md#branches'
|
||||
)}) must have a unique \`range\` property.
|
||||
|
||||
Your configuration for the problematic branches is \`${stringify(branches)}\`.`,
|
||||
}),
|
||||
ERELEASEBRANCHES: ({branches}) => ({
|
||||
message: 'The release branches are invalid in the `branches` configuration.',
|
||||
details: `A minimum of 1 and a maximum of 3 release branches are required in the [branches configuration](${linkify(
|
||||
'docs/usage/configuration.md#branches'
|
||||
)}).
|
||||
|
||||
This may occur if your repository does not have a release branch, such as \`master\`.
|
||||
|
||||
Your configuration for the problematic branches is \`${stringify(branches)}\`.`,
|
||||
}),
|
||||
EPRERELEASEBRANCH: ({branch}) => ({
|
||||
message: 'A pre-release branch configuration is invalid in the `branches` configuration.',
|
||||
details: `Each pre-release branch in the [branches configuration](${linkify(
|
||||
'docs/usage/configuration.md#branches'
|
||||
)}) must have a \`prerelease\` property valid per the [Semantic Versioning Specification](https://semver.org/#spec-item-9). If the \`prerelease\` property is set to \`true\`, then the \`name\` property is used instead.
|
||||
|
||||
Your configuration for the problematic branch is \`${stringify(branch)}\`.`,
|
||||
}),
|
||||
EPRERELEASEBRANCHES: ({branches}) => ({
|
||||
message: 'The pre-release branches are invalid in the `branches` configuration.',
|
||||
details: `Each pre-release branch in the [branches configuration](${linkify(
|
||||
'docs/usage/configuration.md#branches'
|
||||
)}) must have a unique \`prerelease\` property. If the \`prerelease\` property is set to \`true\`, then the \`name\` property is used instead.
|
||||
|
||||
Your configuration for the problematic branches is \`${stringify(branches)}\`.`,
|
||||
}),
|
||||
EINVALIDNEXTVERSION: ({nextRelease: {version}, branch: {name, range}, commits, validBranches}) => ({
|
||||
message: `The release \`${version}\` on branch \`${name}\` cannot be published as it is out of range.`,
|
||||
details: `Based on the releases published on other branches, only versions within the range \`${range}\` can be published from branch \`${name}\`.
|
||||
|
||||
The following commit${commits.length > 1 ? 's are' : ' is'} responsible for the invalid release:
|
||||
${commits.map(({commit: {short}, subject}) => `- ${subject} (${short})`).join('\n')}
|
||||
|
||||
${
|
||||
commits.length > 1 ? 'Those commits' : 'This commit'
|
||||
} should be moved to a valid branch with [git merge](https://git-scm.com/docs/git-merge) or [git cherry-pick](https://git-scm.com/docs/git-cherry-pick) and removed from branch \`${name}\` with [git revert](https://git-scm.com/docs/git-revert) or [git reset](https://git-scm.com/docs/git-reset).
|
||||
|
||||
A valid branch could be ${wordsList(validBranches.map(({name}) => `\`${name}\``))}.
|
||||
|
||||
See the [workflow configuration documentation](${linkify('docs/usage/workflow-configuration.md')}) for more details.`,
|
||||
}),
|
||||
EINVALIDMAINTENANCEMERGE: ({nextRelease: {channel, gitTag, version}, branch: {mergeRange, name}}) => ({
|
||||
message: `The release \`${version}\` on branch \`${name}\` cannot be published as it is out of range.`,
|
||||
details: `Only releases within the range \`${mergeRange}\` can be merged into the maintenance branch \`${name}\` and published to the \`${channel}\` distribution channel.
|
||||
|
||||
The branch \`${name}\` head should be [reset](https://git-scm.com/docs/git-reset) to a previous commit so the commit with tag \`${gitTag}\` is removed from the branch history.
|
||||
|
||||
See the [workflow configuration documentation](${linkify('docs/usage/workflow-configuration.md')}) for more details.`,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/* eslint require-atomic-updates: off */
|
||||
|
||||
const {isString, isPlainObject} = require('lodash');
|
||||
const {getGitHead} = require('../git');
|
||||
const hideSensitive = require('../hide-sensitive');
|
||||
@@ -14,12 +16,12 @@ module.exports = {
|
||||
default: ['@semantic-release/commit-analyzer'],
|
||||
required: true,
|
||||
dryRun: true,
|
||||
outputValidator: output => !output || RELEASE_TYPE.includes(output),
|
||||
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)),
|
||||
commits: commits.filter((commit) => !/\[skip\s+release]|\[release\s+skip]/i.test(commit.message)),
|
||||
}),
|
||||
postprocess: results =>
|
||||
postprocess: (results) =>
|
||||
RELEASE_TYPE[
|
||||
results.reduce((highest, result) => {
|
||||
const typeIndex = RELEASE_TYPE.indexOf(result);
|
||||
@@ -35,7 +37,7 @@ module.exports = {
|
||||
generateNotes: {
|
||||
required: false,
|
||||
dryRun: true,
|
||||
outputValidator: output => !output || isString(output),
|
||||
outputValidator: (output) => !output || isString(output),
|
||||
pipelineConfig: () => ({
|
||||
getNextInput: ({nextRelease, ...context}, notes) => ({
|
||||
...context,
|
||||
@@ -51,7 +53,7 @@ module.exports = {
|
||||
required: false,
|
||||
dryRun: false,
|
||||
pipelineConfig: ({generateNotes}) => ({
|
||||
getNextInput: async context => {
|
||||
getNextInput: async (context) => {
|
||||
const newGitHead = await getGitHead({cwd: context.cwd});
|
||||
// If previous prepare plugin has created a commit (gitHead changed)
|
||||
if (context.nextRelease.gitHead !== newGitHead) {
|
||||
@@ -68,7 +70,20 @@ module.exports = {
|
||||
publish: {
|
||||
required: false,
|
||||
dryRun: false,
|
||||
outputValidator: output => !output || isPlainObject(output),
|
||||
outputValidator: (output) => !output || isPlainObject(output),
|
||||
pipelineConfig: () => ({
|
||||
// Add `nextRelease` and plugin properties to published release
|
||||
transform: (release, step, {nextRelease}) => ({
|
||||
...(release === false ? {} : nextRelease),
|
||||
...release,
|
||||
...step,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
addChannel: {
|
||||
required: false,
|
||||
dryRun: false,
|
||||
outputValidator: (output) => !output || isPlainObject(output),
|
||||
pipelineConfig: () => ({
|
||||
// Add `nextRelease` and plugin properties to published release
|
||||
transform: (release, step, {nextRelease}) => ({
|
||||
|
||||
+6
-13
@@ -1,6 +1,5 @@
|
||||
const gitLogParser = require('git-log-parser');
|
||||
const getStream = require('get-stream');
|
||||
const debug = require('debug')('semantic-release:get-commits');
|
||||
const {getCommits} = require('./git');
|
||||
|
||||
/**
|
||||
* Retrieve the list of commits on the current branch since the commit sha associated with the last release, or all the commits of the current branch if there is no last released version.
|
||||
@@ -9,21 +8,15 @@ const debug = require('debug')('semantic-release:get-commits');
|
||||
*
|
||||
* @return {Promise<Array<Object>>} The list of commits on the branch `branch` since the last release.
|
||||
*/
|
||||
module.exports = async ({cwd, env, lastRelease: {gitHead}, logger}) => {
|
||||
if (gitHead) {
|
||||
debug('Use gitHead: %s', gitHead);
|
||||
module.exports = async ({cwd, env, lastRelease: {gitHead: from}, nextRelease: {gitHead: to = 'HEAD'} = {}, logger}) => {
|
||||
if (from) {
|
||||
debug('Use from: %s', from);
|
||||
} else {
|
||||
logger.log('No previous release found, retrieving all commits');
|
||||
}
|
||||
|
||||
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
|
||||
const commits = (await getStream.array(
|
||||
gitLogParser.parse({_: `${gitHead ? gitHead + '..' : ''}HEAD`}, {cwd, env: {...process.env, ...env}})
|
||||
)).map(commit => {
|
||||
commit.message = commit.message.trim();
|
||||
commit.gitTags = commit.gitTags.trim();
|
||||
return commit;
|
||||
});
|
||||
const commits = await getCommits(from, to, {cwd, env});
|
||||
|
||||
logger.log(`Found ${commits.length} commits since last release`);
|
||||
debug('Parsed commits: %o', commits);
|
||||
return commits;
|
||||
|
||||
+20
-12
@@ -1,6 +1,6 @@
|
||||
const {castArray, pickBy, isNil, isString, isPlainObject} = require('lodash');
|
||||
const readPkgUp = require('read-pkg-up');
|
||||
const cosmiconfig = require('cosmiconfig');
|
||||
const {cosmiconfig} = require('cosmiconfig');
|
||||
const resolveFrom = require('resolve-from');
|
||||
const debug = require('debug')('semantic-release:config');
|
||||
const {repoUrl} = require('./git');
|
||||
@@ -19,14 +19,14 @@ const CONFIG_FILES = [
|
||||
`${CONFIG_NAME}.config.js`,
|
||||
];
|
||||
|
||||
module.exports = async (context, opts) => {
|
||||
module.exports = async (context, cliOptions) => {
|
||||
const {cwd, env} = context;
|
||||
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};
|
||||
let options = {...config, ...cliOptions};
|
||||
if (options.ci === false) {
|
||||
options.noCi = true;
|
||||
}
|
||||
@@ -38,14 +38,14 @@ module.exports = async (context, opts) => {
|
||||
// If `extends` is defined, load and merge each shareable config with `options`
|
||||
options = {
|
||||
...castArray(extendPaths).reduce((result, extendPath) => {
|
||||
const extendsOpts = require(resolveFrom.silent(__dirname, extendPath) || resolveFrom(cwd, extendPath));
|
||||
const extendsOptions = require(resolveFrom.silent(__dirname, extendPath) || resolveFrom(cwd, extendPath));
|
||||
|
||||
// For each plugin defined in a shareable config, save in `pluginsPath` the extendable config path,
|
||||
// so those plugin will be loaded relatively to the config file
|
||||
Object.entries(extendsOpts)
|
||||
Object.entries(extendsOptions)
|
||||
.filter(([, value]) => Boolean(value))
|
||||
.reduce((pluginsPath, [option, value]) => {
|
||||
castArray(value).forEach(plugin => {
|
||||
castArray(value).forEach((plugin) => {
|
||||
if (option === 'plugins' && validatePlugin(plugin)) {
|
||||
pluginsPath[parseConfig(plugin)[0]] = extendPath;
|
||||
} else if (
|
||||
@@ -58,7 +58,7 @@ module.exports = async (context, opts) => {
|
||||
return pluginsPath;
|
||||
}, pluginsPath);
|
||||
|
||||
return {...result, ...extendsOpts};
|
||||
return {...result, ...extendsOptions};
|
||||
}, {}),
|
||||
...options,
|
||||
};
|
||||
@@ -66,7 +66,14 @@ module.exports = async (context, opts) => {
|
||||
|
||||
// Set default options values if not defined yet
|
||||
options = {
|
||||
branch: 'master',
|
||||
branches: [
|
||||
'+([0-9])?(.{+([0-9]),x}).x',
|
||||
'master',
|
||||
'next',
|
||||
'next-major',
|
||||
{name: 'beta', prerelease: true},
|
||||
{name: 'alpha', prerelease: true},
|
||||
],
|
||||
repositoryUrl: (await pkgRepoUrl({normalize: false, cwd})) || (await repoUrl({cwd, env})),
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: [
|
||||
@@ -76,7 +83,8 @@ module.exports = async (context, opts) => {
|
||||
'@semantic-release/github',
|
||||
],
|
||||
// Remove `null` and `undefined` options so they can be replaced with default ones
|
||||
...pickBy(options, option => !isNil(option)),
|
||||
...pickBy(options, (option) => !isNil(option)),
|
||||
...(options.branches ? {branches: castArray(options.branches)} : {}),
|
||||
};
|
||||
|
||||
debug('options values: %O', options);
|
||||
@@ -84,7 +92,7 @@ module.exports = async (context, opts) => {
|
||||
return {options, plugins: await plugins({...context, options}, pluginsPath)};
|
||||
};
|
||||
|
||||
async function pkgRepoUrl(opts) {
|
||||
const {package: pkg} = (await readPkgUp(opts)) || {};
|
||||
return pkg && (isPlainObject(pkg.repository) ? pkg.repository.url : pkg.repository);
|
||||
async function pkgRepoUrl(options) {
|
||||
const {packageJson} = (await readPkgUp(options)) || {};
|
||||
return packageJson && (isPlainObject(packageJson.repository) ? packageJson.repository.url : packageJson.repository);
|
||||
}
|
||||
|
||||
+86
-22
@@ -2,16 +2,49 @@ const {parse, format} = require('url'); // eslint-disable-line node/no-deprecate
|
||||
const {isNil} = require('lodash');
|
||||
const hostedGitInfo = require('hosted-git-info');
|
||||
const {verifyAuth} = require('./git');
|
||||
const debug = require('debug')('semantic-release:get-git-auth-url');
|
||||
|
||||
const GIT_TOKENS = {
|
||||
GIT_CREDENTIALS: undefined,
|
||||
GH_TOKEN: undefined,
|
||||
GITHUB_TOKEN: undefined,
|
||||
GL_TOKEN: 'gitlab-ci-token:',
|
||||
GITLAB_TOKEN: 'gitlab-ci-token:',
|
||||
BB_TOKEN: 'x-token-auth:',
|
||||
BITBUCKET_TOKEN: 'x-token-auth:',
|
||||
};
|
||||
/**
|
||||
* Machinery to format a repository URL with the given credentials
|
||||
*
|
||||
* @param {String} protocol URL protocol (which should not be present in repositoryUrl)
|
||||
* @param {String} repositoryUrl User-given repository URL
|
||||
* @param {String} gitCredentials The basic auth part of the URL
|
||||
*
|
||||
* @return {String} The formatted Git repository URL.
|
||||
*/
|
||||
function formatAuthUrl(protocol, repositoryUrl, gitCredentials) {
|
||||
const [match, auth, host, basePort, path] =
|
||||
/^(?!.+:\/\/)(?:(?<auth>.*)@)?(?<host>.*?):(?<port>\d+)?:?\/?(?<path>.*)$/.exec(repositoryUrl) || [];
|
||||
const {port, hostname, ...parsed} = parse(
|
||||
match ? `ssh://${auth ? `${auth}@` : ''}${host}${basePort ? `:${basePort}` : ''}/${path}` : repositoryUrl
|
||||
);
|
||||
|
||||
return format({
|
||||
...parsed,
|
||||
auth: gitCredentials,
|
||||
host: `${hostname}${protocol === 'ssh:' ? '' : port ? `:${port}` : ''}`,
|
||||
protocol: protocol && /http[^s]/.test(protocol) ? 'http' : 'https',
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify authUrl by calling git.verifyAuth, but don't throw on failure
|
||||
*
|
||||
* @param {Object} context semantic-release context.
|
||||
* @param {String} authUrl Repository URL to verify
|
||||
*
|
||||
* @return {String} The authUrl as is if the connection was successfull, null otherwise
|
||||
*/
|
||||
async function ensureValidAuthUrl({cwd, env, branch}, authUrl) {
|
||||
try {
|
||||
await verifyAuth(authUrl, branch.name, {cwd, env});
|
||||
return authUrl;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine the the git repository URL to use to push, either:
|
||||
@@ -24,7 +57,23 @@ const GIT_TOKENS = {
|
||||
*
|
||||
* @return {String} The formatted Git repository URL.
|
||||
*/
|
||||
module.exports = async ({cwd, env, options: {repositoryUrl, branch}}) => {
|
||||
module.exports = async (context) => {
|
||||
const {cwd, env, branch} = context;
|
||||
const GIT_TOKENS = {
|
||||
GIT_CREDENTIALS: undefined,
|
||||
GH_TOKEN: undefined,
|
||||
// GitHub Actions require the "x-access-token:" prefix for git access
|
||||
// https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#http-based-git-access-by-an-installation
|
||||
GITHUB_TOKEN: isNil(env.GITHUB_ACTION) ? undefined : 'x-access-token:',
|
||||
GL_TOKEN: 'gitlab-ci-token:',
|
||||
GITLAB_TOKEN: 'gitlab-ci-token:',
|
||||
BB_TOKEN: 'x-token-auth:',
|
||||
BITBUCKET_TOKEN: 'x-token-auth:',
|
||||
BB_TOKEN_BASIC_AUTH: '',
|
||||
BITBUCKET_TOKEN_BASIC_AUTH: '',
|
||||
};
|
||||
|
||||
let {repositoryUrl} = context.options;
|
||||
const info = hostedGitInfo.fromUrl(repositoryUrl, {noGitPlus: true});
|
||||
const {protocol, ...parsed} = parse(repositoryUrl);
|
||||
|
||||
@@ -38,19 +87,34 @@ module.exports = async ({cwd, env, options: {repositoryUrl, branch}}) => {
|
||||
|
||||
// Test if push is allowed without transforming the URL (e.g. is ssh keys are set up)
|
||||
try {
|
||||
await verifyAuth(repositoryUrl, branch, {cwd, env});
|
||||
} catch (error) {
|
||||
const envVar = Object.keys(GIT_TOKENS).find(envVar => !isNil(env[envVar]));
|
||||
const gitCredentials = `${GIT_TOKENS[envVar] || ''}${env[envVar] || ''}`;
|
||||
debug('Verifying ssh auth by attempting to push to %s', repositoryUrl);
|
||||
await verifyAuth(repositoryUrl, branch.name, {cwd, env});
|
||||
} catch (_) {
|
||||
debug('SSH key auth failed, falling back to https.');
|
||||
const envVars = Object.keys(GIT_TOKENS).filter((envVar) => !isNil(env[envVar]));
|
||||
|
||||
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',
|
||||
});
|
||||
// Skip verification if there is no ambiguity on which env var to use for authentication
|
||||
if (envVars.length === 1) {
|
||||
const gitCredentials = `${GIT_TOKENS[envVars[0]] || ''}${env[envVars[0]]}`;
|
||||
return formatAuthUrl(protocol, repositoryUrl, gitCredentials);
|
||||
}
|
||||
|
||||
if (envVars.length > 1) {
|
||||
debug(`Found ${envVars.length} credentials in environment, trying all of them`);
|
||||
|
||||
const candidateRepositoryUrls = [];
|
||||
for (const envVar of envVars) {
|
||||
const gitCredentials = `${GIT_TOKENS[envVar] || ''}${env[envVar]}`;
|
||||
const authUrl = formatAuthUrl(protocol, repositoryUrl, gitCredentials);
|
||||
candidateRepositoryUrls.push(ensureValidAuthUrl(context, authUrl));
|
||||
}
|
||||
|
||||
const validRepositoryUrls = await Promise.all(candidateRepositoryUrls);
|
||||
const chosenAuthUrlIndex = validRepositoryUrls.findIndex((url) => url !== null);
|
||||
if (chosenAuthUrlIndex > -1) {
|
||||
debug(`Using "${envVars[chosenAuthUrlIndex]}" to authenticate`);
|
||||
return validRepositoryUrls[chosenAuthUrlIndex];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+18
-25
@@ -1,51 +1,44 @@
|
||||
const {escapeRegExp, template} = require('lodash');
|
||||
const {isUndefined} = require('lodash');
|
||||
const semver = require('semver');
|
||||
const pLocate = require('p-locate');
|
||||
const debug = require('debug')('semantic-release:get-last-release');
|
||||
const {getTags, isRefInHistory, getTagHead} = require('./git');
|
||||
const {makeTag, isSameChannel} = require('./utils');
|
||||
|
||||
/**
|
||||
* Last release.
|
||||
*
|
||||
* @typedef {Object} LastRelease
|
||||
* @property {string} version The version number of the last release.
|
||||
* @property {string} [gitHead] The Git reference used to make the last release.
|
||||
* @property {string} gitHead The Git reference used to make the last release.
|
||||
* @property {string} gitTag The git tag associated with the last release.
|
||||
* @property {string} channel The channel on which of the last release was published.
|
||||
* @property {string} name The name of the last release.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Determine the Git tag and version of the last tagged release.
|
||||
*
|
||||
* - Obtain all the tags referencing commits in the current branch history
|
||||
* - Filter out the ones that are not valid semantic version or doesn't match the `tagFormat`
|
||||
* - Filter out the branch tags that are not valid semantic version
|
||||
* - Sort the versions
|
||||
* - Retrive the highest version
|
||||
*
|
||||
* @param {Object} context semantic-release context.
|
||||
* @param {Object} params Function parameters.
|
||||
* @param {Object} params.before Find only releases with version number lower than this version.
|
||||
*
|
||||
* @return {Promise<LastRelease>} The last tagged release or `undefined` if none is found.
|
||||
* @return {LastRelease} The last tagged release or empty object if none is found.
|
||||
*/
|
||||
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 not be present in the `tagFormat`.
|
||||
const tagRegexp = `^${escapeRegExp(template(tagFormat)({version: ' '})).replace(' ', '(.+)')}`;
|
||||
const tags = (await getTags({cwd, env}))
|
||||
.map(tag => ({gitTag: tag, version: (tag.match(tagRegexp) || new Array(2))[1]}))
|
||||
module.exports = ({branch, options: {tagFormat}}, {before} = {}) => {
|
||||
const [{version, gitTag, channels} = {}] = branch.tags
|
||||
.filter(
|
||||
tag => tag.version && semver.valid(semver.clean(tag.version)) && !semver.prerelease(semver.clean(tag.version))
|
||||
(tag) =>
|
||||
((branch.type === 'prerelease' && tag.channels.some((channel) => isSameChannel(branch.channel, channel))) ||
|
||||
!semver.prerelease(tag.version)) &&
|
||||
(isUndefined(before) || semver.lt(tag.version, before))
|
||||
)
|
||||
.sort((a, b) => semver.rcompare(a.version, b.version));
|
||||
|
||||
debug('found tags: %o', tags);
|
||||
|
||||
const tag = await pLocate(tags, tag => isRefInHistory(tag.gitTag, {cwd, env}), {preserveOrder: true});
|
||||
|
||||
if (tag) {
|
||||
logger.log(`Found git tag ${tag.gitTag} associated with version ${tag.version}`);
|
||||
return {gitHead: await getTagHead(tag.gitTag, {cwd, env}), ...tag};
|
||||
if (gitTag) {
|
||||
return {version, gitTag, channels, gitHead: gitTag, name: makeTag(tagFormat, version)};
|
||||
}
|
||||
|
||||
logger.log('No git tag version found');
|
||||
return {};
|
||||
};
|
||||
|
||||
+25
-5
@@ -1,13 +1,33 @@
|
||||
const semver = require('semver');
|
||||
const {FIRST_RELEASE} = require('./definitions/constants');
|
||||
const {FIRST_RELEASE, FIRSTPRERELEASE} = require('./definitions/constants');
|
||||
const {isSameChannel, getLatestVersion, tagsToVersions, highest} = require('./utils');
|
||||
|
||||
module.exports = ({nextRelease: {type}, lastRelease, logger}) => {
|
||||
module.exports = ({branch, nextRelease: {type, channel}, lastRelease, logger}) => {
|
||||
let version;
|
||||
if (lastRelease.version) {
|
||||
version = semver.inc(lastRelease.version, type);
|
||||
logger.log(`The next release version is ${version}`);
|
||||
const {major, minor, patch} = semver.parse(lastRelease.version);
|
||||
|
||||
if (branch.type === 'prerelease') {
|
||||
if (
|
||||
semver.prerelease(lastRelease.version) &&
|
||||
lastRelease.channels.some((lastReleaseChannel) => isSameChannel(lastReleaseChannel, channel))
|
||||
) {
|
||||
version = highest(
|
||||
semver.inc(lastRelease.version, 'prerelease'),
|
||||
`${semver.inc(getLatestVersion(tagsToVersions(branch.tags), {withPrerelease: true}), type)}-${
|
||||
branch.prerelease
|
||||
}.${FIRSTPRERELEASE}`
|
||||
);
|
||||
} else {
|
||||
version = `${semver.inc(`${major}.${minor}.${patch}`, type)}-${branch.prerelease}.${FIRSTPRERELEASE}`;
|
||||
}
|
||||
} else {
|
||||
version = semver.inc(lastRelease.version, type);
|
||||
}
|
||||
|
||||
logger.log('The next release version is %s', version);
|
||||
} else {
|
||||
version = FIRST_RELEASE;
|
||||
version = branch.type === 'prerelease' ? `${FIRST_RELEASE}-${branch.prerelease}.${FIRSTPRERELEASE}` : FIRST_RELEASE;
|
||||
logger.log(`There is no previous release, the next release version is ${version}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
const {uniqBy, intersection} = require('lodash');
|
||||
const semver = require('semver');
|
||||
const semverDiff = require('semver-diff');
|
||||
const getLastRelease = require('./get-last-release');
|
||||
const {makeTag, getLowerBound} = require('./utils');
|
||||
|
||||
/**
|
||||
* Find releases that have been merged from from a higher branch but not added on the channel of the current branch.
|
||||
*
|
||||
* @param {Object} context semantic-release context.
|
||||
*
|
||||
* @return {Array<Object>} Last release and next release to be added on the channel of the current branch.
|
||||
*/
|
||||
module.exports = (context) => {
|
||||
const {
|
||||
branch,
|
||||
branches,
|
||||
options: {tagFormat},
|
||||
} = context;
|
||||
|
||||
const higherChannels = branches
|
||||
// Consider only releases of higher branches
|
||||
.slice(branches.findIndex(({name}) => name === branch.name) + 1)
|
||||
// Exclude prerelease branches
|
||||
.filter(({type}) => type !== 'prerelease')
|
||||
.map(({channel}) => channel || null);
|
||||
|
||||
const versiontoAdd = uniqBy(
|
||||
branch.tags.filter(
|
||||
({channels, version}) =>
|
||||
!channels.includes(branch.channel || null) &&
|
||||
intersection(channels, higherChannels).length > 0 &&
|
||||
(branch.type !== 'maintenance' || semver.gte(version, getLowerBound(branch.mergeRange)))
|
||||
),
|
||||
'version'
|
||||
).sort((a, b) => semver.compare(b.version, a.version))[0];
|
||||
|
||||
if (versiontoAdd) {
|
||||
const {version, gitTag, channels} = versiontoAdd;
|
||||
const lastRelease = getLastRelease(context, {before: version});
|
||||
if (semver.gt(getLastRelease(context).version, version)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const type = lastRelease.version ? semverDiff(lastRelease.version, version) : 'major';
|
||||
const name = makeTag(tagFormat, version);
|
||||
return {
|
||||
lastRelease,
|
||||
currentRelease: {type, version, channels, gitTag, name, gitHead: gitTag},
|
||||
nextRelease: {
|
||||
type,
|
||||
version,
|
||||
channel: branch.channel || null,
|
||||
gitTag: makeTag(tagFormat, version),
|
||||
name,
|
||||
gitHead: gitTag,
|
||||
},
|
||||
};
|
||||
}
|
||||
};
|
||||
+198
-47
@@ -1,5 +1,10 @@
|
||||
const gitLogParser = require('git-log-parser');
|
||||
const getStream = require('get-stream');
|
||||
const execa = require('execa');
|
||||
const debug = require('debug')('semantic-release:git');
|
||||
const {GIT_NOTE_REF} = require('./definitions/constants');
|
||||
|
||||
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
|
||||
|
||||
/**
|
||||
* Get the commit sha for a given tag.
|
||||
@@ -7,64 +12,143 @@ const debug = require('debug')('semantic-release:git');
|
||||
* @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`.
|
||||
* @return {String} The commit sha of the tag in parameter or `null`.
|
||||
*/
|
||||
async function getTagHead(tagName, execaOpts) {
|
||||
try {
|
||||
return await execa.stdout('git', ['rev-list', '-1', tagName], execaOpts);
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
async function getTagHead(tagName, execaOptions) {
|
||||
return (await execa('git', ['rev-list', '-1', tagName], execaOptions)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the repository tags.
|
||||
* Get all the tags for a given branch.
|
||||
*
|
||||
* @param {String} branch The branch for which to retrieve the tags.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Array<String>} List of git tags.
|
||||
* @throws {Error} If the `git` command fails.
|
||||
*/
|
||||
async function getTags(execaOpts) {
|
||||
return (await execa.stdout('git', ['tag'], execaOpts))
|
||||
async function getTags(branch, execaOptions) {
|
||||
return (await execa('git', ['tag', '--merged', branch], execaOptions)).stdout
|
||||
.split('\n')
|
||||
.map(tag => tag.trim())
|
||||
.map((tag) => tag.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify if the `ref` is in the direct history of the current branch.
|
||||
* Retrieve a range of commits.
|
||||
*
|
||||
* @param {String} ref The reference to look for.
|
||||
* @param {String} from to includes all commits made after this sha (does not include this sha).
|
||||
* @param {String} to to includes all commits made before this sha (also include this sha).
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
* @return {Promise<Array<Object>>} The list of commits between `from` and `to`.
|
||||
*/
|
||||
async function getCommits(from, to, execaOptions) {
|
||||
return (
|
||||
await getStream.array(
|
||||
gitLogParser.parse(
|
||||
{_: `${from ? from + '..' : ''}${to}`},
|
||||
{cwd: execaOptions.cwd, env: {...process.env, ...execaOptions.env}}
|
||||
)
|
||||
)
|
||||
).map(({message, gitTags, ...commit}) => ({...commit, message: message.trim(), gitTags: gitTags.trim()}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the repository branches.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @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 {Array<String>} List of git branches.
|
||||
* @throws {Error} If the `git` command fails.
|
||||
*/
|
||||
async function isRefInHistory(ref, execaOpts) {
|
||||
try {
|
||||
await execa('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], execaOpts);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error.code === 1) {
|
||||
return false;
|
||||
}
|
||||
async function getBranches(repositoryUrl, execaOptions) {
|
||||
return (await execa('git', ['ls-remote', '--heads', repositoryUrl], execaOptions)).stdout
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
.map((branch) => branch.match(/^.+refs\/heads\/(?<branch>.+)$/)[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify if the `ref` exits
|
||||
*
|
||||
* @param {String} ref The reference to verify.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Boolean} `true` if the reference exists, falsy otherwise.
|
||||
*/
|
||||
async function isRefExists(ref, execaOptions) {
|
||||
try {
|
||||
return (await execa('git', ['rev-parse', '--verify', ref], execaOptions)).exitCode === 0;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unshallow the git repository if necessary and fetch all the tags.
|
||||
* Fetch all the tags from a branch. Unshallow if necessary.
|
||||
* This will update the local branch from the latest on the remote if:
|
||||
* - The branch is not the one that triggered the CI
|
||||
* - The CI created a detached head
|
||||
*
|
||||
* Otherwise it just calls `git fetch` without specifying the `refspec` option to avoid overwritting the head commit set by the CI.
|
||||
*
|
||||
* The goal is to retrieve the informations on all the release branches without "disturbing" the CI, leaving the trigger branch or the detached head intact.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {String} branch The repository branch to fetch.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function fetch(repositoryUrl, branch, ciBranch, execaOptions) {
|
||||
const isDetachedHead =
|
||||
(await execa('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {...execaOptions, reject: false})).stdout === 'HEAD';
|
||||
|
||||
try {
|
||||
await execa(
|
||||
'git',
|
||||
[
|
||||
'fetch',
|
||||
'--unshallow',
|
||||
'--tags',
|
||||
...(branch === ciBranch && !isDetachedHead
|
||||
? [repositoryUrl]
|
||||
: ['--update-head-ok', repositoryUrl, `+refs/heads/${branch}:refs/heads/${branch}`]),
|
||||
],
|
||||
execaOptions
|
||||
);
|
||||
} catch (_) {
|
||||
await execa(
|
||||
'git',
|
||||
[
|
||||
'fetch',
|
||||
'--tags',
|
||||
...(branch === ciBranch && !isDetachedHead
|
||||
? [repositoryUrl]
|
||||
: ['--update-head-ok', repositoryUrl, `+refs/heads/${branch}:refs/heads/${branch}`]),
|
||||
],
|
||||
execaOptions
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unshallow the git repository if necessary and fetch all the notes.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function fetch(repositoryUrl, execaOpts) {
|
||||
async function fetchNotes(repositoryUrl, execaOptions) {
|
||||
try {
|
||||
await execa('git', ['fetch', '--unshallow', '--tags', repositoryUrl], execaOpts);
|
||||
} catch (error) {
|
||||
await execa('git', ['fetch', '--tags', repositoryUrl], execaOpts);
|
||||
await execa(
|
||||
'git',
|
||||
['fetch', '--unshallow', repositoryUrl, `+refs/notes/${GIT_NOTE_REF}:refs/notes/${GIT_NOTE_REF}`],
|
||||
execaOptions
|
||||
);
|
||||
} catch (_) {
|
||||
await execa('git', ['fetch', repositoryUrl, `+refs/notes/${GIT_NOTE_REF}:refs/notes/${GIT_NOTE_REF}`], {
|
||||
...execaOptions,
|
||||
reject: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,8 +159,8 @@ async function fetch(repositoryUrl, execaOpts) {
|
||||
*
|
||||
* @return {String} the sha of the HEAD commit.
|
||||
*/
|
||||
function getGitHead(execaOpts) {
|
||||
return execa.stdout('git', ['rev-parse', 'HEAD'], execaOpts);
|
||||
async function getGitHead(execaOptions) {
|
||||
return (await execa('git', ['rev-parse', 'HEAD'], execaOptions)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -86,9 +170,9 @@ function getGitHead(execaOpts) {
|
||||
*
|
||||
* @return {string} The value of the remote git URL.
|
||||
*/
|
||||
async function repoUrl(execaOpts) {
|
||||
async function repoUrl(execaOptions) {
|
||||
try {
|
||||
return await execa.stdout('git', ['config', '--get', 'remote.origin.url'], execaOpts);
|
||||
return (await execa('git', ['config', '--get', 'remote.origin.url'], execaOptions)).stdout;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
@@ -101,9 +185,9 @@ async function repoUrl(execaOpts) {
|
||||
*
|
||||
* @return {Boolean} `true` if the current working directory is in a git repository, falsy otherwise.
|
||||
*/
|
||||
async function isGitRepo(execaOpts) {
|
||||
async function isGitRepo(execaOptions) {
|
||||
try {
|
||||
return (await execa('git', ['rev-parse', '--git-dir'], execaOpts)).code === 0;
|
||||
return (await execa('git', ['rev-parse', '--git-dir'], execaOptions)).exitCode === 0;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
@@ -113,14 +197,14 @@ async function isGitRepo(execaOpts) {
|
||||
* Verify the write access authorization to remote repository with push dry-run.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {String} branch The repositoru branch for which to verify write access.
|
||||
* @param {String} branch The repository branch for which to verify write access.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @throws {Error} if not authorized to push.
|
||||
*/
|
||||
async function verifyAuth(repositoryUrl, branch, execaOpts) {
|
||||
async function verifyAuth(repositoryUrl, branch, execaOptions) {
|
||||
try {
|
||||
await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`], execaOpts);
|
||||
await execa('git', ['push', '--dry-run', '--no-verify', repositoryUrl, `HEAD:${branch}`], execaOptions);
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
throw error;
|
||||
@@ -131,12 +215,13 @@ async function verifyAuth(repositoryUrl, branch, execaOpts) {
|
||||
* Tag the commit head on the local repository.
|
||||
*
|
||||
* @param {String} tagName The name of the tag.
|
||||
* @param {String} ref The Git reference to tag.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @throws {Error} if the tag creation failed.
|
||||
*/
|
||||
async function tag(tagName, execaOpts) {
|
||||
await execa('git', ['tag', tagName], execaOpts);
|
||||
async function tag(tagName, ref, execaOptions) {
|
||||
await execa('git', ['tag', tagName, ref], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -147,8 +232,20 @@ async function tag(tagName, execaOpts) {
|
||||
*
|
||||
* @throws {Error} if the push failed.
|
||||
*/
|
||||
async function push(repositoryUrl, execaOpts) {
|
||||
await execa('git', ['push', '--tags', repositoryUrl], execaOpts);
|
||||
async function push(repositoryUrl, execaOptions) {
|
||||
await execa('git', ['push', '--tags', repositoryUrl], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push notes to the remote repository.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @throws {Error} if the push failed.
|
||||
*/
|
||||
async function pushNotes(repositoryUrl, execaOptions) {
|
||||
await execa('git', ['push', repositoryUrl, `refs/notes/${GIT_NOTE_REF}`], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -159,9 +256,25 @@ async function push(repositoryUrl, execaOpts) {
|
||||
*
|
||||
* @return {Boolean} `true` if valid, falsy otherwise.
|
||||
*/
|
||||
async function verifyTagName(tagName, execaOpts) {
|
||||
async function verifyTagName(tagName, execaOptions) {
|
||||
try {
|
||||
return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOpts)).code === 0;
|
||||
return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOptions)).exitCode === 0;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a branch name is a valid Git reference.
|
||||
*
|
||||
* @param {String} branch the branch name to verify.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Boolean} `true` if valid, falsy otherwise.
|
||||
*/
|
||||
async function verifyBranchName(branch, execaOptions) {
|
||||
try {
|
||||
return (await execa('git', ['check-ref-format', `refs/heads/${branch}`], execaOptions)).exitCode === 0;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
@@ -170,31 +283,69 @@ async function verifyTagName(tagName, execaOpts) {
|
||||
/**
|
||||
* Verify the local branch is up to date with the remote one.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {String} branch The repository branch for which to verify status.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @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);
|
||||
async function isBranchUpToDate(repositoryUrl, branch, execaOptions) {
|
||||
return (
|
||||
(await getGitHead(execaOptions)) ===
|
||||
(await execa('git', ['ls-remote', '--heads', repositoryUrl, branch], execaOptions)).stdout.match(/^(?<ref>\w+)?/)[1]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get and parse the JSON note of a given reference.
|
||||
*
|
||||
* @param {String} ref The Git reference for which to retrieve the note.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Object} the parsed JSON note if there is one, an empty object otherwise.
|
||||
*/
|
||||
async function getNote(ref, execaOptions) {
|
||||
try {
|
||||
return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts);
|
||||
return JSON.parse((await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'show', ref], execaOptions)).stdout);
|
||||
} catch (error) {
|
||||
if (error.exitCode === 1) {
|
||||
return {};
|
||||
}
|
||||
|
||||
debug(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get and parse the JSON note of a given reference.
|
||||
*
|
||||
* @param {Object} note The object to save in the reference note.
|
||||
* @param {String} ref The Git reference to add the note to.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function addNote(note, ref, execaOptions) {
|
||||
await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'add', '-f', '-m', JSON.stringify(note), ref], execaOptions);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getTagHead,
|
||||
getTags,
|
||||
isRefInHistory,
|
||||
getCommits,
|
||||
getBranches,
|
||||
isRefExists,
|
||||
fetch,
|
||||
fetchNotes,
|
||||
getGitHead,
|
||||
repoUrl,
|
||||
isGitRepo,
|
||||
verifyAuth,
|
||||
tag,
|
||||
push,
|
||||
pushNotes,
|
||||
verifyTagName,
|
||||
isBranchUpToDate,
|
||||
verifyBranchName,
|
||||
getNote,
|
||||
addNote,
|
||||
};
|
||||
|
||||
+14
-6
@@ -1,12 +1,20 @@
|
||||
const {escapeRegExp, size, isString} = require('lodash');
|
||||
const {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('./definitions/constants');
|
||||
|
||||
module.exports = env => {
|
||||
const toReplace = Object.keys(env).filter(
|
||||
envVar => /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE
|
||||
);
|
||||
module.exports = (env) => {
|
||||
const toReplace = Object.keys(env).filter((envVar) => {
|
||||
// https://github.com/semantic-release/semantic-release/issues/1558
|
||||
if (envVar === 'GOPRIVATE') {
|
||||
return false;
|
||||
}
|
||||
|
||||
const regexp = new RegExp(toReplace.map(envVar => escapeRegExp(env[envVar])).join('|'), 'g');
|
||||
return output =>
|
||||
return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;
|
||||
});
|
||||
|
||||
const regexp = new RegExp(
|
||||
toReplace.map((envVar) => `${escapeRegExp(env[envVar])}|${escapeRegExp(encodeURI(env[envVar]))}`).join('|'),
|
||||
'g'
|
||||
);
|
||||
return (output) =>
|
||||
output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;
|
||||
};
|
||||
|
||||
@@ -46,14 +46,14 @@ module.exports = (context, pluginsPath) => {
|
||||
|
||||
const pluginsConf = Object.entries(PLUGINS_DEFINITIONS).reduce(
|
||||
(pluginsConf, [type, {required, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]) => {
|
||||
let pluginOpts;
|
||||
let pluginOptions;
|
||||
|
||||
if (isNil(options[type]) && def) {
|
||||
pluginOpts = def;
|
||||
pluginOptions = def;
|
||||
} 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 =>
|
||||
options[type] = castArray(plugins[type]).map((plugin) =>
|
||||
plugin ? [plugin[0], Object.assign(plugin[1], options[type])] : plugin
|
||||
);
|
||||
}
|
||||
@@ -63,10 +63,10 @@ module.exports = (context, pluginsPath) => {
|
||||
return pluginsConf;
|
||||
}
|
||||
|
||||
pluginOpts = options[type];
|
||||
pluginOptions = options[type];
|
||||
}
|
||||
|
||||
const steps = castArray(pluginOpts).map(pluginOpt =>
|
||||
const steps = castArray(pluginOptions).map((pluginOpt) =>
|
||||
normalize(
|
||||
{...context, options: omit(options, Object.keys(PLUGINS_DEFINITIONS), 'plugins')},
|
||||
type,
|
||||
@@ -75,7 +75,7 @@ module.exports = (context, pluginsPath) => {
|
||||
)
|
||||
);
|
||||
|
||||
pluginsConf[type] = async input =>
|
||||
pluginsConf[type] = async (input) =>
|
||||
postprocess(
|
||||
await pipeline(steps, pipelineConfig && pipelineConfig(pluginsConf, logger))(await preprocess(input)),
|
||||
input
|
||||
|
||||
@@ -26,7 +26,7 @@ module.exports = (context, type, pluginOpt, pluginsPath) => {
|
||||
throw getError('EPLUGIN', {type, pluginName});
|
||||
}
|
||||
|
||||
const validator = async input => {
|
||||
const validator = async (input) => {
|
||||
const {dryRun, outputValidator} = PLUGINS_DEFINITIONS[type] || {};
|
||||
try {
|
||||
if (!input.options.dryRun || dryRun) {
|
||||
@@ -48,7 +48,7 @@ module.exports = (context, type, pluginOpt, pluginsPath) => {
|
||||
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}));
|
||||
extractErrors(error).forEach((err) => Object.assign(err, {pluginName}));
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -25,7 +25,7 @@ const {extractErrors} = require('../utils');
|
||||
*
|
||||
* @return {Pipeline} A Function that execute the `steps` sequencially
|
||||
*/
|
||||
module.exports = (steps, {settleAll = false, getNextInput = identity, transform = identity} = {}) => async input => {
|
||||
module.exports = (steps, {settleAll = false, getNextInput = identity, transform = identity} = {}) => async (input) => {
|
||||
const results = [];
|
||||
const errors = [];
|
||||
await pReduce(
|
||||
|
||||
@@ -2,8 +2,8 @@ const {dirname} = require('path');
|
||||
const {isString, isFunction, castArray, isArray, isPlainObject, isNil} = require('lodash');
|
||||
const resolveFrom = require('resolve-from');
|
||||
|
||||
const validateSteps = conf => {
|
||||
return conf.every(conf => {
|
||||
const validateSteps = (conf) => {
|
||||
return conf.every((conf) => {
|
||||
if (
|
||||
isArray(conf) &&
|
||||
(conf.length === 1 || conf.length === 2) &&
|
||||
|
||||
+88
-7
@@ -1,4 +1,5 @@
|
||||
const {isFunction} = require('lodash');
|
||||
const {isFunction, union, template} = require('lodash');
|
||||
const semver = require('semver');
|
||||
const hideSensitive = require('./hide-sensitive');
|
||||
|
||||
function extractErrors(err) {
|
||||
@@ -7,14 +8,94 @@ function extractErrors(err) {
|
||||
|
||||
function hideSensitiveValues(env, objs) {
|
||||
const hideFunction = hideSensitive(env);
|
||||
return objs.map(obj => {
|
||||
Object.getOwnPropertyNames(obj).forEach(prop => {
|
||||
if (obj[prop]) {
|
||||
obj[prop] = hideFunction(obj[prop]);
|
||||
return objs.map((object) => {
|
||||
Object.getOwnPropertyNames(object).forEach((prop) => {
|
||||
if (object[prop]) {
|
||||
object[prop] = hideFunction(object[prop]);
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
return object;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {extractErrors, hideSensitiveValues};
|
||||
function tagsToVersions(tags) {
|
||||
return tags.map(({version}) => version);
|
||||
}
|
||||
|
||||
function isMajorRange(range) {
|
||||
return /^\d+\.x(?:\.x)?$/i.test(range);
|
||||
}
|
||||
|
||||
function isMaintenanceRange(range) {
|
||||
return /^\d+\.(?:\d+|x)(?:\.x)?$/i.test(range);
|
||||
}
|
||||
|
||||
function getUpperBound(range) {
|
||||
const result = semver.valid(range)
|
||||
? range
|
||||
: ((semver.validRange(range) || '').match(/<(?<upperBound>\d+\.\d+\.\d+(-\d+)?)$/) || [])[1];
|
||||
|
||||
return result
|
||||
? // https://github.com/npm/node-semver/issues/322
|
||||
result.replace(/-\d+$/, '')
|
||||
: result;
|
||||
}
|
||||
|
||||
function getLowerBound(range) {
|
||||
return ((semver.validRange(range) || '').match(/(?<lowerBound>\d+\.\d+\.\d+)/) || [])[1];
|
||||
}
|
||||
|
||||
function highest(version1, version2) {
|
||||
return version1 && version2 ? (semver.gt(version1, version2) ? version1 : version2) : version1 || version2;
|
||||
}
|
||||
|
||||
function lowest(version1, version2) {
|
||||
return version1 && version2 ? (semver.lt(version1, version2) ? version1 : version2) : version1 || version2;
|
||||
}
|
||||
|
||||
function getLatestVersion(versions, {withPrerelease} = {}) {
|
||||
return versions.filter((version) => withPrerelease || !semver.prerelease(version)).sort(semver.rcompare)[0];
|
||||
}
|
||||
|
||||
function getEarliestVersion(versions, {withPrerelease} = {}) {
|
||||
return versions.filter((version) => withPrerelease || !semver.prerelease(version)).sort(semver.compare)[0];
|
||||
}
|
||||
|
||||
function getFirstVersion(versions, lowerBranches) {
|
||||
const lowerVersion = union(...lowerBranches.map(({tags}) => tagsToVersions(tags))).sort(semver.rcompare);
|
||||
if (lowerVersion[0]) {
|
||||
return versions.sort(semver.compare).find((version) => semver.gt(version, lowerVersion[0]));
|
||||
}
|
||||
|
||||
return getEarliestVersion(versions);
|
||||
}
|
||||
|
||||
function getRange(min, max) {
|
||||
return `>=${min}${max ? ` <${max}` : ''}`;
|
||||
}
|
||||
|
||||
function makeTag(tagFormat, version) {
|
||||
return template(tagFormat)({version});
|
||||
}
|
||||
|
||||
function isSameChannel(channel, otherChannel) {
|
||||
return channel === otherChannel || (!channel && !otherChannel);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
extractErrors,
|
||||
hideSensitiveValues,
|
||||
tagsToVersions,
|
||||
isMajorRange,
|
||||
isMaintenanceRange,
|
||||
getUpperBound,
|
||||
getLowerBound,
|
||||
highest,
|
||||
lowest,
|
||||
getLatestVersion,
|
||||
getEarliestVersion,
|
||||
getFirstVersion,
|
||||
getRange,
|
||||
makeTag,
|
||||
isSameChannel,
|
||||
};
|
||||
|
||||
+17
-4
@@ -1,9 +1,14 @@
|
||||
const {template} = require('lodash');
|
||||
const {template, isString, isPlainObject} = require('lodash');
|
||||
const AggregateError = require('aggregate-error');
|
||||
const {isGitRepo, verifyTagName} = require('./git');
|
||||
const getError = require('./get-error');
|
||||
|
||||
module.exports = async ({cwd, env, options: {repositoryUrl, tagFormat}}) => {
|
||||
module.exports = async (context) => {
|
||||
const {
|
||||
cwd,
|
||||
env,
|
||||
options: {repositoryUrl, tagFormat, branches},
|
||||
} = context;
|
||||
const errors = [];
|
||||
|
||||
if (!(await isGitRepo({cwd, env}))) {
|
||||
@@ -14,16 +19,24 @@ module.exports = async ({cwd, env, options: {repositoryUrl, tagFormat}}) => {
|
||||
|
||||
// Verify that compiling the `tagFormat` produce a valid Git tag
|
||||
if (!(await verifyTagName(template(tagFormat)({version: '0.0.0'})))) {
|
||||
errors.push(getError('EINVALIDTAGFORMAT', {tagFormat}));
|
||||
errors.push(getError('EINVALIDTAGFORMAT', context));
|
||||
}
|
||||
|
||||
// Verify the `tagFormat` contains the variable `version` by compiling the `tagFormat` template
|
||||
// with a space as the `version` value and verify the result contains the space.
|
||||
// The space is used as it's an invalid tag character, so it's guaranteed to no be present in the `tagFormat`.
|
||||
if ((template(tagFormat)({version: ' '}).match(/ /g) || []).length !== 1) {
|
||||
errors.push(getError('ETAGNOVERSION', {tagFormat}));
|
||||
errors.push(getError('ETAGNOVERSION', context));
|
||||
}
|
||||
|
||||
branches.forEach((branch) => {
|
||||
if (
|
||||
!((isString(branch) && branch.trim()) || (isPlainObject(branch) && isString(branch.name) && branch.name.trim()))
|
||||
) {
|
||||
errors.push(getError('EINVALIDBRANCH', {branch}));
|
||||
}
|
||||
});
|
||||
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
|
||||
+39
-36
@@ -3,73 +3,74 @@
|
||||
"description": "Automated semver compliant package publishing",
|
||||
"version": "0.0.0-development",
|
||||
"author": "Stephan Bönnemann <stephan@boennemann.me> (http://boennemann.me)",
|
||||
"ava": {
|
||||
"files": [
|
||||
"test/**/*.test.js"
|
||||
],
|
||||
"timeout": "2m"
|
||||
},
|
||||
"bin": {
|
||||
"semantic-release": "bin/semantic-release.js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/semantic-release/semantic-release/issues"
|
||||
},
|
||||
"config": {
|
||||
"commitizen": {
|
||||
"path": "cz-conventional-changelog"
|
||||
}
|
||||
},
|
||||
"contributors": [
|
||||
"Gregor Martynus (https://twitter.com/gr2m)",
|
||||
"Pierre Vanduynslager (https://twitter.com/@pvdlg_)"
|
||||
],
|
||||
"dependencies": {
|
||||
"@semantic-release/commit-analyzer": "^6.1.0",
|
||||
"@semantic-release/commit-analyzer": "^8.0.0",
|
||||
"@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.2",
|
||||
"@semantic-release/github": "^7.0.0",
|
||||
"@semantic-release/npm": "^7.0.0",
|
||||
"@semantic-release/release-notes-generator": "^9.0.0",
|
||||
"aggregate-error": "^3.0.0",
|
||||
"cosmiconfig": "^5.0.1",
|
||||
"cosmiconfig": "^6.0.0",
|
||||
"debug": "^4.0.0",
|
||||
"env-ci": "^3.0.0",
|
||||
"execa": "^1.0.0",
|
||||
"env-ci": "^5.0.0",
|
||||
"execa": "^4.0.0",
|
||||
"figures": "^3.0.0",
|
||||
"find-versions": "^3.0.0",
|
||||
"get-stream": "^5.0.0",
|
||||
"git-log-parser": "^1.2.0",
|
||||
"hook-std": "^2.0.0",
|
||||
"hosted-git-info": "^2.7.1",
|
||||
"lodash": "^4.17.4",
|
||||
"marked": "^0.6.0",
|
||||
"marked-terminal": "^3.2.0",
|
||||
"p-locate": "^4.0.0",
|
||||
"hosted-git-info": "^3.0.0",
|
||||
"lodash": "^4.17.15",
|
||||
"marked": "^1.0.0",
|
||||
"marked-terminal": "^4.0.0",
|
||||
"micromatch": "^4.0.2",
|
||||
"p-each-series": "^2.1.0",
|
||||
"p-reduce": "^2.0.0",
|
||||
"read-pkg-up": "^6.0.0",
|
||||
"read-pkg-up": "^7.0.0",
|
||||
"resolve-from": "^5.0.0",
|
||||
"semver": "^6.0.0",
|
||||
"semver": "^7.3.2",
|
||||
"semver-diff": "^3.1.1",
|
||||
"signale": "^1.2.1",
|
||||
"yargs": "^13.1.0"
|
||||
"yargs": "^15.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"ava": "^1.3.1",
|
||||
"clear-module": "^3.0.0",
|
||||
"ava": "^3.1.0",
|
||||
"clear-module": "^4.0.0",
|
||||
"codecov": "^3.0.0",
|
||||
"commitizen": "^3.0.0",
|
||||
"cz-conventional-changelog": "^2.0.0",
|
||||
"delay": "^4.0.0",
|
||||
"dockerode": "^2.5.2",
|
||||
"dockerode": "^3.0.0",
|
||||
"file-url": "^3.0.0",
|
||||
"fs-extra": "^8.0.0",
|
||||
"got": "^9.0.0",
|
||||
"fs-extra": "^9.0.0",
|
||||
"got": "^11.0.0",
|
||||
"js-yaml": "^3.10.0",
|
||||
"mockserver-client": "^5.1.1",
|
||||
"nock": "^10.0.0",
|
||||
"nyc": "^14.0.0",
|
||||
"nock": "^12.0.0",
|
||||
"nyc": "^15.0.0",
|
||||
"p-retry": "^4.0.0",
|
||||
"proxyquire": "^2.0.0",
|
||||
"sinon": "^7.2.7",
|
||||
"sinon": "^9.0.0",
|
||||
"stream-buffers": "^3.0.2",
|
||||
"tempy": "^0.3.0",
|
||||
"xo": "^0.24.0"
|
||||
"tempy": "^0.5.0",
|
||||
"xo": "^0.29.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.3"
|
||||
"node": ">=10.18"
|
||||
},
|
||||
"files": [
|
||||
"bin",
|
||||
@@ -110,14 +111,13 @@
|
||||
"trailingComma": "es5"
|
||||
},
|
||||
"publishConfig": {
|
||||
"tag": "next"
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/semantic-release/semantic-release.git"
|
||||
},
|
||||
"scripts": {
|
||||
"cm": "git-cz",
|
||||
"codecov": "codecov -f coverage/coverage-final.json",
|
||||
"lint": "xo",
|
||||
"pretest": "npm run lint",
|
||||
@@ -126,6 +126,9 @@
|
||||
},
|
||||
"xo": {
|
||||
"prettier": true,
|
||||
"space": true
|
||||
"space": true,
|
||||
"rules": {
|
||||
"unicorn/string-content": "off"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
const test = require('ava');
|
||||
const {union} = require('lodash');
|
||||
const semver = require('semver');
|
||||
const proxyquire = require('proxyquire');
|
||||
|
||||
const getBranch = (branches, branch) => branches.find(({name}) => name === branch);
|
||||
const release = (branches, name, version) => getBranch(branches, name).tags.push({version});
|
||||
const merge = (branches, source, target, tag) => {
|
||||
getBranch(branches, target).tags = union(
|
||||
getBranch(branches, source).tags.filter(({version}) => !tag || semver.cmp(version, '<=', tag)),
|
||||
getBranch(branches, target).tags
|
||||
);
|
||||
};
|
||||
|
||||
test('Enforce ranges with branching release workflow', async (t) => {
|
||||
const branches = [
|
||||
{name: '1.x', tags: []},
|
||||
{name: '1.0.x', tags: []},
|
||||
{name: 'master', tags: []},
|
||||
{name: 'next', tags: []},
|
||||
{name: 'next-major', tags: []},
|
||||
{name: 'beta', prerelease: true, tags: []},
|
||||
{name: 'alpha', prerelease: true, tags: []},
|
||||
];
|
||||
const getBranches = proxyquire('../../lib/branches', {'./get-tags': () => branches, './expand': () => []});
|
||||
|
||||
let result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, '1.0.x').range, '>=1.0.0 <1.0.0', 'Cannot release on 1.0.x before a releasing on master');
|
||||
t.is(getBranch(result, '1.x').range, '>=1.1.0 <1.0.0', 'Cannot release on 1.x before a releasing on master');
|
||||
t.is(getBranch(result, 'master').range, '>=1.0.0');
|
||||
t.is(getBranch(result, 'next').range, '>=1.0.0');
|
||||
t.is(getBranch(result, 'next-major').range, '>=1.0.0');
|
||||
|
||||
release(branches, 'master', '1.0.0');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, '1.0.x').range, '>=1.0.0 <1.0.0', 'Cannot release on 1.0.x before a releasing on master');
|
||||
t.is(getBranch(result, '1.x').range, '>=1.1.0 <1.0.0', 'Cannot release on 1.x before a releasing on master');
|
||||
t.is(getBranch(result, 'master').range, '>=1.0.0');
|
||||
t.is(getBranch(result, 'next').range, '>=1.0.0');
|
||||
t.is(getBranch(result, 'next-major').range, '>=1.0.0');
|
||||
|
||||
release(branches, 'master', '1.0.1');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=1.0.1', 'Can release only > than 1.0.1 on master');
|
||||
t.is(getBranch(result, 'next').range, '>=1.0.1', 'Can release only > than 1.0.1 on next');
|
||||
t.is(getBranch(result, 'next-major').range, '>=1.0.1', 'Can release only > than 1.0.1 on next-major');
|
||||
|
||||
merge(branches, 'master', 'next');
|
||||
merge(branches, 'master', 'next-major');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=1.0.1', 'Can release only > than 1.0.1 on master');
|
||||
t.is(getBranch(result, 'next').range, '>=1.0.1', 'Can release only > than 1.0.1 on next');
|
||||
t.is(getBranch(result, 'next-major').range, '>=1.0.1', 'Can release only > than 1.0.1 on next-major');
|
||||
|
||||
release(branches, 'next', '1.1.0');
|
||||
release(branches, 'next', '1.1.1');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=1.0.1 <1.1.0', 'Can release only patch, > than 1.0.1 on master');
|
||||
t.is(getBranch(result, 'next').range, '>=1.1.1', 'Can release only > than 1.1.1 on next');
|
||||
t.is(getBranch(result, 'next-major').range, '>=1.1.1', 'Can release > than 1.1.1 on next-major');
|
||||
|
||||
release(branches, 'next-major', '2.0.0');
|
||||
release(branches, 'next-major', '2.0.1');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=1.0.1 <1.1.0', 'Can release only patch, > than 1.0.1 on master');
|
||||
t.is(getBranch(result, 'next').range, '>=1.1.1 <2.0.0', 'Can release only patch or minor, > than 1.1.0 on next');
|
||||
t.is(getBranch(result, 'next-major').range, '>=2.0.1', 'Can release any version, > than 2.0.1 on next-major');
|
||||
|
||||
merge(branches, 'next-major', 'beta');
|
||||
release(branches, 'beta', '3.0.0-beta.1');
|
||||
merge(branches, 'beta', 'alpha');
|
||||
release(branches, 'alpha', '4.0.0-alpha.1');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'next-major').range, '>=2.0.1', 'Can release any version, > than 2.0.1 on next-major');
|
||||
|
||||
merge(branches, 'master', '1.0.x');
|
||||
merge(branches, 'master', '1.x');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=1.0.1 <1.1.0', 'Can release only patch, > than 1.0.1 on master');
|
||||
t.is(
|
||||
getBranch(result, '1.0.x').range,
|
||||
'>=1.0.1 <1.0.1',
|
||||
'Cannot release on 1.0.x before >= 1.1.0 is released on master'
|
||||
);
|
||||
t.is(getBranch(result, '1.x').range, '>=1.1.0 <1.0.1', 'Cannot release on 1.x before >= 1.2.0 is released on master');
|
||||
|
||||
release(branches, 'master', '1.0.2');
|
||||
release(branches, 'master', '1.0.3');
|
||||
release(branches, 'master', '1.0.4');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=1.0.4 <1.1.0', 'Can release only patch, > than 1.0.4 on master');
|
||||
t.is(
|
||||
getBranch(result, '1.0.x').range,
|
||||
'>=1.0.1 <1.0.2',
|
||||
'Cannot release on 1.0.x before >= 1.1.0 is released on master'
|
||||
);
|
||||
t.is(getBranch(result, '1.x').range, '>=1.1.0 <1.0.2', 'Cannot release on 1.x before >= 1.2.0 is released on master');
|
||||
|
||||
merge(branches, 'next', 'master');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
|
||||
t.is(getBranch(result, 'master').range, '>=1.1.1', 'Can release only > than 1.1.1 on master');
|
||||
t.is(getBranch(result, 'next').range, '>=1.1.1 <2.0.0', 'Can release only patch or minor, > than 1.1.1 on next');
|
||||
t.is(getBranch(result, 'next-major').range, '>=2.0.1', 'Can release any version, > than 2.0.1 on next-major');
|
||||
t.is(
|
||||
getBranch(result, '1.0.x').range,
|
||||
'>=1.0.1 <1.0.2',
|
||||
'Cannot release on 1.0.x before 1.0.x version from master are merged'
|
||||
);
|
||||
t.is(getBranch(result, '1.x').range, '>=1.1.0 <1.0.2', 'Cannot release on 1.x before >= 2.0.0 is released on master');
|
||||
|
||||
merge(branches, 'master', '1.0.x', '1.0.4');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=1.1.1', 'Can release only > than 1.1.1 on master');
|
||||
t.is(getBranch(result, '1.0.x').range, '>=1.0.4 <1.1.0', 'Can release on 1.0.x only within range');
|
||||
t.is(getBranch(result, '1.x').range, '>=1.1.0 <1.1.0', 'Cannot release on 1.x before >= 2.0.0 is released on master');
|
||||
|
||||
merge(branches, 'master', '1.x');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=1.1.1', 'Can release only > than 1.1.1 on master');
|
||||
t.is(getBranch(result, '1.0.x').range, '>=1.0.4 <1.1.0', 'Can release on 1.0.x only within range');
|
||||
t.is(getBranch(result, '1.x').range, '>=1.1.1 <1.1.1', 'Cannot release on 1.x before >= 2.0.0 is released on master');
|
||||
|
||||
merge(branches, 'next-major', 'next');
|
||||
merge(branches, 'next', 'master');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=2.0.1', 'Can release only > than 2.0.1 on master');
|
||||
t.is(getBranch(result, 'next').range, '>=2.0.1', 'Can release only > than 2.0.1 on next');
|
||||
t.is(getBranch(result, 'next-major').range, '>=2.0.1', 'Can release only > than 2.0.1 on next-major');
|
||||
t.is(getBranch(result, '1.x').range, '>=1.1.1 <2.0.0', 'Can release on 1.x only within range');
|
||||
|
||||
merge(branches, 'beta', 'master');
|
||||
release(branches, 'master', '3.0.0');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, 'master').range, '>=3.0.0', 'Can release only > than 3.0.0 on master');
|
||||
t.is(getBranch(result, 'next').range, '>=3.0.0', 'Can release only > than 3.0.0 on next');
|
||||
t.is(getBranch(result, 'next-major').range, '>=3.0.0', 'Can release only > than 3.0.0 on next-major');
|
||||
|
||||
branches.push({name: '1.1.x', tags: []});
|
||||
merge(branches, '1.x', '1.1.x');
|
||||
result = (await getBranches('repositoryUrl', 'master', {options: {branches}})).map(({name, range}) => ({
|
||||
name,
|
||||
range,
|
||||
}));
|
||||
t.is(getBranch(result, '1.0.x').range, '>=1.0.4 <1.1.0', 'Can release on 1.0.x only within range');
|
||||
t.is(getBranch(result, '1.1.x').range, '>=1.1.1 <1.2.0', 'Can release on 1.1.x only within range');
|
||||
t.is(getBranch(result, '1.x').range, '>=1.2.0 <2.0.0', 'Can release on 1.x only within range');
|
||||
});
|
||||
|
||||
test('Throw SemanticReleaseError for invalid configurations', async (t) => {
|
||||
const branches = [
|
||||
{name: '123', range: '123', tags: []},
|
||||
{name: '1.x', tags: []},
|
||||
{name: 'maintenance-1', range: '1.x', tags: []},
|
||||
{name: '1.x.x', tags: []},
|
||||
{name: 'beta', prerelease: '', tags: []},
|
||||
{name: 'alpha', prerelease: 'alpha', tags: []},
|
||||
{name: 'preview', prerelease: 'alpha', tags: []},
|
||||
];
|
||||
const getBranches = proxyquire('../../lib/branches', {'./get-tags': () => branches, './expand': () => []});
|
||||
const errors = [...(await t.throwsAsync(getBranches('repositoryUrl', 'master', {options: {branches}})))];
|
||||
|
||||
t.is(errors[0].name, 'SemanticReleaseError');
|
||||
t.is(errors[0].code, 'EMAINTENANCEBRANCH');
|
||||
t.truthy(errors[0].message);
|
||||
t.truthy(errors[0].details);
|
||||
t.is(errors[1].name, 'SemanticReleaseError');
|
||||
t.is(errors[1].code, 'EMAINTENANCEBRANCHES');
|
||||
t.truthy(errors[1].message);
|
||||
t.truthy(errors[1].details);
|
||||
t.is(errors[2].name, 'SemanticReleaseError');
|
||||
t.is(errors[2].code, 'EPRERELEASEBRANCH');
|
||||
t.truthy(errors[2].message);
|
||||
t.truthy(errors[2].details);
|
||||
t.is(errors[3].name, 'SemanticReleaseError');
|
||||
t.is(errors[3].code, 'EPRERELEASEBRANCHES');
|
||||
t.truthy(errors[3].message);
|
||||
t.truthy(errors[3].details);
|
||||
t.is(errors[4].name, 'SemanticReleaseError');
|
||||
t.is(errors[4].code, 'ERELEASEBRANCHES');
|
||||
t.truthy(errors[4].message);
|
||||
t.truthy(errors[4].details);
|
||||
});
|
||||
|
||||
test('Throw a SemanticReleaseError if there is duplicate branches', async (t) => {
|
||||
const branches = [
|
||||
{name: 'master', tags: []},
|
||||
{name: 'master', tags: []},
|
||||
];
|
||||
const getBranches = proxyquire('../../lib/branches', {'./get-tags': () => branches, './expand': () => []});
|
||||
|
||||
const errors = [...(await t.throwsAsync(getBranches('repositoryUrl', 'master', {options: {branches}})))];
|
||||
|
||||
t.is(errors[0].name, 'SemanticReleaseError');
|
||||
t.is(errors[0].code, 'EDUPLICATEBRANCHES');
|
||||
t.truthy(errors[0].message);
|
||||
t.truthy(errors[0].details);
|
||||
});
|
||||
|
||||
test('Throw a SemanticReleaseError for each invalid branch name', async (t) => {
|
||||
const branches = [
|
||||
{name: '~master', tags: []},
|
||||
{name: '^master', tags: []},
|
||||
];
|
||||
const getBranches = proxyquire('../../lib/branches', {'./get-tags': () => branches, './expand': () => []});
|
||||
|
||||
const errors = [...(await t.throwsAsync(getBranches('repositoryUrl', 'master', {options: {branches}})))];
|
||||
|
||||
t.is(errors[0].name, 'SemanticReleaseError');
|
||||
t.is(errors[0].code, 'EINVALIDBRANCHNAME');
|
||||
t.truthy(errors[0].message);
|
||||
t.truthy(errors[0].details);
|
||||
t.is(errors[1].name, 'SemanticReleaseError');
|
||||
t.is(errors[1].code, 'EINVALIDBRANCHNAME');
|
||||
t.truthy(errors[1].message);
|
||||
t.truthy(errors[1].details);
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
const test = require('ava');
|
||||
const expand = require('../../lib/branches/expand');
|
||||
const {gitRepo, gitCommits, gitCheckout, gitPush} = require('../helpers/git-utils');
|
||||
|
||||
test('Expand branches defined with globs', async (t) => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
await gitCheckout('1.0.x', true, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitPush(repositoryUrl, '1.0.x', {cwd});
|
||||
await gitCheckout('1.x.x', true, {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitPush(repositoryUrl, '1.x.x', {cwd});
|
||||
await gitCheckout('2.x', true, {cwd});
|
||||
await gitCommits(['Fourth'], {cwd});
|
||||
await gitPush(repositoryUrl, '2.x', {cwd});
|
||||
await gitCheckout('next', true, {cwd});
|
||||
await gitCommits(['Fifth'], {cwd});
|
||||
await gitPush(repositoryUrl, 'next', {cwd});
|
||||
await gitCheckout('pre/foo', true, {cwd});
|
||||
await gitCommits(['Sixth'], {cwd});
|
||||
await gitPush(repositoryUrl, 'pre/foo', {cwd});
|
||||
await gitCheckout('pre/bar', true, {cwd});
|
||||
await gitCommits(['Seventh'], {cwd});
|
||||
await gitPush(repositoryUrl, 'pre/bar', {cwd});
|
||||
await gitCheckout('beta', true, {cwd});
|
||||
await gitCommits(['Eighth'], {cwd});
|
||||
await gitPush(repositoryUrl, 'beta', {cwd});
|
||||
|
||||
const branches = [
|
||||
// Should match all maintenance type branches
|
||||
{name: '+([0-9])?(.{+([0-9]),x}).x'},
|
||||
{name: 'master', channel: 'latest'},
|
||||
{name: 'next'},
|
||||
{name: 'pre/{foo,bar}', channel: `\${name.replace(/^pre\\//g, '')}`, prerelease: true},
|
||||
// Should be ignored as there is no matching branches in the repo
|
||||
{name: 'missing'},
|
||||
// Should be ignored as the matching branch in the repo is already matched by `/^pre\\/(\\w+)$/gi`
|
||||
{name: '*/foo', channel: 'foo', prerelease: 'foo'},
|
||||
{name: 'beta', channel: `channel-\${name}`, prerelease: true},
|
||||
];
|
||||
|
||||
t.deepEqual(await expand(repositoryUrl, {cwd}, branches), [
|
||||
{name: '1.0.x'},
|
||||
{name: '1.x.x'},
|
||||
{name: '2.x'},
|
||||
{name: 'master', channel: 'latest'},
|
||||
{name: 'next'},
|
||||
{name: 'pre/bar', channel: 'bar', prerelease: true},
|
||||
{name: 'pre/foo', channel: 'foo', prerelease: true},
|
||||
{name: 'beta', channel: 'channel-beta', prerelease: true},
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
const test = require('ava');
|
||||
const getTags = require('../../lib/branches/get-tags');
|
||||
const {gitRepo, gitCommits, gitTagVersion, gitCheckout, gitAddNote} = require('../helpers/git-utils');
|
||||
|
||||
test('Get the valid tags', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('foo', undefined, {cwd});
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
commits.push(...(await gitCommits(['Second'], {cwd})));
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
commits.push(...(await gitCommits(['Third'], {cwd})));
|
||||
await gitTagVersion('v3.0', undefined, {cwd});
|
||||
commits.push(...(await gitCommits(['Fourth'], {cwd})));
|
||||
await gitTagVersion('v3.0.0-beta.1', undefined, {cwd});
|
||||
|
||||
const result = await getTags({cwd, options: {tagFormat: `v\${version}`}}, [{name: 'master'}]);
|
||||
|
||||
t.deepEqual(result, [
|
||||
{
|
||||
name: 'master',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: [null]},
|
||||
{gitTag: 'v3.0.0-beta.1', version: '3.0.0-beta.1', channels: [null]},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('Get the valid tags from multiple branches', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitAddNote(JSON.stringify({channels: [null, '1.x']}), 'v1.0.0', {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v1.1.0', undefined, {cwd});
|
||||
await gitAddNote(JSON.stringify({channels: [null, '1.x']}), 'v1.1.0', {cwd});
|
||||
await gitCheckout('1.x', true, {cwd});
|
||||
await gitCheckout('master', false, {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
await gitAddNote(JSON.stringify({channels: [null, 'next']}), 'v2.0.0', {cwd});
|
||||
await gitCheckout('next', true, {cwd});
|
||||
await gitCommits(['Fourth'], {cwd});
|
||||
await gitTagVersion('v3.0.0', undefined, {cwd});
|
||||
await gitAddNote(JSON.stringify({channels: ['next']}), 'v3.0.0', {cwd});
|
||||
|
||||
const result = await getTags({cwd, options: {tagFormat: `v\${version}`}}, [
|
||||
{name: '1.x'},
|
||||
{name: 'master'},
|
||||
{name: 'next'},
|
||||
]);
|
||||
|
||||
t.deepEqual(result, [
|
||||
{
|
||||
name: '1.x',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null, '1.x']},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: [null, '1.x']},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'master',
|
||||
tags: [...result[0].tags, {gitTag: 'v2.0.0', version: '2.0.0', channels: [null, 'next']}],
|
||||
},
|
||||
{
|
||||
name: 'next',
|
||||
tags: [...result[1].tags, {gitTag: 'v3.0.0', version: '3.0.0', channels: ['next']}],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test('Return branches with and empty tags array if no valid tag is found', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('foo', undefined, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v2.0.x', undefined, {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v3.0', undefined, {cwd});
|
||||
|
||||
const result = await getTags({cwd, options: {tagFormat: `prefix@v\${version}`}}, [{name: 'master'}]);
|
||||
|
||||
t.deepEqual(result, [{name: 'master', tags: []}]);
|
||||
});
|
||||
|
||||
test('Return branches with and empty tags array if no valid tag is found in history of configured branches', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitCheckout('next', true, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitAddNote(JSON.stringify({channels: [null, 'next']}), 'v1.0.0', {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
await gitAddNote(JSON.stringify({channels: [null, 'next']}), 'v2.0.0', {cwd});
|
||||
await gitCommits(['Fourth'], {cwd});
|
||||
await gitTagVersion('v3.0.0', undefined, {cwd});
|
||||
await gitAddNote(JSON.stringify({channels: [null, 'next']}), 'v3.0.0', {cwd});
|
||||
await gitCheckout('master', false, {cwd});
|
||||
|
||||
const result = await getTags({cwd, options: {tagFormat: `prefix@v\${version}`}}, [{name: 'master'}, {name: 'next'}]);
|
||||
|
||||
t.deepEqual(result, [
|
||||
{name: 'master', tags: []},
|
||||
{name: 'next', tags: []},
|
||||
]);
|
||||
});
|
||||
|
||||
test('Get the highest valid tag corresponding to the "tagFormat"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
|
||||
await gitTagVersion('1.0.0', undefined, {cwd});
|
||||
t.deepEqual(await getTags({cwd, options: {tagFormat: `\${version}`}}, [{name: 'master'}]), [
|
||||
{name: 'master', tags: [{gitTag: '1.0.0', version: '1.0.0', channels: [null]}]},
|
||||
]);
|
||||
|
||||
await gitTagVersion('foo-1.0.0-bar', undefined, {cwd});
|
||||
t.deepEqual(await getTags({cwd, options: {tagFormat: `foo-\${version}-bar`}}, [{name: 'master'}]), [
|
||||
{name: 'master', tags: [{gitTag: 'foo-1.0.0-bar', version: '1.0.0', channels: [null]}]},
|
||||
]);
|
||||
|
||||
await gitTagVersion('foo-v1.0.0-bar', undefined, {cwd});
|
||||
t.deepEqual(await getTags({cwd, options: {tagFormat: `foo-v\${version}-bar`}}, [{name: 'master'}]), [
|
||||
{
|
||||
name: 'master',
|
||||
tags: [{gitTag: 'foo-v1.0.0-bar', version: '1.0.0', channels: [null]}],
|
||||
},
|
||||
]);
|
||||
|
||||
await gitTagVersion('(.+)/1.0.0/(a-z)', undefined, {cwd});
|
||||
t.deepEqual(await getTags({cwd, options: {tagFormat: `(.+)/\${version}/(a-z)`}}, [{name: 'master'}]), [
|
||||
{
|
||||
name: 'master',
|
||||
tags: [{gitTag: '(.+)/1.0.0/(a-z)', version: '1.0.0', channels: [null]}],
|
||||
},
|
||||
]);
|
||||
|
||||
await gitTagVersion('2.0.0-1.0.0-bar.1', undefined, {cwd});
|
||||
t.deepEqual(await getTags({cwd, options: {tagFormat: `2.0.0-\${version}-bar.1`}}, [{name: 'master'}]), [
|
||||
{
|
||||
name: 'master',
|
||||
tags: [{gitTag: '2.0.0-1.0.0-bar.1', version: '1.0.0', channels: [null]}],
|
||||
},
|
||||
]);
|
||||
|
||||
await gitTagVersion('3.0.0-bar.2', undefined, {cwd});
|
||||
t.deepEqual(await getTags({cwd, options: {tagFormat: `\${version}-bar.2`}}, [{name: 'master'}]), [
|
||||
{name: 'master', tags: [{gitTag: '3.0.0-bar.2', version: '3.0.0', channels: [null]}]},
|
||||
]);
|
||||
});
|
||||
@@ -0,0 +1,397 @@
|
||||
const test = require('ava');
|
||||
const normalize = require('../../lib/branches/normalize');
|
||||
|
||||
const toTags = (versions) => versions.map((version) => ({version}));
|
||||
|
||||
test('Maintenance branches - initial state', (t) => {
|
||||
const maintenance = [
|
||||
{name: '1.x', channel: '1.x', tags: []},
|
||||
{name: '1.1.x', tags: []},
|
||||
{name: '1.2.x', tags: []},
|
||||
];
|
||||
const release = [{name: 'master', tags: []}];
|
||||
t.deepEqual(
|
||||
normalize.maintenance({maintenance, release}).map(({type, name, range, accept, channel, mergeRange}) => ({
|
||||
type,
|
||||
name,
|
||||
range,
|
||||
accept,
|
||||
channel,
|
||||
mergeRange,
|
||||
})),
|
||||
[
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: '1.1.x',
|
||||
range: '>=1.1.0 <1.0.0',
|
||||
accept: [],
|
||||
channel: '1.1.x',
|
||||
mergeRange: '>=1.1.0 <1.2.0',
|
||||
},
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: '1.2.x',
|
||||
range: '>=1.2.0 <1.0.0',
|
||||
accept: [],
|
||||
channel: '1.2.x',
|
||||
mergeRange: '>=1.2.0 <1.3.0',
|
||||
},
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: '1.x',
|
||||
range: '>=1.3.0 <1.0.0',
|
||||
accept: [],
|
||||
channel: '1.x',
|
||||
mergeRange: '>=1.3.0 <2.0.0',
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Maintenance branches - cap range to first release present on default branch and not in any Maintenance one', (t) => {
|
||||
const maintenance = [
|
||||
{name: '1.x', tags: toTags(['1.0.0', '1.1.0', '1.1.1', '1.2.0', '1.2.1', '1.3.0', '1.4.0', '1.5.0'])},
|
||||
{name: 'name', range: '1.1.x', tags: toTags(['1.0.0', '1.0.1', '1.1.0', '1.1.1'])},
|
||||
{name: '1.2.x', tags: toTags(['1.0.0', '1.1.0', '1.1.1', '1.2.0', '1.2.1'])},
|
||||
{name: '2.x.x', tags: toTags(['1.0.0', '1.1.0', '1.1.1', '1.2.0', '1.2.1', '1.5.0'])},
|
||||
];
|
||||
const release = [
|
||||
{
|
||||
name: 'master',
|
||||
tags: toTags(['1.0.0', '1.1.0', '1.1.1', '1.2.0', '1.2.1', '1.3.0', '1.4.0', '1.5.0', '1.6.0', '2.0.0']),
|
||||
},
|
||||
];
|
||||
|
||||
t.deepEqual(
|
||||
normalize
|
||||
.maintenance({maintenance, release})
|
||||
.map(({type, name, range, accept, channel, mergeRange: maintenanceRange}) => ({
|
||||
type,
|
||||
name,
|
||||
range,
|
||||
accept,
|
||||
channel,
|
||||
mergeRange: maintenanceRange,
|
||||
})),
|
||||
[
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: 'name',
|
||||
range: '>=1.1.1 <1.2.0',
|
||||
accept: ['patch'],
|
||||
channel: 'name',
|
||||
mergeRange: '>=1.1.0 <1.2.0',
|
||||
},
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: '1.2.x',
|
||||
range: '>=1.2.1 <1.3.0',
|
||||
accept: ['patch'],
|
||||
channel: '1.2.x',
|
||||
mergeRange: '>=1.2.0 <1.3.0',
|
||||
},
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: '1.x',
|
||||
range: '>=1.5.0 <1.6.0',
|
||||
accept: ['patch'],
|
||||
channel: '1.x',
|
||||
mergeRange: '>=1.3.0 <2.0.0',
|
||||
},
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: '2.x.x',
|
||||
range: '>=2.0.0 <1.6.0',
|
||||
accept: [],
|
||||
channel: '2.x.x',
|
||||
mergeRange: '>=2.0.0 <3.0.0',
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Maintenance branches - cap range to default branch last release if all release are also present on maintenance branch', (t) => {
|
||||
const maintenance = [
|
||||
{name: '1.x', tags: toTags(['1.0.0', '1.2.0', '1.3.0'])},
|
||||
{name: '2.x.x', tags: toTags(['1.0.0', '1.2.0', '1.3.0', '2.0.0'])},
|
||||
];
|
||||
const release = [{name: 'master', tags: toTags(['1.0.0', '1.2.0', '1.3.0', '2.0.0'])}];
|
||||
|
||||
t.deepEqual(
|
||||
normalize.maintenance({maintenance, release}).map(({type, name, range, accept, channel, mergeRange}) => ({
|
||||
type,
|
||||
name,
|
||||
range,
|
||||
accept,
|
||||
channel,
|
||||
mergeRange,
|
||||
})),
|
||||
[
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: '1.x',
|
||||
range: '>=1.3.0 <2.0.0',
|
||||
accept: ['patch', 'minor'],
|
||||
channel: '1.x',
|
||||
mergeRange: '>=1.0.0 <2.0.0',
|
||||
},
|
||||
{
|
||||
type: 'maintenance',
|
||||
name: '2.x.x',
|
||||
range: '>=2.0.0 <2.0.0',
|
||||
accept: [],
|
||||
channel: '2.x.x',
|
||||
mergeRange: '>=2.0.0 <3.0.0',
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Release branches - initial state', (t) => {
|
||||
const release = [
|
||||
{name: 'master', tags: []},
|
||||
{name: 'next', channel: 'next', tags: []},
|
||||
{name: 'next-major', tags: []},
|
||||
];
|
||||
|
||||
t.deepEqual(
|
||||
normalize
|
||||
.release({release})
|
||||
.map(({type, name, range, accept, channel, main}) => ({type, name, range, accept, channel, main})),
|
||||
[
|
||||
{
|
||||
type: 'release',
|
||||
name: 'master',
|
||||
range: '>=1.0.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: undefined,
|
||||
main: true,
|
||||
},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next',
|
||||
range: '>=1.0.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: 'next',
|
||||
main: false,
|
||||
},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next-major',
|
||||
range: '>=1.0.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: 'next-major',
|
||||
main: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Release branches - 3 release branches', (t) => {
|
||||
const release = [
|
||||
{name: 'master', tags: toTags(['1.0.0', '1.0.1', '1.0.2'])},
|
||||
{name: 'next', tags: toTags(['1.0.0', '1.0.1', '1.0.2', '1.1.0', '1.2.0'])},
|
||||
{name: 'next-major', tags: toTags(['1.0.0', '1.0.1', '1.0.2', '1.1.0', '1.2.0', '2.0.0', '2.0.1', '2.1.0'])},
|
||||
];
|
||||
|
||||
t.deepEqual(
|
||||
normalize
|
||||
.release({release})
|
||||
.map(({type, name, range, accept, channel, main}) => ({type, name, range, accept, channel, main})),
|
||||
[
|
||||
{type: 'release', name: 'master', range: '>=1.0.2 <1.1.0', accept: ['patch'], channel: undefined, main: true},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next',
|
||||
range: '>=1.2.0 <2.0.0',
|
||||
accept: ['patch', 'minor'],
|
||||
channel: 'next',
|
||||
main: false,
|
||||
},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next-major',
|
||||
range: '>=2.1.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: 'next-major',
|
||||
main: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Release branches - 2 release branches', (t) => {
|
||||
const release = [
|
||||
{name: 'master', tags: toTags(['1.0.0', '1.0.1', '1.1.0', '1.1.1', '1.2.0'])},
|
||||
{name: 'next', tags: toTags(['1.0.0', '1.0.1', '1.1.0', '1.1.1', '1.2.0', '2.0.0', '2.0.1', '2.1.0'])},
|
||||
];
|
||||
|
||||
t.deepEqual(
|
||||
normalize
|
||||
.release({release})
|
||||
.map(({type, name, range, accept, channel, main}) => ({type, name, range, accept, channel, main})),
|
||||
[
|
||||
{
|
||||
type: 'release',
|
||||
name: 'master',
|
||||
range: '>=1.2.0 <2.0.0',
|
||||
accept: ['patch', 'minor'],
|
||||
channel: undefined,
|
||||
main: true,
|
||||
},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next',
|
||||
range: '>=2.1.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: 'next',
|
||||
main: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Release branches - 1 release branches', (t) => {
|
||||
const release = [{name: 'master', tags: toTags(['1.0.0', '1.1.0', '1.1.1', '1.2.0'])}];
|
||||
|
||||
t.deepEqual(
|
||||
normalize.release({release}).map(({type, name, range, accept, channel}) => ({type, name, range, accept, channel})),
|
||||
[{type: 'release', name: 'master', range: '>=1.2.0', accept: ['patch', 'minor', 'major'], channel: undefined}]
|
||||
);
|
||||
});
|
||||
|
||||
test('Release branches - cap ranges to first release only present on following branch', (t) => {
|
||||
const release = [
|
||||
{name: 'master', tags: toTags(['1.0.0', '1.1.0', '1.2.0', '2.0.0'])},
|
||||
{name: 'next', tags: toTags(['1.0.0', '1.1.0', '1.2.0', '2.0.0', '2.1.0'])},
|
||||
{name: 'next-major', tags: toTags(['1.0.0', '1.1.0', '1.2.0', '2.0.0', '2.1.0', '2.2.0'])},
|
||||
];
|
||||
|
||||
t.deepEqual(
|
||||
normalize
|
||||
.release({release})
|
||||
.map(({type, name, range, accept, channel, main}) => ({type, name, range, accept, channel, main})),
|
||||
[
|
||||
{type: 'release', name: 'master', range: '>=2.0.0 <2.1.0', accept: ['patch'], channel: undefined, main: true},
|
||||
{type: 'release', name: 'next', range: '>=2.1.0 <2.2.0', accept: ['patch'], channel: 'next', main: false},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next-major',
|
||||
range: '>=2.2.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: 'next-major',
|
||||
main: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Release branches - Handle missing previous tags in branch history', (t) => {
|
||||
const release = [
|
||||
{name: 'master', tags: toTags(['1.0.0', '2.0.0'])},
|
||||
{name: 'next', tags: toTags(['1.0.0', '1.1.0', '1.1.1', '1.2.0', '2.0.0'])},
|
||||
];
|
||||
|
||||
t.deepEqual(
|
||||
normalize
|
||||
.release({release})
|
||||
.map(({type, name, range, accept, channel, main}) => ({type, name, range, accept, channel, main})),
|
||||
[
|
||||
{
|
||||
type: 'release',
|
||||
name: 'master',
|
||||
range: '>=2.0.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: undefined,
|
||||
main: true,
|
||||
},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next',
|
||||
range: '>=2.0.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: 'next',
|
||||
main: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Release branches - limit releases on 2nd and 3rd branch based on 1st branch last release', (t) => {
|
||||
const release = [
|
||||
{name: 'master', tags: toTags(['1.0.0', '1.1.0', '2.0.0', '3.0.0'])},
|
||||
{name: 'next', tags: toTags(['1.0.0', '1.1.0'])},
|
||||
{name: 'next-major', tags: toTags(['1.0.0', '1.1.0', '2.0.0'])},
|
||||
];
|
||||
|
||||
t.deepEqual(
|
||||
normalize
|
||||
.release({release})
|
||||
.map(({type, name, range, accept, channel, main}) => ({type, name, range, accept, channel, main})),
|
||||
[
|
||||
{
|
||||
type: 'release',
|
||||
name: 'master',
|
||||
range: '>=3.0.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: undefined,
|
||||
main: true,
|
||||
},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next',
|
||||
range: '>=3.0.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: 'next',
|
||||
main: false,
|
||||
},
|
||||
{
|
||||
type: 'release',
|
||||
name: 'next-major',
|
||||
range: '>=3.0.0',
|
||||
accept: ['patch', 'minor', 'major'],
|
||||
channel: 'next-major',
|
||||
main: false,
|
||||
},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Prerelease branches', (t) => {
|
||||
const prerelease = [
|
||||
{name: 'beta', channel: 'beta', prerelease: true, tags: []},
|
||||
{name: 'alpha', prerelease: 'preview', tags: []},
|
||||
];
|
||||
|
||||
t.deepEqual(
|
||||
normalize.prerelease({prerelease}).map(({type, name, channel}) => ({type, name, channel})),
|
||||
[
|
||||
{type: 'prerelease', name: 'beta', channel: 'beta'},
|
||||
{type: 'prerelease', name: 'alpha', channel: 'alpha'},
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
test('Allow to set channel to "false" to prevent default', (t) => {
|
||||
const maintenance = [{name: '1.x', channel: false, tags: []}];
|
||||
const release = [
|
||||
{name: 'master', channel: false, tags: []},
|
||||
{name: 'next', channel: false, tags: []},
|
||||
];
|
||||
const prerelease = [{name: 'beta', channel: false, prerelease: true, tags: []}];
|
||||
t.deepEqual(
|
||||
normalize.maintenance({maintenance, release}).map(({name, channel}) => ({name, channel})),
|
||||
[{name: '1.x', channel: false}]
|
||||
);
|
||||
t.deepEqual(
|
||||
normalize.release({release}).map(({name, channel}) => ({name, channel})),
|
||||
[
|
||||
{name: 'master', channel: false},
|
||||
{name: 'next', channel: false},
|
||||
]
|
||||
);
|
||||
t.deepEqual(
|
||||
normalize.prerelease({prerelease}).map(({name, channel}) => ({name, channel})),
|
||||
[{name: 'beta', channel: false}]
|
||||
);
|
||||
});
|
||||
+35
-36
@@ -1,34 +1,33 @@
|
||||
import test from 'ava';
|
||||
import {escapeRegExp} from 'lodash';
|
||||
import proxyquire from 'proxyquire';
|
||||
import {stub} from 'sinon';
|
||||
import {SECRET_REPLACEMENT} from '../lib/definitions/constants';
|
||||
const test = require('ava');
|
||||
const {escapeRegExp} = require('lodash');
|
||||
const proxyquire = require('proxyquire').noPreserveCache();
|
||||
const {stub} = require('sinon');
|
||||
const {SECRET_REPLACEMENT} = require('../lib/definitions/constants');
|
||||
|
||||
const requireNoCache = proxyquire.noPreserveCache();
|
||||
|
||||
test.beforeEach(t => {
|
||||
test.beforeEach((t) => {
|
||||
t.context.logs = '';
|
||||
t.context.errors = '';
|
||||
t.context.stdout = stub(process.stdout, 'write').callsFake(val => {
|
||||
t.context.logs += val.toString();
|
||||
t.context.stdout = stub(process.stdout, 'write').callsFake((value) => {
|
||||
t.context.logs += value.toString();
|
||||
});
|
||||
t.context.stderr = stub(process.stderr, 'write').callsFake(val => {
|
||||
t.context.errors += val.toString();
|
||||
t.context.stderr = stub(process.stderr, 'write').callsFake((value) => {
|
||||
t.context.errors += value.toString();
|
||||
});
|
||||
});
|
||||
|
||||
test.afterEach.always(t => {
|
||||
test.afterEach.always((t) => {
|
||||
t.context.stdout.restore();
|
||||
t.context.stderr.restore();
|
||||
});
|
||||
|
||||
test.serial('Pass options to semantic-release API', async t => {
|
||||
test.serial('Pass options to semantic-release API', async (t) => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = [
|
||||
'',
|
||||
'',
|
||||
'-b',
|
||||
'master',
|
||||
'next',
|
||||
'-r',
|
||||
'https://github/com/owner/repo.git',
|
||||
'-t',
|
||||
@@ -64,11 +63,11 @@ test.serial('Pass options to semantic-release API', async t => {
|
||||
'--debug',
|
||||
'-d',
|
||||
];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.is(run.args[0][0].branch, 'master');
|
||||
t.deepEqual(run.args[0][0].branches, ['master', 'next']);
|
||||
t.is(run.args[0][0].repositoryUrl, 'https://github/com/owner/repo.git');
|
||||
t.is(run.args[0][0].tagFormat, `v\${version}`);
|
||||
t.deepEqual(run.args[0][0].plugins, ['plugin1', 'plugin2']);
|
||||
@@ -87,12 +86,12 @@ test.serial('Pass options to semantic-release API', async t => {
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Pass options to semantic-release API with alias arguments', async t => {
|
||||
test.serial('Pass options to semantic-release API with alias arguments', async (t) => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = [
|
||||
'',
|
||||
'',
|
||||
'--branch',
|
||||
'--branches',
|
||||
'master',
|
||||
'--repository-url',
|
||||
'https://github/com/owner/repo.git',
|
||||
@@ -106,11 +105,11 @@ test.serial('Pass options to semantic-release API with alias arguments', async t
|
||||
'config2',
|
||||
'--dry-run',
|
||||
];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.is(run.args[0][0].branch, 'master');
|
||||
t.deepEqual(run.args[0][0].branches, ['master']);
|
||||
t.is(run.args[0][0].repositoryUrl, 'https://github/com/owner/repo.git');
|
||||
t.is(run.args[0][0].tagFormat, `v\${version}`);
|
||||
t.deepEqual(run.args[0][0].plugins, ['plugin1', 'plugin2']);
|
||||
@@ -120,10 +119,10 @@ test.serial('Pass options to semantic-release API with alias arguments', async t
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Pass unknown options to semantic-release API', async t => {
|
||||
test.serial('Pass unknown options to semantic-release API', async (t) => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '--bool', '--first-option', 'value1', '--second-option', 'value2', '--second-option', 'value3'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
@@ -134,10 +133,10 @@ test.serial('Pass unknown options to semantic-release API', async t => {
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Pass empty Array to semantic-release API for list option set to "false"', async t => {
|
||||
test.serial('Pass empty Array to semantic-release API for list option set to "false"', async (t) => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '--publish', 'false'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
@@ -146,10 +145,10 @@ test.serial('Pass empty Array to semantic-release API for list option set to "fa
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Do not set properties in option for which arg is not in command line', async t => {
|
||||
test.serial('Do not set properties in option for which arg is not in command line', async (t) => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '-b', 'master'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
await cli();
|
||||
|
||||
@@ -163,10 +162,10 @@ 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('Display help', async t => {
|
||||
test.serial('Display help', async (t) => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '--help'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
@@ -174,10 +173,10 @@ test.serial('Display help', async t => {
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Return error code and prints help if called with a command', async t => {
|
||||
test.serial('Return error exitCode 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}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
@@ -186,10 +185,10 @@ test.serial('Return error code and prints help if called with a command', async
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test.serial('Return error code if multiple plugin are set for single plugin', async t => {
|
||||
test.serial('Return error exitCode if multiple plugin are set for single plugin', async (t) => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '--analyze-commits', 'analyze1', 'analyze2'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
@@ -198,10 +197,10 @@ test.serial('Return error code if multiple plugin are set for single plugin', as
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test.serial('Return error code if semantic-release throw error', async t => {
|
||||
test.serial('Return error exitCode if semantic-release throw error', async (t) => {
|
||||
const run = stub().rejects(new Error('semantic-release error'));
|
||||
const argv = ['', ''];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
@@ -209,11 +208,11 @@ test.serial('Return error code if semantic-release throw error', async t => {
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test.serial('Hide sensitive environment variable values from the logs', async t => {
|
||||
test.serial('Hide sensitive environment variable values from the logs', async (t) => {
|
||||
const env = {MY_TOKEN: 'secret token'};
|
||||
const run = stub().rejects(new Error(`Throw error: Exposing token ${env.MY_TOKEN}`));
|
||||
const argv = ['', ''];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv, env: {...process.env, ...env}}});
|
||||
const cli = proxyquire('../cli', {'.': run, process: {...process, argv, env: {...process.env, ...env}}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
const test = require('ava');
|
||||
const {maintenance, prerelease, release} = require('../../lib/definitions/branches');
|
||||
|
||||
test('A "maintenance" branch is identified by having a "range" property or a "name" formatted like "N.x", "N.x.x" or "N.N.x"', (t) => {
|
||||
t.true(maintenance.filter({name: '1.x.x'}));
|
||||
t.true(maintenance.filter({name: '1.0.x'}));
|
||||
t.true(maintenance.filter({name: '1.x'}));
|
||||
t.true(maintenance.filter({name: 'some-name', range: '1.x.x'}));
|
||||
t.true(maintenance.filter({name: 'some-name', range: '1.1.x'}));
|
||||
t.true(maintenance.filter({name: 'some-name', range: ''}));
|
||||
t.true(maintenance.filter({name: 'some-name', range: true}));
|
||||
|
||||
t.false(maintenance.filter({name: 'some-name', range: null}));
|
||||
t.false(maintenance.filter({name: 'some-name', range: false}));
|
||||
t.false(maintenance.filter({name: 'some-name'}));
|
||||
t.false(maintenance.filter({name: '1.0.0'}));
|
||||
t.false(maintenance.filter({name: 'x.x.x'}));
|
||||
});
|
||||
|
||||
test('A "maintenance" branches must have a "range" property formatted like "N.x", "N.x.x" or "N.N.x"', (t) => {
|
||||
t.true(maintenance.branchValidator({name: 'some-name', range: '1.x.x'}));
|
||||
t.true(maintenance.branchValidator({name: 'some-name', range: '1.1.x'}));
|
||||
|
||||
t.false(maintenance.branchValidator({name: 'some-name', range: '^1.0.0'}));
|
||||
t.false(maintenance.branchValidator({name: 'some-name', range: '>=1.0.0 <2.0.0'}));
|
||||
t.false(maintenance.branchValidator({name: 'some-name', range: '1.0.0'}));
|
||||
t.false(maintenance.branchValidator({name: 'some-name', range: 'wrong-range'}));
|
||||
t.false(maintenance.branchValidator({name: 'some-name', range: true}));
|
||||
t.false(maintenance.branchValidator({name: 'some-name', range: ''}));
|
||||
});
|
||||
|
||||
test('The "maintenance" branches must have unique ranges', (t) => {
|
||||
t.true(maintenance.branchesValidator([{range: '1.x.x'}, {range: '1.0.x'}]));
|
||||
|
||||
t.false(maintenance.branchesValidator([{range: '1.x.x'}, {range: '1.x.x'}]));
|
||||
t.false(maintenance.branchesValidator([{range: '1.x.x'}, {range: '1.x'}]));
|
||||
});
|
||||
|
||||
test('A "prerelease" branch is identified by having a thruthy "prerelease" property', (t) => {
|
||||
t.true(prerelease.filter({name: 'some-name', prerelease: true}));
|
||||
t.true(prerelease.filter({name: 'some-name', prerelease: 'beta'}));
|
||||
t.true(prerelease.filter({name: 'some-name', prerelease: ''}));
|
||||
|
||||
t.false(prerelease.filter({name: 'some-name', prerelease: null}));
|
||||
t.false(prerelease.filter({name: 'some-name', prerelease: false}));
|
||||
t.false(prerelease.filter({name: 'some-name'}));
|
||||
});
|
||||
|
||||
test('A "prerelease" branch must have a valid prerelease detonation in "prerelease" property or in "name" if "prerelease" is "true"', (t) => {
|
||||
t.true(prerelease.branchValidator({name: 'beta', prerelease: true}));
|
||||
t.true(prerelease.branchValidator({name: 'some-name', prerelease: 'beta'}));
|
||||
|
||||
t.false(prerelease.branchValidator({name: 'some-name', prerelease: ''}));
|
||||
t.false(prerelease.branchValidator({name: 'some-name', prerelease: null}));
|
||||
t.false(prerelease.branchValidator({name: 'some-name', prerelease: false}));
|
||||
t.false(prerelease.branchValidator({name: 'some-name', prerelease: '000'}));
|
||||
t.false(prerelease.branchValidator({name: 'some-name', prerelease: '#beta'}));
|
||||
t.false(prerelease.branchValidator({name: '000', prerelease: true}));
|
||||
t.false(prerelease.branchValidator({name: '#beta', prerelease: true}));
|
||||
});
|
||||
|
||||
test('The "prerelease" branches must have unique "prerelease" property', (t) => {
|
||||
t.true(prerelease.branchesValidator([{prerelease: 'beta'}, {prerelease: 'alpha'}]));
|
||||
|
||||
t.false(prerelease.branchesValidator([{range: 'beta'}, {range: 'beta'}, {range: 'alpha'}]));
|
||||
});
|
||||
|
||||
test('A "release" branch is identified by not havin a "range" or "prerelease" property or a "name" formatted like "N.x", "N.x.x" or "N.N.x"', (t) => {
|
||||
t.true(release.filter({name: 'some-name'}));
|
||||
|
||||
t.false(release.filter({name: '1.x.x'}));
|
||||
t.false(release.filter({name: '1.0.x'}));
|
||||
t.false(release.filter({name: 'some-name', range: '1.x.x'}));
|
||||
t.false(release.filter({name: 'some-name', range: '1.1.x'}));
|
||||
t.false(release.filter({name: 'some-name', prerelease: true}));
|
||||
t.false(release.filter({name: 'some-name', prerelease: 'beta'}));
|
||||
});
|
||||
|
||||
test('There must be between 1 and 3 release branches', (t) => {
|
||||
t.true(release.branchesValidator([{name: 'branch1'}]));
|
||||
t.true(release.branchesValidator([{name: 'branch1'}, {name: 'branch2'}]));
|
||||
t.true(release.branchesValidator([{name: 'branch1'}, {name: 'branch2'}, {name: 'branch3'}]));
|
||||
|
||||
t.false(release.branchesValidator([]));
|
||||
t.false(release.branchesValidator([{name: 'branch1'}, {name: 'branch2'}, {name: 'branch3'}, {name: 'branch4'}]));
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import test from 'ava';
|
||||
import plugins from '../../lib/definitions/plugins';
|
||||
import {RELEASE_NOTES_SEPARATOR, SECRET_REPLACEMENT} from '../../lib/definitions/constants';
|
||||
const test = require('ava');
|
||||
const plugins = require('../../lib/definitions/plugins');
|
||||
const {RELEASE_NOTES_SEPARATOR, SECRET_REPLACEMENT} = require('../../lib/definitions/constants');
|
||||
|
||||
test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', t => {
|
||||
test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', (t) => {
|
||||
t.false(plugins.analyzeCommits.outputValidator('invalid'));
|
||||
t.false(plugins.analyzeCommits.outputValidator(1));
|
||||
t.false(plugins.analyzeCommits.outputValidator({}));
|
||||
@@ -12,7 +12,7 @@ test('The "analyzeCommits" plugin output must be either undefined or a valid sem
|
||||
t.true(plugins.analyzeCommits.outputValidator('major'));
|
||||
});
|
||||
|
||||
test('The "generateNotes" plugin output, if defined, must be a string', t => {
|
||||
test('The "generateNotes" plugin output, if defined, must be a string', (t) => {
|
||||
t.false(plugins.generateNotes.outputValidator(1));
|
||||
t.false(plugins.generateNotes.outputValidator({}));
|
||||
|
||||
@@ -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 or "false"', 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'));
|
||||
|
||||
@@ -33,7 +33,17 @@ test('The "publish" plugin output, if defined, must be an object or "false"', t
|
||||
t.true(plugins.publish.outputValidator(false));
|
||||
});
|
||||
|
||||
test('The "generateNotes" plugins output are concatenated with separator and sensitive data is hidden', t => {
|
||||
test('The "addChannel" plugin output, if defined, must be an object', (t) => {
|
||||
t.false(plugins.addChannel.outputValidator(1));
|
||||
t.false(plugins.addChannel.outputValidator('string'));
|
||||
|
||||
t.true(plugins.addChannel.outputValidator({}));
|
||||
t.true(plugins.addChannel.outputValidator());
|
||||
t.true(plugins.addChannel.outputValidator(null));
|
||||
t.true(plugins.addChannel.outputValidator(''));
|
||||
});
|
||||
|
||||
test('The "generateNotes" plugins output are concatenated with separator and sensitive data is hidden', (t) => {
|
||||
const env = {MY_TOKEN: 'secret token'};
|
||||
t.is(plugins.generateNotes.postprocess(['note 1', 'note 2'], {env}), `note 1${RELEASE_NOTES_SEPARATOR}note 2`);
|
||||
t.is(plugins.generateNotes.postprocess(['', 'note'], {env}), 'note');
|
||||
@@ -53,7 +63,7 @@ test('The "generateNotes" plugins output are concatenated with separator and sen
|
||||
);
|
||||
});
|
||||
|
||||
test('The "analyzeCommits" plugins output are reduced to the highest release type', t => {
|
||||
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');
|
||||
|
||||
+29
-10
@@ -1,16 +1,16 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import getCommits from '../lib/get-commits';
|
||||
import {gitRepo, gitCommits, gitDetachedHead} from './helpers/git-utils';
|
||||
const test = require('ava');
|
||||
const {stub} = require('sinon');
|
||||
const getCommits = require('../lib/get-commits');
|
||||
const {gitRepo, gitCommits, gitDetachedHead} = require('./helpers/git-utils');
|
||||
|
||||
test.beforeEach(t => {
|
||||
test.beforeEach((t) => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.error = stub();
|
||||
t.context.logger = {log: t.context.log, error: t.context.error};
|
||||
});
|
||||
|
||||
test('Get all commits when there is no last release', async t => {
|
||||
test('Get all commits when there is no last release', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
@@ -24,7 +24,7 @@ test('Get all commits when there is no last release', async t => {
|
||||
t.deepEqual(result, commits);
|
||||
});
|
||||
|
||||
test('Get all commits since gitHead (from lastRelease)', async t => {
|
||||
test('Get all commits since gitHead (from lastRelease)', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
@@ -42,7 +42,7 @@ test('Get all commits since gitHead (from lastRelease)', async t => {
|
||||
t.deepEqual(result, commits.slice(0, 2));
|
||||
});
|
||||
|
||||
test('Get all commits since gitHead (from lastRelease) on a detached head repo', async t => {
|
||||
test('Get all commits since gitHead (from lastRelease) on a detached head repo', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
@@ -66,7 +66,26 @@ test('Get all commits since gitHead (from lastRelease) on a detached head repo',
|
||||
t.truthy(result[0].committer.name);
|
||||
});
|
||||
|
||||
test('Return empty array if lastRelease.gitHead is the last commit', async t => {
|
||||
test('Get all commits between lastRelease.gitHead and a shas', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First', 'Second', 'Third'], {cwd});
|
||||
|
||||
// Retrieve the commits with the commits module, between commit 'First' and 'Third'
|
||||
const result = await getCommits({
|
||||
cwd,
|
||||
lastRelease: {gitHead: commits[commits.length - 1].hash},
|
||||
nextRelease: {gitHead: commits[1].hash},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.length, 1);
|
||||
t.deepEqual(result, commits.slice(1, -1));
|
||||
});
|
||||
|
||||
test('Return empty array if lastRelease.gitHead is the last commit', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
@@ -83,7 +102,7 @@ test('Return empty array if lastRelease.gitHead is the last commit', async t =>
|
||||
t.deepEqual(result, []);
|
||||
});
|
||||
|
||||
test('Return empty array if there is no commits', async t => {
|
||||
test('Return empty array if there is no commits', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
|
||||
+125
-94
@@ -1,12 +1,12 @@
|
||||
import path from 'path';
|
||||
import {format} from 'util';
|
||||
import test from 'ava';
|
||||
import {writeFile, outputJson} from 'fs-extra';
|
||||
import {omit} from 'lodash';
|
||||
import proxyquire from 'proxyquire';
|
||||
import {stub} from 'sinon';
|
||||
import yaml from 'js-yaml';
|
||||
import {gitRepo, gitCommits, gitShallowClone, gitAddConfig} from './helpers/git-utils';
|
||||
const path = require('path');
|
||||
const {format} = require('util');
|
||||
const test = require('ava');
|
||||
const {writeFile, outputJson} = require('fs-extra');
|
||||
const {omit} = require('lodash');
|
||||
const proxyquire = require('proxyquire');
|
||||
const {stub} = require('sinon');
|
||||
const yaml = require('js-yaml');
|
||||
const {gitRepo, gitTagVersion, gitCommits, gitShallowClone, gitAddConfig} = require('./helpers/git-utils');
|
||||
|
||||
const DEFAULT_PLUGINS = [
|
||||
'@semantic-release/commit-analyzer',
|
||||
@@ -15,16 +15,18 @@ const DEFAULT_PLUGINS = [
|
||||
'@semantic-release/github',
|
||||
];
|
||||
|
||||
test.beforeEach(t => {
|
||||
test.beforeEach((t) => {
|
||||
t.context.plugins = stub().returns({});
|
||||
t.context.getConfig = proxyquire('../lib/get-config', {'./plugins': t.context.plugins});
|
||||
});
|
||||
|
||||
test('Default values, reading repositoryUrl from package.json', async t => {
|
||||
test('Default values, reading repositoryUrl from package.json', async (t) => {
|
||||
const pkg = {repository: 'https://host.null/owner/package.git'};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const {cwd} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitTagVersion('v1.1.0', undefined, {cwd});
|
||||
// Add remote.origin.url config
|
||||
await gitAddConfig('remote.origin.url', 'git@host.null:owner/repo.git', {cwd});
|
||||
// Create package.json in repository root
|
||||
@@ -33,26 +35,40 @@ test('Default values, reading repositoryUrl from package.json', async t => {
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(result.branch, 'master');
|
||||
t.deepEqual(result.branches, [
|
||||
'+([0-9])?(.{+([0-9]),x}).x',
|
||||
'master',
|
||||
'next',
|
||||
'next-major',
|
||||
{name: 'beta', prerelease: true},
|
||||
{name: 'alpha', prerelease: true},
|
||||
]);
|
||||
t.is(result.repositoryUrl, 'https://host.null/owner/package.git');
|
||||
t.is(result.tagFormat, `v\${version}`);
|
||||
});
|
||||
|
||||
test('Default values, reading repositoryUrl from repo if not set in package.json', async t => {
|
||||
test('Default values, reading repositoryUrl from repo if not set in package.json', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const {cwd} = await gitRepo(true);
|
||||
// Add remote.origin.url config
|
||||
await gitAddConfig('remote.origin.url', 'https://host.null/owner/module.git', {cwd});
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(result.branch, 'master');
|
||||
t.deepEqual(result.branches, [
|
||||
'+([0-9])?(.{+([0-9]),x}).x',
|
||||
'master',
|
||||
'next',
|
||||
'next-major',
|
||||
{name: 'beta', prerelease: true},
|
||||
{name: 'alpha', prerelease: true},
|
||||
]);
|
||||
t.is(result.repositoryUrl, 'https://host.null/owner/module.git');
|
||||
t.is(result.tagFormat, `v\${version}`);
|
||||
});
|
||||
|
||||
test('Default values, reading repositoryUrl (http url) from package.json if not set in repo', async t => {
|
||||
test('Default values, reading repositoryUrl (http url) from package.json if not set in repo', async (t) => {
|
||||
const pkg = {repository: 'https://host.null/owner/module.git'};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
@@ -62,12 +78,19 @@ test('Default values, reading repositoryUrl (http url) from package.json if not
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(result.branch, 'master');
|
||||
t.deepEqual(result.branches, [
|
||||
'+([0-9])?(.{+([0-9]),x}).x',
|
||||
'master',
|
||||
'next',
|
||||
'next-major',
|
||||
{name: 'beta', prerelease: true},
|
||||
{name: 'alpha', prerelease: true},
|
||||
]);
|
||||
t.is(result.repositoryUrl, 'https://host.null/owner/module.git');
|
||||
t.is(result.tagFormat, `v\${version}`);
|
||||
});
|
||||
|
||||
test('Convert "ci" option to "noCi"', async t => {
|
||||
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();
|
||||
@@ -79,13 +102,13 @@ test('Convert "ci" option to "noCi"', async t => {
|
||||
t.is(result.noCi, true);
|
||||
});
|
||||
|
||||
test('Read options from package.json', async t => {
|
||||
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();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
@@ -95,18 +118,19 @@ test('Read options from package.json', async t => {
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {...options, branches: ['test_branch']};
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
});
|
||||
|
||||
test('Read options from .releaserc.yml', async t => {
|
||||
test('Read options from .releaserc.yml', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
@@ -116,18 +140,19 @@ test('Read options from .releaserc.yml', async t => {
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {...options, branches: ['test_branch']};
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
});
|
||||
|
||||
test('Read options from .releaserc.json', async t => {
|
||||
test('Read options from .releaserc.json', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
@@ -137,18 +162,19 @@ test('Read options from .releaserc.json', async t => {
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {...options, branches: ['test_branch']};
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
});
|
||||
|
||||
test('Read options from .releaserc.js', async t => {
|
||||
test('Read options from .releaserc.js', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
@@ -158,18 +184,19 @@ test('Read options from .releaserc.js', async t => {
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {...options, branches: ['test_branch']};
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
});
|
||||
|
||||
test('Read options from release.config.js', async t => {
|
||||
test('Read options from release.config.js', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
@@ -179,13 +206,14 @@ test('Read options from release.config.js', async t => {
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {...options, branches: ['test_branch']};
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
});
|
||||
|
||||
test('Prioritise CLI/API parameters over file configuration and git repo', async t => {
|
||||
test('Prioritise CLI/API parameters over file configuration and git repo', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
@@ -193,11 +221,11 @@ test('Prioritise CLI/API parameters over file configuration and git repo', async
|
||||
cwd = await gitShallowClone(repositoryUrl);
|
||||
const pkgOptions = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_pkg'},
|
||||
branch: 'branch_pkg',
|
||||
branches: ['branch_pkg'],
|
||||
};
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_cli'},
|
||||
branch: 'branch_cli',
|
||||
branches: ['branch_cli'],
|
||||
repositoryUrl: 'http://cli-url.com/owner/package',
|
||||
tagFormat: `cli\${version}`,
|
||||
plugins: false,
|
||||
@@ -208,20 +236,21 @@ test('Prioritise CLI/API parameters over file configuration and git repo', async
|
||||
|
||||
const result = await t.context.getConfig({cwd}, options);
|
||||
|
||||
const expected = {...options, branches: ['branch_cli']};
|
||||
// Verify the options contains the plugin config from CLI/API
|
||||
t.deepEqual(result.options, options);
|
||||
t.deepEqual(result.options, expected);
|
||||
// Verify the plugins module is called with the plugin options from CLI/API
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
});
|
||||
|
||||
test('Read configuration from file path in "extends"', async t => {
|
||||
test('Read configuration from file path in "extends"', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {extends: './shareable.json'};
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: ['plugin-1', ['plugin-2', {plugin2Opt: 'value'}]],
|
||||
@@ -232,10 +261,11 @@ test('Read configuration from file path in "extends"', async t => {
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {...options, branches: ['test_branch']};
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(result, options);
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: './shareable.json',
|
||||
generateNotes: './shareable.json',
|
||||
@@ -244,14 +274,14 @@ test('Read configuration from file path in "extends"', async t => {
|
||||
});
|
||||
});
|
||||
|
||||
test('Read configuration from module path in "extends"', async t => {
|
||||
test('Read configuration from module path in "extends"', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {extends: 'shareable'};
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
@@ -260,33 +290,34 @@ test('Read configuration from module path in "extends"', async t => {
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
|
||||
await outputJson(path.resolve(cwd, 'node_modules/shareable/index.json'), options);
|
||||
|
||||
const {options: results} = await t.context.getConfig({cwd});
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {...options, branches: ['test_branch']};
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(results, options);
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: 'shareable',
|
||||
generateNotes: 'shareable',
|
||||
});
|
||||
});
|
||||
|
||||
test('Read configuration from an array of paths in "extends"', async t => {
|
||||
test('Read configuration from an array of paths in "extends"', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {extends: ['./shareable1.json', './shareable2.json']};
|
||||
const options1 = {
|
||||
verifyRelease: 'verifyRelease1',
|
||||
analyzeCommits: {path: 'analyzeCommits1', param: 'analyzeCommits_param1'},
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
};
|
||||
const options2 = {
|
||||
verifyRelease: 'verifyRelease2',
|
||||
generateNotes: 'generateNotes2',
|
||||
analyzeCommits: {path: 'analyzeCommits2', param: 'analyzeCommits_param2'},
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
@@ -295,12 +326,13 @@ test('Read configuration from an array of paths in "extends"', async t => {
|
||||
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
|
||||
await outputJson(path.resolve(cwd, 'shareable2.json'), options2);
|
||||
|
||||
const {options: results} = await t.context.getConfig({cwd});
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {...options1, ...options2, branches: ['test_branch']};
|
||||
// Verify the options contains the plugin config from shareable1.json and shareable2.json
|
||||
t.deepEqual(results, {...options1, ...options2});
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from shareable1.json and shareable2.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options: {...options1, ...options2}});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
verifyRelease1: './shareable1.json',
|
||||
verifyRelease2: './shareable2.json',
|
||||
@@ -310,12 +342,12 @@ test('Read configuration from an array of paths in "extends"', async t => {
|
||||
});
|
||||
});
|
||||
|
||||
test('Prioritize configuration from config file over "extends"', async t => {
|
||||
test('Prioritize configuration from config file over "extends"', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {
|
||||
extends: './shareable.json',
|
||||
branch: 'test_pkg',
|
||||
branches: ['test_pkg'],
|
||||
generateNotes: 'generateNotes',
|
||||
publish: [{path: 'publishPkg', param: 'publishPkg_param'}],
|
||||
};
|
||||
@@ -323,7 +355,7 @@ test('Prioritize configuration from config file over "extends"', async t => {
|
||||
analyzeCommits: 'analyzeCommits',
|
||||
generateNotes: 'generateNotesShareable',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param'}],
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
@@ -332,12 +364,13 @@ test('Prioritize configuration from config file over "extends"', async t => {
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
|
||||
await outputJson(path.resolve(cwd, 'shareable.json'), options1);
|
||||
|
||||
const {options} = await t.context.getConfig({cwd});
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = omit({...options1, ...pkgOptions, branches: ['test_pkg']}, 'extends');
|
||||
// Verify the options contains the plugin config from package.json and shareable.json
|
||||
t.deepEqual(options, omit({...options1, ...pkgOptions}, 'extends'));
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from package.json and shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options: omit({...options, ...pkgOptions}, 'extends')});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: './shareable.json',
|
||||
generateNotesShareable: './shareable.json',
|
||||
@@ -345,18 +378,18 @@ test('Prioritize configuration from config file over "extends"', async t => {
|
||||
});
|
||||
});
|
||||
|
||||
test('Prioritize configuration from cli/API options over "extends"', async t => {
|
||||
test('Prioritize configuration from cli/API options over "extends"', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const cliOptions = {
|
||||
extends: './shareable2.json',
|
||||
branch: 'branch_opts',
|
||||
branches: ['branch_opts'],
|
||||
publish: [{path: 'publishOpts', param: 'publishOpts_param'}],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
};
|
||||
const pkgOptions = {
|
||||
extends: './shareable1.json',
|
||||
branch: 'branch_pkg',
|
||||
branches: ['branch_pkg'],
|
||||
generateNotes: 'generateNotes',
|
||||
publish: [{path: 'publishPkg', param: 'publishPkg_param'}],
|
||||
};
|
||||
@@ -364,13 +397,13 @@ test('Prioritize configuration from cli/API options over "extends"', async t =>
|
||||
analyzeCommits: 'analyzeCommits1',
|
||||
generateNotes: 'generateNotesShareable1',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param1'}],
|
||||
branch: 'test_branch1',
|
||||
branches: ['test_branch1'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
};
|
||||
const options2 = {
|
||||
analyzeCommits: 'analyzeCommits2',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param2'}],
|
||||
branch: 'test_branch2',
|
||||
branches: ['test_branch2'],
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
@@ -379,24 +412,22 @@ test('Prioritize configuration from cli/API options over "extends"', async t =>
|
||||
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
|
||||
await outputJson(path.resolve(cwd, 'shareable2.json'), options2);
|
||||
|
||||
const {options} = await t.context.getConfig({cwd}, cliOptions);
|
||||
const {options: result} = await t.context.getConfig({cwd}, cliOptions);
|
||||
|
||||
const expected = omit({...options2, ...pkgOptions, ...cliOptions, branches: ['branch_opts']}, 'extends');
|
||||
// Verify the options contains the plugin config from package.json and shareable2.json
|
||||
t.deepEqual(options, omit({...options2, ...pkgOptions, ...cliOptions}, 'extends'));
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from package.json and shareable2.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {
|
||||
cwd,
|
||||
options: omit({...options2, ...pkgOptions, ...cliOptions}, 'extends'),
|
||||
});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
});
|
||||
|
||||
test('Allow to unset properties defined in shareable config with "null"', async t => {
|
||||
test('Allow to unset properties defined in shareable config with "null"', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {
|
||||
extends: './shareable.json',
|
||||
analyzeCommits: null,
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
plugins: null,
|
||||
};
|
||||
@@ -427,6 +458,7 @@ test('Allow to unset properties defined in shareable config with "null"', async
|
||||
},
|
||||
cwd,
|
||||
});
|
||||
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
generateNotes: './shareable.json',
|
||||
analyzeCommits: './shareable.json',
|
||||
@@ -434,13 +466,13 @@ test('Allow to unset properties defined in shareable config with "null"', async
|
||||
});
|
||||
});
|
||||
|
||||
test('Allow to unset properties defined in shareable config with "undefined"', async t => {
|
||||
test('Allow to unset properties defined in shareable config with "undefined"', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {
|
||||
extends: './shareable.json',
|
||||
analyzeCommits: undefined,
|
||||
branch: 'test_branch',
|
||||
branches: ['test_branch'],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
};
|
||||
const options1 = {
|
||||
@@ -453,25 +485,24 @@ test('Allow to unset properties defined in shareable config with "undefined"', a
|
||||
await writeFile(path.resolve(cwd, 'release.config.js'), `module.exports = ${format(pkgOptions)}`);
|
||||
await outputJson(path.resolve(cwd, 'shareable.json'), options1);
|
||||
|
||||
const {options} = await t.context.getConfig({cwd});
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
const expected = {
|
||||
...omit(options1, 'analyzeCommits'),
|
||||
...omit(pkgOptions, ['extends', 'analyzeCommits']),
|
||||
branches: ['test_branch'],
|
||||
};
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(options, {...omit(options1, 'analyzeCommits'), ...omit(pkgOptions, ['extends', 'analyzeCommits'])});
|
||||
t.deepEqual(result, expected);
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {
|
||||
options: {
|
||||
...omit(options1, 'analyzeCommits'),
|
||||
...omit(pkgOptions, ['extends', 'analyzeCommits']),
|
||||
},
|
||||
cwd,
|
||||
});
|
||||
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
generateNotes: './shareable.json',
|
||||
analyzeCommits: './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test('Throw an Error if one of the shareable config cannot be found', async t => {
|
||||
test('Throw an Error if one of the shareable config cannot be found', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkhOptions = {extends: ['./shareable1.json', 'non-existing-path']};
|
||||
@@ -480,8 +511,8 @@ 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.throwsAsync(t.context.getConfig({cwd}), Error);
|
||||
|
||||
t.is(error.message, "Cannot find module 'non-existing-path'");
|
||||
t.is(error.code, 'MODULE_NOT_FOUND');
|
||||
await t.throwsAsync(t.context.getConfig({cwd}), {
|
||||
message: /Cannot find module 'non-existing-path'/,
|
||||
code: 'MODULE_NOT_FOUND',
|
||||
});
|
||||
});
|
||||
|
||||
+206
-77
@@ -1,107 +1,126 @@
|
||||
import test from 'ava';
|
||||
import getAuthUrl from '../lib/get-git-auth-url';
|
||||
import {gitRepo} from './helpers/git-utils';
|
||||
const test = require('ava');
|
||||
const getAuthUrl = require('../lib/get-git-auth-url');
|
||||
const {gitRepo} = require('./helpers/git-utils');
|
||||
|
||||
const env = {GIT_ASKPASS: 'echo', GIT_TERMINAL_PROMPT: 0};
|
||||
|
||||
test('Return the same "git" formatted URL if "gitCredentials" is not defined', async t => {
|
||||
test('Return the same "git" formatted URL if "gitCredentials" is not defined', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'}}),
|
||||
await getAuthUrl({cwd, env, branch: {name: 'master'}, options: {repositoryUrl: 'git@host.null:owner/repo.git'}}),
|
||||
'git@host.null:owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the same "https" formatted URL if "gitCredentials" is not defined', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {branch: 'master', repositoryUrl: 'https://host.null/owner/repo.git'}}),
|
||||
'https://host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is not defined and repositoryUrl is a "git+https" URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {branch: 'master', repositoryUrl: 'git+https://host.null/owner/repo.git'}}),
|
||||
'https://host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Do not add trailing ".git" if not present in the origian URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo'}}),
|
||||
'git@host.null:owner/repo'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "https" URL with group and subgroup', async t => {
|
||||
test('Return the same "https" formatted URL if "gitCredentials" is not defined', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
options: {branch: 'master', repositoryUrl: 'https://host.null/group/subgroup/owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'https://host.null/owner/repo.git'},
|
||||
}),
|
||||
'https://host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is not defined and repositoryUrl is a "git+https" URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git+https://host.null/owner/repo.git'},
|
||||
}),
|
||||
'https://host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Do not add trailing ".git" if not present in the origian URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, vranch: {name: 'master'}, options: {repositoryUrl: 'git@host.null:owner/repo'}}),
|
||||
'git@host.null:owner/repo'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "https" URL with group and subgroup', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'https://host.null/group/subgroup/owner/repo.git'},
|
||||
}),
|
||||
'https://host.null/group/subgroup/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "git" URL with group and subgroup', async t => {
|
||||
test('Handle "git" URL with group and subgroup', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:group/subgroup/owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:group/subgroup/owner/repo.git'},
|
||||
}),
|
||||
'git@host.null:group/subgroup/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Convert shorthand URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {repositoryUrl: 'semanitc-release/semanitc-release'}}),
|
||||
'https://github.com/semanitc-release/semanitc-release.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Convert GitLab shorthand URL', async t => {
|
||||
test('Convert shorthand URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
options: {branch: 'master', repositoryUrl: 'gitlab:semanitc-release/semanitc-release'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'semantic-release/semantic-release'},
|
||||
}),
|
||||
'https://gitlab.com/semanitc-release/semanitc-release.git'
|
||||
'https://github.com/semantic-release/semantic-release.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL', async t => {
|
||||
test('Convert GitLab shorthand URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'gitlab:semantic-release/semantic-release'},
|
||||
}),
|
||||
'https://gitlab.com/semantic-release/semantic-release.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@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 "git" URL without user', async t => {
|
||||
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(
|
||||
@@ -114,167 +133,277 @@ 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 "https" URL', async t => {
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL without user and with a custom port', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'https://host.null/owner/repo.git'},
|
||||
options: {branch: 'master', repositoryUrl: 'host.null:6666:owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null:6666/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL without user and with a custom port followed by a slash', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'host.null:6666:/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null:6666/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();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'https://host.null/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "http" URL', async t => {
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "http" URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'http://host.null/owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'http://host.null/owner/repo.git'},
|
||||
}),
|
||||
'http://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+https" URL', async t => {
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "http" URL with custom port', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'git+https://host.null/owner/repo.git'},
|
||||
options: {branch: 'master', repositoryUrl: 'http://host.null:8080/owner/repo.git'},
|
||||
}),
|
||||
'http://user:pass@host.null:8080/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+https" URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git+https://host.null/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+http" URL', async t => {
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+http" URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'git+http://host.null/owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git+http://host.null/owner/repo.git'},
|
||||
}),
|
||||
'http://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GH_TOKEN"', async t => {
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "ssh" URL', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'ssh://git@host.null:2222/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GH_TOKEN"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GH_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GITHUB_TOKEN"', async t => {
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GITHUB_TOKEN"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GITHUB_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GL_TOKEN"', async t => {
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GL_TOKEN"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GL_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://gitlab-ci-token:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GITLAB_TOKEN"', async t => {
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GITLAB_TOKEN"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GITLAB_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://gitlab-ci-token:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "BB_TOKEN"', async t => {
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "BB_TOKEN"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, BB_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://x-token-auth:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "BITBUCKET_TOKEN"', async t => {
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "BITBUCKET_TOKEN"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, BITBUCKET_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://x-token-auth:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "https" URL with group and subgroup, with "GIT_CREDENTIALS"', async t => {
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "BB_TOKEN_BASIC_AUTH"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, BB_TOKEN_BASIC_AUTH: 'username:token'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://username:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "BITBUCKET_TOKEN_BASIC_AUTH"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, BITBUCKET_TOKEN_BASIC_AUTH: 'username:token'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://username:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "GITHUB_ACTION" is set', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GITHUB_ACTION: 'foo', GITHUB_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://x-access-token:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "https" URL with group and subgroup, with "GIT_CREDENTIALS"', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'https://host.null/group/subgroup/owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'https://host.null/group/subgroup/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/group/subgroup/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "git" URL with group and subgroup, with "GIT_CREDENTIALS', async t => {
|
||||
test('Handle "git" URL with group and subgroup, with "GIT_CREDENTIALS', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:group/subgroup/owner/repo.git'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'git@host.null:group/subgroup/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/group/subgroup/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Do not add git credential to repositoryUrl if push is allowed', async t => {
|
||||
test('Do not add git credential to repositoryUrl if push is allowed', async (t) => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env: {...env, GIT_CREDENTIALS: 'user:pass'}, options: {branch: 'master', repositoryUrl}}),
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl},
|
||||
}),
|
||||
repositoryUrl
|
||||
);
|
||||
});
|
||||
|
||||
+68
-139
@@ -1,151 +1,80 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import getLastRelease from '../lib/get-last-release';
|
||||
import {gitRepo, gitCommits, gitTagVersion, gitCheckout} from './helpers/git-utils';
|
||||
const test = require('ava');
|
||||
const getLastRelease = require('../lib/get-last-release');
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.logger = {log: t.context.log};
|
||||
test('Get the highest non-prerelease valid tag', (t) => {
|
||||
const result = getLastRelease({
|
||||
branch: {
|
||||
name: 'master',
|
||||
tags: [
|
||||
{version: '2.0.0', gitTag: 'v2.0.0', gitHead: 'v2.0.0'},
|
||||
{version: '1.0.0', gitTag: 'v1.0.0', gitHead: 'v1.0.0'},
|
||||
{version: '3.0.0-beta.1', gitTag: 'v3.0.0-beta.1', gitHead: 'v3.0.0-beta.1'},
|
||||
],
|
||||
type: 'release',
|
||||
},
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.deepEqual(result, {version: '2.0.0', gitTag: 'v2.0.0', name: 'v2.0.0', gitHead: 'v2.0.0', channels: undefined});
|
||||
});
|
||||
|
||||
test('Get the highest non-prerelease valid tag', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Create some commits and tags
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('foo', undefined, {cwd});
|
||||
const commits = await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitCommits(['Fourth'], {cwd});
|
||||
await gitTagVersion('v3.0', undefined, {cwd});
|
||||
await gitCommits(['Fifth'], {cwd});
|
||||
await gitTagVersion('v3.0.0-beta.1', undefined, {cwd});
|
||||
test('Get the highest prerelease valid tag, ignoring other tags from other prerelease channels', (t) => {
|
||||
const result = getLastRelease({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
prerelease: 'beta',
|
||||
channel: 'beta',
|
||||
tags: [
|
||||
{version: '1.0.0-beta.1', gitTag: 'v1.0.0-beta.1', gitHead: 'v1.0.0-beta.1', channels: ['beta']},
|
||||
{version: '1.0.0-beta.2', gitTag: 'v1.0.0-beta.2', gitHead: 'v1.0.0-beta.2', channels: ['beta']},
|
||||
{version: '1.0.0-alpha.1', gitTag: 'v1.0.0-alpha.1', gitHead: 'v1.0.0-alpha.1', channels: ['alpha']},
|
||||
],
|
||||
type: 'prerelease',
|
||||
},
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'v2.0.0', version: '2.0.0'});
|
||||
t.deepEqual(t.context.log.args[0], ['Found git tag v2.0.0 associated with version 2.0.0']);
|
||||
t.deepEqual(result, {
|
||||
version: '1.0.0-beta.2',
|
||||
gitTag: 'v1.0.0-beta.2',
|
||||
name: 'v1.0.0-beta.2',
|
||||
gitHead: 'v1.0.0-beta.2',
|
||||
channels: ['beta'],
|
||||
});
|
||||
});
|
||||
|
||||
test('Get the highest tag in the history of the current branch', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commit to the master branch
|
||||
await gitCommits(['First'], {cwd});
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch', true, {cwd});
|
||||
// Add commit to the 'other-branch' branch
|
||||
await gitCommits(['Second'], {cwd});
|
||||
// Create the tag corresponding to version 3.0.0
|
||||
await gitTagVersion('v3.0.0', undefined, {cwd});
|
||||
// Checkout master
|
||||
await gitCheckout('master', false, {cwd});
|
||||
// Add another commit to the master branch
|
||||
const commits = await gitCommits(['Third'], {cwd});
|
||||
// Create the tag corresponding to version 2.0.0
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'v2.0.0', version: '2.0.0'});
|
||||
});
|
||||
|
||||
test('Match the tag name from the begining of the string', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('prefix/v1.0.0', undefined, {cwd});
|
||||
await gitTagVersion('prefix/v2.0.0', undefined, {cwd});
|
||||
await gitTagVersion('other-prefix/v3.0.0', undefined, {cwd});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `prefix/v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'prefix/v2.0.0', version: '2.0.0'});
|
||||
});
|
||||
|
||||
test('Return empty object if no valid tag is found', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Create some commits and tags
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('foo', undefined, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v2.0.x', undefined, {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v3.0', undefined, {cwd});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `v\${version}`}, logger: t.context.logger});
|
||||
test('Return empty object if no valid tag is found', (t) => {
|
||||
const result = getLastRelease({
|
||||
branch: {
|
||||
name: 'master',
|
||||
tags: [{version: '3.0.0-beta.1', gitTag: 'v3.0.0-beta.1', gitHead: 'v3.0.0-beta.1'}],
|
||||
type: 'release',
|
||||
},
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.deepEqual(result, {});
|
||||
t.is(t.context.log.args[0][0], 'No git tag version found');
|
||||
});
|
||||
|
||||
test('Return empty object if no valid tag is found in history', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitCheckout('other-branch', true, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
await gitTagVersion('v3.0.0', undefined, {cwd});
|
||||
await gitCheckout('master', false, {cwd});
|
||||
test('Get the highest non-prerelease valid tag before a certain version', (t) => {
|
||||
const result = getLastRelease(
|
||||
{
|
||||
branch: {
|
||||
name: 'master',
|
||||
channel: undefined,
|
||||
tags: [
|
||||
{version: '2.0.0', gitTag: 'v2.0.0', gitHead: 'v2.0.0'},
|
||||
{version: '1.0.0', gitTag: 'v1.0.0', gitHead: 'v1.0.0'},
|
||||
{version: '2.0.0-beta.1', gitTag: 'v2.0.0-beta.1', gitHead: 'v2.0.0-beta.1'},
|
||||
{version: '2.1.0', gitTag: 'v2.1.0', gitHead: 'v2.1.0'},
|
||||
{version: '2.1.1', gitTag: 'v2.1.1', gitHead: 'v2.1.1'},
|
||||
],
|
||||
type: 'release',
|
||||
},
|
||||
options: {tagFormat: `v\${version}`},
|
||||
},
|
||||
{before: '2.1.0'}
|
||||
);
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {});
|
||||
t.is(t.context.log.args[0][0], 'No git tag version found');
|
||||
});
|
||||
|
||||
test('Get the highest valid tag corresponding to the "tagFormat"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Create some commits and tags
|
||||
const [{hash: gitHead}] = await gitCommits(['First'], {cwd});
|
||||
|
||||
await gitTagVersion('1.0.0', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `\${version}`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: '1.0.0',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('foo-1.0.0-bar', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `foo-\${version}-bar`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: 'foo-1.0.0-bar',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('foo-v1.0.0-bar', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `foo-v\${version}-bar`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: 'foo-v1.0.0-bar',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('(.+)/1.0.0/(a-z)', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `(.+)/\${version}/(a-z)`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: '(.+)/1.0.0/(a-z)',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('2.0.0-1.0.0-bar.1', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `2.0.0-\${version}-bar.1`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: '2.0.0-1.0.0-bar.1',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('3.0.0-bar.1', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `\${version}-bar.1`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: '3.0.0-bar.1',
|
||||
version: '3.0.0',
|
||||
});
|
||||
t.deepEqual(result, {version: '2.0.0', gitTag: 'v2.0.0', name: 'v2.0.0', gitHead: 'v2.0.0', channels: undefined});
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import test from 'ava';
|
||||
import {spy} from 'sinon';
|
||||
import getLogger from '../lib/get-logger';
|
||||
const test = require('ava');
|
||||
const {spy} = require('sinon');
|
||||
const getLogger = require('../lib/get-logger');
|
||||
|
||||
test('Expose "error", "success" and "log" functions', t => {
|
||||
test('Expose "error", "success" and "log" functions', (t) => {
|
||||
const stdout = spy();
|
||||
const stderr = spy();
|
||||
const logger = getLogger({stdout: {write: stdout}, stderr: {write: stderr}});
|
||||
|
||||
+264
-28
@@ -1,41 +1,277 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import getNextVersion from '../lib/get-next-version';
|
||||
const test = require('ava');
|
||||
const {stub} = require('sinon');
|
||||
const getNextVersion = require('../lib/get-next-version');
|
||||
|
||||
test.beforeEach(t => {
|
||||
test.beforeEach((t) => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.logger = {log: t.context.log};
|
||||
});
|
||||
|
||||
test('Increase version for patch release', t => {
|
||||
const version = getNextVersion({
|
||||
nextRelease: {type: 'patch'},
|
||||
lastRelease: {version: '1.0.0'},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
t.is(version, '1.0.1');
|
||||
test('Increase version for patch release', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {name: 'master', type: 'release', tags: [{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]}]},
|
||||
nextRelease: {type: 'patch'},
|
||||
lastRelease: {version: '1.0.0', channels: [null]},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.0.1'
|
||||
);
|
||||
});
|
||||
|
||||
test('Increase version for minor release', t => {
|
||||
const version = getNextVersion({
|
||||
nextRelease: {type: 'minor'},
|
||||
lastRelease: {version: '1.0.0'},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
t.is(version, '1.1.0');
|
||||
test('Increase version for minor release', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {name: 'master', type: 'release', tags: [{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]}]},
|
||||
nextRelease: {type: 'minor'},
|
||||
lastRelease: {version: '1.0.0', channels: [null]},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.1.0'
|
||||
);
|
||||
});
|
||||
|
||||
test('Increase version for major release', t => {
|
||||
const version = getNextVersion({
|
||||
nextRelease: {type: 'major'},
|
||||
lastRelease: {version: '1.0.0'},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
t.is(version, '2.0.0');
|
||||
test('Increase version for major release', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {name: 'master', type: 'release', tags: [{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]}]},
|
||||
nextRelease: {type: 'major'},
|
||||
lastRelease: {version: '1.0.0', channels: [null]},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'2.0.0'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return 1.0.0 if there is no previous release', t => {
|
||||
const version = getNextVersion({nextRelease: {type: 'minor'}, lastRelease: {}, logger: t.context.logger});
|
||||
t.is(version, '1.0.0');
|
||||
test('Return 1.0.0 if there is no previous release', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {name: 'master', type: 'release', tags: []},
|
||||
nextRelease: {type: 'minor'},
|
||||
lastRelease: {},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.0.0'
|
||||
);
|
||||
});
|
||||
|
||||
test('Increase version for patch release on prerelease branch', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]}],
|
||||
},
|
||||
nextRelease: {type: 'patch', channel: 'beta'},
|
||||
lastRelease: {version: '1.0.0', channels: [null]},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.0.1-beta.1'
|
||||
);
|
||||
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v1.0.1-beta.1', version: '1.0.1-beta.1', channels: ['beta']},
|
||||
],
|
||||
},
|
||||
nextRelease: {type: 'patch', channel: 'beta'},
|
||||
lastRelease: {version: '1.0.1-beta.1', channels: ['beta']},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.0.1-beta.2'
|
||||
);
|
||||
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'alpha',
|
||||
type: 'prerelease',
|
||||
prerelease: 'alpha',
|
||||
tags: [{gitTag: 'v1.0.1-beta.1', version: '1.0.1-beta.1', channels: ['beta']}],
|
||||
},
|
||||
nextRelease: {type: 'patch', channel: 'alpha'},
|
||||
lastRelease: {version: '1.0.1-beta.1', channels: ['beta']},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.0.2-alpha.1'
|
||||
);
|
||||
});
|
||||
|
||||
test('Increase version for minor release on prerelease branch', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]}],
|
||||
},
|
||||
nextRelease: {type: 'minor', channel: 'beta'},
|
||||
lastRelease: {version: '1.0.0', channels: [null]},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.1.0-beta.1'
|
||||
);
|
||||
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v1.1.0-beta.1', version: '1.1.0-beta.1', channels: ['beta']},
|
||||
],
|
||||
},
|
||||
nextRelease: {type: 'minor', channel: 'beta'},
|
||||
lastRelease: {version: '1.1.0-beta.1', channels: ['beta']},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.1.0-beta.2'
|
||||
);
|
||||
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'alpha',
|
||||
type: 'prerelease',
|
||||
prerelease: 'alpha',
|
||||
tags: [{gitTag: 'v1.1.0-beta.1', version: '1.1.0-beta.1', channels: ['beta']}],
|
||||
},
|
||||
nextRelease: {type: 'minor', channel: 'alpha'},
|
||||
lastRelease: {version: '1.1.0-beta.1', channels: ['beta']},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.2.0-alpha.1'
|
||||
);
|
||||
});
|
||||
|
||||
test('Increase version for major release on prerelease branch', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]}],
|
||||
},
|
||||
nextRelease: {type: 'major', channel: 'beta'},
|
||||
lastRelease: {version: '1.0.0', channels: [null]},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'2.0.0-beta.1'
|
||||
);
|
||||
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v2.0.0-beta.1', version: '2.0.0-beta.1', channels: ['beta']},
|
||||
],
|
||||
},
|
||||
nextRelease: {type: 'major', channel: 'beta'},
|
||||
lastRelease: {version: '2.0.0-beta.1', channels: ['beta']},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'2.0.0-beta.2'
|
||||
);
|
||||
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'alpha',
|
||||
type: 'prerelease',
|
||||
prerelease: 'alpha',
|
||||
tags: [{gitTag: 'v2.0.0-beta.1', version: '2.0.0-beta.1', channels: ['beta']}],
|
||||
},
|
||||
nextRelease: {type: 'major', channel: 'alpha'},
|
||||
lastRelease: {version: '2.0.0-beta.1', channels: ['beta']},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'3.0.0-alpha.1'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return 1.0.0 if there is no previous release on prerelease branch', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {name: 'beta', type: 'prerelease', prerelease: 'beta', tags: []},
|
||||
nextRelease: {type: 'minor'},
|
||||
lastRelease: {},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.0.0-beta.1'
|
||||
);
|
||||
});
|
||||
|
||||
test('Increase version for release on prerelease branch after previous commits were merged to release branch', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: [null]}, // Version v1.1.0 released on default branch after beta was merged into master
|
||||
{gitTag: 'v1.1.0-beta.1', version: '1.1.0-beta.1', channels: [null, 'beta']},
|
||||
],
|
||||
},
|
||||
nextRelease: {type: 'minor'},
|
||||
lastRelease: {version: '1.1.0', channels: [null]},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.2.0-beta.1'
|
||||
);
|
||||
});
|
||||
|
||||
test('Increase version for release on prerelease branch based on highest commit type since last regular release', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v1.1.0-beta.1', version: '1.1.0-beta.1', channels: [null, 'beta']},
|
||||
],
|
||||
},
|
||||
nextRelease: {type: 'major'},
|
||||
lastRelease: {version: 'v1.1.0-beta.1', channels: [null]},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'2.0.0-beta.1'
|
||||
);
|
||||
});
|
||||
|
||||
test('Increase version for release on prerelease branch when there is no regular releases on other branches', (t) => {
|
||||
t.is(
|
||||
getNextVersion({
|
||||
branch: {
|
||||
name: 'beta',
|
||||
type: 'prerelease',
|
||||
prerelease: 'beta',
|
||||
tags: [{gitTag: 'v1.0.0-beta.1', version: '1.0.0-beta.1', channels: ['beta']}],
|
||||
},
|
||||
nextRelease: {type: 'minor', channel: 'beta'},
|
||||
lastRelease: {version: 'v1.0.0-beta.1', channels: ['beta']},
|
||||
logger: t.context.logger,
|
||||
}),
|
||||
'1.0.0-beta.2'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
const test = require('ava');
|
||||
const getReleaseToAdd = require('../lib/get-release-to-add');
|
||||
|
||||
test('Return versions merged from release to maintenance branch, excluding lower than branch start range', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: '2.x',
|
||||
channel: '2.x',
|
||||
type: 'maintenance',
|
||||
mergeRange: '>=2.0.0 <3.0.0',
|
||||
tags: [
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: ['2.x']},
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: [null]},
|
||||
{gitTag: 'v2.1.0', version: '2.1.0', channels: [null]},
|
||||
{gitTag: 'v2.1.1', version: '2.1.1', channels: [null]},
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: [null]},
|
||||
],
|
||||
},
|
||||
branches: [{name: '2.x', channel: '2.x'}, {name: 'master'}],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.deepEqual(result, {
|
||||
lastRelease: {version: '2.1.0', channels: [null], gitTag: 'v2.1.0', name: 'v2.1.0', gitHead: 'v2.1.0'},
|
||||
currentRelease: {
|
||||
type: 'patch',
|
||||
version: '2.1.1',
|
||||
channels: [null],
|
||||
gitTag: 'v2.1.1',
|
||||
name: 'v2.1.1',
|
||||
gitHead: 'v2.1.1',
|
||||
},
|
||||
nextRelease: {
|
||||
type: 'patch',
|
||||
version: '2.1.1',
|
||||
channel: '2.x',
|
||||
gitTag: 'v2.1.1',
|
||||
name: 'v2.1.1',
|
||||
gitHead: 'v2.1.1',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('Return versions merged between release branches', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: 'master',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null, 'next']},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: ['next']},
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: ['next-major']},
|
||||
],
|
||||
},
|
||||
branches: [{name: 'master'}, {name: 'next', channel: 'next'}, {name: 'next-major', channel: 'next-major'}],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.deepEqual(result, {
|
||||
lastRelease: {
|
||||
version: '1.1.0',
|
||||
gitTag: 'v1.1.0',
|
||||
name: 'v1.1.0',
|
||||
gitHead: 'v1.1.0',
|
||||
channels: ['next'],
|
||||
},
|
||||
currentRelease: {
|
||||
type: 'major',
|
||||
version: '2.0.0',
|
||||
channels: ['next-major'],
|
||||
gitTag: 'v2.0.0',
|
||||
name: 'v2.0.0',
|
||||
gitHead: 'v2.0.0',
|
||||
},
|
||||
nextRelease: {
|
||||
type: 'major',
|
||||
version: '2.0.0',
|
||||
channel: null,
|
||||
gitTag: 'v2.0.0',
|
||||
name: 'v2.0.0',
|
||||
gitHead: 'v2.0.0',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('Return releases sorted by ascending order', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: 'master',
|
||||
tags: [
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: ['next-major']},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: ['next']},
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null, 'next']},
|
||||
],
|
||||
},
|
||||
branches: [{name: 'master'}, {name: 'next', channel: 'next'}, {name: 'next-major', channel: 'next-major'}],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.deepEqual(result, {
|
||||
lastRelease: {version: '1.1.0', gitTag: 'v1.1.0', name: 'v1.1.0', gitHead: 'v1.1.0', channels: ['next']},
|
||||
currentRelease: {
|
||||
type: 'major',
|
||||
version: '2.0.0',
|
||||
channels: ['next-major'],
|
||||
gitTag: 'v2.0.0',
|
||||
name: 'v2.0.0',
|
||||
gitHead: 'v2.0.0',
|
||||
},
|
||||
nextRelease: {
|
||||
type: 'major',
|
||||
version: '2.0.0',
|
||||
channel: null,
|
||||
gitTag: 'v2.0.0',
|
||||
name: 'v2.0.0',
|
||||
gitHead: 'v2.0.0',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('No lastRelease', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: 'master',
|
||||
tags: [{gitTag: 'v1.0.0', version: '1.0.0', channels: ['next']}],
|
||||
},
|
||||
branches: [{name: 'master'}, {name: 'next', channel: 'next'}],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.deepEqual(result, {
|
||||
lastRelease: {},
|
||||
currentRelease: {
|
||||
type: 'major',
|
||||
version: '1.0.0',
|
||||
channels: ['next'],
|
||||
gitTag: 'v1.0.0',
|
||||
name: 'v1.0.0',
|
||||
gitHead: 'v1.0.0',
|
||||
},
|
||||
nextRelease: {
|
||||
type: 'major',
|
||||
version: '1.0.0',
|
||||
channel: null,
|
||||
gitTag: 'v1.0.0',
|
||||
name: 'v1.0.0',
|
||||
gitHead: 'v1.0.0',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('Ignore pre-release versions', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: 'master',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null, 'next']},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: ['next']},
|
||||
{gitTag: 'v2.0.0-alpha.1', version: '2.0.0-alpha.1', channels: ['alpha']},
|
||||
],
|
||||
},
|
||||
branches: [
|
||||
{name: 'master'},
|
||||
{name: 'next', channel: 'next'},
|
||||
{name: 'alpha', type: 'prerelease', channel: 'alpha'},
|
||||
],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.deepEqual(result, {
|
||||
lastRelease: {version: '1.0.0', channels: [null, 'next'], gitTag: 'v1.0.0', name: 'v1.0.0', gitHead: 'v1.0.0'},
|
||||
currentRelease: {
|
||||
type: 'minor',
|
||||
version: '1.1.0',
|
||||
channels: ['next'],
|
||||
gitTag: 'v1.1.0',
|
||||
name: 'v1.1.0',
|
||||
gitHead: 'v1.1.0',
|
||||
},
|
||||
nextRelease: {
|
||||
type: 'minor',
|
||||
version: '1.1.0',
|
||||
channel: null,
|
||||
gitTag: 'v1.1.0',
|
||||
name: 'v1.1.0',
|
||||
gitHead: 'v1.1.0',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('Exclude versions merged from release to maintenance branch if they have the same "channel"', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: '2.x',
|
||||
channel: 'latest',
|
||||
type: 'maintenance',
|
||||
mergeRange: '>=2.0.0 <3.0.0',
|
||||
tags: [
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: [null]},
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: [null]},
|
||||
{gitTag: 'v2.1.0', version: '2.1.0', channels: [null]},
|
||||
{gitTag: 'v2.1.1', version: '2.1.1', channels: [null]},
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: [null]},
|
||||
],
|
||||
},
|
||||
branches: [
|
||||
{name: '2.x', channel: 'latest'},
|
||||
{name: 'master', channel: 'latest'},
|
||||
],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.is(result, undefined);
|
||||
});
|
||||
|
||||
test('Exclude versions merged between release branches if they have the same "channel"', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: 'master',
|
||||
channel: 'latest',
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', channels: ['latest'], version: '1.0.0'},
|
||||
{gitTag: 'v1.1.0', channels: ['latest'], version: '1.1.0'},
|
||||
{gitTag: 'v2.0.0', channels: ['latest'], version: '2.0.0'},
|
||||
],
|
||||
},
|
||||
branches: [
|
||||
{name: 'master', channel: 'latest'},
|
||||
{name: 'next', channel: 'latest'},
|
||||
{name: 'next-major', channel: 'latest'},
|
||||
],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.is(result, undefined);
|
||||
});
|
||||
|
||||
test('Exclude versions merged between release branches if they all have "channel" set to "false"', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: 'master',
|
||||
channel: false,
|
||||
tags: [
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: [null]},
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: [null]},
|
||||
],
|
||||
},
|
||||
branches: [
|
||||
{name: 'master', channel: false},
|
||||
{name: 'next', channel: false},
|
||||
{name: 'next-major', channel: false},
|
||||
],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.is(result, undefined);
|
||||
});
|
||||
|
||||
test('Exclude versions number less than the latest version already released on that branch', (t) => {
|
||||
const result = getReleaseToAdd({
|
||||
branch: {
|
||||
name: '2.x',
|
||||
channel: '2.x',
|
||||
type: 'maintenance',
|
||||
mergeRange: '>=2.0.0 <3.0.0',
|
||||
tags: [
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: ['2.x']},
|
||||
{gitTag: 'v2.0.0', version: '2.0.0', channels: [null]},
|
||||
{gitTag: 'v2.1.0', version: '2.1.0', channels: [null]},
|
||||
{gitTag: 'v2.1.1', version: '2.1.1', channels: [null, '2.x']},
|
||||
{gitTag: 'v1.0.0', version: '1.0.0', channels: [null]},
|
||||
{gitTag: 'v1.1.0', version: '1.1.0', channels: [null]},
|
||||
],
|
||||
},
|
||||
branches: [{name: '2.x', channel: '2.x'}, {name: 'master'}],
|
||||
options: {tagFormat: `v\${version}`},
|
||||
});
|
||||
|
||||
t.is(result, undefined);
|
||||
});
|
||||
+234
-59
@@ -1,19 +1,23 @@
|
||||
import test from 'ava';
|
||||
import tempy from 'tempy';
|
||||
import {
|
||||
const test = require('ava');
|
||||
const tempy = require('tempy');
|
||||
const {
|
||||
getTagHead,
|
||||
isRefInHistory,
|
||||
isRefExists,
|
||||
fetch,
|
||||
getGitHead,
|
||||
repoUrl,
|
||||
tag,
|
||||
push,
|
||||
getTags,
|
||||
getBranches,
|
||||
isGitRepo,
|
||||
verifyTagName,
|
||||
isBranchUpToDate,
|
||||
} from '../lib/git';
|
||||
import {
|
||||
getNote,
|
||||
addNote,
|
||||
fetchNotes,
|
||||
} = require('../lib/git');
|
||||
const {
|
||||
gitRepo,
|
||||
gitCommits,
|
||||
gitCheckout,
|
||||
@@ -25,9 +29,14 @@ import {
|
||||
gitRemoteTagHead,
|
||||
gitPush,
|
||||
gitDetachedHead,
|
||||
} from './helpers/git-utils';
|
||||
gitDetachedHeadFromBranch,
|
||||
gitAddNote,
|
||||
gitGetNote,
|
||||
gitFetch,
|
||||
initGit,
|
||||
} = require('./helpers/git-utils');
|
||||
|
||||
test('Get the last commit sha', async t => {
|
||||
test('Get the last commit sha', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
@@ -38,14 +47,14 @@ test('Get the last commit sha', async t => {
|
||||
t.is(result, commits[0].hash);
|
||||
});
|
||||
|
||||
test('Throw error if the last commit sha cannot be found', async t => {
|
||||
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.throwsAsync(getGitHead({cwd}), Error);
|
||||
await t.throwsAsync(getGitHead({cwd}));
|
||||
});
|
||||
|
||||
test('Unshallow and fetch repository', async t => {
|
||||
test('Unshallow and fetch repository', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
@@ -56,21 +65,26 @@ test('Unshallow and fetch repository', async t => {
|
||||
// Verify the shallow clone contains only one commit
|
||||
t.is((await gitGetCommits(undefined, {cwd})).length, 1);
|
||||
|
||||
await fetch(repositoryUrl, {cwd});
|
||||
await fetch(repositoryUrl, 'master', 'master', {cwd});
|
||||
|
||||
// Verify the shallow clone contains all the commits
|
||||
t.is((await gitGetCommits(undefined, {cwd})).length, 2);
|
||||
});
|
||||
|
||||
test('Do not throw error when unshallow a complete repository', async t => {
|
||||
test('Do not throw error when unshallow a complete repository', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd, repositoryUrl} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await t.notThrowsAsync(fetch(repositoryUrl, {cwd}));
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
await gitCheckout('second-branch', true, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitPush(repositoryUrl, 'second-branch', {cwd});
|
||||
|
||||
await t.notThrowsAsync(fetch(repositoryUrl, 'master', 'master', {cwd}));
|
||||
await t.notThrowsAsync(fetch(repositoryUrl, 'second-branch', 'master', {cwd}));
|
||||
});
|
||||
|
||||
test('Fetch all tags on a detached head repository', async t => {
|
||||
test('Fetch all tags on a detached head repository', async (t) => {
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
|
||||
await gitCommits(['First'], {cwd});
|
||||
@@ -82,28 +96,99 @@ test('Fetch all tags on a detached head repository', async t => {
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
cwd = await gitDetachedHead(repositoryUrl, commit.hash);
|
||||
|
||||
await fetch(repositoryUrl, {cwd});
|
||||
await fetch(repositoryUrl, 'master', 'master', {cwd});
|
||||
|
||||
t.deepEqual((await getTags({cwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0'].sort());
|
||||
t.deepEqual((await getTags('master', {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 => {
|
||||
test('Fetch all tags on a repository with a detached head from branch (CircleCI)', async (t) => {
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v1.0.1', undefined, {cwd});
|
||||
const [commit] = await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v1.1.0', undefined, {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
await gitCheckout('other-branch', true, {cwd});
|
||||
await gitPush(repositoryUrl, 'other-branch', {cwd});
|
||||
await gitCheckout('master', false, {cwd});
|
||||
await gitCommits(['Fourth'], {cwd});
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
cwd = await gitDetachedHeadFromBranch(repositoryUrl, 'other-branch', commit.hash);
|
||||
|
||||
await fetch(repositoryUrl, 'master', 'other-branch', {cwd});
|
||||
await fetch(repositoryUrl, 'other-branch', 'other-branch', {cwd});
|
||||
|
||||
t.deepEqual((await getTags('other-branch', {cwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0'].sort());
|
||||
t.deepEqual((await getTags('master', {cwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0', 'v2.0.0'].sort());
|
||||
});
|
||||
|
||||
test('Fetch all tags on a detached head repository with outdated cached repo (GitLab CI)', async (t) => {
|
||||
const {cwd, repositoryUrl} = await gitRepo();
|
||||
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v1.0.1', undefined, {cwd});
|
||||
let [commit] = await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v1.1.0', undefined, {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
|
||||
// Create a clone (as first CI run would)
|
||||
const cloneCwd = await gitShallowClone(repositoryUrl);
|
||||
await gitFetch(repositoryUrl, {cwd: cloneCwd});
|
||||
await gitCheckout(commit.hash, false, {cwd: cloneCwd});
|
||||
|
||||
// Push tag to remote
|
||||
[commit] = await gitCommits(['Fourth'], {cwd});
|
||||
await gitTagVersion('v1.2.0', undefined, {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
|
||||
// Fetch on the cached repo and make detached head, leaving master outdated
|
||||
await fetch(repositoryUrl, 'master', 'master', {cwd: cloneCwd});
|
||||
await gitCheckout(commit.hash, false, {cwd: cloneCwd});
|
||||
|
||||
t.deepEqual((await getTags('master', {cwd: cloneCwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0', 'v1.2.0'].sort());
|
||||
});
|
||||
|
||||
test('Verify if a branch exists', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
await gitCommits(['First'], {cwd});
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch', true, {cwd});
|
||||
// Add commits to the 'other-branch' branch
|
||||
const otherCommits = await gitCommits(['Second'], {cwd});
|
||||
await gitCheckout('master', false, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
|
||||
t.true(await isRefInHistory(commits[0].hash, {cwd}));
|
||||
t.falsy(await isRefInHistory(otherCommits[0].hash, {cwd}));
|
||||
await t.throwsAsync(isRefInHistory('non-existant-sha', {cwd}));
|
||||
t.true(await isRefExists('master', {cwd}));
|
||||
t.true(await isRefExists('other-branch', {cwd}));
|
||||
t.falsy(await isRefExists('next', {cwd}));
|
||||
});
|
||||
|
||||
test('Get the commit sha for a given tag or falsy if the tag does not exists', async t => {
|
||||
test('Get all branches', async (t) => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
await gitCheckout('second-branch', true, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitPush(repositoryUrl, 'second-branch', {cwd});
|
||||
await gitCheckout('third-branch', true, {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitPush(repositoryUrl, 'third-branch', {cwd});
|
||||
|
||||
t.deepEqual((await getBranches(repositoryUrl, {cwd})).sort(), ['master', 'second-branch', 'third-branch'].sort());
|
||||
});
|
||||
|
||||
test('Return empty array if there are no branches', async (t) => {
|
||||
const {cwd, repositoryUrl} = await initGit(true);
|
||||
t.deepEqual(await getBranches(repositoryUrl, {cwd}), []);
|
||||
});
|
||||
|
||||
test('Get the commit sha for a given tag', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
@@ -112,10 +197,9 @@ test('Get the commit sha for a given tag or falsy if the tag does not exists', a
|
||||
await gitTagVersion('v1.0.0', undefined, {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 => {
|
||||
test('Return git remote repository url from config', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add remote.origin.url config
|
||||
@@ -124,7 +208,7 @@ test('Return git remote repository url from config', async t => {
|
||||
t.is(await repoUrl({cwd}), 'git@hostname.com:owner/package.git');
|
||||
});
|
||||
|
||||
test('Return git remote repository url set while cloning', async t => {
|
||||
test('Return git remote repository url set while cloning', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
@@ -134,109 +218,200 @@ test('Return git remote repository url set while cloning', async t => {
|
||||
t.is(await repoUrl({cwd}), repositoryUrl);
|
||||
});
|
||||
|
||||
test('Return falsy if git repository url is not set', async t => {
|
||||
test('Return falsy if git repository url is not set', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.falsy(await repoUrl({cwd}));
|
||||
});
|
||||
|
||||
test('Add tag on head commit', async t => {
|
||||
test('Add tag on head commit', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const commits = await gitCommits(['Test commit'], {cwd});
|
||||
|
||||
await tag('tag_name', {cwd});
|
||||
await tag('tag_name', 'HEAD', {cwd});
|
||||
|
||||
await t.is(await gitCommitTag(commits[0].hash, {cwd}), 'tag_name');
|
||||
});
|
||||
|
||||
test('Push tag 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 tag('tag_name', 'HEAD', {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 => {
|
||||
test('Push tag to remote repository with remote branch ahead', 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});
|
||||
const temporaryRepo = await gitShallowClone(repositoryUrl);
|
||||
await gitCommits(['Second'], {cwd: temporaryRepo});
|
||||
await gitPush('origin', 'master', {cwd: temporaryRepo});
|
||||
|
||||
await tag('tag_name', {cwd});
|
||||
await tag('tag_name', 'HEAD', {cwd});
|
||||
await push(repositoryUrl, {cwd});
|
||||
|
||||
t.is(await gitRemoteTagHead(repositoryUrl, 'tag_name', {cwd}), commits[0].hash);
|
||||
});
|
||||
|
||||
test('Return "true" if in a Git repository', async t => {
|
||||
test('Return "true" if in a Git repository', async (t) => {
|
||||
// Create a git repository with a remote, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo(true);
|
||||
|
||||
t.true(await isGitRepo({cwd}));
|
||||
});
|
||||
|
||||
test('Return falsy if not in a Git repository', async t => {
|
||||
test('Return falsy if not in a Git repository', async (t) => {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
t.falsy(await isGitRepo({cwd}));
|
||||
});
|
||||
|
||||
test('Return "true" for valid tag names', async t => {
|
||||
test('Return "true" for valid tag names', async (t) => {
|
||||
t.true(await verifyTagName('1.0.0'));
|
||||
t.true(await verifyTagName('v1.0.0'));
|
||||
t.true(await verifyTagName('tag_name'));
|
||||
t.true(await verifyTagName('tag/name'));
|
||||
});
|
||||
|
||||
test('Return falsy for invalid tag names', async t => {
|
||||
test('Return falsy for invalid tag names', async (t) => {
|
||||
t.falsy(await verifyTagName('?1.0.0'));
|
||||
t.falsy(await verifyTagName('*1.0.0'));
|
||||
t.falsy(await verifyTagName('[1.0.0]'));
|
||||
t.falsy(await verifyTagName('1.0.0..'));
|
||||
});
|
||||
|
||||
test('Throws error if obtaining the tags fails', async t => {
|
||||
test('Throws error if obtaining the tags fails', async (t) => {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
await t.throwsAsync(getTags({cwd}));
|
||||
await t.throwsAsync(getTags('master', {cwd}));
|
||||
});
|
||||
|
||||
test('Return "true" if repository is up to date', async t => {
|
||||
test('Return "true" if repository is up to date', async (t) => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
|
||||
t.true(await isBranchUpToDate('master', {cwd}));
|
||||
t.true(await isBranchUpToDate(repositoryUrl, 'master', {cwd}));
|
||||
});
|
||||
|
||||
test('Return falsy if repository is not up to date', async t => {
|
||||
test('Return falsy if repository is not up to date', async (t) => {
|
||||
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}));
|
||||
t.true(await isBranchUpToDate(repositoryUrl, 'master', {cwd}));
|
||||
|
||||
const tmpRepo = await gitShallowClone(repositoryUrl);
|
||||
await gitCommits(['Third'], {cwd: tmpRepo});
|
||||
await gitPush('origin', 'master', {cwd: tmpRepo});
|
||||
const temporaryRepo = await gitShallowClone(repositoryUrl);
|
||||
await gitCommits(['Third'], {cwd: temporaryRepo});
|
||||
await gitPush('origin', 'master', {cwd: temporaryRepo});
|
||||
|
||||
t.falsy(await isBranchUpToDate('master', {cwd}));
|
||||
t.falsy(await isBranchUpToDate(repositoryUrl, 'master', {cwd}));
|
||||
});
|
||||
|
||||
test('Return "true" if local repository is ahead', async t => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
test('Return falsy if detached head repository is not up to date', async (t) => {
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
|
||||
const [commit] = await gitCommits(['First'], {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
cwd = await gitDetachedHead(repositoryUrl, commit.hash);
|
||||
await fetch(repositoryUrl, 'master', 'master', {cwd});
|
||||
|
||||
t.true(await isBranchUpToDate('master', {cwd}));
|
||||
t.falsy(await isBranchUpToDate(repositoryUrl, 'master', {cwd}));
|
||||
});
|
||||
|
||||
test('Get a commit note', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
|
||||
await gitAddNote(JSON.stringify({note: 'note'}), commits[0].hash, {cwd});
|
||||
|
||||
t.deepEqual(await getNote(commits[0].hash, {cwd}), {note: 'note'});
|
||||
});
|
||||
|
||||
test('Return empty object if there is no commit note', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
|
||||
t.deepEqual(await getNote(commits[0].hash, {cwd}), {});
|
||||
});
|
||||
|
||||
test('Throw error if a commit note in invalid', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
|
||||
await gitAddNote('non-json note', commits[0].hash, {cwd});
|
||||
|
||||
await t.throwsAsync(getNote(commits[0].hash, {cwd}));
|
||||
});
|
||||
|
||||
test('Add a commit note', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
|
||||
await addNote({note: 'note'}, commits[0].hash, {cwd});
|
||||
|
||||
t.is(await gitGetNote(commits[0].hash, {cwd}), '{"note":"note"}');
|
||||
});
|
||||
|
||||
test('Overwrite a commit note', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
|
||||
await addNote({note: 'note'}, commits[0].hash, {cwd});
|
||||
await addNote({note: 'note2'}, commits[0].hash, {cwd});
|
||||
|
||||
t.is(await gitGetNote(commits[0].hash, {cwd}), '{"note":"note2"}');
|
||||
});
|
||||
|
||||
test('Unshallow and fetch repository with notes', async (t) => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First', 'Second'], {cwd});
|
||||
await gitAddNote(JSON.stringify({note: 'note'}), commits[0].hash, {cwd});
|
||||
// Create a shallow clone with only 1 commit
|
||||
cwd = await gitShallowClone(repositoryUrl);
|
||||
|
||||
// Verify the shallow clone doesn't contains the note
|
||||
await t.throwsAsync(gitGetNote(commits[0].hash, {cwd}));
|
||||
|
||||
await fetch(repositoryUrl, 'master', 'master', {cwd});
|
||||
await fetchNotes(repositoryUrl, {cwd});
|
||||
|
||||
// Verify the shallow clone contains the note
|
||||
t.is(await gitGetNote(commits[0].hash, {cwd}), '{"note":"note"}');
|
||||
});
|
||||
|
||||
test('Fetch all notes on a detached head repository', async (t) => {
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
|
||||
await gitCommits(['First'], {cwd});
|
||||
const [commit] = await gitCommits(['Second'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
await gitAddNote(JSON.stringify({note: 'note'}), commit.hash, {cwd});
|
||||
cwd = await gitDetachedHead(repositoryUrl, commit.hash);
|
||||
|
||||
await fetch(repositoryUrl, 'master', 'master', {cwd});
|
||||
await fetchNotes(repositoryUrl, {cwd});
|
||||
|
||||
t.is(await gitGetNote(commit.hash, {cwd}), '{"note":"note"}');
|
||||
});
|
||||
|
||||
+163
-45
@@ -1,12 +1,13 @@
|
||||
import tempy from 'tempy';
|
||||
import execa from 'execa';
|
||||
import fileUrl from 'file-url';
|
||||
import pReduce from 'p-reduce';
|
||||
import gitLogParser from 'git-log-parser';
|
||||
import getStream from 'get-stream';
|
||||
const tempy = require('tempy');
|
||||
const execa = require('execa');
|
||||
const fileUrl = require('file-url');
|
||||
const pEachSeries = require('p-each-series');
|
||||
const gitLogParser = require('git-log-parser');
|
||||
const getStream = require('get-stream');
|
||||
const {GIT_NOTE_REF} = require('../../lib/definitions/constants');
|
||||
|
||||
/**
|
||||
* Commit message informations.
|
||||
* Commit message information.
|
||||
*
|
||||
* @typedef {Object} Commit
|
||||
* @property {String} branch The commit branch.
|
||||
@@ -14,21 +15,34 @@ import getStream from 'get-stream';
|
||||
* @property {String} message The commit message.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Initialize git repository
|
||||
* If `withRemote` is `true`, creates a bare repository and initialize it.
|
||||
* If `withRemote` is `false`, creates a regular repository and initialize it.
|
||||
*
|
||||
* @param {Boolean} withRemote `true` to create a shallow clone of a bare repository.
|
||||
* @return {String} The path of the repository
|
||||
*/
|
||||
async function initGit(withRemote) {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
await execa('git', ['init', ...(withRemote ? ['--bare'] : [])], {cwd});
|
||||
const repositoryUrl = fileUrl(cwd);
|
||||
return {cwd, repositoryUrl};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a temporary git repository.
|
||||
* If `withRemote` is `true`, creates a bare repository, initialize it and create a shallow clone. Change the current working directory to the clone root.
|
||||
* If `withRemote` is `false`, creates a regular repository and initialize it. Change the current working directory to the repository root.
|
||||
* If `withRemote` is `true`, creates a shallow clone. Change the current working directory to the clone root.
|
||||
* If `withRemote` is `false`, just change the current working directory to the repository root.
|
||||
*
|
||||
*
|
||||
* @param {Boolean} withRemote `true` to create a shallow clone of a bare repository.
|
||||
* @param {String} [branch='master'] The branch to initialize.
|
||||
* @return {String} The path of the clone if `withRemote` is `true`, the path of the repository otherwise.
|
||||
*/
|
||||
export async function gitRepo(withRemote, branch = 'master') {
|
||||
let cwd = tempy.directory();
|
||||
|
||||
await execa('git', ['init', ...(withRemote ? ['--bare'] : [])], {cwd});
|
||||
|
||||
const repositoryUrl = fileUrl(cwd);
|
||||
async function gitRepo(withRemote, branch = 'master') {
|
||||
let {cwd, repositoryUrl} = await initGit(withRemote);
|
||||
if (withRemote) {
|
||||
await initBareRepo(repositoryUrl, branch);
|
||||
cwd = await gitShallowClone(repositoryUrl, branch);
|
||||
@@ -52,7 +66,7 @@ export async function gitRepo(withRemote, branch = 'master') {
|
||||
* @param {String} repositoryUrl The URL of the bare repository.
|
||||
* @param {String} [branch='master'] the branch to initialize.
|
||||
*/
|
||||
export async function initBareRepo(repositoryUrl, branch = 'master') {
|
||||
async function initBareRepo(repositoryUrl, branch = 'master') {
|
||||
const cwd = tempy.directory();
|
||||
await execa('git', ['clone', '--no-hardlinks', repositoryUrl, cwd], {cwd});
|
||||
await gitCheckout(branch, true, {cwd});
|
||||
@@ -68,11 +82,13 @@ export async function initBareRepo(repositoryUrl, branch = 'master') {
|
||||
*
|
||||
* @returns {Array<Commit>} The created commits, in reverse order (to match `git log` order).
|
||||
*/
|
||||
export async function gitCommits(messages, execaOpts) {
|
||||
await pReduce(messages, (_, message) =>
|
||||
execa.stdout('git', ['commit', '-m', message, '--allow-empty', '--no-gpg-sign'], execaOpts)
|
||||
async function gitCommits(messages, execaOptions) {
|
||||
await pEachSeries(
|
||||
messages,
|
||||
async (message) =>
|
||||
(await execa('git', ['commit', '-m', message, '--allow-empty', '--no-gpg-sign'], execaOptions)).stdout
|
||||
);
|
||||
return (await gitGetCommits(undefined, execaOpts)).slice(0, messages.length);
|
||||
return (await gitGetCommits(undefined, execaOptions)).slice(0, messages.length);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,11 +99,16 @@ export async function gitCommits(messages, execaOpts) {
|
||||
*
|
||||
* @return {Array<Object>} The list of parsed commits.
|
||||
*/
|
||||
export async function gitGetCommits(from, execaOpts) {
|
||||
async function gitGetCommits(from, execaOptions) {
|
||||
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
|
||||
return (await getStream.array(
|
||||
gitLogParser.parse({_: `${from ? from + '..' : ''}HEAD`}, {...execaOpts, env: {...process.env, ...execaOpts.env}})
|
||||
)).map(commit => {
|
||||
return (
|
||||
await getStream.array(
|
||||
gitLogParser.parse(
|
||||
{_: `${from ? from + '..' : ''}HEAD`},
|
||||
{...execaOptions, env: {...process.env, ...execaOptions.env}}
|
||||
)
|
||||
)
|
||||
).map((commit) => {
|
||||
commit.message = commit.message.trim();
|
||||
commit.gitTags = commit.gitTags.trim();
|
||||
return commit;
|
||||
@@ -98,11 +119,21 @@ export async function gitGetCommits(from, execaOpts) {
|
||||
* Checkout a branch on the current git repository.
|
||||
*
|
||||
* @param {String} branch Branch name.
|
||||
* @param {Boolean} create `true` to create the branch, `false` to checkout an existing branch.
|
||||
* @param {Boolean} create to create the branch, `false` to checkout an existing branch.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
export async function gitCheckout(branch, create = true, execaOpts) {
|
||||
await execa('git', create ? ['checkout', '-b', branch] : ['checkout', branch], execaOpts);
|
||||
async function gitCheckout(branch, create, execaOptions) {
|
||||
await execa('git', create ? ['checkout', '-b', branch] : ['checkout', branch], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch current git repository.
|
||||
*
|
||||
* @param {String} repositoryUrl The repository remote URL.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function gitFetch(repositoryUrl, execaOptions) {
|
||||
await execa('git', ['fetch', repositoryUrl], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -112,8 +143,8 @@ export async function gitCheckout(branch, create = true, execaOpts) {
|
||||
*
|
||||
* @return {String} The sha of the head commit in the current git repository.
|
||||
*/
|
||||
export function gitHead(execaOpts) {
|
||||
return execa.stdout('git', ['rev-parse', 'HEAD'], execaOpts);
|
||||
async function gitHead(execaOptions) {
|
||||
return (await execa('git', ['rev-parse', 'HEAD'], execaOptions)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -123,8 +154,8 @@ export function gitHead(execaOpts) {
|
||||
* @param {String} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
export async function gitTagVersion(tagName, sha, execaOpts) {
|
||||
await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName], execaOpts);
|
||||
async function gitTagVersion(tagName, sha, execaOptions) {
|
||||
await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -136,7 +167,7 @@ export async function gitTagVersion(tagName, sha, execaOpts) {
|
||||
* @param {Number} [depth=1] The number of commit to clone.
|
||||
* @return {String} The path of the cloned repository.
|
||||
*/
|
||||
export async function gitShallowClone(repositoryUrl, branch = 'master', depth = 1) {
|
||||
async function gitShallowClone(repositoryUrl, branch = 'master', depth = 1) {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, repositoryUrl, cwd], {
|
||||
@@ -152,7 +183,7 @@ export async function gitShallowClone(repositoryUrl, branch = 'master', depth =
|
||||
* @param {Number} head A commit sha of the remote repo that will become the detached head of the new one.
|
||||
* @return {String} The path of the new repository.
|
||||
*/
|
||||
export async function gitDetachedHead(repositoryUrl, head) {
|
||||
async function gitDetachedHead(repositoryUrl, head) {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
await execa('git', ['init'], {cwd});
|
||||
@@ -162,6 +193,17 @@ export async function gitDetachedHead(repositoryUrl, head) {
|
||||
return cwd;
|
||||
}
|
||||
|
||||
async function gitDetachedHeadFromBranch(repositoryUrl, branch, head) {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
await execa('git', ['init'], {cwd});
|
||||
await execa('git', ['remote', 'add', 'origin', repositoryUrl], {cwd});
|
||||
await execa('git', ['fetch', '--force', repositoryUrl, `${branch}:remotes/origin/${branch}`], {cwd});
|
||||
await execa('git', ['reset', '--hard', head], {cwd});
|
||||
await execa('git', ['checkout', '-q', '-B', branch], {cwd});
|
||||
return cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new Git configuration.
|
||||
*
|
||||
@@ -169,8 +211,8 @@ export async function gitDetachedHead(repositoryUrl, head) {
|
||||
* @param {String} value Config value.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
export async function gitAddConfig(name, value, execaOpts) {
|
||||
await execa('git', ['config', '--add', name, value], execaOpts);
|
||||
async function gitAddConfig(name, value, execaOptions) {
|
||||
await execa('git', ['config', '--add', name, value], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -181,8 +223,8 @@ export async function gitAddConfig(name, value, execaOpts) {
|
||||
*
|
||||
* @return {String} The sha of the commit associated with `tagName` on the local repository.
|
||||
*/
|
||||
export function gitTagHead(tagName, execaOpts) {
|
||||
return execa.stdout('git', ['rev-list', '-1', tagName], execaOpts);
|
||||
async function gitTagHead(tagName, execaOptions) {
|
||||
return (await execa('git', ['rev-list', '-1', tagName], execaOptions)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -194,11 +236,11 @@ export function gitTagHead(tagName, execaOpts) {
|
||||
*
|
||||
* @return {String} The sha of the commit associated with `tagName` on the remote repository.
|
||||
*/
|
||||
export async function gitRemoteTagHead(repositoryUrl, tagName, execaOpts) {
|
||||
return (await execa.stdout('git', ['ls-remote', '--tags', repositoryUrl, tagName], execaOpts))
|
||||
async function gitRemoteTagHead(repositoryUrl, tagName, execaOptions) {
|
||||
return (await execa('git', ['ls-remote', '--tags', repositoryUrl, tagName], execaOptions)).stdout
|
||||
.split('\n')
|
||||
.filter(tag => Boolean(tag))
|
||||
.map(tag => tag.match(/^(\S+)/)[1])[0];
|
||||
.filter((tag) => Boolean(tag))
|
||||
.map((tag) => tag.match(/^(?<tag>\S+)/)[1])[0];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,8 +251,8 @@ export async function gitRemoteTagHead(repositoryUrl, tagName, execaOpts) {
|
||||
*
|
||||
* @return {String} The tag associatedwith the sha in parameter or `null`.
|
||||
*/
|
||||
export function gitCommitTag(gitHead, execaOpts) {
|
||||
return execa.stdout('git', ['describe', '--tags', '--exact-match', gitHead], execaOpts);
|
||||
async function gitCommitTag(gitHead, execaOptions) {
|
||||
return (await execa('git', ['describe', '--tags', '--exact-match', gitHead], execaOptions)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -222,6 +264,82 @@ export function gitCommitTag(gitHead, execaOpts) {
|
||||
*
|
||||
* @throws {Error} if the push failed.
|
||||
*/
|
||||
export async function gitPush(repositoryUrl = 'origin', branch = 'master', execaOpts) {
|
||||
await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`], execaOpts);
|
||||
async function gitPush(repositoryUrl, branch, execaOptions) {
|
||||
await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a branch into the current one with `git merge`.
|
||||
*
|
||||
* @param {String} ref The ref to merge.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function merge(ref, execaOptions) {
|
||||
await execa('git', ['merge', '--no-ff', ref], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a branch into the current one with `git merge --ff`.
|
||||
*
|
||||
* @param {String} ref The ref to merge.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function mergeFf(ref, execaOptions) {
|
||||
await execa('git', ['merge', '--ff', ref], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge a branch into the current one with `git rebase`.
|
||||
*
|
||||
* @param {String} ref The ref to merge.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function rebase(ref, execaOptions) {
|
||||
await execa('git', ['rebase', ref], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a note to a Git reference.
|
||||
*
|
||||
* @param {String} note The note to add.
|
||||
* @param {String} ref The ref to add the note to.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function gitAddNote(note, ref, execaOptions) {
|
||||
await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'add', '-m', note, ref], execaOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the note associated with a Git reference.
|
||||
*
|
||||
* @param {String} ref The ref to get the note from.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function gitGetNote(ref, execaOptions) {
|
||||
return (await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'show', ref], execaOptions)).stdout;
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
initGit,
|
||||
gitRepo,
|
||||
initBareRepo,
|
||||
gitCommits,
|
||||
gitGetCommits,
|
||||
gitCheckout,
|
||||
gitFetch,
|
||||
gitHead,
|
||||
gitTagVersion,
|
||||
gitShallowClone,
|
||||
gitDetachedHead,
|
||||
gitDetachedHeadFromBranch,
|
||||
gitAddConfig,
|
||||
gitTagHead,
|
||||
gitRemoteTagHead,
|
||||
gitCommitTag,
|
||||
gitPush,
|
||||
merge,
|
||||
mergeFf,
|
||||
rebase,
|
||||
gitAddNote,
|
||||
gitGetNote,
|
||||
};
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import Docker from 'dockerode';
|
||||
import getStream from 'get-stream';
|
||||
import pRetry from 'p-retry';
|
||||
import {initBareRepo, gitShallowClone} from './git-utils';
|
||||
const Docker = require('dockerode');
|
||||
const getStream = require('get-stream');
|
||||
const pRetry = require('p-retry');
|
||||
const {initBareRepo, gitShallowClone} = require('./git-utils');
|
||||
|
||||
const IMAGE = 'pvdlg/docker-gitbox';
|
||||
const IMAGE = 'pvdlg/docker-gitbox:latest';
|
||||
const SERVER_PORT = 80;
|
||||
const HOST_PORT = 2080;
|
||||
const SERVER_HOST = 'localhost';
|
||||
@@ -69,4 +69,4 @@ async function createRepo(name, branch = 'master', description = `Repository ${n
|
||||
return {cwd, repositoryUrl, authUrl};
|
||||
}
|
||||
|
||||
export default {start, stop, gitCredential, createRepo};
|
||||
module.exports = {start, stop, gitCredential, createRepo};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import Docker from 'dockerode';
|
||||
import getStream from 'get-stream';
|
||||
import got from 'got';
|
||||
import pRetry from 'p-retry';
|
||||
import {mockServerClient} from 'mockserver-client';
|
||||
const Docker = require('dockerode');
|
||||
const getStream = require('get-stream');
|
||||
const got = require('got');
|
||||
const pRetry = require('p-retry');
|
||||
const {mockServerClient} = require('mockserver-client');
|
||||
|
||||
const IMAGE = 'jamesdbloom/mockserver:latest';
|
||||
const MOCK_SERVER_PORT = 1080;
|
||||
@@ -30,7 +30,7 @@ async function start() {
|
||||
minTimeout: 1000,
|
||||
factor: 2,
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (_) {
|
||||
throw new Error(`Couldn't start mock-server after 2 min`);
|
||||
}
|
||||
}
|
||||
@@ -100,4 +100,4 @@ function verify(expectation) {
|
||||
return client.verify(expectation);
|
||||
}
|
||||
|
||||
export default {start, stop, mock, verify, url};
|
||||
module.exports = {start, stop, mock, verify, url};
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import Docker from 'dockerode';
|
||||
import getStream from 'get-stream';
|
||||
import got from 'got';
|
||||
import delay from 'delay';
|
||||
import pRetry from 'p-retry';
|
||||
const Docker = require('dockerode');
|
||||
const getStream = require('get-stream');
|
||||
const got = require('got');
|
||||
const delay = require('delay');
|
||||
const pRetry = require('p-retry');
|
||||
|
||||
const IMAGE = 'semanticrelease/npm-registry-docker:latest';
|
||||
const SERVER_PORT = 15986;
|
||||
@@ -39,16 +39,16 @@ async function start() {
|
||||
minTimeout: 1000,
|
||||
factor: 2,
|
||||
});
|
||||
} catch (error) {
|
||||
} catch (_) {
|
||||
throw new Error(`Couldn't start npm-registry-docker after 2 min`);
|
||||
}
|
||||
|
||||
// Create user
|
||||
await got(`http://${SERVER_HOST}:${SERVER_PORT}/_users/org.couchdb.user:${NPM_USERNAME}`, {
|
||||
json: true,
|
||||
auth: `${COUCHDB_USER}:${COUCHDB_PASSWORD}`,
|
||||
username: COUCHDB_USER,
|
||||
password: COUCHDB_PASSWORD,
|
||||
method: 'PUT',
|
||||
body: {
|
||||
json: {
|
||||
_id: `org.couchdb.user:${NPM_USERNAME}`,
|
||||
name: NPM_USERNAME,
|
||||
roles: [],
|
||||
@@ -76,4 +76,4 @@ async function stop() {
|
||||
await container.remove();
|
||||
}
|
||||
|
||||
export default {start, stop, authEnv, url};
|
||||
module.exports = {start, stop, authEnv, url};
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
const execa = require('execa');
|
||||
|
||||
async function npmView(packageName, env) {
|
||||
return JSON.parse((await execa('npm', ['view', packageName, '--json'], {env})).stdout);
|
||||
}
|
||||
|
||||
module.exports = {npmView};
|
||||
+38
-12
@@ -1,9 +1,9 @@
|
||||
import test from 'ava';
|
||||
import {repeat} from 'lodash';
|
||||
import hideSensitive from '../lib/hide-sensitive';
|
||||
import {SECRET_REPLACEMENT, SECRET_MIN_SIZE} from '../lib/definitions/constants';
|
||||
const test = require('ava');
|
||||
const {repeat} = require('lodash');
|
||||
const hideSensitive = require('../lib/hide-sensitive');
|
||||
const {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('../lib/definitions/constants');
|
||||
|
||||
test('Replace multiple sensitive environment variable values', t => {
|
||||
test('Replace multiple sensitive environment variable values', (t) => {
|
||||
const env = {SOME_PASSWORD: 'password', SOME_TOKEN: 'secret'};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${env.SOME_PASSWORD}@host.com?token=${env.SOME_TOKEN}`),
|
||||
@@ -11,7 +11,7 @@ test('Replace multiple sensitive environment variable values', t => {
|
||||
);
|
||||
});
|
||||
|
||||
test('Replace multiple occurences of sensitive environment variable values', t => {
|
||||
test('Replace multiple occurences of sensitive environment variable values', (t) => {
|
||||
const env = {secretKey: 'secret'};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${env.secretKey}@host.com?token=${env.secretKey}`),
|
||||
@@ -19,7 +19,20 @@ test('Replace multiple occurences of sensitive environment variable values', t =
|
||||
);
|
||||
});
|
||||
|
||||
test('Escape regexp special characters', t => {
|
||||
test('Replace sensitive environment variable matching specific regex for "private"', (t) => {
|
||||
const env = {privateKey: 'secret', GOPRIVATE: 'host.com'};
|
||||
t.is(hideSensitive(env)(`https://host.com?token=${env.privateKey}`), `https://host.com?token=${SECRET_REPLACEMENT}`);
|
||||
});
|
||||
|
||||
test('Replace url-encoded environment variable', (t) => {
|
||||
const env = {privateKey: 'secret '};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://host.com?token=${encodeURI(env.privateKey)}`),
|
||||
`https://host.com?token=${SECRET_REPLACEMENT}`
|
||||
);
|
||||
});
|
||||
|
||||
test('Escape regexp special characters', (t) => {
|
||||
const env = {SOME_CREDENTIALS: 'p$^{.+}\\w[a-z]o.*rd'};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${env.SOME_CREDENTIALS}@host.com`),
|
||||
@@ -27,15 +40,23 @@ test('Escape regexp special characters', t => {
|
||||
);
|
||||
});
|
||||
|
||||
test('Accept "undefined" input', t => {
|
||||
test('Escape regexp special characters in url-encoded environment variable', (t) => {
|
||||
const env = {SOME_PASSWORD: 'secret password p$^{.+}\\w[a-z]o.*rd)('};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${encodeURI(env.SOME_PASSWORD)}@host.com`),
|
||||
`https://user:${SECRET_REPLACEMENT}@host.com`
|
||||
);
|
||||
});
|
||||
|
||||
test('Accept "undefined" input', (t) => {
|
||||
t.is(hideSensitive({})(), undefined);
|
||||
});
|
||||
|
||||
test('Return same string if no environment variable has to be replaced', t => {
|
||||
test('Return same string if no environment variable has to be replaced', (t) => {
|
||||
t.is(hideSensitive({})('test'), 'test');
|
||||
});
|
||||
|
||||
test('Exclude empty environment variables from the regexp', t => {
|
||||
test('Exclude empty environment variables from the regexp', (t) => {
|
||||
const env = {SOME_PASSWORD: 'password', SOME_TOKEN: ''};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${env.SOME_PASSWORD}@host.com?token=`),
|
||||
@@ -43,11 +64,16 @@ test('Exclude empty environment variables from the regexp', t => {
|
||||
);
|
||||
});
|
||||
|
||||
test('Exclude empty environment variables from the regexp if there is only empty ones', t => {
|
||||
test('Exclude empty environment variables from the regexp if there is only empty ones', (t) => {
|
||||
t.is(hideSensitive({SOME_PASSWORD: '', SOME_TOKEN: ' \n '})(`https://host.com?token=`), 'https://host.com?token=');
|
||||
});
|
||||
|
||||
test('Exclude environment variables with value shorter than SECRET_MIN_SIZE from the regexp', t => {
|
||||
test('Exclude nonsensitive GOPRIVATE environment variable for Golang projects from the regexp', (t) => {
|
||||
const env = {GOPRIVATE: 'host.com'};
|
||||
t.is(hideSensitive(env)(`https://host.com?token=`), 'https://host.com?token=');
|
||||
});
|
||||
|
||||
test('Exclude environment variables with value shorter than SECRET_MIN_SIZE from the regexp', (t) => {
|
||||
const SHORT_TOKEN = repeat('a', SECRET_MIN_SIZE - 1);
|
||||
const LONG_TOKEN = repeat('b', SECRET_MIN_SIZE);
|
||||
const env = {SHORT_TOKEN, LONG_TOKEN};
|
||||
|
||||
+927
-160
File diff suppressed because it is too large
Load Diff
+184
-90
@@ -1,15 +1,28 @@
|
||||
import path from 'path';
|
||||
import proxyquire from 'proxyquire';
|
||||
import test from 'ava';
|
||||
import {escapeRegExp} from 'lodash';
|
||||
import {writeJson, readJson} from 'fs-extra';
|
||||
import execa from 'execa';
|
||||
import {WritableStreamBuffer} from 'stream-buffers';
|
||||
import {SECRET_REPLACEMENT} from '../lib/definitions/constants';
|
||||
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';
|
||||
const path = require('path');
|
||||
const test = require('ava');
|
||||
const proxyquire = require('proxyquire');
|
||||
const {escapeRegExp} = require('lodash');
|
||||
const {writeJson, readJson} = require('fs-extra');
|
||||
const execa = require('execa');
|
||||
const {WritableStreamBuffer} = require('stream-buffers');
|
||||
const delay = require('delay');
|
||||
const getAuthUrl = require('../lib/get-git-auth-url');
|
||||
const {SECRET_REPLACEMENT} = require('../lib/definitions/constants');
|
||||
const {
|
||||
gitHead,
|
||||
gitTagHead,
|
||||
gitRepo,
|
||||
gitCommits,
|
||||
gitRemoteTagHead,
|
||||
gitPush,
|
||||
gitCheckout,
|
||||
merge,
|
||||
gitGetNote,
|
||||
} = require('./helpers/git-utils');
|
||||
const {npmView} = require('./helpers/npm-utils');
|
||||
const gitbox = require('./helpers/gitbox');
|
||||
const mockServer = require('./helpers/mockserver');
|
||||
const npmRegistry = require('./helpers/npm-registry');
|
||||
|
||||
/* eslint camelcase: ["error", {properties: "never"}] */
|
||||
|
||||
@@ -46,7 +59,7 @@ test.after.always(async () => {
|
||||
await Promise.all([gitbox.stop(), npmRegistry.stop(), mockServer.stop()]);
|
||||
});
|
||||
|
||||
test('Release patch, minor and major versions', async t => {
|
||||
test('Release patch, minor and major versions', async (t) => {
|
||||
const packageName = 'test-release';
|
||||
const owner = 'git';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
@@ -58,7 +71,7 @@ test('Release patch, minor and major versions', async t => {
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: repositoryUrl},
|
||||
publishConfig: {registry: npmRegistry.url},
|
||||
release: {success: false, fail: false},
|
||||
release: {branches: ['master', 'next'], success: false, fail: false},
|
||||
});
|
||||
// Create a npm-shrinkwrap.json file
|
||||
await execa('npm', ['shrinkwrap'], {env: testEnv, cwd});
|
||||
@@ -72,9 +85,9 @@ test('Release patch, minor and major versions', async t => {
|
||||
t.log('Commit a chore');
|
||||
await gitCommits(['chore: Init repository'], {cwd});
|
||||
t.log('$ semantic-release');
|
||||
let {stdout, code} = await execa(cli, [], {env, cwd});
|
||||
let {stdout, exitCode} = await execa(cli, [], {env, cwd});
|
||||
t.regex(stdout, /There are no relevant changes, so no new version is released/);
|
||||
t.is(code, 0);
|
||||
t.is(exitCode, 0);
|
||||
|
||||
/* Initial release */
|
||||
let version = '1.0.0';
|
||||
@@ -86,7 +99,7 @@ test('Release patch, minor and major versions', async t => {
|
||||
let createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
body: {tag_name: `v${version}`, name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
@@ -95,25 +108,24 @@ test('Release patch, minor and major versions', async t => {
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit'], {cwd});
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env, cwd}));
|
||||
({stdout, exitCode} = await execa(cli, [], {env, cwd}));
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
t.is(exitCode, 0);
|
||||
|
||||
// Verify package.json and npm-shrinkwrap.json have been updated
|
||||
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, version);
|
||||
t.is((await readJson(path.resolve(cwd, 'npm-shrinkwrap.json'))).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
|
||||
);
|
||||
let {
|
||||
'dist-tags': {latest: releasedVersion},
|
||||
} = await npmView(packageName, testEnv);
|
||||
let head = await gitHead({cwd});
|
||||
t.is(releasedVersion, version);
|
||||
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}`);
|
||||
t.log(`+ released ${releasedVersion}`);
|
||||
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
@@ -128,7 +140,7 @@ test('Release patch, minor and major versions', async t => {
|
||||
createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
body: {tag_name: `v${version}`, name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
@@ -137,25 +149,24 @@ test('Release patch, minor and major versions', async t => {
|
||||
t.log('Commit a fix');
|
||||
await gitCommits(['fix: bar'], {cwd});
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env, cwd}));
|
||||
({stdout, exitCode} = await execa(cli, [], {env, cwd}));
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
t.is(exitCode, 0);
|
||||
|
||||
// Verify package.json and npm-shrinkwrap.json have been updated
|
||||
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, version);
|
||||
t.is((await readJson(path.resolve(cwd, 'npm-shrinkwrap.json'))).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
|
||||
);
|
||||
({
|
||||
'dist-tags': {latest: releasedVersion},
|
||||
} = await npmView(packageName, testEnv));
|
||||
head = await gitHead({cwd});
|
||||
t.is(releasedVersion, version);
|
||||
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}`);
|
||||
t.log(`+ released ${releasedVersion}`);
|
||||
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
@@ -170,7 +181,7 @@ test('Release patch, minor and major versions', async t => {
|
||||
createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
body: {tag_name: `v${version}`, name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
@@ -179,30 +190,29 @@ test('Release patch, minor and major versions', async t => {
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: baz'], {cwd});
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env, cwd}));
|
||||
({stdout, exitCode} = await execa(cli, [], {env, cwd}));
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
t.is(exitCode, 0);
|
||||
|
||||
// Verify package.json and npm-shrinkwrap.json have been updated
|
||||
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, version);
|
||||
t.is((await readJson(path.resolve(cwd, 'npm-shrinkwrap.json'))).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
|
||||
);
|
||||
({
|
||||
'dist-tags': {latest: releasedVersion},
|
||||
} = await npmView(packageName, testEnv));
|
||||
head = await gitHead({cwd});
|
||||
t.is(releasedVersion, version);
|
||||
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}`);
|
||||
t.log(`+ released ${releasedVersion}`);
|
||||
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
|
||||
/* Major release */
|
||||
/* Major release on next */
|
||||
version = '2.0.0';
|
||||
verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
@@ -212,40 +222,90 @@ test('Release patch, minor and major versions', async t => {
|
||||
createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
body: {tag_name: `v${version}`, name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
);
|
||||
|
||||
t.log('Commit a breaking change');
|
||||
t.log('Commit a breaking change on next');
|
||||
await gitCheckout('next', true, {cwd});
|
||||
await gitPush('origin', 'next', {cwd});
|
||||
await gitCommits(['feat: foo\n\n BREAKING CHANGE: bar'], {cwd});
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env, cwd}));
|
||||
({stdout, exitCode} = await execa(cli, [], {env: {...env, TRAVIS_BRANCH: 'next'}, cwd}));
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
t.is(exitCode, 0);
|
||||
|
||||
// Verify package.json and npm-shrinkwrap.json have been updated
|
||||
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, version);
|
||||
t.is((await readJson(path.resolve(cwd, 'npm-shrinkwrap.json'))).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
|
||||
);
|
||||
({
|
||||
'dist-tags': {next: releasedVersion},
|
||||
} = await npmView(packageName, testEnv));
|
||||
head = await gitHead({cwd});
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, head);
|
||||
t.is(await gitGetNote(`v${version}`, {cwd}), '{"channels":["next"]}');
|
||||
t.is(await gitTagHead(`v${version}`, {cwd}), head);
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
|
||||
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
|
||||
t.log(`+ released ${releasedVersion} on @next`);
|
||||
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
|
||||
/* Merge next into master */
|
||||
version = '2.0.0';
|
||||
const releaseId = 1;
|
||||
verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
const getReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases/tags/v2.0.0`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {id: releaseId}, method: 'GET'}
|
||||
);
|
||||
const updateReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases/${releaseId}`,
|
||||
{
|
||||
body: {name: `v${version}`, prerelease: false},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}, method: 'PATCH'}
|
||||
);
|
||||
|
||||
t.log('Merge next into master');
|
||||
await gitCheckout('master', false, {cwd});
|
||||
await merge('next', {cwd});
|
||||
await gitPush('origin', 'master', {cwd});
|
||||
t.log('$ semantic-release');
|
||||
({stdout, exitCode} = await execa(cli, [], {env, cwd}));
|
||||
t.regex(stdout, new RegExp(`Updated GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Adding version ${version} to npm registry on dist-tag latest`));
|
||||
t.is(exitCode, 0);
|
||||
|
||||
// Wait for 3s as the change of dist-tag takes time to be reflected in the registry
|
||||
await delay(3000);
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
({
|
||||
'dist-tags': {latest: releasedVersion},
|
||||
} = await npmView(packageName, testEnv));
|
||||
t.is(releasedVersion, version);
|
||||
t.is(await gitGetNote(`v${version}`, {cwd}), '{"channels":["next",null]}');
|
||||
t.is(await gitTagHead(`v${version}`, {cwd}), await gitTagHead(`v${version}`, {cwd}));
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), await gitRemoteTagHead(authUrl, `v${version}`, {cwd}));
|
||||
t.log(`+ added ${releasedVersion}`);
|
||||
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(getReleaseMock);
|
||||
await mockServer.verify(updateReleaseMock);
|
||||
});
|
||||
|
||||
test('Exit with 1 if a plugin is not found', async t => {
|
||||
test('Exit with 1 if a plugin is not found', async (t) => {
|
||||
const packageName = 'test-plugin-not-found';
|
||||
const owner = 'test-repo';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
@@ -258,12 +318,12 @@ 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.throwsAsync(execa(cli, [], {env, cwd}));
|
||||
t.is(code, 1);
|
||||
const {exitCode, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
|
||||
t.is(exitCode, 1);
|
||||
t.regex(stderr, /Cannot find module/);
|
||||
});
|
||||
|
||||
test('Exit with 1 if a shareable config is not found', async t => {
|
||||
test('Exit with 1 if a shareable config is not found', async (t) => {
|
||||
const packageName = 'test-config-not-found';
|
||||
const owner = 'test-repo';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
@@ -276,12 +336,12 @@ 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.throwsAsync(execa(cli, [], {env, cwd}));
|
||||
t.is(code, 1);
|
||||
const {exitCode, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
|
||||
t.is(exitCode, 1);
|
||||
t.regex(stderr, /Cannot find module/);
|
||||
});
|
||||
|
||||
test('Exit with 1 if a shareable config reference a not found plugin', async t => {
|
||||
test('Exit with 1 if a shareable config reference a not found plugin', async (t) => {
|
||||
const packageName = 'test-config-ref-not-found';
|
||||
const owner = 'test-repo';
|
||||
const shareable = {analyzeCommits: 'non-existing-path'};
|
||||
@@ -297,12 +357,12 @@ 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.throwsAsync(execa(cli, [], {env, cwd}));
|
||||
t.is(code, 1);
|
||||
const {exitCode, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
|
||||
t.is(exitCode, 1);
|
||||
t.regex(stderr, /Cannot find module/);
|
||||
});
|
||||
|
||||
test('Dry-run', async t => {
|
||||
test('Dry-run', async (t) => {
|
||||
const packageName = 'test-dry-run';
|
||||
const owner = 'git';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
@@ -327,18 +387,18 @@ test('Dry-run', async t => {
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit'], {cwd});
|
||||
t.log('$ semantic-release -d');
|
||||
const {stdout, code} = await execa(cli, ['-d'], {env, cwd});
|
||||
const {stdout, exitCode} = await execa(cli, ['-d'], {env, cwd});
|
||||
t.regex(stdout, new RegExp(`There is no previous release, the next release version is ${version}`));
|
||||
t.regex(stdout, new RegExp(`Release note for version ${version}`));
|
||||
t.regex(stdout, /Initial commit/);
|
||||
t.is(code, 0);
|
||||
t.is(exitCode, 0);
|
||||
|
||||
// Verify package.json and has not been modified
|
||||
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, '0.0.0-dev');
|
||||
await mockServer.verify(verifyMock);
|
||||
});
|
||||
|
||||
test('Allow local releases with "noCi" option', async t => {
|
||||
test('Allow local releases with "noCi" option', async (t) => {
|
||||
const envNoCi = {...env};
|
||||
delete envNoCi.TRAVIS;
|
||||
delete envNoCi.CI;
|
||||
@@ -366,7 +426,7 @@ test('Allow local releases with "noCi" option', async t => {
|
||||
const createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
body: {tag_name: `v${version}`, name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
@@ -375,18 +435,16 @@ test('Allow local releases with "noCi" option', async t => {
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit'], {cwd});
|
||||
t.log('$ semantic-release --no-ci');
|
||||
const {stdout, code} = await execa(cli, ['--no-ci'], {env: envNoCi, cwd});
|
||||
const {stdout, exitCode} = await execa(cli, ['--no-ci'], {env: envNoCi, cwd});
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
t.is(exitCode, 0);
|
||||
|
||||
// Verify package.json and has been updated
|
||||
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
|
||||
);
|
||||
const {version: releasedVersion, gitHead: releasedGitHead} = await npmView(packageName, testEnv);
|
||||
|
||||
const head = await gitHead({cwd});
|
||||
t.is(releasedVersion, version);
|
||||
@@ -399,7 +457,7 @@ test('Allow local releases with "noCi" option', async t => {
|
||||
await mockServer.verify(createReleaseMock);
|
||||
});
|
||||
|
||||
test('Pass options via CLI arguments', async t => {
|
||||
test('Pass options via CLI arguments', async (t) => {
|
||||
const packageName = 'test-cli';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
@@ -417,7 +475,7 @@ test('Pass options via CLI arguments', async t => {
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit'], {cwd});
|
||||
t.log('$ semantic-release');
|
||||
const {stdout, code} = await execa(
|
||||
const {stdout, exitCode} = await execa(
|
||||
cli,
|
||||
[
|
||||
'--verify-conditions',
|
||||
@@ -433,15 +491,13 @@ test('Pass options via CLI arguments', async t => {
|
||||
{env, cwd}
|
||||
);
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
t.is(exitCode, 0);
|
||||
|
||||
// Verify package.json and has been updated
|
||||
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
|
||||
);
|
||||
const {version: releasedVersion, gitHead: releasedGitHead} = await npmView(packageName, testEnv);
|
||||
const head = await gitHead({cwd});
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, head);
|
||||
@@ -450,7 +506,7 @@ test('Pass options via CLI arguments', async t => {
|
||||
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
|
||||
});
|
||||
|
||||
test('Run via JS API', async t => {
|
||||
test('Run via JS API', async (t) => {
|
||||
const semanticRelease = requireNoCache('..', {
|
||||
'./lib/logger': {log: () => {}, error: () => {}, stdout: () => {}},
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
@@ -482,7 +538,7 @@ test('Run via JS API', async t => {
|
||||
const createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
body: {tag_name: `v${version}`, name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
@@ -497,9 +553,7 @@ test('Run via JS API', async t => {
|
||||
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
|
||||
);
|
||||
const {version: releasedVersion, gitHead: releasedGitHead} = await npmView(packageName, testEnv);
|
||||
const head = await gitHead({cwd});
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, head);
|
||||
@@ -511,7 +565,7 @@ test('Run via JS API', async t => {
|
||||
await mockServer.verify(createReleaseMock);
|
||||
});
|
||||
|
||||
test('Log unexpected errors from plugins and exit with 1', async t => {
|
||||
test('Log unexpected errors from plugins and exit with 1', async (t) => {
|
||||
const packageName = 'test-unexpected-error';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
@@ -528,17 +582,17 @@ test('Log unexpected errors from plugins and exit with 1', async t => {
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit'], {cwd});
|
||||
t.log('$ semantic-release');
|
||||
const {stderr, code} = await execa(cli, [], {env, cwd, reject: false});
|
||||
const {stderr, exitCode} = await execa(cli, [], {env, cwd, reject: false});
|
||||
// Verify the type and message are logged
|
||||
t.regex(stderr, /Error: a/);
|
||||
// Verify the the stacktrace is logged
|
||||
t.regex(stderr, new RegExp(pluginError));
|
||||
// Verify the Error properties are logged
|
||||
t.regex(stderr, /errorProperty: 'errorProperty'/);
|
||||
t.is(code, 1);
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test('Log errors inheriting SemanticReleaseError and exit with 1', async t => {
|
||||
test('Log errors inheriting SemanticReleaseError and exit with 1', async (t) => {
|
||||
const packageName = 'test-inherited-error';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
@@ -555,13 +609,13 @@ test('Log errors inheriting SemanticReleaseError and exit with 1', async t => {
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit'], {cwd});
|
||||
t.log('$ semantic-release');
|
||||
const {stderr, code} = await execa(cli, [], {env, cwd, reject: false});
|
||||
const {stderr, exitCode} = await execa(cli, [], {env, cwd, reject: false});
|
||||
// Verify the type and message are logged
|
||||
t.regex(stderr, /EINHERITED Inherited error/);
|
||||
t.is(code, 1);
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test('Exit with 1 if missing permission to push to the remote repository', async t => {
|
||||
test('Exit with 1 if missing permission to push to the remote repository', async (t) => {
|
||||
const packageName = 'unauthorized';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository');
|
||||
@@ -573,17 +627,17 @@ test('Exit with 1 if missing permission to push to the remote repository', async
|
||||
await gitCommits(['feat: Initial commit'], {cwd});
|
||||
await gitPush('origin', 'master', {cwd});
|
||||
t.log('$ semantic-release');
|
||||
const {stderr, code} = await execa(
|
||||
const {stderr, exitCode} = await execa(
|
||||
cli,
|
||||
['--repository-url', 'http://user:wrong_pass@localhost:2080/git/unauthorized.git'],
|
||||
{env: {...env, GH_TOKEN: 'user:wrong_pass'}, cwd, reject: false}
|
||||
);
|
||||
// Verify the type and message are logged
|
||||
t.regex(stderr, /EGITNOPERMISSION/);
|
||||
t.is(code, 1);
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test('Hide sensitive environment variable values from the logs', async t => {
|
||||
test('Hide sensitive environment variable values from the logs', async (t) => {
|
||||
const packageName = 'log-secret';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository');
|
||||
@@ -603,3 +657,43 @@ test('Hide sensitive environment variable values from the logs', async t => {
|
||||
t.regex(stderr, new RegExp(`Error: Console token ${escapeRegExp(SECRET_REPLACEMENT)}`));
|
||||
t.regex(stderr, new RegExp(`Throw error: Exposing ${escapeRegExp(SECRET_REPLACEMENT)}`));
|
||||
});
|
||||
|
||||
test('Use the valid git credentials when multiple are provided', async (t) => {
|
||||
const {cwd, authUrl} = await gitbox.createRepo('test-auth');
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {
|
||||
GITHUB_TOKEN: 'dummy',
|
||||
GITLAB_TOKEN: 'trash',
|
||||
BB_TOKEN_BASIC_AUTH: gitbox.gitCredential,
|
||||
GIT_ASKPASS: 'echo',
|
||||
GIT_TERMINAL_PROMPT: 0,
|
||||
},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: 'http://toto@localhost:2080/git/test-auth.git'},
|
||||
}),
|
||||
authUrl
|
||||
);
|
||||
});
|
||||
|
||||
test('Use the repository URL as is if none of the given git credentials are valid', async (t) => {
|
||||
const {cwd} = await gitbox.createRepo('test-invalid-auth');
|
||||
const dummyUrl = 'http://toto@localhost:2080/git/test-auth.git';
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {
|
||||
GITHUB_TOKEN: 'dummy',
|
||||
GITLAB_TOKEN: 'trash',
|
||||
GIT_ASKPASS: 'echo',
|
||||
GIT_TERMINAL_PROMPT: 0,
|
||||
},
|
||||
branch: {name: 'master'},
|
||||
options: {repositoryUrl: dummyUrl},
|
||||
}),
|
||||
dummyUrl
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import test from 'ava';
|
||||
import {noop} from 'lodash';
|
||||
import {stub} from 'sinon';
|
||||
import normalize from '../../lib/plugins/normalize';
|
||||
const test = require('ava');
|
||||
const {noop} = require('lodash');
|
||||
const {stub} = require('sinon');
|
||||
const normalize = require('../../lib/plugins/normalize');
|
||||
|
||||
const cwd = process.cwd();
|
||||
|
||||
test.beforeEach(t => {
|
||||
test.beforeEach((t) => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.error = stub();
|
||||
@@ -19,7 +19,7 @@ test.beforeEach(t => {
|
||||
};
|
||||
});
|
||||
|
||||
test('Normalize and load plugin from string', t => {
|
||||
test('Normalize and load plugin from string', (t) => {
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, logger: t.context.logger},
|
||||
'verifyConditions',
|
||||
@@ -32,7 +32,7 @@ test('Normalize and load plugin from string', t => {
|
||||
t.deepEqual(t.context.success.args[0], ['Loaded plugin "verifyConditions" from "./test/fixtures/plugin-noop"']);
|
||||
});
|
||||
|
||||
test('Normalize and load plugin from object', t => {
|
||||
test('Normalize and load plugin from object', (t) => {
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, logger: t.context.logger},
|
||||
'publish',
|
||||
@@ -45,7 +45,7 @@ test('Normalize and load plugin from object', t => {
|
||||
t.deepEqual(t.context.success.args[0], ['Loaded plugin "publish" from "./test/fixtures/plugin-noop"']);
|
||||
});
|
||||
|
||||
test('Normalize and load plugin from a base file path', t => {
|
||||
test('Normalize and load plugin from a base file path', (t) => {
|
||||
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, 'verifyConditions', './plugin-noop', {
|
||||
'./plugin-noop': './test/fixtures',
|
||||
});
|
||||
@@ -57,7 +57,7 @@ test('Normalize and load plugin from a base file path', t => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('Wrap plugin in a function that add the "pluginName" to the error"', async t => {
|
||||
test('Wrap plugin in a function that add the "pluginName" to the error"', async (t) => {
|
||||
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, 'verifyConditions', './plugin-error', {
|
||||
'./plugin-error': './test/fixtures',
|
||||
});
|
||||
@@ -67,7 +67,7 @@ test('Wrap plugin in a function that add the "pluginName" to the error"', async
|
||||
t.is(error.pluginName, './plugin-error');
|
||||
});
|
||||
|
||||
test('Wrap plugin in a function that add the "pluginName" to multiple errors"', async t => {
|
||||
test('Wrap plugin in a function that add the "pluginName" to multiple errors"', async (t) => {
|
||||
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, 'verifyConditions', './plugin-errors', {
|
||||
'./plugin-errors': './test/fixtures',
|
||||
});
|
||||
@@ -78,7 +78,7 @@ test('Wrap plugin in a function that add the "pluginName" to multiple errors"',
|
||||
}
|
||||
});
|
||||
|
||||
test('Normalize and load plugin from function', t => {
|
||||
test('Normalize and load plugin from function', (t) => {
|
||||
const pluginFunction = () => {};
|
||||
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, '', pluginFunction, {});
|
||||
|
||||
@@ -86,7 +86,7 @@ test('Normalize and load plugin from function', t => {
|
||||
t.is(typeof plugin, 'function');
|
||||
});
|
||||
|
||||
test('Normalize and load plugin that retuns multiple functions', t => {
|
||||
test('Normalize and load plugin that retuns multiple functions', (t) => {
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, logger: t.context.logger},
|
||||
'verifyConditions',
|
||||
@@ -98,7 +98,7 @@ test('Normalize and load plugin that retuns multiple functions', t => {
|
||||
t.deepEqual(t.context.success.args[0], ['Loaded plugin "verifyConditions" from "./test/fixtures/multi-plugin"']);
|
||||
});
|
||||
|
||||
test('Wrap "analyzeCommits" plugin in a function that validate the output of the plugin', async t => {
|
||||
test('Wrap "analyzeCommits" plugin in a function that validate the output of the plugin', async (t) => {
|
||||
const analyzeCommits = stub().resolves(2);
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, stderr: t.context.stderr, logger: t.context.logger},
|
||||
@@ -116,7 +116,7 @@ test('Wrap "analyzeCommits" plugin in a function that validate the output of the
|
||||
t.regex(error.details, /2/);
|
||||
});
|
||||
|
||||
test('Wrap "generateNotes" plugin in a function that validate the output of the plugin', async t => {
|
||||
test('Wrap "generateNotes" plugin in a function that validate the output of the plugin', async (t) => {
|
||||
const generateNotes = stub().resolves(2);
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, stderr: t.context.stderr, logger: t.context.logger},
|
||||
@@ -134,7 +134,7 @@ test('Wrap "generateNotes" plugin in a function that validate the output of the
|
||||
t.regex(error.details, /2/);
|
||||
});
|
||||
|
||||
test('Wrap "publish" plugin in a function that validate the output of the plugin', async t => {
|
||||
test('Wrap "publish" plugin in a function that validate the output of the plugin', async (t) => {
|
||||
const publish = stub().resolves(2);
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, stderr: t.context.stderr, logger: t.context.logger},
|
||||
@@ -152,7 +152,25 @@ test('Wrap "publish" plugin in a function that validate the output of the plugin
|
||||
t.regex(error.details, /2/);
|
||||
});
|
||||
|
||||
test('Plugin is called with "pluginConfig" (with object definition) and input', async t => {
|
||||
test('Wrap "addChannel" plugin in a function that validate the output of the plugin', async (t) => {
|
||||
const addChannel = stub().resolves(2);
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, stderr: t.context.stderr, logger: t.context.logger},
|
||||
'addChannel',
|
||||
addChannel,
|
||||
{}
|
||||
);
|
||||
|
||||
const error = await t.throwsAsync(plugin({options: {}}));
|
||||
|
||||
t.is(error.code, 'EADDCHANNELOUTPUT');
|
||||
t.is(error.name, 'SemanticReleaseError');
|
||||
t.truthy(error.message);
|
||||
t.truthy(error.details);
|
||||
t.regex(error.details, /2/);
|
||||
});
|
||||
|
||||
test('Plugin is called with "pluginConfig" (with object definition) and input', async (t) => {
|
||||
const pluginFunction = stub().resolves();
|
||||
const pluginConf = {path: pluginFunction, conf: 'confValue'};
|
||||
const options = {global: 'globalValue'};
|
||||
@@ -167,7 +185,7 @@ test('Plugin is called with "pluginConfig" (with object definition) and input',
|
||||
);
|
||||
});
|
||||
|
||||
test('Plugin is called with "pluginConfig" (with array definition) and input', async t => {
|
||||
test('Plugin is called with "pluginConfig" (with array definition) and input', async (t) => {
|
||||
const pluginFunction = stub().resolves();
|
||||
const pluginConf = [pluginFunction, {conf: 'confValue'}];
|
||||
const options = {global: 'globalValue'};
|
||||
@@ -182,8 +200,8 @@ test('Plugin is called with "pluginConfig" (with array definition) and input', a
|
||||
);
|
||||
});
|
||||
|
||||
test('Prevent plugins to modify "pluginConfig"', async t => {
|
||||
const pluginFunction = stub().callsFake(pluginConfig => {
|
||||
test('Prevent plugins to modify "pluginConfig"', async (t) => {
|
||||
const pluginFunction = stub().callsFake((pluginConfig) => {
|
||||
pluginConfig.conf.subConf = 'otherConf';
|
||||
});
|
||||
const pluginConf = {path: pluginFunction, conf: {subConf: 'originalConf'}};
|
||||
@@ -195,7 +213,7 @@ test('Prevent plugins to modify "pluginConfig"', async t => {
|
||||
t.is(options.globalConf.globalSubConf, 'originalGlobalConf');
|
||||
});
|
||||
|
||||
test('Prevent plugins to modify its input', async t => {
|
||||
test('Prevent plugins to modify its input', async (t) => {
|
||||
const pluginFunction = stub().callsFake((pluginConfig, options) => {
|
||||
options.param.subParam = 'otherParam';
|
||||
});
|
||||
@@ -206,13 +224,13 @@ test('Prevent plugins to modify its input', async t => {
|
||||
t.is(input.param.subParam, 'originalSubParam');
|
||||
});
|
||||
|
||||
test('Return noop if the plugin is not defined', t => {
|
||||
test('Return noop if the plugin is not defined', (t) => {
|
||||
const plugin = normalize({cwd, options: {}, logger: t.context.logger});
|
||||
|
||||
t.is(plugin, noop);
|
||||
});
|
||||
|
||||
test('Always pass a defined "pluginConfig" for plugin defined with string', async t => {
|
||||
test('Always pass a defined "pluginConfig" for plugin defined with string', async (t) => {
|
||||
// Call the normalize function with the path of a plugin that returns its config
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, logger: t.context.logger},
|
||||
@@ -225,7 +243,7 @@ test('Always pass a defined "pluginConfig" for plugin defined with string', asyn
|
||||
t.deepEqual(pluginResult.pluginConfig, {});
|
||||
});
|
||||
|
||||
test('Always pass a defined "pluginConfig" for plugin defined with path', async t => {
|
||||
test('Always pass a defined "pluginConfig" for plugin defined with path', async (t) => {
|
||||
// Call the normalize function with the path of a plugin that returns its config
|
||||
const plugin = normalize(
|
||||
{cwd, options: {}, logger: t.context.logger},
|
||||
@@ -238,7 +256,7 @@ test('Always pass a defined "pluginConfig" for plugin defined with path', async
|
||||
t.deepEqual(pluginResult.pluginConfig, {});
|
||||
});
|
||||
|
||||
test('Throws an error if the plugin return an object without the expected plugin function', t => {
|
||||
test('Throws an error if the plugin return an object without the expected plugin function', (t) => {
|
||||
const error = t.throws(() =>
|
||||
normalize({cwd, options: {}, logger: t.context.logger}, 'inexistantPlugin', './test/fixtures/multi-plugin', {})
|
||||
);
|
||||
@@ -249,12 +267,10 @@ test('Throws an error if the plugin return an object without the expected plugin
|
||||
t.truthy(error.details);
|
||||
});
|
||||
|
||||
test('Throws an error if the plugin is not found', t => {
|
||||
const error = t.throws(
|
||||
() => normalize({cwd, options: {}, logger: t.context.logger}, 'inexistantPlugin', 'non-existing-path', {}),
|
||||
Error
|
||||
);
|
||||
|
||||
t.is(error.message, "Cannot find module 'non-existing-path'");
|
||||
t.is(error.code, 'MODULE_NOT_FOUND');
|
||||
test('Throws an error if the plugin is not found', (t) => {
|
||||
t.throws(() => normalize({cwd, options: {}, logger: t.context.logger}, 'inexistantPlugin', 'non-existing-path', {}), {
|
||||
message: /Cannot find module 'non-existing-path'/,
|
||||
code: 'MODULE_NOT_FOUND',
|
||||
instanceOf: Error,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import AggregateError from 'aggregate-error';
|
||||
import pipeline from '../../lib/plugins/pipeline';
|
||||
const test = require('ava');
|
||||
const {stub} = require('sinon');
|
||||
const AggregateError = require('aggregate-error');
|
||||
const pipeline = require('../../lib/plugins/pipeline');
|
||||
|
||||
test('Execute each function in series passing the same input', async t => {
|
||||
test('Execute each function in series passing the same input', async (t) => {
|
||||
const step1 = stub().resolves(1);
|
||||
const step2 = stub().resolves(2);
|
||||
const step3 = stub().resolves(3);
|
||||
@@ -18,7 +18,7 @@ test('Execute each function in series passing the same input', async t => {
|
||||
t.true(step2.calledBefore(step3));
|
||||
});
|
||||
|
||||
test('Execute each function in series passing a transformed input from "getNextInput"', async t => {
|
||||
test('Execute each function in series passing a transformed input from "getNextInput"', async (t) => {
|
||||
const step1 = stub().resolves(1);
|
||||
const step2 = stub().resolves(2);
|
||||
const step3 = stub().resolves(3);
|
||||
@@ -37,7 +37,7 @@ test('Execute each function in series passing a transformed input from "getNextI
|
||||
t.true(step3.calledBefore(step4));
|
||||
});
|
||||
|
||||
test('Execute each function in series passing the "lastResult" and "result" to "getNextInput"', async t => {
|
||||
test('Execute each function in series passing the "lastResult" and "result" to "getNextInput"', async (t) => {
|
||||
const step1 = stub().resolves(1);
|
||||
const step2 = stub().resolves(2);
|
||||
const step3 = stub().resolves(3);
|
||||
@@ -47,50 +47,68 @@ test('Execute each function in series passing the "lastResult" and "result" to "
|
||||
const result = await pipeline([step1, step2, step3, step4], {settleAll: false, getNextInput})(5);
|
||||
|
||||
t.deepEqual(result, [1, 2, 3, 4]);
|
||||
t.deepEqual(getNextInput.args, [[5, 1], [5, 2], [5, 3], [5, 4]]);
|
||||
t.deepEqual(getNextInput.args, [
|
||||
[5, 1],
|
||||
[5, 2],
|
||||
[5, 3],
|
||||
[5, 4],
|
||||
]);
|
||||
});
|
||||
|
||||
test('Execute each function in series calling "transform" to modify the results', async t => {
|
||||
test('Execute each function in series calling "transform" to modify the results', async (t) => {
|
||||
const step1 = stub().resolves(1);
|
||||
const step2 = stub().resolves(2);
|
||||
const step3 = stub().resolves(3);
|
||||
const step4 = stub().resolves(4);
|
||||
const getNextInput = stub().returnsArg(0);
|
||||
const transform = stub().callsFake(result => result + 1);
|
||||
const transform = stub().callsFake((result) => result + 1);
|
||||
|
||||
const result = await pipeline([step1, step2, step3, step4], {getNextInput, transform})(5);
|
||||
|
||||
t.deepEqual(result, [1 + 1, 2 + 1, 3 + 1, 4 + 1]);
|
||||
t.deepEqual(getNextInput.args, [[5, 1 + 1], [5, 2 + 1], [5, 3 + 1], [5, 4 + 1]]);
|
||||
t.deepEqual(getNextInput.args, [
|
||||
[5, 1 + 1],
|
||||
[5, 2 + 1],
|
||||
[5, 3 + 1],
|
||||
[5, 4 + 1],
|
||||
]);
|
||||
});
|
||||
|
||||
test('Execute each function in series calling "transform" to modify the results with "settleAll"', async t => {
|
||||
test('Execute each function in series calling "transform" to modify the results with "settleAll"', async (t) => {
|
||||
const step1 = stub().resolves(1);
|
||||
const step2 = stub().resolves(2);
|
||||
const step3 = stub().resolves(3);
|
||||
const step4 = stub().resolves(4);
|
||||
const getNextInput = stub().returnsArg(0);
|
||||
const transform = stub().callsFake(result => result + 1);
|
||||
const transform = stub().callsFake((result) => result + 1);
|
||||
|
||||
const result = await pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput, transform})(5);
|
||||
|
||||
t.deepEqual(result, [1 + 1, 2 + 1, 3 + 1, 4 + 1]);
|
||||
t.deepEqual(getNextInput.args, [[5, 1 + 1], [5, 2 + 1], [5, 3 + 1], [5, 4 + 1]]);
|
||||
t.deepEqual(getNextInput.args, [
|
||||
[5, 1 + 1],
|
||||
[5, 2 + 1],
|
||||
[5, 3 + 1],
|
||||
[5, 4 + 1],
|
||||
]);
|
||||
});
|
||||
|
||||
test('Stop execution and throw error if a step rejects', async t => {
|
||||
test('Stop execution and throw error if a step rejects', async (t) => {
|
||||
const step1 = stub().resolves(1);
|
||||
const step2 = stub().rejects(new Error('test error'));
|
||||
const step3 = stub().resolves(3);
|
||||
|
||||
const error = await t.throwsAsync(pipeline([step1, step2, step3])(0), Error);
|
||||
const error = await t.throwsAsync(pipeline([step1, step2, step3])(0), {
|
||||
instanceOf: Error,
|
||||
message: 'test error',
|
||||
});
|
||||
t.is(error.message, 'test error');
|
||||
t.true(step1.calledWith(0));
|
||||
t.true(step2.calledWith(0));
|
||||
t.true(step3.notCalled);
|
||||
});
|
||||
|
||||
test('Throw all errors from the first step throwing an AggregateError', async t => {
|
||||
test('Throw all errors from the first step throwing an AggregateError', async (t) => {
|
||||
const error1 = new Error('test error 1');
|
||||
const error2 = new Error('test error 2');
|
||||
|
||||
@@ -106,7 +124,7 @@ test('Throw all errors from the first step throwing an AggregateError', async t
|
||||
t.true(step3.notCalled);
|
||||
});
|
||||
|
||||
test('Execute all even if a Promise rejects', async t => {
|
||||
test('Execute all even if a Promise rejects', async (t) => {
|
||||
const error1 = new Error('test error 1');
|
||||
const error2 = new Error('test error 2');
|
||||
const step1 = stub().resolves(1);
|
||||
@@ -121,7 +139,7 @@ test('Execute all even if a Promise rejects', async t => {
|
||||
t.true(step3.calledWith(0));
|
||||
});
|
||||
|
||||
test('Throw all errors from all steps throwing an AggregateError', async t => {
|
||||
test('Throw all errors from all steps throwing an AggregateError', async (t) => {
|
||||
const error1 = new Error('test error 1');
|
||||
const error2 = new Error('test error 2');
|
||||
const error3 = new Error('test error 3');
|
||||
@@ -136,14 +154,14 @@ test('Throw all errors from all steps throwing an AggregateError', async t => {
|
||||
t.true(step2.calledWith(0));
|
||||
});
|
||||
|
||||
test('Execute each function in series passing a transformed input even if a step rejects', async t => {
|
||||
test('Execute each function in series passing a transformed input even if a step rejects', async (t) => {
|
||||
const error2 = new Error('test error 2');
|
||||
const error3 = new Error('test error 3');
|
||||
const step1 = stub().resolves(1);
|
||||
const step2 = stub().rejects(error2);
|
||||
const step3 = stub().rejects(error3);
|
||||
const step4 = stub().resolves(4);
|
||||
const getNextInput = (prevResult, result) => prevResult + result;
|
||||
const getNextInput = (previousResult, result) => previousResult + result;
|
||||
|
||||
const errors = await t.throwsAsync(pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput})(0));
|
||||
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import path from 'path';
|
||||
import test from 'ava';
|
||||
import {copy, outputFile} from 'fs-extra';
|
||||
import {stub} from 'sinon';
|
||||
import tempy from 'tempy';
|
||||
import getPlugins from '../../lib/plugins';
|
||||
const path = require('path');
|
||||
const test = require('ava');
|
||||
const {copy, outputFile} = require('fs-extra');
|
||||
const {stub} = require('sinon');
|
||||
const tempy = require('tempy');
|
||||
const getPlugins = require('../../lib/plugins');
|
||||
|
||||
// Save the current working diretory
|
||||
const cwd = process.cwd();
|
||||
|
||||
test.beforeEach(t => {
|
||||
test.beforeEach((t) => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.success = stub();
|
||||
t.context.logger = {log: t.context.log, success: t.context.success, scope: () => t.context.logger};
|
||||
});
|
||||
|
||||
test('Export default plugins', t => {
|
||||
test('Export default plugins', (t) => {
|
||||
const plugins = getPlugins({cwd, options: {}, logger: t.context.logger}, {});
|
||||
|
||||
// Verify the module returns a function for each plugin
|
||||
@@ -29,7 +29,7 @@ test('Export default plugins', t => {
|
||||
t.is(typeof plugins.fail, 'function');
|
||||
});
|
||||
|
||||
test('Export plugins based on steps config', t => {
|
||||
test('Export plugins based on steps config', (t) => {
|
||||
const plugins = getPlugins(
|
||||
{
|
||||
cwd,
|
||||
@@ -55,7 +55,7 @@ test('Export plugins based on steps config', t => {
|
||||
t.is(typeof plugins.fail, 'function');
|
||||
});
|
||||
|
||||
test('Export plugins based on "plugins" config (array)', async t => {
|
||||
test('Export plugins based on "plugins" config (array)', async (t) => {
|
||||
const plugin1 = {verifyConditions: stub(), publish: stub()};
|
||||
const plugin2 = {verifyConditions: stub(), verifyRelease: stub()};
|
||||
const plugins = getPlugins(
|
||||
@@ -84,7 +84,7 @@ test('Export plugins based on "plugins" config (array)', async t => {
|
||||
t.is(typeof plugins.fail, 'function');
|
||||
});
|
||||
|
||||
test('Export plugins based on "plugins" config (single definition)', async t => {
|
||||
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}}, {});
|
||||
|
||||
@@ -105,7 +105,7 @@ test('Export plugins based on "plugins" config (single definition)', async t =>
|
||||
t.is(typeof plugins.fail, 'function');
|
||||
});
|
||||
|
||||
test('Merge global options, "plugins" options and step options', async t => {
|
||||
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'}];
|
||||
const plugin3 = [stub(), {pluginOpt3: 'plugin3'}];
|
||||
@@ -129,7 +129,7 @@ test('Merge global options, "plugins" options and step options', async t => {
|
||||
t.deepEqual(plugin3[0].args[0][0], {globalOpt: 'global', pluginOpt3: 'plugin3'});
|
||||
});
|
||||
|
||||
test('Unknown steps of plugins configured in "plugins" are ignored', t => {
|
||||
test('Unknown steps of plugins configured in "plugins" are ignored', (t) => {
|
||||
const plugin1 = {verifyConditions: () => {}, unknown: () => {}};
|
||||
const plugins = getPlugins({cwd, logger: t.context.logger, options: {plugins: [plugin1]}}, {});
|
||||
|
||||
@@ -137,7 +137,7 @@ test('Unknown steps of plugins configured in "plugins" are ignored', t => {
|
||||
t.is(plugins.unknown, undefined);
|
||||
});
|
||||
|
||||
test('Export plugins loaded from the dependency of a shareable config module', async t => {
|
||||
test('Export plugins loaded from the dependency of a shareable config module', async (t) => {
|
||||
const cwd = tempy.directory();
|
||||
await copy(
|
||||
'./test/fixtures/plugin-noop.js',
|
||||
@@ -170,7 +170,7 @@ test('Export plugins loaded from the dependency of a shareable config module', a
|
||||
t.is(typeof plugins.fail, 'function');
|
||||
});
|
||||
|
||||
test('Export plugins loaded from the dependency of a shareable config file', async t => {
|
||||
test('Export plugins loaded from the dependency of a shareable config file', async (t) => {
|
||||
const cwd = tempy.directory();
|
||||
await copy('./test/fixtures/plugin-noop.js', path.resolve(cwd, 'plugin/plugin-noop.js'));
|
||||
await outputFile(path.resolve(cwd, 'shareable-config.js'), '');
|
||||
@@ -200,7 +200,7 @@ test('Export plugins loaded from the dependency of a shareable config file', asy
|
||||
t.is(typeof plugins.fail, 'function');
|
||||
});
|
||||
|
||||
test('Use default when only options are passed for a single plugin', t => {
|
||||
test('Use default when only options are passed for a single plugin', (t) => {
|
||||
const analyzeCommits = {};
|
||||
const generateNotes = {};
|
||||
const publish = {};
|
||||
@@ -234,7 +234,7 @@ test('Use default when only options are passed for a single plugin', t => {
|
||||
t.falsy(fail.path);
|
||||
});
|
||||
|
||||
test('Merge global options with plugin options', async t => {
|
||||
test('Merge global options with plugin options', async (t) => {
|
||||
const plugins = getPlugins(
|
||||
{
|
||||
cwd,
|
||||
@@ -253,7 +253,7 @@ test('Merge global options with plugin options', async t => {
|
||||
t.deepEqual(result.pluginConfig, {localOpt: 'local', globalOpt: 'global', otherOpt: 'locally-defined'});
|
||||
});
|
||||
|
||||
test('Throw an error for each invalid plugin configuration', t => {
|
||||
test('Throw an error for each invalid plugin configuration', (t) => {
|
||||
const errors = [
|
||||
...t.throws(() =>
|
||||
getPlugins(
|
||||
@@ -283,7 +283,7 @@ test('Throw an error for each invalid plugin configuration', t => {
|
||||
t.is(errors[3].code, 'EPLUGINCONF');
|
||||
});
|
||||
|
||||
test('Throw EPLUGINSCONF error if the "plugins" option contains an old plugin definition (returns a function)', t => {
|
||||
test('Throw EPLUGINSCONF error if the "plugins" option contains an old plugin definition (returns a function)', (t) => {
|
||||
const errors = [
|
||||
...t.throws(() =>
|
||||
getPlugins(
|
||||
@@ -303,7 +303,7 @@ test('Throw EPLUGINSCONF error if the "plugins" option contains an old plugin de
|
||||
t.is(errors[1].code, 'EPLUGINSCONF');
|
||||
});
|
||||
|
||||
test('Throw EPLUGINSCONF error for each invalid definition if the "plugins" option', t => {
|
||||
test('Throw EPLUGINSCONF error for each invalid definition if the "plugins" option', (t) => {
|
||||
const errors = [
|
||||
...t.throws(() =>
|
||||
getPlugins({cwd, logger: t.context.logger, options: {plugins: [1, {path: 1}, [() => {}, {}, {}]]}}, {})
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import test from 'ava';
|
||||
import {validatePlugin, validateStep, loadPlugin, parseConfig} from '../../lib/plugins/utils';
|
||||
const test = require('ava');
|
||||
const {validatePlugin, validateStep, loadPlugin, parseConfig} = require('../../lib/plugins/utils');
|
||||
|
||||
test('validatePlugin', t => {
|
||||
test('validatePlugin', (t) => {
|
||||
const path = 'plugin-module';
|
||||
const options = {option1: 'value1', option2: 'value2'};
|
||||
|
||||
@@ -25,7 +25,7 @@ test('validatePlugin', t => {
|
||||
t.false(validatePlugin({path: 1}), 'Object definition, wrong path');
|
||||
});
|
||||
|
||||
test('validateStep: optional plugin configuration', t => {
|
||||
test('validateStep: optional plugin configuration', (t) => {
|
||||
const type = {multiple: true, required: false};
|
||||
|
||||
// Empty config
|
||||
@@ -107,7 +107,7 @@ test('validateStep: optional plugin configuration', t => {
|
||||
);
|
||||
});
|
||||
|
||||
test('validateStep: required plugin configuration', t => {
|
||||
test('validateStep: required plugin configuration', (t) => {
|
||||
const type = {required: true};
|
||||
|
||||
// Empty config
|
||||
@@ -189,7 +189,7 @@ test('validateStep: required plugin configuration', t => {
|
||||
);
|
||||
});
|
||||
|
||||
test('loadPlugin', t => {
|
||||
test('loadPlugin', (t) => {
|
||||
const cwd = process.cwd();
|
||||
const func = () => {};
|
||||
|
||||
@@ -202,7 +202,7 @@ test('loadPlugin', t => {
|
||||
t.is(func, loadPlugin({cwd}, func, {}), 'Defined as a function');
|
||||
});
|
||||
|
||||
test('parseConfig', t => {
|
||||
test('parseConfig', (t) => {
|
||||
const path = 'plugin-module';
|
||||
const options = {option1: 'value1', option2: 'value2'};
|
||||
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
const test = require('ava');
|
||||
const AggregateError = require('aggregate-error');
|
||||
const {
|
||||
extractErrors,
|
||||
tagsToVersions,
|
||||
isMajorRange,
|
||||
isMaintenanceRange,
|
||||
getUpperBound,
|
||||
getLowerBound,
|
||||
highest,
|
||||
lowest,
|
||||
getLatestVersion,
|
||||
getEarliestVersion,
|
||||
getFirstVersion,
|
||||
getRange,
|
||||
makeTag,
|
||||
isSameChannel,
|
||||
} = require('../lib/utils');
|
||||
|
||||
test('extractErrors', (t) => {
|
||||
const errors = [new Error('Error 1'), new Error('Error 2')];
|
||||
|
||||
t.deepEqual(extractErrors(new AggregateError(errors)), errors);
|
||||
t.deepEqual(extractErrors(errors[0]), [errors[0]]);
|
||||
});
|
||||
|
||||
test('tagsToVersions', (t) => {
|
||||
t.deepEqual(tagsToVersions([{version: '1.0.0'}, {version: '1.1.0'}, {version: '1.2.0'}]), [
|
||||
'1.0.0',
|
||||
'1.1.0',
|
||||
'1.2.0',
|
||||
]);
|
||||
});
|
||||
|
||||
test('isMajorRange', (t) => {
|
||||
t.false(isMajorRange('1.1.x'));
|
||||
t.false(isMajorRange('1.11.x'));
|
||||
t.false(isMajorRange('11.1.x'));
|
||||
t.false(isMajorRange('11.11.x'));
|
||||
t.false(isMajorRange('1.1.X'));
|
||||
t.false(isMajorRange('1.1.0'));
|
||||
|
||||
t.true(isMajorRange('1.x.x'));
|
||||
t.true(isMajorRange('11.x.x'));
|
||||
t.true(isMajorRange('1.X.X'));
|
||||
t.true(isMajorRange('1.x'));
|
||||
t.true(isMajorRange('11.x'));
|
||||
t.true(isMajorRange('1.X'));
|
||||
});
|
||||
|
||||
test('isMaintenanceRange', (t) => {
|
||||
t.true(isMaintenanceRange('1.1.x'));
|
||||
t.true(isMaintenanceRange('11.1.x'));
|
||||
t.true(isMaintenanceRange('11.11.x'));
|
||||
t.true(isMaintenanceRange('1.11.x'));
|
||||
t.true(isMaintenanceRange('1.x.x'));
|
||||
t.true(isMaintenanceRange('11.x.x'));
|
||||
t.true(isMaintenanceRange('1.x'));
|
||||
t.true(isMaintenanceRange('11.x'));
|
||||
t.true(isMaintenanceRange('1.1.X'));
|
||||
t.true(isMaintenanceRange('1.X.X'));
|
||||
t.true(isMaintenanceRange('1.X'));
|
||||
|
||||
t.false(isMaintenanceRange('1.1.0'));
|
||||
t.false(isMaintenanceRange('11.1.0'));
|
||||
t.false(isMaintenanceRange('1.11.0'));
|
||||
t.false(isMaintenanceRange('11.11.0'));
|
||||
t.false(isMaintenanceRange('~1.0.0'));
|
||||
t.false(isMaintenanceRange('^1.0.0'));
|
||||
});
|
||||
|
||||
test('getUpperBound', (t) => {
|
||||
t.is(getUpperBound('1.x.x'), '2.0.0');
|
||||
t.is(getUpperBound('1.X.X'), '2.0.0');
|
||||
t.is(getUpperBound('10.x.x'), '11.0.0');
|
||||
t.is(getUpperBound('1.x'), '2.0.0');
|
||||
t.is(getUpperBound('10.x'), '11.0.0');
|
||||
t.is(getUpperBound('1.0.x'), '1.1.0');
|
||||
t.is(getUpperBound('10.0.x'), '10.1.0');
|
||||
t.is(getUpperBound('10.10.x'), '10.11.0');
|
||||
t.is(getUpperBound('1.0.0'), '1.0.0');
|
||||
t.is(getUpperBound('10.0.0'), '10.0.0');
|
||||
|
||||
t.is(getUpperBound('foo'), undefined);
|
||||
});
|
||||
|
||||
test('getLowerBound', (t) => {
|
||||
t.is(getLowerBound('1.x.x'), '1.0.0');
|
||||
t.is(getLowerBound('1.X.X'), '1.0.0');
|
||||
t.is(getLowerBound('10.x.x'), '10.0.0');
|
||||
t.is(getLowerBound('1.x'), '1.0.0');
|
||||
t.is(getLowerBound('10.x'), '10.0.0');
|
||||
t.is(getLowerBound('1.0.x'), '1.0.0');
|
||||
t.is(getLowerBound('10.0.x'), '10.0.0');
|
||||
t.is(getLowerBound('1.10.x'), '1.10.0');
|
||||
t.is(getLowerBound('1.0.0'), '1.0.0');
|
||||
t.is(getLowerBound('10.0.0'), '10.0.0');
|
||||
|
||||
t.is(getLowerBound('foo'), undefined);
|
||||
});
|
||||
|
||||
test('highest', (t) => {
|
||||
t.is(highest('1.0.0', '2.0.0'), '2.0.0');
|
||||
t.is(highest('1.1.1', '1.1.0'), '1.1.1');
|
||||
t.is(highest(null, '1.0.0'), '1.0.0');
|
||||
t.is(highest('1.0.0'), '1.0.0');
|
||||
t.is(highest(), undefined);
|
||||
});
|
||||
|
||||
test('lowest', (t) => {
|
||||
t.is(lowest('1.0.0', '2.0.0'), '1.0.0');
|
||||
t.is(lowest('1.1.1', '1.1.0'), '1.1.0');
|
||||
t.is(lowest(null, '1.0.0'), '1.0.0');
|
||||
t.is(lowest(), undefined);
|
||||
});
|
||||
|
||||
test.serial('getLatestVersion', (t) => {
|
||||
t.is(getLatestVersion(['1.2.3-alpha.3', '1.2.0', '1.0.1', '1.0.0-alpha.1']), '1.2.0');
|
||||
t.is(getLatestVersion(['1.2.3-alpha.3', '1.2.3-alpha.2']), undefined);
|
||||
|
||||
t.is(getLatestVersion(['1.2.3-alpha.3', '1.2.0', '1.0.1', '1.0.0-alpha.1']), '1.2.0');
|
||||
t.is(getLatestVersion(['1.2.3-alpha.3', '1.2.3-alpha.2']), undefined);
|
||||
|
||||
t.is(getLatestVersion(['1.2.3-alpha.3', '1.2.0', '1.0.1', '1.0.0-alpha.1'], {withPrerelease: true}), '1.2.3-alpha.3');
|
||||
t.is(getLatestVersion(['1.2.3-alpha.3', '1.2.3-alpha.2'], {withPrerelease: true}), '1.2.3-alpha.3');
|
||||
|
||||
t.is(getLatestVersion([]), undefined);
|
||||
});
|
||||
|
||||
test.serial('getEarliestVersion', (t) => {
|
||||
t.is(getEarliestVersion(['1.2.3-alpha.3', '1.2.0', '1.0.0', '1.0.1-alpha.1']), '1.0.0');
|
||||
t.is(getEarliestVersion(['1.2.3-alpha.3', '1.2.3-alpha.2']), undefined);
|
||||
|
||||
t.is(getEarliestVersion(['1.2.3-alpha.3', '1.2.0', '1.0.0', '1.0.1-alpha.1']), '1.0.0');
|
||||
t.is(getEarliestVersion(['1.2.3-alpha.3', '1.2.3-alpha.2']), undefined);
|
||||
|
||||
t.is(
|
||||
getEarliestVersion(['1.2.3-alpha.3', '1.2.0', '1.0.1', '1.0.0-alpha.1'], {withPrerelease: true}),
|
||||
'1.0.0-alpha.1'
|
||||
);
|
||||
t.is(getEarliestVersion(['1.2.3-alpha.3', '1.2.3-alpha.2'], {withPrerelease: true}), '1.2.3-alpha.2');
|
||||
|
||||
t.is(getEarliestVersion([]), undefined);
|
||||
});
|
||||
|
||||
test('getFirstVersion', (t) => {
|
||||
t.is(getFirstVersion(['1.2.0', '1.0.0', '1.3.0', '1.1.0', '1.4.0'], []), '1.0.0');
|
||||
t.is(
|
||||
getFirstVersion(
|
||||
['1.2.0', '1.0.0', '1.3.0', '1.1.0', '1.4.0'],
|
||||
[
|
||||
{name: 'master', tags: [{version: '1.0.0'}, {version: '1.1.0'}]},
|
||||
{name: 'next', tags: [{version: '1.0.0'}, {version: '1.1.0'}, {version: '1.2.0'}]},
|
||||
]
|
||||
),
|
||||
'1.3.0'
|
||||
);
|
||||
t.is(
|
||||
getFirstVersion(
|
||||
['1.2.0', '1.0.0', '1.1.0'],
|
||||
[
|
||||
{name: 'master', tags: [{version: '1.0.0'}, {version: '1.1.0'}]},
|
||||
{name: 'next', tags: [{version: '1.0.0'}, {version: '1.1.0'}, {version: '1.2.0'}]},
|
||||
]
|
||||
),
|
||||
undefined
|
||||
);
|
||||
});
|
||||
|
||||
test('getRange', (t) => {
|
||||
t.is(getRange('1.0.0', '1.1.0'), '>=1.0.0 <1.1.0');
|
||||
t.is(getRange('1.0.0'), '>=1.0.0');
|
||||
});
|
||||
|
||||
test('makeTag', (t) => {
|
||||
t.is(makeTag(`v\${version}`, '1.0.0'), 'v1.0.0');
|
||||
});
|
||||
|
||||
test('isSameChannel', (t) => {
|
||||
t.true(isSameChannel('next', 'next'));
|
||||
t.true(isSameChannel(null, undefined));
|
||||
t.true(isSameChannel(false, undefined));
|
||||
t.true(isSameChannel('', false));
|
||||
|
||||
t.false(isSameChannel('next', false));
|
||||
});
|
||||
+54
-16
@@ -1,11 +1,11 @@
|
||||
import test from 'ava';
|
||||
import tempy from 'tempy';
|
||||
import verify from '../lib/verify';
|
||||
import {gitRepo} from './helpers/git-utils';
|
||||
const test = require('ava');
|
||||
const tempy = require('tempy');
|
||||
const verify = require('../lib/verify');
|
||||
const {gitRepo} = require('./helpers/git-utils');
|
||||
|
||||
test('Throw a AggregateError', async t => {
|
||||
test('Throw a AggregateError', async (t) => {
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {};
|
||||
const options = {branches: [{name: 'master'}, {name: ''}]};
|
||||
|
||||
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
|
||||
|
||||
@@ -21,11 +21,15 @@ test('Throw a AggregateError', async t => {
|
||||
t.is(errors[2].code, 'ETAGNOVERSION');
|
||||
t.truthy(errors[2].message);
|
||||
t.truthy(errors[2].details);
|
||||
t.is(errors[3].name, 'SemanticReleaseError');
|
||||
t.is(errors[3].code, 'EINVALIDBRANCH');
|
||||
t.truthy(errors[3].message);
|
||||
t.truthy(errors[3].details);
|
||||
});
|
||||
|
||||
test('Throw a SemanticReleaseError if does not run on a git repository', async t => {
|
||||
test('Throw a SemanticReleaseError if does not run on a git repository', async (t) => {
|
||||
const cwd = tempy.directory();
|
||||
const options = {};
|
||||
const options = {branches: []};
|
||||
|
||||
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
|
||||
|
||||
@@ -35,9 +39,9 @@ test('Throw a SemanticReleaseError if does not run on a git repository', async t
|
||||
t.truthy(errors[0].details);
|
||||
});
|
||||
|
||||
test('Throw a SemanticReleaseError if the "tagFormat" is not valid', async t => {
|
||||
test('Throw a SemanticReleaseError if the "tagFormat" is not valid', async (t) => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
const options = {repositoryUrl, tagFormat: `?\${version}`};
|
||||
const options = {repositoryUrl, tagFormat: `?\${version}`, branches: []};
|
||||
|
||||
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
|
||||
|
||||
@@ -47,9 +51,9 @@ test('Throw a SemanticReleaseError if the "tagFormat" is not valid', async t =>
|
||||
t.truthy(errors[0].details);
|
||||
});
|
||||
|
||||
test('Throw a SemanticReleaseError if the "tagFormat" does not contains the "version" variable', async t => {
|
||||
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 options = {repositoryUrl, tagFormat: 'test', branches: []};
|
||||
|
||||
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
|
||||
|
||||
@@ -59,9 +63,9 @@ test('Throw a SemanticReleaseError if the "tagFormat" does not contains the "ver
|
||||
t.truthy(errors[0].details);
|
||||
});
|
||||
|
||||
test('Throw a SemanticReleaseError if the "tagFormat" contains multiple "version" variables', async t => {
|
||||
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 options = {repositoryUrl, tagFormat: `\${version}v\${version}`, branches: []};
|
||||
|
||||
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
|
||||
|
||||
@@ -71,9 +75,43 @@ test('Throw a SemanticReleaseError if the "tagFormat" contains multiple "version
|
||||
t.truthy(errors[0].details);
|
||||
});
|
||||
|
||||
test('Return "true" if all verification pass', async t => {
|
||||
test('Throw a SemanticReleaseError for each invalid branch', async (t) => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
const options = {repositoryUrl, tagFormat: `v\${version}`};
|
||||
const options = {
|
||||
repositoryUrl,
|
||||
tagFormat: `v\${version}`,
|
||||
branches: [{name: ''}, {name: ' '}, {name: 1}, {}, {name: ''}, 1, 'master'],
|
||||
};
|
||||
|
||||
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
|
||||
|
||||
t.is(errors[0].name, 'SemanticReleaseError');
|
||||
t.is(errors[0].code, 'EINVALIDBRANCH');
|
||||
t.truthy(errors[0].message);
|
||||
t.truthy(errors[0].details);
|
||||
t.is(errors[1].name, 'SemanticReleaseError');
|
||||
t.is(errors[1].code, 'EINVALIDBRANCH');
|
||||
t.truthy(errors[1].message);
|
||||
t.truthy(errors[1].details);
|
||||
t.is(errors[2].name, 'SemanticReleaseError');
|
||||
t.is(errors[2].code, 'EINVALIDBRANCH');
|
||||
t.truthy(errors[2].message);
|
||||
t.truthy(errors[2].details);
|
||||
t.is(errors[3].name, 'SemanticReleaseError');
|
||||
t.is(errors[3].code, 'EINVALIDBRANCH');
|
||||
t.truthy(errors[3].message);
|
||||
t.truthy(errors[3].details);
|
||||
t.is(errors[4].code, 'EINVALIDBRANCH');
|
||||
t.truthy(errors[4].message);
|
||||
t.truthy(errors[4].details);
|
||||
t.is(errors[5].code, 'EINVALIDBRANCH');
|
||||
t.truthy(errors[5].message);
|
||||
t.truthy(errors[5].details);
|
||||
});
|
||||
|
||||
test('Return "true" if all verification pass', async (t) => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
const options = {repositoryUrl, tagFormat: `v\${version}`, branches: [{name: 'master'}]};
|
||||
|
||||
await t.notThrowsAsync(verify({cwd, options}));
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user