Compare commits

..
Author SHA1 Message Date
Gregor Martynus e72d201afe wip esm adapt lodash 2021-07-30 13:57:35 -07:00
Gregor Martynus ab7a428102 WIP esm - adapt sinon 2021-07-30 13:57:35 -07:00
Gregor Martynus ce263c5f4a WIP convert CJS to ESM using https://github.com/homer0/cjs2esm 2021-07-30 13:57:35 -07:00
Matt Travi d9605a5e45 docs(node-version): updated documentation to reference the new minimum 2021-07-30 15:47:49 -05:00
Matt Travi e1c00e2531 feat(node-version): raised the minimum required version to v14.17
for #2055

BREAKING CHANGE: the minimum required version of node is now v14.17
2021-07-30 15:18:22 -05:00
101 changed files with 10635 additions and 20283 deletions
+21
View File
@@ -0,0 +1,21 @@
---
name: Bug report
about: Something not working as expected
---
## Current behavior
<!-- Describe how the issue manifests. -->
## Expected behavior
<!-- Describe what the desired behavior would be. -->
## Environment
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
- CI environment: <!-- CI service name -->
- Plugins used: <!-- List semantic-release plugin used if any -->
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
- CI logs: <!-- link to your CI logs or semantic-release logs -->
-51
View File
@@ -1,51 +0,0 @@
name: Bug Report
description: Something not working as expected
body:
- type: textarea
attributes:
label: Current behavior
description: Describe how the issue manifests.
validations:
required: true
- type: textarea
attributes:
label: Expected behavior
description: Describe what the desired behavior would be.
validations:
required: true
- type: input
attributes:
label: "`semantic-release` version"
description: Version set in `package.json` `devDpendencies`.
validations:
required: true
- type: input
attributes:
label: CI environment
description: CI service name.
validations:
required: true
- type: textarea
attributes:
label: Plugins used
description: List `semantic-release` plugin used, if any.
validations:
required: false
- type: textarea
attributes:
label: "`semantic-release` configuration"
description: Link to your repository or relevant part of the `semantic-release` config.
validations:
required: true
- type: textarea
attributes:
label: CI logs
description: Link to your CI logs or `semantic-release` logs.
validations:
required: true
@@ -0,0 +1,17 @@
---
name: Feature request
about: Wouldn’t it be nice if semantic-release could ...
---
## New feature motivation
<!-- Describe the context, the use-case and the advantages of the feature request. -->
## New feature description
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
## New feature implementation
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
@@ -1,23 +0,0 @@
name: Feature request
description: Wouldn't it be nice if `semantic-release` could ...
body:
- type: textarea
attributes:
label: New feature motivation
description: Describe the context, the use-case and the advantages of the feature request.
validations:
required: true
- type: textarea
attributes:
label: New feature description
description: Describe the functional changes that would have to be made in `semantic-release` or its plugins.
validations:
required: true
- type: textarea
attributes:
label: New feature implementation
description: Optionally describe the technical changes to be made in `semantic-release` or its plugins.
validations:
required: false
@@ -0,0 +1,13 @@
---
name: New plugin suggestion
about: Integrate with a new platform, etc
---
## New plugin motivation
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
## Third-party documentation
<!-- Provide explanation and documentation links for the platform to integrate with. -->
@@ -1,16 +0,0 @@
name: New plugin suggestion
description: Integrate with a new platform, etc
body:
- type: textarea
attributes:
label: New plugin motivation
description: Describe the reasons to create a new plugin and why it's not covered by the existing ones.
validations:
required: true
- type: textarea
attributes:
label: Third-party documentation
description: Provide explanation and documentation links for the platform to integrate with.
validations:
required: true
+5 -5
View File
@@ -1,21 +1,21 @@
name: Release
"on":
on:
push:
branches:
- master
- next
- beta
- "*.x"
- "*.x" # maintenance releases branches
jobs:
release:
name: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
cache: npm
node-version: 16
- run: npm ci
- run: npx semantic-release
env:
+7 -9
View File
@@ -18,20 +18,21 @@ jobs:
matrix:
node-version:
- 14.17
- 16.0.0
- 17
- 16
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v2
- run: git config --global user.name github-actions
- run: git config --global user.email github-actions@github.com
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node-version }}
cache: npm
- name: Ensure dependencies are compatible with the version of node
run: echo 'engine-strict=true' >> .npmrc
- run: npm ci
- run: npm run test:ci
@@ -41,12 +42,9 @@ jobs:
runs-on: ubuntu-latest
needs: test_matrix
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: 16
cache: npm
- run: npm ci
- name: Ensure dependencies are compatible with the version of node
run: npx ls-engines@0.4
- run: npm run lint
+16 -32
View File
@@ -20,55 +20,45 @@ Help us keep **semantic-release** open and inclusive. Please read and follow our
### Improve documentation
As a **semantic-release** user, you are the perfect candidate to help us improve our documentation: typo corrections, clarifications, more examples, new [recipes](docs/recipes), etc. Take a look at the [documentation issues that need help](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22+label%3Adocs+).
As a **semantic-release** user, you are the perfect candidate to help us improve our documentation: typo corrections, clarifications, more examples, new [recipes](docs/recipes/README.md), etc. Take a look at the [documentation issues that need help](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22+label%3Adocs+).
Please follow the [Documentation guidelines](#documentation).
### Give feedback on issues
Some issues are created without information requested in the [Bug report guideline](#bug-report).
Help make them easier to resolve by adding any relevant information.
Some issues are created without information requested in the [Bug report guideline](#bug-report). Help make them easier to resolve by adding any relevant information.
Issues with the [design label](https://github.com/issues?q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3Adesign) are meant to discuss the implementation of new features.
Participating in the discussion is a good opportunity to get involved and influence the future direction of **semantic-release**.
Issues with the [design label](https://github.com/issues?q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3Adesign) are meant to discuss the implementation of new features. Participating in the discussion is a good opportunity to get involved and influence the future direction of **semantic-release**.
### Fix bugs and implement features
Confirmed bugs and ready-to-implement features are marked with the [help wanted label](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22).
Post a comment on an issue to indicate you would like to work on it and to request help from the [@semantic-release/maintainers](https://github.com/orgs/semantic-release/teams/contributors) and the community.
Confirmed bugs and ready-to-implement features are marked with the [help wanted label](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22). Post a comment on an issue to indicate you would like to work on it and to request help from the [@semantic-release/maintainers](https://github.com/orgs/semantic-release/teams/contributors) and the community.
## Using the issue tracker
The issue tracker is the channel for [bug reports](#bug-report), [features requests](#feature-request) and [submitting pull requests](#submitting-a-pull-request) only.
Please use the [Support](docs/support/README.md) and [Get help](README.md#get-help) sections for support, troubleshooting and questions.
The issue tracker is the channel for [bug reports](#bug-report), [features requests](#feature-request) and [submitting pull requests](#submitting-a-pull-request) only. Please use the [Support](docs/support/README.md) and [Get help](README.md#get-help) sections for support, troubleshooting and questions.
Before opening an issue or a Pull Request, please use the [GitHub issue search](https://github.com/issues?utf8=%E2%9C%93&q=user%3Asemantic-release) to make sure the bug or feature request hasn't been already reported or fixed.
### Bug report
A good bug report shouldn't leave others needing to chase you for more information.
Please try to be as detailed as possible in your report and fill the information requested in the [bug report template](https://github.com/semantic-release/semantic-release/issues/new?template=01_bug_report.md).
A good bug report shouldn't leave others needing to chase you for more information. Please try to be as detailed as possible in your report and fill the information requested in the [Bug report template](https://github.com/semantic-release/semantic-release/issues/new?template=bug-report.md).
### Feature request
Feature requests are welcome, but take a moment to find out whether your idea fits with the scope and aims of the project.
It's up to you to make a strong case to convince the project's developers of the merits of this feature.
Please provide as much detail and context as possible and fill the information requested in the [feature request template](https://github.com/semantic-release/semantic-release/issues/new?template=02_feature_request.md).
Feature requests are welcome, but take a moment to find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible and fill the information requested in the [Feature request template](https://github.com/semantic-release/semantic-release/issues/new?template=feature-request.md).
### New plugin request
[Plugins](docs/usage/plugins.md) are a great way to extend **semantic-release** capabilities, integrate with other systems and support new project type.
Please provide as much detail and context as possible and fill the information requested in the [plugin suggestion template](https://github.com/semantic-release/semantic-release/issues/new?template=03_plugin_suggestion.md).
[Plugins](docs/usage/plugins.md) are a great way to extend **semantic-release** capabilities, integrate with other systems and support new project type. Please provide as much detail and context as possible and fill the information requested in the [New plugin request template](https://github.com/semantic-release/semantic-release/issues/new?template=plugin-request.md).
## Submitting a Pull Request
Good pull requests, whether patches, improvements, or new features, are a fantastic help.
They should remain focused in scope and avoid containing unrelated commits.
Good pull requests, whether patches, improvements, or new features, are a fantastic help. They should remain focused in scope and avoid containing unrelated commits.
**Please ask first** before embarking on any significant pull requests (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's maintainers might not want to merge into the project.
**Please ask first** before embarking on any significant pull requests (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project.
If you have never created a pull request before, welcome 🎉 😄.
[Here is a great tutorial](https://opensource.guide/how-to-contribute/#opening-a-pull-request) on how to send one :)
If you have never created a pull request before, welcome 🎉 😄. [Here is a great tutorial](https://opensource.guide/how-to-contribute/#opening-a-pull-request) on how to send one :)
Here is a summary of the steps to follow:
@@ -93,9 +83,7 @@ $ git push origin <topic-branch-name>
**Tips**:
- For ambitious tasks, open a Pull Request as soon as possible with the `[WIP]` prefix in the title, in order to get feedback and help from the community.
- [Allow semantic-release maintainers to make changes to your Pull Request branch](https://help.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork).
This way, we can rebase it and make some minor changes if necessary.
All changes we make will be done in new commit, and we'll ask for your approval before merging them.
- [Allow semantic-release maintainers to make changes to your Pull Request branch](https://help.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork). This way, we can rebase it and make some minor changes if necessary. All changes we make will be done in new commit and we'll ask for your approval before merging them.
## Coding rules
@@ -141,8 +129,7 @@ A complex feature can be broken down into multiple commits as long as each one m
#### Commit message format
Each commit message consists of a **header**, a **body** and a **footer**.
The header has a special format that includes a **type**, a **scope** and a **subject**:
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special format that includes a **type**, a **scope** and a **subject**:
```commit
<type>(<scope>): <subject>
@@ -158,8 +145,7 @@ The **footer** can contain a [closing reference to an issue](https://help.github
#### Revert
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit.
In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.
#### Type
@@ -192,8 +178,7 @@ The body should include the motivation for the change and contrast this with pre
#### Footer
The footer should contain any information about **Breaking Changes** and is also the place to reference GitHub issues that this commit **Closes**.
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines.
The rest of the commit message is then used for this.
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
#### Examples
@@ -234,8 +219,7 @@ $ npm install
### Lint
All the [semantic-release](https://github.com/semantic-release) repositories use [XO](https://github.com/sindresorhus/xo) for linting and [Prettier](https://prettier.io) for formatting.
Prettier formatting will be automatically verified and fixed by XO.
All the [semantic-release](https://github.com/semantic-release) repositories use [XO](https://github.com/sindresorhus/xo) for linting and [Prettier](https://prettier.io) for formatting. Prettier formatting will be automatically verified and fixed by XO.
Before pushing your code changes make sure there are no linting errors with `npm run lint`.
+25 -29
View File
@@ -8,7 +8,7 @@
<img alt="Build states" src="https://github.com/semantic-release/semantic-release/workflows/Test/badge.svg">
</a>
<a href="#badge">
<img alt="semantic-release: angular" src="https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release">
<img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg">
</a>
</p>
<p align="center">
@@ -23,9 +23,9 @@
</a>
</p>
**semantic-release** automates the whole package release workflow including: determining the next version number, generating the release notes, and publishing the package.
**semantic-release** automates the whole package release workflow including: determining the next version number, generating the release notes and publishing the package.
This removes the immediate connection between human emotions and version numbers, strictly following the [Semantic Versioning](http://semver.org) specification and communicating the **impact** of changes to consumers.
This removes the immediate connection between human emotions and version numbers, strictly following the [Semantic Versioning](http://semver.org) specification.
> Trust us, this will change your workflow for the better. – [egghead.io](https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release)
@@ -37,20 +37,18 @@ This removes the immediate connection between human emotions and version numbers
- 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/release-workflow/README.md#ci-configurations)
- 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/release-workflow/README.md#package-managers-and-languages) via [plugins](docs/usage/plugins.md)
- Support any [package managers and languages](docs/recipes/README.md#package-managers-and-languages) via [plugins](docs/usage/plugins.md)
- Simple and reusable configuration via [shareable configurations](docs/usage/shareable-configurations.md)
## How does it work?
### Commit message format
**semantic-release** uses the commit messages to determine the consumer impact of changes in the codebase.
Following formalized conventions for commit messages, **semantic-release** automatically determines the next [semantic version](https://semver.org) number, generates a changelog and publishes the release.
**semantic-release** uses the commit messages to determine the type of changes in the codebase. Following formalized conventions for commit messages, **semantic-release** automatically determines the next [semantic version](https://semver.org) number, generates a changelog and publishes the release.
By default, **semantic-release** uses [Angular Commit Message Conventions](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-format).
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.
By default **semantic-release** uses [Angular Commit Message Conventions](https://github.com/angular/angular/blob/master/CONTRIBUTING.md#-commit-message-format). 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) or [commitlint](https://github.com/conventional-changelog/commitlint) can be used to help contributors and enforce valid commit messages.
@@ -58,25 +56,23 @@ The table below shows which commit message gets you which release type when `sem
| Commit message | Release type |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------- |
| `fix(pencil): stop graphite breaking when too much pressure applied` | ~~Patch~~ Fix Release |
| `fix(pencil): stop graphite breaking when too much pressure applied` | Patch Release |
| `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
| `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release <br /> (Note that the `BREAKING CHANGE: ` token must be in the footer of the commit) |
| `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release |
### Automation with CI
**semantic-release** is meant to be executed on the CI environment after every successful build on the release branch.
This way no human is directly involved in the release process and the releases are guaranteed to be [unromantic and unsentimental](http://sentimentalversioning.org).
**semantic-release** is meant to be executed on the CI environment after every successful build on the release branch. This way no human is directly involved in the release process and the releases are guaranteed to be [unromantic and unsentimental](http://sentimentalversioning.org).
### Triggering a release
For each new commit 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.
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.
**semantic-release** offers various ways to control the timing, the content and the audience of published releases.
See example workflows in the following recipes:
**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/release-workflow/distribution-channels.md#publishing-on-distribution-channels)
- [Maintenance releases](docs/recipes/release-workflow/maintenance-releases.md#publishing-maintenance-releases)
- [Pre-releases](docs/recipes/release-workflow/pre-releases.md#publishing-pre-releases)
- [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
@@ -100,8 +96,8 @@ 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)
- A Git CLI version that meets [our version requirement](docs/support/git-version.md) installed in your Continuous Integration environment
- A [Node.js](https://nodejs.org) version that meets [our version requirement](docs/support/node-version.md) installed in your Continuous Integration environment
- 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 [14.17 or higher](docs/support/FAQ.md#why-does-semantic-release-require-node-version--1417) installed in your Continuous Integration environment
## Documentation
@@ -117,9 +113,10 @@ In order to use **semantic-release** you need:
- [Plugins](docs/extending/plugins-list.md)
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
- Recipes
- [CI configurations](docs/recipes/ci-configurations/README.md)
- [Git hosted services](docs/recipes/git-hosted-services/README.md)
- [Release workflow](docs/recipes/release-workflow/README.md)
- [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 development](docs/developer-guide/plugin.md)
@@ -133,19 +130,18 @@ In order to use **semantic-release** you need:
## Get help
- [GitHub Discussions](https://github.com/semantic-release/semantic-release/discussions)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/semantic-release)
- [GitHub Discussions](https://github.com/semantic-release/semantic-release/discussions)
- [Twitter](https://twitter.com/SemanticRelease)
## Badge
Let people know that your package is published using **semantic-release** and which [commit-convention](#commit-message-format) is followed by including this badge in your readme.
Let people know that your package is published using **semantic-release** by including this badge in your readme.
[![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
```md
[![semantic-release: angular](https://img.shields.io/badge/semantic--release-angular-e10079?logo=semantic-release)](https://github.com/semantic-release/semantic-release)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
```
## Team
+7 -13
View File
@@ -14,18 +14,13 @@
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
## Recipes
- [CI configurations](docs/recipes/ci-configurations/README.md)
- [CircleCI 2.0](docs/recipes/ci-configurations/circleci-workflows.md)
- [Travis CI](docs/recipes/ci-configurations/travis.md)
- [GitLab CI](docs/recipes/ci-configurations/gitlab-ci.md)
- [GitHub Actions](docs/recipes/ci-configurations/github-actions.md)
- [Jenkins CI](docs/recipes/ci-configurations/jenkins-ci.md)
- [Git hosted services](docs/recipes/git-hosted-services/README.md)
- [Git authentication with SSH keys](docs/recipes/git-hosted-services/git-auth-ssh-keys.md)
- [Release Workflow](docs/recipes/release-workflow/README.md)
- [Publishing on distribution channels](docs/recipes/release-workflow/distribution-channels.md)
- [Publishing maintenance releases](docs/recipes/release-workflow/maintenance-releases.md)
- [Publishing pre-releases](docs/recipes/release-workflow/pre-releases.md)
- [CI configurations](docs/recipes/README.md#ci-configurations)
- [CircleCI 2.0](docs/recipes/circleci-workflows.md)
- [Travis CI](docs/recipes/travis.md)
- [GitLab CI](docs/recipes/gitlab-ci.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)
## Developer guide
- [JavaScript API](docs/developer-guide/js-api.md)
@@ -38,4 +33,3 @@
- [Troubleshooting](docs/support/troubleshooting.md)
- [Node version requirement](docs/support/node-version.md)
- [Node Support Policy](docs/support/node-support-policy.md)
- [Git version requirement](docs/support/git-version.md)
+9 -15
View File
@@ -1,22 +1,15 @@
#!/usr/bin/env node
/* eslint-disable no-var */
#!/usr/bin/env node// Bad news: We have to write plain ES5 in this file
import semver from 'semver';
import { execa } from 'execa';
import findVersions from 'find-versions';
import cli from '../cli.js';
import {createRequire} from 'node:module';
const require = createRequire(import.meta.url);
const { engines } = require('../package.json');
const { satisfies, lt } = semver;
import execa from 'execa';
import findVersions from 'find-versions';
import pkg from '../package.json';
const MIN_GIT_VERSION = '2.7.1';
if (!satisfies(process.version, engines.node)) {
if (!semver.satisfies(process.version, pkg.engines.node)) {
console.error(
`[semantic-release]: node version ${engines.node} is required. Found ${process.version}.
`[semantic-release]: node version ${pkg.engines.node} is required. Found ${process.version}.
See https://github.com/semantic-release/semantic-release/blob/master/docs/support/node-version.md for more details and solutions.`
);
@@ -26,7 +19,7 @@ See https://github.com/semantic-release/semantic-release/blob/master/docs/suppor
execa('git', ['--version'])
.then(({stdout}) => {
const gitVersion = findVersions(stdout)[0];
if (lt(gitVersion, MIN_GIT_VERSION)) {
if (semver.lt(gitVersion, MIN_GIT_VERSION)) {
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. Found ${gitVersion}.`);
process.exit(1);
}
@@ -37,7 +30,8 @@ execa('git', ['--version'])
process.exit(1);
});
cli()
// Node 10+ from this point on
require('../cli')()
.then((exitCode) => {
process.exitCode = exitCode;
})
+10 -7
View File
@@ -1,7 +1,9 @@
import util from 'node:util';
import util from 'util';
import hideSensitive from './lib/hide-sensitive';
import yargs from 'yargs';
import {hideBin} from 'yargs/helpers';
import hideSensitive from './lib/hide-sensitive.js';
import debug from 'debug';
import run from '.';
const stringList = {
type: 'string',
@@ -13,7 +15,7 @@ const stringList = {
};
export default async () => {
const cli = yargs(hideBin(process.argv))
const cli = yargs
.command('$0', 'Run automated package publishing', (yargs) => {
yargs.demandCommand(0, 0).usage(`Run automated package publishing
@@ -37,6 +39,7 @@ Usage:
.option('debug', {describe: 'Output debugging information', type: 'boolean', group: 'Options'})
.option('d', {alias: 'dry-run', describe: 'Skip publishing', type: 'boolean', group: 'Options'})
.option('h', {alias: 'help', group: 'Options'})
.option('v', {alias: 'version', group: 'Options'})
.strict(false)
.exitProcess(false);
@@ -49,10 +52,10 @@ Usage:
if (options.debug) {
// Debug must be enabled before other requires in order to work
(await import('debug')).default.enable('semantic-release:*');
debug.enable('semantic-release:*');
}
await (await import('./index.js')).default(options);
await run(options);
return 0;
} catch (error) {
if (error.name !== 'YError') {
@@ -61,4 +64,4 @@ Usage:
return 1;
}
}
};
+1 -1
View File
@@ -2,6 +2,6 @@
- [Usage](usage/README.md) - **semantic-release** installation and configuration
- [Extending](extending/README.md) - Extending **semantic-release** with plugins and shareable configurations
- [Recipes](recipes/release-workflow/README.md) - Community written recipes for common **semantic-release** use-cases
- [Recipes](recipes/README.md) - Community written recipes for common **semantic-release** use-cases
- [Developer Guide](developer-guide/README.md) - The essentials of writing a **semantic-release** plugin or shareable configurations
- [Support](support/README.md) - FAQ and troubleshooting
+6 -20
View File
@@ -12,9 +12,9 @@ To create a plugin for `semantic-release`, you need to decide which parts of the
- `success`
- `fail`
`semantic-release` will require the plugin via `node` and look through the required object for methods named like the lifecycles stated above. For example, if your plugin only had a `verifyConditions` and `success` step, the `main` file for your object would need to `export` an object with `verifyConditions` and `success` functions.
`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 `verifyConditions` and `success` step, the `main` file for your object would need to `export` an object with `verifyConditions` and `success` functions.
In addition to the lifecycle methods, each lifecycle is passed two objects:
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.
@@ -34,7 +34,7 @@ We recommend you setup a linting system to ensure good javascript practices are
In your `index.js` file, you can start by writing the following code
```javascript
const verify = require('./src/verify');
const verifyConditions = require('./src/verify');
let verified;
@@ -43,12 +43,12 @@ let verified;
* @param {*} pluginConfig The semantic-release plugin config
* @param {*} context The context provided by semantic-release
*/
async function verifyConditions(pluginConfig, context) {
await verify(pluginConfig, context);
async function verify(pluginConfig, context) {
await verifyConditions(pluginConfig, context);
verified = true;
}
module.exports = { verifyConditions };
module.exports = { verify };
```
Then, in your `src` folder, create a file called `verify.js` and add the following
@@ -237,20 +237,6 @@ if (env.GITHUB_TOKEN) {
//...
}
```
## Logger
Use `context.logger` to provide debug logging in the plugin.
```js
const { logger } = context;
logger.log('Some message from plugin.').
```
The above usage yields the following where `PLUGIN_PACKAGE_NAME` is automatically inferred.
```
[3:24:04 PM] [semantic-release] [PLUGIN_PACKAGE_NAME] › ℹ Some message from plugin.
```
## Execution order
+3 -33
View File
@@ -54,13 +54,12 @@
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag
- [@semantic-release-plus/docker](https://github.com/semantic-release-plus/semantic-release-plus/tree/master/packages/plugins/docker)
- `verifyConditions`: Verify that all needed configuration is present and login to the configured docker registry.
- `publish`: Tag the image specified by `name` with the new version and channel and push it to the configured docker registry.
- `addChannel`: Updates a release published on one channel with the destinations channel tag and pushes to the registry i.e.: next to latest.
- `publish`: Tag the image specified by `name` with the new version, push it to the configured docker registry and update the `latest`, `major`, `minor` tags based on the configuration settings.
- [semantic-release-gcr](https://github.com/carlos-cubas/semantic-release-gcr)
- `verifyConditions`: Verify that all needed configuration is present and login to the Docker registry
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag
- [semantic-release-vsce](https://github.com/raix/semantic-release-vsce)
- `verifyConditions`: Verify the presence and the validity of the "VS Code extension" authentication and release configuration
- `verifyConditions`: Verify the presence and the validity of the vsce authentication and release configuration
- `prepare`: Create a `.vsix` for distribution
- `publish`: Publish the package to the Visual Studio Code marketplace
- [semantic-release-verify-deps](https://github.com/piercus/semantic-release-verify-deps)
@@ -84,7 +83,7 @@
- `prepare`: Changes the version number in the `pom.xml` (or all `pom.xml` files in maven projects with multiple `pom.xml` files) and optionally creates a commit with this version number and pushes it to `master`
- `publish`: Runs `mvn deploy` to deploy to maven central and optionally will update to next snapshot version and merge changes to development branch
- [semantic-release-ado](https://github.com/lluchmk/semantic-release-ado)
- `prepare`: Stores the version number as an Azure DevOps pipeline variable available to downstream steps on the job
- `prepare`: Stores the version number as an Azure DevOps pipeline variable availabe to downstream steps on the job
- [gradle-semantic-release](https://github.com/KengoTODA/gradle-semantic-release-plugin)
- `verifyConditions`: Verify that project has a Gradle wrapper script, and `build.gradle` contains a task to publish artifacts.
- `prepare`: Changes the version number in the `gradle.properties`
@@ -141,32 +140,3 @@
- `verifyConditions`: Validate configuration and verify ```HEROKU_API_KEY```
- `prepare`: Update the package.json version and create release tarball
- `publish`: Publish version to heroku
- [semantic-release-mattermost](https://github.com/ttrobisch/semantic-release-mattermost)
- `verifyConditions`: Verify that the webhook is setup and release-notes-generator is present.
- `success`: Send a message about the new release and its notes to a [mattermost](https://mattermost.com/) webhook.
- [semantic-release-github-milestones](https://github.com/nitzano/semantic-release-github-milestones)
- `verifyConditions`: Verify github tokens are present and valid.
- `verifyRelease`: Display information regarding the matching github milestone.
- [semantic-release-telegram-bot](https://github.com/skoropadas/semantic-release-telegram-bot)
- `verifyConditions`: Validate configuration and verify `TELEGRAM_BOT_TOKEN` and package name
- `success`: Publish a success message to certain telegram chats
- `fail`: Publish a fail message to certain telegram chats
- [semantic-release-npm-deprecate](https://github.com/jpoehnelt/semantic-release-npm-deprecate)
- `publish`: Automatically mark old versions as deprecated.
- [@eshepelyuk/semantic-release-helm-oci](https://github.com/eshepelyuk/semantic-release-helm-oci)
- `verifyConditions`: Verify plugin configuration and login to Helm registry
- `prepare`: Package Helm chart to local folder
- `publish`: Publish Helm chart to OCI registry
- [semantic-release-space](https://github.com/123FLO321/semantic-release-space)
- `verifyConditions` Verifies that all required options are set.
- `prepare` Creates a JetBrains Space Deployment Target if it does not yet exist.
- `publish` Starts a JetBrains Space Deployment.
- `success` Marks the JetBrains Space Deployment as completed.
- `fail` Marks the JetBrains Space Deployment as failed.
- [semantic-release-react-native](https://github.com/alexandermendes/semantic-release-react-native)
- `verifyConditions` Validate configuration.
- `prepare` Version native iOS and Android files.
- [semantic-release-cargo](https://github.com/buehler/semantic-release-cargo)
- `verifyConditions` Validate configuration, `Cargo.toml`, and local cargo executable. Also, logs in into `crates.io`.
- `prepare` Write the new version number into `Cargo.toml` file and perform `cargo check` if configured.
- `publish` Publish the Rust crate to `crates.io`
@@ -6,7 +6,7 @@
## 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`).
- 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`.
@@ -18,3 +18,4 @@
- Updates GitHub release with release-notes.
- Bumps a version in package.json.
- Publishes the new version to [NPM](https://npmjs.org).
+18
View File
@@ -0,0 +1,18 @@
# Recipes
## CI configurations
- [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
-6
View File
@@ -1,6 +0,0 @@
# CI configurations
- [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)
@@ -2,27 +2,24 @@
## Environment variables
The [Authentication](../../usage/ci-configuration.md#authentication) environment variables can be configured in [CircleCi Project Settings](https://circleci.com/docs/2.0/env-vars/#adding-environment-variables-in-the-app)..
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [CircleCi Project Settings](https://circleci.com/docs/2.0/env-vars/#adding-environment-variables-in-the-app)..
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../../usage/getting-started.md#getting-started).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/getting-started.md#getting-started).
## Multiple Node jobs configuration
### `.circleci/config.yml` configuration for multiple Node jobs
This example is a minimal configuration for **semantic-release** with tests running against Node 16 and 14.
See [CircleCI documentation](https://circleci.com/docs/2.0) for additional configuration options.
This example is a minimal configuration for **semantic-release** with tests running against Node 16 and 14. See [CircleCI documentation](https://circleci.com/docs/2.0) for additional configuration options.
In this example, the [`circleci/node`](https://circleci.com/developer/orbs/orb/circleci/node) orb is imported (Which makes some node operations easier), then a `release` job is defined which will run `semantic-release`.
To run our `release` job, we have created a workflow named `test_and_release` which will run two jobs, `node/test`, which comes from the node orb and will test our application, and our release job.
Here, we are actually making use of [matrix jobs](https://circleci.com/blog/circleci-matrix-jobs/) so that our single `node/test` job will actually be executed twice, once for Node version 16, and once for version 14.
Finally, we call our release job with a `requires` parameter so that `release` will run against the latest LTS version of node, only after `node/test` has successfully tested against v14 and v16.
To run our `release` job, we have created a workflow named `test_and_release` which will run two jobs, `node/test`, which comes from the node orb and will test our application, and our release job. Here, we are actually making use of [matrix jobs](https://circleci.com/blog/circleci-matrix-jobs/) so that our single `node/test` job will actually be executed twice, once for Node version 16, and once for version 14. Finally, we call our release job with a `requires` parameter so that `release` will only run after `node/test` has successfully tested against v14 and v16.
```yaml
version: 2.1
orbs:
node: circleci/node@5.0.0
node: circleci/node@4.5
jobs:
release:
executor: node/default
@@ -47,3 +44,15 @@ workflows:
requires:
- node/test
```
### `package.json` configuration for multiple Node jobs
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
"devDependencies": {
"semantic-release": "^18.0.0"
}
}
```
@@ -1,10 +1,10 @@
# 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 feedback before distributing the release to all users.
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']`
- [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
@@ -1,6 +1,6 @@
# Git authentication with SSH keys
When using [environment variables](../../usage/ci-configuration.md#authentication) to set up the Git authentication, the remote Git repository will automatically be accessed via [https](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_http_protocols), independently of the [`repositoryUrl`](../../usage/configuration.md#repositoryurl) format configured in the **semantic-release** [Configuration](../../usage/configuration.md#configuration) (the format will be automatically converted as needed).
When using [environment variables](../usage/ci-configuration.md#authentication) to set up the Git authentication, the remote Git repository will automatically be accessed via [https](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_http_protocols), independently of the [`repositoryUrl`](../usage/configuration.md#repositoryurl) format configured in the **semantic-release** [Configuration](../usage/configuration.md#configuration) (the format will be automatically converted as needed).
Alternatively the Git repository can be accessed via [SSH](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_ssh_protocol) by creating SSH keys, adding the public one to your Git hosted account and making the private one available on the CI environment.
@@ -1,2 +0,0 @@
# Git hosted services
- [Git authentication with SSH keys](git-auth-ssh-keys.md)
@@ -2,7 +2,7 @@
## Environment variables
The [Authentication](../../usage/ci-configuration.md#authentication) environment variables can be configured with [Secret Variables](https://docs.github.com/en/actions/reference/encrypted-secrets).
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 a publish type [`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.
@@ -10,11 +10,11 @@ In this example a publish type [`NPM_TOKEN`](https://docs.npmjs.com/creating-and
[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 a [Node version that meets our version requirement](../../support/node-version.md).
**Note**: The publish pipeline must run on [Node version >= 14.17](../support/FAQ.md#why-does-semantic-release-require-node-version--1417).
### `.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 the latest LTS version of Node when a new commit is pushed to a `master` branch.
The following is a minimal configuration for [`semantic-release`](https://github.com/semantic-release/semantic-release) with a build running on Node 14.17 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
@@ -33,9 +33,9 @@ jobs:
with:
fetch-depth: 0
- name: Setup Node.js
uses: actions/setup-node@v2
uses: actions/setup-node@v1
with:
node-version: 'lts/*'
node-version: '14.17'
- name: Install dependencies
run: npm ci
- name: Release
@@ -2,7 +2,7 @@
## Environment 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).
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.
@@ -10,13 +10,13 @@ The [Authentication](../../usage/ci-configuration.md#authentication) environment
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 version that meets our version requirement](../../support/node-version.md).
**Note**: The publish pipeline must run a [Node >= 14.17 version](../support/FAQ.md#why-does-semantic-release-require-node-version--1417).
### `.gitlab-ci.yml` configuration for Node 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.
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 on whether you are using a [local](../../usage/installation.md#local-installation) or [global](../../usage/installation.md#global-installation) **semantic-release** installation.
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
```yaml
# The release pipeline will run only if all jobs in the test pipeline are successful
@@ -48,9 +48,9 @@ publish:
### `.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.
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.
**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
@@ -66,8 +66,8 @@ release:
- npm install -g semantic-release @semantic-release/gitlab
script:
- semantic-release
rules:
- if: $CI_COMMIT_BRANCH == "master"
only:
- master
release:
image: node:12-buster-slim
@@ -77,13 +77,13 @@ release:
- npm install -g semantic-release @semantic-release/gitlab
script:
- semantic-release
rules:
- if: $CI_COMMIT_BRANCH == "master"
only:
- master
```
### `package.json` configuration
A `package.json` is required only for [local](../../usage/installation.md#local-installation) **semantic-release** installation.
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
@@ -2,19 +2,19 @@
## 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/)..
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).
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 version that [meets our requirement](../../support/node-version.md).
**Note**: The publish pipeline must run a [Node >= 14.17 version](../support/FAQ.md#why-does-semantic-release-require-node-version--1417).
This example is a minimal configuration for **semantic-release** with a build running a version of Node labelled as "node LTS".
Since versions of Node are manually downloaded and labelled, we recommend keeping the version used for the release steps up-to-date with the latest LTS version.
See the [Jenkins documentation](https://www.jenkins.io/doc/) for additional configuration options.
This example is a minimal configuration for **semantic-release** with a build running Node 14.17. 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
@@ -31,11 +31,11 @@ pipeline {
npm install
npm test
'''
}
}
}
stage('Release') {
tools {
nodejs "node LTS"
nodejs "node 14.17"
}
steps {
sh '''
@@ -50,7 +50,7 @@ pipeline {
### `package.json` configuration for a Node job
A `package.json` is required only for [local](../../usage/installation.md#local-installation) **semantic-release** installation.
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
@@ -3,8 +3,8 @@
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']`
- [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
@@ -18,7 +18,7 @@ The Git history of the repository is:
## 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 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`.
@@ -3,8 +3,8 @@
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']`
- [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
-4
View File
@@ -1,4 +0,0 @@
# Release workflow
- [Publishing on distribution channels](distribution-channels.md)
- [Publishing maintenance releases](maintenance-releases.md)
- [Publishing pre-releases](pre-releases.md)
@@ -2,9 +2,9 @@
## Environment variables
The [Authentication](../../usage/ci-configuration.md#authentication) environment variables can be configured in [Travis Repository Settings](https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-Settings) or with the [travis env set CLI](https://github.com/travis-ci/travis.rb#env).
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [Travis Repository Settings](https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-Settings) or with the [travis env set CLI](https://github.com/travis-ci/travis.rb#env).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../../usage/getting-started.md#getting-started).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/getting-started.md#getting-started).
## Node.js projects configuration
@@ -12,7 +12,7 @@ Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with
This example is a minimal configuration for **semantic-release** with a build running Node 14 and 16. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
@@ -43,7 +43,7 @@ jobs:
### `package.json` configuration for multiple Node jobs
A `package.json` is required only for [local](../../usage/installation.md#local-installation) **semantic-release** installation.
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
@@ -57,13 +57,13 @@ A `package.json` is required only for [local](../../usage/installation.md#local-
For projects that require to be tested with one or multiple version of a Non-JavaScript [language](https://docs.travis-ci.com/user/languages), optionally on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
This recipe cover the Travis specifics only. See [Non JavaScript projects recipe](../../support/FAQ.md#can-i-use-semantic-release-to-publish-non-javascript-packages) for more information on the **semantic-release** configuration.
This recipe cover the Travis specifics only. See [Non JavaScript projects recipe](../support/FAQ.md#can-i-use-semantic-release-to-publish-non-javascript-packages) for more information on the **semantic-release** configuration.
### `.travis.yml` configuration for non-JavaScript projects
This example is a minimal configuration for **semantic-release** with a build running [Go 1.6 and 1.7](https://docs.travis-ci.com/user/languages/go). See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
+21 -11
View File
@@ -44,12 +44,12 @@ Yes, **semantic-release** is a Node CLI application, but it can be used to publi
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 a version of Node that [meets our version requirement](./node-version.md) to execute the `semantic-release` command
- 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 >= 14.17](#why-does-semantic-release-require-node-version--1417) to execute the `semantic-release` command
See the [CI configuration recipes](../recipes/release-workflow/README.md#ci-configurations) for more details on specific CI environments.
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
In addition, you will need to configure the **semantic-release** [plugins](../usage/plugins.md#plugins) to disable the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin which is used by default and use a plugin for your project type.
In addition you will need to configure the **semantic-release** [plugins](../usage/plugins.md#plugins) to disable the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin which is used by default and use a plugin for your project type.
If there is no specific plugin for your project type you can use the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin to publish the release with a shell command.
@@ -71,7 +71,7 @@ Here is a basic example to create [GitHub releases](https://help.github.com/arti
**Note**: This is a theoretical example where the command `set-version` update the project version with the value passed as its first argument and `publish-package` publishes the package to a registry.
See the [package managers and languages recipes](../recipes/release-workflow/README.md#package-managers-and-languages) for more details on specific project types.
See the [package managers and languages recipes](../recipes/README.md#package-managers-and-languages) for more details on specific project types.
## Can I use semantic-release with any CI service?
@@ -79,7 +79,7 @@ Yes, **semantic-release** can be used with any CI service, as long as it provide
- A way to set [authentication](../usage/ci-configuration.md#authentication) via environment variables
- A way to guarantee that the `semantic-release` command is [executed only after all the tests of all the jobs in the CI build pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
See the [CI configuration recipes](../recipes/release-workflow/README.md#ci-configurations) for more details on specific CI environments.
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
## Can I run semantic-release on my local machine rather than on a CI server?
@@ -95,7 +95,7 @@ However this is not the recommended approach, as running unit and integration te
Yes, with the [`@semantic-release/gitlab-config`](https://github.com/semantic-release/gitlab-config) shareable configuration.
See the [GitLab CI recipes](../recipes/ci-configurations/gitlab-ci.md#using-semantic-release-with-gitlab-ci) for the CI configuration.
See the [GitLab CI recipes](../recipes/gitlab-ci.md#using-semantic-release-with-gitlab-ci) for the CI configuration.
## Can I use semantic-release with any Git hosted environment?
@@ -153,7 +153,7 @@ Any npm compatible registry is supported with the [`@semantic-release/npm`](http
See [npm registry authentication](https://github.com/semantic-release/npm#npm-registry-authentication) for more details.
See [Artifactory - npm Registry](https://www.jfrog.com/confluence/display/RTF/Npm+Registry#NpmRegistry-AuthenticatingthenpmClient) documentation for Artifactory configuration.
See [Artifactory - npm Registry](https://www.jfrog.com/confluence/display/RTF/Npm+Registry#NpmRegistry-AuthenticatingthenpmClient) documentation for Artifactiry configuration.
## Can I manually trigger the release of a specific version?
@@ -194,15 +194,25 @@ 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.
If your project is under heavy development, with frequent breaking changes, and is not production ready yet we recommend [publishing pre-releases](../recipes/release-workflow/pre-releases.md#publishing-pre-releases).
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`.
## Can I trust semantic-release with my releases?
**semantic-release** has a full unit and integration test suite that tests `npm` publishes against the [verdaccio](https://www.npmjs.com/package/verdaccio).
**semantic-release** has a full unit and integration test suite that tests `npm` publishes against the [npm-registry-couchapp](https://github.com/npm/npm-registry-couchapp).
In addition, the [verify conditions step](../../README.md#release-steps) verifies that all necessary conditions for proceeding with a release are met, and a new release will be performed [only if all your tests pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
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 >= 14.17?
**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 14.17 or higher**.
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?
-4
View File
@@ -1,4 +0,0 @@
# Git version requirement
**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.
+5 -13
View File
@@ -1,21 +1,13 @@
# Node Support Policy
We will always support at least the latest [Long-Term Support](https://github.com/nodejs/Release) version of Node, but provide no promise of support for older versions.
The supported range will always be defined in the `engines.node` property of the `package.json` of our packages.
We only support [Long-Term Support](https://github.com/nodejs/Release) versions of Node starting with [Node 14.17.0 (LTS)](https://nodejs.org/en/blog/release/v14.17.0).
We specifically limit our support to LTS versions of Node, not because this package won't work on other versions, but because we have a limited amount of time, and supporting LTS offers the greatest return on that investment.
It's possible this package will work correctly on newer versions of Node.
It may even be possible to use this package on older versions of Node, though that's more unlikely as we'll make every effort to take advantage of features available in the oldest LTS version we support.
It's possible this package will work correctly on newer versions of Node. It may even be possible to use this package on older versions of Node, though that's more unlikely as we'll make every effort to take advantage of features available in the oldest LTS version we support.
As new Node LTS versions become available we may remove previous versions from the `engines.node` property of our package's `package.json` file.
Removing a Node version is considered a breaking change and will entail the publishing of a new major version of this package.
We will not accept any requests to support an end-of-life version of Node.
Any merge requests or issues supporting an end-of-life version of Node will be closed.
As each Node LTS version reaches its end-of-life we will remove that version from the node engines property of our package's package.json file. Removing a Node version is considered a breaking change and will entail the publishing of a new major version of this package. We will not accept any requests to support an end-of-life version of Node. Any merge requests or issues supporting an end-of-life version of Node will be closed.
We will accept code that allows this package to run on newer, non-LTS, versions of Node.
Furthermore, we will attempt to ensure our own changes work on the latest version of Node.
To help in that commitment, our continuous integration setup runs against all LTS versions of Node in addition the most recent Node release; called current.
We will accept code that allows this package to run on newer, non-LTS, versions of Node. Furthermore, we will attempt to ensure our own changes work on the latest version of Node. To help in that commitment, our continuous integration setup runs against all LTS versions of Node in addition the most recent Node release; called current.
JavaScript package managers should allow you to install this package with any version of Node, with, at most, a warning if your version of Node does not fall within the range specified by our node engines property.
If you encounter issues installing this package, please report the issue to your package manager.
JavaScript package managers should allow you to install this package with any version of Node, with, at most, a warning if your version of Node does not fall within the range specified by our node engines property. If you encounter issues installing this package, please report the issue to your package manager.
+12 -13
View File
@@ -1,38 +1,37 @@
# 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 Node version 14.17 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 14.17 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 version of Node that meets our version requirement.
**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 14.17 or higher.
See our [Node Support Policy](node-support-policy.md) for our long-term promise regarding Node version support.
## Recommended solution
### Run at least one CI job with a version of Node that meets our version requirement
### Run at least one CI job with Node >= 14.17
The recommended approach is to run the `semantic-release` command from a CI job running on the latest available LTS version of node.
This can either be a job used by your project to test on the latest Node LTS version 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 14.17 or higher.
This can either be a job used by your project to test on Node >= 14.17 or a dedicated job for the release steps.
See [CI configuration](../usage/ci-configuration.md) and [CI configuration recipes](../recipes/release-workflow/README.md#ci-configurations) for more details.
See [CI configuration](../usage/ci-configuration.md) and [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
## Alternative solutions
### Use `npx` to execute in the latest LTS version of Node
### Use `npx`
`npx` is included with npm >= 5.2 and can be used to download the latest [Node LTS package published on npm](https://www.npmjs.com/package/node).
`npx` is included with npm >= 5.2 and can be used to download the latest [Node 14 package published on npm](https://www.npmjs.com/package/node).
Use it to execute the `semantic-release` command.
```bash
$ npx -p node@lts -c "npx semantic-release"
$ npx -p node@14 -c "npx semantic-release"
```
**Note**: See [What is npx](./FAQ.md#what-is-npx) for more details.
**Note:**: See [What is npx](./FAQ.md#what-is-npx) for more details.
### Use `nvm`
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can use it to switch to the latest LTS version of Node before running the `semantic-release` command.
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can use it to switch to Node 14.17 before running the `semantic-release` command.
```bash
$ nvm install 'lts/*' && npx semantic-release
$ nvm install 14.17 && npx semantic-release
```
+3 -3
View File
@@ -30,7 +30,7 @@ When [squashing commits](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-Hist
When squashing commits make sure to rewrite the resulting commit message to be compliant with the project's commit message convention.
**Note**: if the resulting squashed commit encompasses multiple changes (for example multiple unrelated features or fixes) then it's probably not a good idea to squash those commits together. A commit should contain exactly one self-contained functional change and a functional change should be contained in exactly one commit. See [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit).
**Note**: if the resulting squashed commit would encompasses multiple changes (for example multiple unrelated features or fixes) then it's probably not a good idea to squash those commits together. A commit should contain exactly one self-contained functional change and a functional change should be contained in exactly one commit. See [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit).
## `reference already exists` error when pushing tag
@@ -63,7 +63,7 @@ After a git history rewrite due to a `git push --force`, the git tags and notes
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 -d :[TAG NAME]`, e.g. `git push origin -d :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`.
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"]}' v2.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"]}'`
3. Re-create the git notes for each release tag, e.g. `git notes --ref semantic-release add -f -m '{"channels":["beta"]}' v2.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 -5
View File
@@ -3,7 +3,7 @@
## Run `semantic-release` only after all tests succeeded
The `semantic-release` command must be executed only after all the tests in the CI build pass. If the build runs multiple jobs (for example to test on multiple Operating Systems or Node versions) the CI has to be configured to guarantee that the `semantic-release` command is executed only after all jobs are successful.
Here are a few examples of the CI services that can be used to achieve this:
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)
@@ -13,7 +13,7 @@ Here are a few examples of the CI services that can be used to achieve this:
- [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/ci-configurations#ci-configurations) for more details.
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
## Authentication
@@ -26,10 +26,10 @@ See [CI configuration recipes](../recipes/ci-configurations#ci-configurations) f
| `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 clarification `user:token` has to be the value of this env. |
| `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-hosted-services/git-auth-ssh-keys.md).
Alternatively the Git authentication can be set up via [SSH keys](../recipes/git-auth-ssh-keys.md).
### Authentication for plugins
@@ -44,6 +44,6 @@ 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/ci-configurations#ci-configurations) for more details on how to configure environment variables in your CI service.
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).
+6 -6
View File
@@ -12,8 +12,8 @@ Additionally, metadata of Git tags generated by **semantic-release** can be cust
## Configuration file
**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`/`.cjs`
- A `release.config.(js|cjs)` file that exports an object
- 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
Alternatively, some options can be set via CLI arguments.
@@ -45,7 +45,7 @@ $ semantic-release --branches next
**Note**: Plugin options cannot be defined via CLI arguments and must be defined in the configuration file.
**Note**: When configuring via `package.json`, the configuration must be under the `release` property. However, when using a `.releaserc` or a `release.config` file, the configuration must be set without a `release` property.
**Note**: When configuring via `package.json`, the configuration must be under the `release` property. However, when using a `.releaserc` or a `release.config.js` file, the configuration must be set without a `release` property.
## Options
@@ -69,8 +69,8 @@ The branches on which releases should happen. By default **semantic-release** wi
- 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
- pre-releases to the `beta` distribution channel from the branch `beta` if it exists
- pre-releases to the `alpha` distribution channel from the branch `alpha` 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.
@@ -116,7 +116,7 @@ Type: `Boolean`<br>
Default: `false` if running in a CI environment, `true` otherwise<br>
CLI arguments: `-d`, `--dry-run`
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, addChannel, success and fail. In addition to this it prints the next version and release notes to the console.
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.
+3 -5
View File
@@ -24,9 +24,7 @@ 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 `npx semantic-release@18`).
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@18`).
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.
+6 -6
View File
@@ -1,12 +1,12 @@
# Workflow configuration
**semantic-release** allow to manage and automate complex release workflow, based on multiple Git branches and distribution channels. This allow to:
- Distribute certain releases to a particular group of users via distribution channels
- 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/release-workflow/README.md#release-workflow) for detailed examples.
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.
@@ -91,7 +91,7 @@ For example the configuration `['master', {name: 'pre/rc', prerelease: '${name.r
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: true}, // `prerelease` is set to `beta` as it is the value of `name`
{name: 'beta', channel: 'beta', prerelease: 'beta'}, // `prerelease` is set to `beta` as it is the value of `name`
]
}
```
@@ -108,7 +108,7 @@ A project must define a minimum of 1 release branch and can have a maximum of 3.
**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/release-workflow/distribution-channels.md) for a detailed example.
See [publishing on distribution channels recipe](../recipes/distribution-channels.md) for a detailed example.
#### Pushing to a release branch
@@ -142,7 +142,7 @@ Maintenance branches are always considered lower than [release branches](#releas
**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/release-workflow/maintenance-releases.md) for a detailed example.
See [publishing maintenance releases recipe](../recipes/maintenance-releases.md) for a detailed example.
#### Pushing to a maintenance branch
@@ -171,7 +171,7 @@ A pre-release branch is characterized by the `prerelease` property that defines
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/release-workflow/pre-releases.md) for a detailed example.
See [publishing pre-releases recipe](../recipes/pre-releases.md) for a detailed example.
#### Pushing to a pre-release branch
+31 -40
View File
@@ -1,50 +1,42 @@
import {createRequire} from 'node:module';
import {pick} from 'lodash-es';
import * as marked from 'marked';
import lodash from 'lodash'
const {pick} = lodash
import marked from 'marked';
import TerminalRenderer from 'marked-terminal';
import envCi from 'env-ci';
import {hookStd} from 'hook-std';
import hookStd from 'hook-std';
import semver from 'semver';
import AggregateError from 'aggregate-error';
import hideSensitive from './lib/hide-sensitive.js';
import getConfig from './lib/get-config.js';
import verify from './lib/verify.js';
import getNextVersion from './lib/get-next-version.js';
import getCommits from './lib/get-commits.js';
import getLastRelease from './lib/get-last-release.js';
import getReleaseToAdd from './lib/get-release-to-add.js';
import {extractErrors, makeTag} from './lib/utils.js';
import getGitAuthUrl from './lib/get-git-auth-url.js';
import getBranches from './lib/branches/index.js';
import getLogger from './lib/get-logger.js';
import {addNote, getGitHead, getTagHead, isBranchUpToDate, push, pushNotes, tag, verifyAuth} from './lib/git.js';
import getError from './lib/get-error.js';
import {COMMIT_EMAIL, COMMIT_NAME} from './lib/definitions/constants.js';
import pkg from './package.json';
import hideSensitive from './lib/hide-sensitive';
import getConfig from './lib/get-config';
import verify from './lib/verify';
import getNextVersion from './lib/get-next-version';
import getCommits from './lib/get-commits';
import getLastRelease from './lib/get-last-release';
import getReleaseToAdd from './lib/get-release-to-add';
import {extractErrors, makeTag} from './lib/utils';
import getGitAuthUrl from './lib/get-git-auth-url';
import getBranches from './lib/branches';
import getLogger from './lib/get-logger';
const require = createRequire(import.meta.url);
const pkg = require('./package.json');
import {verifyAuth, isBranchUpToDate, getGitHead, tag, push, pushNotes, getTagHead, addNote} from './lib/git';
let markedOptionsSet = false;
async function terminalOutput(text) {
if (!markedOptionsSet) {
const {default: TerminalRenderer} = await import('marked-terminal'); // eslint-disable-line node/no-unsupported-features/es-syntax
marked.setOptions({renderer: new TerminalRenderer()});
markedOptionsSet = true;
}
import getError from './lib/get-error';
import {COMMIT_NAME, COMMIT_EMAIL} from './lib/definitions/constants';
return marked.parse(text);
}
marked.setOptions({renderer: new TerminalRenderer()});
/* eslint complexity: off */
async function run(context, plugins) {
const {cwd, env, options, logger, envCi} = context;
const {isCi, branch, prBranch, isPr} = envCi;
const {cwd, env, options, logger} = context;
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.');
options.dryRun = true;
} else {
// When running on CI, set the commits author and committer info and prevent the `git` CLI to prompt for username/password. See #703.
// When running on CI, set the commits author and commiter info and prevent the `git` CLI to prompt for username/password. See #703.
Object.assign(env, {
GIT_AUTHOR_NAME: COMMIT_NAME,
GIT_AUTHOR_EMAIL: COMMIT_EMAIL,
@@ -78,7 +70,7 @@ async function run(context, plugins) {
}
logger[options.dryRun ? 'warn' : 'success'](
`Run automated release from branch ${ciBranch} on repository ${options.originalRepositoryURL}${
`Run automated release from branch ${ciBranch} on repository ${options.repositoryUrl}${
options.dryRun ? ' in dry-run mode' : ''
}`
);
@@ -218,20 +210,20 @@ async function run(context, plugins) {
if (options.dryRun) {
logger.log(`Release note for version ${nextRelease.version}:`);
if (nextRelease.notes) {
context.stdout.write(await terminalOutput(nextRelease.notes));
context.stdout.write(marked(nextRelease.notes));
}
}
return pick(context, ['lastRelease', 'commits', 'nextRelease', 'releases']);
}
async function logErrors({logger, stderr}, err) {
function logErrors({logger, stderr}, err) {
const errors = extractErrors(err).sort((error) => (error.semanticRelease ? -1 : 0));
for (const error of errors) {
if (error.semanticRelease) {
logger.error(`${error.code} ${error.message}`);
if (error.details) {
stderr.write(await terminalOutput(error.details)); // eslint-disable-line no-await-in-loop
stderr.write(marked(error.details));
}
} else {
logger.error('An error occurred while running semantic-release: %O', error);
@@ -245,7 +237,7 @@ async function callFail(context, plugins, err) {
try {
await plugins.fail({...context, errors});
} catch (error) {
await logErrors(context, error);
logErrors(context, error);
}
}
}
@@ -266,7 +258,6 @@ export default async (cliOptions = {}, {cwd = process.cwd(), env = process.env,
context.logger.log(`Running ${pkg.name} version ${pkg.version}`);
try {
const {plugins, options} = await getConfig(context, cliOptions);
options.originalRepositoryURL = options.repositoryUrl;
context.options = options;
try {
const result = await run(context, plugins);
@@ -277,8 +268,8 @@ export default async (cliOptions = {}, {cwd = process.cwd(), env = process.env,
throw error;
}
} catch (error) {
await logErrors(context, error);
logErrors(context, error);
unhook();
throw error;
}
}
};
+3 -2
View File
@@ -1,4 +1,5 @@
import {isString, mapValues, omit, remove, template} from 'lodash-es';
import lodash from 'lodash'
const {isString, remove, omit, mapValues, template} = lodash
import micromatch from 'micromatch';
import {getBranches} from '../git.js';
@@ -15,4 +16,4 @@ export default async (repositoryUrl, {cwd}, branches) => {
],
[]
);
}
};
+6 -7
View File
@@ -1,11 +1,10 @@
import {escapeRegExp, template} from 'lodash-es';
import lodash from 'lodash'
const {template, escapeRegExp} = lodash
import semver from 'semver';
import pReduce from 'p-reduce';
import debugTags from 'debug';
import {getNote, getTags} from '../../lib/git.js';
const debug = debugTags('semantic-release:get-tags');
import debugFactory from 'debug';
const debug = debugFactory('semantic-release:get-tags');
import {getTags, getNote} from '../../lib/git.js';
export default async ({cwd, env, options: {tagFormat}}, branches) => {
// Generate a regex to parse tags formatted with `tagFormat`
@@ -33,4 +32,4 @@ export default async ({cwd, env, options: {tagFormat}}, branches) => {
},
[]
);
}
};
+5 -5
View File
@@ -1,12 +1,13 @@
import {isRegExp, isString} from 'lodash-es';
import lodash from 'lodash'
const {isString, isRegExp} = lodash
import AggregateError from 'aggregate-error';
import pEachSeries from 'p-each-series';
import * as DEFINITIONS from '../definitions/branches.js';
import DEFINITIONS from '../definitions/branches.js';
import getError from '../get-error.js';
import {fetch, fetchNotes, verifyBranchName} from '../git.js';
import expand from './expand.js';
import getTags from './get-tags.js';
import * as normalize from './normalize.js';
import normalize from './normalize.js';
export default async (repositoryUrl, ciBranch, context) => {
const {cwd, env} = context;
@@ -27,7 +28,6 @@ export default async (repositoryUrl, ciBranch, context) => {
const errors = [];
const branchesByType = Object.entries(DEFINITIONS).reduce(
// eslint-disable-next-line unicorn/no-fn-reference-in-iterator
(branchesByType, [type, {filter}]) => ({[type]: branches.filter(filter), ...branchesByType}),
{}
);
@@ -68,4 +68,4 @@ export default async (repositoryUrl, ciBranch, context) => {
}
return [...result.maintenance, ...result.release, ...result.prerelease];
}
};
+22 -10
View File
@@ -1,18 +1,21 @@
import {isNil, sortBy} from 'lodash-es';
import lodash from 'lodash'
const {sortBy, isNil} = lodash
import semverDiff from 'semver-diff';
import {FIRST_RELEASE, RELEASE_TYPE} from '../definitions/constants.js';
import {
getFirstVersion,
getLatestVersion,
getLowerBound, getRange,
getUpperBound,
highest,
tagsToVersions,
isMajorRange,
getUpperBound,
getLowerBound,
highest,
lowest,
tagsToVersions
getLatestVersion,
getFirstVersion,
getRange,
} from '../utils.js';
export function maintenance({maintenance, release}) {
function maintenance({maintenance, release}) {
return sortBy(
maintenance.map(({name, range, channel, ...rest}) => ({
...rest,
@@ -54,7 +57,7 @@ export function maintenance({maintenance, release}) {
});
}
export function release({release}) {
function release({release}) {
if (release.length === 0) {
return release;
}
@@ -88,7 +91,7 @@ export function release({release}) {
});
}
export function prerelease({prerelease}) {
function prerelease({prerelease}) {
return prerelease.map(({name, prerelease, channel, tags, ...rest}) => {
const preid = prerelease === true ? name : prerelease;
return {
@@ -101,3 +104,12 @@ export function prerelease({prerelease}) {
};
});
}
const exported = {
maintenance,
release,
prerelease,
};
export default exported;
export {maintenance, release, prerelease};
+14 -5
View File
@@ -1,22 +1,31 @@
import {isNil, uniqBy} from 'lodash-es';
import lodash from 'lodash'
const {isNil, uniqBy} = lodash
import semver from 'semver';
import {isMaintenanceRange} from '../utils.js';
export const maintenance = {
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,
};
export const prerelease = {
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,
};
export const release = {
// eslint-disable-next-line unicorn/no-fn-reference-in-iterator
const release = {
filter: (branch) => !maintenance.filter(branch) && !prerelease.filter(branch),
branchesValidator: (branches) => branches.length <= 3 && branches.length > 0,
};
const exported = {
maintenance,
prerelease,
release,
};
export default exported;
export {maintenance, prerelease, release};
+34 -9
View File
@@ -1,17 +1,42 @@
export const RELEASE_TYPE = ['patch', 'minor', 'major'];
const RELEASE_TYPE = ['patch', 'minor', 'major'];
export const FIRST_RELEASE = '1.0.0';
const FIRST_RELEASE = '1.0.0';
export const FIRSTPRERELEASE = '1';
const FIRSTPRERELEASE = '1';
export const COMMIT_NAME = 'semantic-release-bot';
const COMMIT_NAME = 'semantic-release-bot';
export const COMMIT_EMAIL = 'semantic-release-bot@martynus.net';
const COMMIT_EMAIL = 'semantic-release-bot@martynus.net';
export const RELEASE_NOTES_SEPARATOR = '\n\n';
const RELEASE_NOTES_SEPARATOR = '\n\n';
export const SECRET_REPLACEMENT = '[secure]';
const SECRET_REPLACEMENT = '[secure]';
export const SECRET_MIN_SIZE = 5;
const SECRET_MIN_SIZE = 5;
export const GIT_NOTE_REF = 'semantic-release';
const GIT_NOTE_REF = 'semantic-release';
const exported = {
RELEASE_TYPE,
FIRST_RELEASE,
FIRSTPRERELEASE,
COMMIT_NAME,
COMMIT_EMAIL,
RELEASE_NOTES_SEPARATOR,
SECRET_REPLACEMENT,
SECRET_MIN_SIZE,
GIT_NOTE_REF,
};
export default exported;
export {
RELEASE_TYPE,
FIRST_RELEASE,
FIRSTPRERELEASE,
COMMIT_NAME,
COMMIT_EMAIL,
RELEASE_NOTES_SEPARATOR,
SECRET_REPLACEMENT,
SECRET_MIN_SIZE,
GIT_NOTE_REF,
};
+82 -99
View File
@@ -1,11 +1,9 @@
import {inspect} from 'node:util';
import {createRequire} from 'node:module';
import {isString, toLower, trim} from 'lodash-es';
import {inspect} from 'util';
import lodash from 'lodash'
const {toLower, isString, trim} = lodash
import pkg from '../../package.json';
import {RELEASE_TYPE} from './constants.js';
const require = createRequire(import.meta.url);
const pkg = require('../../package.json');
const [homepage] = pkg.homepage.split('#');
const stringify = (object) =>
isString(object) ? object : inspect(object, {breakLength: Infinity, depth: 2, maxArrayLength: 5});
@@ -13,19 +11,17 @@ 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])}`;
export function ENOGITREPO({cwd}) {
return {
const exported = {
ENOGITREPO: ({cwd}) => ({
message: 'Not running from a git repository.',
details: `The \`semantic-release\` command must be executed from a Git repository.
The current working directory is \`${cwd}\`.
Please verify your CI configuration to make sure the \`semantic-release\` command is executed from the root of the cloned repository.`,
};
}
}),
export function ENOREPOURL() {
return {
ENOREPOURL: () => ({
message: 'The `repositoryUrl` option is required.',
details: `The [repositoryUrl option](${linkify(
'docs/usage/configuration.md#repositoryurl'
@@ -34,11 +30,9 @@ export function ENOREPOURL() {
Please make sure to add the \`repositoryUrl\` to the [semantic-release configuration] (${linkify(
'docs/usage/configuration.md'
)}).`,
};
}
}),
export function EGITNOPERMISSION({options: {repositoryUrl}, branch: {name}}) {
return {
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}\`.
@@ -46,57 +40,47 @@ 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'
)})`,
};
}
'docs/usage/ci-configuration.md#authentication'
)})`,
}),
export function EINVALIDTAGFORMAT({options: {tagFormat}}) {
return {
EINVALIDTAGFORMAT: ({options: {tagFormat}}) => ({
message: 'Invalid `tagFormat` option.',
details: `The [tagFormat](${linkify(
'docs/usage/configuration.md#tagformat'
)}) must compile to a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description).
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
};
}
}),
export function ETAGNOVERSION({options: {tagFormat}}) {
return {
ETAGNOVERSION: ({options: {tagFormat}}) => ({
message: 'Invalid `tagFormat` option.',
details: `The [tagFormat](${linkify(
'docs/usage/configuration.md#tagformat'
)}) option must contain the variable \`version\` exactly once.
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
};
}
}),
export function EPLUGINCONF({type, required, pluginConf}) {
return {
EPLUGINCONF: ({type, required, pluginConf}) => ({
message: `The \`${type}\` plugin configuration is invalid.`,
details: `The [${type} plugin configuration](${linkify(`docs/usage/plugins.md#${toLower(type)}-plugin`)}) ${
required ? 'is required and ' : ''
} must be a single or an array of plugins definition. A plugin definition is an npm module name, optionally wrapped in an array with an object.
Your configuration for the \`${type}\` plugin is \`${stringify(pluginConf)}\`.`,
};
}
}),
export function EPLUGINSCONF({plugin}) {
return {
EPLUGINSCONF: ({plugin}) => ({
message: 'The `plugins` configuration is invalid.',
details: `The [plugins](${linkify(
'docs/usage/configuration.md#plugins'
)}) option must be an array of plugin definitions. A plugin definition is an npm module name, optionally wrapped in an array with an object.
)}) option must be an array of plugin definions. A plugin definition is an npm module name, optionally wrapped in an array with an object.
The invalid configuration is \`${stringify(plugin)}\`.`,
};
}
}),
export function EPLUGIN({pluginName, type}) {
return {
EPLUGIN: ({pluginName, type}) => ({
message: `A plugin configured in the step ${type} is not a valid semantic-release plugin.`,
details: `A valid \`${type}\` **semantic-release** plugin must be a function or an object with a function in the property \`${type}\`.
@@ -105,11 +89,9 @@ The plugin \`${pluginName}\` doesn't have the property \`${type}\` and cannot be
Please refer to the \`${pluginName}\` and [semantic-release plugins configuration](${linkify(
'docs/usage/plugins.md'
)}) documentation for more details.`,
};
}
}),
export function EANALYZECOMMITSOUTPUT({result, pluginName}) {
return {
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}\``
@@ -124,11 +106,9 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
'docs/developer-guide/plugin.md'
)})`,
};
}
}),
export function EGENERATENOTESOUTPUT({result, pluginName}) {
return {
EGENERATENOTESOUTPUT: ({result, pluginName}) => ({
message: 'The `generateNotes` plugin returned an invalid value. It must return a `String`.',
details: `The \`generateNotes\` plugin must return a \`String\`.
@@ -141,11 +121,9 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
'docs/developer-guide/plugin.md'
)})`,
};
}
}),
export function EPUBLISHOUTPUT({result, pluginName}) {
return {
EPUBLISHOUTPUT: ({result, pluginName}) => ({
message: 'A `publish` plugin returned an invalid value. It must return an `Object`.',
details: `The \`publish\` plugins must return an \`Object\`.
@@ -158,11 +136,9 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
'docs/developer-guide/plugin.md'
)})`,
};
}
}),
export function EADDCHANNELOUTPUT({result, pluginName}) {
return {
EADDCHANNELOUTPUT: ({result, pluginName}) => ({
message: 'A `addChannel` plugin returned an invalid value. It must return an `Object`.',
details: `The \`addChannel\` plugins must return an \`Object\`.
@@ -175,66 +151,54 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
'docs/developer-guide/plugin.md'
)})`,
};
}
}),
export function EINVALIDBRANCH({branch}) {
return {
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)}\`.`,
};
}
}),
export function EINVALIDBRANCHNAME({branch}) {
return {
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)}\`.`,
};
}
}),
export function EDUPLICATEBRANCHES({duplicates}) {
return {
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)}\`.`,
};
}
}),
export function EMAINTENANCEBRANCH({branch}) {
return {
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)}\`.`,
};
}
}),
export function EMAINTENANCEBRANCHES({branches}) {
return {
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)}\`.`,
};
}
}),
export function ERELEASEBRANCHES({branches}) {
return {
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'
@@ -243,33 +207,27 @@ export function ERELEASEBRANCHES({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)}\`.`,
};
}
}),
export function EPRERELEASEBRANCH({branch}) {
return {
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)}\`.`,
};
}
}),
export function EPRERELEASEBRANCHES({branches}) {
return {
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)}\`.`,
};
}
}),
export function EINVALIDNEXTVERSION({nextRelease: {version}, branch: {name, range}, commits, validBranches}) {
return {
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}\`.
@@ -277,22 +235,47 @@ The following commit${commits.length > 1 ? 's are' : ' is'} responsible for the
${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).
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.`,
};
}
}),
export function EINVALIDMAINTENANCEMERGE({nextRelease: {channel, gitTag, version}, branch: {mergeRange, name}}) {
return {
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.`,
};
}
}),
};
export default exported;
export const {
ENOGITREPO,
ENOREPOURL,
EGITNOPERMISSION,
EINVALIDTAGFORMAT,
ETAGNOVERSION,
EPLUGINCONF,
EPLUGINSCONF,
EPLUGIN,
EANALYZECOMMITSOUTPUT,
EGENERATENOTESOUTPUT,
EPUBLISHOUTPUT,
EADDCHANNELOUTPUT,
EINVALIDBRANCH,
EINVALIDBRANCHNAME,
EDUPLICATEBRANCHES,
EMAINTENANCEBRANCH,
EMAINTENANCEBRANCHES,
ERELEASEBRANCHES,
EPRERELEASEBRANCH,
EPRERELEASEBRANCHES,
EINVALIDNEXTVERSION,
EINVALIDMAINTENANCEMERGE,
} = exported;
+26 -4
View File
@@ -1,17 +1,18 @@
/* eslint require-atomic-updates: off */
import lodash from 'lodash'
const {isString, isPlainObject} = lodash
import {isPlainObject, isString} from 'lodash-es';
import {getGitHead} from '../git.js';
import hideSensitive from '../hide-sensitive.js';
import {hideSensitiveValues} from '../utils.js';
import {RELEASE_NOTES_SEPARATOR, RELEASE_TYPE} from './constants.js';
import {RELEASE_TYPE, RELEASE_NOTES_SEPARATOR} from './constants.js';
export default {
const exported = {
verifyConditions: {
required: false,
dryRun: true,
pipelineConfig: () => ({settleAll: true}),
},
analyzeCommits: {
default: ['@semantic-release/commit-analyzer'],
required: true,
@@ -29,11 +30,13 @@ export default {
}, -1)
],
},
verifyRelease: {
required: false,
dryRun: true,
pipelineConfig: () => ({settleAll: true}),
},
generateNotes: {
required: false,
dryRun: true,
@@ -49,6 +52,7 @@ export default {
}),
postprocess: (results, {env}) => hideSensitive(env)(results.filter(Boolean).join(RELEASE_NOTES_SEPARATOR)),
},
prepare: {
required: false,
dryRun: false,
@@ -67,6 +71,7 @@ export default {
},
}),
},
publish: {
required: false,
dryRun: false,
@@ -80,6 +85,7 @@ export default {
}),
}),
},
addChannel: {
required: false,
dryRun: false,
@@ -93,12 +99,14 @@ export default {
}),
}),
},
success: {
required: false,
dryRun: false,
pipelineConfig: () => ({settleAll: true}),
preprocess: ({releases, env, ...inputs}) => ({...inputs, env, releases: hideSensitiveValues(env, releases)}),
},
fail: {
required: false,
dryRun: false,
@@ -106,3 +114,17 @@ export default {
preprocess: ({errors, env, ...inputs}) => ({...inputs, env, errors: hideSensitiveValues(env, errors)}),
},
};
export default exported;
export const {
verifyConditions,
analyzeCommits,
verifyRelease,
generateNotes,
prepare,
publish,
addChannel,
success,
fail,
} = exported;
+3 -4
View File
@@ -1,8 +1,7 @@
import debugCommits from 'debug';
import debugFactory from 'debug';
const debug = debugFactory('semantic-release:get-commits');
import {getCommits} from './git.js';
const debug = debugCommits('semantic-release:get-commits');
/**
* 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.
*
@@ -22,4 +21,4 @@ export default async ({cwd, env, lastRelease: {gitHead: from}, nextRelease: {git
logger.log(`Found ${commits.length} commits since last release`);
debug('Parsed commits: %o', commits);
return commits;
}
};
+13 -20
View File
@@ -1,20 +1,14 @@
import {dirname, resolve} from 'node:path';
import {fileURLToPath} from 'node:url';
import {createRequire} from 'node:module';
import {castArray, isNil, isPlainObject, isString, pickBy} from 'lodash-es';
import {readPackageUp} from 'read-pkg-up';
import lodash from 'lodash'
const {castArray, pickBy, isNil, isString, isPlainObject} = lodash
import readPkgUp from 'read-pkg-up';
import {cosmiconfig} from 'cosmiconfig';
import resolveFrom from 'resolve-from';
import debugConfig from 'debug';
import debugFactory from 'debug';
const debug = debugFactory('semantic-release:config');
import {repoUrl} from './git.js';
import PLUGINS_DEFINITIONS from './definitions/plugins.js';
import plugins from './plugins/index.js';
import {parseConfig, validatePlugin} from './plugins/utils.js';
const debug = debugConfig('semantic-release:config');
const __dirname = dirname(fileURLToPath(import.meta.url));
const require = createRequire(import.meta.url);
import plugins from './plugins';
import {validatePlugin, parseConfig} from './plugins/utils.js';
const CONFIG_NAME = 'release';
@@ -33,12 +27,11 @@ export default async (context, cliOptions) => {
if (extendPaths) {
// If `extends` is defined, load and merge each shareable config with `options`
options = {
...await (castArray(extendPaths).reduce(async(eventualResult, extendPath) => {
const result = await eventualResult;
...castArray(extendPaths).reduce((result, 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 relative to the config file
// so those plugin will be loaded relatively to the config file
Object.entries(extendsOptions)
.filter(([, value]) => Boolean(value))
.reduce((pluginsPath, [option, value]) => {
@@ -56,7 +49,7 @@ export default async (context, cliOptions) => {
}, pluginsPath);
return {...result, ...extendsOptions};
}, {})),
}, {}),
...options,
};
}
@@ -79,7 +72,7 @@ export default async (context, cliOptions) => {
'@semantic-release/npm',
'@semantic-release/github',
],
// Remove `null` and `undefined` options, so they can be replaced with default ones
// Remove `null` and `undefined` options so they can be replaced with default ones
...pickBy(options, (option) => !isNil(option)),
...(options.branches ? {branches: castArray(options.branches)} : {}),
};
@@ -91,9 +84,9 @@ export default async (context, cliOptions) => {
debug('options values: %O', options);
return {options, plugins: await plugins({...context, options}, pluginsPath)};
}
};
async function pkgRepoUrl(options) {
const {packageJson} = (await readPackageUp(options)) || {};
const {packageJson} = (await readPkgUp(options)) || {};
return packageJson && (isPlainObject(packageJson.repository) ? packageJson.repository.url : packageJson.repository);
}
+2 -2
View File
@@ -1,7 +1,7 @@
import SemanticReleaseError from '@semantic-release/error';
import * as ERROR_DEFINITIONS from './definitions/errors.js';
import ERROR_DEFINITIONS from './definitions/errors.js';
export default (code, ctx = {}) => {
const {message, details} = ERROR_DEFINITIONS[code](ctx);
return new SemanticReleaseError(message, code, details);
}
};
+9 -9
View File
@@ -1,10 +1,10 @@
import {format, parse} from 'node:url';
import {isNil} from 'lodash-es';
import {format} from 'url';
import lodash from 'lodash'
const {isNil} = lodash
import hostedGitInfo from 'hosted-git-info';
import debugAuthUrl from 'debug';
import {verifyAuth} from './git.js';
const debug = debugAuthUrl('semantic-release:get-git-auth-url');
import debugFactory from 'debug';
const debug = debugFactory('semantic-release:get-git-auth-url');
/**
* Machinery to format a repository URL with the given credentials
@@ -18,7 +18,7 @@ const debug = debugAuthUrl('semantic-release:get-git-auth-url');
function formatAuthUrl(protocol, repositoryUrl, gitCredentials) {
const [match, auth, host, basePort, path] =
/^(?!.+:\/\/)(?:(?<auth>.*)@)?(?<host>.*?):(?<port>\d+)?:?\/?(?<path>.*)$/.exec(repositoryUrl) || [];
const {port, hostname, ...parsed} = parse(
const {port, hostname, ...parsed} = new URL(
match ? `ssh://${auth ? `${auth}@` : ''}${host}${basePort ? `:${basePort}` : ''}/${path}` : repositoryUrl
);
@@ -77,7 +77,7 @@ export default async (context) => {
let {repositoryUrl} = context.options;
const info = hostedGitInfo.fromUrl(repositoryUrl, {noGitPlus: true});
const {protocol, ...parsed} = parse(repositoryUrl);
const {protocol, ...parsed} = new URL(repositoryUrl);
if (info && info.getDefaultRepresentation() === 'shortcut') {
// Expand shorthand URLs (such as `owner/repo` or `gitlab:owner/repo`)
@@ -91,7 +91,7 @@ export default async (context) => {
try {
debug('Verifying ssh auth by attempting to push to %s', repositoryUrl);
await verifyAuth(repositoryUrl, branch.name, {cwd, env});
} catch {
} catch (_) {
debug('SSH key auth failed, falling back to https.');
const envVars = Object.keys(GIT_TOKENS).filter((envVar) => !isNil(env[envVar]));
@@ -121,4 +121,4 @@ export default async (context) => {
}
return repositoryUrl;
}
};
+5 -4
View File
@@ -1,6 +1,7 @@
import {isUndefined} from 'lodash-es';
import lodash from 'lodash'
const {isUndefined} = lodash
import semver from 'semver';
import {isSameChannel, makeTag} from './utils.js';
import {makeTag, isSameChannel} from './utils.js';
/**
* Last release.
@@ -18,7 +19,7 @@ import {isSameChannel, makeTag} from './utils.js';
*
* - Filter out the branch tags that are not valid semantic version
* - Sort the versions
* - Retrieve the highest version
* - Retrive the highest version
*
* @param {Object} context semantic-release context.
* @param {Object} params Function parameters.
@@ -41,4 +42,4 @@ export default ({branch, options: {tagFormat}}, {before} = {}) => {
}
return {};
}
};
+2 -4
View File
@@ -1,8 +1,6 @@
import signale from 'signale';
import {Signale} from 'signale';
import figures from 'figures';
const {Signale} = signale;
export default ({stdout, stderr}) =>
new Signale({
config: {displayTimestamp: true, underlineMessage: false, displayLabel: false},
@@ -15,4 +13,4 @@ export default ({stdout, stderr}) =>
log: {badge: figures.info, color: 'magenta', label: '', stream: [stdout]},
success: {badge: figures.tick, color: 'green', label: '', stream: [stdout]},
},
})
});
+2 -2
View File
@@ -1,6 +1,6 @@
import semver from 'semver';
import {FIRST_RELEASE, FIRSTPRERELEASE} from './definitions/constants.js';
import {getLatestVersion, highest, isSameChannel, tagsToVersions} from './utils.js';
import {isSameChannel, getLatestVersion, tagsToVersions, highest} from './utils.js';
export default ({branch, nextRelease: {type, channel}, lastRelease, logger}) => {
let version;
@@ -32,4 +32,4 @@ export default ({branch, nextRelease: {type, channel}, lastRelease, logger}) =>
}
return version;
}
};
+4 -3
View File
@@ -1,8 +1,9 @@
import {intersection, uniqBy} from 'lodash-es';
import lodash from 'lodash'
const {uniqBy, intersection} = lodash
import semver from 'semver';
import semverDiff from 'semver-diff';
import getLastRelease from './get-last-release.js';
import {getLowerBound, makeTag} from './utils.js';
import {makeTag, getLowerBound} from './utils.js';
/**
* Find releases that have been merged from from a higher branch but not added on the channel of the current branch.
@@ -57,4 +58,4 @@ export default (context) => {
},
};
}
}
};
+69 -25
View File
@@ -1,11 +1,10 @@
import gitLogParser from 'git-log-parser';
import getStream from 'get-stream';
import {execa} from 'execa';
import debugGit from 'debug';
import execa from 'execa';
import debugFactory from 'debug';
const debug = debugFactory('semantic-release:git');
import {GIT_NOTE_REF} from './definitions/constants.js';
const debug = debugGit('semantic-release:git');
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
/**
@@ -16,7 +15,7 @@ Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', commi
*
* @return {String} The commit sha of the tag in parameter or `null`.
*/
export async function getTagHead(tagName, execaOptions) {
async function getTagHead(tagName, execaOptions) {
return (await execa('git', ['rev-list', '-1', tagName], execaOptions)).stdout;
}
@@ -29,7 +28,7 @@ export async function getTagHead(tagName, execaOptions) {
* @return {Array<String>} List of git tags.
* @throws {Error} If the `git` command fails.
*/
export async function getTags(branch, execaOptions) {
async function getTags(branch, execaOptions) {
return (await execa('git', ['tag', '--merged', branch], execaOptions)).stdout
.split('\n')
.map((tag) => tag.trim())
@@ -44,7 +43,7 @@ export async function getTags(branch, execaOptions) {
* @param {Object} [execaOpts] Options to pass to `execa`.
* @return {Promise<Array<Object>>} The list of commits between `from` and `to`.
*/
export async function getCommits(from, to, execaOptions) {
async function getCommits(from, to, execaOptions) {
return (
await getStream.array(
gitLogParser.parse(
@@ -64,7 +63,7 @@ export async function getCommits(from, to, execaOptions) {
* @return {Array<String>} List of git branches.
* @throws {Error} If the `git` command fails.
*/
export async function getBranches(repositoryUrl, execaOptions) {
async function getBranches(repositoryUrl, execaOptions) {
return (await execa('git', ['ls-remote', '--heads', repositoryUrl], execaOptions)).stdout
.split('\n')
.filter(Boolean)
@@ -79,7 +78,7 @@ export async function getBranches(repositoryUrl, execaOptions) {
*
* @return {Boolean} `true` if the reference exists, falsy otherwise.
*/
export async function isRefExists(ref, execaOptions) {
async function isRefExists(ref, execaOptions) {
try {
return (await execa('git', ['rev-parse', '--verify', ref], execaOptions)).exitCode === 0;
} catch (error) {
@@ -101,7 +100,7 @@ export async function isRefExists(ref, execaOptions) {
* @param {String} branch The repository branch to fetch.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function fetch(repositoryUrl, branch, ciBranch, execaOptions) {
async function fetch(repositoryUrl, branch, ciBranch, execaOptions) {
const isDetachedHead =
(await execa('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {...execaOptions, reject: false})).stdout === 'HEAD';
@@ -118,7 +117,7 @@ export async function fetch(repositoryUrl, branch, ciBranch, execaOptions) {
],
execaOptions
);
} catch {
} catch (_) {
await execa(
'git',
[
@@ -139,14 +138,14 @@ export async function fetch(repositoryUrl, branch, ciBranch, execaOptions) {
* @param {String} repositoryUrl The remote repository URL.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function fetchNotes(repositoryUrl, execaOptions) {
async function fetchNotes(repositoryUrl, execaOptions) {
try {
await execa(
'git',
['fetch', '--unshallow', repositoryUrl, `+refs/notes/${GIT_NOTE_REF}:refs/notes/${GIT_NOTE_REF}`],
execaOptions
);
} catch {
} catch (_) {
await execa('git', ['fetch', repositoryUrl, `+refs/notes/${GIT_NOTE_REF}:refs/notes/${GIT_NOTE_REF}`], {
...execaOptions,
reject: false,
@@ -161,7 +160,7 @@ export async function fetchNotes(repositoryUrl, execaOptions) {
*
* @return {String} the sha of the HEAD commit.
*/
export async function getGitHead(execaOptions) {
async function getGitHead(execaOptions) {
return (await execa('git', ['rev-parse', 'HEAD'], execaOptions)).stdout;
}
@@ -172,7 +171,7 @@ export async function getGitHead(execaOptions) {
*
* @return {string} The value of the remote git URL.
*/
export async function repoUrl(execaOptions) {
async function repoUrl(execaOptions) {
try {
return (await execa('git', ['config', '--get', 'remote.origin.url'], execaOptions)).stdout;
} catch (error) {
@@ -187,7 +186,7 @@ export async function repoUrl(execaOptions) {
*
* @return {Boolean} `true` if the current working directory is in a git repository, falsy otherwise.
*/
export async function isGitRepo(execaOptions) {
async function isGitRepo(execaOptions) {
try {
return (await execa('git', ['rev-parse', '--git-dir'], execaOptions)).exitCode === 0;
} catch (error) {
@@ -204,7 +203,7 @@ export async function isGitRepo(execaOptions) {
*
* @throws {Error} if not authorized to push.
*/
export async function verifyAuth(repositoryUrl, branch, execaOptions) {
async function verifyAuth(repositoryUrl, branch, execaOptions) {
try {
await execa('git', ['push', '--dry-run', '--no-verify', repositoryUrl, `HEAD:${branch}`], execaOptions);
} catch (error) {
@@ -222,7 +221,7 @@ export async function verifyAuth(repositoryUrl, branch, execaOptions) {
*
* @throws {Error} if the tag creation failed.
*/
export async function tag(tagName, ref, execaOptions) {
async function tag(tagName, ref, execaOptions) {
await execa('git', ['tag', tagName, ref], execaOptions);
}
@@ -234,7 +233,7 @@ export async function tag(tagName, ref, execaOptions) {
*
* @throws {Error} if the push failed.
*/
export async function push(repositoryUrl, execaOptions) {
async function push(repositoryUrl, execaOptions) {
await execa('git', ['push', '--tags', repositoryUrl], execaOptions);
}
@@ -246,7 +245,7 @@ export async function push(repositoryUrl, execaOptions) {
*
* @throws {Error} if the push failed.
*/
export async function pushNotes(repositoryUrl, execaOptions) {
async function pushNotes(repositoryUrl, execaOptions) {
await execa('git', ['push', repositoryUrl, `refs/notes/${GIT_NOTE_REF}`], execaOptions);
}
@@ -258,7 +257,7 @@ export async function pushNotes(repositoryUrl, execaOptions) {
*
* @return {Boolean} `true` if valid, falsy otherwise.
*/
export async function verifyTagName(tagName, execaOptions) {
async function verifyTagName(tagName, execaOptions) {
try {
return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOptions)).exitCode === 0;
} catch (error) {
@@ -274,7 +273,7 @@ export async function verifyTagName(tagName, execaOptions) {
*
* @return {Boolean} `true` if valid, falsy otherwise.
*/
export async function verifyBranchName(branch, execaOptions) {
async function verifyBranchName(branch, execaOptions) {
try {
return (await execa('git', ['check-ref-format', `refs/heads/${branch}`], execaOptions)).exitCode === 0;
} catch (error) {
@@ -291,7 +290,7 @@ export async function verifyBranchName(branch, execaOptions) {
*
* @return {Boolean} `true` is the HEAD of the current local branch is the same as the HEAD of the remote branch, falsy otherwise.
*/
export async function isBranchUpToDate(repositoryUrl, branch, execaOptions) {
async function isBranchUpToDate(repositoryUrl, branch, execaOptions) {
return (
(await getGitHead(execaOptions)) ===
(await execa('git', ['ls-remote', '--heads', repositoryUrl, branch], execaOptions)).stdout.match(/^(?<ref>\w+)?/)[1]
@@ -306,7 +305,7 @@ export async function isBranchUpToDate(repositoryUrl, branch, execaOptions) {
*
* @return {Object} the parsed JSON note if there is one, an empty object otherwise.
*/
export async function getNote(ref, execaOptions) {
async function getNote(ref, execaOptions) {
try {
return JSON.parse((await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'show', ref], execaOptions)).stdout);
} catch (error) {
@@ -326,6 +325,51 @@ export async function getNote(ref, execaOptions) {
* @param {String} ref The Git reference to add the note to.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function addNote(note, ref, execaOptions) {
async function addNote(note, ref, execaOptions) {
await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'add', '-f', '-m', JSON.stringify(note), ref], execaOptions);
}
const exported = {
getTagHead,
getTags,
getCommits,
getBranches,
isRefExists,
fetch,
fetchNotes,
getGitHead,
repoUrl,
isGitRepo,
verifyAuth,
tag,
push,
pushNotes,
verifyTagName,
isBranchUpToDate,
verifyBranchName,
getNote,
addNote,
};
export default exported;
export {
getTagHead,
getTags,
getCommits,
getBranches,
isRefExists,
fetch,
fetchNotes,
getGitHead,
repoUrl,
isGitRepo,
verifyAuth,
tag,
push,
pushNotes,
verifyTagName,
isBranchUpToDate,
verifyBranchName,
getNote,
addNote,
};
+4 -3
View File
@@ -1,5 +1,6 @@
import {escapeRegExp, isString, size} from 'lodash-es';
import {SECRET_MIN_SIZE, SECRET_REPLACEMENT} from './definitions/constants.js';
import lodash from 'lodash'
const {escapeRegExp, size, isString} = lodash
import {SECRET_REPLACEMENT, SECRET_MIN_SIZE} from './definitions/constants.js';
export default (env) => {
const toReplace = Object.keys(env).filter((envVar) => {
@@ -17,4 +18,4 @@ export default (env) => {
);
return (output) =>
output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;
}
};
+22 -31
View File
@@ -1,21 +1,21 @@
import {castArray, identity, isNil, isPlainObject, isString, omit} from 'lodash-es';
import lodash from 'lodash'
const {identity, isPlainObject, omit, castArray, isNil, isString} = lodash
import AggregateError from 'aggregate-error';
import getError from '../get-error.js';
import PLUGINS_DEFINITIONS from '../definitions/plugins.js';
import {loadPlugin, parseConfig, validatePlugin, validateStep} from './utils.js';
import {validatePlugin, validateStep, loadPlugin, parseConfig} from './utils.js';
import pipeline from './pipeline.js';
import normalize from './normalize.js';
export default async (context, pluginsPath) => {
export default (context, pluginsPath) => {
let {options, logger} = context;
const errors = [];
const plugins = options.plugins
? await castArray(options.plugins).reduce(async (eventualPluginsList, plugin) => {
const pluginsList = await eventualPluginsList;
? castArray(options.plugins).reduce((plugins, plugin) => {
if (validatePlugin(plugin)) {
const [name, config] = parseConfig(plugin);
plugin = isString(name) ? await loadPlugin(context, name, pluginsPath) : name;
plugin = isString(name) ? loadPlugin(context, name, pluginsPath) : name;
if (isPlainObject(plugin)) {
Object.entries(plugin).forEach(([type, func]) => {
@@ -25,7 +25,7 @@ export default async (context, pluginsPath) => {
writable: false,
enumerable: true,
});
pluginsList[type] = [...(pluginsList[type] || []), [func, config]];
plugins[type] = [...(plugins[type] || []), [func, config]];
}
});
} else {
@@ -35,7 +35,7 @@ export default async (context, pluginsPath) => {
errors.push(getError('EPLUGINSCONF', {plugin}));
}
return pluginsList;
return plugins;
}, {})
: [];
@@ -45,13 +45,9 @@ export default async (context, pluginsPath) => {
options = {...plugins, ...options};
const pluginsConfig = await Object.entries(PLUGINS_DEFINITIONS).reduce(
async (
eventualPluginsConfigAccumulator,
[type, {required, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]
) => {
const pluginsConf = Object.entries(PLUGINS_DEFINITIONS).reduce(
(pluginsConf, [type, {required, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]) => {
let pluginOptions;
const pluginsConfigAccumulator = await eventualPluginsConfigAccumulator;
if (isNil(options[type]) && def) {
pluginOptions = def;
@@ -65,33 +61,28 @@ export default async (context, pluginsPath) => {
if (!validateStep({required}, options[type])) {
errors.push(getError('EPLUGINCONF', {type, required, pluginConf: options[type]}));
return pluginsConfigAccumulator;
return pluginsConf;
}
pluginOptions = options[type];
}
const steps = await Promise.all(
castArray(pluginOptions).map(async (pluginOpt) =>
normalize(
{...context, options: omit(options, Object.keys(PLUGINS_DEFINITIONS), 'plugins')},
type,
pluginOpt,
pluginsPath
)
const steps = castArray(pluginOptions).map((pluginOpt) =>
normalize(
{...context, options: omit(options, Object.keys(PLUGINS_DEFINITIONS), 'plugins')},
type,
pluginOpt,
pluginsPath
)
);
pluginsConfigAccumulator[type] = async (input) =>
pluginsConf[type] = async (input) =>
postprocess(
await pipeline(
steps,
pipelineConfig && pipelineConfig(pluginsConfigAccumulator, logger)
)(await preprocess(input)),
await pipeline(steps, pipelineConfig && pipelineConfig(pluginsConf, logger))(await preprocess(input)),
input
);
return pluginsConfigAccumulator;
return pluginsConf;
},
plugins
);
@@ -99,5 +90,5 @@ export default async (context, pluginsPath) => {
throw new AggregateError(errors);
}
return pluginsConfig;
}
return pluginsConf;
};
+7 -7
View File
@@ -1,13 +1,13 @@
import {cloneDeep, isFunction, isPlainObject, noop, omit} from 'lodash-es';
import debugPlugins from 'debug';
import lodash from 'lodash'
const {isPlainObject, isFunction, noop, cloneDeep, omit} = lodash
import debugFactory from 'debug';
const debug = debugFactory('semantic-release:plugins');
import getError from '../get-error.js';
import {extractErrors} from '../utils.js';
import PLUGINS_DEFINITIONS from '../definitions/plugins.js';
import {loadPlugin, parseConfig} from './utils.js';
const debug = debugPlugins('semantic-release:plugins');
export default async (context, type, pluginOpt, pluginsPath) => {
export default (context, type, pluginOpt, pluginsPath) => {
const {stdout, stderr, options, logger} = context;
if (!pluginOpt) {
return noop;
@@ -15,7 +15,7 @@ export default async (context, type, pluginOpt, pluginsPath) => {
const [name, config] = parseConfig(pluginOpt);
const pluginName = name.pluginName ? name.pluginName : isFunction(name) ? `[Function: ${name.name}]` : name;
const plugin = await loadPlugin(context, name, pluginsPath);
const plugin = loadPlugin(context, name, pluginsPath);
debug(`options for ${pluginName}/${type}: %O`, config);
@@ -66,4 +66,4 @@ export default async (context, type, pluginOpt, pluginsPath) => {
}
return validator;
}
};
+4 -3
View File
@@ -1,4 +1,5 @@
import {identity} from 'lodash-es';
import lodash from 'lodash'
const {identity} = lodash
import pReduce from 'p-reduce';
import AggregateError from 'aggregate-error';
import {extractErrors} from '../utils.js';
@@ -23,7 +24,7 @@ import {extractErrors} from '../utils.js';
* @param {Function} [options.getNextInput=identity] Function called after each step is executed, with the last step input and the current current step result; the returned value will be used as the input of the next step.
* @param {Function} [options.transform=identity] Function called after each step is executed, with the current step result, the step function and the last step input; the returned value will be saved in the pipeline results.
*
* @return {Pipeline} A Function that execute the `steps` sequentially
* @return {Pipeline} A Function that execute the `steps` sequencially
*/
export default (steps, {settleAll = false, getNextInput = identity, transform = identity} = {}) => async (input) => {
const results = [];
@@ -55,4 +56,4 @@ export default (steps, {settleAll = false, getNextInput = identity, transform =
}
return results;
}
};
+18 -13
View File
@@ -1,10 +1,8 @@
import {dirname} from 'node:path';
import {fileURLToPath} from 'node:url';
import {castArray, isArray, isFunction, isNil, isPlainObject, isString} from 'lodash-es';
import {dirname} from 'path';
import lodash from 'lodash'
const {isString, isFunction, castArray, isArray, isPlainObject, isNil} = lodash
import resolveFrom from 'resolve-from';
const __dirname = dirname(fileURLToPath(import.meta.url));
const validateSteps = (conf) => {
return conf.every((conf) => {
if (
@@ -27,7 +25,7 @@ const validateSteps = (conf) => {
});
};
export function validatePlugin(conf) {
function validatePlugin(conf) {
return (
isString(conf) ||
(isArray(conf) &&
@@ -38,7 +36,7 @@ export function validatePlugin(conf) {
);
}
export function validateStep({required}, conf) {
function validateStep({required}, conf) {
conf = castArray(conf).filter(Boolean);
if (required) {
return conf.length >= 1 && validateSteps(conf);
@@ -47,17 +45,14 @@ export function validateStep({required}, conf) {
return conf.length === 0 || validateSteps(conf);
}
export async function loadPlugin({cwd}, name, pluginsPath) {
function loadPlugin({cwd}, name, pluginsPath) {
const basePath = pluginsPath[name]
? dirname(resolveFrom.silent(__dirname, pluginsPath[name]) || resolveFrom(cwd, pluginsPath[name]))
: __dirname;
// See https://github.com/mysticatea/eslint-plugin-node/issues/250
// eslint-disable-next-line node/no-unsupported-features/es-syntax
return isFunction(name) ? name : (await import(resolveFrom.silent(basePath, name) || resolveFrom(cwd, name))).default;
return isFunction(name) ? name : require(resolveFrom.silent(basePath, name) || resolveFrom(cwd, name));
}
export function parseConfig(plugin) {
function parseConfig(plugin) {
let path;
let config;
if (isArray(plugin)) {
@@ -70,3 +65,13 @@ export function parseConfig(plugin) {
return [path, config || {}];
}
const exported = {
validatePlugin,
validateStep,
loadPlugin,
parseConfig,
};
export default exported;
export {validatePlugin, validateStep, loadPlugin, parseConfig};
+55 -17
View File
@@ -1,12 +1,13 @@
import {isFunction, template, union} from 'lodash-es';
import lodash from 'lodash'
const {isFunction, union, template} = lodash
import semver from 'semver';
import hideSensitive from './hide-sensitive.js';
export function extractErrors(err) {
return err && err.errors ? [...err.errors] : [err];
function extractErrors(err) {
return err && isFunction(err[Symbol.iterator]) ? [...err] : [err];
}
export function hideSensitiveValues(env, objs) {
function hideSensitiveValues(env, objs) {
const hideFunction = hideSensitive(env);
return objs.map((object) => {
Object.getOwnPropertyNames(object).forEach((prop) => {
@@ -18,19 +19,19 @@ export function hideSensitiveValues(env, objs) {
});
}
export function tagsToVersions(tags) {
function tagsToVersions(tags) {
return tags.map(({version}) => version);
}
export function isMajorRange(range) {
function isMajorRange(range) {
return /^\d+\.x(?:\.x)?$/i.test(range);
}
export function isMaintenanceRange(range) {
function isMaintenanceRange(range) {
return /^\d+\.(?:\d+|x)(?:\.x)?$/i.test(range);
}
export function getUpperBound(range) {
function getUpperBound(range) {
const result = semver.valid(range)
? range
: ((semver.validRange(range) || '').match(/<(?<upperBound>\d+\.\d+\.\d+(-\d+)?)$/) || [])[1];
@@ -41,27 +42,27 @@ export function getUpperBound(range) {
: result;
}
export function getLowerBound(range) {
function getLowerBound(range) {
return ((semver.validRange(range) || '').match(/(?<lowerBound>\d+\.\d+\.\d+)/) || [])[1];
}
export function highest(version1, version2) {
function highest(version1, version2) {
return version1 && version2 ? (semver.gt(version1, version2) ? version1 : version2) : version1 || version2;
}
export function lowest(version1, version2) {
function lowest(version1, version2) {
return version1 && version2 ? (semver.lt(version1, version2) ? version1 : version2) : version1 || version2;
}
export function getLatestVersion(versions, {withPrerelease} = {}) {
function getLatestVersion(versions, {withPrerelease} = {}) {
return versions.filter((version) => withPrerelease || !semver.prerelease(version)).sort(semver.rcompare)[0];
}
export function getEarliestVersion(versions, {withPrerelease} = {}) {
function getEarliestVersion(versions, {withPrerelease} = {}) {
return versions.filter((version) => withPrerelease || !semver.prerelease(version)).sort(semver.compare)[0];
}
export function getFirstVersion(versions, lowerBranches) {
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]));
@@ -70,14 +71,51 @@ export function getFirstVersion(versions, lowerBranches) {
return getEarliestVersion(versions);
}
export function getRange(min, max) {
function getRange(min, max) {
return `>=${min}${max ? ` <${max}` : ''}`;
}
export function makeTag(tagFormat, version) {
function makeTag(tagFormat, version) {
return template(tagFormat)({version});
}
export function isSameChannel(channel, otherChannel) {
function isSameChannel(channel, otherChannel) {
return channel === otherChannel || (!channel && !otherChannel);
}
const exported = {
extractErrors,
hideSensitiveValues,
tagsToVersions,
isMajorRange,
isMaintenanceRange,
getUpperBound,
getLowerBound,
highest,
lowest,
getLatestVersion,
getEarliestVersion,
getFirstVersion,
getRange,
makeTag,
isSameChannel,
};
export default exported;
export {
extractErrors,
hideSensitiveValues,
tagsToVersions,
isMajorRange,
isMaintenanceRange,
getUpperBound,
getLowerBound,
highest,
lowest,
getLatestVersion,
getEarliestVersion,
getFirstVersion,
getRange,
makeTag,
isSameChannel,
};
+3 -2
View File
@@ -1,4 +1,5 @@
import {isPlainObject, isString, template} from 'lodash-es';
import lodash from 'lodash'
const {template, isString, isPlainObject} = lodash
import AggregateError from 'aggregate-error';
import {isGitRepo, verifyTagName} from './git.js';
import getError from './get-error.js';
@@ -40,4 +41,4 @@ export default async (context) => {
if (errors.length > 0) {
throw new AggregateError(errors);
}
}
};
+8813 -18461
View File
File diff suppressed because it is too large Load Diff
+44 -51
View File
@@ -1,17 +1,13 @@
{
"name": "semantic-release",
"type": "module",
"description": "Automated semver compliant package publishing",
"version": "0.0.0-development",
"type": "module",
"author": "Stephan Bönnemann <stephan@boennemann.me> (http://boennemann.me)",
"ava": {
"files": [
"test/**/*.test.js"
],
"nodeArguments": [
"--loader=testdouble",
"--no-warnings"
],
"timeout": "2m"
},
"bin": {
@@ -22,64 +18,61 @@
},
"contributors": [
"Gregor Martynus (https://twitter.com/gr2m)",
"Pierre Vanduynslager (https://twitter.com/@pvdlg_)",
"Matt Travi <npm@travi.org> (https://matt.travi.org/)"
"Pierre Vanduynslager (https://twitter.com/@pvdlg_)"
],
"dependencies": {
"@semantic-release/commit-analyzer": "^9.0.2",
"@semantic-release/error": "^3.0.0",
"@semantic-release/github": "^8.0.0",
"@semantic-release/npm": "^9.0.0",
"@semantic-release/release-notes-generator": "^10.0.0",
"aggregate-error": "^4.0.1",
"@semantic-release/commit-analyzer": "^8.0.0",
"@semantic-release/error": "^2.2.0",
"@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": "^7.0.0",
"debug": "^4.0.0",
"env-ci": "8.0.0-beta.1",
"execa": "^6.1.0",
"figures": "^5.0.0",
"find-versions": "^5.1.0",
"env-ci": "^5.0.0",
"execa": "^5.0.0",
"figures": "^3.0.0",
"find-versions": "^4.0.0",
"get-stream": "^6.0.0",
"git-log-parser": "^1.2.0",
"hook-std": "^3.0.0",
"hosted-git-info": "^5.1.0",
"lodash-es": "^4.17.21",
"marked": "^4.1.0",
"marked-terminal": "^5.1.1",
"hook-std": "^2.0.0",
"hosted-git-info": "^4.0.0",
"lodash": "^4.17.21",
"marked": "^2.0.0",
"marked-terminal": "^4.1.1",
"micromatch": "^4.0.2",
"p-each-series": "^3.0.0",
"p-reduce": "^3.0.0",
"read-pkg-up": "^9.1.0",
"p-each-series": "^2.1.0",
"p-reduce": "^2.0.0",
"read-pkg-up": "^7.0.0",
"resolve-from": "^5.0.0",
"semver": "^7.3.2",
"semver-diff": "^3.1.1",
"signale": "^1.2.1",
"yargs": "^17.5.1"
"yargs": "^16.2.0"
},
"devDependencies": {
"ava": "4.3.3",
"c8": "7.12.0",
"clear-module": "4.1.2",
"codecov": "3.8.3",
"ava": "3.15.0",
"cjs2esm": "^2.0.0",
"clear-module": "4.1.1",
"codecov": "3.8.2",
"delay": "5.0.0",
"dockerode": "3.3.4",
"file-url": "^4.0.0",
"fs-extra": "^10.1.0",
"got": "^12.5.0",
"dockerode": "3.3.0",
"file-url": "3.0.0",
"fs-extra": "10.0.0",
"got": "11.8.2",
"js-yaml": "4.1.0",
"mockserver-client": "5.14.0",
"nock": "13.2.9",
"p-retry": "^5.1.1",
"sinon": "14.0.0",
"mockserver-client": "5.11.2",
"nock": "13.1.1",
"nyc": "15.1.0",
"p-retry": "4.6.1",
"proxyquire": "2.1.3",
"sinon": "11.1.1",
"stream-buffers": "3.0.2",
"tempy": "^3.0.0",
"testdouble": "3.16.6",
"xo": "0.32.1"
},
"overrides": {
"semantic-release": "20.0.0-beta.1"
"tempy": "1.0.1",
"xo": "0.29.1"
},
"engines": {
"node": ">=16 || ^14.17"
"node": ">=14.17"
},
"files": [
"bin",
@@ -101,8 +94,8 @@
"version"
],
"license": "MIT",
"main": "index.js",
"c8": {
"exports": "./index.js",
"nyc": {
"include": [
"lib/**/*.js",
"index.js",
@@ -131,15 +124,15 @@
"lint": "xo",
"pretest": "npm run lint",
"semantic-release": "./bin/semantic-release.js",
"test": "c8 ava --verbose",
"test:ci": "c8 ava --verbose"
"test": "nyc ava -v",
"test:ci": "nyc ava -v"
},
"xo": {
"prettier": true,
"space": true,
"rules": {
"unicorn/no-reduce": "off",
"unicorn/string-content": "off"
"unicorn/string-content": "off",
"import/extensions": "off"
}
},
"renovate": {
+22 -39
View File
@@ -1,7 +1,8 @@
import test from 'ava';
import {union} from 'lodash-es';
import lodash from 'lodash'
const {union} = lodash
import semver from 'semver';
import * as td from 'testdouble';
import proxyquire from 'proxyquire';
const getBranch = (branches, branch) => branches.find(({name}) => name === branch);
const release = (branches, name, version) => getBranch(branches, name).tags.push({version});
@@ -11,21 +12,8 @@ const merge = (branches, source, target, tag) => {
getBranch(branches, target).tags
);
};
const remoteBranches = [];
const repositoryUrl = 'repositoryUrl';
let expand, getTags, getBranches;
test.beforeEach(async (t) => {
getTags = (await td.replaceEsm('../../lib/branches/get-tags.js')).default;
expand = (await td.replaceEsm('../../lib/branches/expand.js')).default;
getBranches = (await import('../../lib/branches/index.js')).default;
})
test.afterEach.always((t) => {
td.reset();
});
test.serial('Enforce ranges with branching release workflow', async (t) => {
test('Enforce ranges with branching release workflow', async (t) => {
const branches = [
{name: '1.x', tags: []},
{name: '1.0.x', tags: []},
@@ -35,11 +23,12 @@ test.serial('Enforce ranges with branching release workflow', async (t) => {
{name: 'beta', prerelease: true, tags: []},
{name: 'alpha', prerelease: true, tags: []},
];
const context = {options: {branches}};
td.when(expand(repositoryUrl, context, branches)).thenResolve(remoteBranches);
td.when(getTags(context, remoteBranches)).thenResolve(branches);
const getBranches = proxyquire('../../lib/branches', {'./get-tags': () => branches, './expand': () => []});
let result = (await getBranches(repositoryUrl, 'master', context)).map(({name, range}) => ({name, range,}));
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');
@@ -47,7 +36,10 @@ test.serial('Enforce ranges with branching release workflow', async (t) => {
t.is(getBranch(result, 'next-major').range, '>=1.0.0');
release(branches, 'master', '1.0.0');
result = (await getBranches('repositoryUrl', 'master', context)).map(({name, range}) => ({name, range}));
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');
@@ -198,7 +190,7 @@ test.serial('Enforce ranges with branching release workflow', async (t) => {
t.is(getBranch(result, '1.x').range, '>=1.2.0 <2.0.0', 'Can release on 1.x only within range');
});
test.serial('Throw SemanticReleaseError for invalid configurations', async (t) => {
test('Throw SemanticReleaseError for invalid configurations', async (t) => {
const branches = [
{name: '123', range: '123', tags: []},
{name: '1.x', tags: []},
@@ -208,12 +200,8 @@ test.serial('Throw SemanticReleaseError for invalid configurations', async (t) =
{name: 'alpha', prerelease: 'alpha', tags: []},
{name: 'preview', prerelease: 'alpha', tags: []},
];
const context = {options: {branches}};
td.when(expand(repositoryUrl, context, branches)).thenResolve(remoteBranches);
td.when(getTags(context, remoteBranches)).thenResolve(branches);
const error = await t.throwsAsync(getBranches(repositoryUrl, 'master', context));
const errors = [...error.errors];
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');
@@ -237,16 +225,14 @@ test.serial('Throw SemanticReleaseError for invalid configurations', async (t) =
t.truthy(errors[4].details);
});
test.serial('Throw a SemanticReleaseError if there is duplicate branches', async (t) => {
test('Throw a SemanticReleaseError if there is duplicate branches', async (t) => {
const branches = [
{name: 'master', tags: []},
{name: 'master', tags: []},
];
const context = {options: {branches}};
td.when(expand(repositoryUrl, context, branches)).thenResolve(remoteBranches);
td.when(getTags(context, remoteBranches)).thenResolve(branches);
const getBranches = proxyquire('../../lib/branches', {'./get-tags': () => branches, './expand': () => []});
const errors = [...(await t.throwsAsync(getBranches(repositoryUrl, 'master', context))).errors];
const errors = [...(await t.throwsAsync(getBranches('repositoryUrl', 'master', {options: {branches}})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EDUPLICATEBRANCHES');
@@ -254,17 +240,14 @@ test.serial('Throw a SemanticReleaseError if there is duplicate branches', async
t.truthy(errors[0].details);
});
test.serial('Throw a SemanticReleaseError for each invalid branch name', async (t) => {
test('Throw a SemanticReleaseError for each invalid branch name', async (t) => {
const branches = [
{name: '~master', tags: []},
{name: '^master', tags: []},
];
const context = {options: {branches}};
const remoteBranches = [];
td.when(expand(repositoryUrl, context, branches)).thenResolve(remoteBranches);
td.when(getTags(context, remoteBranches)).thenResolve(branches);
const getBranches = proxyquire('../../lib/branches', {'./get-tags': () => branches, './expand': () => []});
const errors = [...(await t.throwsAsync(getBranches(repositoryUrl, 'master', context))).errors];
const errors = [...(await t.throwsAsync(getBranches('repositoryUrl', 'master', {options: {branches}})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EINVALIDBRANCHNAME');
+1 -1
View File
@@ -1,6 +1,6 @@
import test from 'ava';
import expand from '../../lib/branches/expand.js';
import {gitCheckout, gitCommits, gitPush, gitRepo} from '../helpers/git-utils.js';
import {gitRepo, gitCommits, gitCheckout, gitPush} from '../helpers/git-utils.js';
test('Expand branches defined with globs', async (t) => {
const {cwd, repositoryUrl} = await gitRepo(true);
+1 -1
View File
@@ -1,6 +1,6 @@
import test from 'ava';
import getTags from '../../lib/branches/get-tags.js';
import {gitAddNote, gitCheckout, gitCommits, gitRepo, gitTagVersion} from '../helpers/git-utils.js';
import {gitRepo, gitCommits, gitTagVersion, gitCheckout, gitAddNote} from '../helpers/git-utils.js';
test('Get the valid tags', async (t) => {
const {cwd} = await gitRepo();
+1 -1
View File
@@ -1,5 +1,5 @@
import test from 'ava';
import * as normalize from '../../lib/branches/normalize.js';
import normalize from '../../lib/branches/normalize.js';
const toTags = (versions) => versions.map((version) => ({version}));
+51 -114
View File
@@ -1,37 +1,28 @@
import test from 'ava';
import {escapeRegExp} from 'lodash-es';
import * as td from 'testdouble';
import {stub} from 'sinon';
import lodash from 'lodash'
const {escapeRegExp} = lodash
const proxyquire = require('proxyquire').noPreserveCache();
import sinon from 'sinon';
import {SECRET_REPLACEMENT} from '../lib/definitions/constants.js';
let previousArgv;
let previousEnv;
test.beforeEach((t) => {
t.context.logs = '';
t.context.errors = '';
t.context.stdout = stub(process.stdout, 'write').callsFake((value) => {
t.context.stdout = sinon.stubprocess.stdout, 'write').callsFake((value) => {
t.context.logs += value.toString();
});
t.context.stderr = stub(process.stderr, 'write').callsFake((value) => {
t.context.stderr = sinon.stubprocess.stderr, 'write').callsFake((value) => {
t.context.errors += value.toString();
});
previousArgv = process.argv;
previousEnv = process.env;
});
test.afterEach.always((t) => {
t.context.stdout.restore();
t.context.stderr.restore();
process.argv = previousArgv;
process.env = previousEnv;
td.reset();
});
test.serial('Pass options to semantic-release API', async (t) => {
const run = sinon.stub).resolves(true);
const argv = [
'',
'',
@@ -73,49 +64,31 @@ test.serial('Pass options to semantic-release API', async (t) => {
'--debug',
'-d',
];
const index = await td.replaceEsm('../index.js');
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
td.verify(index.default({
branches: ['master', 'next'],
b: ['master', 'next'],
'repository-url': 'https://github/com/owner/repo.git',
repositoryUrl: 'https://github/com/owner/repo.git',
r: 'https://github/com/owner/repo.git',
'tag-format': `v\${version}`,
tagFormat: `v\${version}`,
t: `v\${version}`,
plugins: ['plugin1', 'plugin2'],
p: ['plugin1', 'plugin2'],
extends: ['config1', 'config2'],
e: ['config1', 'config2'],
'dry-run': true,
dryRun: true,
d: true,
verifyConditions: ['condition1', 'condition2'],
'verify-conditions': ['condition1', 'condition2'],
analyzeCommits: 'analyze',
'analyze-commits': 'analyze',
verifyRelease: ['verify1', 'verify2'],
'verify-release': ['verify1', 'verify2'],
generateNotes: ['notes'],
'generate-notes': ['notes'],
prepare: ['prepare1', 'prepare2'],
publish: ['publish1', 'publish2'],
success: ['success1', 'success2'],
fail: ['fail1', 'fail2'],
debug: true,
_: [],
'$0': ''
}));
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']);
t.deepEqual(run.args[0][0].extends, ['config1', 'config2']);
t.deepEqual(run.args[0][0].verifyConditions, ['condition1', 'condition2']);
t.is(run.args[0][0].analyzeCommits, 'analyze');
t.deepEqual(run.args[0][0].verifyRelease, ['verify1', 'verify2']);
t.deepEqual(run.args[0][0].generateNotes, ['notes']);
t.deepEqual(run.args[0][0].prepare, ['prepare1', 'prepare2']);
t.deepEqual(run.args[0][0].publish, ['publish1', 'publish2']);
t.deepEqual(run.args[0][0].success, ['success1', 'success2']);
t.deepEqual(run.args[0][0].fail, ['fail1', 'fail2']);
t.is(run.args[0][0].debug, true);
t.is(run.args[0][0].dryRun, true);
t.is(exitCode, 0);
});
test.serial('Pass options to semantic-release API with alias arguments', async (t) => {
const run = sinon.stub).resolves(true);
const argv = [
'',
'',
@@ -133,75 +106,50 @@ test.serial('Pass options to semantic-release API with alias arguments', async (
'config2',
'--dry-run',
];
const index = await td.replaceEsm('../index.js');
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
td.verify(index.default({
branches: ['master'],
b: ['master'],
'repository-url': 'https://github/com/owner/repo.git',
repositoryUrl: 'https://github/com/owner/repo.git',
r: 'https://github/com/owner/repo.git',
'tag-format': `v\${version}`,
tagFormat: `v\${version}`,
t: `v\${version}`,
plugins: ['plugin1', 'plugin2'],
p: ['plugin1', 'plugin2'],
extends: ['config1', 'config2'],
e: ['config1', 'config2'],
'dry-run': true,
dryRun: true,
d: true,
_: [],
'$0': ''
}));
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']);
t.deepEqual(run.args[0][0].extends, ['config1', 'config2']);
t.is(run.args[0][0].dryRun, true);
t.is(exitCode, 0);
});
test.serial('Pass unknown options to semantic-release API', async (t) => {
const run = sinon.stub).resolves(true);
const argv = ['', '', '--bool', '--first-option', 'value1', '--second-option', 'value2', '--second-option', 'value3'];
const index = await td.replaceEsm('../index.js');
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
td.verify(index.default({
bool: true,
firstOption: 'value1',
'first-option': 'value1',
secondOption: ['value2', 'value3'],
'second-option': ['value2', 'value3'],
_: [],
'$0': ''
}));
t.is(run.args[0][0].bool, true);
t.is(run.args[0][0].firstOption, 'value1');
t.deepEqual(run.args[0][0].secondOption, ['value2', 'value3']);
t.is(exitCode, 0);
});
test.serial('Pass empty Array to semantic-release API for list option set to "false"', async (t) => {
const run = sinon.stub).resolves(true);
const argv = ['', '', '--publish', 'false'];
const index = await td.replaceEsm('../index.js');
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
td.verify(index.default({publish: [], _: [], '$0': ''}));
t.deepEqual(run.args[0][0].publish, []);
t.is(exitCode, 0);
});
test.serial('Do not set properties in option for which arg is not in command line', async (t) => {
const run = stub().resolves(true);
const run = sinon.stub).resolves(true);
const argv = ['', '', '-b', 'master'];
await td.replaceEsm('../index.js', null, run);
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
await cli();
@@ -216,11 +164,9 @@ test.serial('Do not set properties in option for which arg is not in command lin
});
test.serial('Display help', async (t) => {
const run = stub().resolves(true);
const run = sinon.stub).resolves(true);
const argv = ['', '', '--help'];
await td.replaceEsm('../index.js', null, run);
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
@@ -229,11 +175,9 @@ test.serial('Display help', async (t) => {
});
test.serial('Return error exitCode and prints help if called with a command', async (t) => {
const run = stub().resolves(true);
const run = sinon.stub).resolves(true);
const argv = ['', '', 'pre'];
await td.replaceEsm('../index.js', null, run);
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
@@ -243,11 +187,9 @@ test.serial('Return error exitCode and prints help if called with a command', as
});
test.serial('Return error exitCode if multiple plugin are set for single plugin', async (t) => {
const run = stub().resolves(true);
const run = sinon.stub).resolves(true);
const argv = ['', '', '--analyze-commits', 'analyze1', 'analyze2'];
await td.replaceEsm('../index.js', null, run);
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
@@ -257,11 +199,9 @@ test.serial('Return error exitCode if multiple plugin are set for single plugin'
});
test.serial('Return error exitCode if semantic-release throw error', async (t) => {
const run = sinon.stub).rejects(new Error('semantic-release error'));
const argv = ['', ''];
const index = await td.replaceEsm('../index.js');
td.when(index.default({_: [], '$0': ''})).thenReject(new Error('semantic-release error'));
process.argv = argv;
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
@@ -271,12 +211,9 @@ test.serial('Return error exitCode if semantic-release throw error', async (t) =
test.serial('Hide sensitive environment variable values from the logs', async (t) => {
const env = {MY_TOKEN: 'secret token'};
const run = sinon.stub).rejects(new Error(`Throw error: Exposing token ${env.MY_TOKEN}`));
const argv = ['', ''];
const index = await td.replaceEsm('../index.js');
td.when(index.default({_: [], '$0': ''})).thenReject(new Error(`Throw error: Exposing token ${env.MY_TOKEN}`));
process.argv = argv;
process.env = {...process.env, ...env};
const cli = (await import('../cli.js')).default;
const cli = proxyquire('../cli', {'.': run, process: {...process, argv, env: {...process.env, ...env}}});
const exitCode = await cli();
-6
View File
@@ -2,7 +2,6 @@ import test from 'ava';
import {maintenance, prerelease, release} from '../../lib/definitions/branches.js';
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) => {
/* eslint-disable unicorn/no-fn-reference-in-iterator */
t.true(maintenance.filter({name: '1.x.x'}));
t.true(maintenance.filter({name: '1.0.x'}));
t.true(maintenance.filter({name: '1.x'}));
@@ -16,7 +15,6 @@ test('A "maintenance" branch is identified by having a "range" property or a "na
t.false(maintenance.filter({name: 'some-name'}));
t.false(maintenance.filter({name: '1.0.0'}));
t.false(maintenance.filter({name: 'x.x.x'}));
/* eslint-enable unicorn/no-fn-reference-in-iterator */
});
test('A "maintenance" branches must have a "range" property formatted like "N.x", "N.x.x" or "N.N.x"', (t) => {
@@ -39,7 +37,6 @@ test('The "maintenance" branches must have unique ranges', (t) => {
});
test('A "prerelease" branch is identified by having a thruthy "prerelease" property', (t) => {
/* eslint-disable unicorn/no-fn-reference-in-iterator */
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: ''}));
@@ -47,7 +44,6 @@ test('A "prerelease" branch is identified by having a thruthy "prerelease" prope
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'}));
/* eslint-enable unicorn/no-fn-reference-in-iterator */
});
test('A "prerelease" branch must have a valid prerelease detonation in "prerelease" property or in "name" if "prerelease" is "true"', (t) => {
@@ -70,7 +66,6 @@ test('The "prerelease" branches must have unique "prerelease" property', (t) =>
});
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) => {
/* eslint-disable unicorn/no-fn-reference-in-iterator */
t.true(release.filter({name: 'some-name'}));
t.false(release.filter({name: '1.x.x'}));
@@ -79,7 +74,6 @@ test('A "release" branch is identified by not havin a "range" or "prerelease" pr
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'}));
/* eslint-enable unicorn/no-fn-reference-in-iterator */
});
test('There must be between 1 and 3 release branches', (t) => {
+1 -1
View File
@@ -1 +1 @@
export default () => {}
export default () => {};
@@ -1,4 +1,4 @@
module.exports = {
const exported = {
verifyConditions: () => {},
getLastRelease: () => {},
analyzeCommits: () => {},
@@ -6,3 +6,7 @@ module.exports = {
generateNotes: () => {},
publish: () => {},
};
export default exported;
export const {verifyConditions, getLastRelease, analyzeCommits, verifyRelease, generateNotes, publish} = exported;
+1 -1
View File
@@ -11,4 +11,4 @@ class InheritedError extends SemanticReleaseError {
export default () => {
throw new InheritedError('Inherited error', 'EINHERITED');
}
};
+1 -1
View File
@@ -2,4 +2,4 @@ export default () => {
const error = new Error('a');
error.errorProperty = 'errorProperty';
throw error;
}
};
+1 -1
View File
@@ -2,4 +2,4 @@ import AggregateError from 'aggregate-error';
export default () => {
throw new AggregateError([new Error('a'), new Error('b')]);
}
};
+1 -1
View File
@@ -1 +1 @@
export default (pluginConfig, context) => context
export default (pluginConfig, context) => context;
+1 -1
View File
@@ -3,4 +3,4 @@ export default (pluginConfig, {env, logger}) => {
logger.log(`Log: Exposing token ${env.MY_TOKEN}`);
logger.error(`Error: Console token ${env.MY_TOKEN}`);
throw new Error(`Throw error: Exposing ${env.MY_TOKEN}`);
}
};
-3
View File
@@ -1,3 +0,0 @@
module.exports = function noop() {
};
+1
View File
@@ -0,0 +1 @@
export default () => {};
+1 -1
View File
@@ -1 +1 @@
export default (pluginConfig, context) => ({pluginConfig, context})
export default (pluginConfig, context) => ({pluginConfig, context});
+4 -4
View File
@@ -1,12 +1,12 @@
import test from 'ava';
import {stub} from 'sinon';
import sinon from 'sinon';
import getCommits from '../lib/get-commits.js';
import {gitCommits, gitDetachedHead, gitRepo} from './helpers/git-utils.js';
import {gitRepo, gitCommits, gitDetachedHead} from './helpers/git-utils.js';
test.beforeEach((t) => {
// Stub the logger functions
t.context.log = stub();
t.context.error = stub();
t.context.log = sinon.stub();
t.context.error = sinon.stub();
t.context.logger = {log: t.context.log, error: t.context.error};
});
+145 -155
View File
@@ -1,15 +1,13 @@
import path from 'node:path';
import {format} from 'node:util';
import path from 'path';
import {format} from 'util';
import test from 'ava';
import fsExtra from 'fs-extra';
import {omit} from 'lodash-es';
import * as td from 'testdouble';
import {writeFile, outputJson} from 'fs-extra';
import lodash from 'lodash'
const {omit} = lodash
import proxyquire from 'proxyquire';
import sinon from 'sinon';
import yaml from 'js-yaml';
import {gitAddConfig, gitCommits, gitRepo, gitShallowClone, gitTagVersion} from './helpers/git-utils.js';
const {outputJson, writeFile} = fsExtra;
const pluginsConfig = {foo: 'bar', baz: 'qux'};
let plugins;
import {gitRepo, gitTagVersion, gitCommits, gitShallowClone, gitAddConfig} from './helpers/git-utils.js';
const DEFAULT_PLUGINS = [
'@semantic-release/commit-analyzer',
@@ -18,13 +16,9 @@ const DEFAULT_PLUGINS = [
'@semantic-release/github',
];
test.beforeEach(async (t) => {
plugins = (await td.replaceEsm('../lib/plugins/index.js')).default;
t.context.getConfig = (await import('../lib/get-config.js')).default;
});
test.afterEach.always((t) => {
td.reset();
test.beforeEach((t) => {
t.context.plugins = sinon.stub).returns({});
t.context.getConfig = proxyquire('../lib/get-config', {'./plugins': t.context.plugins});
});
test('Default values, reading repositoryUrl from package.json', async (t) => {
@@ -109,7 +103,7 @@ test('Convert "ci" option to "noCi"', async (t) => {
t.is(result.noCi, true);
});
test.serial('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 = {
@@ -120,18 +114,19 @@ test.serial('Read options from package.json', async (t) => {
tagFormat: `v\${version}`,
plugins: false,
};
// Verify the plugins module is called with the plugin options from package.json
td.when(plugins({cwd, options}, {})).thenResolve(pluginsConfig);
// Create package.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: options});
const result = 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 package.json
t.deepEqual(result, {options, plugins: pluginsConfig});
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], {options: expected, cwd});
});
test.serial('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 = {
@@ -143,16 +138,17 @@ test.serial('Read options from .releaserc.yml', async (t) => {
};
// Create package.json in repository root
await writeFile(path.resolve(cwd, '.releaserc.yml'), yaml.dump(options));
// Verify the plugins module is called with the plugin options from package.json
td.when(plugins({cwd, options}, {})).thenResolve(pluginsConfig);
const result = 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 package.json
t.deepEqual(result, {options, plugins: pluginsConfig});
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], {options: expected, cwd});
});
test.serial('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 = {
@@ -164,16 +160,17 @@ test.serial('Read options from .releaserc.json', async (t) => {
};
// Create package.json in repository root
await outputJson(path.resolve(cwd, '.releaserc.json'), options);
// Verify the plugins module is called with the plugin options from package.json
td.when(plugins({cwd, options}, {})).thenResolve(pluginsConfig);
const result = 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 package.json
t.deepEqual(result, {options, plugins: pluginsConfig});
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], {options: expected, cwd});
});
test.serial('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 = {
@@ -185,16 +182,17 @@ test.serial('Read options from .releaserc.js', async (t) => {
};
// Create package.json in repository root
await writeFile(path.resolve(cwd, '.releaserc.js'), `module.exports = ${JSON.stringify(options)}`);
// Verify the plugins module is called with the plugin options from package.json
td.when(plugins({cwd, options}, {})).thenResolve(pluginsConfig);
const result = 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 package.json
t.deepEqual(result, {options, plugins: pluginsConfig});
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], {options: expected, cwd});
});
test.serial('Read options from .releaserc.cjs', async (t) => {
test('Read options from .releaserc.cjs', async (t) => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd} = await gitRepo();
const options = {
@@ -206,16 +204,17 @@ test.serial('Read options from .releaserc.cjs', async (t) => {
};
// Create .releaserc.cjs in repository root
await writeFile(path.resolve(cwd, '.releaserc.cjs'), `module.exports = ${JSON.stringify(options)}`);
// Verify the plugins module is called with the plugin options from .releaserc.cjs
td.when(plugins({cwd, options}, {})).thenResolve(pluginsConfig);
const result = 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 .releaserc.cjs
t.deepEqual(result, {options, plugins: pluginsConfig});
t.deepEqual(result, expected);
// Verify the plugins module is called with the plugin options from .releaserc.cjs
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
});
test.serial('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 = {
@@ -227,16 +226,17 @@ test.serial('Read options from release.config.js', async (t) => {
};
// Create package.json in repository root
await writeFile(path.resolve(cwd, 'release.config.js'), `module.exports = ${JSON.stringify(options)}`);
// Verify the plugins module is called with the plugin options from package.json
td.when(plugins({cwd, options}, {})).thenResolve(pluginsConfig);
const result = 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 package.json
t.deepEqual(result, {options, plugins: pluginsConfig});
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], {options: expected, cwd});
});
test.serial('Read options from release.config.cjs', async (t) => {
test('Read options from release.config.cjs', async (t) => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd} = await gitRepo();
const options = {
@@ -246,18 +246,19 @@ test.serial('Read options from release.config.cjs', async (t) => {
tagFormat: `v\${version}`,
plugins: false,
};
// Verify the plugins module is called with the plugin options from release.config.cjs
td.when(plugins({cwd, options}, {})).thenResolve(pluginsConfig);
// Create release.config.cjs in repository root
await writeFile(path.resolve(cwd, 'release.config.cjs'), `module.exports = ${JSON.stringify(options)}`);
const result = 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 release.config.cjs
t.deepEqual(result, {options, plugins: pluginsConfig});
t.deepEqual(result, expected);
// Verify the plugins module is called with the plugin options from release.config.cjs
t.deepEqual(t.context.plugins.args[0][0], {options: expected, cwd});
});
test.serial('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});
@@ -274,19 +275,20 @@ test.serial('Prioritise CLI/API parameters over file configuration and git repo'
tagFormat: `cli\${version}`,
plugins: false,
};
// Verify the plugins module is called with the plugin options from CLI/API
td.when(plugins({cwd, options}, {})).thenResolve(pluginsConfig);
const pkg = {release: pkgOptions, repository: 'git@host.null:owner/module.git'};
// Create package.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), pkg);
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, plugins: pluginsConfig});
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], {options: expected, cwd});
});
test.serial('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'};
@@ -301,24 +303,23 @@ test.serial('Read configuration from file path in "extends"', async (t) => {
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
await outputJson(path.resolve(cwd, 'shareable.json'), options);
// Verify the plugins module is called with the plugin options from shareable.json
td.when(plugins(
{cwd, options},
{
analyzeCommits: './shareable.json',
generateNotes: './shareable.json',
'plugin-1': './shareable.json',
'plugin-2': './shareable.json',
}
)).thenResolve(pluginsConfig);
const result = 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(result, {options, plugins: pluginsConfig});
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: expected, cwd});
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: './shareable.json',
generateNotes: './shareable.json',
'plugin-1': './shareable.json',
'plugin-2': './shareable.json',
});
});
test.serial('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'};
@@ -333,19 +334,21 @@ test.serial('Read configuration from module path in "extends"', async (t) => {
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
await outputJson(path.resolve(cwd, 'node_modules/shareable/index.json'), options);
// Verify the plugins module is called with the plugin options from shareable.json
td.when(plugins(
{cwd, options},
{analyzeCommits: 'shareable', generateNotes: 'shareable'}
)).thenResolve(pluginsConfig);
const result = 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(result, {options, plugins: pluginsConfig});
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: expected, cwd});
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: 'shareable',
generateNotes: 'shareable',
});
});
test.serial('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']};
@@ -367,26 +370,24 @@ test.serial('Read configuration from an array of paths in "extends"', async (t)
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
await outputJson(path.resolve(cwd, 'shareable2.json'), options2);
const expectedOptions = {...options1, ...options2, branches: ['test_branch']};
// Verify the plugins module is called with the plugin options from shareable1.json and shareable2.json
td.when(plugins(
{options: expectedOptions, cwd},
{
verifyRelease1: './shareable1.json',
verifyRelease2: './shareable2.json',
generateNotes2: './shareable2.json',
analyzeCommits1: './shareable1.json',
analyzeCommits2: './shareable2.json',
}
)).thenResolve(pluginsConfig);
const result = 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(result, {options: expectedOptions, plugins: pluginsConfig});
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], {options: expected, cwd});
t.deepEqual(t.context.plugins.args[0][1], {
verifyRelease1: './shareable1.json',
verifyRelease2: './shareable2.json',
generateNotes2: './shareable2.json',
analyzeCommits1: './shareable1.json',
analyzeCommits2: './shareable2.json',
});
});
test.serial('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 = {
@@ -407,24 +408,22 @@ test.serial('Prioritize configuration from config file over "extends"', async (t
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
await outputJson(path.resolve(cwd, 'shareable.json'), options1);
const expectedOptions = omit({...options1, ...pkgOptions, branches: ['test_pkg']}, 'extends');
// Verify the plugins module is called with the plugin options from package.json and shareable.json
td.when(plugins(
{cwd, options: expectedOptions},
{
analyzeCommits: './shareable.json',
generateNotesShareable: './shareable.json',
publishShareable: './shareable.json',
}
)).thenResolve(pluginsConfig);
const result = 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(result, {options: expectedOptions, plugins: pluginsConfig});
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], {options: expected, cwd});
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: './shareable.json',
generateNotesShareable: './shareable.json',
publishShareable: './shareable.json',
});
});
test.serial('Prioritize configuration from cli/API options over "extends"', async (t) => {
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 = {
@@ -457,20 +456,17 @@ test.serial('Prioritize configuration from cli/API options over "extends"', asyn
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
await outputJson(path.resolve(cwd, 'shareable2.json'), options2);
const expectedOptions = omit({...options2, ...pkgOptions, ...cliOptions, branches: ['branch_opts']}, 'extends');
// Verify the plugins module is called with the plugin options from package.json and shareable2.json
td.when(plugins(
{cwd, options: expectedOptions},
{analyzeCommits2: './shareable2.json', publishShareable: './shareable2.json'}
)).thenResolve(pluginsConfig);
const result = 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(result, {options: expectedOptions, plugins: pluginsConfig});
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], {options: expected, cwd});
});
test.serial('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 = {
@@ -489,40 +485,33 @@ test.serial('Allow to unset properties defined in shareable config with "null"',
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
await outputJson(path.resolve(cwd, 'shareable.json'), options1);
// Verify the plugins module is called with the plugin options from shareable.json and the default `plugins`
td.when(plugins(
{
options: {
...omit(options1, 'analyzeCommits'),
...omit(pkgOptions, ['extends', 'analyzeCommits']),
plugins: DEFAULT_PLUGINS,
},
cwd,
},
{
generateNotes: './shareable.json',
analyzeCommits: './shareable.json',
'test-plugin': './shareable.json',
}
)).thenResolve(pluginsConfig);
const result = await t.context.getConfig({cwd});
const {options} = await t.context.getConfig({cwd});
// Verify the options contains the plugin config from shareable.json and the default `plugins`
t.deepEqual(
result,
{
options: {
...omit(options1, ['analyzeCommits']),
...omit(pkgOptions, ['extends', 'analyzeCommits']),
plugins: DEFAULT_PLUGINS,
},
plugins: pluginsConfig
}
);
t.deepEqual(options, {
...omit(options1, ['analyzeCommits']),
...omit(pkgOptions, ['extends', 'analyzeCommits']),
plugins: DEFAULT_PLUGINS,
});
// Verify the plugins module is called with the plugin options from shareable.json and the default `plugins`
t.deepEqual(t.context.plugins.args[0][0], {
options: {
...omit(options1, 'analyzeCommits'),
...omit(pkgOptions, ['extends', 'analyzeCommits']),
plugins: DEFAULT_PLUGINS,
},
cwd,
});
t.deepEqual(t.context.plugins.args[0][1], {
generateNotes: './shareable.json',
analyzeCommits: './shareable.json',
'test-plugin': './shareable.json',
});
});
test.serial('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 = {
@@ -537,24 +526,25 @@ test.serial('Allow to unset properties defined in shareable config with "undefin
tagFormat: `v\${version}`,
plugins: false,
};
// Create release.config.js and shareable.json in repository root
// Create package.json and release.config.js in repository root
await writeFile(path.resolve(cwd, 'release.config.js'), `module.exports = ${format(pkgOptions)}`);
await outputJson(path.resolve(cwd, 'shareable.json'), options1);
const expectedOptions = {
const {options: result} = await t.context.getConfig({cwd});
const expected = {
...omit(options1, 'analyzeCommits'),
...omit(pkgOptions, ['extends', 'analyzeCommits']),
branches: ['test_branch'],
};
// Verify the plugins module is called with the plugin options from shareable.json
td.when(plugins(
{options: expectedOptions, cwd},
{generateNotes: './shareable.json', analyzeCommits: './shareable.json'}
)).thenResolve(pluginsConfig);
const result = await t.context.getConfig({cwd});
// Verify the options contains the plugin config from shareable.json
t.deepEqual(result, {options: expectedOptions, plugins: pluginsConfig});
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: 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) => {
+2 -2
View File
@@ -1,10 +1,10 @@
import test from 'ava';
import {stub} from 'sinon';
import sinon from 'sinon';
import getNextVersion from '../lib/get-next-version.js';
test.beforeEach((t) => {
// Stub the logger functions
t.context.log = stub();
t.context.log = sinon.stub);
t.context.logger = {log: t.context.log};
});
+27 -25
View File
@@ -1,39 +1,41 @@
import test from 'ava';
import {temporaryDirectory} from 'tempy';
import tempy from 'tempy';
import {
addNote,
fetch,
fetchNotes,
getBranches,
getGitHead,
getNote,
getTagHead,
getTags,
isBranchUpToDate,
isGitRepo,
isRefExists,
push,
fetch,
getGitHead,
repoUrl,
tag,
verifyTagName
push,
getTags,
getBranches,
isGitRepo,
verifyTagName,
isBranchUpToDate,
getNote,
addNote,
fetchNotes,
} from '../lib/git.js';
import {
gitAddConfig,
gitAddNote,
gitCheckout,
gitRepo,
gitCommits,
gitCheckout,
gitTagVersion,
gitShallowClone,
gitGetCommits,
gitAddConfig,
gitCommitTag,
gitRemoteTagHead,
gitPush,
gitDetachedHead,
gitDetachedHeadFromBranch,
gitFetch,
gitGetCommits,
gitAddNote,
gitGetNote,
gitPush,
gitRemoteTagHead,
gitRepo,
gitShallowClone,
gitTagVersion,
initGit
gitFetch,
initGit,
} from './helpers/git-utils.js';
test('Get the last commit sha', async (t) => {
@@ -268,7 +270,7 @@ test('Return "true" if in a Git repository', async (t) => {
});
test('Return falsy if not in a Git repository', async (t) => {
const cwd = temporaryDirectory();
const cwd = tempy.directory();
t.falsy(await isGitRepo({cwd}));
});
@@ -288,7 +290,7 @@ test('Return falsy for invalid tag names', async (t) => {
});
test('Throws error if obtaining the tags fails', async (t) => {
const cwd = temporaryDirectory();
const cwd = tempy.directory();
await t.throwsAsync(getTags('master', {cwd}));
});
-23
View File
@@ -1,23 +0,0 @@
storage: /verdaccio/storage/data
plugins: /verdaccio/plugins
web:
title: Verdaccio
auth:
htpasswd:
file: /verdaccio/storage/htpasswd
packages:
'@*/*':
access: $all
publish: $authenticated
unpublish: $authenticated
'**':
access: $all
publish: $authenticated
unpublish: $authenticated
server:
keepAliveTimeout: 60
middlewares:
audit:
enabled: true
logs:
- { type: stdout, format: pretty, level: http }
+80 -29
View File
@@ -1,5 +1,5 @@
import {temporaryDirectory} from 'tempy';
import {execa} from 'execa';
import tempy from 'tempy';
import execa from 'execa';
import fileUrl from 'file-url';
import pEachSeries from 'p-each-series';
import gitLogParser from 'git-log-parser';
@@ -23,8 +23,8 @@ import {GIT_NOTE_REF} from '../../lib/definitions/constants.js';
* @param {Boolean} withRemote `true` to create a shallow clone of a bare repository.
* @return {String} The path of the repository
*/
export async function initGit(withRemote) {
const cwd = temporaryDirectory();
async function initGit(withRemote) {
const cwd = tempy.directory();
const args = withRemote ? ['--bare', '--initial-branch=master'] : ['--initial-branch=master'];
await execa('git', ['init', ...args], {cwd}).catch(() => {
@@ -45,7 +45,7 @@ export async function initGit(withRemote) {
* @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') {
async function gitRepo(withRemote, branch = 'master') {
let {cwd, repositoryUrl} = await initGit(withRemote);
if (withRemote) {
await initBareRepo(repositoryUrl, branch);
@@ -70,8 +70,8 @@ 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') {
const cwd = temporaryDirectory();
async function initBareRepo(repositoryUrl, branch = 'master') {
const cwd = tempy.directory();
await execa('git', ['clone', '--no-hardlinks', repositoryUrl, cwd], {cwd});
await gitCheckout(branch, true, {cwd});
await gitCommits(['Initial commit'], {cwd});
@@ -86,7 +86,7 @@ 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, execaOptions) {
async function gitCommits(messages, execaOptions) {
await pEachSeries(
messages,
async (message) =>
@@ -103,7 +103,7 @@ export async function gitCommits(messages, execaOptions) {
*
* @return {Array<Object>} The list of parsed commits.
*/
export async function gitGetCommits(from, execaOptions) {
async function gitGetCommits(from, execaOptions) {
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
return (
await getStream.array(
@@ -126,7 +126,7 @@ export async function gitGetCommits(from, execaOptions) {
* @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, execaOptions) {
async function gitCheckout(branch, create, execaOptions) {
await execa('git', create ? ['checkout', '-b', branch] : ['checkout', branch], execaOptions);
}
@@ -136,7 +136,7 @@ export async function gitCheckout(branch, create, execaOptions) {
* @param {String} repositoryUrl The repository remote URL.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function gitFetch(repositoryUrl, execaOptions) {
async function gitFetch(repositoryUrl, execaOptions) {
await execa('git', ['fetch', repositoryUrl], execaOptions);
}
@@ -147,7 +147,7 @@ export async function gitFetch(repositoryUrl, execaOptions) {
*
* @return {String} The sha of the head commit in the current git repository.
*/
export async function gitHead(execaOptions) {
async function gitHead(execaOptions) {
return (await execa('git', ['rev-parse', 'HEAD'], execaOptions)).stdout;
}
@@ -158,7 +158,7 @@ export async function gitHead(execaOptions) {
* @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, execaOptions) {
async function gitTagVersion(tagName, sha, execaOptions) {
await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName], execaOptions);
}
@@ -171,8 +171,8 @@ export async function gitTagVersion(tagName, sha, execaOptions) {
* @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) {
const cwd = temporaryDirectory();
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], {
cwd,
@@ -187,8 +187,8 @@ 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) {
const cwd = temporaryDirectory();
async function gitDetachedHead(repositoryUrl, head) {
const cwd = tempy.directory();
await execa('git', ['init'], {cwd});
await execa('git', ['remote', 'add', 'origin', repositoryUrl], {cwd});
@@ -197,8 +197,8 @@ export async function gitDetachedHead(repositoryUrl, head) {
return cwd;
}
export async function gitDetachedHeadFromBranch(repositoryUrl, branch, head) {
const cwd = temporaryDirectory();
async function gitDetachedHeadFromBranch(repositoryUrl, branch, head) {
const cwd = tempy.directory();
await execa('git', ['init'], {cwd});
await execa('git', ['remote', 'add', 'origin', repositoryUrl], {cwd});
@@ -215,7 +215,7 @@ export async function gitDetachedHeadFromBranch(repositoryUrl, branch, head) {
* @param {String} value Config value.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function gitAddConfig(name, value, execaOptions) {
async function gitAddConfig(name, value, execaOptions) {
await execa('git', ['config', '--add', name, value], execaOptions);
}
@@ -227,7 +227,7 @@ export async function gitAddConfig(name, value, execaOptions) {
*
* @return {String} The sha of the commit associated with `tagName` on the local repository.
*/
export async function gitTagHead(tagName, execaOptions) {
async function gitTagHead(tagName, execaOptions) {
return (await execa('git', ['rev-list', '-1', tagName], execaOptions)).stdout;
}
@@ -240,7 +240,7 @@ export async function gitTagHead(tagName, execaOptions) {
*
* @return {String} The sha of the commit associated with `tagName` on the remote repository.
*/
export async function gitRemoteTagHead(repositoryUrl, tagName, execaOptions) {
async function gitRemoteTagHead(repositoryUrl, tagName, execaOptions) {
return (await execa('git', ['ls-remote', '--tags', repositoryUrl, tagName], execaOptions)).stdout
.split('\n')
.filter((tag) => Boolean(tag))
@@ -255,7 +255,7 @@ export async function gitRemoteTagHead(repositoryUrl, tagName, execaOptions) {
*
* @return {String} The tag associatedwith the sha in parameter or `null`.
*/
export async function gitCommitTag(gitHead, execaOptions) {
async function gitCommitTag(gitHead, execaOptions) {
return (await execa('git', ['describe', '--tags', '--exact-match', gitHead], execaOptions)).stdout;
}
@@ -268,7 +268,7 @@ export async function gitCommitTag(gitHead, execaOptions) {
*
* @throws {Error} if the push failed.
*/
export async function gitPush(repositoryUrl, branch, execaOptions) {
async function gitPush(repositoryUrl, branch, execaOptions) {
await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`], execaOptions);
}
@@ -278,7 +278,7 @@ export async function gitPush(repositoryUrl, branch, execaOptions) {
* @param {String} ref The ref to merge.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function merge(ref, execaOptions) {
async function merge(ref, execaOptions) {
await execa('git', ['merge', '--no-ff', ref], execaOptions);
}
@@ -288,7 +288,7 @@ export async function merge(ref, execaOptions) {
* @param {String} ref The ref to merge.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function mergeFf(ref, execaOptions) {
async function mergeFf(ref, execaOptions) {
await execa('git', ['merge', '--ff', ref], execaOptions);
}
@@ -298,7 +298,7 @@ export async function mergeFf(ref, execaOptions) {
* @param {String} ref The ref to merge.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function rebase(ref, execaOptions) {
async function rebase(ref, execaOptions) {
await execa('git', ['rebase', ref], execaOptions);
}
@@ -309,7 +309,7 @@ export async function rebase(ref, execaOptions) {
* @param {String} ref The ref to add the note to.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function gitAddNote(note, ref, execaOptions) {
async function gitAddNote(note, ref, execaOptions) {
await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'add', '-m', note, ref], execaOptions);
}
@@ -319,6 +319,57 @@ export async function gitAddNote(note, ref, execaOptions) {
* @param {String} ref The ref to get the note from.
* @param {Object} [execaOpts] Options to pass to `execa`.
*/
export async function gitGetNote(ref, execaOptions) {
async function gitGetNote(ref, execaOptions) {
return (await execa('git', ['notes', '--ref', GIT_NOTE_REF, 'show', ref], execaOptions)).stdout;
}
const exported = {
initGit,
gitRepo,
initBareRepo,
gitCommits,
gitGetCommits,
gitCheckout,
gitFetch,
gitHead,
gitTagVersion,
gitShallowClone,
gitDetachedHead,
gitDetachedHeadFromBranch,
gitAddConfig,
gitTagHead,
gitRemoteTagHead,
gitCommitTag,
gitPush,
merge,
mergeFf,
rebase,
gitAddNote,
gitGetNote,
};
export default exported;
export {
initGit,
gitRepo,
initBareRepo,
gitCommits,
gitGetCommits,
gitCheckout,
gitFetch,
gitHead,
gitTagVersion,
gitShallowClone,
gitDetachedHead,
gitDetachedHeadFromBranch,
gitAddConfig,
gitTagHead,
gitRemoteTagHead,
gitCommitTag,
gitPush,
merge,
mergeFf,
rebase,
gitAddNote,
gitGetNote,
};
+16 -6
View File
@@ -1,9 +1,9 @@
import Docker from 'dockerode';
import getStream from 'get-stream';
import pRetry from 'p-retry';
import {gitShallowClone, initBareRepo} from './git-utils.js';
import {initBareRepo, gitShallowClone} from './git-utils.js';
const IMAGE = 'semanticrelease/docker-gitbox:latest';
const IMAGE = 'pvdlg/docker-gitbox:latest';
const SERVER_PORT = 80;
const HOST_PORT = 2080;
const SERVER_HOST = 'localhost';
@@ -12,12 +12,12 @@ const GIT_PASSWORD = 'suchsecure';
const docker = new Docker();
let container;
export const gitCredential = `${GIT_USERNAME}:${GIT_PASSWORD}`;
const gitCredential = `${GIT_USERNAME}:${GIT_PASSWORD}`;
/**
* Download the `gitbox` Docker image, create a new container and start it.
*/
export async function start() {
async function start() {
await getStream(await docker.pull(IMAGE));
container = await docker.createContainer({
@@ -38,7 +38,7 @@ export async function start() {
/**
* Stop and remote the `mockserver` Docker container.
*/
export async function stop() {
async function stop() {
await container.stop();
await container.remove();
}
@@ -51,7 +51,7 @@ export async function stop() {
* @param {String} [description=`Repository ${name}`] The repository description.
* @return {Object} The `repositoryUrl` (URL without auth) and `authUrl` (URL with auth).
*/
export async function createRepo(name, branch = 'master', description = `Repository ${name}`) {
async function createRepo(name, branch = 'master', description = `Repository ${name}`) {
const exec = await container.exec({
Cmd: ['repo-admin', '-n', name, '-d', description],
AttachStdout: true,
@@ -68,3 +68,13 @@ export async function createRepo(name, branch = 'master', description = `Reposit
return {cwd, repositoryUrl, authUrl};
}
const exported = {
start,
stop,
gitCredential,
createRepo,
};
export default exported;
export {start, stop, gitCredential, createRepo};
+20 -9
View File
@@ -4,7 +4,7 @@ import got from 'got';
import pRetry from 'p-retry';
import {mockServerClient} from 'mockserver-client';
const IMAGE = 'mockserver/mockserver:latest';
const IMAGE = 'jamesdbloom/mockserver:latest';
const MOCK_SERVER_PORT = 1080;
const MOCK_SERVER_HOST = 'localhost';
const docker = new Docker();
@@ -13,7 +13,7 @@ let container;
/**
* Download the `mockserver` Docker image, create a new container and start it.
*/
export async function start() {
async function start() {
await getStream(await docker.pull(IMAGE));
container = await docker.createContainer({
@@ -30,15 +30,15 @@ export async function start() {
minTimeout: 1000,
factor: 2,
});
} catch {
} catch (_) {
throw new Error(`Couldn't start mock-server after 2 min`);
}
}
/**
* Stop and remove the `mockserver` Docker container.
* Stop and remote the `mockserver` Docker container.
*/
export async function stop() {
async function stop() {
await container.stop();
await container.remove();
}
@@ -50,7 +50,7 @@ const client = mockServerClient(MOCK_SERVER_HOST, MOCK_SERVER_PORT);
/**
* @type {string} the url of the `mockserver` instance
*/
export const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`;
const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`;
/**
* Set up the `mockserver` instance response for a specific request.
@@ -65,7 +65,7 @@ export const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`;
* @param {Object} response.body The JSON object to respond in the response body.
* @return {Object} An object representation the expectation. Pass to the `verify` function to validate the `mockserver` has been called with a `request` matching the expectations.
*/
export async function mock(
async function mock(
path,
{body: requestBody, headers: requestHeaders},
{method = 'POST', statusCode = 200, body: responseBody}
@@ -91,11 +91,22 @@ export async function mock(
}
/**
* Verify the `mockserver` has been called with a request matching expectations. The `expectation` is created with the `mock` function.
* Verify the `mockserver` has been called with a requestion matching expectations. The `expectation` is created with the `mock` function.
*
* @param {Object} expectation The expectation created with `mock` function.
* @return {Promise} A Promise that resolves if the expectation is met or reject otherwise.
*/
export function verify(expectation) {
function verify(expectation) {
return client.verify(expectation);
}
const exported = {
start,
stop,
mock,
verify,
url,
};
export default exported;
export {start, stop, mock, verify, url};
+27 -15
View File
@@ -1,32 +1,32 @@
import path, {dirname} from 'node:path';
import {fileURLToPath} from 'node:url';
import Docker from 'dockerode';
import getStream from 'get-stream';
import got from 'got';
import delay from 'delay';
import pRetry from 'p-retry';
const IMAGE = 'verdaccio/verdaccio:4';
const REGISTRY_PORT = 4873;
const REGISTRY_HOST = 'localhost';
const IMAGE = 'semanticrelease/npm-registry-docker:latest';
const SERVER_PORT = 15986;
const COUCHDB_PORT = 5984;
const SERVER_HOST = 'localhost';
const COUCHDB_USER = 'admin';
const COUCHDB_PASSWORD = 'password';
const NPM_USERNAME = 'integration';
const NPM_PASSWORD = 'suchsecure';
const NPM_EMAIL = 'integration@test.com';
const docker = new Docker();
const __dirname = dirname(fileURLToPath(import.meta.url));
let container;
/**
* Download the `npm-registry-docker` Docker image, create a new container and start it.
*/
export async function start() {
async function start() {
await getStream(await docker.pull(IMAGE));
container = await docker.createContainer({
Tty: true,
Image: IMAGE,
PortBindings: {[`${REGISTRY_PORT}/tcp`]: [{HostPort: `${REGISTRY_PORT}`}]},
Binds: [`${path.join(__dirname, 'config.yaml')}:/verdaccio/conf/config.yaml`],
PortBindings: {[`${COUCHDB_PORT}/tcp`]: [{HostPort: `${SERVER_PORT}`}]},
Env: [`COUCHDB_USER=${COUCHDB_USER}`, `COUCHDB_PASSWORD=${COUCHDB_PASSWORD}`],
});
await container.start();
@@ -34,17 +34,19 @@ export async function start() {
try {
// Wait for the registry to be ready
await pRetry(() => got(`http://${REGISTRY_HOST}:${REGISTRY_PORT}/`, {cache: false}), {
await pRetry(() => got(`http://${SERVER_HOST}:${SERVER_PORT}/registry/_design/app`, {cache: false}), {
retries: 7,
minTimeout: 1000,
factor: 2,
});
} catch {
} catch (_) {
throw new Error(`Couldn't start npm-registry-docker after 2 min`);
}
// Create user
await got(`http://${REGISTRY_HOST}:${REGISTRY_PORT}/-/user/org.couchdb.user:${NPM_USERNAME}`, {
await got(`http://${SERVER_HOST}:${SERVER_PORT}/_users/org.couchdb.user:${NPM_USERNAME}`, {
username: COUCHDB_USER,
password: COUCHDB_PASSWORD,
method: 'PUT',
json: {
_id: `org.couchdb.user:${NPM_USERNAME}`,
@@ -57,9 +59,9 @@ export async function start() {
});
}
export const url = `http://${REGISTRY_HOST}:${REGISTRY_PORT}/`;
const url = `http://${SERVER_HOST}:${SERVER_PORT}/registry/_design/app/_rewrite/`;
export const authEnv = {
const authEnv = {
npm_config_registry: url, // eslint-disable-line camelcase
NPM_USERNAME,
NPM_PASSWORD,
@@ -69,7 +71,17 @@ export const authEnv = {
/**
* Stop and remote the `npm-registry-docker` Docker container.
*/
export async function stop() {
async function stop() {
await container.stop();
await container.remove();
}
const exported = {
start,
stop,
authEnv,
url,
};
export default exported;
export {start, stop, authEnv, url};
+9 -2
View File
@@ -1,5 +1,12 @@
import {execa} from 'execa';
import execa from 'execa';
export async function npmView(packageName, env) {
async function npmView(packageName, env) {
return JSON.parse((await execa('npm', ['view', packageName, '--json'], {env})).stdout);
}
const exported = {
npmView,
};
export default exported;
export {npmView};
+3 -2
View File
@@ -1,7 +1,8 @@
import test from 'ava';
import {repeat} from 'lodash-es';
import lodash from 'lodash'
const {repeat} = lodash
import hideSensitive from '../lib/hide-sensitive.js';
import {SECRET_MIN_SIZE, SECRET_REPLACEMENT} from '../lib/definitions/constants.js';
import {SECRET_REPLACEMENT, SECRET_MIN_SIZE} from '../lib/definitions/constants.js';
test('Replace multiple sensitive environment variable values', (t) => {
const env = {SOME_PASSWORD: 'password', SOME_TOKEN: 'secret'};
+424 -409
View File
File diff suppressed because it is too large Load Diff
+31 -28
View File
@@ -1,34 +1,36 @@
import path from 'path';
import test from 'ava';
import * as td from 'testdouble';
import {escapeRegExp} from 'lodash-es';
import fsExtra from 'fs-extra';
import {execa} from 'execa';
import proxyquire from 'proxyquire';
import lodash from 'lodash'
const {escapeRegExp} = lodash
import {writeJson, readJson} from 'fs-extra';
import execa from 'execa';
import {WritableStreamBuffer} from 'stream-buffers';
import delay from 'delay';
import getAuthUrl from '../lib/get-git-auth-url.js';
import {SECRET_REPLACEMENT} from '../lib/definitions/constants.js';
import {
gitCheckout,
gitCommits,
gitGetNote,
gitHead,
gitPush,
gitRemoteTagHead,
gitRepo,
gitTagHead,
merge
} from './helpers/git-utils.js';
import {npmView} from './helpers/npm-utils.js';
import * as gitbox from './helpers/gitbox.js';
import * as mockServer from './helpers/mockserver.js';
import * as npmRegistry from './helpers/npm-registry.js';
const {readJson, writeJson} = fsExtra;
import {
gitHead,
gitTagHead,
gitRepo,
gitCommits,
gitRemoteTagHead,
gitPush,
gitCheckout,
merge,
gitGetNote,
} from './helpers/git-utils.js';
import {npmView} from './helpers/npm-utils.js';
import gitbox from './helpers/gitbox.js';
import mockServer from './helpers/mockserver.js';
import npmRegistry from './helpers/npm-registry.js';
/* eslint camelcase: ["error", {properties: "never"}] */
const requireNoCache = proxyquire.noPreserveCache();
// Environment variables used with semantic-release cli (similar to what a user would setup)
const {GITHUB_ACTION, GITHUB_TOKEN, ...processEnvWithoutGitHubActionsVariables} = process.env;
const env = {
@@ -50,10 +52,10 @@ const npmTestEnv = {
LEGACY_TOKEN: Buffer.from(`${env.NPM_USERNAME}:${env.NPM_PASSWORD}`, 'utf8').toString('base64'),
};
const cli = path.resolve('./bin/semantic-release.js');
const pluginError = path.resolve('./test/fixtures/plugin-error');
const pluginInheritedError = path.resolve('./test/fixtures/plugin-error-inherited');
const pluginLogEnv = path.resolve('./test/fixtures/plugin-log-env');
const cli = require.resolve('../bin/semantic-release');
const pluginError = require.resolve('./fixtures/plugin-error');
const pluginInheritedError = require.resolve('./fixtures/plugin-error-inherited');
const pluginLogEnv = require.resolve('./fixtures/plugin-log-env');
test.before(async () => {
await Promise.all([gitbox.start(), npmRegistry.start(), mockServer.start()]);
@@ -510,9 +512,10 @@ test('Pass options via CLI arguments', async (t) => {
});
test('Run via JS API', async (t) => {
td.replace('../lib/logger', {log: () => {}, error: () => {}, stdout: () => {}});
td.replace('env-ci', () => ({isCi: true, branch: 'master', isPr: false}));
const semanticRelease = (await import('../index.js')).default;
const semanticRelease = requireNoCache('..', {
'./lib/logger': {log: () => {}, error: () => {}, stdout: () => {}},
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const packageName = 'test-js-api';
const owner = 'git';
// Create a git repository, set the current working directory at the root of the repo
+60 -62
View File
@@ -1,16 +1,17 @@
import test from 'ava';
import {noop} from 'lodash-es';
import {stub} from 'sinon';
import lodash from 'lodash'
const {noop} = lodash
import sinon from 'sinon';
import normalize from '../../lib/plugins/normalize.js';
const cwd = process.cwd();
test.beforeEach((t) => {
// Stub the logger functions
t.context.log = stub();
t.context.error = stub();
t.context.success = stub();
t.context.stderr = {write: stub()};
t.context.log = sinon.stub);
t.context.error = sinon.stub);
t.context.success = sinon.stub);
t.context.stderr = {write: sinon.stub)};
t.context.logger = {
log: t.context.log,
error: t.context.error,
@@ -19,46 +20,46 @@ test.beforeEach((t) => {
};
});
test('Normalize and load plugin from string', async (t) => {
const plugin = await normalize(
test('Normalize and load plugin from string', (t) => {
const plugin = normalize(
{cwd, options: {}, logger: t.context.logger},
'verifyConditions',
'./test/fixtures/plugin-noop.cjs',
'./test/fixtures/plugin-noop',
{}
);
t.is(plugin.pluginName, './test/fixtures/plugin-noop.cjs');
t.is(plugin.pluginName, './test/fixtures/plugin-noop');
t.is(typeof plugin, 'function');
t.deepEqual(t.context.success.args[0], ['Loaded plugin "verifyConditions" from "./test/fixtures/plugin-noop.cjs"']);
t.deepEqual(t.context.success.args[0], ['Loaded plugin "verifyConditions" from "./test/fixtures/plugin-noop"']);
});
test('Normalize and load plugin from object', async (t) => {
const plugin = await normalize(
test('Normalize and load plugin from object', (t) => {
const plugin = normalize(
{cwd, options: {}, logger: t.context.logger},
'publish',
{path: './test/fixtures/plugin-noop.cjs'},
{path: './test/fixtures/plugin-noop'},
{}
);
t.is(plugin.pluginName, './test/fixtures/plugin-noop.cjs');
t.is(plugin.pluginName, './test/fixtures/plugin-noop');
t.is(typeof plugin, 'function');
t.deepEqual(t.context.success.args[0], ['Loaded plugin "publish" from "./test/fixtures/plugin-noop.cjs"']);
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', async (t) => {
const plugin = await normalize({cwd, options: {}, logger: t.context.logger}, 'verifyConditions', './plugin-noop.cjs', {
'./plugin-noop.cjs': './test/fixtures',
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',
});
t.is(plugin.pluginName, './plugin-noop.cjs');
t.is(plugin.pluginName, './plugin-noop');
t.is(typeof plugin, 'function');
t.deepEqual(t.context.success.args[0], [
'Loaded plugin "verifyConditions" from "./plugin-noop.cjs" in shareable config "./test/fixtures"',
'Loaded plugin "verifyConditions" from "./plugin-noop" in shareable config "./test/fixtures"',
]);
});
test('Wrap plugin in a function that add the "pluginName" to the error"', async (t) => {
const plugin = await normalize({cwd, options: {}, logger: t.context.logger}, 'verifyConditions', './plugin-error', {
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, 'verifyConditions', './plugin-error', {
'./plugin-error': './test/fixtures',
});
@@ -68,39 +69,39 @@ test('Wrap plugin in a function that add the "pluginName" to the error"', async
});
test('Wrap plugin in a function that add the "pluginName" to multiple errors"', async (t) => {
const plugin = await normalize({cwd, options: {}, logger: t.context.logger}, 'verifyConditions', './plugin-errors', {
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, 'verifyConditions', './plugin-errors', {
'./plugin-errors': './test/fixtures',
});
const errors = [...(await t.throwsAsync(plugin({options: {}}))).errors];
const errors = [...(await t.throwsAsync(plugin({options: {}})))];
for (const error of errors) {
t.is(error.pluginName, './plugin-errors');
}
});
test('Normalize and load plugin from function', async (t) => {
test('Normalize and load plugin from function', (t) => {
const pluginFunction = () => {};
const plugin = await normalize({cwd, options: {}, logger: t.context.logger}, '', pluginFunction, {});
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, '', pluginFunction, {});
t.is(plugin.pluginName, '[Function: pluginFunction]');
t.is(typeof plugin, 'function');
});
test('Normalize and load plugin that retuns multiple functions', async (t) => {
const plugin = await normalize(
test('Normalize and load plugin that retuns multiple functions', (t) => {
const plugin = normalize(
{cwd, options: {}, logger: t.context.logger},
'verifyConditions',
'./test/fixtures/multi-plugin.cjs',
'./test/fixtures/multi-plugin',
{}
);
t.is(typeof plugin, 'function');
t.deepEqual(t.context.success.args[0], ['Loaded plugin "verifyConditions" from "./test/fixtures/multi-plugin.cjs"']);
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) => {
const analyzeCommits = stub().resolves(2);
const plugin = await normalize(
const analyzeCommits = sinon.stub).resolves(2);
const plugin = normalize(
{cwd, options: {}, stderr: t.context.stderr, logger: t.context.logger},
'analyzeCommits',
analyzeCommits,
@@ -117,8 +118,8 @@ test('Wrap "analyzeCommits" plugin in a function that validate the output of the
});
test('Wrap "generateNotes" plugin in a function that validate the output of the plugin', async (t) => {
const generateNotes = stub().resolves(2);
const plugin = await normalize(
const generateNotes = sinon.stub).resolves(2);
const plugin = normalize(
{cwd, options: {}, stderr: t.context.stderr, logger: t.context.logger},
'generateNotes',
generateNotes,
@@ -135,8 +136,8 @@ test('Wrap "generateNotes" plugin in a function that validate the output of the
});
test('Wrap "publish" plugin in a function that validate the output of the plugin', async (t) => {
const publish = stub().resolves(2);
const plugin = await normalize(
const publish = sinon.stub).resolves(2);
const plugin = normalize(
{cwd, options: {}, stderr: t.context.stderr, logger: t.context.logger},
'publish',
publish,
@@ -153,8 +154,8 @@ test('Wrap "publish" plugin in a function that validate the output of the plugin
});
test('Wrap "addChannel" plugin in a function that validate the output of the plugin', async (t) => {
const addChannel = stub().resolves(2);
const plugin = await normalize(
const addChannel = sinon.stub).resolves(2);
const plugin = normalize(
{cwd, options: {}, stderr: t.context.stderr, logger: t.context.logger},
'addChannel',
addChannel,
@@ -171,10 +172,10 @@ test('Wrap "addChannel" plugin in a function that validate the output of the plu
});
test('Plugin is called with "pluginConfig" (with object definition) and input', async (t) => {
const pluginFunction = stub().resolves();
const pluginFunction = sinon.stub).resolves();
const pluginConf = {path: pluginFunction, conf: 'confValue'};
const options = {global: 'globalValue'};
const plugin = await normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin({options: {}, param: 'param'});
t.true(
@@ -186,10 +187,10 @@ test('Plugin is called with "pluginConfig" (with object definition) and input',
});
test('Plugin is called with "pluginConfig" (with array definition) and input', async (t) => {
const pluginFunction = stub().resolves();
const pluginFunction = sinon.stub).resolves();
const pluginConf = [pluginFunction, {conf: 'confValue'}];
const options = {global: 'globalValue'};
const plugin = await normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin({options: {}, param: 'param'});
t.true(
@@ -201,12 +202,12 @@ 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) => {
const pluginFunction = sinon.stub).callsFake((pluginConfig) => {
pluginConfig.conf.subConf = 'otherConf';
});
const pluginConf = {path: pluginFunction, conf: {subConf: 'originalConf'}};
const options = {globalConf: {globalSubConf: 'originalGlobalConf'}};
const plugin = await normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin({options: {}});
t.is(pluginConf.conf.subConf, 'originalConf');
@@ -214,25 +215,25 @@ test('Prevent plugins to modify "pluginConfig"', async (t) => {
});
test('Prevent plugins to modify its input', async (t) => {
const pluginFunction = stub().callsFake((pluginConfig, options) => {
const pluginFunction = sinon.stub).callsFake((pluginConfig, options) => {
options.param.subParam = 'otherParam';
});
const input = {param: {subParam: 'originalSubParam'}, options: {}};
const plugin = await normalize({cwd, options: {}, logger: t.context.logger}, '', pluginFunction, {});
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, '', pluginFunction, {});
await plugin(input);
t.is(input.param.subParam, 'originalSubParam');
});
test('Return noop if the plugin is not defined', async (t) => {
const plugin = await normalize({cwd, options: {}, logger: t.context.logger});
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) => {
// Call the normalize function with the path of a plugin that returns its config
const plugin = await normalize(
const plugin = normalize(
{cwd, options: {}, logger: t.context.logger},
'',
'./test/fixtures/plugin-result-config',
@@ -245,7 +246,7 @@ test('Always pass a defined "pluginConfig" for plugin defined with string', asyn
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 = await normalize(
const plugin = normalize(
{cwd, options: {}, logger: t.context.logger},
'',
{path: './test/fixtures/plugin-result-config'},
@@ -256,9 +257,9 @@ 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', async (t) => {
const error = await t.throwsAsync(() =>
normalize({cwd, options: {}, logger: t.context.logger}, 'nonExistentPlugin', './test/fixtures/multi-plugin.cjs', {})
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', {})
);
t.is(error.code, 'EPLUGIN');
@@ -267,13 +268,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', async (t) => {
await t.throwsAsync(
() => normalize({cwd, options: {}, logger: t.context.logger}, 'nonExistentPlugin', 'non-existing-path', {}),
{
message: /Cannot find module 'non-existing-path'/,
code: 'MODULE_NOT_FOUND',
instanceOf: Error,
}
);
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,
});
});
+48 -48
View File
@@ -1,12 +1,12 @@
import test from 'ava';
import {stub} from 'sinon';
import sinon from 'sinon';
import AggregateError from 'aggregate-error';
import pipeline from '../../lib/plugins/pipeline.js';
test('Execute each function in series passing the same input', async (t) => {
const step1 = stub().resolves(1);
const step2 = stub().resolves(2);
const step3 = stub().resolves(3);
const step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).resolves(2);
const step3 = sinon.stub).resolves(3);
const result = await pipeline([step1, step2, step3])(0);
t.deepEqual(result, [1, 2, 3]);
@@ -19,10 +19,10 @@ test('Execute each function in series passing the same input', 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);
const step4 = stub().resolves(4);
const step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).resolves(2);
const step3 = sinon.stub).resolves(3);
const step4 = sinon.stub).resolves(4);
const getNextInput = (lastResult, result) => lastResult + result;
const result = await pipeline([step1, step2, step3, step4], {settleAll: false, getNextInput})(0);
@@ -38,11 +38,11 @@ test('Execute each function in series passing a transformed input from "getNextI
});
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);
const step4 = stub().resolves(4);
const getNextInput = stub().returnsArg(0);
const step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).resolves(2);
const step3 = sinon.stub).resolves(3);
const step4 = sinon.stub).resolves(4);
const getNextInput = sinon.stub).returnsArg(0);
const result = await pipeline([step1, step2, step3, step4], {settleAll: false, getNextInput})(5);
@@ -56,12 +56,12 @@ test('Execute each function in series passing the "lastResult" and "result" to "
});
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 step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).resolves(2);
const step3 = sinon.stub).resolves(3);
const step4 = sinon.stub).resolves(4);
const getNextInput = sinon.stub).returnsArg(0);
const transform = sinon.stub).callsFake((result) => result + 1);
const result = await pipeline([step1, step2, step3, step4], {getNextInput, transform})(5);
@@ -75,12 +75,12 @@ test('Execute each function in series calling "transform" to modify the results'
});
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 step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).resolves(2);
const step3 = sinon.stub).resolves(3);
const step4 = sinon.stub).resolves(4);
const getNextInput = sinon.stub).returnsArg(0);
const transform = sinon.stub).callsFake((result) => result + 1);
const result = await pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput, transform})(5);
@@ -94,9 +94,9 @@ test('Execute each function in series calling "transform" to modify the results
});
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 step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).rejects(new Error('test error'));
const step3 = sinon.stub).resolves(3);
const error = await t.throwsAsync(pipeline([step1, step2, step3])(0), {
instanceOf: Error,
@@ -112,13 +112,13 @@ 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');
const step1 = stub().resolves(1);
const step2 = stub().rejects(new AggregateError([error1, error2]));
const step3 = stub().resolves(3);
const step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).rejects(new AggregateError([error1, error2]));
const step3 = sinon.stub).resolves(3);
const error = await t.throwsAsync(pipeline([step1, step2, step3])(0));
const errors = await t.throwsAsync(pipeline([step1, step2, step3])(0));
t.deepEqual([...error.errors], [error1, error2]);
t.deepEqual([...errors], [error1, error2]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
t.true(step3.notCalled);
@@ -127,13 +127,13 @@ test('Throw all errors from the first step throwing an AggregateError', 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);
const step2 = stub().rejects(error1);
const step3 = stub().rejects(error2);
const step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).rejects(error1);
const step3 = sinon.stub).rejects(error2);
const error = await t.throwsAsync(pipeline([step1, step2, step3], {settleAll: true})(0));
const errors = await t.throwsAsync(pipeline([step1, step2, step3], {settleAll: true})(0));
t.deepEqual([...error.errors], [error1, error2]);
t.deepEqual([...errors], [error1, error2]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
t.true(step3.calledWith(0));
@@ -144,12 +144,12 @@ test('Throw all errors from all steps throwing an AggregateError', async (t) =>
const error2 = new Error('test error 2');
const error3 = new Error('test error 3');
const error4 = new Error('test error 4');
const step1 = stub().rejects(new AggregateError([error1, error2]));
const step2 = stub().rejects(new AggregateError([error3, error4]));
const step1 = sinon.stub).rejects(new AggregateError([error1, error2]));
const step2 = sinon.stub).rejects(new AggregateError([error3, error4]));
const error = await t.throwsAsync(pipeline([step1, step2], {settleAll: true})(0));
const errors = await t.throwsAsync(pipeline([step1, step2], {settleAll: true})(0));
t.deepEqual([...error.errors], [error1, error2, error3, error4]);
t.deepEqual([...errors], [error1, error2, error3, error4]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
});
@@ -157,15 +157,15 @@ test('Throw all errors from all steps throwing an AggregateError', 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 step1 = sinon.stub).resolves(1);
const step2 = sinon.stub).rejects(error2);
const step3 = sinon.stub).rejects(error3);
const step4 = sinon.stub).resolves(4);
const getNextInput = (previousResult, result) => previousResult + result;
const error = await t.throwsAsync(pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput})(0));
const errors = await t.throwsAsync(pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput})(0));
t.deepEqual([...error.errors], [error2, error3]);
t.deepEqual([...errors], [error2, error3]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0 + 1));
t.true(step3.calledWith(0 + 1 + error2));
+46 -45
View File
@@ -1,22 +1,22 @@
import path from 'path';
import test from 'ava';
import {copy, outputFile} from 'fs-extra';
import {stub} from 'sinon';
import {temporaryDirectory} from 'tempy';
import getPlugins from '../../lib/plugins/index.js';
import sinon from 'sinon';
import tempy from 'tempy';
import getPlugins from '../../lib/plugins';
// Save the current working directory
// Save the current working diretory
const cwd = process.cwd();
test.beforeEach((t) => {
// Stub the logger functions
t.context.log = stub();
t.context.success = stub();
t.context.log = sinon.stub);
t.context.success = sinon.stub);
t.context.logger = {log: t.context.log, success: t.context.success, scope: () => t.context.logger};
});
test('Export default plugins', async (t) => {
const plugins = await getPlugins({cwd, options: {}, logger: t.context.logger}, {});
test('Export default plugins', (t) => {
const plugins = getPlugins({cwd, options: {}, logger: t.context.logger}, {});
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
@@ -29,15 +29,15 @@ test('Export default plugins', async (t) => {
t.is(typeof plugins.fail, 'function');
});
test('Export plugins based on steps config', async (t) => {
const plugins = await getPlugins(
test('Export plugins based on steps config', (t) => {
const plugins = getPlugins(
{
cwd,
logger: t.context.logger,
options: {
verifyConditions: ['./test/fixtures/plugin-noop.cjs', {path: './test/fixtures/plugin-noop.cjs'}],
generateNotes: './test/fixtures/plugin-noop.cjs',
analyzeCommits: {path: './test/fixtures/plugin-noop.cjs'},
verifyConditions: ['./test/fixtures/plugin-noop', {path: './test/fixtures/plugin-noop'}],
generateNotes: './test/fixtures/plugin-noop',
analyzeCommits: {path: './test/fixtures/plugin-noop'},
verifyRelease: () => {},
},
},
@@ -56,12 +56,13 @@ test('Export plugins based on steps config', 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 = await getPlugins(
const plugin1 = {verifyConditions: sinon.stub), publish: sinon.stub)};
const plugin2 = {verifyConditions: sinon.stub), verifyRelease: sinon.stub)};
const plugins = getPlugins(
{cwd, logger: t.context.logger, options: {plugins: [plugin1, [plugin2, {}]], verifyRelease: () => {}}},
{}
);
await plugins.verifyConditions({options: {}});
t.true(plugin1.verifyConditions.calledOnce);
t.true(plugin2.verifyConditions.calledOnce);
@@ -84,8 +85,8 @@ test('Export plugins based on "plugins" config (array)', async (t) => {
});
test('Export plugins based on "plugins" config (single definition)', async (t) => {
const plugin1 = {verifyConditions: stub(), publish: stub()};
const plugins = await getPlugins({cwd, logger: t.context.logger, options: {plugins: plugin1}}, {});
const plugin1 = {verifyConditions: sinon.stub), publish: sinon.stub)};
const plugins = getPlugins({cwd, logger: t.context.logger, options: {plugins: plugin1}}, {});
await plugins.verifyConditions({options: {}});
t.true(plugin1.verifyConditions.calledOnce);
@@ -105,10 +106,10 @@ test('Export plugins based on "plugins" config (single definition)', 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 plugin1 = [{verifyConditions: sinon.stub), publish: sinon.stub)}, {pluginOpt1: 'plugin1'}];
const plugin2 = [{verifyConditions: sinon.stub)}, {pluginOpt2: 'plugin2'}];
const plugin3 = [stub(), {pluginOpt3: 'plugin3'}];
const plugins = await getPlugins(
const plugins = getPlugins(
{
cwd,
logger: t.context.logger,
@@ -128,23 +129,23 @@ 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', async (t) => {
test('Unknown steps of plugins configured in "plugins" are ignored', (t) => {
const plugin1 = {verifyConditions: () => {}, unknown: () => {}};
const plugins = await getPlugins({cwd, logger: t.context.logger, options: {plugins: [plugin1]}}, {});
const plugins = getPlugins({cwd, logger: t.context.logger, options: {plugins: [plugin1]}}, {});
t.is(typeof plugins.verifyConditions, 'function');
t.is(plugins.unknown, undefined);
});
test('Export plugins loaded from the dependency of a shareable config module', async (t) => {
const cwd = temporaryDirectory();
const cwd = tempy.directory();
await copy(
'./test/fixtures/plugin-noop.cjs',
'./test/fixtures/plugin-noop.js',
path.resolve(cwd, 'node_modules/shareable-config/node_modules/custom-plugin/index.js')
);
await outputFile(path.resolve(cwd, 'node_modules/shareable-config/index.js'), '');
const plugins = await getPlugins(
const plugins = getPlugins(
{
cwd,
logger: t.context.logger,
@@ -170,18 +171,18 @@ test('Export plugins loaded from the dependency of a shareable config module', a
});
test('Export plugins loaded from the dependency of a shareable config file', async (t) => {
const cwd = temporaryDirectory();
await copy('./test/fixtures/plugin-noop.cjs', path.resolve(cwd, 'plugin/plugin-noop.cjs'));
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'), '');
const plugins = await getPlugins(
const plugins = getPlugins(
{
cwd,
logger: t.context.logger,
options: {
verifyConditions: ['./plugin/plugin-noop.cjs', {path: './plugin/plugin-noop.cjs'}],
generateNotes: './plugin/plugin-noop.cjs',
analyzeCommits: {path: './plugin/plugin-noop.cjs'},
verifyConditions: ['./plugin/plugin-noop', {path: './plugin/plugin-noop'}],
generateNotes: './plugin/plugin-noop',
analyzeCommits: {path: './plugin/plugin-noop'},
verifyRelease: () => {},
},
},
@@ -199,14 +200,14 @@ 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', async (t) => {
test('Use default when only options are passed for a single plugin', (t) => {
const analyzeCommits = {};
const generateNotes = {};
const publish = {};
const success = () => {};
const fail = [() => {}];
const plugins = await getPlugins(
const plugins = getPlugins(
{
cwd,
logger: t.context.logger,
@@ -234,7 +235,7 @@ test('Use default when only options are passed for a single plugin', async (t) =
});
test('Merge global options with plugin options', async (t) => {
const plugins = await getPlugins(
const plugins = getPlugins(
{
cwd,
logger: t.context.logger,
@@ -252,9 +253,9 @@ 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', async (t) => {
test('Throw an error for each invalid plugin configuration', (t) => {
const errors = [
...(await t.throwsAsync(() =>
...t.throws(() =>
getPlugins(
{
cwd,
@@ -269,7 +270,7 @@ test('Throw an error for each invalid plugin configuration', async (t) => {
},
{}
)
)).errors,
),
];
t.is(errors[0].name, 'SemanticReleaseError');
@@ -282,18 +283,18 @@ test('Throw an error for each invalid plugin configuration', async (t) => {
t.is(errors[3].code, 'EPLUGINCONF');
});
test('Throw EPLUGINSCONF error if the "plugins" option contains an old plugin definition (returns a function)', async (t) => {
test('Throw EPLUGINSCONF error if the "plugins" option contains an old plugin definition (returns a function)', (t) => {
const errors = [
...(await t.throwsAsync(() =>
...t.throws(() =>
getPlugins(
{
cwd,
logger: t.context.logger,
options: {plugins: ['./test/fixtures/multi-plugin.cjs', './test/fixtures/plugin-noop.cjs', () => {}]},
options: {plugins: ['./test/fixtures/multi-plugin', './test/fixtures/plugin-noop', () => {}]},
},
{}
)
)).errors,
),
];
t.is(errors[0].name, 'SemanticReleaseError');
@@ -302,11 +303,11 @@ 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', async (t) => {
test('Throw EPLUGINSCONF error for each invalid definition if the "plugins" option', (t) => {
const errors = [
...(await t.throwsAsync(() =>
...t.throws(() =>
getPlugins({cwd, logger: t.context.logger, options: {plugins: [1, {path: 1}, [() => {}, {}, {}]]}}, {})
)).errors,
),
];
t.is(errors[0].name, 'SemanticReleaseError');
+6 -6
View File
@@ -1,5 +1,5 @@
import test from 'ava';
import {loadPlugin, parseConfig, validatePlugin, validateStep} from '../../lib/plugins/utils.js';
import {validatePlugin, validateStep, loadPlugin, parseConfig} from '../../lib/plugins/utils.js';
test('validatePlugin', (t) => {
const path = 'plugin-module';
@@ -189,17 +189,17 @@ test('validateStep: required plugin configuration', (t) => {
);
});
test('loadPlugin', async (t) => {
test('loadPlugin', (t) => {
const cwd = process.cwd();
const func = () => {};
t.is((await import('../fixtures/plugin-noop.cjs')).default, await loadPlugin({cwd: './test/fixtures'}, './plugin-noop.cjs', {}), 'From cwd');
t.is(require('../fixtures/plugin-noop'), loadPlugin({cwd: './test/fixtures'}, './plugin-noop', {}), 'From cwd');
t.is(
(await import('../fixtures/plugin-noop.cjs')).default,
await loadPlugin({cwd}, './plugin-noop.cjs', {'./plugin-noop.cjs': './test/fixtures'}),
require('../fixtures/plugin-noop'),
loadPlugin({cwd}, './plugin-noop', {'./plugin-noop': './test/fixtures'}),
'From a shareable config context'
);
t.is(func, await loadPlugin({cwd}, func, {}), 'Defined as a function');
t.is(func, loadPlugin({cwd}, func, {}), 'Defined as a function');
});
test('parseConfig', (t) => {
+10 -9
View File
@@ -1,20 +1,21 @@
import test from 'ava';
import AggregateError from 'aggregate-error';
import {
extractErrors,
tagsToVersions,
isMajorRange,
isMaintenanceRange,
getUpperBound,
getLowerBound,
highest,
lowest,
getLatestVersion,
getEarliestVersion,
getFirstVersion,
getLatestVersion,
getLowerBound,
getRange,
getUpperBound,
highest,
isMaintenanceRange,
isMajorRange,
isSameChannel,
lowest,
makeTag,
tagsToVersions
isSameChannel,
} from '../lib/utils.js';
test('extractErrors', (t) => {

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