Compare commits
@@ -0,0 +1,48 @@
|
||||
<!--
|
||||
Please fill the informations requested or use one of the following url:
|
||||
- Bug report: https://github.com/semantic-release/semantic-release/issues/new?template=bug-report.md
|
||||
- Feature request: https://github.com/semantic-release/semantic-release/issues/new?template=feature-request.md
|
||||
- New plugin request: https://github.com/semantic-release/semantic-release/issues/new?template=plugin-request.md
|
||||
-->
|
||||
|
||||
<!--------------------- FOR BUG REPORT ONLY --------------------->
|
||||
|
||||
## Current behavior
|
||||
|
||||
<!-- Describe how the issue manifests. -->
|
||||
|
||||
## Expected behavior
|
||||
|
||||
<!-- Describe what the desired behavior would be. -->
|
||||
|
||||
## Environment
|
||||
|
||||
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
|
||||
- CI environment: <!-- CI service name -->
|
||||
- Plugins used: <!-- List semantic-release plugin used if any -->
|
||||
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
|
||||
- CI logs: <!-- link to your CI logs or semantic-release logs -->
|
||||
|
||||
<!--------------------- FOR FEATURE REQUEST ONLY --------------------->
|
||||
|
||||
## New feature motivation
|
||||
|
||||
<!-- Describe the context, the use-case and the advantages of the feature request. -->
|
||||
|
||||
## New feature description
|
||||
|
||||
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
|
||||
|
||||
## New feature implementation
|
||||
|
||||
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
|
||||
|
||||
<!--------------------- FOR NEW PLUGIN REQUEST ONLY --------------------->
|
||||
|
||||
## New plugin motivation
|
||||
|
||||
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
|
||||
|
||||
## Third-party documentation
|
||||
|
||||
<!-- Provide explanation and documentation links for the platform to integrate with. -->
|
||||
@@ -0,0 +1,17 @@
|
||||
# Bug report
|
||||
|
||||
## Current behavior
|
||||
|
||||
<!-- Describe how the issue manifests. -->
|
||||
|
||||
## Expected behavior
|
||||
|
||||
<!-- Describe what the desired behavior would be. -->
|
||||
|
||||
## Environment
|
||||
|
||||
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
|
||||
- CI environment: <!-- CI service name -->
|
||||
- Plugins used: <!-- List semantic-release plugin used if any -->
|
||||
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
|
||||
- CI logs: <!-- link to your CI logs or semantic-release logs -->
|
||||
@@ -0,0 +1,13 @@
|
||||
# Feature request
|
||||
|
||||
## New feature motivation
|
||||
|
||||
<!-- Describe the context, the use-case and the advantages of the feature request. -->
|
||||
|
||||
## New feature description
|
||||
|
||||
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
|
||||
|
||||
## New feature implementation
|
||||
|
||||
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
|
||||
@@ -0,0 +1,9 @@
|
||||
# New plugin request
|
||||
|
||||
## New plugin motivation
|
||||
|
||||
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
|
||||
|
||||
## Third-party documentation
|
||||
|
||||
<!-- Provide explanation and documentation links for the platform to integrate with. -->
|
||||
@@ -0,0 +1 @@
|
||||
base: app0ZOxG0FnHmOiuU
|
||||
+3
-5
@@ -125,11 +125,9 @@ $RECYCLE.BIN/
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# End of https://www.gitignore.io/api/macos,windows,linux,node
|
||||
|
||||
# Lockfiles
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
|
||||
# Registry tests
|
||||
test/helpers/registry/couch
|
||||
test/helpers/registry/data
|
||||
# Gitbook
|
||||
_book
|
||||
|
||||
+10
-4
@@ -1,10 +1,10 @@
|
||||
language: node_js
|
||||
|
||||
services:
|
||||
- couchdb
|
||||
- docker
|
||||
notifications:
|
||||
email: false
|
||||
|
||||
node_js:
|
||||
- 9
|
||||
- 8
|
||||
|
||||
# Trigger a push build on caribou and greenkeeper branches + PRs build on every branches
|
||||
@@ -23,4 +23,10 @@ script:
|
||||
|
||||
after_success:
|
||||
- npm run codecov
|
||||
- npm run semantic-release
|
||||
|
||||
jobs:
|
||||
include:
|
||||
- stage: release
|
||||
node_js: lts/*
|
||||
script:
|
||||
- npm run semantic-release
|
||||
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
# Contributing to semantic-release
|
||||
|
||||
✨ Thanks for contributing to **semantic-release**! ✨
|
||||
|
||||
As a contributor, here are the guidelines we would like you to follow:
|
||||
- [Code of conduct](#code-of-conduct)
|
||||
- [How can I contribute?](#how-can-i-contribute)
|
||||
- [Using the issue tracker](#using-the-issue-tracker)
|
||||
- [Submitting a Pull Request](#submitting-a-pull-request)
|
||||
- [Coding rules](#coding-rules)
|
||||
- [Working with the code](#working-with-the-code)
|
||||
|
||||
We also recommend to read [How to Contribute to Open Source](https://opensource.guide/how-to-contribute).
|
||||
|
||||
## Code of conduct
|
||||
|
||||
Help us keep **semantic-release** open and inclusive. Please read and follow our [Code of conduct](CODE_OF_CONDUCT.md).
|
||||
|
||||
## How can I contribute?
|
||||
|
||||
### Improve documentation
|
||||
|
||||
As a **semantic-release** user you are the perfect candidate to help us improve our documentation: typo corrections, clarifications, more examples, new [recipes](docs/recipes/README.md) etc. Take a look at the [documentation issues that need help](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22+label%3Adocs+).
|
||||
|
||||
Please follow the [Documentation guideline](#documentation).
|
||||
|
||||
### Give feedback on issues
|
||||
|
||||
Some issues are created without information requested in the [Bug report guideline](#bug-report). Help making them easier to resolve by adding any relevant informations.
|
||||
|
||||
Issues with the [design label](https://github.com/issues?q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3Adesign) are meant to discuss the implementation of new features. Participating in the discussion is a good opportunity to get involved and influence the future direction of **semantic-release**.
|
||||
|
||||
### Fix bugs and implement features
|
||||
|
||||
Confirmed bug and ready to implement features are marked with the [help wanted label](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22). Post a comment on an issue to indicate you would like to work on it and to request help from the [@semantic-release/maintainers](https://github.com/orgs/semantic-release/teams/contributors) and the community.
|
||||
|
||||
## Using the issue tracker
|
||||
|
||||
The issue tracker is the channel for [bug reports](#bug-report), [features requests](#feature-request) and [submitting pull requests](#submitting-a-pull-request) only. Please use the [Support](docs/support/README.md) and [Get help](README.md#get-help) sections for support, troubleshooting and questions.
|
||||
|
||||
Before opening an Issue or a Pull Request, please use the [GitHub issue search](https://github.com/issues?utf8=%E2%9C%93&q=user%3Asemantic-release) to make the bug or feature request hasn't been already reported or fixed.
|
||||
|
||||
### Bug report
|
||||
|
||||
A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report and fill the information requested in the [Bug report template](https://github.com/semantic-release/semantic-release/issues/new?template=bug-report.md).
|
||||
|
||||
### Feature request
|
||||
|
||||
Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible and fill the information requested in the [Feature request template](https://github.com/semantic-release/semantic-release/issues/new?template=feature-request.md).
|
||||
|
||||
### New plugin request
|
||||
|
||||
[Plugins](docs/usage/plugins.md) are a great way to extend **semantic-release** capabilities, integrate with other systems and support new project type. Please provide as much detail and context as possible and fill the information requested in the [New plugin request template](https://github.com/semantic-release/semantic-release/issues/new?template=plugin-request.md).
|
||||
|
||||
## Submitting a Pull Request
|
||||
|
||||
Good pull requests whether patches, improvements or new features are a fantastic help. They should remain focused in scope and avoid containing unrelated commits.
|
||||
|
||||
**Please ask first** before embarking on any significant pull request (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project.
|
||||
|
||||
If you never created a pull request before, welcome 🎉 😄. [Here is a great tutorial](https://opensource.guide/how-to-contribute/#opening-a-pull-request) on how to send one :)
|
||||
|
||||
Here is a summary of the steps to follow:
|
||||
|
||||
1. [Set up the workspace](#set-up-the-workspace)
|
||||
2. If you cloned a while ago, get the latest changes from upstream and update dependencies:
|
||||
```bash
|
||||
$ git checkout master
|
||||
$ git pull upstream master
|
||||
$ rm -rf node_modules
|
||||
$ npm install
|
||||
```
|
||||
3. Create a new topic branch (off the main project development branch) to contain your feature, change, or fix:
|
||||
```bash
|
||||
$ git checkout -b <topic-branch-name>
|
||||
```
|
||||
4. Make your code changes, following the [Coding rules](#coding-rules)
|
||||
5. Push your topic branch up to your fork:
|
||||
```bash
|
||||
$ git push origin <topic-branch-name>
|
||||
```
|
||||
6. [Open a Pull Request](https://help.github.com/articles/creating-a-pull-request/#creating-the-pull-request) with a clear title and description.
|
||||
|
||||
**Tips**:
|
||||
- For ambitious tasks, open a Pull Request as soon as possible with the `[WIP]` prefix i nthe title, in order to get feedback and help from the community.
|
||||
- [Allow semantic-release maintainers to make changes to you Pull Request branch](https://help.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork) this way we can rebase it and make some minor changes if necessary. All changes we make will be done in new commit and we'll ask for your approval before merging them.
|
||||
|
||||
## Coding rules
|
||||
|
||||
### Source code
|
||||
|
||||
To ensure consistency and quality throughout the source code, all code modification must have:
|
||||
- No [linting](#lint) errors
|
||||
- A [test](#tests) for every possible cases introduced by your code change
|
||||
- **100%** test coverage
|
||||
- [Valid commit message(s)](#commit-message-guidelines)
|
||||
- Documentation for new features
|
||||
- Updated documentation for modified features
|
||||
|
||||
### Documentation
|
||||
|
||||
To ensure consistency and quality all documentation modification must:
|
||||
- Refer to brand in [bold](https://help.github.com/articles/basic-writing-and-formatting-syntax/#styling-text) with proper capitalization, i.e. **GitHub**, **semantic-release**, **npm**
|
||||
- Prefer [tables](https://help.github.com/articles/organizing-information-with-tables) over [lists](https://help.github.com/articles/basic-writing-and-formatting-syntax/#lists) when listing key values, i.e. List of options with their description
|
||||
- Use [links](https://help.github.com/articles/basic-writing-and-formatting-syntax/#links) when, the first you are referring to:
|
||||
- a **semantic-release** concept described somewhere else in the documentation, i.e. How to [contribute](CONTRIBUTING.md)
|
||||
- a third-party product/brand/service, i.e. Integrate with [GitHub](https://github.com)
|
||||
- an external concept or feature, i.e. Create a [GitHub release](https://help.github.com/articles/creating-releases)
|
||||
- a package or module, i.e. The [`@semantic-release/github`](https://github.com/semantic-release/github) module
|
||||
- Use the the [single backtick `code` quoting](https://help.github.com/articles/basic-writing-and-formatting-syntax/#quoting-code) for:
|
||||
- commands inside sentences, i.e. the `semantic-release` command
|
||||
- programming language keywords, i.e. `function`, `async`, `String`
|
||||
- packages or modules, i.e. The [`@semantic-release/github`](https://github.com/semantic-release/github) module
|
||||
- Use the the [triple backtick `code` formatting](https://help.github.com/articles/creating-and-highlighting-code-blocks) for:
|
||||
- code examples
|
||||
- configuration examples
|
||||
- sequence of command lines
|
||||
|
||||
### Commit message guidelines
|
||||
|
||||
#### Atomic commits
|
||||
|
||||
If possible, make [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit), which means:
|
||||
- a commit should contain exactly one self-contained functional change
|
||||
- a functional change should be contained in exactly one commit
|
||||
- a commit should not create an inconsistent state (such as test errors, linting errors, partial fix, feature with documentation etc...)
|
||||
|
||||
A complex feature can be broken down into multiple commits as long as each one keep a consistent state and consist of a self-contained change.
|
||||
|
||||
#### Commit message format
|
||||
|
||||
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special format that includes a **type**, a **scope** and a **subject**:
|
||||
|
||||
```commit
|
||||
<type>(<scope>): <subject>
|
||||
<BLANK LINE>
|
||||
<body>
|
||||
<BLANK LINE>
|
||||
<footer>
|
||||
```
|
||||
|
||||
The **header** is mandatory and the **scope** of the header is optional.
|
||||
|
||||
The **footer** can contain a [closing reference to an issue](https://help.github.com/articles/closing-issues-via-commit-messages).
|
||||
|
||||
#### Revert
|
||||
|
||||
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header of the reverted commit. In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit being reverted.
|
||||
|
||||
#### Type
|
||||
|
||||
The type must be one of the following:
|
||||
|
||||
| Type | Description |
|
||||
|--------------|-------------------------------------------------------------------------------------------------------------|
|
||||
| **build** | Changes that affect the build system or external dependencies (example scopes: gulp, broccoli, npm) |
|
||||
| **ci** | Changes to our CI configuration files and scripts (example scopes: Travis, Circle, BrowserStack, SauceLabs) |
|
||||
| **docs** | Documentation only changes |
|
||||
| **feat** | A new feature |
|
||||
| **fix** | A bug fix |
|
||||
| **perf** | A code change that improves performance |
|
||||
| **refactor** | A code change that neither fixes a bug nor adds a feature |
|
||||
| **style** | Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) |
|
||||
| **test** | Adding missing tests or correcting existing tests |
|
||||
|
||||
#### Subject
|
||||
|
||||
The subject contains succinct description of the change:
|
||||
|
||||
- use the imperative, present tense: "change" not "changed" nor "changes"
|
||||
- don't capitalize first letter
|
||||
- no dot (.) at the end
|
||||
|
||||
#### Body
|
||||
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
|
||||
The body should include the motivation for the change and contrast this with previous behavior.
|
||||
|
||||
#### Footer
|
||||
The footer should contain any information about **Breaking Changes** and is also the place to reference GitHub issues that this commit **Closes**.
|
||||
|
||||
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines. The rest of the commit message is then used for this.
|
||||
|
||||
#### Examples
|
||||
|
||||
```commit
|
||||
`fix(pencil): stop graphite breaking when too much pressure applied`
|
||||
```
|
||||
|
||||
```commit
|
||||
`feat(pencil): add 'graphiteWidth' option`
|
||||
|
||||
Fix #42
|
||||
```
|
||||
|
||||
```commit
|
||||
perf(pencil): remove graphiteWidth option`
|
||||
|
||||
BREAKING CHANGE: The graphiteWidth option has been removed.
|
||||
|
||||
The default graphite width of 10mm is always used for performance reasons.
|
||||
```
|
||||
|
||||
## Working with the code
|
||||
|
||||
### Set up the workspace
|
||||
|
||||
[Fork](https://guides.github.com/activities/forking/#fork) the project, [clone](https://guides.github.com/activities/forking/#clone) your fork, configure the remotes and install the dependencies:
|
||||
|
||||
```bash
|
||||
# Clone your fork of the repo into the current directory
|
||||
$ git clone https://github.com/semantic-release/<repo-name>
|
||||
# Navigate to the newly cloned directory
|
||||
$ cd <repo-name>
|
||||
# Assign the original repo to a remote called "upstream"
|
||||
$ git remote add upstream https://github.com/semantic-release/<repo-name>
|
||||
# Install the dependencies
|
||||
$ npm install
|
||||
```
|
||||
|
||||
### Lint
|
||||
|
||||
All the [semantic-release](https://github.com/semantic-release) repository use [XO](https://github.com/sindresorhus/xo) for linting and [Prettier](https://prettier.io) for formatting. Prettier formatting will be automatically verified and fixed by XO.
|
||||
|
||||
Before pushing your code changes make sure there is no linting errors with `npm run lint`.
|
||||
|
||||
**Tips**:
|
||||
- Most linting errors can be automatically fixed with `npm run lint --fix`.
|
||||
- Install the [XO plugin](https://github.com/sindresorhus/xo#editor-plugins) for your editor to see linting error directly in your editor and automatically fix them on save.
|
||||
|
||||
### Tests
|
||||
|
||||
Running the integration test require to install [Docker](https://docs.docker.com/engine/installation) on your machine.
|
||||
|
||||
All the [semantic-release](https://github.com/semantic-release) repository use [AVA](https://github.com/avajs/ava) for writing and running tests.
|
||||
|
||||
Before pushing your code changes make sure all **test pass** and the **coverage is 100%**:
|
||||
|
||||
```bash
|
||||
$ npm run test
|
||||
```
|
||||
|
||||
**Tips:** During development you can:
|
||||
- run only a subset of test files with `ava <glob>`, for example `ava test/mytestfile.test.js`
|
||||
- run in watch mode with `ava -w` to automatically run a test file when you modify it
|
||||
- run only the test you are working on by adding [`.only` to the test definition](https://github.com/avajs/ava#running-specific-tests)
|
||||
|
||||
### Commits
|
||||
|
||||
All the [semantic-release](https://github.com/semantic-release) repository use [Commitizen](https://github.com/commitizen/cz-cli) to help you create [valid commit messages](#commit-message-guidelines).
|
||||
|
||||
After staging your changes with `git add`, run `npm run cm` to start the interactive commit message CLI.
|
||||
@@ -1,297 +1,128 @@
|
||||
# :package::rocket: semantic-release
|
||||
<h1 align="center" style="border-bottom: none;">📦🚀 semantic-release</h1>
|
||||
<h3 align="center">Fully automated version management and package publishing</h3>
|
||||
<p align="center">
|
||||
<a href="https://gitter.im/semantic-release/semantic-release">
|
||||
<img alt="Gitter" src="https://badges.gitter.im/semantic-release/semantic-release.svg">
|
||||
</a>
|
||||
<a href="https://travis-ci.org/semantic-release/semantic-release">
|
||||
<img alt="Travis" src="https://img.shields.io/travis/semantic-release/semantic-release/caribou.svg">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/semantic-release/semantic-release">
|
||||
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/semantic-release/semantic-release/caribou.svg">
|
||||
</a>
|
||||
<a href="https://greenkeeper.io">
|
||||
<img alt="Greenkeeper" src="https://badges.greenkeeper.io/semantic-release/semantic-release.svg">
|
||||
</a>
|
||||
<a href="#badge">
|
||||
<img alt="semantic-release" src="https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg">
|
||||
</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<a href="https://www.npmjs.com/package/semantic-release">
|
||||
<img alt="npm latest version" src="https://img.shields.io/npm/v/semantic-release/latest.svg">
|
||||
</a>
|
||||
<a href="https://www.npmjs.com/package/semantic-release">
|
||||
<img alt="npm next version" src="https://img.shields.io/npm/v/semantic-release/next.svg">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
**fully automated package publishing**
|
||||
**semantic-release** automates the whole package release workflow including: determining the next version number, generating the release notes and publishing the package.
|
||||
|
||||
> **Trust us, this will change your workflow for the better.**
|
||||
This removes the immediate connection between human emotions and version numbers, strictly following the [Semantic Versioning](http://semver.org) specification.
|
||||
|
||||
> – [egghead.io](https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release)
|
||||
> Trust us, this will change your workflow for the better. – [egghead.io](https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release)
|
||||
|
||||
[](https://gitter.im/semantic-release/semantic-release?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](https://www.npmjs.com/package/semantic-release)
|
||||
[](https://greenkeeper.io/)
|
||||
[](https://github.com/semantic-release/semantic-release/blob/master/LICENSE)
|
||||
[](https://github.com/prettier/prettier)
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
[](http://commitizen.github.io/cz-cli/)
|
||||
## Highlights
|
||||
|
||||
[](https://travis-ci.org/semantic-release/semantic-release)
|
||||
[](https://codecov.io/gh/semantic-release/semantic-release)
|
||||
|
||||
Out of the box this is just about _commit-messages_, but you can do so much more.
|
||||
|
||||
* **Detect breaking changes** using the test suite of your last release: [cracks](https://github.com/semantic-release/cracks)
|
||||
* Detect breaking changes using your dependents’ test suites: [Help out! Implement the **dont-break** plugin](https://github.com/semantic-release/semantic-release/issues/65)
|
||||
* Detect breaking changes diffing your JSDoc interface: [Help out! Implement the **india** plugin](https://github.com/semantic-release/semantic-release/issues/66)
|
||||
* Abort releases with **insufficient test coverage**: [Help out! Implement the **istanbul** plugin](https://github.com/semantic-release/semantic-release/issues/68)
|
||||
* Abort releases with **vulnerable dependencies** in the tree: [Help out! Implement the **nsp** plugin](https://github.com/semantic-release/semantic-release/issues/67)
|
||||
* Everything you can imagine: [Build Plugins!](https://github.com/semantic-release/semantic-release#plugins)
|
||||
|
||||
| Commands | Comment
|
||||
--- | --- | ---
|
||||
| **manual/before** | <pre><code><div>npm version major</div><div>git push origin master --tags</div><div>npm publish</div></code></pre> | You **manually decide** what the **next version** is. You have to remember what major, minor and patch means. You have to remember to push both commits and tags. You have to wait for the CI to pass. |
|
||||
| **semantic-release/after** | <pre><code><div>git commit -m "fix: <message>"</div><div>git push</div></code></pre> | You **describe the changes** you’ve made. A new version is automatically published with the correct version number.
|
||||
|
||||
This removes the immediate connection between human emotions and version numbers, so strictly following the [SemVer](http://semver.org/) spec is not a problem anymore – and that’s ultimately `semantic-release`’s goal.
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th colspan="2">
|
||||
“How to Write a JavaScript Library - Automating Releases with semantic-release” – egghead.io
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
<a href="https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release"><img src="https://cloud.githubusercontent.com/assets/908178/9730739/7b1da5d8-5610-11e5-88b6-5c75fdda7ee2.png" alt="egghead.io session"></a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2">
|
||||
A free egghead.io tutorial series on how to write an open source library featuring semantic-release.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th>
|
||||
“We fail to follow SemVer – and why it needn’t matter”
|
||||
</th>
|
||||
<th>
|
||||
“semantic-release Q&A with Kent C. Dodds”
|
||||
</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://www.youtube.com/watch?v=tc2UgG5L7WM&index=6&list=PLFZ5NyC0xHDaaTy6tY9p0C0jd_rRRl5Zm"><img alt="JSConfBP Talk" src="https://cloud.githubusercontent.com/assets/908178/9428178/c337ed26-49a2-11e5-8ad0-a602500a65bf.png"></a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://www.youtube.com/watch?v=g6y3DnhkjrI"><img alt="Hangout on Air with Kent C. Dodds" src="https://cloud.githubusercontent.com/assets/908178/9428179/c3387318-49a2-11e5-9f5f-dccd3fbb0c1d.png"></a>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
This talk gives you a complete introduction to the underlying concepts of this module. 38:30
|
||||
</td>
|
||||
<td>
|
||||
A “Hangouts on Air” conversation with hands on questions and answers about how to use semantic-release. 53:52
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
- Fully automated release
|
||||
- Enforce [Semantic Versioning](https://semver.org) specification
|
||||
- New features and fixes are immediately available to users
|
||||
- Use formalized commit message convention to document changes in the codebase
|
||||
- Integrate with your [continuous integration workflow](docs/recipes/README.md#ci-configurations)
|
||||
- Avoid potential errors associated with manual releases
|
||||
- Support any [package managers and languages](docs/recipes/README.md#package-managers-and-languages) via [plugins](docs/usage/plugins.md)
|
||||
- Simple and reusable configuration via [shareable configurations](docs/usage/shareable-configurations.md)
|
||||
|
||||
## How does it work?
|
||||
|
||||
Instead of writing [meaningless commit messages](http://whatthecommit.com/), we can take our time to think about the changes in the codebase and write them down. Following formalized conventions it is then possible to generate a helpful changelog and to derive the next semantic version number from them.
|
||||
|
||||
When `semantic-release` is set up it will do that after every successful continuous integration build of your master branch (or any other branch you specify) and publish the new version for you. This way no human is directly involved in the release process and your releases are guaranteed to be [unromantic and unsentimental](http://sentimentalversioning.org/).
|
||||
|
||||
If you fear the loss of control over timing and marketing implications of software releases you should know that `semantic-release` supports [release channels](https://github.com/npm/npm/issues/2718) using `npm`’s [dist-tags](https://docs.npmjs.com/cli/dist-tag). This way you can keep control over what your users end up using by default, you can decide when to promote an automatically released version to the stable channel, and you can choose which versions to write blogposts and tweets about. You can use the same mechanism to [support older versions of your software](https://gist.github.com/boennemann/54042374e49c7ade8910), for example with important security fixes.
|
||||
|
||||
When pushing new commits with `git push` a CI build is triggered. After running the tests the command `semantic-release` will execute the following tasks in series:
|
||||
|
||||
| Step | Description |
|
||||
| ------------------ | ------------------------------------------------------------------------------------------- |
|
||||
| Verify Conditions` | Run the [verifyConditions](#verifyConditions) plugin) |
|
||||
| Get last release` | Obtain last release with the [getLastRelease](#getLastRelease) plugin |
|
||||
| Analyze commits | Determine the type of release to do with the [analyzeCommits](#analyzeCommits) plugin |
|
||||
| Verify release | Call the [verifyRelease](#verifyRelease) plugin |
|
||||
| npm publish | Update the version in `package.json` and call `npm publish` |
|
||||
| Generate notes | Generate release notes with plugin [generateNotes](#generateNotes) |
|
||||
| Github release | A git tag and [Github release](https://help.github.com/articles/about-releases/) is created |
|
||||
|
||||
_Note:_ The current release/tag implementation is tied to GitHub, but could be opened up to Bitbucket, GitLab, et al. Feel free to send PRs for these services.
|
||||
|
||||
## Default Commit Message Format
|
||||
|
||||
This module ships with the [AngularJS Commit Message Conventions](https://docs.google.com/document/d/1QrDFcIiPjSLDn3EL15IJygNPiHORgU1_OOAqWjiDU5Y/edit) and changelog generator, but you can [define your own](#plugins) style.
|
||||
|
||||
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special
|
||||
format that includes a **type**, a **scope** and a **subject** ([full explanation](https://github.com/stevemao/conventional-changelog-angular/blob/master/convention.md)):
|
||||
|
||||
```
|
||||
<type>(<scope>): <subject>
|
||||
<BLANK LINE>
|
||||
<body>
|
||||
<BLANK LINE>
|
||||
<footer>
|
||||
```
|
||||
|
||||
You can simplify using this convention for yourself and contributors by using [commitizen](https://github.com/commitizen/cz-cli) and [commitlint](https://github.com/marionebl/commitlint) or [semantic-git-commit-cli](https://github.com/JPeer264/node-semantic-git-commit-cli).
|
||||
|
||||
### Patch Release
|
||||
|
||||
```
|
||||
fix(pencil): stop graphite breaking when too much pressure applied
|
||||
```
|
||||
|
||||
### ~~Minor~~ Feature Release
|
||||
|
||||
```
|
||||
feat(pencil): add 'graphiteWidth' option
|
||||
```
|
||||
|
||||
### ~~Major~~ Breaking Release
|
||||
|
||||
```
|
||||
perf(pencil): remove graphiteWidth option
|
||||
|
||||
BREAKING CHANGE: The graphiteWidth option has been removed. The default graphite width of 10mm is always used for performance reasons.
|
||||
```
|
||||
|
||||
## Setup
|
||||
|
||||
[](https://nodei.co/npm/semantic-release/)
|
||||
|
||||
```bash
|
||||
npm install -g semantic-release-cli
|
||||
|
||||
cd your-module
|
||||
semantic-release-cli setup
|
||||
```
|
||||
|
||||

|
||||
|
||||
_[This is what happens under the hood.](https://github.com/semantic-release/cli#what-it-does)_
|
||||
|
||||
## Options
|
||||
|
||||
You can pass options either via command line (in [kebab-case](https://lodash.com/docs#kebabCase)) or in the `release` field of your `package.json` (in [camelCase](https://lodash.com/docs#camelCase)). The following two examples are the same, but CLI arguments take precedence.
|
||||
|
||||
##### CLI
|
||||
```bash
|
||||
semantic-release --branch next
|
||||
```
|
||||
|
||||
##### package.json
|
||||
```json
|
||||
"release": {
|
||||
"branch": "next"
|
||||
}
|
||||
```
|
||||
```bash
|
||||
semantic-release
|
||||
```
|
||||
|
||||
These options are currently available:
|
||||
- `branch`: The branch on which releases should happen. Default: `'master'`
|
||||
- `dry-run`: Dry-run mode, skipping verifyConditions, publishing and release, printing next version and release notes
|
||||
- `debug`: Output debugging information
|
||||
- `githubToken`: The token used to authenticate with GitHub. Default: `process.env.GH_TOKEN`
|
||||
- `githubUrl`: Optional. Pass your GitHub Enterprise endpoint.
|
||||
- `githubApiPathPrefix`: Optional. The path prefix for your GitHub Enterprise API.
|
||||
|
||||
_A few notes on `npm` config_:
|
||||
1. The `npm` token can only be defined in the environment as `NPM_TOKEN`, because that’s where `npm` itself is going to read it from.
|
||||
|
||||
2. In order to publish to a different `npm` registry you can specify that inside the `package.json`’s [`publishConfig`](https://docs.npmjs.com/files/package.json#publishconfig) field.
|
||||
|
||||
3. If you want to use another dist-tag for your publishes than `'latest'` you can specify that inside the `package.json`’s [`publishConfig`](https://docs.npmjs.com/files/package.json#publishconfig) field.
|
||||
|
||||
4. `semantic-release` generally tries to orientate itself towards `npm` – it inherits the loglevel for example.
|
||||
|
||||
## Plugins
|
||||
|
||||
There are numerous steps where you can customize `semantic-release`’s behaviour using plugins. A plugin is a regular [option](#options), but passed inside the `release` block of `package.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"release": {
|
||||
"analyzeCommits": "npm-module-name",
|
||||
"generateNotes": "./path/to/a/local/module",
|
||||
"verifyConditions": {
|
||||
"path": "./path/to/a/module",
|
||||
"additional": "config"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```
|
||||
semantic-release --analyze-commits="npm-module-name"
|
||||
```
|
||||
|
||||
A plugin itself is an async function that always receives three arguments.
|
||||
|
||||
```js
|
||||
module.exports = function (pluginConfig, config, callback) {}
|
||||
```
|
||||
|
||||
- `pluginConfig`: If the user of your plugin specifies additional plugin config in the `package.json` (see the `verifyConditions` example above) then it’s this object.
|
||||
- `config`: A config object containing a lot of information to act upon.
|
||||
- `env`: All environment variables
|
||||
- `npm`: Select npm configuration bits like `registry`, `tag` and `auth`
|
||||
- `options`: `semantic-release` options like `debug`, or `branch`
|
||||
- `pkg`: Parsed `package.json`
|
||||
- For certain plugins the `config` object contains even more information. See below.
|
||||
- `callback`: If an error occurs pass it as first argument. Otherwise pass your result as second argument.
|
||||
|
||||
|
||||
### `analyzeCommits`
|
||||
|
||||
This plugin is responsible for determining the type of the next release. It additionally receives a `commits` array inside `config`. One commit is an object with a `message` and `hash` property. Call the callback with `'major'`, `'premajor'`, `'minor'`, `'preminor'`, `'patch'`, `'prepatch'`, `'prerelease'`, or `null` if nothing changed.
|
||||
|
||||
While it may be tempting to use `'prepatch'`, `'preminor'` & `'prerelease'` as part of a release process, this is strongly discouraged. A better approach is to use [dist-tags](https://docs.npmjs.com/cli/dist-tag) to create release channels (such as 'latest', 'next', 'stable') and to return only `'major'`, `'premajor'` and `'minor'` from the commit analyzer.
|
||||
|
||||
Have a look at the [default implementation](https://github.com/semantic-release/commit-analyzer/).
|
||||
|
||||
### `generateNotes`
|
||||
|
||||
This plugin is responsible for generating release notes. Call the callback with the notes as a string. Have a look at the [default implementation](https://github.com/semantic-release/release-notes-generator/).
|
||||
It receives a `commits` array, the `lastRelease` and `nextRelease` inside `config`.
|
||||
|
||||
### `verifyConditions`
|
||||
|
||||
This plugins is responsible for verifying that a release should happen in the first place. For example, the [default implementation](https://github.com/semantic-release/condition-travis/) verifies that the publish is happening on Travis, that it’s the right branch, and that all other build jobs succeeded. There are more use cases for this, e.g. verifying that test coverage is above a certain threshold or that there are no [vulnerabilities](https://nodesecurity.io/) in your dependencies. Be creative.
|
||||
|
||||
Passing an array of plugins will run them in series.
|
||||
|
||||
### `verifyRelease`
|
||||
|
||||
This plugin is responsible for verifying a release that was determined before and is about to be published. There is no default implementation. It additionally receives `nextRelease`, `lastRelease` and `commits` inside `config`. While `commits` is the same as with analyzeCommits, `nextRelease` contains a `type` (e.g. `'major'`) and the new version (e.g. `'1.0.0'`) and `lastRelease` contains the old `version`, the `gitHead` at the time of the release and the npm dist-`tag` (e.g. `'latest'`). Using this information you could [detect breaking changes](https://github.com/semantic-release/cracks) or hold back certain types of releases. Again: Be creative.
|
||||
|
||||
Passing an array of plugins will run them in series.
|
||||
|
||||
### `getLastRelease`
|
||||
|
||||
This plugin is responsible for determining a package’s last release version. The [default implementation](https://github.com/semantic-release/last-release-npm) uses the last published version on a npm registry.
|
||||
|
||||
## ITYM*FAQ*LT
|
||||
> I think you might frequently ask questions like these
|
||||
|
||||
### Why is the `package.json`’s version not updated in my repository?
|
||||
|
||||
The `npm` docs even state:
|
||||
|
||||
> The most important things in your package.json are the name and version fields. Those are actually required, and your package won’t install without them.
|
||||
> – [npm docs](https://docs.npmjs.com/files/package.json#version)
|
||||
|
||||
While this entirely true the version number doesn’t have to be checked into source control. `semantic-release` takes care of the version field right before `npm publish` uses it – and this is the only point where it _really_ is required.
|
||||
|
||||
### Is there a way to preview which version would currently get published?
|
||||
|
||||
If you run `npm run semantic-release` locally a dry run gets performed, which logs the version that would currently get published.
|
||||
|
||||
### Can I run this on my own machine rather than on a CI server?
|
||||
|
||||
Of course you can, but this doesn’t necessarily mean you should. Running your tests on an independent machine before releasing software is a crucial part of this workflow. Also it is a pain to set this up locally, with tokens lying around and everything. That said, you can run the scripts with `--debug=false` explicitly. You have to export `GH_TOKEN=<your_token>` and `NPM_TOKEN=<your_other_token>`.
|
||||
|
||||
### Can I manually trigger the release of a specific version?
|
||||
|
||||
You can trigger a release by pushing to your GitHub repository. You deliberately cannot trigger a _specific_ version release, because this is the whole point of `semantic-release`. Start your packages with `1.0.0` and semver on.
|
||||
|
||||
### Is it _really_ a good idea to release on every push?
|
||||
|
||||
It is indeed a great idea because it _forces_ you to follow best practices. If you don’t feel comfortable making every passing feature or fix on your master branch addressable via `npm` you might not treat your master right. Have a look at [branch workflows](https://guides.github.com/introduction/flow/index.html). If you still think you should have control over the exact point in time of your release, e.g. because you are following a release schedule, you can release only on the `production`/`deploy`/`release` branch and push your code there in certain intervals, or better yet use [dist-tags](https://docs.npmjs.com/cli/dist-tag).
|
||||
|
||||
### Why should I trust `semantic-release` with my releases?
|
||||
|
||||
`semantic-release` has a full unit- and integration-test-suite that tests _actual_ `npm` publishes against the [npm-registry-couchapp](https://github.com/npm/npm-registry-couchapp/). A new version won’t get published if it doesn’t pass on all these engines.
|
||||
|
||||
### Why does `semantic-release` require node version >= 8
|
||||
|
||||
Being able to write code for just the most recent node versions greatly simplifies development. More language features are available, no transpilation is required, less test builds are to be run, awaited and debugged.
|
||||
|
||||
For a special purpose tool like `semantic-release`, that's only meant to be used in controlled CI environments, we think it's okay to have such a high version requirement. As `semantic-release` handles package publishing we expect almost every project to have at least one build job running node 8 already – and that's all it takes. Even if that's not that case `semantic-release` can still be executed with the help of [npx](https://www.npmjs.com/package/npx) (`npx -p node@8 npm run semantic-release`).
|
||||
### Commit message format
|
||||
|
||||
**semantic-release** uses the commit messages to determine the type of changes in the codebase. Following formalized conventions for commit messages, **semantic-release** automatically determines the next [semantic version](https://semver.org) number, generates a changelog and publish the release.
|
||||
|
||||
By default **semantic-release** uses [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines). The commit message format can be changed with the [`preset` or `config` options](docs/usage/configuration.md#options) of the [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer#options) and [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator#options) plugins.
|
||||
|
||||
Tools such as [commitizen](https://github.com/commitizen/cz-cli), [commitlint](https://github.com/marionebl/commitlint) or [semantic-git-commit-cli](https://github.com/JPeer264/node-semantic-git-commit-cli) can be used to help contributor and enforce valid commits message.
|
||||
|
||||
Here is an example of the release type that will be done based on a commit messages:
|
||||
|
||||
| Commit message | Release type |
|
||||
|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------|
|
||||
| `fix(pencil): stop graphite breaking when too much pressure applied` | Patch Release |
|
||||
| `feat(pencil): add 'graphiteWidth' option` | ~~Minor~~ Feature Release |
|
||||
| `perf(pencil): remove graphiteWidth option`<br><br>`BREAKING CHANGE: The graphiteWidth option has been removed.`<br>`The default graphite width of 10mm is always used for performance reasons.` | ~~Major~~ Breaking Release |
|
||||
|
||||
### Automation with CI
|
||||
|
||||
**semantic-release** is meant to be executed on the CI environment after every successful build on the release branch. This way no human is directly involved in the release process and the releases are guaranteed to be [unromantic and unsentimental](http://sentimentalversioning.org).
|
||||
|
||||
### Triggering a release
|
||||
|
||||
When pushing new commits to the release branch (i.e. `master`) with `git push` or by merging a pull request or merging from another branch, a CI build is triggered and runs the `semantic-release` command to make a release if there is relevant codebase changes since the last release.
|
||||
|
||||
By default a release will be done for each push to the release branch that contains relevant code changes. If you need more control over the timing of releases you have a couple of options:
|
||||
- Publish releases on a distribution channel (for example npm’s [dist-tags](https://docs.npmjs.com/cli/dist-tag)). This way you can keep control over what your users end up using by default, and you can decide when to make an automatically released version available to the stable channel, and promote it.
|
||||
- Develop on a `dev` branch and merge it to the release branch (i.e. `master`) once you are ready to publish. **semantic-release** will run only on pushes to the release branch.
|
||||
|
||||
### Release steps
|
||||
|
||||
After running the tests the command `semantic-release` will execute the following steps:
|
||||
|
||||
| Step | Description |
|
||||
|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| Verify Conditions | Verify all the conditions to proceed with the release with the [verify conditions plugins](docs/usage/plugins.md#verifyconditions-plugin). |
|
||||
| Get last release | Obtain the commit corresponding to the last release by analyzing [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). |
|
||||
| Analyze commits | Determine the type of release to do with the [analyze commits plugin](docs/usage/plugins.md#analyzecommits-plugin) based on the commits added since the last release. |
|
||||
| Verify release | Verify the release conformity with the [verify release plugins](docs/usage/plugins.md#verifyrelease-plugin). |
|
||||
| Generate notes | Generate release notes with the [generate notes plugin](docs/usage/plugins.md#generatenotes-plugin) for the commits added since the last release. |
|
||||
| Create Git tag | Create a Git tag corresponding the new release version |
|
||||
| Publish | Publish the release with the [publish plugins](docs/usage/plugins.md#publish-plugin). |
|
||||
|
||||
## Documentation
|
||||
|
||||
- Usage
|
||||
- [Installation](docs/usage/installation.md#installation)
|
||||
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
|
||||
- [Configuration](docs/usage/configuration.md#configuration)
|
||||
- [Plugins](docs/usage/plugins.md)
|
||||
- [Shareable configurations](docs/usage/shareable-configurations.md)
|
||||
- Extending
|
||||
- [Plugins](docs/extending/plugins-list.md)
|
||||
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
|
||||
- Recipes
|
||||
- [CI configurations](docs/recipes/README.md)
|
||||
- [Package managers and languages](docs/recipes/README.md)
|
||||
- Developer guide
|
||||
- [Plugins](docs/developer-guide/plugin.md)
|
||||
- [Shareable configuration](docs/developer-guide/shareable-configuration.md)
|
||||
- Resources
|
||||
- [Videos](docs/resources.md#videos)
|
||||
- [Articles](docs/resources.md#articles)
|
||||
- [Tutorials](docs/resources.md#tutorials)
|
||||
- Support
|
||||
- [Frequently Asked Questions](docs/support/FAQ.md)
|
||||
- [Troubleshooting](docs/support/troubleshooting.md)
|
||||
- [Node version requirement](docs/support/node-version.md)
|
||||
- [Node Support Policy](docs/support/node-support-policy.md)
|
||||
|
||||
## Get help
|
||||
|
||||
- [Stack Overflow](https://stackoverflow.com/questions/tagged/semantic-release)
|
||||
- [Gitter chat](https://gitter.im/semantic-release/semantic-release)
|
||||
- [Twitter](https://twitter.com/SemanticRelease)
|
||||
|
||||
## Badge
|
||||
|
||||
Use this in one of your projects? Include one of these badges in your README.md to let people know that your package is published using `semantic-release`.
|
||||
Let people know that your package is published using **semantic-release** by including this badge in your readme.
|
||||
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
|
||||
@@ -299,21 +130,12 @@ Use this in one of your projects? Include one of these badges in your README.md
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
```
|
||||
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
## Team
|
||||
|
||||
```md
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
```
|
||||
| [](https://github.com/boennemann) | [](https://github.com/relekang) | [](https://github.com/jo) | [](https://github.com/gr2m) | [](https://github.com/finnp) | [](https://github.com/pvdlg) | [](https://github.com/christophwitzko) |
|
||||
|---------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------|
|
||||
| [Stephan Bönnemann](https://github.com/boennemann) | [Rolf Erik Lekang](https://github.com/relekang) | [Johannes Jörg Schmidt](https://github.com/jo) | [Gregor Martynus](https://github.com/gr2m) | [Finn Pauls](https://github.com/finnp) | [Pierre Vanduynslager](https://github.com/pvdlg) | [Christoph Witzko](https://github.com/christophwitzko) |
|
||||
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
|
||||
```md
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT License
|
||||
2015 © Stephan Bönnemann and [contributors](https://github.com/semantic-release/semantic-release/graphs/contributors)
|
||||
|
||||
[](https://twitter.com/trodrigues/status/509301317467373571)
|
||||
<p align="center">
|
||||
<img alt="Kill all humans" src="media/bender.png">
|
||||
</p>
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
# Summary
|
||||
|
||||
## About
|
||||
- [Highlights](README.md#highlights)
|
||||
- [How does it work?](README.md#how-does-it-work)
|
||||
|
||||
## Usage
|
||||
- [Installation](docs/usage/installation.md#installation)
|
||||
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
|
||||
- [Configuration](docs/usage/configuration.md#configuration)
|
||||
- [Plugins](docs/usage/plugins.md)
|
||||
- [Shareable configurations](docs/usage/shareable-configurations.md)
|
||||
|
||||
## Extending
|
||||
- [Plugins](docs/extending/plugins-list.md)
|
||||
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
|
||||
|
||||
## Recipes
|
||||
- [CI configurations](docs/recipes/README.md)
|
||||
- [CircleCI 2.0 workflows](docs/recipes/circleci-workflows.md)
|
||||
- [Travis CI](docs/recipes/travis.md)
|
||||
- [Travis CI with build stages](docs/recipes/travis-build-stages.md)
|
||||
- [GitLab CI](docs/recipes/gitlab-ci.md)
|
||||
- [Package managers and languages](docs/recipes/README.md)
|
||||
|
||||
## Developer guide
|
||||
- [Plugin](docs/developer-guide/plugin.md)
|
||||
- [Shareable configuration](docs/developer-guide/shareable-configuration.md)
|
||||
|
||||
## Resources
|
||||
- [Videos](docs/resources.md#videos)
|
||||
- [Articles](docs/resources.md#articles)
|
||||
- [Tutorials](docs/resources.md#tutorials)
|
||||
|
||||
## Support
|
||||
- [Frequently Asked Questions](docs/support/FAQ.md)
|
||||
- [Troubleshooting](docs/support/troubleshooting.md)
|
||||
- [Node version requirement](docs/support/node-version.md)
|
||||
- [Node Support Policy](docs/support/node-support-policy.md)
|
||||
@@ -1,34 +0,0 @@
|
||||
# Troubleshooting semantic-release
|
||||
|
||||
### ENOTINHISTORY Commit not in history
|
||||
|
||||
```
|
||||
semantic-release ERR! commits The commit the last release of this package was derived from is not in the direct history of the "master" branch.
|
||||
semantic-release ERR! commits This means semantic-release can not extract the commits between now and then.
|
||||
semantic-release ERR! commits This is usually caused by force pushing, releasing from an unrelated branch, or using an already existing package name.
|
||||
semantic-release ERR! commits You can recover from this error by publishing manually or restoring the commit "123".
|
||||
semantic-release ERR! pre Failed to determine new version.
|
||||
semantic-release ERR! pre ENOTINHISTORY Commit not in history
|
||||
```
|
||||
|
||||
To restore semantic-release, follow these steps:
|
||||
|
||||
```
|
||||
git pull
|
||||
git reset --hard origin/master
|
||||
npm version x.y.z # check your current version and set this based on semver rules manually
|
||||
|
||||
# if you have a PR workflow, create a new branch, otherwise commit to master
|
||||
|
||||
git checkout -B chore/release
|
||||
git commit -am 'chore: release'
|
||||
git push
|
||||
|
||||
# merge (not squash-merge) on github (this is important before running git push). This is only required when you work with branches
|
||||
git checkout master
|
||||
|
||||
# definitely required
|
||||
git pull
|
||||
git push --tags
|
||||
npm publish
|
||||
```
|
||||
+8
-13
@@ -3,26 +3,21 @@
|
||||
// Bad news: We have to write plain ES5 in this file
|
||||
// Good news: It's the only file of the entire project
|
||||
|
||||
/* eslint-disable no-var */
|
||||
|
||||
var semver = require('semver');
|
||||
var pkg = require('../package.json');
|
||||
|
||||
if (semver.lt(process.version, '8.0.0')) {
|
||||
if (!semver.satisfies(process.version, pkg.engines.node)) {
|
||||
console.error(
|
||||
`semantic-release: node version >= 8 is required. Found ${process.version}.
|
||||
`[semantic-release]: node version ${pkg.engines.node} is required. Found ${process.version}.
|
||||
|
||||
If there is another job running on node version >= 8, it will be picked as
|
||||
the build leader and you can safely ignore this message.
|
||||
|
||||
If you don't have node 8 in your build matrix you can use "npx" to restore
|
||||
compatibility with minimal overhead:
|
||||
|
||||
$ npx -p node@8 npm run semantic-release
|
||||
|
||||
npx is bundled with npm >= 5.4, or available via npm. More info: npm.im/npx`
|
||||
See https://github.com/semantic-release/semantic-release/blob/caribou/docs/support/node-version.md for more details and solutions.`
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// node 8+ from this point on
|
||||
require('../src/cli')().catch(() => {
|
||||
// Node 8+ from this point on
|
||||
require('../cli')().catch(() => {
|
||||
process.exitCode = 1;
|
||||
});
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"plugins" : ["github", "anchors"],
|
||||
"pluginsConfig": {
|
||||
"github": {
|
||||
"url": "https://github.com/semantic-release/semantic-release"
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-16
@@ -1,5 +1,5 @@
|
||||
const program = require('commander');
|
||||
const logger = require('./lib/logger');
|
||||
const {pickBy, isUndefined} = require('lodash');
|
||||
|
||||
function list(values) {
|
||||
return values.split(',').map(value => value.trim());
|
||||
@@ -10,22 +10,25 @@ module.exports = async () => {
|
||||
.name('semantic-release')
|
||||
.description('Run automated package publishing')
|
||||
.option('-b, --branch <branch>', 'Branch to release from')
|
||||
.option('--github-token <token>', 'Token to authenticate with Github API')
|
||||
.option('--github-url <url>', 'GitHub Enterprise endpoint')
|
||||
.option('--github-api-path-prefix <prefix>', 'Prefix of the GitHub Enterprise endpoint')
|
||||
.option('-r, --repository-url <repositoryUrl>', 'Git repository URL')
|
||||
.option('-e, --extends <paths>', 'Comma separated list of shareable config paths or packages name', list)
|
||||
.option(
|
||||
'--verify-conditions <paths>',
|
||||
'Comma separated list of paths or packages name for the verifyConditions plugin',
|
||||
'Comma separated list of paths or packages name for the verifyConditions plugin(s)',
|
||||
list
|
||||
)
|
||||
.option('--get-last-release <path>', 'Path or package name for the getLastRelease plugin')
|
||||
.option('--analyze-commits <path>', 'Path or package name for the analyzeCommits plugin')
|
||||
.option(
|
||||
'--verify-release <paths>',
|
||||
'Comma separated list of paths or packages name for the verifyRelease plugin',
|
||||
'Comma separated list of paths or packages name for the verifyRelease plugin(s)',
|
||||
list
|
||||
)
|
||||
.option('--generate-notes <path>', 'Path or package name for the generateNotes plugin')
|
||||
.option('--publish <paths>', 'Comma separated list of paths or packages name for the publish plugin(s)', list)
|
||||
.option(
|
||||
'--no-ci',
|
||||
'Skip Continuous Integration environment verifications, allowing to make releases from a local machine'
|
||||
)
|
||||
.option('--debug', 'Output debugging information')
|
||||
.option(
|
||||
'-d, --dry-run',
|
||||
@@ -43,16 +46,13 @@ module.exports = async () => {
|
||||
program.outputHelp();
|
||||
process.exitCode = 1;
|
||||
} else {
|
||||
await require('./index')(program);
|
||||
const opts = program.opts();
|
||||
// Set the `noCi` options as commander.js sets the `ci` options instead (becasue args starts with `--no`)
|
||||
opts.noCi = opts.ci === false ? true : undefined;
|
||||
// Remove option with undefined values, as commander.js sets non defined options as `undefined`
|
||||
await require('.')(pickBy(opts, value => !isUndefined(value)));
|
||||
}
|
||||
} catch (err) {
|
||||
// If error is a SemanticReleaseError then it's an expected exception case (no release to be done, running on a PR etc..) and the cli will return with 0
|
||||
// Otherwise it's an unexpected error (configuration issue, code issue, plugin issue etc...) and the cli will return 1
|
||||
if (err.semanticRelease) {
|
||||
logger.log(`%s ${err.message}`, err.code);
|
||||
} else {
|
||||
process.exitCode = 1;
|
||||
logger.error('An error occurred while running semantic-release: %O', err);
|
||||
}
|
||||
process.exitCode = 1;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
# semantic-release documentation
|
||||
|
||||
- [Usage](usage/README.md) - **semantic-release** installation and configuration
|
||||
- [Extending][extending/README.md]- Extending **semantic-release** with plugins and shareable configurations
|
||||
- [Recipes](recipes/README.md) - Community written recipes for common **semantic-release** use-cases
|
||||
- [Developer Guide](developer-guide/README.md) - The essentials of writing a **semantic-release** plugin or shareable configurations
|
||||
- [Resources](resources.md) - Videos, articles and tutorials
|
||||
- [Support](support/README.md) - FAQ and troubleshooting
|
||||
@@ -0,0 +1,4 @@
|
||||
# Developer guide
|
||||
|
||||
- [Plugins](plugin.md)
|
||||
- [Shareable configuration](shareable-configuration.md)
|
||||
@@ -0,0 +1 @@
|
||||
# Plugin developer guide
|
||||
@@ -0,0 +1 @@
|
||||
# Shareable configuration developer guide
|
||||
@@ -0,0 +1,4 @@
|
||||
# Extending semantic-release
|
||||
|
||||
- [Plugins list](plugins-list.md)
|
||||
- [Shareable configuration list](shareable-configurations-list.md)
|
||||
@@ -0,0 +1,30 @@
|
||||
# Plugins list
|
||||
|
||||
## Default plugins
|
||||
|
||||
- [@semantic-release/github](https://github.com/semantic-release/github)
|
||||
- [verifyConditions](https://github.com/semantic-release/github#verifyconditions): Verify the presence and the validity of the GitHub authentication and release configuration
|
||||
- [publish](https://github.com/semantic-release/github#publish): Publish a [GitHub release](https://help.github.com/articles/about-releases)
|
||||
- [@semantic-release/npm](https://github.com/semantic-release/npm)
|
||||
- [verifyConditions](https://github.com/semantic-release/npm#verifyconditions): Verify the presence and the validity of the npm authentication and release configuration
|
||||
- [publish](https://github.com/semantic-release/npm#publish): Publish the package on the npm registry
|
||||
|
||||
## Official plugins
|
||||
|
||||
- [@semantic-release/gitlab](https://github.com/semantic-release/gitlab)
|
||||
- [verifyConditions](https://github.com/semantic-release/gitlab#verifyconditions): Verify the presence and the validity of the GitLab authentication and release configuration
|
||||
- [publish](https://github.com/semantic-release/gitlab#publish): Publish a [GitLab release](https://docs.gitlab.com/ce/workflow/releases.html)
|
||||
- [@semantic-release/git](https://github.com/semantic-release/git)
|
||||
- [verifyConditions](https://github.com/semantic-release/git#verifyconditions): Verify the presence and the validity of the Git authentication and release configuration
|
||||
- [publish](https://github.com/semantic-release/git#publish): Push a release commit and tag, including configurable files
|
||||
- [@semantic-release/changelog](https://github.com/semantic-release/changelog)
|
||||
- [verifyConditions](https://github.com/semantic-release/changelog#verifyconditions): Verify the presence and the validity of the configuration
|
||||
- [publish](https://github.com/semantic-release/changelog#publish): Create or update the changelog file in the local project repository
|
||||
- [@semantic-release/exec](https://github.com/semantic-release/exec)
|
||||
- [verifyConditions](https://github.com/semantic-release/exec#verifyconditions): Execute a shell command to verify if the release should happen
|
||||
- [analyzeCommits](https://github.com/semantic-release/exec#analyzecommits): Execute a shell command to determine the type of release
|
||||
- [verifyRelease](https://github.com/semantic-release/exec#verifyrelease): Execute a shell command to verifying a release that was determined before and is about to be published.
|
||||
- [generateNotes](https://github.com/semantic-release/exec#analyzecommits): Execute a shell command to generate the release note
|
||||
- [publish](https://github.com/semantic-release/exec#publish): Execute a shell command to publish the release.
|
||||
|
||||
## Community plugins
|
||||
@@ -0,0 +1,7 @@
|
||||
# Shareable configurations list
|
||||
|
||||
## Official configurations
|
||||
- [@semantic-release/apm-config](https://github.com/semantic-release/apm-config) - semantic-release shareable configuration for releasing atom packages
|
||||
- [@semantic-release/gitlab-config](https://github.com/semantic-release/gitlab-config) - semantic-release shareable configuration for GitLab
|
||||
|
||||
## Community configurations
|
||||
@@ -0,0 +1,12 @@
|
||||
# Recipes
|
||||
|
||||
## CI configurations
|
||||
- [CircleCI 2.0 workflows](circleci-workflows.md)
|
||||
- [Travis CI](travis.md)
|
||||
- [Travis CI with build stages](travis-build-stages.md)
|
||||
- [GitLab CI](gitlab-ci.md)
|
||||
|
||||
## Git hosted services
|
||||
- [Git authentication with SSH keys](git-auth-ssh-keys.md)
|
||||
|
||||
## Package managers and languages
|
||||
@@ -0,0 +1 @@
|
||||
# CircleCI 2.0 workflows
|
||||
@@ -0,0 +1,161 @@
|
||||
# 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).
|
||||
|
||||
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.
|
||||
|
||||
## Generating the SSH keys
|
||||
|
||||
In your local repository root:
|
||||
|
||||
```bash
|
||||
$ ssh-keygen -t rsa -b 4096 -C "<your_email>" -f git_deploy_key -N "<ssh_passphrase>"
|
||||
```
|
||||
|
||||
`your_email` must be the email associated with your Git hosted account. `ssh_passphrase` must be a long and hard to guess string. It will be used later.
|
||||
|
||||
This will generate a public key in `git_deploy_key.pub` and a private key in `git_deploy_key`.
|
||||
|
||||
## Adding the SSH public key to the Git hosted account
|
||||
|
||||
Step by step instructions are provided for the following Git hosted services:
|
||||
- [GitHub](#adding-the-ssh-public-key-to-github)
|
||||
|
||||
### Adding the SSH public key to GitHub
|
||||
|
||||
Open the `git_deploy_key.pub` file (public key) and copy the entire content.
|
||||
|
||||
In GitHub **Settings**, click on **SSH and GPG keys** in the sidebar, then on the **New SSH Key** button.
|
||||
|
||||
Paste the entire content of `git_deploy_key.pub` file (public key) and click the **Add SSH Key** button.
|
||||
|
||||
Delete the `git_deploy_key.pub` file:
|
||||
|
||||
```bash
|
||||
$ rm git_deploy_key.pub
|
||||
```
|
||||
|
||||
See [Adding a new SSH key to your GitHub account](https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/) for more details.
|
||||
|
||||
## Adding the SSH private key to the CI environment
|
||||
|
||||
In order to be available on the CI environment, the SSH private key must be encrypted, committed to the Git repository and decrypted by the CI service.
|
||||
|
||||
Step by step instructions are provided for the following environments:
|
||||
- [Travis CI](#adding-the-ssh-private-key-to-travis-ci)
|
||||
- [Circle CI](#adding-the-ssh-private-key-to-circle-ci)
|
||||
|
||||
### Adding the SSH private key to Travis CI
|
||||
|
||||
Install the [Travis CLI](https://github.com/travis-ci/travis.rb#installation):
|
||||
|
||||
```bash
|
||||
$ gem install travis
|
||||
```
|
||||
|
||||
[Login](https://github.com/travis-ci/travis.rb#login) to Travis with the CLI:
|
||||
|
||||
```bash
|
||||
$ travis login
|
||||
```
|
||||
|
||||
Add the [environment](https://github.com/travis-ci/travis.rb#env) variable `SSH_PASSPHRASE` to Travis with the value set during the [SSH keys generation](#generating-the-ssh-keys) step:
|
||||
|
||||
```bash
|
||||
$ travis env set SSH_PASSPHRASE <ssh_passphrase>
|
||||
```
|
||||
|
||||
[Encrypt](https://github.com/travis-ci/travis.rb#encrypt) the `git_deploy_key` (private key) using a symmetric encryption (AES-256), and store the secret in a secure environment variable in the Travis environment:
|
||||
|
||||
```bash
|
||||
$ travis encrypt-file git_deploy_key
|
||||
```
|
||||
|
||||
The `travis encrypt-file` will encrypt the private key into the `git_deploy_key.enc` file and output in the console the command to add to your `.travis.yml` file. It should look like `openssl aes-256-cbc -K $encrypted_KKKKKKKKKKKK_key -iv $encrypted_VVVVVVVVVVVV_iv -in git_deploy_key.enc -out git_deploy_key -d`.
|
||||
|
||||
Copy this command to your `.travis.yml` file in the `before_install` step. Change the output path to write the unencrypted key in `/tmp`: `-out git_deploy_key` => `/tmp/git_deploy_key`. This will avoid to commit / modify / delete the unencrypted key by mistake on the CI. Then add the commands to decrypt the ssh private key and make it available to `git`:
|
||||
|
||||
```yaml
|
||||
before_install:
|
||||
# Decrypt the git_deploy_key.enc key into /tmp/git_deploy_key
|
||||
- openssl aes-256-cbc -K $encrypted_KKKKKKKKKKKK_key -iv $encrypted_VVVVVVVVVVVV_iv -in git_deploy_key.enc -out /tmp/git_deploy_key -d
|
||||
# Make sure only the current user can read the private key
|
||||
- chmod 600 /tmp/git_deploy_key
|
||||
# Create a script to return the passphrase environment variable to ssh-add
|
||||
- echo 'echo ${SSH_PASSPHRASE}' > /tmp/askpass && chmod +x /tmp/askpass
|
||||
# Start the authentication agent
|
||||
- eval "$(ssh-agent -s)"
|
||||
# Add the key to the authentication agent
|
||||
- DISPLAY=":0.0" SSH_ASKPASS="/tmp/askpass" setsid ssh-add /tmp/git_deploy_key </dev/null
|
||||
```
|
||||
|
||||
See [Encrypting Files](https://docs.travis-ci.com/user/encrypting-files) for more details.
|
||||
|
||||
Delete the local private key as it won't be used anymore:
|
||||
|
||||
```bash
|
||||
$ rm git_deploy_key
|
||||
```
|
||||
|
||||
Commit the encrypted private key and the `.travis.yml` file to your repository:
|
||||
|
||||
```bash
|
||||
$ git add git_deploy_key.enc .travis.yml
|
||||
$ git commit -m "ci(travis): Add the encrypted private ssh key"
|
||||
$ git push
|
||||
```
|
||||
|
||||
### Adding the SSH private key to Circle CI
|
||||
|
||||
First we encrypt the `git_deploy_key` (private key) using a symmetric encryption (AES-256). Run the following `openssl` command and *make sure to note the output which we'll need later*:
|
||||
|
||||
```bash
|
||||
$ openssl aes-256-cbc -e -p -in git_deploy_key -out git_deploy_key.enc -K `openssl rand -hex 32` -iv `openssl rand -hex 16`
|
||||
salt=SSSSSSSSSSSSSSSS
|
||||
key=KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
|
||||
iv =VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
|
||||
```
|
||||
|
||||
Add the following [environment variables](https://circleci.com/docs/2.0/env-vars/#adding-environment-variables-in-the-app) to Circle CI:
|
||||
- `SSL_PASSPHRASE` - the value set during the [SSH keys generation](#generating-the-ssh-keys) step.
|
||||
- `REPO_ENC_KEY` - the `key` (KKK) value from the `openssl` step above.
|
||||
- `REPO_ENC_IV` - the `iv` (VVV) value from the `openssl` step above.
|
||||
|
||||
Then add to your `.circleci/config.yml` the commands to decrypt the ssh private key and make it available to `git`:
|
||||
|
||||
```yaml
|
||||
version: 2
|
||||
jobs:
|
||||
coverage_test_publish:
|
||||
# docker, working_dir, etc
|
||||
steps:
|
||||
- run:
|
||||
# Decrypt the git_deploy_key.enc key into /tmp/git_deploy_key
|
||||
- openssl aes-256-cbc -d -K $REPO_ENC_KEY -iv $REPO_ENC_IV -in git_deploy_key.enc -out /tmp/git_deploy_key
|
||||
# Make sure only the current user can read the private key
|
||||
- chmod 600 /tmp/git_deploy_key
|
||||
# Create a script to return the passphrase environment variable to ssh-add
|
||||
- echo 'echo ${SSH_PASSPHRASE}' > /tmp/askpass && chmod +x /tmp/askpass
|
||||
# Start the authentication agent
|
||||
- eval "$(ssh-agent -s)"
|
||||
# Add the key to the authentication agent
|
||||
- DISPLAY=":0.0" SSH_ASKPASS="/tmp/askpass" setsid ssh-add /tmp/git_deploy_key </dev/null
|
||||
# checkout, restore_cache, run: yarn install, save_cache, etc.
|
||||
# Run semantic-release after all the above is set.
|
||||
```
|
||||
|
||||
The unencrypted key is written to `/tmp` to avoid to commit / modify / delete the unencrypted key by mistake on the CI environment.
|
||||
|
||||
Delete the local private key as it won't be used anymore:
|
||||
|
||||
```bash
|
||||
$ rm git_deploy_key
|
||||
```
|
||||
|
||||
Commit the encrypted private key and the `.circleci/config.yml` file to your repository:
|
||||
|
||||
```bash
|
||||
$ git add git_deploy_key.enc .circleci/config.yml
|
||||
$ git commit -m "ci(cicle): Add the encrypted private ssh key"
|
||||
$ git push
|
||||
```
|
||||
@@ -0,0 +1,71 @@
|
||||
# Using semantic-release with [GitLab CI](https://about.gitlab.com/features/gitlab-ci-cd)
|
||||
|
||||
## Environment variables
|
||||
|
||||
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured with [Secret variables](https://docs.gitlab.com/ce/ci/variables/README.html#secret-variables).
|
||||
|
||||
## Node project configuration
|
||||
|
||||
GitLab CI supports [Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html) allowing to test on multiple Node versions and publishing a release only when all test pass.
|
||||
|
||||
**Note**: The publish pipeline must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--8).
|
||||
|
||||
### `.gitlab-ci.yml` configuration for Node projects
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 4, 6 and 8 on Linux. See [GitLab CI - Configuration of your jobs with .gitlab-ci.yml](https://docs.gitlab.com/ee/ci/yaml/README.html) for additional configuration options.
|
||||
|
||||
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
|
||||
|
||||
```yaml
|
||||
# The release pipeline will run only if all jobs in the test pipeline are successful
|
||||
stages:
|
||||
- test
|
||||
- release
|
||||
|
||||
before_script:
|
||||
- npm install
|
||||
|
||||
node:4:
|
||||
image: node:4
|
||||
stage: test
|
||||
script:
|
||||
- npm test
|
||||
|
||||
node:6:
|
||||
image: node:6
|
||||
stage: test
|
||||
script:
|
||||
- npm test
|
||||
|
||||
node:8:
|
||||
image: node:8
|
||||
stage: test
|
||||
script:
|
||||
- npm test
|
||||
|
||||
publish:
|
||||
image: node:8
|
||||
stage: release
|
||||
script:
|
||||
# Only for a local semantic-release installation
|
||||
- npm run semantic-release
|
||||
|
||||
# Only for a global semantic-release installation
|
||||
- npm install -g semantic-release
|
||||
- semantic-release
|
||||
```
|
||||
|
||||
### `package.json` configuration
|
||||
|
||||
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
|
||||
|
||||
```json
|
||||
{
|
||||
"devDependencies": {
|
||||
"semantic-release": "^12.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"semantic-release": "semantic-release"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
# Using semantic-release with [Travis CI build stages](https://docs.travis-ci.com/user/build-stages)
|
||||
@@ -0,0 +1,165 @@
|
||||
# Using semantic-release with [Travis CI](https://travis-ci.org)
|
||||
|
||||
## Environment variables
|
||||
|
||||
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [Travis Repository Settings](https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-Settings) or with the [travis env set CLI](https://github.com/travis-ci/travis.rb#env).
|
||||
|
||||
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/ci-configuration.md#automatic-setup-with-semantic-release-cli).
|
||||
|
||||
## Single Node job configuration
|
||||
|
||||
For projects that require to be tested only with a single [Node version](https://docs.travis-ci.com/user/getting-started/#Selecting-a-different-programming-language) on [one Operating System](https://docs.travis-ci.com/user/getting-started/#Selecting-infrastructure-(optional)).
|
||||
|
||||
**Note**: [Node 8 is the minimal version required](../support/FAQ.md#why-does-semantic-release-require-node-version--8).
|
||||
|
||||
### `.travis.yml` configuration for single Node job
|
||||
|
||||
This example is a minimal configuration for semantic-release with a build running Node 8 on Linux. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
|
||||
|
||||
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
|
||||
|
||||
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
|
||||
|
||||
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) semantic-release installation.
|
||||
|
||||
```yaml
|
||||
language: node_js
|
||||
|
||||
node_js: 8
|
||||
|
||||
script:
|
||||
# Run tests
|
||||
- npm run test
|
||||
|
||||
deploy:
|
||||
provider: script
|
||||
skip_cleanup: true
|
||||
script:
|
||||
# Only for a local semantic-release installation
|
||||
- npm run semantic-release
|
||||
# Only for a global semantic-release installation
|
||||
- npm install -g semantic-release && semantic-release
|
||||
```
|
||||
|
||||
### `package.json` configuration for single Node job
|
||||
|
||||
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
|
||||
|
||||
```json
|
||||
{
|
||||
"devDependencies": {
|
||||
"semantic-release": "^11.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"semantic-release": "semantic-release"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Multiple Node jobs configuration
|
||||
|
||||
For projects that require to be tested with multiple [Node versions](https://docs.travis-ci.com/user/languages/javascript-with-nodejs/#Specifying-Node.js-versions) and/or on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
|
||||
|
||||
**Note**: At least one job must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--83).
|
||||
|
||||
### `.travis.yml` configuration for multiple Node jobs
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 4, 6 and 8 on Linux and OSX. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
|
||||
|
||||
This example uses [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once) in order to command [Run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
|
||||
|
||||
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
|
||||
|
||||
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
|
||||
|
||||
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
|
||||
|
||||
```yaml
|
||||
language: node_js
|
||||
|
||||
node_js:
|
||||
- 8
|
||||
- 6
|
||||
- 4
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
script:
|
||||
# Run tests
|
||||
- npm run test
|
||||
|
||||
deploy:
|
||||
provider: script
|
||||
skip_cleanup: true
|
||||
script:
|
||||
# Only for a local semantic-release installation
|
||||
- npm run travis-deploy-once "npm run semantic-release"
|
||||
# Only for a global semantic-release installation
|
||||
- npm install -g travis-deploy-once semantic-release && travis-deploy-once "semantic-release"
|
||||
```
|
||||
|
||||
**Note**: See the `travis-deploy-once` [`pro`](https://github.com/semantic-release/travis-deploy-once#-p---pro) and [`travis-url`](https://github.com/semantic-release/travis-deploy-once#-u---travis-url) options for using with [Travis Pro](https://docs.travis-ci.com/user/travis-pro) and [Travis Enterprise](https://enterprise.travis-ci.com).
|
||||
|
||||
### `package.json` configuration for multiple Node jobs
|
||||
|
||||
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
|
||||
|
||||
```json
|
||||
{
|
||||
"devDependencies": {
|
||||
"semantic-release": "^12.0.0",
|
||||
"travis-deploy-once": "^4.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"semantic-release": "semantic-release",
|
||||
"travis-deploy-once": "travis-deploy-once"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Non-JavaScript projects configuration
|
||||
|
||||
For projects that require to be tested with one or multiple version of a Non-JavaScript [language](https://docs.travis-ci.com/user/languages), optionally on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
|
||||
|
||||
This recipe cover the Travis specifics only. See [Non JavaScript projects recipe](../support/FAQ.md#can-i-use-semantic-release-to-publish-non-javascript-packages) for more information on the **semantic-release** configuration.
|
||||
|
||||
### `.travis.yml` configuration for non-JavaScript projects
|
||||
|
||||
This example is a minimal configuration for semantic-release with a build running [Go 1.6 and 1.7](https://docs.travis-ci.com/user/languages/go) on Linux and OSX. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
|
||||
|
||||
This example uses [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once) in order to [run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
|
||||
|
||||
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
|
||||
|
||||
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
|
||||
|
||||
```yaml
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.6
|
||||
- 1.7
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
script:
|
||||
# Run tests
|
||||
- go test -v ./...
|
||||
|
||||
deploy:
|
||||
provider: script
|
||||
skip_cleanup: true
|
||||
script:
|
||||
# Use nvm to install and use the Node LTS version (nvm is installed on all Travis images)
|
||||
- nvm install lts/*
|
||||
# Install travis-deploy-once and semantic-release
|
||||
- npm install -g travis-deploy-once semantic-release
|
||||
# Run semantic-release only on job, after all other are successful
|
||||
- travis-deploy-once "semantic-release"
|
||||
```
|
||||
|
||||
**Note**: See the `travis-deploy-once` [`pro`](https://github.com/semantic-release/travis-deploy-once#-p---pro) and [`travis-url`](https://github.com/semantic-release/travis-deploy-once#-u---travis-url) options for using with [Travis Pro](https://docs.travis-ci.com/user/travis-pro) and [Travis Enterprise](https://enterprise.travis-ci.com).
|
||||
@@ -0,0 +1,19 @@
|
||||
# Resources
|
||||
|
||||
## Videos
|
||||
|
||||
- ["Introducing Reliable Dependency and Release Management for npm Packages" - Gregor Martynus](https://www.youtube.com/watch?v=R2RJWLcfzwc)
|
||||
- ["Kill all humans" - Jan Lehnardt](https://www.youtube.com/watch?v=ZXyx_1kN1L8&t=2s)
|
||||
- [Publishing JavaScript Packages" - JavaScript Air](https://javascriptair.com/episodes/2016-07-20)
|
||||
- ["Managing Dependencies like a boss 😎" - JavaScript Air](https://javascriptair.com/episodes/2016-08-17)
|
||||
- ["Dependency Hell Just Froze Over" - Stephan Bönnemann](https://www.youtube.com/watch?v=PA139CERNbc)
|
||||
- [“semantic-release Q&A with Kent C. Dodds”](https://www.youtube.com/watch?v=g6y3DnhkjrI)
|
||||
- [“We fail to follow SemVer – and why it needn’t matter” - Stephan Bönnemann](https://www.youtube.com/watch?v=tc2UgG5L7WM)
|
||||
|
||||
## Articles
|
||||
|
||||
- [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2)
|
||||
|
||||
## Tutorials
|
||||
|
||||
- [“How to Write a JavaScript Library - Automating Releases with semantic-release” – egghead.io](https://egghead.io/lessons/javascript-automating-releases-with-semantic-release)
|
||||
@@ -0,0 +1,158 @@
|
||||
# Frequently Asked Questions
|
||||
|
||||
## Why is the `package.json`’s version not updated in my repository?
|
||||
|
||||
**semantic-release** takes care of updating the `package.json`’s version before publishing to [npm](https://www.npmjs.com).
|
||||
|
||||
By default, only the published package will contains the version, which is the only place where it is *really* required, but the updated `package.json` will not be pushed to the Git repository
|
||||
|
||||
However, the [`@semantic-release/git`](https://github.com/semantic-release/git) plugin can be used to push the updated `package.json` as well as other files to the Git repository.
|
||||
|
||||
## How can I use a npm build script that requires the `package.json`’s version ?
|
||||
|
||||
The `package.json`’s version will be updated by the `semantic-release` command just before publishing to [npm](https://www.npmjs.com), therefore it won't be available for scripts ran before the `semantic-release` command.
|
||||
|
||||
As semantic-release uses the [npm CLI](https://docs.npmjs.com/cli/npm) to publish, all [npm hook scripts](https://docs.npmjs.com/misc/scripts#hook-scripts) will be executed. Therefore you can run your build script in the [`prepublishOnly`](https://docs.npmjs.com/misc/scripts#prepublish-and-prepare) hook. It will be executed after the `semantic-release` command update the `package.json`’s version and before publishing.
|
||||
|
||||
## Is there a way to preview which version would currently get published?
|
||||
|
||||
Yes with the [dry-run options](../usage/configuration.md#dryrun) which prints to the console the next version to be published and the release notes.
|
||||
|
||||
## Can I use semantic-release with Yarn?
|
||||
|
||||
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation and run multiple CI jobs with different versions, the `yarn install` command will fail on jobs running with Node < 8 as **semantic-release** requires [Node >= 8.3](#why-does-semantic-release-require-node-version--83) and specifies it in its `package.json`s [`engines`](https://docs.npmjs.com/files/package.json#engines) key.
|
||||
|
||||
The recommended solution is to use the [Yarn](https://yarnpkg.com) [--ignore-engines](https://yarnpkg.com/en/docs/cli/install#toc-yarn-install-ignore-engines) option to install the project dependencies on the CI environment, so Yarn will ignore the **semantic-release**'s `engines` key:
|
||||
|
||||
```bash
|
||||
$ yarn install --ignore-engines
|
||||
```
|
||||
|
||||
**Note**: Several CI services use Yarn by default if your repository contains a `yarn.lock` file. So you should override the install step to specify `yarn install --ignore-engines`.
|
||||
|
||||
Alternatively you can use a [global](../usage/installation.md#global-installation) **semantic-release** installation and make sure to install and run the `semantic-release` command only in a CI jobs running with Node >= 8.3.
|
||||
|
||||
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can switch to Node 8 before installing and running the `semantic-release` command:
|
||||
|
||||
```bash
|
||||
$ nvm install 8 && yarn install -g semantic-release && semantic-release
|
||||
```
|
||||
|
||||
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
|
||||
|
||||
## Can I use semantic-release to publish non-JavaScript packages?
|
||||
|
||||
Yes, **semantic-release** is a Node CLI application but it can be used to publish any type of packages.
|
||||
|
||||
To publish a non-Node package (without a `package.json`) you would need to:
|
||||
- Use a [global](../usage/installation.md#global-installation) **semantic-release** installation
|
||||
- Set **semantic-release** [options](../usage/configuration.md#options) via [CLI arguments or rc file](../usage/configuration.md#configuration)
|
||||
- Make sure your CI job executing the `semantic-release` command has access to [Node >= 8](#why-does-semantic-release-require-node-version--83) to execute the `semantic-release` command
|
||||
|
||||
See the [CI configuration recipes](../usage/ci-configuration.md) for more details on specific CI environments.
|
||||
|
||||
## Can I use semantic-release with any CI service?
|
||||
|
||||
Yes, **semantic-release** can be used with any CI service, as long as it provides:
|
||||
- A way to set [authentication](../usage/ci-configuration.md#authentication) via environment variables
|
||||
- A way to guarantee that the `semantic-release` command is [executed only after all the tests of all the jobs in the CI build pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
|
||||
|
||||
See the [CI configuration recipes](../usage/ci-configuration.md) for more details on specific CI environments.
|
||||
|
||||
## Can I run semantic-release on my local machine rather than on a CI server?
|
||||
|
||||
Yes, you can by explicitly setting the [`--no-ci` CLI option](../usage/configuration.md#options) option. You will also have to set the required [authentication](../usage/ci-configuration.md#authentication) via environment variables on your local machine, for example:
|
||||
|
||||
```bash
|
||||
$ NPM_TOKEN=<your_npm_token> GH_TOKEN=<your_github_token> npm run semantic-release --no-ci
|
||||
```
|
||||
|
||||
However this is not the recommended approach, as running unit and integration tests on an independent machine before publishing software is a crucial part of the release workflow.
|
||||
|
||||
## Can I use semantic-release with GitLab?
|
||||
|
||||
Yes, with the [`@semantic-release/gitlab-config`](https://github.com/semantic-release/gitlab-config) shareable configuration.
|
||||
|
||||
See the [GitLab CI recipes](../recipes/gitlab-ci.md#using-semantic-release-with-gitlab-ci) for the CI configuration.
|
||||
|
||||
## Can I use semantic-release with any Git hosted environment?
|
||||
|
||||
By default **semantic-release** uses the [`@semantic-release/github`](https://github.com/semantic-release/github) plugin to publish a [GitHub release](https://help.github.com/articles/about-releases). For other Git hosted environment the [`@semantic-release/git`](https://github.com/semantic-release/git) and [`@semantic-release/changelog`](https://github.com/semantic-release/changelog) plugins can be used via [plugins configuration](../usage/plugins.md#configuration).
|
||||
|
||||
See the [`@semantic-release/git`](https://github.com/semantic-release/git#semantic-releasegit) [`@semantic-release/changelog`](https://github.com/semantic-release/changelog#semantic-releasechangelog) plugins documentation for more details.
|
||||
|
||||
## Can I skip the release to the npm registry?
|
||||
|
||||
Yes, the publishing to the npm registry can be disabled with the [`npmPublish`](https://github.com/semantic-release/npm#options) option of the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin. In addition the [`tarballDir`](https://github.com/semantic-release/npm#options) option allow to generate the package tarball in order to publish it to your repository with the [`@semantic-release/git`](https://github.com/semantic-release/git) or to a [GitHub release](https://help.github.com/articles/about-releases) with the [`@semantic-release/github`](https://github.com/semantic-release/github) plugin.
|
||||
|
||||
See the [`@semantic-release/npm`](https://github.com/semantic-release/npm#semantic-releasenpm) plugin documentation for more details.
|
||||
|
||||
## Can I use `.npmrc` options?
|
||||
|
||||
Yes, all the [npm configuration options](https://docs.npmjs.com/misc/config) are supported via the [`.npmrc`](https://docs.npmjs.com/files/npmrc) file at the root of your repository.
|
||||
|
||||
See the [`@semantic-release/npm`](https://github.com/semantic-release/npm#npm-configuration) plugin documentation for more details.
|
||||
|
||||
## How can I set the access level of the published npm package?
|
||||
|
||||
The [npm `access` option](https://docs.npmjs.com/misc/config#access) can be set in the [`.npmrc`](https://docs.npmjs.com/files/npmrc) file at the root of your repository:
|
||||
|
||||
```rc
|
||||
access=public
|
||||
```
|
||||
|
||||
Or with the `publishConfig.access` key in your project's `package.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Can I use semantic-release to publish a package on Artifactory?
|
||||
|
||||
Any npm compatible registry is supported with the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin. For Artifactory versions prior to 5.4, the legacy authentication has to be used (with `NPM_USERNAME`, `NPM_PASSWORD` and `NPM_EMAIL` [environment variables](https://github.com/semantic-release/npm#environment-variables)).
|
||||
|
||||
See [npm registry authentication](https://github.com/semantic-release/npm#npm-registry-authentication) for more details.
|
||||
|
||||
See [Artifactory - npm Registry](https://www.jfrog.com/confluence/display/RTF/Npm+Registry#NpmRegistry-AuthenticatingthenpmClient) documentation for Artifactiry configuration.
|
||||
|
||||
## Can I manually trigger the release of a specific version?
|
||||
|
||||
You can trigger a release by pushing to your Git repository. You deliberately cannot trigger a *specific* version release, because this is the whole point of semantic-release.
|
||||
|
||||
### Can I exclude commits from the analysis?
|
||||
|
||||
Yes, every commits that contains `[skip release]` or `[release skip]` in their message will be excluded from the commit analysis and won't participate in the release type determination.
|
||||
|
||||
## Is it *really* a good idea to release on every push?
|
||||
|
||||
It is indeed a great idea because it *forces* you to follow best practices. If you don’t feel comfortable releasing every feature or fix on your `master` you might not treat your `master` branch as intended.
|
||||
|
||||
From [Understanding the GitHub Flow](https://guides.github.com/introduction/flow/index.html):
|
||||
|
||||
> Branching is a core concept in Git, and the entire GitHub Flow is based upon it. There's only one rule: anything in the master branch is always deployable.
|
||||
|
||||
If you need more control over the timing of releases, see [Triggering a release](../../README.md#triggering-a-release) for different options.
|
||||
|
||||
## Can I set the initial release version of my package to `0.0.1`?
|
||||
|
||||
This is not supported by **semantic-release** as it's not considered a good practice, mostly because [Semantic Versioning](https://semver.org) rules applies differently to major version zero.
|
||||
|
||||
In early development phase when your package is not ready for production yet we recommend to publish releases on a distribution channel (for example npm’s [dist-tags](https://docs.npmjs.com/cli/dist-tag)) or to develop on a `dev` branch and merge it to `master` periodically. See [Triggering a release](../../README.md#triggering-a-release) for more details on those solutions.
|
||||
|
||||
See [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2) for more details on [Semantic Versioning](https://semver.org) and the recommendation to start at version `1.0.0`.
|
||||
|
||||
## Can I trust semantic-release with my releases?
|
||||
|
||||
**semantic-release** has a full unit and integration test suite that tests `npm` publishes against the [npm-registry-couchapp](https://github.com/npm/npm-registry-couchapp).
|
||||
|
||||
In addition the [verify conditions step](../../README.md#release-steps) verifies that all necessary conditions for proceeding with a release are met, and a new release will be performed [only if all your tests pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
|
||||
|
||||
## Why does semantic-release require Node version >= 8.3?
|
||||
|
||||
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which **requires Node version 8.3 or higher**.
|
||||
|
||||
See [Node version requirement](../support/node-version.md#node-version-requirement) for more details and solutions.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Support
|
||||
|
||||
- [Frequently Asked Questions](FAQ.md)
|
||||
- [Troubleshooting](troubleshooting.md)
|
||||
- [Node version requirement](node-version.md)
|
||||
- [Node Support Policy](node-support-policy.md)
|
||||
@@ -0,0 +1,13 @@
|
||||
# Node Support Policy
|
||||
|
||||
We only support [Long-Term Support](https://github.com/nodejs/Release) versions of Node starting with [Node 8.9.0 (LTS)](https://nodejs.org/en/blog/release/v8.9.0).
|
||||
|
||||
We specifically limit our support to LTS versions of Node, not because this package won't work on other versions, but because we have a limited amount of time, and supporting LTS offers the greatest return on that investment.
|
||||
|
||||
It's possible this package will work correctly on newer versions of Node. It may even be possible to use this package on older versions of Node, though that's more unlikely as we'll make every effort to take advantage of features available in the oldest LTS version we support.
|
||||
|
||||
As each Node LTS version reaches its end-of-life we will remove that version from the node engines property of our package's package.json file. Removing a Node version is considered a breaking change and will entail the publishing of a new major version of this package. We will not accept any requests to support an end-of-life version of Node. Any merge requests or issues supporting an end-of-life version of Node will be closed.
|
||||
|
||||
We will accept code that allows this package to run on newer, non-LTS, versions of Node. Furthermore, we will attempt to ensure our own changes work on the latest version of Node. To help in that commitment, our continuous integration setup runs against all LTS versions of Node in addition the most recent Node release; called current.
|
||||
|
||||
JavaScript package managers should allow you to install this package with any version of Node, with, at most, a warning if your version of Node does not fall within the range specified by our node engines property. If you encounter issues installing this package, please report the issue to your package manager.
|
||||
@@ -0,0 +1,52 @@
|
||||
# Node version requirement
|
||||
|
||||
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which requires **requires Node version 8.3 or higher**.
|
||||
|
||||
**semantic-release** is meant to be used in a CI environment as a development support tool, not as a production dependency. Therefore the only constraint is to run the `semantic-release` in a CI environment providing Node 8 or higher.
|
||||
|
||||
See our [Node Support Policy](node-support-policy.md) for our long-term promise regarding Node version support.
|
||||
|
||||
## Recommended solution
|
||||
|
||||
### Run at least one CI job with Node >= 8.3
|
||||
|
||||
The recommended approach is to run the `semantic-release` command from a CI job running on Node 8.3 or higher. This can either be a job used by your project to test on Node >= 8.3 or a dedicated job for the release steps.
|
||||
|
||||
See [CI configuration](../usage/ci-configuration.md) and [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
|
||||
|
||||
## Alternative solutions
|
||||
|
||||
### Use `npx`
|
||||
|
||||
[`npx`](https://github.com/zkat/npx) is a CLI to execute npm binaries. It is bundled with [npm](https://www.npmjs.com/package/npm) >= 5.4, or can be installed via `npm install -g npx`.
|
||||
|
||||
`npx` can be used to download the latest [Node 8 package published on npm](https://www.npmjs.com/package/node) and use it to execute the `semantic-release` command.
|
||||
|
||||
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation:
|
||||
|
||||
```bash
|
||||
$ npm install -g npx && npx -p node@8 -c "npm run semantic-release"
|
||||
```
|
||||
|
||||
If you are using a [global](../usage/installation.md#global-installation) **semantic-release** installation:
|
||||
|
||||
```bash
|
||||
# For global semantic-release install
|
||||
$ npm install -g semantic-release npx && npx -p node@8 -c "semantic-release"
|
||||
```
|
||||
|
||||
### Use `nvm`
|
||||
|
||||
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can use it to switch to Node 8 before running the `semantic-release` command.
|
||||
|
||||
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation:
|
||||
|
||||
```bash
|
||||
$ nvm install 8 && npm run semantic-release
|
||||
```
|
||||
|
||||
If you are using a [global](../usage/installation.md#global-installation) **semantic-release** installation:
|
||||
|
||||
```bash
|
||||
$ nvm install 8 && npm install -g semantic-release && semantic-release
|
||||
```
|
||||
@@ -0,0 +1,31 @@
|
||||
# Troubleshooting
|
||||
|
||||
## ENOTINHISTORY Commit not in history
|
||||
|
||||
This error happens when the commit associated with the last release cannot be found in the branch history.
|
||||
|
||||
Multiple situation can cause this issue:
|
||||
- The package name configured in your `package.json` already exists and **semantic-release** obtains the last release of that package, which is unrelated to yours
|
||||
- The commit history has been rewritten since the last release (with `git rebase` and `git push -f`)
|
||||
|
||||
If the package name configured in your `package.json` already exits, you should change it, and commit the `package.json`. Then **semantic-release** will proceed normally and make the initial release.
|
||||
|
||||
If you can identify the commit in your branch history that should be associated with the release version mentioned in the error message you can recover by tagging this commit:
|
||||
|
||||
```bash
|
||||
$ git tag -f v<version of the last release> <commit sha1 corresponding to last release>
|
||||
$ git push -f --tags origin <your release branch>
|
||||
```
|
||||
|
||||
## ENOGITHEAD There is no commit associated with last release
|
||||
|
||||
This error happens when there is no commit associated with the last release that can be found in the package metadata on the npm registry.
|
||||
|
||||
This usually happen when the last release has been made without access to the git repository informations.
|
||||
|
||||
You can recover from that issue by identifying the commit in your branch history that should have been associated with the release version mentioned in the error message and tagging this commit:
|
||||
|
||||
```bash
|
||||
$ git tag -f v<version of the last release> <commit sha1 corresponding to last release>
|
||||
$ git push -f --tags origin <your release branch>
|
||||
```
|
||||
@@ -0,0 +1,7 @@
|
||||
# Usage
|
||||
|
||||
- [Installation](installation.md#installation)
|
||||
- [CI Configuration](ci-configuration.md#ci-configuration)
|
||||
- [Configuration](configuration.md#configuration)
|
||||
- [Plugins](plugins.md)
|
||||
- [Shareable configurations](shareable-configurations.md)
|
||||
@@ -0,0 +1,49 @@
|
||||
# CI configuration
|
||||
|
||||
## Run `semantic-release` only after all tests succeeded
|
||||
|
||||
The `semantic-release` command must be executed only after all the tests in the CI build pass. If the build runs multiple jobs (for example to test on multiple Operating Systems or Node versions) the CI has to be configured to guarantee that the `semantic-release` command is executed only after all jobs are successful. This can be achieved with [Travis Build Stages](https://docs.travis-ci.com/user/build-stages), [CircleCI Workflows](https://circleci.com/docs/2.0/workflows), [Codeship Deployment Pipelines](https://documentation.codeship.com/basic/builds-and-configuration/deployment-pipelines), [GitLab Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html#introduction-to-pipelines-and-jobs), [Wercker Workflows](http://devcenter.wercker.com/docs/workflows), [GoCD Pipelines](https://docs.gocd.org/current/introduction/concepts_in_go.html#pipeline) or specific tools like [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once).
|
||||
|
||||
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
|
||||
|
||||
## Authentication
|
||||
|
||||
**semantic-release** requires push access to the project Git repository in order to create [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). The Git authentication can be set with one of the following environment variables:
|
||||
|
||||
| Variable | Description |
|
||||
|------------------------------|-------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `GH_TOKEN` or `GITHUB_TOKEN` | A GitHub [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line). |
|
||||
| `GL_TOKEN` or `GITLAB_TOKEN` | A GitLab [personal access token](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html). |
|
||||
| `GIT_CREDENTIALS` | [URL encoded basic HTTP Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication#URL_encoding) credentials). |
|
||||
|
||||
`GIT_CREDENTIALS` can be the Git username and password in the format `<username>:<password>` or a token for certain Git providers like [Bitbucket](https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html).
|
||||
|
||||
Alternatively the Git authentication can be set up via [SSH keys](../recipes/git-auth-ssh-keys.md).
|
||||
|
||||
Most **semantic-release** [plugins](plugins.md) require to set up authentication in order to publish to a package manager registry. The default [npm](https://github.com/semantic-release/npm#environment-variables) and [github](https://github.com/semantic-release/github#environment-variables) plugins require the following environment variables:
|
||||
|
||||
| Variable | Description |
|
||||
|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `NPM_TOKEN` | npm token created via [npm token create](https://docs.npmjs.com/getting-started/working_with_tokens#how-to-create-new-tokens).<br/>**Note**: Only the `auth-only` [level of npm two-factor authentication](https://docs.npmjs.com/getting-started/using-two-factor-authentication#levels-of-authentication) is supported. |
|
||||
| `GH_TOKEN` | GitHub authentication token.<br/>**Note**: Only the [personal token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line) authentication is supported. |
|
||||
|
||||
See each plugin documentation for the environment variables to set up.
|
||||
|
||||
The authentication token/credentials have to be made available in the CI service via environment variables.
|
||||
|
||||
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on how to configure environment variables in your CI service.
|
||||
|
||||
## Automatic setup with `semantic-release-cli`
|
||||
|
||||
[`semantic-release-cli`](https://github.com/semantic-release/cli) allow to easily [install](installation.md) **semantic-release** in your Node project and set up the CI configuration:
|
||||
|
||||
```bash
|
||||
npm install -g semantic-release-cli
|
||||
|
||||
cd your-module
|
||||
semantic-release-cli setup
|
||||
```
|
||||
|
||||

|
||||
|
||||
See the [semantic-release-cli](https://github.com/semantic-release/cli#what-it-does) documentation for more details.
|
||||
@@ -0,0 +1,156 @@
|
||||
# Configuration
|
||||
|
||||
In order to customize **semantic-release**’s behavior, [options](#options) and [plugins](plugins.md) can be set via:
|
||||
- A `.releaserc` file, written in YAML or JSON, with optional extensions: .`yaml`/`.yml`/`.json`/`.js`
|
||||
- A `release.config.js` file that exports an object
|
||||
- A `release` key in the project's `package.json` file
|
||||
- CLI arguments
|
||||
|
||||
The following two examples are the same.
|
||||
|
||||
Via CLI argument:
|
||||
|
||||
```bash
|
||||
$ semantic-release --branch next
|
||||
```
|
||||
|
||||
Via `release` key in the project's `package.json` file:
|
||||
|
||||
```json
|
||||
"release": {
|
||||
"branch": "next"
|
||||
}
|
||||
```
|
||||
```bash
|
||||
$ semantic-release
|
||||
```
|
||||
|
||||
**Note**: CLI arguments take precedence over options configured in the configuration file.
|
||||
|
||||
**Note**: Plugins options cannot be defined via CLI arguments and must be defined in the configuration file.
|
||||
|
||||
## Options
|
||||
|
||||
### extends
|
||||
|
||||
Type: `Array`, `String`
|
||||
|
||||
CLI arguments: `-e`, `--extends`
|
||||
|
||||
List of modules or file paths containing a [shareable configuration](shareable-configurations.md). If multiple shareable configuration are set, they will be imported in the order defined with each configuration option taking precedence over the options defined in a previous shareable configuration.
|
||||
|
||||
**Note**: Options defined via CLI arguments or in the configuration file will take precedence over the ones defined in any shareable configuration.
|
||||
|
||||
### branch
|
||||
|
||||
Type: `String`
|
||||
|
||||
Default: `master`
|
||||
|
||||
CLI arguments: `-b`, `--branch`
|
||||
|
||||
The branch on which releases should happen.
|
||||
|
||||
### repositoryUrl
|
||||
|
||||
Type: `String`
|
||||
|
||||
Default: `repository` property in `package.json` or [git origin url](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes)
|
||||
|
||||
CLI arguments: `-r`, `--repository-url`
|
||||
|
||||
The git repository URL
|
||||
|
||||
Any valid git url format is supported (See [Git protocols](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols)).
|
||||
|
||||
**Note**: If the [Github plugin](https://github.com/semantic-release/github) is used the URL must be a valid Github URL that include the `owner`, the `repository` name and the `host`. **The Github shorthand URL is not supported.**
|
||||
|
||||
### dryRun
|
||||
|
||||
Type: `Boolean`
|
||||
|
||||
Default: `false` if running in a CI environment, `false` otherwise
|
||||
|
||||
CLI arguments: `-d`, `--dry-run`
|
||||
|
||||
Dry-run mode, skip publishing, print next version and release notes.
|
||||
|
||||
### noCi
|
||||
|
||||
Type: `Boolean`
|
||||
|
||||
Default: `false`
|
||||
|
||||
CLI arguments: `--no-ci`
|
||||
|
||||
Skip Continuous Integration environment verifications, allowing to make releases from a local machine.
|
||||
|
||||
### debug
|
||||
|
||||
Type: `Boolean`
|
||||
|
||||
Default: `false`
|
||||
|
||||
CLI argument: `--debug`
|
||||
|
||||
Output debugging information. It can also be enabled by set the `DEBUG` environment variable to `semantic-release`.
|
||||
|
||||
### verifyConditions
|
||||
|
||||
Type: `Array`, `String`, `Object`
|
||||
|
||||
Default: `['@semantic-release/npm', '@semantic-release/github']`
|
||||
|
||||
CLI argument: `--verify-conditions`
|
||||
|
||||
Define the list of [verify conditions plugins](plugins.md#verifyconditions-plugin). Plugins will run in series, in the order defined in the `Array`.
|
||||
|
||||
See [Plugins configuration](plugins.md#configuration) for more details.
|
||||
|
||||
### analyzeCommits
|
||||
|
||||
Type: `String`, `Object`
|
||||
|
||||
Default: `['@semantic-release/commit-analyzer']`
|
||||
|
||||
CLI argument: `--analyze-commits`
|
||||
|
||||
Define the [analyze commits plugin](plugins.md#analyzecommits-plugin).
|
||||
|
||||
See [Plugins configuration](plugins.md#configuration) for more details.
|
||||
|
||||
### verifyRelease
|
||||
|
||||
Type: `Array`, `String`, `Object`
|
||||
|
||||
Default: `[]`
|
||||
|
||||
CLI argument: `--verify-release`
|
||||
|
||||
Define the list of [verify release plugins](plugins.md#verifyrelease-plugin). Plugins will run in series, in the order defined in the `Array`.
|
||||
|
||||
See [Plugins configuration](plugins.md#configuration) for more details.
|
||||
|
||||
### generateNotes
|
||||
|
||||
Type: `String`, `Object`
|
||||
|
||||
Default: `['@semantic-release/release-notes-generator']`
|
||||
|
||||
CLI argument: `--generate-notes`
|
||||
|
||||
Define the [generate notes plugin](plugins.md#generatenotes-plugin).
|
||||
|
||||
See [Plugins configuration](plugins.md#configuration) for more details.
|
||||
|
||||
### publish
|
||||
|
||||
Type: `Array`, `String`, `Object`
|
||||
|
||||
Default: `['@semantic-release/npm', '@semantic-release/github']`
|
||||
|
||||
CLI argument: `--publish`
|
||||
|
||||
Define the list of [publish plugins](plugins.md#publish-plugin). Plugins will run in series, in the order defined in the `Array`.
|
||||
|
||||
See [Plugins configuration](plugins.md#configuration) for more details.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Installation
|
||||
|
||||
## Local installation
|
||||
|
||||
For [Node modules projects](https://docs.npmjs.com/getting-started/creating-node-modules) we recommend to install **semantic-release** locally and to run the `semantic-release` command with a [npm script](https://docs.npmjs.com/misc/scripts):
|
||||
|
||||
```bash
|
||||
$ npm install --save-dev semantic-release
|
||||
```
|
||||
|
||||
In your `package.json`:
|
||||
|
||||
```json
|
||||
"scripts": {
|
||||
"semantic-release": "semantic-release"
|
||||
}
|
||||
```
|
||||
|
||||
Then in the CI environment:
|
||||
|
||||
```bash
|
||||
$ npm run semantic-release
|
||||
```
|
||||
|
||||
## Global installation
|
||||
|
||||
For other type of projects we recommend to install **semantic-release** globally directly in the CI environment:
|
||||
|
||||
```bash
|
||||
$ npm install -g semantic-release
|
||||
$ semantic-release
|
||||
```
|
||||
**Note:**: For a global installation, it's recommended to specify the major **semantic-release** version to install (for example with with `npm install -g semantic-release@12`). This way your build will not automatically use the next major **semantic-release** release that could possibly break your build. You will have to upgrade manually when a new major version is released.
|
||||
@@ -0,0 +1,76 @@
|
||||
# Plugins
|
||||
|
||||
Each [release steps](../../README.md#release-steps) is implemented within a plugin or a list of plugins that can be configured, allowing to support different [commit message format](../../README.md#commit-message-format), release not generator and publishing platforms.
|
||||
|
||||
## Plugin types
|
||||
|
||||
### verifyConditions plugin
|
||||
|
||||
Plugin responsible for verifying all the conditions to proceed with the release: configuration is correct, authentication token are valid, etc...
|
||||
|
||||
Default implementation: [npm](https://github.com/semantic-release/npm#verifyconditions) and [github](https://github.com/semantic-release/github#verifyconditions).
|
||||
|
||||
### analyzeCommits plugin
|
||||
|
||||
Plugin responsible for determining the type of the next release (`major`, `minor` or `patch`).
|
||||
|
||||
Default implementation: [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer).
|
||||
|
||||
### verifyRelease plugin
|
||||
|
||||
Plugin responsible for verifying the parameters (version, type, dist-tag etc...) of the release that is about to be published match certain expectations. For example the [cracks plugin](https://github.com/semantic-release/cracks) allows to verify that if a release contains breaking changes, its type must be `major`.
|
||||
|
||||
Default implementation: none.
|
||||
|
||||
### generateNotes plugin
|
||||
|
||||
Plugin responsible for generating release notes.
|
||||
|
||||
Default implementation: [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator).
|
||||
|
||||
### publish plugin
|
||||
|
||||
Plugin responsible for publishing the release.
|
||||
|
||||
Default implementation: [npm](https://github.com/semantic-release/npm#publish) and [github](https://github.com/semantic-release/github#publish).
|
||||
|
||||
## Configuration
|
||||
|
||||
Plugin can be configured by specifying the plugin's module name or file path directly as a `String` or within the `path` key of an `Object`.
|
||||
|
||||
Plugins specific options can be set similarly to the other **semantic-release** [options](configuration.md#options) or within the plugin `Object`. Plugins options defined along the other **semantic-release** [options](configuration.md#options) will apply to all plugins, while the one defined within the plugin `Object` will apply only to this specific plugin.
|
||||
|
||||
For example:
|
||||
```json
|
||||
{
|
||||
"release": {
|
||||
"verifyConditions": [
|
||||
{
|
||||
"path": "@semantic-release/exec",
|
||||
"cmd": "verify-conditions.sh"
|
||||
},
|
||||
"@semantic-release/npm",
|
||||
"@semantic-release/github"
|
||||
],
|
||||
"analyzeCommits": "custom-plugin",
|
||||
"verifyRelease": [
|
||||
{
|
||||
"path": "@semantic-release/exec",
|
||||
"cmd": "verify-release.sh"
|
||||
},
|
||||
],
|
||||
"generateNotes": "./build/my-plugin.js",
|
||||
"githubUrl": "https://my-ghe.com",
|
||||
"githubApiPathPrefix": "/api-prefix"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
With this configuration:
|
||||
- the `custom-plugin` npm module will be used to [analyze commits](#analyzecommits-plugin)
|
||||
- the `./build/my-plugin.js` script will be used to [generate release notes](#generatenotes-plugin)
|
||||
- the [`@semantic-release/exec`](https://github.com/semantic-release/exec), [`@semantic-release/npm`](https://github.com/semantic-release/npm) and [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugins will be used to [verify conditions](#verifyconditions-plugin)
|
||||
- the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin will be used to [verify the release](#verifyrelease-plugin)
|
||||
- the `cmd` option will be set to `verify-conditions.sh` only for the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin used to [verify conditions](#verifyconditions-plugin)
|
||||
- the `cmd` option will be set to `verify-release.sh` only for the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin used to [verify the release](#verifyrelease-plugin)
|
||||
- the `githubUrl` and `githubApiPathPrefix` options will be set to respectively `https://my-ghe.com` and `/api-prefix` for all plugins
|
||||
@@ -0,0 +1,5 @@
|
||||
# Shareable configurations
|
||||
|
||||
A sharable configuration is an [npm](https://www.npmjs.com/) package that exports a **semantic-release** configuration object. It allows to easily use the same configuration across several projects.
|
||||
|
||||
The shareable configurations to use can be set with the [extends](configuration.md#extends) option.
|
||||
@@ -0,0 +1,121 @@
|
||||
const marked = require('marked');
|
||||
const TerminalRenderer = require('marked-terminal');
|
||||
const envCi = require('env-ci');
|
||||
const hookStd = require('hook-std');
|
||||
const hideSensitive = require('./lib/hide-sensitive');
|
||||
const getConfig = require('./lib/get-config');
|
||||
const verify = require('./lib/verify');
|
||||
const getNextVersion = require('./lib/get-next-version');
|
||||
const getCommits = require('./lib/get-commits');
|
||||
const getLastRelease = require('./lib/get-last-release');
|
||||
const logger = require('./lib/logger');
|
||||
const {unshallow, gitHead: getGitHead, tag, push, deleteTag} = require('./lib/git');
|
||||
|
||||
async function run(opts) {
|
||||
const {isCi, branch, isPr} = envCi();
|
||||
const config = await getConfig(opts, logger);
|
||||
const {plugins, options} = config;
|
||||
|
||||
if (!isCi && !options.dryRun && !options.noCi) {
|
||||
logger.log('This run was not triggered in a known CI environment, running in dry-run mode.');
|
||||
options.dryRun = true;
|
||||
}
|
||||
|
||||
if (isCi && isPr && !options.noCi) {
|
||||
logger.log("This run was triggered by a pull request and therefore a new version won't be published.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!await verify(options, branch, logger)) {
|
||||
return;
|
||||
}
|
||||
|
||||
logger.log('Run automated release from branch %s', options.branch);
|
||||
|
||||
logger.log('Call plugin %s', 'verify-conditions');
|
||||
await plugins.verifyConditions({options, logger}, true);
|
||||
|
||||
// Unshallow the repo in order to get all the tags
|
||||
await unshallow();
|
||||
|
||||
const lastRelease = await getLastRelease(logger);
|
||||
const commits = await getCommits(lastRelease.gitHead, options.branch, logger);
|
||||
|
||||
logger.log('Call plugin %s', 'analyze-commits');
|
||||
const type = await plugins.analyzeCommits({
|
||||
options,
|
||||
logger,
|
||||
lastRelease,
|
||||
commits: commits.filter(commit => !/\[skip\s+release\]|\[release\s+skip\]/i.test(commit.message)),
|
||||
});
|
||||
if (!type) {
|
||||
logger.log('There are no relevant changes, so no new version is released.');
|
||||
return;
|
||||
}
|
||||
const version = getNextVersion(type, lastRelease, logger);
|
||||
const nextRelease = {type, version, gitHead: await getGitHead(), gitTag: `v${version}`};
|
||||
|
||||
logger.log('Call plugin %s', 'verify-release');
|
||||
await plugins.verifyRelease({options, logger, lastRelease, commits, nextRelease}, true);
|
||||
|
||||
const generateNotesParam = {options, logger, lastRelease, commits, nextRelease};
|
||||
|
||||
if (options.dryRun) {
|
||||
logger.log('Call plugin %s', 'generate-notes');
|
||||
const notes = await plugins.generateNotes(generateNotesParam);
|
||||
marked.setOptions({renderer: new TerminalRenderer()});
|
||||
logger.log('Release note for version %s:\n', nextRelease.version);
|
||||
process.stdout.write(`${marked(notes)}\n`);
|
||||
} else {
|
||||
logger.log('Call plugin %s', 'generateNotes');
|
||||
nextRelease.notes = await plugins.generateNotes(generateNotesParam);
|
||||
|
||||
// Create the tag before calling the publish plugins as some require the tag to exists
|
||||
logger.log('Create tag %s', nextRelease.gitTag);
|
||||
await tag(nextRelease.gitTag);
|
||||
await push(options.repositoryUrl, branch);
|
||||
|
||||
logger.log('Call plugin %s', 'publish');
|
||||
await plugins.publish({options, logger, lastRelease, commits, nextRelease}, false, async prevInput => {
|
||||
const newGitHead = await getGitHead();
|
||||
// If previous publish plugin has created a commit (gitHead changed)
|
||||
if (prevInput.nextRelease.gitHead !== newGitHead) {
|
||||
// Delete the previously created tag
|
||||
await deleteTag(options.repositoryUrl, nextRelease.gitTag);
|
||||
// Recreate the tag, referencing the new gitHead
|
||||
logger.log('Create tag %s', nextRelease.gitTag);
|
||||
await tag(nextRelease.gitTag);
|
||||
await push(options.repositoryUrl, branch);
|
||||
|
||||
nextRelease.gitHead = newGitHead;
|
||||
// Regenerate the release notes
|
||||
logger.log('Call plugin %s', 'generateNotes');
|
||||
nextRelease.notes = await plugins.generateNotes(generateNotesParam);
|
||||
}
|
||||
// Call the next publish plugin with the updated `nextRelease`
|
||||
return {options, logger, lastRelease, commits, nextRelease};
|
||||
});
|
||||
logger.log('Published release: %s', nextRelease.version);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
module.exports = async opts => {
|
||||
const unhook = hookStd({silent: false}, hideSensitive);
|
||||
try {
|
||||
const result = await run(opts);
|
||||
unhook();
|
||||
return result;
|
||||
} catch (err) {
|
||||
const errors = err.name === 'AggregateError' ? Array.from(err).sort(error => !error.semanticRelease) : [err];
|
||||
for (const error of errors) {
|
||||
if (error.semanticRelease) {
|
||||
logger.log(`%s ${error.message}`, error.code);
|
||||
} else {
|
||||
logger.error('An error occurred while running semantic-release: %O', error);
|
||||
}
|
||||
}
|
||||
unhook();
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,32 @@
|
||||
const gitLogParser = require('git-log-parser');
|
||||
const getStream = require('get-stream');
|
||||
const debug = require('debug')('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.
|
||||
*
|
||||
* @param {String} gitHead The commit sha associated with the last release.
|
||||
* @param {String} branch The branch to release from.
|
||||
* @param {Object} logger Global logger.
|
||||
*
|
||||
* @return {Promise<Array<Object>>} The list of commits on the branch `branch` since the last release.
|
||||
*/
|
||||
module.exports = async (gitHead, branch, logger) => {
|
||||
if (gitHead) {
|
||||
debug('Use gitHead: %s', gitHead);
|
||||
} else {
|
||||
logger.log('No previous release found, retrieving all commits');
|
||||
}
|
||||
|
||||
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
|
||||
const commits = (await getStream.array(gitLogParser.parse({_: `${gitHead ? gitHead + '..' : ''}HEAD`}))).map(
|
||||
commit => {
|
||||
commit.message = commit.message.trim();
|
||||
commit.gitTags = commit.gitTags.trim();
|
||||
return commit;
|
||||
}
|
||||
);
|
||||
logger.log('Found %s commits since last release', commits.length);
|
||||
debug('Parsed commits: %o', commits);
|
||||
return commits;
|
||||
};
|
||||
@@ -0,0 +1,76 @@
|
||||
const readPkgUp = require('read-pkg-up');
|
||||
const {castArray, pickBy, isUndefined, isNull, isString, isPlainObject} = require('lodash');
|
||||
const cosmiconfig = require('cosmiconfig');
|
||||
const resolveFrom = require('resolve-from');
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
const debug = require('debug')('semantic-release:config');
|
||||
const {repoUrl} = require('./git');
|
||||
const PLUGINS_DEFINITION = require('./plugins/definitions');
|
||||
const plugins = require('./plugins');
|
||||
const getGitAuthUrl = require('./get-git-auth-url');
|
||||
|
||||
module.exports = async (opts, logger) => {
|
||||
const {config} = (await cosmiconfig('release', {rcExtensions: true}).load(process.cwd())) || {};
|
||||
// Merge config file options and CLI/API options
|
||||
let options = {...config, ...opts};
|
||||
const pluginsPath = {};
|
||||
let extendPaths;
|
||||
({extends: extendPaths, ...options} = options);
|
||||
if (extendPaths) {
|
||||
// If `extends` is defined, load and merge each shareable config with `options`
|
||||
options = {
|
||||
...castArray(extendPaths).reduce((result, extendPath) => {
|
||||
const extendsOpts = require(resolveFrom.silent(__dirname, extendPath) ||
|
||||
resolveFrom(process.cwd(), extendPath));
|
||||
|
||||
// For each plugin defined in a shareable config, save in `pluginsPath` the extendable config path,
|
||||
// so those plugin will be loaded relatively to the config file
|
||||
Object.keys(extendsOpts).reduce((pluginsPath, option) => {
|
||||
if (PLUGINS_DEFINITION[option]) {
|
||||
castArray(extendsOpts[option])
|
||||
.filter(plugin => isString(plugin) || (isPlainObject(plugin) && isString(plugin.path)))
|
||||
.map(plugin => (isString(plugin) ? plugin : plugin.path))
|
||||
.forEach(plugin => {
|
||||
pluginsPath[plugin] = extendPath;
|
||||
});
|
||||
}
|
||||
return pluginsPath;
|
||||
}, pluginsPath);
|
||||
|
||||
return {...result, ...extendsOpts};
|
||||
}, {}),
|
||||
...options,
|
||||
};
|
||||
}
|
||||
|
||||
// Set default options values if not defined yet
|
||||
options = {
|
||||
branch: 'master',
|
||||
repositoryUrl: (await pkgRepoUrl()) || (await repoUrl()),
|
||||
// Remove `null` and `undefined` options so they can be replaced with default ones
|
||||
...pickBy(options, option => !isUndefined(option) && !isNull(option)),
|
||||
};
|
||||
|
||||
debug('options values: %O', Object.keys(options));
|
||||
debug('name: %O', options.name);
|
||||
debug('branch: %O', options.branch);
|
||||
debug('repositoryUrl: %O', options.repositoryUrl);
|
||||
debug('analyzeCommits: %O', options.analyzeCommits);
|
||||
debug('generateNotes: %O', options.generateNotes);
|
||||
debug('verifyConditions: %O', options.verifyConditions);
|
||||
debug('verifyRelease: %O', options.verifyRelease);
|
||||
debug('publish: %O', options.publish);
|
||||
|
||||
if (!options.repositoryUrl) {
|
||||
throw new SemanticReleaseError('The repositoryUrl option is required', 'ENOREPOURL');
|
||||
}
|
||||
|
||||
options.repositoryUrl = getGitAuthUrl(options.repositoryUrl);
|
||||
|
||||
return {options, plugins: await plugins(options, pluginsPath, logger)};
|
||||
};
|
||||
|
||||
async function pkgRepoUrl() {
|
||||
const {pkg} = await readPkgUp();
|
||||
return pkg && pkg.repository ? pkg.repository.url : undefined;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
const {parse, format} = require('url');
|
||||
const {isUndefined} = require('lodash');
|
||||
const gitUrlParse = require('git-url-parse');
|
||||
|
||||
const GIT_TOKENS = ['GH_TOKEN', 'GITHUB_TOKEN', 'GL_TOKEN', 'GITLAB_TOKEN', 'GIT_CREDENTIALS'];
|
||||
|
||||
/**
|
||||
* Generate the git repository URL with creadentials.
|
||||
* If the `gitCredentials` is defined, returns a http or https URL with Basic Authentication (`https://username:passowrd@hostname:port/path.git`).
|
||||
* If the `gitCredentials` is undefined, returns the `repositoryUrl`. In that case it's expected for the user to have setup the Git authentication on the CI (for example via SSH keys).
|
||||
*
|
||||
* @param {String} gitCredentials Basic HTTP Authentication credentials, can be `username:password` or a token for certain Git providers.
|
||||
* @param {String} repositoryUrl The git repository URL.
|
||||
* @return {String} The formatted Git repository URL.
|
||||
*/
|
||||
module.exports = repositoryUrl => {
|
||||
const envVar = GIT_TOKENS.find(envVar => !isUndefined(process.env[envVar]));
|
||||
const gitCredentials = ['GL_TOKEN', 'GITLAB_TOKEN'].includes(envVar)
|
||||
? `gitlab-ci-token:${process.env[envVar]}`
|
||||
: process.env[envVar];
|
||||
|
||||
if (!gitCredentials) {
|
||||
return repositoryUrl;
|
||||
}
|
||||
|
||||
const {protocols} = gitUrlParse(repositoryUrl);
|
||||
const protocol = protocols.includes('https') ? 'https' : protocols.includes('http') ? 'http' : 'https';
|
||||
return format({...parse(`${gitUrlParse(repositoryUrl).toString(protocol)}.git`), ...{auth: gitCredentials}});
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
const semver = require('semver');
|
||||
const pLocate = require('p-locate');
|
||||
const debug = require('debug')('semantic-release:get-last-release');
|
||||
const {gitTags, isRefInHistory, gitTagHead} = require('./git');
|
||||
|
||||
/**
|
||||
* Last release.
|
||||
*
|
||||
* @typedef {Object} LastRelease
|
||||
* @property {string} version The version number of the last release.
|
||||
* @property {string} [gitHead] The Git reference used to make the last release.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Determine the Git tag and version of the last tagged release.
|
||||
*
|
||||
* - Obtain all the tags referencing commits in the current branch history
|
||||
* - Filter out the ones that are not valid semantic version
|
||||
* - Sort the tags
|
||||
* - Retrive the highest tag
|
||||
*
|
||||
* @param {Object} logger Global logger.
|
||||
* @return {Promise<LastRelease>} The last tagged release or `undefined` if none is found.
|
||||
*/
|
||||
module.exports = async logger => {
|
||||
const tags = (await gitTags()).filter(tag => semver.valid(semver.clean(tag))).sort(semver.rcompare);
|
||||
debug('found tags: %o', tags);
|
||||
|
||||
if (tags.length > 0) {
|
||||
const gitTag = await pLocate(tags, tag => isRefInHistory(tag), {concurrency: 1, preserveOrder: true});
|
||||
logger.log('Found git tag version %s', gitTag);
|
||||
return {gitTag, gitHead: await gitTagHead(gitTag), version: semver.valid(semver.clean(gitTag))};
|
||||
}
|
||||
|
||||
logger.log('No git tag version found');
|
||||
return {};
|
||||
};
|
||||
@@ -1,18 +1,13 @@
|
||||
const semver = require('semver');
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
const logger = require('./logger');
|
||||
|
||||
module.exports = (type, lastRelease) => {
|
||||
module.exports = (type, lastRelease, logger) => {
|
||||
let version;
|
||||
if (!lastRelease.version) {
|
||||
if (lastRelease.version) {
|
||||
version = semver.inc(lastRelease.version, type);
|
||||
logger.log('The next release version is %s', version);
|
||||
} else {
|
||||
version = '1.0.0';
|
||||
logger.log('There is no previous release, the next release version is %s', version);
|
||||
} else {
|
||||
version = semver.inc(lastRelease.version, type);
|
||||
if (!version) {
|
||||
throw new SemanticReleaseError(`Invalid release type ${type}`, 'EINVALIDTYPE');
|
||||
}
|
||||
logger.log('The next release version is %s', version);
|
||||
}
|
||||
|
||||
return version;
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
const execa = require('execa');
|
||||
const debug = require('debug')('semantic-release:get-version-head');
|
||||
|
||||
/**
|
||||
* Get the commit sha for a given tag.
|
||||
*
|
||||
* @param {string} tagName Tag name for which to retrieve the commit sha.
|
||||
*
|
||||
* @return {string} The commit sha of the tag in parameter or `null`.
|
||||
*/
|
||||
async function gitTagHead(tagName) {
|
||||
return execa.stdout('git', ['rev-list', '-1', tagName], {reject: false});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {Array<String>} List of git tags.
|
||||
* @throws {Error} If the `git` command fails.
|
||||
*/
|
||||
async function gitTags() {
|
||||
return (await execa.stdout('git', ['tag']))
|
||||
.split('\n')
|
||||
.map(tag => tag.trim())
|
||||
.filter(tag => Boolean(tag));
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify if the `ref` is in the direct history of the current branch.
|
||||
*
|
||||
* @param {string} ref The reference to look for.
|
||||
*
|
||||
* @return {boolean} `true` if the reference is in the history of the current branch, `false` otherwise.
|
||||
*/
|
||||
async function isRefInHistory(ref) {
|
||||
return (await execa('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], {reject: false})).code === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unshallow the git repository (retriving every commits and tags).
|
||||
*/
|
||||
async function unshallow() {
|
||||
await execa('git', ['fetch', '--unshallow', '--tags'], {reject: false});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {string} the sha of the HEAD commit.
|
||||
*/
|
||||
async function gitHead() {
|
||||
return execa.stdout('git', ['rev-parse', 'HEAD']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {string} The value of the remote git URL.
|
||||
*/
|
||||
async function repoUrl() {
|
||||
return execa.stdout('git', ['remote', 'get-url', 'origin'], {reject: false});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {Boolean} `true` if the current working directory is in a git repository, `false` otherwise.
|
||||
*/
|
||||
async function isGitRepo() {
|
||||
return (await execa('git', ['rev-parse', '--git-dir'], {reject: false})).code === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the write access authorization to remote repository with push dry-run.
|
||||
*
|
||||
* @param {String} origin The remote repository URL.
|
||||
* @param {String} branch The repositoru branch for which to verify write access.
|
||||
*
|
||||
* @return {Boolean} `true` is authorized to push, `false` otherwise.
|
||||
*/
|
||||
async function verifyAuth(origin, branch) {
|
||||
return (await execa('git', ['push', '--dry-run', origin, `HEAD:${branch}`], {reject: false})).code === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tag the commit head on the local repository.
|
||||
*
|
||||
* @param {String} tagName The name of the tag.
|
||||
* @throws {Error} if the tag creation failed.
|
||||
*/
|
||||
async function tag(tagName) {
|
||||
await execa('git', ['tag', tagName]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push to the remote repository.
|
||||
*
|
||||
* @param {String} origin The remote repository URL.
|
||||
* @param {String} branch The branch to push.
|
||||
* @throws {Error} if the push failed.
|
||||
*/
|
||||
async function push(origin, branch) {
|
||||
await execa('git', ['push', '--tags', origin, `HEAD:${branch}`]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a tag locally and remotely.
|
||||
*
|
||||
* @param {String} origin The remote repository URL.
|
||||
* @param {String} tagName The tag name to delete.
|
||||
* @throws {SemanticReleaseError} if the remote tag exists and references a commit that is not the local head commit.
|
||||
*/
|
||||
async function deleteTag(origin, tagName) {
|
||||
// Delete the local tag
|
||||
let shell = await execa('git', ['tag', '-d', tagName], {reject: false});
|
||||
debug('delete local tag', shell);
|
||||
|
||||
// Delete the tag remotely
|
||||
shell = await execa('git', ['push', '-d', origin, tagName], {reject: false});
|
||||
debug('delete remote tag', shell);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
gitTagHead,
|
||||
gitTags,
|
||||
isRefInHistory,
|
||||
unshallow,
|
||||
gitHead,
|
||||
repoUrl,
|
||||
isGitRepo,
|
||||
verifyAuth,
|
||||
tag,
|
||||
push,
|
||||
deleteTag,
|
||||
};
|
||||
@@ -0,0 +1,8 @@
|
||||
const {escapeRegExp} = require('lodash');
|
||||
|
||||
const toReplace = Object.keys(process.env).filter(envVar => /token|password|credential|secret|private/i.test(envVar));
|
||||
const regexp = new RegExp(toReplace.map(envVar => escapeRegExp(process.env[envVar])).join('|'), 'g');
|
||||
|
||||
module.exports = output => {
|
||||
return output && toReplace.length > 0 ? output.toString().replace(regexp, '[secure]') : output;
|
||||
};
|
||||
@@ -7,9 +7,9 @@ module.exports = {
|
||||
log(...args) {
|
||||
const [format, ...rest] = args;
|
||||
console.log(
|
||||
`${chalk.grey('[Semantic release]:')}${typeof format === 'string'
|
||||
? ` ${format.replace(/%[^%]/g, seq => chalk.magenta(seq))}`
|
||||
: ''}`,
|
||||
`${chalk.grey('[Semantic release]:')}${
|
||||
typeof format === 'string' ? ` ${format.replace(/%[^%]/g, seq => chalk.magenta(seq))}` : ''
|
||||
}`,
|
||||
...(typeof format === 'string' ? [] : [format]).concat(rest)
|
||||
);
|
||||
},
|
||||
@@ -0,0 +1,55 @@
|
||||
const {isString, isFunction, isArray} = require('lodash');
|
||||
|
||||
const RELEASE_TYPE = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'];
|
||||
const validatePluginConfig = conf => isString(conf) || isString(conf.path) || isFunction(conf);
|
||||
|
||||
module.exports = {
|
||||
verifyConditions: {
|
||||
default: ['@semantic-release/npm', '@semantic-release/github'],
|
||||
config: {
|
||||
validator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
|
||||
message:
|
||||
'The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
|
||||
},
|
||||
},
|
||||
analyzeCommits: {
|
||||
default: '@semantic-release/commit-analyzer',
|
||||
config: {
|
||||
validator: conf => Boolean(conf) && validatePluginConfig(conf),
|
||||
message:
|
||||
'The "analyzeCommits" plugin is mandatory, and must be a single plugin definition. A plugin definition is either a string or an object with a path property.',
|
||||
},
|
||||
output: {
|
||||
validator: output => !output || RELEASE_TYPE.includes(output),
|
||||
message: 'The "analyzeCommits" plugin output, if defined, must be a valid semver release type.',
|
||||
},
|
||||
},
|
||||
verifyRelease: {
|
||||
default: false,
|
||||
config: {
|
||||
validator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
|
||||
message:
|
||||
'The "verifyRelease" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
|
||||
},
|
||||
},
|
||||
generateNotes: {
|
||||
default: '@semantic-release/release-notes-generator',
|
||||
config: {
|
||||
validator: conf => !conf || validatePluginConfig(conf),
|
||||
message:
|
||||
'The "generateNotes" plugin, if defined, must be a single plugin definition. A plugin definition is either a string or an object with a path property.',
|
||||
},
|
||||
output: {
|
||||
validator: output => !output || isString(output),
|
||||
message: 'The "generateNotes" plugin output, if defined, must be a string.',
|
||||
},
|
||||
},
|
||||
publish: {
|
||||
default: ['@semantic-release/npm', '@semantic-release/github'],
|
||||
config: {
|
||||
validator: conf => Boolean(conf) && (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
|
||||
message:
|
||||
'The "publish" plugin is mandatory, and must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
const {isArray, isObject, omit} = require('lodash');
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
const PLUGINS_DEFINITION = require('./definitions');
|
||||
const pipeline = require('./pipeline');
|
||||
const normalize = require('./normalize');
|
||||
|
||||
module.exports = (options, pluginsPath, logger) =>
|
||||
Object.keys(PLUGINS_DEFINITION).reduce((plugins, pluginType) => {
|
||||
const {config, output, default: def} = PLUGINS_DEFINITION[pluginType];
|
||||
let pluginConfs;
|
||||
if (options[pluginType]) {
|
||||
// If an object is passed and the path is missing, set the default one for single plugins
|
||||
if (isObject(options[pluginType]) && !options[pluginType].path && !isArray(def)) {
|
||||
options[pluginType].path = def;
|
||||
}
|
||||
if (config && !config.validator(options[pluginType])) {
|
||||
throw new SemanticReleaseError(config.message, 'EPLUGINCONF');
|
||||
}
|
||||
pluginConfs = options[pluginType];
|
||||
} else {
|
||||
pluginConfs = def;
|
||||
}
|
||||
|
||||
const globalOpts = omit(options, Object.keys(PLUGINS_DEFINITION));
|
||||
|
||||
plugins[pluginType] = isArray(pluginConfs)
|
||||
? pipeline(pluginConfs.map(conf => normalize(pluginType, pluginsPath, globalOpts, conf, logger, output)))
|
||||
: normalize(pluginType, pluginsPath, globalOpts, pluginConfs, logger, output);
|
||||
|
||||
return plugins;
|
||||
}, {});
|
||||
@@ -0,0 +1,48 @@
|
||||
const {dirname} = require('path');
|
||||
const {inspect} = require('util');
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
const {isString, isObject, isFunction, noop, cloneDeep} = require('lodash');
|
||||
const resolveFrom = require('resolve-from');
|
||||
|
||||
module.exports = (pluginType, pluginsPath, globalOpts, pluginOpts, logger, validator) => {
|
||||
if (!pluginOpts) {
|
||||
return noop;
|
||||
}
|
||||
|
||||
const {path, ...config} = isString(pluginOpts) || isFunction(pluginOpts) ? {path: pluginOpts} : pluginOpts;
|
||||
if (!isFunction(pluginOpts)) {
|
||||
if (pluginsPath[path]) {
|
||||
logger.log('Load plugin %s from %s in shareable config %s', pluginType, path, pluginsPath[path]);
|
||||
} else {
|
||||
logger.log('Load plugin %s from %s', pluginType, path);
|
||||
}
|
||||
}
|
||||
|
||||
const basePath = pluginsPath[path]
|
||||
? dirname(resolveFrom.silent(__dirname, pluginsPath[path]) || resolveFrom(process.cwd(), pluginsPath[path]))
|
||||
: __dirname;
|
||||
const plugin = isFunction(path)
|
||||
? path
|
||||
: require(resolveFrom.silent(basePath, path) || resolveFrom(process.cwd(), path));
|
||||
|
||||
let func;
|
||||
if (isFunction(plugin)) {
|
||||
func = plugin.bind(null, cloneDeep({...globalOpts, ...config}));
|
||||
} else if (isObject(plugin) && plugin[pluginType] && isFunction(plugin[pluginType])) {
|
||||
func = plugin[pluginType].bind(null, cloneDeep({...globalOpts, ...config}));
|
||||
} else {
|
||||
throw new SemanticReleaseError(
|
||||
`The ${pluginType} plugin must be a function, or an object with a function in the property ${pluginType}.`,
|
||||
'EPLUGINCONF'
|
||||
);
|
||||
}
|
||||
|
||||
return async input => {
|
||||
const result = await func(cloneDeep(input));
|
||||
|
||||
if (validator && !validator.validator(result)) {
|
||||
throw new Error(`${validator.message} Received: ${inspect(result)}`);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,33 @@
|
||||
const {identity} = require('lodash');
|
||||
const pReflect = require('p-reflect');
|
||||
const pReduce = require('p-reduce');
|
||||
const AggregateError = require('aggregate-error');
|
||||
|
||||
module.exports = steps => async (input, settleAll = false, getNextInput = identity) => {
|
||||
const results = [];
|
||||
const errors = [];
|
||||
await pReduce(
|
||||
steps,
|
||||
async (prevResult, nextStep) => {
|
||||
let result;
|
||||
|
||||
// Call the next step with the input computed at the end of the previous iteration and save intermediary result
|
||||
if (settleAll) {
|
||||
const {isFulfilled, value, reason} = await pReflect(nextStep(prevResult));
|
||||
result = isFulfilled ? value : reason;
|
||||
(isFulfilled ? results : errors).push(result);
|
||||
} else {
|
||||
result = await nextStep(prevResult);
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
// Prepare input for next step, passing the result of the previous iteration and the current one
|
||||
return getNextInput(prevResult, result);
|
||||
},
|
||||
input
|
||||
);
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
return results;
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
const {isGitRepo, verifyAuth} = require('./git');
|
||||
|
||||
module.exports = async (options, branch, logger) => {
|
||||
if (!await isGitRepo()) {
|
||||
logger.error('Semantic-release must run from a git repository.');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!await verifyAuth(options.repositoryUrl, options.branch)) {
|
||||
throw new SemanticReleaseError(
|
||||
`The git credentials doesn't allow to push on the branch ${options.branch}.`,
|
||||
'EGITNOPERMISSION'
|
||||
);
|
||||
}
|
||||
|
||||
if (branch !== options.branch) {
|
||||
logger.log(
|
||||
`This test run was triggered on the branch ${branch}, while semantic-release is configured to only publish from ${
|
||||
options.branch
|
||||
}, therefore a new version won’t be published.`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 142 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 117 KiB |
+54
-48
@@ -14,76 +14,70 @@
|
||||
"path": "cz-conventional-changelog"
|
||||
}
|
||||
},
|
||||
"contributors": [
|
||||
"Gregor Martynus (https://twitter.com/gr2m)",
|
||||
"Pierre Vanduynslager (https://twitter.com/@pvdlg_)"
|
||||
],
|
||||
"dependencies": {
|
||||
"@semantic-release/commit-analyzer": "^4.0.0",
|
||||
"@semantic-release/condition-travis": "^6.0.0",
|
||||
"@semantic-release/commit-analyzer": "^5.0.0",
|
||||
"@semantic-release/error": "^2.1.0",
|
||||
"@semantic-release/last-release-npm": "^2.0.0",
|
||||
"@semantic-release/release-notes-generator": "^5.0.0",
|
||||
"@semantic-release/github": "^4.0.0",
|
||||
"@semantic-release/npm": "^3.0.0",
|
||||
"@semantic-release/release-notes-generator": "^6.0.0",
|
||||
"aggregate-error": "^1.0.0",
|
||||
"chalk": "^2.3.0",
|
||||
"commander": "^2.11.0",
|
||||
"cosmiconfig": "^4.0.0",
|
||||
"debug": "^3.1.0",
|
||||
"execa": "^0.8.0",
|
||||
"fs-extra": "^4.0.2",
|
||||
"env-ci": "^1.0.0",
|
||||
"execa": "^0.9.0",
|
||||
"get-stream": "^3.0.0",
|
||||
"git-head": "^1.2.1",
|
||||
"git-log-parser": "^1.2.0",
|
||||
"github": "^12.0.0",
|
||||
"lodash": "^4.0.0",
|
||||
"marked": "^0.3.6",
|
||||
"git-url-parse": "^8.0.0",
|
||||
"hook-std": "^0.4.0",
|
||||
"lodash": "^4.17.4",
|
||||
"marked": "^0.3.9",
|
||||
"marked-terminal": "^2.0.0",
|
||||
"nerf-dart": "^1.0.0",
|
||||
"normalize-package-data": "^2.3.4",
|
||||
"npm-conf": "^1.1.2",
|
||||
"p-series": "^1.0.0",
|
||||
"parse-github-repo-url": "^1.3.0",
|
||||
"require-relative": "^0.8.7",
|
||||
"p-locate": "^2.0.0",
|
||||
"p-reduce": "^1.0.0",
|
||||
"p-reflect": "^1.0.0",
|
||||
"read-pkg-up": "^3.0.0",
|
||||
"resolve-from": "^4.0.0",
|
||||
"semver": "^5.4.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"ava": "^0.23.0",
|
||||
"ava": "^0.25.0",
|
||||
"clear-module": "^2.1.0",
|
||||
"codecov": "^3.0.0",
|
||||
"commitizen": "^2.9.6",
|
||||
"cz-conventional-changelog": "^2.0.0",
|
||||
"delay": "^2.0.0",
|
||||
"dockerode": "^2.5.2",
|
||||
"eslint": "^4.7.0",
|
||||
"eslint-config-prettier": "^2.5.0",
|
||||
"eslint-config-standard": "^10.2.1",
|
||||
"eslint-plugin-import": "^2.7.0",
|
||||
"eslint-plugin-node": "^5.2.0",
|
||||
"eslint-plugin-prettier": "^2.3.0",
|
||||
"eslint-plugin-promise": "^3.5.0",
|
||||
"eslint-plugin-standard": "^3.0.1",
|
||||
"mockserver-client": "^1.0.16",
|
||||
"file-url": "^2.0.2",
|
||||
"fs-extra": "^5.0.0",
|
||||
"got": "^8.0.0",
|
||||
"js-yaml": "^3.10.0",
|
||||
"mockserver-client": "^5.1.1",
|
||||
"nock": "^9.0.2",
|
||||
"npm-registry-couchapp": "^2.6.12",
|
||||
"nyc": "^11.2.1",
|
||||
"p-map-series": "^1.0.0",
|
||||
"prettier": "^1.7.0",
|
||||
"p-retry": "^1.0.0",
|
||||
"prettier": "~1.10.0",
|
||||
"proxyquire": "^1.8.0",
|
||||
"rimraf": "^2.5.0",
|
||||
"sinon": "^4.0.0",
|
||||
"tempy": "^0.2.1"
|
||||
"tempy": "^0.2.1",
|
||||
"xo": "^0.18.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=4",
|
||||
"npm": ">=2"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": [
|
||||
"standard",
|
||||
"prettier"
|
||||
],
|
||||
"plugins": [
|
||||
"prettier"
|
||||
],
|
||||
"rules": {
|
||||
"prettier/prettier": 2
|
||||
}
|
||||
"node": ">=8.3"
|
||||
},
|
||||
"files": [
|
||||
"bin",
|
||||
"src"
|
||||
"docs",
|
||||
"lib",
|
||||
"index.js",
|
||||
"cli.js"
|
||||
],
|
||||
"homepage": "https://github.com/semantic-release/semantic-release#readme",
|
||||
"keywords": [
|
||||
@@ -101,7 +95,9 @@
|
||||
"main": "index.js",
|
||||
"nyc": {
|
||||
"include": [
|
||||
"src/**/*.js"
|
||||
"lib/**/*.js",
|
||||
"index.js",
|
||||
"cli.js"
|
||||
],
|
||||
"reporter": [
|
||||
"json",
|
||||
@@ -127,12 +123,22 @@
|
||||
"url": "git+https://github.com/semantic-release/semantic-release.git"
|
||||
},
|
||||
"scripts": {
|
||||
"clean": "rimraf coverage && rimraf .nyc_output",
|
||||
"cm": "git-cz",
|
||||
"codecov": "codecov -f coverage/coverage-final.json",
|
||||
"lint": "eslint .",
|
||||
"pretest": "npm run clean && npm run lint",
|
||||
"lint": "xo",
|
||||
"pretest": "npm run lint",
|
||||
"semantic-release": "./bin/semantic-release.js",
|
||||
"test": "nyc ava -v"
|
||||
},
|
||||
"xo": {
|
||||
"extends": [
|
||||
"prettier"
|
||||
],
|
||||
"plugins": [
|
||||
"prettier"
|
||||
],
|
||||
"rules": {
|
||||
"prettier/prettier": 2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
const marked = require('marked');
|
||||
const TerminalRenderer = require('marked-terminal');
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
const getConfig = require('./lib/get-config');
|
||||
const getNextVersion = require('./lib/get-next-version');
|
||||
const verifyPkg = require('./lib/verify-pkg');
|
||||
const verifyAuth = require('./lib/verify-auth');
|
||||
const getCommits = require('./lib/get-commits');
|
||||
const publishNpm = require('./lib/publish-npm');
|
||||
const githubRelease = require('./lib/github-release');
|
||||
const logger = require('./lib/logger');
|
||||
|
||||
module.exports = async opts => {
|
||||
const config = await getConfig(opts);
|
||||
const {plugins, env, options, pkg, npm} = config;
|
||||
|
||||
logger.log('Run automated release for %s on branch %s', pkg.name, options.branch);
|
||||
|
||||
verifyPkg(pkg);
|
||||
if (!options.dryRun) {
|
||||
verifyAuth(options, env);
|
||||
}
|
||||
|
||||
if (!options.dryRun) {
|
||||
logger.log('Call plugin %s', 'verify-conditions');
|
||||
await plugins.verifyConditions({env, options, pkg, npm, logger});
|
||||
}
|
||||
|
||||
logger.log('Call plugin %s', 'get-last-release');
|
||||
const {commits, lastRelease} = await getCommits(
|
||||
await plugins.getLastRelease({env, options, pkg, npm, logger}),
|
||||
options.branch
|
||||
);
|
||||
|
||||
logger.log('Call plugin %s', 'analyze-commits');
|
||||
const type = await plugins.analyzeCommits({env, options, pkg, npm, logger, lastRelease, commits});
|
||||
if (!type) {
|
||||
throw new SemanticReleaseError('There are no relevant changes, so no new version is released.', 'ENOCHANGE');
|
||||
}
|
||||
const nextRelease = {type, version: getNextVersion(type, lastRelease)};
|
||||
|
||||
logger.log('Call plugin %s', 'verify-release');
|
||||
await plugins.verifyRelease({env, options, pkg, npm, logger, lastRelease, commits, nextRelease});
|
||||
|
||||
if (!options.dryRun) {
|
||||
await publishNpm(pkg, npm, nextRelease);
|
||||
}
|
||||
|
||||
logger.log('Call plugin %s', 'generate-notes');
|
||||
const notes = await plugins.generateNotes({env, options, pkg, npm, logger, lastRelease, commits, nextRelease});
|
||||
|
||||
if (options.dryRun) {
|
||||
marked.setOptions({renderer: new TerminalRenderer()});
|
||||
logger.log('Release note for version %s:\n', nextRelease.version);
|
||||
console.log(marked(notes));
|
||||
} else {
|
||||
const releaseUrl = await githubRelease(pkg, notes, nextRelease.version, options);
|
||||
logger.log('Published Github release: %s', releaseUrl);
|
||||
}
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
function debugShell(message, shell, debug) {
|
||||
debug(message);
|
||||
debug('cmd: %O', shell.cmd);
|
||||
debug('stdout: %O', shell.stdout);
|
||||
debug('stderr: %O', shell.stderr);
|
||||
debug('code: %O', shell.code);
|
||||
}
|
||||
|
||||
module.exports = {debugShell};
|
||||
@@ -1,103 +0,0 @@
|
||||
const execa = require('execa');
|
||||
const gitLogParser = require('git-log-parser');
|
||||
const getStream = require('get-stream');
|
||||
const debug = require('debug')('semantic-release:get-commits');
|
||||
const getVersionHead = require('./get-version-head');
|
||||
const {debugShell} = require('./debug');
|
||||
const logger = require('./logger');
|
||||
|
||||
/**
|
||||
* Commit message.
|
||||
*
|
||||
* @typedef {Object} Commit
|
||||
* @property {string} hash The commit hash.
|
||||
* @property {string} message The commit message.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Last release.
|
||||
*
|
||||
* @typedef {Object} LastRelease
|
||||
* @property {string} version The version number of the last release.
|
||||
* @property {string} [gitHead] The commit sha used to make the last release.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Result object.
|
||||
*
|
||||
* @typedef {Object} Result
|
||||
* @property {Array<Commit>} commits The list of commits since the last release.
|
||||
* @property {LastRelease} lastRelease The updated lastRelease.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Retrieve the list of commits on the current branch since the last released version, or all the commits of the current branch if there is no last released version.
|
||||
*
|
||||
* The commit correspoding to the last released version is determined as follow:
|
||||
* - Use `lastRelease.gitHead` if defined and present in `branch` history.
|
||||
* - If `lastRelease.gitHead` is not in the `branch` history, unshallow the repository and try again.
|
||||
* - If `lastRelease.gitHead` is still not in the `branch` history, search for a tag named `v<version>` or `<version>` and verify if it's associated commit sha is present in `branch` history.
|
||||
*
|
||||
* @param {LastRelease} lastRelease The lastRelease object obtained from the getLastRelease plugin.
|
||||
* @param {string} branch The branch to release from.
|
||||
* @param {Object} logger Global logger.
|
||||
*
|
||||
* @return {Promise<Result>} The list of commits on the branch `branch` since the last release and the updated lastRelease with the gitHead used to retrieve the commits.
|
||||
*
|
||||
* @throws {SemanticReleaseError} with code `ENOTINHISTORY` if `lastRelease.gitHead` or the commit sha derived from `config.lastRelease.version` is not in the direct history of `branch`.
|
||||
* @throws {SemanticReleaseError} with code `ENOGITHEAD` if `lastRelease.gitHead` is undefined and no commit sha can be found for the `config.lastRelease.version`.
|
||||
*/
|
||||
module.exports = async ({version, gitHead}, branch) => {
|
||||
if (gitHead || version) {
|
||||
try {
|
||||
gitHead = await getVersionHead(gitHead, version, branch);
|
||||
} catch (err) {
|
||||
if (err.code === 'ENOTINHISTORY') {
|
||||
logger.error(notInHistoryMessage(err.gitHead, branch, version));
|
||||
} else {
|
||||
logger.error(noGitHeadMessage(branch, version));
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
logger.log('Retrieving commits since %s, corresponding to version %s', gitHead, version);
|
||||
} else {
|
||||
logger.log('No previous release found, retrieving all commits');
|
||||
// If there is no gitHead nor a version, there is no previous release. Unshallow the repo in order to retrieve all commits
|
||||
const shell = await execa('git', ['fetch', '--unshallow', '--tags'], {reject: false});
|
||||
debugShell('Unshallow repo', shell, debug);
|
||||
}
|
||||
|
||||
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
|
||||
const commits = (await getStream.array(
|
||||
gitLogParser.parse({_: `${gitHead ? gitHead + '..' : ''}HEAD`})
|
||||
)).map(commit => {
|
||||
commit.message = commit.message.trim();
|
||||
commit.gitTags = commit.gitTags.trim();
|
||||
return commit;
|
||||
});
|
||||
logger.log('Found %s commits since last release', commits.length);
|
||||
debug('Parsed commits: %o', commits);
|
||||
return {commits, lastRelease: {version, gitHead}};
|
||||
};
|
||||
|
||||
function noGitHeadMessage(branch, version) {
|
||||
return `The commit the last release of this package was derived from cannot be determined from the release metadata nor from the repository tags.
|
||||
This means semantic-release can not extract the commits between now and then.
|
||||
This is usually caused by releasing from outside the repository directory or with innaccessible git metadata.
|
||||
|
||||
You can recover from this error by creating a tag for the version "${version}" on the commit corresponding to this release:
|
||||
$ git tag -f v${version} <commit sha1 corresponding to last release>
|
||||
$ git push -f --tags origin ${branch}
|
||||
`;
|
||||
}
|
||||
|
||||
function notInHistoryMessage(gitHead, branch, version) {
|
||||
return `The commit the last release of this package was derived from is not in the direct history of the "${branch}" branch.
|
||||
This means semantic-release can not extract the commits between now and then.
|
||||
This is usually caused by force pushing, releasing from an unrelated branch, or using an already existing package name.
|
||||
|
||||
You can recover from this error by restoring the commit "${gitHead}" or by creating a tag for the version "${version}" on the commit corresponding to this release:
|
||||
$ git tag -f v${version || '<version>'} <commit sha1 corresponding to last release>
|
||||
$ git push -f --tags origin ${branch}
|
||||
`;
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
const url = require('url');
|
||||
const {readJson} = require('fs-extra');
|
||||
const {defaults} = require('lodash');
|
||||
const npmConf = require('npm-conf');
|
||||
const normalizeData = require('normalize-package-data');
|
||||
const debug = require('debug')('semantic-release:config');
|
||||
const logger = require('./logger');
|
||||
const getPlugins = require('./plugins');
|
||||
const getRegistry = require('./get-registry');
|
||||
|
||||
module.exports = async opts => {
|
||||
const pkg = await readJson('./package.json');
|
||||
const {GH_TOKEN, GITHUB_TOKEN, GH_URL} = process.env;
|
||||
normalizeData(pkg);
|
||||
const options = defaults(opts, pkg.release, {
|
||||
branch: 'master',
|
||||
fallbackTags: {next: 'latest'},
|
||||
githubToken: GH_TOKEN || GITHUB_TOKEN,
|
||||
githubUrl: GH_URL,
|
||||
});
|
||||
debug('branch: %O', options.branch);
|
||||
debug('fallbackTags: %O', options.fallbackTags);
|
||||
debug('analyzeCommits: %O', options.analyzeCommits);
|
||||
debug('generateNotes: %O', options.generateNotes);
|
||||
debug('verifyConditions: %O', options.verifyConditions);
|
||||
debug('verifyRelease: %O', options.verifyRelease);
|
||||
|
||||
const plugins = await getPlugins(options);
|
||||
const conf = npmConf();
|
||||
const npm = {
|
||||
auth: {token: process.env.NPM_TOKEN},
|
||||
registry: getRegistry(pkg, conf),
|
||||
tag: (pkg.publishConfig || {}).tag || conf.get('tag'),
|
||||
conf,
|
||||
};
|
||||
|
||||
// normalize trailing slash
|
||||
npm.registry = url.format(url.parse(npm.registry));
|
||||
|
||||
debug('npm registry: %O', npm.registry);
|
||||
debug('npm tag: %O', npm.tag);
|
||||
return {env: process.env, pkg, options, plugins, npm, logger};
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
module.exports = ({publishConfig, name}, conf) => {
|
||||
if (publishConfig && publishConfig.registry) {
|
||||
return publishConfig.registry;
|
||||
}
|
||||
|
||||
if (name[0] !== '@') {
|
||||
return conf.get('registry') || 'https://registry.npmjs.org/';
|
||||
}
|
||||
|
||||
return conf.get(`${name.split('/')[0]}/registry`) || conf.get('registry') || 'https://registry.npmjs.org/';
|
||||
};
|
||||
@@ -1,86 +0,0 @@
|
||||
const execa = require('execa');
|
||||
const debug = require('debug')('semantic-release:get-version-head');
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
const {debugShell} = require('./debug');
|
||||
|
||||
/**
|
||||
* Get the commit sha for a given tag.
|
||||
*
|
||||
* @param {string} tagName Tag name for which to retrieve the commit sha.
|
||||
*
|
||||
* @return {string} The commit sha of the tag in parameter or `null`.
|
||||
*/
|
||||
async function gitTagHead(tagName) {
|
||||
try {
|
||||
const shell = await execa('git', ['rev-list', '-1', '--tags', tagName]);
|
||||
debugShell('Get git tag head', shell, debug);
|
||||
return shell.stdout;
|
||||
} catch (err) {
|
||||
debug(err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify if the commist `sha` is in the direct history of the current branch.
|
||||
*
|
||||
* @param {string} sha The sha of the commit to look for.
|
||||
*
|
||||
* @return {boolean} `true` if the commit `sha` is in the history of the current branch, `false` otherwise.
|
||||
*/
|
||||
async function isCommitInHistory(sha) {
|
||||
const shell = await execa('git', ['merge-base', '--is-ancestor', sha, 'HEAD'], {reject: false});
|
||||
debugShell('Check if commit is in history', shell, debug);
|
||||
return shell.code === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the commit sha for a given version, if it's contained in the given branch.
|
||||
*
|
||||
* @param {string} gitHead The commit sha to look for.
|
||||
* @param {string} version The version corresponding to the commit sha to look for. Used to search in git tags.
|
||||
*
|
||||
* @return {Promise<string>} A Promise that resolves to the commit sha of the version, either `gitHead` of the commit associated with the `version` tag.
|
||||
*
|
||||
* @throws {SemanticReleaseError} with code `ENOTINHISTORY` if `gitHead` or the commit sha dereived from `version` is not in the direct history of `branch`.
|
||||
* @throws {SemanticReleaseError} with code `ENOGITHEAD` if `gitHead` is undefined and no commit sha can be found for the `version`.
|
||||
*/
|
||||
module.exports = async (gitHead, version) => {
|
||||
// Check if gitHead is defined and exists in release branch
|
||||
if (gitHead && (await isCommitInHistory(gitHead))) {
|
||||
debug('Use gitHead: %s', gitHead);
|
||||
return gitHead;
|
||||
}
|
||||
|
||||
// Ushallow the repository
|
||||
const shell = await execa('git', ['fetch', '--unshallow', '--tags'], {reject: false});
|
||||
debugShell('Unshallow repo', shell, debug);
|
||||
|
||||
// Check if gitHead is defined and exists in release branch again
|
||||
if (gitHead && (await isCommitInHistory(gitHead))) {
|
||||
debug('Use gitHead: %s', gitHead);
|
||||
return gitHead;
|
||||
}
|
||||
|
||||
let tagHead;
|
||||
if (version) {
|
||||
// If a version is defined search a corresponding tag
|
||||
tagHead = (await gitTagHead(`v${version}`)) || (await gitTagHead(version));
|
||||
|
||||
// Check if tagHead is found and exists in release branch again
|
||||
if (tagHead && (await isCommitInHistory(tagHead))) {
|
||||
debug('Use tagHead: %s', tagHead);
|
||||
return tagHead;
|
||||
}
|
||||
}
|
||||
|
||||
// Either gitHead is defined or a tagHead has been found but none is in the branch history
|
||||
if (gitHead || tagHead) {
|
||||
const error = new SemanticReleaseError('Commit not in history', 'ENOTINHISTORY');
|
||||
error.gitHead = gitHead || tagHead;
|
||||
throw error;
|
||||
}
|
||||
|
||||
// There is no gitHead in the last release and there is no tags correponsing to the last release version
|
||||
throw new SemanticReleaseError('There is no commit associated with last release', 'ENOGITHEAD');
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
const {promisify} = require('util');
|
||||
const url = require('url');
|
||||
const gitHead = require('git-head');
|
||||
const GitHubApi = require('github');
|
||||
const parseSlug = require('parse-github-repo-url');
|
||||
const debug = require('debug')('semantic-release:github-release');
|
||||
|
||||
module.exports = async (pkg, notes, version, {branch, githubUrl, githubToken, githubApiPathPrefix}) => {
|
||||
const [owner, repo] = parseSlug(pkg.repository.url);
|
||||
let {port, protocol, hostname: host} = githubUrl ? url.parse(githubUrl) : {};
|
||||
protocol = (protocol || '').split(':')[0] || null;
|
||||
const pathPrefix = githubApiPathPrefix || null;
|
||||
const github = new GitHubApi({port, protocol, host, pathPrefix});
|
||||
debug('Github host: %o', host);
|
||||
debug('Github port: %o', port);
|
||||
debug('Github protocol: %o', protocol);
|
||||
debug('Github pathPrefix: %o', pathPrefix);
|
||||
|
||||
github.authenticate({type: 'token', token: githubToken});
|
||||
|
||||
const name = `v${version}`;
|
||||
const release = {owner, repo, tag_name: name, name, target_commitish: branch, body: notes};
|
||||
debug('release owner: %o', owner);
|
||||
debug('release repo: %o', repo);
|
||||
debug('release name: %o', name);
|
||||
debug('release branch: %o', branch);
|
||||
|
||||
const sha = await promisify(gitHead)();
|
||||
const ref = `refs/tags/${name}`;
|
||||
|
||||
debug('Create git tag %o with commit %o', ref, sha);
|
||||
await github.gitdata.createReference({owner, repo, ref, sha});
|
||||
const {data: {html_url: releaseUrl}} = await github.repos.createRelease(release);
|
||||
|
||||
return releaseUrl;
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
module.exports = (config, options, cb) => {
|
||||
cb(null);
|
||||
};
|
||||
@@ -1,45 +0,0 @@
|
||||
const {promisify} = require('util');
|
||||
const relative = require('require-relative');
|
||||
const pSeries = require('p-series');
|
||||
const logger = require('./logger');
|
||||
|
||||
module.exports = options => {
|
||||
const plugins = {
|
||||
analyzeCommits: normalize(options.analyzeCommits, '@semantic-release/commit-analyzer'),
|
||||
generateNotes: normalize(options.generateNotes, '@semantic-release/release-notes-generator'),
|
||||
getLastRelease: normalize(options.getLastRelease, '@semantic-release/last-release-npm'),
|
||||
};
|
||||
['verifyConditions', 'verifyRelease'].forEach(plugin => {
|
||||
if (!Array.isArray(options[plugin])) {
|
||||
plugins[plugin] = normalize(
|
||||
options[plugin],
|
||||
plugin === 'verifyConditions' ? '@semantic-release/condition-travis' : './plugin-noop'
|
||||
);
|
||||
} else {
|
||||
plugins[plugin] = async pluginOptions => {
|
||||
return pSeries(
|
||||
options[plugin].map(step => {
|
||||
return () => normalize(step, './plugin-noop')(pluginOptions);
|
||||
})
|
||||
);
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
return plugins;
|
||||
};
|
||||
|
||||
const normalize = (pluginConfig, fallback) => {
|
||||
if (typeof pluginConfig === 'string') {
|
||||
logger.log('Load plugin %s', pluginConfig);
|
||||
return promisify(relative(pluginConfig).bind(null, {}));
|
||||
}
|
||||
|
||||
if (pluginConfig && typeof pluginConfig.path === 'string') {
|
||||
logger.log('Load plugin %s', pluginConfig.path);
|
||||
return promisify(relative(pluginConfig.path).bind(null, pluginConfig));
|
||||
}
|
||||
return promisify(require(fallback).bind(null, pluginConfig || {}));
|
||||
};
|
||||
|
||||
module.exports.normalize = normalize;
|
||||
@@ -1,35 +0,0 @@
|
||||
const {appendFile, readJson, writeJson, pathExists} = require('fs-extra');
|
||||
const execa = require('execa');
|
||||
const nerfDart = require('nerf-dart');
|
||||
const debug = require('debug')('semantic-release:publish-npm');
|
||||
const {debugShell} = require('./debug');
|
||||
const logger = require('./logger');
|
||||
|
||||
module.exports = async (pkg, {conf, registry, auth}, {version}) => {
|
||||
const pkgFile = await readJson('./package.json');
|
||||
|
||||
if (await pathExists('./npm-shrinkwrap.json')) {
|
||||
const shrinkwrap = await readJson('./npm-shrinkwrap.json');
|
||||
shrinkwrap.version = version;
|
||||
await writeJson('./npm-shrinkwrap.json', shrinkwrap);
|
||||
logger.log('Wrote version %s to npm-shrinkwrap.json', version);
|
||||
}
|
||||
|
||||
await writeJson('./package.json', Object.assign(pkgFile, {version}));
|
||||
logger.log('Wrote version %s to package.json', version);
|
||||
|
||||
if (process.env.NPM_OLD_TOKEN && process.env.NPM_EMAIL) {
|
||||
// Using the old auth token format is not considered part of the public API
|
||||
// This might go away anytime (i.e. once we have a better testing strategy)
|
||||
await appendFile('./.npmrc', `_auth = \${NPM_OLD_TOKEN}\nemail = \${NPM_EMAIL}`);
|
||||
logger.log('Wrote NPM_OLD_TOKEN and NPM_EMAIL to .npmrc.');
|
||||
} else {
|
||||
await appendFile('./.npmrc', `${nerfDart(registry)}:_authToken = \${NPM_TOKEN}`);
|
||||
logger.log('Wrote NPM_TOKEN to .npmrc.');
|
||||
}
|
||||
|
||||
logger.log('Publishing version %s to npm registry %s', version, registry);
|
||||
const shell = await execa('npm', ['publish']);
|
||||
console.log(shell.stdout);
|
||||
debugShell('Publishing on npm', shell, debug);
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
|
||||
module.exports = (options, env) => {
|
||||
if (!options.githubToken) {
|
||||
throw new SemanticReleaseError('No github token specified.', 'ENOGHTOKEN');
|
||||
}
|
||||
|
||||
if (!(env.NPM_TOKEN || (env.NPM_OLD_TOKEN && env.NPM_EMAIL))) {
|
||||
throw new SemanticReleaseError('No npm token specified.', 'ENONPMTOKEN');
|
||||
}
|
||||
};
|
||||
@@ -1,11 +0,0 @@
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
|
||||
module.exports = pkg => {
|
||||
if (!pkg.name) {
|
||||
throw new SemanticReleaseError('No "name" found in package.json.', 'ENOPKGNAME');
|
||||
}
|
||||
|
||||
if (!pkg.repository || !pkg.repository.url) {
|
||||
throw new SemanticReleaseError('No "repository" found in package.json.', 'ENOPKGREPO');
|
||||
}
|
||||
};
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
module.exports = () => {};
|
||||
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
module.exports = {
|
||||
verifyConditions: () => {},
|
||||
getLastRelease: () => {},
|
||||
analyzeCommits: () => {},
|
||||
verifyRelease: () => {},
|
||||
generateNotes: () => {},
|
||||
publish: () => {},
|
||||
};
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
module.exports = function(config, options, cb) {
|
||||
cb(new Error('b'));
|
||||
};
|
||||
+2
-2
@@ -9,6 +9,6 @@ class InheritedError extends SemanticReleaseError {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = function(config, options, cb) {
|
||||
cb(new InheritedError('Inherited error', 'EINHERITED'));
|
||||
module.exports = () => {
|
||||
throw new InheritedError('Inherited error', 'EINHERITED');
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
module.exports = function(config, options, cb) {
|
||||
module.exports = () => {
|
||||
const error = new Error('a');
|
||||
error.errorProperty = 'errorProperty';
|
||||
cb(error);
|
||||
throw error;
|
||||
};
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
module.exports = () => {};
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
module.exports = function(config, options, cb) {
|
||||
cb(null, 'a');
|
||||
};
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
module.exports = function(config, options, cb) {
|
||||
cb(null, 'b');
|
||||
};
|
||||
+1
-3
@@ -1,3 +1 @@
|
||||
module.exports = function(pluginConfig, options, cb) {
|
||||
cb(null, {pluginConfig, options});
|
||||
};
|
||||
module.exports = (pluginConfig, options) => ({pluginConfig, options});
|
||||
|
||||
+25
-433
@@ -1,32 +1,21 @@
|
||||
import test from 'ava';
|
||||
import proxyquire from 'proxyquire';
|
||||
import {stub} from 'sinon';
|
||||
import SemanticReleaseError from '@semantic-release/error';
|
||||
import {
|
||||
gitRepo,
|
||||
gitCommits,
|
||||
gitCheckout,
|
||||
gitTagVersion,
|
||||
gitShallowClone,
|
||||
gitTags,
|
||||
gitLog,
|
||||
gitDetachedHead,
|
||||
} from './helpers/git-utils';
|
||||
import getCommits from '../lib/get-commits';
|
||||
import {gitRepo, gitCommits, gitDetachedHead} from './helpers/git-utils';
|
||||
|
||||
// Save the current working diretory
|
||||
const cwd = process.cwd();
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Save the current working diretory
|
||||
t.context.cwd = process.cwd();
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.error = stub();
|
||||
t.context.getCommits = proxyquire('../src/lib/get-commits', {
|
||||
'./logger': {log: t.context.log, error: t.context.error},
|
||||
});
|
||||
t.context.logger = {log: t.context.log, error: t.context.error};
|
||||
});
|
||||
|
||||
test.afterEach.always(t => {
|
||||
test.afterEach.always(() => {
|
||||
// Restore the current working directory
|
||||
process.chdir(t.context.cwd);
|
||||
process.chdir(cwd);
|
||||
});
|
||||
|
||||
test.serial('Get all commits when there is no last release', async t => {
|
||||
@@ -36,84 +25,11 @@ test.serial('Get all commits when there is no last release', async t => {
|
||||
const commits = await gitCommits(['First', 'Second']);
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const result = await t.context.getCommits({}, 'master');
|
||||
const result = await getCommits(undefined, 'master', t.context.logger);
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.falsy(result.lastRelease.gitHead);
|
||||
t.falsy(result.lastRelease.version);
|
||||
});
|
||||
|
||||
test.serial('Get all commits with gitTags', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second'])).concat(commits);
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const result = await t.context.getCommits({}, 'master');
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[0].gitTags, '(HEAD -> master)');
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
t.is(result.commits[1].gitTags, '(tag: v1.0.0)');
|
||||
});
|
||||
|
||||
test.serial('Get all commits when there is no last release, including the ones not in the shallow clone', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First', 'Second']);
|
||||
// Create a shallow clone with only 1 commit
|
||||
await gitShallowClone(repo);
|
||||
|
||||
// Verify the shallow clone contains only one commit
|
||||
t.is((await gitLog()).length, 1);
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const result = await t.context.getCommits({}, 'master');
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.falsy(result.lastRelease.gitHead);
|
||||
t.falsy(result.lastRelease.version);
|
||||
t.is(result.length, 2);
|
||||
t.deepEqual(result, commits);
|
||||
});
|
||||
|
||||
test.serial('Get all commits since gitHead (from lastRelease)', async t => {
|
||||
@@ -123,24 +39,11 @@ test.serial('Get all commits since gitHead (from lastRelease)', async t => {
|
||||
const commits = await gitCommits(['First', 'Second', 'Third']);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First'
|
||||
const result = await t.context.getCommits({gitHead: commits[commits.length - 1].hash}, 'master');
|
||||
const result = await getCommits(commits[commits.length - 1].hash, 'master', t.context.logger);
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead, commits[commits.length - 1].hash);
|
||||
t.falsy(result.lastRelease.version);
|
||||
t.is(result.length, 2);
|
||||
t.deepEqual(result, commits.slice(0, 2));
|
||||
});
|
||||
|
||||
test.serial('Get all commits since gitHead (from lastRelease) on a detached head repo', async t => {
|
||||
@@ -152,205 +55,15 @@ test.serial('Get all commits since gitHead (from lastRelease) on a detached head
|
||||
await gitDetachedHead(repo, commits[1].hash);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First'
|
||||
const result = await t.context.getCommits({gitHead: commits[commits.length - 1].hash}, 'master');
|
||||
const result = await getCommits(commits[commits.length - 1].hash, 'master', t.context.logger);
|
||||
|
||||
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
|
||||
t.is(result.commits.length, 1);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[0].message, commits[1].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead, commits[commits.length - 1].hash);
|
||||
t.falsy(result.lastRelease.version);
|
||||
});
|
||||
|
||||
test.serial('Get all commits since gitHead (from tag) ', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
|
||||
const result = await t.context.getCommits({version: '1.0.0'}, 'master');
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
|
||||
t.is(result.lastRelease.version, '1.0.0');
|
||||
});
|
||||
|
||||
test.serial('Get all commits since gitHead (from tag) on a detached head repo', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
|
||||
// Create a detached head repo at commit 'feat: Second'
|
||||
await gitDetachedHead(repo, commits[1].hash);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First' (associated with tag 1.0.0)
|
||||
const result = await t.context.getCommits({version: '1.0.0'}, 'master');
|
||||
|
||||
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
|
||||
t.is(result.commits.length, 1);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[0].message, commits[1].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
|
||||
t.is(result.lastRelease.version, '1.0.0');
|
||||
});
|
||||
|
||||
test.serial('Get all commits since gitHead (from tag formatted like v<version>) ', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
|
||||
const result = await t.context.getCommits({version: '1.0.0'}, 'master');
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
|
||||
t.is(result.lastRelease.version, '1.0.0');
|
||||
});
|
||||
|
||||
test.serial('Get commits when last release gitHead is missing but a tag match the version', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
|
||||
const result = await t.context.getCommits({version: '1.0.0', gitHead: 'missing'}, 'master');
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
|
||||
t.is(result.lastRelease.version, '1.0.0');
|
||||
});
|
||||
|
||||
test.serial('Get all commits since gitHead, when gitHead are mising from the shallow clone', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First', 'Second', 'Third']);
|
||||
// Create a shallow clone with only 1 commit and no tags
|
||||
await gitShallowClone(repo);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First'
|
||||
const result = await t.context.getCommits({version: '1.0.0', gitHead: commits[commits.length - 1].hash}, 'master');
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
|
||||
t.is(result.lastRelease.version, '1.0.0');
|
||||
});
|
||||
|
||||
test.serial('Get all commits since gitHead from tag, when tags are mising from the shallow clone', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
|
||||
// Create a shallow clone with only 1 commit and no tags
|
||||
await gitShallowClone(repo);
|
||||
|
||||
// Verify the shallow clone does not contains any tags
|
||||
t.is((await gitTags()).length, 0);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
|
||||
const result = await t.context.getCommits({version: '1.0.0'}, 'master');
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.commits.length, 2);
|
||||
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
|
||||
t.is(result.commits[0].message, commits[0].message);
|
||||
t.truthy(result.commits[0].committerDate);
|
||||
t.truthy(result.commits[0].author.name);
|
||||
t.truthy(result.commits[0].committer.name);
|
||||
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
|
||||
t.is(result.commits[1].message, commits[1].message);
|
||||
t.truthy(result.commits[1].committerDate);
|
||||
t.truthy(result.commits[1].author.name);
|
||||
t.truthy(result.commits[1].committer.name);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
|
||||
t.is(result.lastRelease.version, '1.0.0');
|
||||
t.is(result.length, 1);
|
||||
t.is(result[0].hash, commits[1].hash);
|
||||
t.is(result[0].message, commits[1].message);
|
||||
t.truthy(result[0].committerDate);
|
||||
t.truthy(result[0].author.name);
|
||||
t.truthy(result[0].committer.name);
|
||||
});
|
||||
|
||||
test.serial('Return empty array if lastRelease.gitHead is the last commit', async t => {
|
||||
@@ -360,14 +73,10 @@ test.serial('Return empty array if lastRelease.gitHead is the last commit', asyn
|
||||
const commits = await gitCommits(['First', 'Second']);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'Second' (therefore none)
|
||||
const result = await t.context.getCommits({gitHead: commits[0].hash, version: '1.0.0'}, 'master');
|
||||
const result = await getCommits(commits[0].hash, 'master', t.context.logger);
|
||||
|
||||
// Verify no commit is retrieved
|
||||
t.deepEqual(result.commits, []);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.is(result.lastRelease.gitHead.substring(0, 7), commits[0].hash);
|
||||
t.is(result.lastRelease.version, '1.0.0');
|
||||
t.deepEqual(result, []);
|
||||
});
|
||||
|
||||
test.serial('Return empty array if there is no commits', async t => {
|
||||
@@ -375,125 +84,8 @@ test.serial('Return empty array if there is no commits', async t => {
|
||||
await gitRepo();
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const result = await t.context.getCommits({}, 'master');
|
||||
const result = await getCommits(undefined, 'master', t.context.logger);
|
||||
|
||||
// Verify no commit is retrieved
|
||||
t.deepEqual(result.commits, []);
|
||||
// Verify the last release is returned and updated
|
||||
t.truthy(result.lastRelease);
|
||||
t.falsy(result.lastRelease.gitHead);
|
||||
t.falsy(result.lastRelease.version);
|
||||
});
|
||||
|
||||
test.serial('Throws ENOGITHEAD error if the gitHead of the last release cannot be found', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First', 'Second']);
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const error = await t.throws(t.context.getCommits({version: '1.0.0'}, 'master'));
|
||||
|
||||
// Verify error code and type
|
||||
t.is(error.code, 'ENOGITHEAD');
|
||||
t.true(error instanceof SemanticReleaseError);
|
||||
// Verify the log function has been called with a message explaining the error
|
||||
t.regex(
|
||||
t.context.error.firstCall.args[0],
|
||||
/The commit the last release of this package was derived from cannot be determined from the release metadata nor from the repository tags/
|
||||
);
|
||||
});
|
||||
|
||||
test.serial('Throws ENOTINHISTORY error if gitHead is not in history', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First', 'Second']);
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const error = await t.throws(t.context.getCommits({gitHead: 'notinhistory'}, 'master'));
|
||||
|
||||
// Verify error code and type
|
||||
t.is(error.code, 'ENOTINHISTORY');
|
||||
t.true(error instanceof SemanticReleaseError);
|
||||
// Verify the log function has been called with a message mentionning the branch
|
||||
t.regex(t.context.error.firstCall.args[0], /history of the "master" branch/);
|
||||
// Verify the log function has been called with a message mentionning the missing gitHead
|
||||
t.regex(t.context.error.firstCall.args[0], /restoring the commit "notinhistory"/);
|
||||
});
|
||||
|
||||
test.serial('Throws ENOTINHISTORY error if gitHead is not in branch history but present in others', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First', 'Second']);
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch');
|
||||
// Add commits to the 'other-branch' branch
|
||||
const commitsBranch = await gitCommits(['Third', 'Fourth']);
|
||||
await gitCheckout('master', false);
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const error = await t.throws(t.context.getCommits({version: '1.0.1', gitHead: commitsBranch[0].hash}, 'master'));
|
||||
|
||||
// Verify error code and type
|
||||
t.is(error.code, 'ENOTINHISTORY');
|
||||
t.true(error instanceof SemanticReleaseError);
|
||||
// Verify the log function has been called with a message mentionning the branch
|
||||
t.regex(t.context.error.firstCall.args[0], /history of the "master" branch/);
|
||||
// Verify the log function has been called with a message mentionning the missing gitHead
|
||||
t.regex(t.context.error.firstCall.args[0], new RegExp(`restoring the commit "${commitsBranch[0].hash}"`));
|
||||
});
|
||||
|
||||
test.serial('Throws ENOTINHISTORY error if gitHead is not in detached head but present in other branch', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo();
|
||||
// Add commit to the master branch
|
||||
await gitCommits(['First']);
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch');
|
||||
// Add commits to the 'other-branch' branch
|
||||
const commitsBranch = await gitCommits(['Second', 'Third']);
|
||||
await gitCheckout('master', false);
|
||||
// Add new commit to master branch
|
||||
const commitsMaster = await gitCommits(['Fourth']);
|
||||
// Create a detached head repo at commit 'Fourth'
|
||||
await gitDetachedHead(repo, commitsMaster[0].hash);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'Second'
|
||||
const error = await t.throws(t.context.getCommits({version: '1.0.1', gitHead: commitsBranch[0].hash}, 'master'));
|
||||
|
||||
// Verify error code and type
|
||||
t.is(error.code, 'ENOTINHISTORY');
|
||||
t.true(error instanceof SemanticReleaseError);
|
||||
// Verify the log function has been called with a message mentionning the branch
|
||||
t.regex(t.context.error.firstCall.args[0], /history of the "master" branch/);
|
||||
// Verify the log function has been called with a message mentionning the missing gitHead
|
||||
t.regex(t.context.error.firstCall.args[0], new RegExp(`restoring the commit "${commitsBranch[0].hash}"`));
|
||||
});
|
||||
|
||||
test.serial('Throws ENOTINHISTORY error when a tag is not in branch history but present in others', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First', 'Second']);
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch');
|
||||
// Add commits to the 'other-branch' branch
|
||||
await gitCommits(['Third']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
const shaTag = await gitTagVersion('v1.0.0');
|
||||
await gitCheckout('master', false);
|
||||
// Add new commit to the master branch
|
||||
await gitCommits(['Forth']);
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const error = await t.throws(t.context.getCommits({version: '1.0.0'}, 'master'));
|
||||
// Verify error code and type
|
||||
t.is(error.code, 'ENOTINHISTORY');
|
||||
t.true(error instanceof SemanticReleaseError);
|
||||
// Verify the log function has been called with a message mentionning the branch
|
||||
t.regex(t.context.error.firstCall.args[0], /history of the "master" branch/);
|
||||
// Verify the log function has been called with a message mentionning the missing gitHead
|
||||
t.regex(t.context.error.firstCall.args[0], new RegExp(`restoring the commit "${shaTag}"`));
|
||||
t.deepEqual(result, []);
|
||||
});
|
||||
|
||||
+415
-116
@@ -1,154 +1,453 @@
|
||||
import url from 'url';
|
||||
import {format} from 'util';
|
||||
import test from 'ava';
|
||||
import {writeJson, writeFile} from 'fs-extra';
|
||||
import {writeFile, outputJson} from 'fs-extra';
|
||||
import {omit} from 'lodash';
|
||||
import proxyquire from 'proxyquire';
|
||||
import {stub} from 'sinon';
|
||||
import normalizeData from 'normalize-package-data';
|
||||
import {gitRepo} from './helpers/git-utils';
|
||||
import yaml from 'js-yaml';
|
||||
import {gitRepo, gitCommits, gitShallowClone, gitAddConfig} from './helpers/git-utils';
|
||||
|
||||
// Save the current process.env
|
||||
const envBackup = Object.assign({}, process.env);
|
||||
// Save the current working diretory
|
||||
const cwd = process.cwd();
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Save the current process.env
|
||||
t.context.env = Object.assign({}, process.env);
|
||||
// Save the current working diretory
|
||||
t.context.cwd = process.cwd();
|
||||
t.context.plugins = stub().returns({});
|
||||
t.context.getConfig = proxyquire('../src/lib/get-config', {'./plugins': t.context.plugins});
|
||||
});
|
||||
|
||||
test.afterEach.always(t => {
|
||||
// Restore the current working directory
|
||||
process.chdir(t.context.cwd);
|
||||
// Restore process.env
|
||||
process.env = Object.assign({}, t.context.env);
|
||||
});
|
||||
|
||||
test.serial('Default values', async t => {
|
||||
const pkg = {name: 'package_name', release: {}};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', pkg);
|
||||
process.env.GH_TOKEN = 'GH_TOKEN';
|
||||
|
||||
const result = await t.context.getConfig();
|
||||
|
||||
// Verify the normalized package is returned
|
||||
normalizeData(pkg);
|
||||
t.deepEqual(result.pkg, pkg);
|
||||
// Verify the default options are set
|
||||
t.is(result.options.branch, 'master');
|
||||
t.is(result.options.githubToken, process.env.GH_TOKEN);
|
||||
// Verify the default npm options are set
|
||||
t.is(result.npm.tag, 'latest');
|
||||
|
||||
// Use the environment variable npm_config_registry as the default so the test works on both npm and yarn
|
||||
t.is(result.npm.registry, url.format(url.parse(process.env.npm_config_registry || 'https://registry.npmjs.org/')));
|
||||
});
|
||||
|
||||
test.serial('Read package.json configuration', async t => {
|
||||
const release = {
|
||||
analyzeCommits: 'analyzeCommits',
|
||||
generateNotes: 'generateNotes',
|
||||
getLastRelease: {
|
||||
path: 'getLastRelease',
|
||||
param: 'getLastRelease_param',
|
||||
},
|
||||
branch: 'test_branch',
|
||||
};
|
||||
const pkg = {name: 'package_name', release};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', pkg);
|
||||
// Delete environment variables that could have been set on the machine running the tests
|
||||
delete process.env.GIT_CREDENTIALS;
|
||||
delete process.env.GH_TOKEN;
|
||||
process.env.GITHUB_TOKEN = 'GITHUB_TOKEN';
|
||||
delete process.env.GITHUB_TOKEN;
|
||||
delete process.env.GL_TOKEN;
|
||||
delete process.env.GITLAB_TOKEN;
|
||||
t.context.plugins = stub().returns({});
|
||||
t.context.getConfig = proxyquire('../lib/get-config', {'./plugins': t.context.plugins});
|
||||
});
|
||||
|
||||
const result = await t.context.getConfig();
|
||||
test.afterEach.always(() => {
|
||||
// Restore process.env
|
||||
process.env = envBackup;
|
||||
// Restore the current working directory
|
||||
process.chdir(cwd);
|
||||
});
|
||||
|
||||
test.serial('Default values, reading repositoryUrl from package.json', async t => {
|
||||
const pkg = {repository: 'git@package.com:owner/module.git'};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
await gitCommits(['First']);
|
||||
// Add remote.origin.url config
|
||||
await gitAddConfig('remote.origin.url', 'git@repo.com:owner/module.git');
|
||||
// Create package.json in repository root
|
||||
await outputJson('./package.json', pkg);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(options.branch, 'master');
|
||||
t.is(options.repositoryUrl, 'git@package.com:owner/module.git');
|
||||
});
|
||||
|
||||
test.serial('Default values, reading repositoryUrl from repo if not set in package.json', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add remote.origin.url config
|
||||
await gitAddConfig('remote.origin.url', 'git@repo.com:owner/module.git');
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(options.branch, 'master');
|
||||
t.is(options.repositoryUrl, 'git@repo.com:owner/module.git');
|
||||
});
|
||||
|
||||
test.serial('Default values, reading repositoryUrl (http url) from package.json if not set in repo', async t => {
|
||||
const pkg = {repository: 'git+https://hostname.com/owner/module.git'};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await outputJson('./package.json', pkg);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(options.branch, 'master');
|
||||
t.is(options.repositoryUrl, pkg.repository);
|
||||
});
|
||||
|
||||
test.serial('Read options from package.json', async t => {
|
||||
const release = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await outputJson('./package.json', {release});
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.is(result.options.analyzeCommits, release.analyzeCommits);
|
||||
t.is(result.options.generateNotes, release.generateNotes);
|
||||
t.deepEqual(result.options.getLastRelease, release.getLastRelease);
|
||||
t.is(result.options.branch, release.branch);
|
||||
|
||||
t.deepEqual(options, release);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.is(t.context.plugins.firstCall.args[0].analyzeCommits, release.analyzeCommits);
|
||||
t.is(t.context.plugins.firstCall.args[0].generateNotes, release.generateNotes);
|
||||
t.deepEqual(t.context.plugins.firstCall.args[0].getLastRelease, release.getLastRelease);
|
||||
t.is(t.context.plugins.firstCall.args[0].branch, release.branch);
|
||||
|
||||
t.is(result.options.githubToken, process.env.GITHUB_TOKEN);
|
||||
t.deepEqual(t.context.plugins.args[0][0], release);
|
||||
});
|
||||
|
||||
test.serial('Priority cli parameters over package.json configuration', async t => {
|
||||
test.serial('Read options from .releaserc.yml', async t => {
|
||||
const release = {
|
||||
analyzeCommits: 'analyzeCommits',
|
||||
generateNotes: 'generateNotes',
|
||||
getLastRelease: {
|
||||
path: 'getLastRelease',
|
||||
param: 'getLastRelease_pkg',
|
||||
},
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await writeFile('.releaserc.yml', yaml.safeDump(release));
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(options, release);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], release);
|
||||
});
|
||||
|
||||
test.serial('Read options from .releaserc.json', async t => {
|
||||
const release = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await outputJson('.releaserc.json', release);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(options, release);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], release);
|
||||
});
|
||||
|
||||
test.serial('Read options from .releaserc.js', async t => {
|
||||
const release = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await writeFile('.releaserc.js', `module.exports = ${JSON.stringify(release)}`);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(options, release);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], release);
|
||||
});
|
||||
|
||||
test.serial('Read options from release.config.js', async t => {
|
||||
const release = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await writeFile('release.config.js', `module.exports = ${JSON.stringify(release)}`);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(options, release);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], release);
|
||||
});
|
||||
|
||||
test.serial('Prioritise CLI/API parameters over file configuration and git repo', async t => {
|
||||
const release = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_pkg'},
|
||||
branch: 'branch_pkg',
|
||||
};
|
||||
const options = {
|
||||
getLastRelease: {
|
||||
path: 'getLastRelease',
|
||||
param: 'getLastRelease_cli',
|
||||
},
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_cli'},
|
||||
branch: 'branch_cli',
|
||||
repositoryUrl: 'http://cli-url.com/owner/package',
|
||||
};
|
||||
const pkg = {name: 'package_name', release};
|
||||
|
||||
const pkg = {release, repository: 'git@hostname.com:owner/module.git'};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
const repo = await gitRepo();
|
||||
await gitCommits(['First']);
|
||||
// Create a clone
|
||||
await gitShallowClone(repo);
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', pkg);
|
||||
delete process.env.GH_TOKEN;
|
||||
process.env.GITHUB_TOKEN = 'GITHUB_TOKEN';
|
||||
await outputJson('./package.json', pkg);
|
||||
|
||||
const result = await t.context.getConfig(options);
|
||||
|
||||
// Verify the options contains the plugin config from cli
|
||||
t.deepEqual(result.options.getLastRelease, options.getLastRelease);
|
||||
t.is(result.options.branch, options.branch);
|
||||
|
||||
// Verify the plugins module is called with the plugin options from cli
|
||||
t.deepEqual(t.context.plugins.firstCall.args[0].getLastRelease, options.getLastRelease);
|
||||
t.is(t.context.plugins.firstCall.args[0].branch, options.branch);
|
||||
// Verify the options contains the plugin config from CLI/API
|
||||
t.deepEqual(result.options, options);
|
||||
// Verify the plugins module is called with the plugin options from CLI/API
|
||||
t.deepEqual(t.context.plugins.args[0][0], options);
|
||||
});
|
||||
|
||||
test.serial('Get tag from .npmrc', async t => {
|
||||
const pkg = {name: 'package_name'};
|
||||
test.serial('Read configuration from file path in "extends"', async t => {
|
||||
const release = {extends: './shareable.json'};
|
||||
const shareable = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', pkg);
|
||||
// Create local .npmrc
|
||||
await writeFile('.npmrc', 'tag=npmrc_tag');
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson('./package.json', {release});
|
||||
await outputJson('./shareable.json', shareable);
|
||||
|
||||
// Make sure to not use the environment variable set by npm when running tests with npm run test
|
||||
delete process.env.npm_config_tag;
|
||||
const result = await t.context.getConfig();
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the tag used in the one in .npmrc
|
||||
t.is(result.npm.tag, 'npmrc_tag');
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(options, shareable);
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], shareable);
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: './shareable.json',
|
||||
generateNotes: './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test.serial('Get tag from package.json, even if defined in .npmrc', async t => {
|
||||
const publishConfig = {tag: 'pkg_tag'};
|
||||
const pkg = {name: 'package_name', publishConfig};
|
||||
test.serial('Read configuration from module path in "extends"', async t => {
|
||||
const release = {extends: 'shareable'};
|
||||
const shareable = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', pkg);
|
||||
// Create local .npmrc
|
||||
await writeFile('.npmrc', 'tag=npmrc_tag');
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson('./package.json', {release});
|
||||
await outputJson('./node_modules/shareable/index.json', shareable);
|
||||
|
||||
const result = await t.context.getConfig();
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the tag used in the one in package.json
|
||||
t.is(result.npm.tag, 'pkg_tag');
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(options, shareable);
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], shareable);
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: 'shareable',
|
||||
generateNotes: 'shareable',
|
||||
});
|
||||
});
|
||||
|
||||
test.serial('Read configuration from an array of paths in "extends"', async t => {
|
||||
const release = {extends: ['./shareable1.json', './shareable2.json']};
|
||||
const shareable1 = {
|
||||
verifyRelease: 'verifyRelease1',
|
||||
analyzeCommits: {path: 'analyzeCommits1', param: 'analyzeCommits_param1'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
const shareable2 = {
|
||||
verifyRelease: 'verifyRelease2',
|
||||
generateNotes: 'generateNotes2',
|
||||
analyzeCommits: {path: 'analyzeCommits2', param: 'analyzeCommits_param2'},
|
||||
branch: 'test_branch',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson('./package.json', {release});
|
||||
await outputJson('./shareable1.json', shareable1);
|
||||
await outputJson('./shareable2.json', shareable2);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from shareable1.json and shareable2.json
|
||||
t.deepEqual(options, {...shareable1, ...shareable2});
|
||||
// Verify the plugins module is called with the plugin options from shareable1.json and shareable2.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {...shareable1, ...shareable2});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
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 => {
|
||||
const release = {
|
||||
extends: './shareable.json',
|
||||
branch: 'test_pkg',
|
||||
generateNotes: 'generateNotes',
|
||||
publish: [{path: 'publishPkg', param: 'publishPkg_param'}],
|
||||
};
|
||||
const shareable = {
|
||||
analyzeCommits: 'analyzeCommits',
|
||||
generateNotes: 'generateNotesShareable',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param'}],
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson('./package.json', {release});
|
||||
await outputJson('./shareable.json', shareable);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from package.json and shareable.json
|
||||
t.deepEqual(options, omit({...shareable, ...release}, 'extends'));
|
||||
// Verify the plugins module is called with the plugin options from package.json and shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], omit({...shareable, ...release}, 'extends'));
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: './shareable.json',
|
||||
generateNotesShareable: './shareable.json',
|
||||
publishShareable: './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test.serial('Prioritize configuration from cli/API options over "extends"', async t => {
|
||||
const opts = {
|
||||
extends: './shareable2.json',
|
||||
branch: 'branch_opts',
|
||||
publish: [{path: 'publishOpts', param: 'publishOpts_param'}],
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
const release = {
|
||||
extends: './shareable1.json',
|
||||
branch: 'branch_pkg',
|
||||
generateNotes: 'generateNotes',
|
||||
publish: [{path: 'publishPkg', param: 'publishPkg_param'}],
|
||||
};
|
||||
const shareable1 = {
|
||||
analyzeCommits: 'analyzeCommits1',
|
||||
generateNotes: 'generateNotesShareable1',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param1'}],
|
||||
branch: 'test_branch1',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
const shareable2 = {
|
||||
analyzeCommits: 'analyzeCommits2',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param2'}],
|
||||
branch: 'test_branch2',
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json, shareable1.json and shareable2.json in repository root
|
||||
await outputJson('./package.json', {release});
|
||||
await outputJson('./shareable1.json', shareable1);
|
||||
await outputJson('./shareable2.json', shareable2);
|
||||
|
||||
const {options} = await t.context.getConfig(opts);
|
||||
|
||||
// Verify the options contains the plugin config from package.json and shareable2.json
|
||||
t.deepEqual(options, omit({...shareable2, ...release, ...opts}, 'extends'));
|
||||
// Verify the plugins module is called with the plugin options from package.json and shareable2.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], omit({...shareable2, ...release, ...opts}, 'extends'));
|
||||
});
|
||||
|
||||
test.serial('Allow to unset properties defined in shareable config with "null"', async t => {
|
||||
const release = {
|
||||
extends: './shareable.json',
|
||||
analyzeCommits: null,
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
const shareable = {
|
||||
generateNotes: 'generateNotes',
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson('./package.json', {release});
|
||||
await outputJson('./shareable.json', shareable);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(options, {...omit(shareable, 'analyzeCommits'), ...omit(release, ['extends', 'analyzeCommits'])});
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {
|
||||
...omit(shareable, 'analyzeCommits'),
|
||||
...omit(release, ['extends', 'analyzeCommits']),
|
||||
});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
generateNotes: './shareable.json',
|
||||
analyzeCommits: './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test.serial('Allow to unset properties defined in shareable config with "undefined"', async t => {
|
||||
const release = {
|
||||
extends: './shareable.json',
|
||||
analyzeCommits: undefined,
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'git+https://hostname.com/owner/module.git',
|
||||
};
|
||||
const shareable = {
|
||||
generateNotes: 'generateNotes',
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json and release.config.js in repository root
|
||||
// await outputJson('./package.json', {release});
|
||||
await writeFile('release.config.js', `module.exports = ${format(release)}`);
|
||||
await outputJson('./shareable.json', shareable);
|
||||
|
||||
const {options} = await t.context.getConfig();
|
||||
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(options, {...omit(shareable, 'analyzeCommits'), ...omit(release, ['extends', 'analyzeCommits'])});
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {
|
||||
...omit(shareable, 'analyzeCommits'),
|
||||
...omit(release, ['extends', 'analyzeCommits']),
|
||||
});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
generateNotes: './shareable.json',
|
||||
analyzeCommits: './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test.serial('Throw an Error if one of the shareable config cannot be found', async t => {
|
||||
const release = {extends: ['./shareable1.json', 'non-existing-path']};
|
||||
const shareable = {analyzeCommits: 'analyzeCommits'};
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson('./package.json', {release});
|
||||
await outputJson('./shareable1.json', shareable);
|
||||
|
||||
const error = await t.throws(t.context.getConfig(), Error);
|
||||
|
||||
t.is(error.message, "Cannot find module 'non-existing-path'");
|
||||
t.is(error.code, 'MODULE_NOT_FOUND');
|
||||
});
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import test from 'ava';
|
||||
import getAuthUrl from '../lib/get-git-auth-url';
|
||||
|
||||
// Save the current process.env
|
||||
const envBackup = Object.assign({}, process.env);
|
||||
|
||||
test.beforeEach(() => {
|
||||
// Restore process.env
|
||||
process.env = {};
|
||||
});
|
||||
|
||||
test.afterEach.always(() => {
|
||||
// Restore process.env
|
||||
process.env = envBackup;
|
||||
});
|
||||
|
||||
test.serial('Return the same "repositoryUrl" is no "gitCredentials" is defined', t => {
|
||||
t.is(getAuthUrl('git@host.com:owner/repo.git'), 'git@host.com:owner/repo.git');
|
||||
});
|
||||
|
||||
test.serial('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL', t => {
|
||||
process.env.GIT_CREDENTIALS = 'user:pass';
|
||||
t.is(getAuthUrl('git@host.com:owner/repo.git'), 'https://user:pass@host.com/owner/repo.git');
|
||||
});
|
||||
|
||||
test.serial('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "https" URL', t => {
|
||||
process.env.GIT_CREDENTIALS = 'user:pass';
|
||||
t.is(getAuthUrl('https://host.com/owner/repo.git'), 'https://user:pass@host.com/owner/repo.git');
|
||||
});
|
||||
|
||||
test.serial('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "http" URL', t => {
|
||||
process.env.GIT_CREDENTIALS = 'user:pass';
|
||||
t.is(getAuthUrl('http://host.com/owner/repo.git'), 'http://user:pass@host.com/owner/repo.git');
|
||||
});
|
||||
|
||||
test.serial(
|
||||
'Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+https" URL',
|
||||
t => {
|
||||
process.env.GIT_CREDENTIALS = 'user:pass';
|
||||
t.is(getAuthUrl('git+https://host.com/owner/repo.git'), 'https://user:pass@host.com/owner/repo.git');
|
||||
}
|
||||
);
|
||||
|
||||
test.serial(
|
||||
'Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+http" URL',
|
||||
t => {
|
||||
process.env.GIT_CREDENTIALS = 'user:pass';
|
||||
t.is(getAuthUrl('git+http://host.com/owner/repo.git'), 'http://user:pass@host.com/owner/repo.git');
|
||||
}
|
||||
);
|
||||
|
||||
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "GH_TOKEN"', t => {
|
||||
process.env.GH_TOKEN = 'token';
|
||||
t.is(getAuthUrl('git@host.com:owner/repo.git'), 'https://token@host.com/owner/repo.git');
|
||||
});
|
||||
|
||||
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "GITHUB_TOKEN"', t => {
|
||||
process.env.GITHUB_TOKEN = 'token';
|
||||
t.is(getAuthUrl('git@host.com:owner/repo.git'), 'https://token@host.com/owner/repo.git');
|
||||
});
|
||||
|
||||
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "GL_TOKEN"', t => {
|
||||
process.env.GL_TOKEN = 'token';
|
||||
t.is(getAuthUrl('git@host.com:owner/repo.git'), 'https://gitlab-ci-token:token@host.com/owner/repo.git');
|
||||
});
|
||||
|
||||
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "GITLAB_TOKEN"', t => {
|
||||
process.env.GITLAB_TOKEN = 'token';
|
||||
t.is(getAuthUrl('git@host.com:owner/repo.git'), 'https://gitlab-ci-token:token@host.com/owner/repo.git');
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import getLastRelease from '../lib/get-last-release';
|
||||
import {gitRepo, gitCommits, gitTagVersion, gitCheckout} from './helpers/git-utils';
|
||||
|
||||
// Save the current working diretory
|
||||
const cwd = process.cwd();
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.logger = {log: t.context.log};
|
||||
});
|
||||
|
||||
test.afterEach.always(() => {
|
||||
// Restore the current working directory
|
||||
process.chdir(cwd);
|
||||
});
|
||||
|
||||
test.serial('Get the highest valid tag', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create some commits and tags
|
||||
await gitCommits(['First']);
|
||||
await gitTagVersion('foo');
|
||||
const commits = await gitCommits(['Second']);
|
||||
await gitTagVersion('v2.0.0');
|
||||
await gitCommits(['Third']);
|
||||
await gitTagVersion('v1.0.0');
|
||||
await gitCommits(['Fourth']);
|
||||
await gitTagVersion('v3.0');
|
||||
|
||||
const result = await getLastRelease(t.context.logger);
|
||||
|
||||
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'v2.0.0', version: '2.0.0'});
|
||||
t.deepEqual(t.context.log.args[0], ['Found git tag version %s', 'v2.0.0']);
|
||||
});
|
||||
|
||||
test.serial('Get the highest tag in the history of the current branch', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commit to the master branch
|
||||
await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch');
|
||||
// Add commit to the 'other-branch' branch
|
||||
await gitCommits(['Second']);
|
||||
// Create the tag corresponding to version 3.0.0
|
||||
await gitTagVersion('v3.0.0');
|
||||
// Checkout master
|
||||
await gitCheckout('master', false);
|
||||
// Add another commit to the master branch
|
||||
const commits = await gitCommits(['Third']);
|
||||
// Create the tag corresponding to version 2.0.0
|
||||
await gitTagVersion('v2.0.0');
|
||||
|
||||
const result = await getLastRelease(t.context.logger);
|
||||
|
||||
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'v2.0.0', version: '2.0.0'});
|
||||
});
|
||||
|
||||
test.serial('Return empty object if no valid tag is found', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Create some commits and tags
|
||||
await gitCommits(['First']);
|
||||
await gitTagVersion('foo');
|
||||
await gitCommits(['Second']);
|
||||
await gitTagVersion('v2.0.x');
|
||||
await gitCommits(['Third']);
|
||||
await gitTagVersion('v3.0');
|
||||
|
||||
const result = await getLastRelease(t.context.logger);
|
||||
|
||||
t.deepEqual(result, {});
|
||||
t.is(t.context.log.args[0][0], 'No git tag version found');
|
||||
});
|
||||
@@ -1,36 +1,29 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import proxyquire from 'proxyquire';
|
||||
import SemanticReleaseError from '@semantic-release/error';
|
||||
import getNextVersion from '../lib/get-next-version';
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.getNextVersion = proxyquire('../src/lib/get-next-version', {'./logger': {log: t.context.log}});
|
||||
t.context.logger = {log: t.context.log};
|
||||
});
|
||||
|
||||
test('Increase version for patch release', t => {
|
||||
const version = t.context.getNextVersion('patch', {version: '1.0.0'});
|
||||
const version = getNextVersion('patch', {version: '1.0.0'}, t.context.logger);
|
||||
t.is(version, '1.0.1');
|
||||
});
|
||||
|
||||
test('Increase version for minor release', t => {
|
||||
const version = t.context.getNextVersion('minor', {version: '1.0.0'});
|
||||
const version = getNextVersion('minor', {version: '1.0.0'}, t.context.logger);
|
||||
t.is(version, '1.1.0');
|
||||
});
|
||||
|
||||
test('Increase version for major release', t => {
|
||||
const version = t.context.getNextVersion('major', {version: '1.0.0'});
|
||||
const version = getNextVersion('major', {version: '1.0.0'}, t.context.logger);
|
||||
t.is(version, '2.0.0');
|
||||
});
|
||||
|
||||
test('Return 1.0.0 if there is no previous release', t => {
|
||||
const version = t.context.getNextVersion('minor', {});
|
||||
const version = getNextVersion('minor', {}, t.context.logger);
|
||||
t.is(version, '1.0.0');
|
||||
});
|
||||
|
||||
test('Return an error if the release type is invalid', t => {
|
||||
const error = t.throws(() => t.context.getNextVersion('invalid', {version: '1.0.0'}));
|
||||
t.is(error.code, 'EINVALIDTYPE');
|
||||
t.true(error instanceof SemanticReleaseError);
|
||||
});
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
const getRegistry = require('../src/lib/get-registry');
|
||||
|
||||
test('Get registry from package.json', t => {
|
||||
// Retrieve the registry with the get-registry module and verify it returns the one from the package.json in parameter
|
||||
t.is(getRegistry({name: 'publish-config', publishConfig: {registry: 'a'}}, {}), 'a');
|
||||
});
|
||||
|
||||
test('Prioritize the package.json registry config', t => {
|
||||
// Stub the npmconf object
|
||||
const get = stub();
|
||||
|
||||
// Retrieve the registry with the get-registry module and verify it returns the one from the package.json in parameter
|
||||
t.is(getRegistry({name: 'publish-config', publishConfig: {registry: 'b'}}, {get}), 'b');
|
||||
|
||||
// Verify the registry has been retrieved from the package.json without trying the stubbed npmconf
|
||||
t.true(get.notCalled);
|
||||
});
|
||||
|
||||
test('Get registry for regular package name', t => {
|
||||
// Stub the npmconf object returns 'b' for 'registry' property
|
||||
const get = stub()
|
||||
.withArgs('registry')
|
||||
.returns('b');
|
||||
|
||||
// Retrieve the registry with the get-registry module and verify it returns the one configured in the stubbed npmconf
|
||||
t.is(getRegistry({name: 'normal'}, {get}), 'b');
|
||||
|
||||
// Verify the registry has been retrieved by calling the stubbed npmconf
|
||||
t.true(get.calledWithExactly('registry'));
|
||||
});
|
||||
|
||||
test('Get default registry', t => {
|
||||
// Stub the npmconf object, returns 'null'
|
||||
const get = stub().returns(null);
|
||||
|
||||
// Retrieve the registry with the get-registry module and verify it returns default one
|
||||
t.is(getRegistry({name: 'normal'}, {get}), 'https://registry.npmjs.org/');
|
||||
|
||||
// Verify the module tried first to retrieve the registry by calling the stubbed npmconf
|
||||
t.true(get.calledWithExactly('registry'));
|
||||
});
|
||||
|
||||
test('Get registry for scoped package name', t => {
|
||||
// Stub the npmconf object, returns 'c' for '@scoped/registry' property
|
||||
const get = stub()
|
||||
.withArgs('@scoped/registry')
|
||||
.returns('c');
|
||||
|
||||
// Retrieve the registry with the get-registry module and verify it returns the one configured in the stubbed npmconf
|
||||
t.is(getRegistry({name: '@scoped/foo'}, {get}), 'c');
|
||||
|
||||
// Verify the registry for the scope '@scoped' has been retrieved by calling the stubbed npmconf
|
||||
t.true(get.calledWithExactly('@scoped/registry'));
|
||||
});
|
||||
|
||||
test('Get regular registry for scoped package name', t => {
|
||||
// Stub the npmconf object, returns 'd' for 'registry' property
|
||||
const get = stub()
|
||||
.withArgs('registry')
|
||||
.returns('d');
|
||||
|
||||
// Retrieve the registry with the get-registry module and verify it returns the regular default one for `@scoped` packages
|
||||
t.is(getRegistry({name: '@scoped/baz'}, {get}), 'd');
|
||||
|
||||
// Verify the module tried to retrieve the @scoped registry by calling the stubbed npmconf
|
||||
t.true(get.calledWithExactly('@scoped/registry'));
|
||||
});
|
||||
|
||||
test('Get default registry for scoped package name', t => {
|
||||
// Stub the npmconf object, returns 'd' for 'registry' property
|
||||
const get = stub().returns(null);
|
||||
|
||||
// Retrieve the registry with the get-registry module and verify it returns default one for `@scoped` packages
|
||||
t.is(getRegistry({name: '@scoped/baz'}, {get}), 'https://registry.npmjs.org/');
|
||||
|
||||
// Verify the module tried to retrieve the @scoped registry by calling the stubbed npmconf
|
||||
t.true(get.calledWithExactly('@scoped/registry'));
|
||||
// Verify the module tried to retrieve the regular registry by calling the stubbed npmconf
|
||||
t.true(get.calledWithExactly('registry'));
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
import test from 'ava';
|
||||
import tempy from 'tempy';
|
||||
import {
|
||||
gitTagHead,
|
||||
isRefInHistory,
|
||||
unshallow,
|
||||
gitHead,
|
||||
repoUrl,
|
||||
tag,
|
||||
push,
|
||||
gitTags,
|
||||
isGitRepo,
|
||||
deleteTag,
|
||||
} from '../lib/git';
|
||||
import {
|
||||
gitRepo,
|
||||
gitCommits,
|
||||
gitCheckout,
|
||||
gitTagVersion,
|
||||
gitShallowClone,
|
||||
gitGetCommits,
|
||||
gitAddConfig,
|
||||
gitCommitTag,
|
||||
gitRemoteTagHead,
|
||||
} from './helpers/git-utils';
|
||||
|
||||
// Save the current working diretory
|
||||
const cwd = process.cwd();
|
||||
|
||||
test.afterEach.always(() => {
|
||||
// Restore the current working directory
|
||||
process.chdir(cwd);
|
||||
});
|
||||
|
||||
test.serial('Get the last commit sha', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First']);
|
||||
|
||||
const result = await gitHead();
|
||||
|
||||
t.is(result, commits[0].hash);
|
||||
});
|
||||
|
||||
test.serial('Throw error if the last commit sha cannot be found', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
|
||||
await t.throws(gitHead(), Error);
|
||||
});
|
||||
|
||||
test.serial('Unshallow repository', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First', 'Second']);
|
||||
// Create a shallow clone with only 1 commit
|
||||
await gitShallowClone(repo);
|
||||
|
||||
// Verify the shallow clone contains only one commit
|
||||
t.is((await gitGetCommits()).length, 1);
|
||||
|
||||
await unshallow();
|
||||
|
||||
// Verify the shallow clone contains all the commits
|
||||
t.is((await gitGetCommits()).length, 2);
|
||||
});
|
||||
|
||||
test.serial('Do not throw error when unshallow a complete repository', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First']);
|
||||
await t.notThrows(unshallow());
|
||||
});
|
||||
|
||||
test.serial('Verify if the commit `sha` is in the direct history of the current branch', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First']);
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch');
|
||||
// Add commits to the 'other-branch' branch
|
||||
const otherCommits = await gitCommits(['Second']);
|
||||
await gitCheckout('master', false);
|
||||
|
||||
t.true(await isRefInHistory(commits[0].hash));
|
||||
t.false(await isRefInHistory(otherCommits[0].hash));
|
||||
});
|
||||
|
||||
test.serial('Get the commit sha for a given tag or falsy if the tag does not exists', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
|
||||
t.is(await gitTagHead('v1.0.0'), commits[0].hash);
|
||||
t.falsy(await gitTagHead('missing_tag'));
|
||||
});
|
||||
|
||||
test.serial('Return git remote repository url from config', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add remote.origin.url config
|
||||
await gitAddConfig('remote.origin.url', 'git@hostname.com:owner/package.git');
|
||||
|
||||
t.is(await repoUrl(), 'git@hostname.com:owner/package.git');
|
||||
});
|
||||
|
||||
test.serial('Return git remote repository url set while cloning', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo();
|
||||
await gitCommits(['First']);
|
||||
// Create a clone
|
||||
await gitShallowClone(repo);
|
||||
|
||||
t.is(await repoUrl(), repo);
|
||||
});
|
||||
|
||||
test.serial('Return falsy if git repository url is not set', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
|
||||
t.falsy(await repoUrl());
|
||||
});
|
||||
|
||||
test.serial('Add tag on head commit', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
const commits = await gitCommits(['Test commit']);
|
||||
|
||||
await tag('tag_name');
|
||||
|
||||
await t.is(await gitCommitTag(commits[0].hash), 'tag_name');
|
||||
});
|
||||
|
||||
test.serial('Delete a tag', async t => {
|
||||
// Create a git repository with a remote, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo(true);
|
||||
await gitCommits(['Test commit']);
|
||||
await tag('tag_name');
|
||||
await push(repo, 'master');
|
||||
|
||||
await deleteTag(repo, 'tag_name');
|
||||
t.falsy(await gitTagHead('tag_name'));
|
||||
t.falsy(await gitRemoteTagHead(repo, 'tag_name'));
|
||||
});
|
||||
|
||||
test.serial('Push tag and commit to remote repository', async t => {
|
||||
// Create a git repository with a remote, set the current working directory at the root of the repo
|
||||
const repo = await gitRepo(true);
|
||||
const commits = await gitCommits(['Test commit']);
|
||||
|
||||
await tag('tag_name');
|
||||
await push(repo, 'master');
|
||||
|
||||
t.is(await gitRemoteTagHead(repo, 'tag_name'), commits[0].hash);
|
||||
});
|
||||
|
||||
test.serial('Return "true" if in a Git repository', async t => {
|
||||
// Create a git repository with a remote, set the current working directory at the root of the repo
|
||||
await gitRepo(true);
|
||||
|
||||
t.true(await isGitRepo());
|
||||
});
|
||||
|
||||
test.serial('Return "false" if not in a Git repository', async t => {
|
||||
const dir = tempy.directory();
|
||||
process.chdir(dir);
|
||||
|
||||
t.false(await isGitRepo());
|
||||
});
|
||||
|
||||
test.serial('Throws error if obtaining the tags fails', async t => {
|
||||
const dir = tempy.directory();
|
||||
process.chdir(dir);
|
||||
|
||||
await t.throws(gitTags());
|
||||
});
|
||||
@@ -1,91 +0,0 @@
|
||||
import test from 'ava';
|
||||
import {gitRepo, gitCommits, gitHead} from './helpers/git-utils';
|
||||
import nock from 'nock';
|
||||
import {authenticate} from './helpers/mock-github';
|
||||
import githubRelease from '../src/lib/github-release';
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Save the current working diretory
|
||||
t.context.cwd = process.cwd();
|
||||
});
|
||||
|
||||
test.afterEach.always(t => {
|
||||
// Restore the current working directory
|
||||
process.chdir(t.context.cwd);
|
||||
// Reset nock
|
||||
nock.cleanAll();
|
||||
});
|
||||
|
||||
test.serial('Github release with default url', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['fix: First fix', 'feat: Second feature']);
|
||||
|
||||
const sha = await gitHead();
|
||||
const owner = 'test_user';
|
||||
const repo = 'test_repo';
|
||||
const githubToken = 'github_token';
|
||||
const notes = 'Test release note body';
|
||||
const version = '1.0.0';
|
||||
const branch = 'master';
|
||||
const tagName = `v${version}`;
|
||||
const options = {branch, githubToken};
|
||||
const pkg = {version, repository: {url: `git+https://othertesturl.com/${owner}/${repo}.git`}};
|
||||
const releaseUrl = `https://othertesturl.com/${owner}/${repo}/releases/${version}`;
|
||||
|
||||
// Mock github API for releases and git/refs endpoints
|
||||
const github = authenticate({githubToken})
|
||||
.post(`/repos/${owner}/${repo}/releases`, {
|
||||
tag_name: tagName,
|
||||
target_commitish: branch,
|
||||
name: tagName,
|
||||
body: notes,
|
||||
})
|
||||
.reply(200, {html_url: releaseUrl})
|
||||
.post(`/repos/${owner}/${repo}/git/refs`, {ref: `refs/tags/${tagName}`, sha})
|
||||
.reply({});
|
||||
|
||||
// Call the post module
|
||||
t.is(releaseUrl, await githubRelease(pkg, notes, version, options));
|
||||
// Verify the releases and git/refs endpoint have been call with expected requests
|
||||
t.true(github.isDone());
|
||||
});
|
||||
|
||||
test.serial('Github release with custom url', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['fix: First fix', 'feat: Second feature']);
|
||||
|
||||
const sha = await gitHead();
|
||||
const owner = 'test_user';
|
||||
const repo = 'test_repo';
|
||||
const githubUrl = 'https://testurl.com:443';
|
||||
const githubToken = 'github_token';
|
||||
const githubApiPathPrefix = 'prefix';
|
||||
const notes = 'Test release note body';
|
||||
const version = '1.0.0';
|
||||
const branch = 'master';
|
||||
const tagName = `v${version}`;
|
||||
const options = {branch, githubUrl, githubToken, githubApiPathPrefix};
|
||||
const pkg = {version, repository: {url: `git@othertesturl.com:${owner}/${repo}.git`}};
|
||||
const releaseUrl = `https://othertesturl.com/${owner}/${repo}/releases/${version}`;
|
||||
|
||||
// Mock github API for releases and git/refs endpoints
|
||||
const github = authenticate({githubUrl, githubToken, githubApiPathPrefix})
|
||||
.post(`/repos/${owner}/${repo}/releases`, {
|
||||
tag_name: tagName,
|
||||
target_commitish: branch,
|
||||
name: tagName,
|
||||
body: notes,
|
||||
})
|
||||
.reply(200, {html_url: releaseUrl})
|
||||
.post(`/repos/${owner}/${repo}/git/refs`, {ref: `refs/tags/${tagName}`, sha})
|
||||
.reply({});
|
||||
|
||||
// Call the post module
|
||||
t.is(releaseUrl, await githubRelease(pkg, notes, version, options));
|
||||
// Verify the releases and git/refs endpoint have been call with expected requests
|
||||
t.true(github.isDone());
|
||||
});
|
||||
+137
-64
@@ -1,67 +1,103 @@
|
||||
import {mkdir} from 'fs-extra';
|
||||
import tempy from 'tempy';
|
||||
import execa from 'execa';
|
||||
import pMapSeries from 'p-map-series';
|
||||
import fileUrl from 'file-url';
|
||||
import pReduce from 'p-reduce';
|
||||
import gitLogParser from 'git-log-parser';
|
||||
import getStream from 'get-stream';
|
||||
|
||||
/**
|
||||
* Commit message informations.
|
||||
*
|
||||
*
|
||||
* @typedef {Object} Commit
|
||||
* @property {string} branch The commit branch.
|
||||
* @property {string} hash The commit hash.
|
||||
* @property {string} message The commit message.
|
||||
* @property {String} branch The commit branch.
|
||||
* @property {String} hash The commit hash.
|
||||
* @property {String} message The commit message.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Create a temporary git repository and change the current working directory to the repository root.
|
||||
*
|
||||
* @method gitCommits
|
||||
* @param {Array<Commit>} commits the created commits.
|
||||
*
|
||||
* @return {string} The path of the repository.
|
||||
*/
|
||||
export async function gitRepo() {
|
||||
* Create a temporary git repository.
|
||||
* If `withRemote` is `true`, creates a bare repository, initialize it and create a shallow clone. Change the current working directory to the clone root.
|
||||
* If `withRemote` is `false`, creates a regular repository and initialize it. Change the current working directory to the repository root.
|
||||
*
|
||||
* @param {Boolean} withRemote `true` to create a shallow clone of a bare repository.
|
||||
* @param {String} [branc='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') {
|
||||
const dir = tempy.directory();
|
||||
|
||||
process.chdir(dir);
|
||||
await mkdir('git-templates');
|
||||
await execa('git', ['init', '--template=./git-templates']);
|
||||
await gitCheckout('master');
|
||||
return dir;
|
||||
await execa('git', ['init'].concat(withRemote ? ['--bare'] : []));
|
||||
|
||||
if (withRemote) {
|
||||
await initBareRepo(fileUrl(dir), branch);
|
||||
await gitShallowClone(fileUrl(dir));
|
||||
} else {
|
||||
await gitCheckout(branch);
|
||||
}
|
||||
return fileUrl(dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize an existing bare repository:
|
||||
* - Clone the repository
|
||||
* - Change the current working directory to the clone root
|
||||
* - Create a default branch
|
||||
* - Create an initial commits
|
||||
* - Push to origin
|
||||
*
|
||||
* @param {String} origin The URL of the bare repository.
|
||||
* @param {String} [branch='master'] the branch to initialize.
|
||||
*/
|
||||
export async function initBareRepo(origin, branch = 'master') {
|
||||
const clone = tempy.directory();
|
||||
await execa('git', ['clone', '--no-hardlinks', origin, clone]);
|
||||
process.chdir(clone);
|
||||
await gitCheckout(branch);
|
||||
await gitCommits(['Initial commit']);
|
||||
await execa('git', ['push', origin, branch]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create commits on the current git repository.
|
||||
*
|
||||
* @param {Array<string>} messages commit messages.
|
||||
*
|
||||
*
|
||||
* @returns {Array<Commit>} The created commits, in reverse order (to match `git log` order).
|
||||
*/
|
||||
export async function gitCommits(messages) {
|
||||
return (await pMapSeries(messages, async msg => {
|
||||
const {stdout} = await execa('git', ['commit', '-m', msg, '--allow-empty', '--no-gpg-sign']);
|
||||
const [, branch, hash, message] = /^\[(\w+)\(?.*?\)?(\w+)\] (.+)$/.exec(stdout);
|
||||
return {branch, hash, message};
|
||||
})).reverse();
|
||||
await pReduce(
|
||||
messages,
|
||||
async (commits, msg) => {
|
||||
const stdout = await execa.stdout('git', ['commit', '-m', msg, '--allow-empty', '--no-gpg-sign']);
|
||||
const [, hash] = /^\[(?:\w+)\(?.*?\)?(\w+)\] .+(?:\n|$)/.exec(stdout);
|
||||
commits.push(hash);
|
||||
return commits;
|
||||
},
|
||||
[]
|
||||
);
|
||||
return (await gitGetCommits()).slice(0, messages.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Amend a commit (rewriting the sha) on the current git repository.
|
||||
* Get the list of parsed commits since a git reference.
|
||||
*
|
||||
* @param {string} messages commit message.
|
||||
*
|
||||
* @returns {Array<Commit>} the created commits.
|
||||
* @param {String} [from] Git reference from which to seach commits.
|
||||
* @return {Array<Object>} The list of parsed commits.
|
||||
*/
|
||||
export async function gitAmmendCommit(msg) {
|
||||
const {stdout} = await execa('git', ['commit', '--amend', '-m', msg, '--allow-empty']);
|
||||
const [, branch, hash, message] = /^\[(\w+)\(?.*?\)?(\w+)\] (.+)(.|\s)+$/.exec(stdout);
|
||||
return {branch, hash, message};
|
||||
export async function gitGetCommits(from) {
|
||||
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
|
||||
return (await getStream.array(gitLogParser.parse({_: `${from ? from + '..' : ''}HEAD`}))).map(commit => {
|
||||
commit.message = commit.message.trim();
|
||||
commit.gitTags = commit.gitTags.trim();
|
||||
return commit;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Checkout a branch on the current git repository.
|
||||
*
|
||||
* @param {string} branch Branch name.
|
||||
* @param {String} branch Branch name.
|
||||
* @param {boolean} create `true` to create the branche ans switch, `false` to only switch.
|
||||
*/
|
||||
export async function gitCheckout(branch, create = true) {
|
||||
@@ -69,61 +105,48 @@ export async function gitCheckout(branch, create = true) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {string} The sha of the head commit in the current git repository.
|
||||
* @return {String} The sha of the head commit in the current git repository.
|
||||
*/
|
||||
export async function gitHead() {
|
||||
return (await execa('git', ['rev-parse', 'HEAD'])).stdout;
|
||||
return execa.stdout('git', ['rev-parse', 'HEAD']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a tag on the head commit in the current git repository.
|
||||
*
|
||||
* @param {string} tagName The tag name to create.
|
||||
* @param {string} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit.
|
||||
*
|
||||
* @return {string} The commit sha of the created tag.
|
||||
* @param {String} tagName The tag name to create.
|
||||
* @param {String} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit.
|
||||
*/
|
||||
export async function gitTagVersion(tagName, sha) {
|
||||
await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName]);
|
||||
return (await execa('git', ['rev-list', '-1', '--tags', tagName])).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {Array<string>} The list of tags from the current git repository.
|
||||
*/
|
||||
export async function gitTags() {
|
||||
return (await execa('git', ['tag'])).stdout.split('\n').filter(tag => !!tag);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {Array<string>} The list of commit sha from the current git repository.
|
||||
*/
|
||||
export async function gitLog() {
|
||||
return (await execa('git', ['log', '--format=format:%H'])).stdout.split('\n').filter(sha => !!sha);
|
||||
export async function gitRemoteTagVersion(origin, tagName, sha = 'HEAD') {
|
||||
await execa('git', ['push', origin, `${sha}:refs/tags/${tagName}`]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a shallow clone of a git repository and change the current working directory to the cloned repository root.
|
||||
* The shallow will contain a limited number of commit and no tags.
|
||||
*
|
||||
* @param {string} origin The path of the repository to clone.
|
||||
* @param {number} [depth=1] The number of commit to clone.
|
||||
* @return {string} The path of the cloned repository.
|
||||
*
|
||||
* @param {String} origin The path of the repository to clone.
|
||||
* @param {Number} [depth=1] The number of commit to clone.
|
||||
* @return {String} The path of the cloned repository.
|
||||
*/
|
||||
export async function gitShallowClone(origin, branch = 'master', depth = 1) {
|
||||
const dir = tempy.directory();
|
||||
|
||||
process.chdir(dir);
|
||||
await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, `file://${origin}`, dir]);
|
||||
await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, origin, dir]);
|
||||
return dir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a git repo with a detached head from another git repository and change the current working directory to the new repository root.
|
||||
*
|
||||
* @param {string} origin The path of the repository to clone.
|
||||
* @param {number} head A commit sha of the origin repo that will become the detached head of the new one.
|
||||
* @return {string} The path of the new repository.
|
||||
*
|
||||
* @param {String} origin The path of the repository to clone.
|
||||
* @param {Number} head A commit sha of the origin repo that will become the detached head of the new one.
|
||||
* @return {String} The path of the new repository.
|
||||
*/
|
||||
export async function gitDetachedHead(origin, head) {
|
||||
const dir = tempy.directory();
|
||||
@@ -137,8 +160,58 @@ export async function gitDetachedHead(origin, head) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Pack heads and tags of the current git repository.
|
||||
* Add a new Git configuration.
|
||||
*
|
||||
* @param {String} name Config name.
|
||||
* @param {String} value Config value.
|
||||
*/
|
||||
export async function gitPackRefs() {
|
||||
await execa('git', ['pack-refs', '--all']);
|
||||
export async function gitAddConfig(name, value) {
|
||||
await execa('git', ['config', '--add', name, value]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first commit sha referenced by the tag `tagName` in the local repository.
|
||||
*
|
||||
* @param {String} tagName Tag name for which to retrieve the commit sha.
|
||||
*
|
||||
* @return {String} The sha of the commit associated with `tagName` on the local repository.
|
||||
*/
|
||||
export async function gitTagHead(tagName) {
|
||||
return execa.stdout('git', ['rev-list', '-1', tagName]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first commit sha referenced by the tag `tagName` in the remote repository.
|
||||
*
|
||||
* @param {String} origin The repository remote URL.
|
||||
* @param {String} tagName The tag name to seach for.
|
||||
* @return {String} The sha of the commit associated with `tagName` on the remote repository.
|
||||
*/
|
||||
export async function gitRemoteTagHead(origin, tagName) {
|
||||
return (await execa.stdout('git', ['ls-remote', '--tags', origin, tagName]))
|
||||
.split('\n')
|
||||
.filter(tag => Boolean(tag))
|
||||
.map(tag => tag.match(/^(\S+)/)[1])[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the tag associated with a commit sha.
|
||||
*
|
||||
* @param {String} gitHead The commit sha for which to retrieve the associated tag.
|
||||
*
|
||||
* @return {String} The tag associatedwith the sha in parameter or `null`.
|
||||
*/
|
||||
export async function gitCommitTag(gitHead) {
|
||||
return execa.stdout('git', ['describe', '--tags', '--exact-match', gitHead]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push to the remote repository.
|
||||
*
|
||||
* @param {String} origin The remote repository URL.
|
||||
* @param {String} branch The branch to push.
|
||||
* @throws {Error} if the push failed.
|
||||
*/
|
||||
export async function push(origin, branch) {
|
||||
await execa('git', ['push', '--tags', origin, `HEAD:${branch}`]);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import Docker from 'dockerode';
|
||||
import getStream from 'get-stream';
|
||||
import pRetry from 'p-retry';
|
||||
import {initBareRepo, gitShallowClone} from './git-utils';
|
||||
|
||||
const IMAGE = 'pvdlg/docker-gitbox';
|
||||
const SERVER_PORT = 80;
|
||||
const HOST_PORT = 2080;
|
||||
const SERVER_HOST = 'localhost';
|
||||
const GIT_USERNAME = 'integration';
|
||||
const GIT_PASSWORD = 'suchsecure';
|
||||
const docker = new Docker();
|
||||
let container;
|
||||
|
||||
const gitCredential = `${GIT_USERNAME}:${GIT_PASSWORD}`;
|
||||
|
||||
/**
|
||||
* Download the `gitbox` Docker image, create a new container and start it.
|
||||
*
|
||||
* @return {Promise} Promise that resolves when the container is started.
|
||||
*/
|
||||
async function start() {
|
||||
await getStream(await docker.pull(IMAGE));
|
||||
|
||||
container = await docker.createContainer({
|
||||
Tty: true,
|
||||
Image: IMAGE,
|
||||
PortBindings: {[`${SERVER_PORT}/tcp`]: [{HostPort: `${HOST_PORT}`}]},
|
||||
});
|
||||
await container.start();
|
||||
|
||||
const exec = await container.exec({
|
||||
Cmd: ['ng-auth', '-u', GIT_USERNAME, '-p', GIT_PASSWORD],
|
||||
AttachStdout: true,
|
||||
AttachStderr: true,
|
||||
});
|
||||
await exec.start();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop and remote the `mockserver` Docker container.
|
||||
*
|
||||
* @return {Promise} Promise that resolves when the container is stopped.
|
||||
*/
|
||||
async function stop() {
|
||||
await container.stop();
|
||||
await container.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize a remote repository and creates a shallow clone.
|
||||
*
|
||||
* @param {String} name The remote repository name.
|
||||
* @param {String} [branch='master'] The branch to initialize.
|
||||
* @param {String} [description=`Repository ${name}`] The repository description.
|
||||
* @return {Object} The `repositoryUrl` (URL without auth) and `authUrl` (URL with auth).
|
||||
*/
|
||||
async function createRepo(name, branch = 'master', description = `Repository ${name}`) {
|
||||
const exec = await container.exec({
|
||||
Cmd: ['repo-admin', '-n', name, '-d', description],
|
||||
AttachStdout: true,
|
||||
AttachStderr: true,
|
||||
});
|
||||
await exec.start();
|
||||
|
||||
const repositoryUrl = `http://${SERVER_HOST}:${HOST_PORT}/git/${name}.git`;
|
||||
const authUrl = `http://${gitCredential}@${SERVER_HOST}:${HOST_PORT}/git/${name}.git`;
|
||||
|
||||
// Retry as the server might take a few ms to make the repo available push
|
||||
await pRetry(() => initBareRepo(authUrl, branch), {retries: 3, minTimeout: 500, factor: 2});
|
||||
await gitShallowClone(authUrl);
|
||||
return {repositoryUrl, authUrl};
|
||||
}
|
||||
|
||||
export default {start, stop, gitCredential, createRepo};
|
||||
@@ -2,13 +2,15 @@ import nock from 'nock';
|
||||
|
||||
/**
|
||||
* Retun a `nock` object setup to respond to a github authentication request. Other expectation and responses can be chained.
|
||||
*
|
||||
*
|
||||
* @param {String} [githubToken='GH_TOKEN'] The github token to return in the authentication response.
|
||||
* @param {String} [githubUrl='https://api.github.com'] The url on which to intercept http requests.
|
||||
* @return {Object} A `nock` object ready to respond to a github authentication request.
|
||||
*/
|
||||
export function authenticate(
|
||||
{githubToken = 'GH_TOKEN', githubUrl = 'https://api.github.com', githubApiPathPrefix = ''} = {}
|
||||
) {
|
||||
export default function authenticate({
|
||||
githubToken = 'GH_TOKEN',
|
||||
githubUrl = 'https://api.github.com',
|
||||
githubApiPathPrefix = '',
|
||||
} = {}) {
|
||||
return nock(`${githubUrl}/${githubApiPathPrefix}`, {reqheaders: {Authorization: `token ${githubToken}`}});
|
||||
}
|
||||
|
||||
+28
-10
@@ -1,7 +1,10 @@
|
||||
import Docker from 'dockerode';
|
||||
import getStream from 'get-stream';
|
||||
import got from 'got';
|
||||
import pRetry from 'p-retry';
|
||||
import {mockServerClient} from 'mockserver-client';
|
||||
|
||||
const IMAGE = 'jamesdbloom/mockserver:latest';
|
||||
const MOCK_SERVER_PORT = 1080;
|
||||
const MOCK_SERVER_HOST = 'localhost';
|
||||
const docker = new Docker();
|
||||
@@ -13,22 +16,35 @@ let container;
|
||||
* @return {Promise} Promise that resolves when the container is started.
|
||||
*/
|
||||
async function start() {
|
||||
await getStream(await docker.pull('jamesdbloom/mockserver:latest'));
|
||||
await getStream(await docker.pull(IMAGE));
|
||||
|
||||
container = await docker.createContainer({
|
||||
Image: 'jamesdbloom/mockserver',
|
||||
Tty: true,
|
||||
Image: IMAGE,
|
||||
PortBindings: {[`${MOCK_SERVER_PORT}/tcp`]: [{HostPort: `${MOCK_SERVER_PORT}`}]},
|
||||
});
|
||||
return container.start();
|
||||
await container.start();
|
||||
|
||||
try {
|
||||
// Wait for the mock server to be ready
|
||||
await pRetry(() => got.put(`http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}/status`, {cache: false}), {
|
||||
retries: 7,
|
||||
minTimeout: 1000,
|
||||
factor: 2,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new Error(`Couldn't start mock-server after 2 min`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop the `mockserver` Docker container.
|
||||
* Stop and remote the `mockserver` Docker container.
|
||||
*
|
||||
* @return {Promise} Promise that resolves when the container is stopped.
|
||||
*/
|
||||
async function stop() {
|
||||
return container.stop();
|
||||
await container.stop();
|
||||
await container.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -47,19 +63,19 @@ const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`;
|
||||
* @param {Object} request Request expectation. The http request made on `path` has to match those criteria in order to be valid.
|
||||
* @param {Object} request.body The JSON body the expected request must match.
|
||||
* @param {Object} request.headers The headers the expected request must match.
|
||||
* @param {Object} response The http response to return when receiving a request on `path`.
|
||||
* @param {Object} response The http response to return when receiving a request on `path`.
|
||||
* @param {String} [response.method='POST'] The http method for which to respond.
|
||||
* @param {number} [response.statusCode=200] The status code to respond.
|
||||
* @param {Object} response.body The JSON object to respond in the response body.
|
||||
* @return {Object} An object representation the expectation. Pass to the `verify` function to validate the `mockserver` has been called with a `request` matching the expectations.
|
||||
*/
|
||||
function mock(
|
||||
async function mock(
|
||||
path,
|
||||
{body: requestBody, headers: requestHeaders},
|
||||
{method = 'POST', statusCode = 200, body: responseBody}
|
||||
) {
|
||||
client.mockAnyResponse({
|
||||
httpRequest: {path},
|
||||
await client.mockAnyResponse({
|
||||
httpRequest: {path, method},
|
||||
httpResponse: {
|
||||
statusCode,
|
||||
headers: [{name: 'Content-Type', values: ['application/json; charset=utf-8']}],
|
||||
@@ -72,7 +88,9 @@ function mock(
|
||||
method,
|
||||
path,
|
||||
headers: requestHeaders,
|
||||
body: {type: 'JSON', json: JSON.stringify(requestBody), matchType: 'ONLY_MATCHING_FIELDS'},
|
||||
body: requestBody
|
||||
? {type: 'JSON', json: JSON.stringify(requestBody), matchType: 'ONLY_MATCHING_FIELDS'}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import Docker from 'dockerode';
|
||||
import getStream from 'get-stream';
|
||||
import got from 'got';
|
||||
import delay from 'delay';
|
||||
import pRetry from 'p-retry';
|
||||
|
||||
const IMAGE = 'npmjs/npm-docker-couchdb:1.6.1';
|
||||
const SERVER_PORT = 15986;
|
||||
const COUCHDB_PORT = 5984;
|
||||
const SERVER_HOST = 'localhost';
|
||||
const NPM_USERNAME = 'integration';
|
||||
const NPM_PASSWORD = 'suchsecure';
|
||||
const NPM_EMAIL = 'integration@test.com';
|
||||
const docker = new Docker();
|
||||
let container;
|
||||
|
||||
/**
|
||||
* Download the `npm-docker-couchdb` Docker image, create a new container and start it.
|
||||
*
|
||||
* @return {Promise} Promise that resolves when the container is started.
|
||||
*/
|
||||
async function start() {
|
||||
await getStream(await docker.pull(IMAGE));
|
||||
|
||||
container = await docker.createContainer({
|
||||
Tty: true,
|
||||
Image: IMAGE,
|
||||
PortBindings: {[`${COUCHDB_PORT}/tcp`]: [{HostPort: `${SERVER_PORT}`}]},
|
||||
});
|
||||
|
||||
await container.start();
|
||||
await delay(3000);
|
||||
|
||||
try {
|
||||
// Wait for the registry to be ready
|
||||
await pRetry(() => got(`http://${SERVER_HOST}:${SERVER_PORT}/registry/_design/app`, {cache: false}), {
|
||||
retries: 7,
|
||||
minTimeout: 1000,
|
||||
factor: 2,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new Error(`Couldn't start npm-docker-couchdb after 2 min`);
|
||||
}
|
||||
|
||||
// Create user
|
||||
await got(`http://${SERVER_HOST}:${SERVER_PORT}/_users/org.couchdb.user:${NPM_USERNAME}`, {
|
||||
json: true,
|
||||
auth: 'admin:admin',
|
||||
method: 'PUT',
|
||||
body: {
|
||||
_id: `org.couchdb.user:${NPM_USERNAME}`,
|
||||
name: NPM_USERNAME,
|
||||
roles: [],
|
||||
type: 'user',
|
||||
password: NPM_PASSWORD,
|
||||
email: NPM_EMAIL,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const url = `http://${SERVER_HOST}:${SERVER_PORT}/registry/_design/app/_rewrite/`;
|
||||
|
||||
const authEnv = {
|
||||
npm_config_registry: url, // eslint-disable-line camelcase
|
||||
NPM_USERNAME,
|
||||
NPM_PASSWORD,
|
||||
NPM_EMAIL,
|
||||
};
|
||||
|
||||
/**
|
||||
* Stop and remote the `npm-docker-couchdb` Docker container.
|
||||
*
|
||||
* @return {Promise} Promise that resolves when the container is stopped.
|
||||
*/
|
||||
async function stop() {
|
||||
await container.stop();
|
||||
await container.remove();
|
||||
}
|
||||
|
||||
export default {start, stop, authEnv, url};
|
||||
@@ -1,14 +0,0 @@
|
||||
import execa from 'execa';
|
||||
|
||||
const opts = {cwd: __dirname};
|
||||
const uri = 'http://localhost:' + (process.env.TRAVIS === 'true' ? 5984 : 15986) + '/registry/_design/app/_rewrite/';
|
||||
|
||||
function start() {
|
||||
return execa('./start.sh', opts);
|
||||
}
|
||||
|
||||
function stop() {
|
||||
return execa('./stop.sh', opts);
|
||||
}
|
||||
|
||||
export default {start, stop, uri};
|
||||
@@ -1,20 +0,0 @@
|
||||
[couchdb]
|
||||
database_dir = data
|
||||
view_index_dir = data
|
||||
delayed_commits = false
|
||||
uuid = bf4ecd84a7c89d60b5b2540fdf8c322c
|
||||
|
||||
[couch_httpd_auth]
|
||||
public_fields = appdotnet, avatar, avatarMedium, avatarLarge, date, email, fields, freenode, fullname, github, homepage, name, roles, twitter, type, _id, _rev
|
||||
users_db_public = true
|
||||
|
||||
[httpd]
|
||||
port = 15986
|
||||
bind_address = 127.0.0.1
|
||||
secure_rewrites = false
|
||||
|
||||
[log]
|
||||
file = couch/couch.log
|
||||
|
||||
[admins]
|
||||
admin = -pbkdf2-89582b49cd2e8443e29a841f5a76d367956a8e58,1afa2f1531a17ac97f2ac9e334293753,10
|
||||
@@ -1,41 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# exit if an error occurs
|
||||
set -e
|
||||
|
||||
cd $(dirname $0)
|
||||
|
||||
mkdir -p couch
|
||||
|
||||
if [[ $TRAVIS = true ]]
|
||||
then
|
||||
COUCH=http://admin:password@127.0.0.1:5984
|
||||
|
||||
curl -X PUT http://127.0.0.1:5984/_config/admins/admin -d '"password"'
|
||||
|
||||
curl -X PUT $COUCH/_config/couchdb/delayed_commits -d '"false"'
|
||||
curl -X PUT $COUCH/_config/couch_httpd_auth/users_db_public -d '"true"'
|
||||
curl -X PUT $COUCH/_config/couch_httpd_auth/public_fields -d '"appdotnet, avatar, avatarMedium, avatarLarge, date, email, fields, freenode, fullname, github, homepage, name, roles, twitter, type, _id, _rev"'
|
||||
curl -X PUT $COUCH/_config/httpd/secure_rewrites -d '"false"'
|
||||
|
||||
else
|
||||
COUCH=http://admin:password@127.0.0.1:15986
|
||||
couchdb -b -a local.ini -p couch/pid -o couch/stdout.log -e couch/stderr.log
|
||||
# wait for couch to start
|
||||
sleep 1
|
||||
fi
|
||||
|
||||
# create "registry" database
|
||||
curl -X PUT $COUCH/registry
|
||||
|
||||
# create sample npm user
|
||||
curl -X PUT $COUCH/_users/org.couchdb.user:integration -H Content-Type:application/json --data-binary '{"_id": "org.couchdb.user:integration", "name": "integration", "roles": [], "type": "user", "password": "suchsecure", "email": "integration@test.com"}'
|
||||
|
||||
# npm-registry-couchpp needs this variable set to run
|
||||
export DEPLOY_VERSION=nope
|
||||
|
||||
# setup npm-registry-couchapp
|
||||
npm explore npm-registry-couchapp -- npm start --npm-registry-couchapp:couch=$COUCH/registry
|
||||
npm explore npm-registry-couchapp -- npm run load --npm-registry-couchapp:couch=$COUCH/registry
|
||||
export NO_PROMPT=yes
|
||||
npm explore npm-registry-couchapp -- npm run copy --npm-registry-couchapp:couch=$COUCH/registry
|
||||
@@ -1,13 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# close couchdb background process
|
||||
couchdb -d
|
||||
|
||||
# delete data and logs
|
||||
cd $(dirname $0)
|
||||
|
||||
cat couch/{couch,stdout,stderr}.log
|
||||
|
||||
cat couch/pid | xargs kill
|
||||
rm -rf couch
|
||||
rm -rf data
|
||||
@@ -0,0 +1,42 @@
|
||||
import test from 'ava';
|
||||
import clearModule from 'clear-module';
|
||||
|
||||
test.beforeEach(() => {
|
||||
process.env = {};
|
||||
clearModule('../lib/hide-sensitive');
|
||||
});
|
||||
|
||||
test.serial('Replace multiple sensitive environment variable values', t => {
|
||||
process.env.SOME_PASSWORD = 'password';
|
||||
process.env.SOME_TOKEN = 'secret';
|
||||
t.is(
|
||||
require('../lib/hide-sensitive')(
|
||||
`https://user:${process.env.SOME_PASSWORD}@host.com?token=${process.env.SOME_TOKEN}`
|
||||
),
|
||||
'https://user:[secure]@host.com?token=[secure]'
|
||||
);
|
||||
});
|
||||
|
||||
test.serial('Replace multiple occurences of sensitive environment variable values', t => {
|
||||
process.env.secretKey = 'secret';
|
||||
t.is(
|
||||
require('../lib/hide-sensitive')(`https://user:${process.env.secretKey}@host.com?token=${process.env.secretKey}`),
|
||||
'https://user:[secure]@host.com?token=[secure]'
|
||||
);
|
||||
});
|
||||
|
||||
test.serial('Escape regexp special characters', t => {
|
||||
process.env.SOME_CREDENTIALS = 'p$^{.+}\\w[a-z]o.*rd';
|
||||
t.is(
|
||||
require('../lib/hide-sensitive')(`https://user:${process.env.SOME_CREDENTIALS}@host.com`),
|
||||
'https://user:[secure]@host.com'
|
||||
);
|
||||
});
|
||||
|
||||
test.serial('Accept "undefined" input', t => {
|
||||
t.is(require('../lib/hide-sensitive')(), undefined);
|
||||
});
|
||||
|
||||
test.serial('Return same string if no environment variable has to be replaced', t => {
|
||||
t.is(require('../lib/hide-sensitive')('test'), 'test');
|
||||
});
|
||||
+632
-235
@@ -1,278 +1,675 @@
|
||||
import test from 'ava';
|
||||
import proxyquire from 'proxyquire';
|
||||
import {stub} from 'sinon';
|
||||
import tempy from 'tempy';
|
||||
import clearModule from 'clear-module';
|
||||
import SemanticReleaseError from '@semantic-release/error';
|
||||
import DEFINITIONS from '../lib/plugins/definitions';
|
||||
import {
|
||||
gitHead as getGitHead,
|
||||
gitTagHead,
|
||||
gitRepo,
|
||||
gitCommits,
|
||||
gitTagVersion,
|
||||
gitRemoteTagHead,
|
||||
push,
|
||||
gitShallowClone,
|
||||
} from './helpers/git-utils';
|
||||
|
||||
const consoleLog = stub(console, 'log');
|
||||
// Save the current process.env
|
||||
const envBackup = Object.assign({}, process.env);
|
||||
// Save the current working diretory
|
||||
const cwd = process.cwd();
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Save the current process.env
|
||||
t.context.env = Object.assign({}, process.env);
|
||||
// Save the current working diretory
|
||||
t.context.cwd = process.cwd();
|
||||
clearModule('../lib/hide-sensitive');
|
||||
|
||||
// Delete environment variables that could have been set on the machine running the tests
|
||||
delete process.env.GIT_CREDENTIALS;
|
||||
delete process.env.GH_TOKEN;
|
||||
delete process.env.GITHUB_TOKEN;
|
||||
delete process.env.GL_TOKEN;
|
||||
delete process.env.GITLAB_TOKEN;
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.error = stub();
|
||||
t.context.logger = {log: t.context.log, error: t.context.error};
|
||||
t.context.stdout = stub(process.stdout, 'write');
|
||||
t.context.stderr = stub(process.stderr, 'write');
|
||||
});
|
||||
|
||||
test.afterEach.always(t => {
|
||||
// Restore the current working directory
|
||||
process.chdir(t.context.cwd);
|
||||
// Restore process.env
|
||||
process.env = Object.assign({}, t.context.env);
|
||||
process.env = envBackup;
|
||||
// Restore the current working directory
|
||||
process.chdir(cwd);
|
||||
|
||||
t.context.stdout.restore();
|
||||
t.context.stderr.restore();
|
||||
});
|
||||
|
||||
test.after.always(t => {
|
||||
consoleLog.restore();
|
||||
});
|
||||
test.serial('Plugins are called with expected values', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second'])).concat(commits);
|
||||
|
||||
test('Plugins are called with expected values', async t => {
|
||||
const env = {NPM_TOKEN: 'NPM_TOKEN'};
|
||||
const pkgOptions = {branch: 'master'};
|
||||
const cliOptions = {githubToken: 'GH_TOKEN'};
|
||||
const options = Object.assign({}, pkgOptions, cliOptions);
|
||||
const pkg = {name: 'available', release: options, repository: {url: 'http://github.com/whats/up.git'}};
|
||||
const npm = {registry: 'http://test.registry.com'};
|
||||
const lastRelease = {version: '1.0.0', gitHead: 'test_commit_head'};
|
||||
const commitsLastRelease = {version: '1.0.0', gitHead: 'tag_head'};
|
||||
const commits = [{hash: '1', message: 'fix: First fix'}, {hash: '2', message: 'feat: First feature'}];
|
||||
const nextRelease = {type: 'major', version: '2.0.0'};
|
||||
const lastRelease = {version: '1.0.0', gitHead: commits[commits.length - 1].hash, gitTag: 'v1.0.0'};
|
||||
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
|
||||
const notes = 'Release notes';
|
||||
|
||||
// Stub modules
|
||||
const log = stub();
|
||||
const error = stub();
|
||||
const logger = {log, error};
|
||||
const verifyAuth = stub().returns();
|
||||
const publishNpm = stub().resolves();
|
||||
const githubRelease = stub().resolves();
|
||||
const getCommits = stub().resolves({commits, lastRelease: commitsLastRelease});
|
||||
const getNextVersion = stub().returns(nextRelease.version);
|
||||
// Stub plugins
|
||||
const verifyConditions = stub().resolves();
|
||||
const getLastRelease = stub().resolves(lastRelease);
|
||||
const verifyConditions1 = stub().resolves();
|
||||
const verifyConditions2 = stub().resolves();
|
||||
const analyzeCommits = stub().resolves(nextRelease.type);
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves(notes);
|
||||
const getConfig = stub().resolves({
|
||||
plugins: {getLastRelease, analyzeCommits, verifyRelease, verifyConditions, generateNotes},
|
||||
env,
|
||||
options,
|
||||
pkg,
|
||||
npm,
|
||||
const publish = stub().resolves();
|
||||
|
||||
const config = {branch: 'master', repositoryUrl, globalOpt: 'global'};
|
||||
const options = {
|
||||
...config,
|
||||
verifyConditions: [verifyConditions1, verifyConditions2],
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
t.truthy(await semanticRelease(options));
|
||||
|
||||
const semanticRelease = proxyquire('../src/index', {
|
||||
'./lib/logger': logger,
|
||||
'./lib/verify-auth': verifyAuth,
|
||||
'./lib/get-config': getConfig,
|
||||
'./lib/get-commits': getCommits,
|
||||
'./lib/publish-npm': publishNpm,
|
||||
'./lib/github-release': githubRelease,
|
||||
'./lib/get-next-version': getNextVersion,
|
||||
});
|
||||
t.is(verifyConditions1.callCount, 1);
|
||||
t.deepEqual(verifyConditions1.args[0][0], config);
|
||||
t.deepEqual(verifyConditions1.args[0][1], {options, logger: t.context.logger});
|
||||
t.is(verifyConditions2.callCount, 1);
|
||||
t.deepEqual(verifyConditions2.args[0][1], {options, logger: t.context.logger});
|
||||
|
||||
// Call the index module
|
||||
await semanticRelease(cliOptions);
|
||||
t.is(analyzeCommits.callCount, 1);
|
||||
t.deepEqual(analyzeCommits.args[0][0], config);
|
||||
t.deepEqual(analyzeCommits.args[0][1].options, options);
|
||||
t.deepEqual(analyzeCommits.args[0][1].logger, t.context.logger);
|
||||
t.deepEqual(analyzeCommits.args[0][1].lastRelease, lastRelease);
|
||||
t.deepEqual(analyzeCommits.args[0][1].commits[0].hash, commits[0].hash);
|
||||
t.deepEqual(analyzeCommits.args[0][1].commits[0].message, commits[0].message);
|
||||
|
||||
// Verify the sub-modules have been called with expected parameters
|
||||
t.true(getConfig.calledOnce);
|
||||
t.true(getConfig.calledWithExactly(cliOptions));
|
||||
t.true(verifyAuth.calledOnce);
|
||||
t.true(verifyAuth.calledWithExactly(options, env));
|
||||
t.true(publishNpm.calledOnce);
|
||||
t.true(publishNpm.calledWithExactly(pkg, npm, nextRelease));
|
||||
t.true(githubRelease.calledOnce);
|
||||
t.true(githubRelease.calledWithExactly(pkg, notes, nextRelease.version, options));
|
||||
// Verify plugins have been called with expected parameters
|
||||
t.true(verifyConditions.calledOnce);
|
||||
t.true(verifyConditions.calledWithExactly({env, options, pkg, npm, logger}));
|
||||
t.true(getLastRelease.calledOnce);
|
||||
t.true(getLastRelease.calledWithExactly({env, options, pkg, npm, logger}));
|
||||
t.true(analyzeCommits.calledOnce);
|
||||
t.true(analyzeCommits.calledWithExactly({env, options, pkg, npm, logger, lastRelease: commitsLastRelease, commits}));
|
||||
t.true(verifyRelease.calledOnce);
|
||||
t.true(
|
||||
verifyRelease.calledWithExactly({
|
||||
env,
|
||||
options,
|
||||
pkg,
|
||||
npm,
|
||||
logger,
|
||||
lastRelease: commitsLastRelease,
|
||||
commits,
|
||||
nextRelease,
|
||||
})
|
||||
);
|
||||
t.true(generateNotes.calledOnce);
|
||||
t.true(
|
||||
generateNotes.calledWithExactly({
|
||||
env,
|
||||
options,
|
||||
pkg,
|
||||
npm,
|
||||
logger,
|
||||
lastRelease: commitsLastRelease,
|
||||
commits,
|
||||
nextRelease,
|
||||
})
|
||||
);
|
||||
t.is(verifyRelease.callCount, 1);
|
||||
t.deepEqual(verifyRelease.args[0][0], config);
|
||||
t.deepEqual(verifyRelease.args[0][1].options, options);
|
||||
t.deepEqual(verifyRelease.args[0][1].logger, t.context.logger);
|
||||
t.deepEqual(verifyRelease.args[0][1].lastRelease, lastRelease);
|
||||
t.deepEqual(verifyRelease.args[0][1].commits[0].hash, commits[0].hash);
|
||||
t.deepEqual(verifyRelease.args[0][1].commits[0].message, commits[0].message);
|
||||
t.deepEqual(verifyRelease.args[0][1].nextRelease, nextRelease);
|
||||
|
||||
t.is(generateNotes.callCount, 1);
|
||||
t.deepEqual(generateNotes.args[0][0], config);
|
||||
t.deepEqual(generateNotes.args[0][1].options, options);
|
||||
t.deepEqual(generateNotes.args[0][1].logger, t.context.logger);
|
||||
t.deepEqual(generateNotes.args[0][1].lastRelease, lastRelease);
|
||||
t.deepEqual(generateNotes.args[0][1].commits[0].hash, commits[0].hash);
|
||||
t.deepEqual(generateNotes.args[0][1].commits[0].message, commits[0].message);
|
||||
t.deepEqual(generateNotes.args[0][1].nextRelease, nextRelease);
|
||||
|
||||
t.is(publish.callCount, 1);
|
||||
t.deepEqual(publish.args[0][0], config);
|
||||
t.deepEqual(publish.args[0][1].options, options);
|
||||
t.deepEqual(publish.args[0][1].logger, t.context.logger);
|
||||
t.deepEqual(publish.args[0][1].lastRelease, lastRelease);
|
||||
t.deepEqual(publish.args[0][1].commits[0].hash, commits[0].hash);
|
||||
t.deepEqual(publish.args[0][1].commits[0].message, commits[0].message);
|
||||
t.deepEqual(publish.args[0][1].nextRelease, Object.assign({}, nextRelease, {notes}));
|
||||
|
||||
// Verify the tag has been created on the local and remote repo and reference the gitHead
|
||||
t.is(await gitTagHead(nextRelease.gitTag), nextRelease.gitHead);
|
||||
t.is(await gitRemoteTagHead(repositoryUrl, nextRelease.gitTag), nextRelease.gitHead);
|
||||
});
|
||||
|
||||
test('Dry-run skips verifyAuth, verifyConditions, publishNpm and githubRelease', async t => {
|
||||
const env = {NPM_TOKEN: 'NPM_TOKEN'};
|
||||
const pkgOptions = {branch: 'master'};
|
||||
const cliOptions = {githubToken: 'GH_TOKEN', dryRun: true};
|
||||
const options = Object.assign({}, pkgOptions, cliOptions);
|
||||
const pkg = {name: 'available', release: options, repository: {url: 'http://github.com/whats/up.git'}};
|
||||
const npm = {registry: 'http://test.registry.com'};
|
||||
const lastRelease = {version: '1.0.0', gitHead: 'test_commit_head'};
|
||||
const commitsLastRelease = {version: '1.0.0', gitHead: 'tag_head'};
|
||||
const commits = [{hash: '1', message: 'fix: First fix'}, {hash: '2', message: 'feat: First feature'}];
|
||||
const nextRelease = {type: 'major', version: '2.0.0'};
|
||||
test.serial('Use new gitHead, and recreate release notes if a publish plugin create a commit', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second'])).concat(commits);
|
||||
|
||||
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
|
||||
const notes = 'Release notes';
|
||||
|
||||
const generateNotes = stub().resolves(notes);
|
||||
const publish1 = stub().callsFake(async () => {
|
||||
commits = (await gitCommits(['Third'])).concat(commits);
|
||||
});
|
||||
const publish2 = stub().resolves();
|
||||
|
||||
const options = {
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions: stub().resolves(),
|
||||
analyzeCommits: stub().resolves(nextRelease.type),
|
||||
verifyRelease: stub().resolves(),
|
||||
generateNotes,
|
||||
publish: [publish1, publish2],
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
|
||||
t.truthy(await semanticRelease(options));
|
||||
|
||||
t.is(generateNotes.callCount, 2);
|
||||
t.deepEqual(generateNotes.args[0][1].nextRelease, nextRelease);
|
||||
t.is(publish1.callCount, 1);
|
||||
t.deepEqual(publish1.args[0][1].nextRelease, Object.assign({}, nextRelease, {notes}));
|
||||
|
||||
nextRelease.gitHead = await getGitHead();
|
||||
|
||||
t.deepEqual(generateNotes.secondCall.args[1].nextRelease, Object.assign({}, nextRelease, {notes}));
|
||||
t.is(publish2.callCount, 1);
|
||||
t.deepEqual(publish2.args[0][1].nextRelease, Object.assign({}, nextRelease, {notes}));
|
||||
|
||||
// Verify the tag has been created on the local and remote repo and reference the last gitHead
|
||||
t.is(await gitTagHead(nextRelease.gitTag), commits[0].hash);
|
||||
t.is(await gitRemoteTagHead(repositoryUrl, nextRelease.gitTag), commits[0].hash);
|
||||
});
|
||||
|
||||
test.serial('Log all "verifyConditions" errors', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First']);
|
||||
|
||||
const error1 = new Error('error 1');
|
||||
const error2 = new SemanticReleaseError('error 2', 'ERR2');
|
||||
const error3 = new SemanticReleaseError('error 3', 'ERR3');
|
||||
const options = {
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions: [stub().rejects(error1), stub().rejects(error2), stub().rejects(error3)],
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
const errors = await t.throws(semanticRelease(options));
|
||||
|
||||
t.deepEqual(Array.from(errors), [error1, error2, error3]);
|
||||
t.deepEqual(t.context.log.args[t.context.log.args.length - 2], ['%s error 2', 'ERR2']);
|
||||
t.deepEqual(t.context.log.args[t.context.log.args.length - 1], ['%s error 3', 'ERR3']);
|
||||
t.deepEqual(t.context.error.args[t.context.error.args.length - 1], [
|
||||
'An error occurred while running semantic-release: %O',
|
||||
error1,
|
||||
]);
|
||||
t.true(t.context.error.calledAfter(t.context.log));
|
||||
});
|
||||
|
||||
test.serial('Log all "verifyRelease" errors', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
await gitCommits(['Second']);
|
||||
|
||||
const error1 = new SemanticReleaseError('error 1', 'ERR1');
|
||||
const error2 = new SemanticReleaseError('error 2', 'ERR2');
|
||||
const options = {
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions: stub().resolves(),
|
||||
analyzeCommits: stub().resolves('major'),
|
||||
verifyRelease: [stub().rejects(error1), stub().rejects(error2)],
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
const errors = await t.throws(semanticRelease(options));
|
||||
|
||||
t.deepEqual(Array.from(errors), [error1, error2]);
|
||||
t.deepEqual(t.context.log.args[t.context.log.args.length - 2], ['%s error 1', 'ERR1']);
|
||||
t.deepEqual(t.context.log.args[t.context.log.args.length - 1], ['%s error 2', 'ERR2']);
|
||||
});
|
||||
|
||||
test.serial('Dry-run skips publish', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
await gitCommits(['Second']);
|
||||
|
||||
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
|
||||
const notes = 'Release notes';
|
||||
|
||||
// Stub modules
|
||||
const log = stub();
|
||||
const error = stub();
|
||||
const logger = {log, error};
|
||||
const verifyAuth = stub().returns();
|
||||
const publishNpm = stub().resolves();
|
||||
const githubRelease = stub().resolves();
|
||||
const getCommits = stub().resolves({commits, lastRelease: commitsLastRelease});
|
||||
const getNextVersion = stub().returns(nextRelease.version);
|
||||
// Stub plugins
|
||||
const verifyConditions = stub().resolves();
|
||||
const getLastRelease = stub().resolves(lastRelease);
|
||||
const analyzeCommits = stub().resolves(nextRelease.type);
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves(notes);
|
||||
const getConfig = stub().resolves({
|
||||
plugins: {getLastRelease, analyzeCommits, verifyRelease, verifyConditions, generateNotes},
|
||||
env,
|
||||
options,
|
||||
pkg,
|
||||
npm,
|
||||
const publish = stub().resolves();
|
||||
|
||||
const options = {
|
||||
dryRun: true,
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions,
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
t.truthy(await semanticRelease(options));
|
||||
|
||||
const semanticRelease = proxyquire('../src/index', {
|
||||
'./lib/logger': logger,
|
||||
'./lib/verify-auth': verifyAuth,
|
||||
'./lib/get-config': getConfig,
|
||||
'./lib/get-commits': getCommits,
|
||||
'./lib/publish-npm': publishNpm,
|
||||
'./lib/github-release': githubRelease,
|
||||
'./lib/get-next-version': getNextVersion,
|
||||
});
|
||||
|
||||
// Call the index module
|
||||
await semanticRelease(cliOptions);
|
||||
|
||||
// Verify that publishNpm, githubRelease, verifyAuth, verifyConditions have not been called in a dry run
|
||||
t.true(publishNpm.notCalled);
|
||||
t.true(githubRelease.notCalled);
|
||||
t.true(verifyAuth.notCalled);
|
||||
t.true(verifyConditions.notCalled);
|
||||
// Verify the release notes are logged
|
||||
t.true(consoleLog.calledWithMatch(notes));
|
||||
// Verify the sub-modules have been called with expected parameters
|
||||
t.true(getConfig.calledOnce);
|
||||
t.true(getConfig.calledWithExactly(cliOptions));
|
||||
// Verify plugins have been called with expected parameters
|
||||
t.true(getLastRelease.calledOnce);
|
||||
t.true(getLastRelease.calledWithExactly({env, options, pkg, npm, logger}));
|
||||
t.true(analyzeCommits.calledOnce);
|
||||
t.true(analyzeCommits.calledWithExactly({env, options, pkg, npm, logger, lastRelease: commitsLastRelease, commits}));
|
||||
t.true(verifyRelease.calledOnce);
|
||||
t.true(
|
||||
verifyRelease.calledWithExactly({
|
||||
env,
|
||||
options,
|
||||
pkg,
|
||||
npm,
|
||||
logger,
|
||||
lastRelease: commitsLastRelease,
|
||||
commits,
|
||||
nextRelease,
|
||||
})
|
||||
);
|
||||
t.true(generateNotes.calledOnce);
|
||||
t.true(
|
||||
generateNotes.calledWithExactly({
|
||||
env,
|
||||
options,
|
||||
pkg,
|
||||
npm,
|
||||
logger,
|
||||
lastRelease: commitsLastRelease,
|
||||
commits,
|
||||
nextRelease,
|
||||
})
|
||||
);
|
||||
t.not(t.context.log.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
|
||||
t.is(verifyConditions.callCount, 1);
|
||||
t.is(analyzeCommits.callCount, 1);
|
||||
t.is(verifyRelease.callCount, 1);
|
||||
t.is(generateNotes.callCount, 1);
|
||||
t.is(publish.callCount, 0);
|
||||
});
|
||||
|
||||
test('Throw SemanticReleaseError if there is no release to be done', async t => {
|
||||
const env = {NPM_TOKEN: 'NPM_TOKEN'};
|
||||
const pkgOptions = {branch: 'master'};
|
||||
const cliOptions = {githubToken: 'GH_TOKEN'};
|
||||
const options = Object.assign({}, pkgOptions, cliOptions);
|
||||
const pkg = {name: 'available', release: options, repository: {url: 'http://github.com/whats/up.git'}};
|
||||
const npm = {registry: 'http://test.registry.com'};
|
||||
const lastRelease = {version: '1.0.0', gitHead: 'test_commit_head'};
|
||||
const commitsLastRelease = {version: '1.0.0', gitHead: 'tag_head'};
|
||||
const commits = [{hash: '1', message: 'fix: First fix'}, {hash: '2', message: 'feat: First feature'}];
|
||||
const nextRelease = {type: undefined};
|
||||
test.serial('Force a dry-run if not on a CI and "noCi" is not explicitly set', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
await gitCommits(['Second']);
|
||||
|
||||
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
|
||||
const notes = 'Release notes';
|
||||
|
||||
// Stub modules
|
||||
const log = stub();
|
||||
const error = stub();
|
||||
const logger = {log, error};
|
||||
const verifyAuth = stub().returns();
|
||||
const publishNpm = stub().resolves();
|
||||
const githubRelease = stub().resolves();
|
||||
const getCommits = stub().resolves({commits, lastRelease: commitsLastRelease});
|
||||
const getNextVersion = stub().returns(null);
|
||||
// Stub plugins
|
||||
const verifyConditions = stub().resolves();
|
||||
const getLastRelease = stub().resolves(lastRelease);
|
||||
const analyzeCommits = stub().resolves(nextRelease.type);
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves(notes);
|
||||
const publish = stub().resolves();
|
||||
|
||||
const options = {
|
||||
dryRun: false,
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions,
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: false, branch: 'master'}),
|
||||
});
|
||||
t.truthy(await semanticRelease(options));
|
||||
|
||||
t.is(t.context.log.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
|
||||
t.is(verifyConditions.callCount, 1);
|
||||
t.is(analyzeCommits.callCount, 1);
|
||||
t.is(verifyRelease.callCount, 1);
|
||||
t.is(generateNotes.callCount, 1);
|
||||
t.is(publish.callCount, 0);
|
||||
});
|
||||
|
||||
test.serial('Allow local releases with "noCi" option', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
await gitCommits(['Second']);
|
||||
|
||||
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
|
||||
const notes = 'Release notes';
|
||||
|
||||
const verifyConditions = stub().resolves();
|
||||
const analyzeCommits = stub().resolves(nextRelease.type);
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves(notes);
|
||||
const publish = stub().resolves();
|
||||
|
||||
const options = {
|
||||
noCi: true,
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions,
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: false, branch: 'master', isPr: true}),
|
||||
});
|
||||
t.truthy(await semanticRelease(options));
|
||||
|
||||
t.not(t.context.log.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
|
||||
t.not(
|
||||
t.context.log.args[0][0],
|
||||
"This run was triggered by a pull request and therefore a new version won't be published."
|
||||
);
|
||||
t.is(verifyConditions.callCount, 1);
|
||||
t.is(analyzeCommits.callCount, 1);
|
||||
t.is(verifyRelease.callCount, 1);
|
||||
t.is(generateNotes.callCount, 1);
|
||||
t.is(publish.callCount, 1);
|
||||
});
|
||||
|
||||
test.serial('Accept "undefined" value returned by the "generateNotes" plugins', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
let commits = await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
commits = (await gitCommits(['Second'])).concat(commits);
|
||||
|
||||
const lastRelease = {version: '1.0.0', gitHead: commits[commits.length - 1].hash, gitTag: 'v1.0.0'};
|
||||
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
|
||||
const verifyConditions = stub().resolves();
|
||||
const analyzeCommits = stub().resolves(nextRelease.type);
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves();
|
||||
const getConfig = stub().resolves({
|
||||
plugins: {getLastRelease, analyzeCommits, verifyRelease, verifyConditions, generateNotes},
|
||||
env,
|
||||
options,
|
||||
pkg,
|
||||
npm,
|
||||
});
|
||||
const publish = stub().resolves();
|
||||
|
||||
const semanticRelease = proxyquire('../src/index', {
|
||||
'./lib/logger': logger,
|
||||
'./lib/verify-auth': verifyAuth,
|
||||
'./lib/get-config': getConfig,
|
||||
'./lib/get-commits': getCommits,
|
||||
'./lib/publish-npm': publishNpm,
|
||||
'./lib/github-release': githubRelease,
|
||||
'./lib/get-next-version': getNextVersion,
|
||||
});
|
||||
const options = {
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions: [verifyConditions],
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
// Call the index module
|
||||
const err = await t.throws(semanticRelease(cliOptions));
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
t.truthy(await semanticRelease(options));
|
||||
|
||||
t.is(analyzeCommits.callCount, 1);
|
||||
t.deepEqual(analyzeCommits.args[0][1].lastRelease, lastRelease);
|
||||
|
||||
t.is(verifyRelease.callCount, 1);
|
||||
t.deepEqual(verifyRelease.args[0][1].lastRelease, lastRelease);
|
||||
|
||||
t.is(generateNotes.callCount, 1);
|
||||
t.deepEqual(generateNotes.args[0][1].lastRelease, lastRelease);
|
||||
|
||||
t.is(publish.callCount, 1);
|
||||
t.deepEqual(publish.args[0][1].lastRelease, lastRelease);
|
||||
t.falsy(publish.args[0][1].nextRelease.notes);
|
||||
});
|
||||
|
||||
test.serial('Returns falsy value if not running from a git repository', async t => {
|
||||
// Set the current working directory to a temp directory
|
||||
process.chdir(tempy.directory());
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
t.falsy(await semanticRelease({repositoryUrl: 'git@hostname.com:owner/module.git'}));
|
||||
t.is(t.context.error.args[0][0], 'Semantic-release must run from a git repository.');
|
||||
});
|
||||
|
||||
test.serial('Returns falsy value if triggered by a PR', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: true}),
|
||||
});
|
||||
|
||||
t.falsy(await semanticRelease({repositoryUrl}));
|
||||
t.is(
|
||||
t.context.log.args[6][0],
|
||||
"This run was triggered by a pull request and therefore a new version won't be published."
|
||||
);
|
||||
});
|
||||
|
||||
test.serial('Returns falsy value if not running from the configured branch', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
|
||||
const verifyConditions = stub().resolves();
|
||||
const analyzeCommits = stub().resolves();
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves();
|
||||
const publish = stub().resolves();
|
||||
|
||||
const options = {
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions: [verifyConditions],
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'other-branch', isPr: false}),
|
||||
});
|
||||
|
||||
t.falsy(await semanticRelease(options));
|
||||
t.is(
|
||||
t.context.log.args[0][0],
|
||||
'This test run was triggered on the branch other-branch, while semantic-release is configured to only publish from master, therefore a new version won’t be published.'
|
||||
);
|
||||
});
|
||||
|
||||
test.serial('Returns falsy value if there is no relevant changes', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First']);
|
||||
|
||||
const verifyConditions = stub().resolves();
|
||||
const analyzeCommits = stub().resolves();
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves();
|
||||
const publish = stub().resolves();
|
||||
|
||||
const options = {
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions: [verifyConditions],
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
|
||||
t.falsy(await semanticRelease(options));
|
||||
t.is(analyzeCommits.callCount, 1);
|
||||
t.is(verifyRelease.callCount, 0);
|
||||
t.is(generateNotes.callCount, 0);
|
||||
t.is(publish.callCount, 0);
|
||||
t.is(t.context.log.args[6][0], 'There are no relevant changes, so no new version is released.');
|
||||
});
|
||||
|
||||
test.serial('Exclude commits with [skip release] or [release skip] from analysis', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits([
|
||||
'Test commit',
|
||||
'Test commit [skip release]',
|
||||
'Test commit [release skip]',
|
||||
'Test commit [Release Skip]',
|
||||
'Test commit [Skip Release]',
|
||||
'Test commit [skip release]',
|
||||
'Test commit\n\n commit body\n[skip release]',
|
||||
'Test commit\n\n commit body\n[release skip]',
|
||||
]);
|
||||
|
||||
const verifyConditions1 = stub().resolves();
|
||||
const verifyConditions2 = stub().resolves();
|
||||
const analyzeCommits = stub().resolves();
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves();
|
||||
const publish = stub().resolves();
|
||||
|
||||
const config = {branch: 'master', repositoryUrl, globalOpt: 'global'};
|
||||
const options = {
|
||||
...config,
|
||||
verifyConditions: [verifyConditions1, verifyConditions2],
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
await semanticRelease(options);
|
||||
|
||||
t.is(analyzeCommits.callCount, 1);
|
||||
|
||||
t.is(analyzeCommits.args[0][1].commits.length, 2);
|
||||
t.deepEqual(analyzeCommits.args[0][1].commits[0], commits[commits.length - 1]);
|
||||
});
|
||||
|
||||
test.serial('Hide sensitive environment variable values from the logs', async t => {
|
||||
process.env.MY_TOKEN = 'secret token';
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
|
||||
const options = {
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions: async (pluginConfig, {logger}) => {
|
||||
console.log(`Console: The token ${process.env.MY_TOKEN} is invalid`);
|
||||
logger.log(`Log: The token ${process.env.MY_TOKEN} is invalid`);
|
||||
logger.error(`Error: The token ${process.env.MY_TOKEN} is invalid`);
|
||||
throw new Error(`Invalid token ${process.env.MY_TOKEN}`);
|
||||
},
|
||||
};
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
|
||||
await t.throws(semanticRelease(options));
|
||||
|
||||
t.regex(t.context.stdout.args[6][0], /Console: The token \[secure\] is invalid/);
|
||||
t.regex(t.context.stdout.args[7][0], /Log: The token \[secure\] is invalid/);
|
||||
t.regex(t.context.stderr.args[0][0], /Error: The token \[secure\] is invalid/);
|
||||
t.regex(t.context.stderr.args[1][0], /Invalid token \[secure\]/);
|
||||
});
|
||||
|
||||
test.serial('Throw SemanticReleaseError if repositoryUrl is not set and cannot be found from repo config', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
await gitRepo();
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
const error = await t.throws(semanticRelease());
|
||||
|
||||
// Verify error code and type
|
||||
t.is(err.code, 'ENOCHANGE');
|
||||
t.true(err instanceof SemanticReleaseError);
|
||||
// Verify the sub-modules have been called with expected parameters
|
||||
t.true(getConfig.calledOnce);
|
||||
t.true(getConfig.calledWithExactly(cliOptions));
|
||||
t.true(verifyAuth.calledOnce);
|
||||
t.true(verifyAuth.calledWithExactly(options, env));
|
||||
// Verify plugins have been called with expected parameters
|
||||
t.true(verifyConditions.calledOnce);
|
||||
t.true(verifyConditions.calledWithExactly({env, options, pkg, npm, logger}));
|
||||
t.true(getLastRelease.calledOnce);
|
||||
t.true(getLastRelease.calledWithExactly({env, options, pkg, npm, logger}));
|
||||
t.true(analyzeCommits.calledOnce);
|
||||
t.true(analyzeCommits.calledWithExactly({env, options, pkg, npm, logger, lastRelease: commitsLastRelease, commits}));
|
||||
// Verify that verifyRelease, publishNpm, generateNotes, githubRelease have not been called when no release is done
|
||||
t.true(verifyRelease.notCalled);
|
||||
t.true(generateNotes.notCalled);
|
||||
t.true(publishNpm.notCalled);
|
||||
t.true(githubRelease.notCalled);
|
||||
t.is(error.code, 'ENOREPOURL');
|
||||
t.is(error.name, 'SemanticReleaseError');
|
||||
});
|
||||
|
||||
test.serial('Throw an Error if plugin returns an unexpected value', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First']);
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0');
|
||||
// Add new commits to the master branch
|
||||
await gitCommits(['Second']);
|
||||
|
||||
const verifyConditions = stub().resolves();
|
||||
const analyzeCommits = stub().resolves('string');
|
||||
|
||||
const options = {
|
||||
branch: 'master',
|
||||
repositoryUrl,
|
||||
verifyConditions: [verifyConditions],
|
||||
analyzeCommits,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
const error = await t.throws(semanticRelease(options), Error);
|
||||
|
||||
// Verify error message
|
||||
t.regex(error.message, new RegExp(DEFINITIONS.analyzeCommits.output.message));
|
||||
t.regex(error.message, /Received: 'string'/);
|
||||
});
|
||||
|
||||
test.serial('Get all commits including the ones not in the shallow clone', async t => {
|
||||
const repositoryUrl = await gitRepo(true);
|
||||
await gitTagVersion('v1.0.0');
|
||||
await gitCommits(['First', 'Second', 'Third']);
|
||||
await push(repositoryUrl, 'master');
|
||||
|
||||
await gitShallowClone(repositoryUrl);
|
||||
|
||||
const nextRelease = {type: 'major', version: '2.0.0', gitHead: await getGitHead(), gitTag: 'v2.0.0'};
|
||||
const notes = 'Release notes';
|
||||
const verifyConditions = stub().resolves();
|
||||
const analyzeCommits = stub().resolves(nextRelease.type);
|
||||
const verifyRelease = stub().resolves();
|
||||
const generateNotes = stub().resolves(notes);
|
||||
const publish = stub().resolves();
|
||||
|
||||
const config = {branch: 'master', repositoryUrl, globalOpt: 'global'};
|
||||
const options = {
|
||||
...config,
|
||||
verifyConditions,
|
||||
analyzeCommits,
|
||||
verifyRelease,
|
||||
generateNotes,
|
||||
publish,
|
||||
};
|
||||
|
||||
const semanticRelease = proxyquire('..', {
|
||||
'./lib/logger': t.context.logger,
|
||||
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
|
||||
});
|
||||
t.truthy(await semanticRelease(options));
|
||||
|
||||
t.is(analyzeCommits.args[0][1].commits.length, 3);
|
||||
});
|
||||
|
||||
+312
-372
@@ -2,73 +2,116 @@ import test from 'ava';
|
||||
import {writeJson, readJson} from 'fs-extra';
|
||||
import {stub} from 'sinon';
|
||||
import execa from 'execa';
|
||||
import {gitRepo, gitCommits, gitHead, gitTagVersion, gitPackRefs, gitAmmendCommit} from './helpers/git-utils';
|
||||
import registry from './helpers/registry';
|
||||
import {gitHead as getGitHead, gitTagHead, gitRepo, gitCommits, gitRemoteTagHead} from './helpers/git-utils';
|
||||
import gitbox from './helpers/gitbox';
|
||||
import mockServer from './helpers/mockserver';
|
||||
import semanticRelease from '../src';
|
||||
import npmRegistry from './helpers/npm-registry';
|
||||
import semanticRelease from '..';
|
||||
|
||||
// Environment variables used with cli
|
||||
/* eslint camelcase: ["error", {properties: "never"}] */
|
||||
|
||||
// Environment variables used with semantic-release cli (similar to what a user would setup)
|
||||
const env = {
|
||||
npm_config_registry: registry.uri,
|
||||
GH_TOKEN: 'github_token',
|
||||
NPM_OLD_TOKEN: 'aW50ZWdyYXRpb246c3VjaHNlY3VyZQ==',
|
||||
GH_TOKEN: gitbox.gitCredential,
|
||||
GITHUB_URL: mockServer.url,
|
||||
NPM_EMAIL: 'integration@test.com',
|
||||
NPM_USERNAME: 'integration',
|
||||
NPM_PASSWORD: 'suchsecure',
|
||||
};
|
||||
// Environment variables used only for the local npm command used to do verification
|
||||
const testEnv = Object.assign({}, process.env, {
|
||||
npm_config_registry: npmRegistry.url,
|
||||
NPM_EMAIL: 'integration@test.com',
|
||||
LEGACY_TOKEN: Buffer.from(`${process.env.NPM_USERNAME}:${process.env.NPM_PASSWORD}`, 'utf8').toString('base64'),
|
||||
});
|
||||
// Save the current process.env
|
||||
const envBackup = Object.assign({}, process.env);
|
||||
const cli = require.resolve('../bin/semantic-release');
|
||||
const noop = require.resolve('../src/lib/plugin-noop');
|
||||
const pluginError = require.resolve('./fixtures/plugin-error-a');
|
||||
const pluginError = require.resolve('./fixtures/plugin-error');
|
||||
const pluginInheritedError = require.resolve('./fixtures/plugin-error-inherited');
|
||||
// Save the current working diretory
|
||||
const cwd = process.cwd();
|
||||
// Disable logs during tests
|
||||
stub(process.stdout, 'write');
|
||||
stub(process.stderr, 'write');
|
||||
|
||||
test.before(async t => {
|
||||
await mockServer.start();
|
||||
test.before(async () => {
|
||||
// Start the Git server
|
||||
await gitbox.start();
|
||||
// Start the local NPM registry
|
||||
await registry.start();
|
||||
await npmRegistry.start();
|
||||
// Start Mock Server
|
||||
await mockServer.start();
|
||||
});
|
||||
|
||||
test.beforeEach(async t => {
|
||||
// Save the current process.env
|
||||
t.context.env = Object.assign({}, process.env);
|
||||
// Save the current working diretory
|
||||
t.context.cwd = process.cwd();
|
||||
test.beforeEach(() => {
|
||||
// Delete environment variables that could have been set on the machine running the tests
|
||||
delete process.env.NPM_TOKEN;
|
||||
delete process.env.NPM_USERNAME;
|
||||
delete process.env.NPM_PASSWORD;
|
||||
delete process.env.NPM_EMAIL;
|
||||
delete process.env.GH_URL;
|
||||
delete process.env.GITHUB_URL;
|
||||
delete process.env.GH_PREFIX;
|
||||
delete process.env.GITHUB_PREFIX;
|
||||
delete process.env.GIT_CREDENTIALS;
|
||||
delete process.env.GH_TOKEN;
|
||||
delete process.env.GITHUB_TOKEN;
|
||||
delete process.env.GL_TOKEN;
|
||||
delete process.env.GITLAB_TOKEN;
|
||||
|
||||
t.context.log = stub(console, 'log');
|
||||
t.context.error = stub(console, 'error');
|
||||
process.env.TRAVIS = 'true';
|
||||
process.env.CI = 'true';
|
||||
process.env.TRAVIS_BRANCH = 'master';
|
||||
process.env.TRAVIS_PULL_REQUEST = 'false';
|
||||
|
||||
// Delete all `npm_config` environment variable set by CI as they take precedence over the `.npmrc` because the process that runs the tests is started before the `.npmrc` is created
|
||||
for (let i = 0, keys = Object.keys(process.env); i < keys.length; i++) {
|
||||
if (keys[i].startsWith('npm_')) {
|
||||
delete process.env[keys[i]];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test.afterEach.always(async t => {
|
||||
test.afterEach.always(() => {
|
||||
// Restore process.env
|
||||
process.env = Object.assign({}, t.context.env);
|
||||
process.env = envBackup;
|
||||
// Restore the current working directory
|
||||
process.chdir(t.context.cwd);
|
||||
|
||||
t.context.log.restore();
|
||||
t.context.error.restore();
|
||||
process.chdir(cwd);
|
||||
});
|
||||
|
||||
test.after.always(async t => {
|
||||
await mockServer.stop();
|
||||
test.after.always(async () => {
|
||||
// Stop the Git server
|
||||
await gitbox.stop();
|
||||
// Stop the local NPM registry
|
||||
await registry.stop();
|
||||
await npmRegistry.stop();
|
||||
// Stop Mock Server
|
||||
await mockServer.stop();
|
||||
});
|
||||
|
||||
test.serial('Release patch, minor and major versions', async t => {
|
||||
const packageName = 'test-module';
|
||||
const repo = 'test-repo';
|
||||
const packageName = 'test-release';
|
||||
const owner = 'git';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
await gitRepo();
|
||||
const {repositoryUrl, authUrl} = await gitbox.createRepo(packageName);
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
release: {verifyConditions: noop, githubUrl: mockServer.url},
|
||||
repository: {url: repositoryUrl},
|
||||
publishConfig: {registry: npmRegistry.url},
|
||||
});
|
||||
// Create a npm-shrinkwrap.json file
|
||||
await execa('npm', ['shrinkwrap'], {env});
|
||||
await execa('npm', ['shrinkwrap'], {env: testEnv});
|
||||
|
||||
/** No release **/
|
||||
/* No release */
|
||||
|
||||
let verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
t.log('Commit a chore');
|
||||
await gitCommits(['chore: Init repository']);
|
||||
t.log('$ semantic-release');
|
||||
@@ -76,15 +119,15 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
t.regex(stdout, /There are no relevant changes, so no new version is released/);
|
||||
t.is(code, 0);
|
||||
|
||||
/** Initial release **/
|
||||
/* Initial release */
|
||||
let version = '1.0.0';
|
||||
let createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
let createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
let createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
@@ -96,8 +139,8 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env}));
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
|
||||
// Verify package.json and npm-shrinkwrap.json have been updated
|
||||
@@ -106,24 +149,27 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env})).stdout
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
|
||||
);
|
||||
let gitHead = await getGitHead();
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, await gitHead());
|
||||
t.is(releasedGitHead, gitHead);
|
||||
t.is(await gitTagHead(`v${version}`), gitHead);
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
|
||||
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
|
||||
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
|
||||
/** Patch release **/
|
||||
/* Patch release */
|
||||
version = '1.0.1';
|
||||
createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
@@ -135,8 +181,8 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
await gitCommits(['fix: bar']);
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env}));
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
|
||||
// Verify package.json and npm-shrinkwrap.json have been updated
|
||||
@@ -145,24 +191,27 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', 'test-module', 'version', 'gitHead'], {env})).stdout
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
|
||||
);
|
||||
gitHead = await getGitHead();
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, await gitHead());
|
||||
t.is(releasedGitHead, gitHead);
|
||||
t.is(await gitTagHead(`v${version}`), gitHead);
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
|
||||
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
|
||||
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
|
||||
/** Minor release **/
|
||||
/* Minor release */
|
||||
version = '1.1.0';
|
||||
createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
@@ -174,8 +223,8 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
await gitCommits(['feat: baz']);
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env}));
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
|
||||
// Verify package.json and npm-shrinkwrap.json have been updated
|
||||
@@ -184,24 +233,27 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', 'test-module', 'version', 'gitHead'], {env})).stdout
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
|
||||
);
|
||||
gitHead = await getGitHead();
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, await gitHead());
|
||||
t.is(releasedGitHead, gitHead);
|
||||
t.is(await gitTagHead(`v${version}`), gitHead);
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
|
||||
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
|
||||
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
|
||||
/** Major release **/
|
||||
/* Major release */
|
||||
version = '2.0.0';
|
||||
createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
@@ -213,8 +265,8 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
await gitCommits(['feat: foo\n\n BREAKING CHANGE: bar']);
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env}));
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
|
||||
// Verify package.json and npm-shrinkwrap.json have been updated
|
||||
@@ -223,111 +275,29 @@ test.serial('Release patch, minor and major versions', async t => {
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', 'test-module', 'version', 'gitHead'], {env})).stdout
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
|
||||
);
|
||||
gitHead = await getGitHead();
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, await gitHead());
|
||||
t.is(releasedGitHead, gitHead);
|
||||
t.is(await gitTagHead(`v${version}`), gitHead);
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
|
||||
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
|
||||
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
});
|
||||
|
||||
test.serial('Release versions from a packed git repository, using tags to determine last release gitHead', async t => {
|
||||
const packageName = 'test-module-2';
|
||||
const repo = 'test-repo';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository');
|
||||
await gitRepo();
|
||||
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git@github.com:${repo}/${packageName}.git`},
|
||||
release: {verifyConditions: noop, githubUrl: mockServer.url},
|
||||
});
|
||||
|
||||
/** Initial release **/
|
||||
let version = '1.0.0';
|
||||
let createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
);
|
||||
let createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
);
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ git pack-refs --all');
|
||||
await gitPackRefs();
|
||||
t.log('$ semantic-release');
|
||||
let {stdout, code} = await execa(cli, [], {env});
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.is(code, 0);
|
||||
// Verify package.json has been updated
|
||||
t.is((await readJson('./package.json')).version, version);
|
||||
// Retrieve the published package from the registry and check version
|
||||
let releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env})).stdout;
|
||||
t.is(releasedVersion, version);
|
||||
t.log(`+ released ${releasedVersion}`);
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
// Create a tag version so the tag can be used later to determine the commit associated with the version
|
||||
await gitTagVersion(`v${version}`);
|
||||
t.log(`Create git tag v${version}`);
|
||||
|
||||
/** Patch release **/
|
||||
version = '1.0.1';
|
||||
createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
);
|
||||
createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
);
|
||||
t.log('Commit a fix');
|
||||
await gitCommits(['fix: bar']);
|
||||
t.log('$ semantic-release');
|
||||
({stdout, code} = await execa(cli, [], {env}));
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.is(code, 0);
|
||||
// Verify package.json has been updated
|
||||
t.is((await readJson('./package.json')).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version
|
||||
releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env})).stdout;
|
||||
t.is(releasedVersion, version);
|
||||
t.log(`+ released ${releasedVersion}`);
|
||||
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
});
|
||||
|
||||
test.serial('Exit with 1 if a plugin is not found', async t => {
|
||||
const packageName = 'test-module-3';
|
||||
const repo = 'test-repo';
|
||||
const packageName = 'test-plugin-not-found';
|
||||
const owner = 'test-repo';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository');
|
||||
await gitRepo();
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
repository: {url: `git+https://github.com/${owner}/${packageName}`},
|
||||
release: {analyzeCommits: 'non-existing-path'},
|
||||
});
|
||||
|
||||
@@ -336,138 +306,70 @@ test.serial('Exit with 1 if a plugin is not found', async t => {
|
||||
t.regex(stderr, /Cannot find module/);
|
||||
});
|
||||
|
||||
test.serial('Create a tag as a recovery solution for "ENOTINHISTORY" error', async t => {
|
||||
const packageName = 'test-module-4';
|
||||
const repo = 'test-repo';
|
||||
test.serial('Exit with 1 if a shareable config is not found', async t => {
|
||||
const packageName = 'test-config-not-found';
|
||||
const owner = 'test-repo';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository');
|
||||
await gitRepo();
|
||||
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
release: {verifyConditions: noop, githubUrl: mockServer.url},
|
||||
repository: {url: `git+https://github.com/${owner}/${packageName}`},
|
||||
release: {extends: 'non-existing-path'},
|
||||
});
|
||||
|
||||
/** Initial release **/
|
||||
let version = '1.0.0';
|
||||
let createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
);
|
||||
let createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
);
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release');
|
||||
let {stderr, stdout, code} = await execa(cli, [], {env});
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.is(code, 0);
|
||||
// Verify package.json has been updated
|
||||
t.is((await readJson('./package.json')).version, version);
|
||||
const {code, stderr} = await t.throws(execa(cli, [], {env}));
|
||||
t.is(code, 1);
|
||||
t.regex(stderr, /Cannot find module/);
|
||||
});
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env})).stdout
|
||||
);
|
||||
const head = await gitHead();
|
||||
t.is(releasedGitHead, head);
|
||||
t.is(releasedVersion, version);
|
||||
t.log(`+ released ${releasedVersion}`);
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
test.serial('Exit with 1 if a shareable config reference a not found plugin', async t => {
|
||||
const packageName = 'test-config-ref-not-found';
|
||||
const owner = 'test-repo';
|
||||
const shareable = {analyzeCommits: 'non-existing-path'};
|
||||
|
||||
// Create a tag version so the tag can be used later to determine the commit associated with the version
|
||||
await gitTagVersion(`v${version}`);
|
||||
t.log(`Create git tag v${version}`);
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository');
|
||||
await gitRepo();
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${owner}/${packageName}`},
|
||||
release: {extends: './shareable.json'},
|
||||
});
|
||||
await writeJson('./shareable.json', shareable);
|
||||
|
||||
/** Rewrite sha of commit used for release **/
|
||||
|
||||
t.log('Amend release commit');
|
||||
const {hash} = await gitAmmendCommit('feat: Initial commit');
|
||||
|
||||
/** Patch release **/
|
||||
|
||||
t.log('Commit a fix');
|
||||
await gitCommits(['fix: bar']);
|
||||
t.log('$ semantic-release');
|
||||
({stderr, stdout, code} = await execa(cli, [], {env, reject: false}));
|
||||
|
||||
t.log('Log "ENOTINHISTORY" message');
|
||||
t.is(code, 0);
|
||||
t.regex(
|
||||
stderr,
|
||||
new RegExp(
|
||||
`You can recover from this error by restoring the commit "${head}" or by creating a tag for the version "${version}" on the commit corresponding to this release`
|
||||
)
|
||||
);
|
||||
|
||||
/** Create a tag to recover and redo release **/
|
||||
|
||||
t.log(`Create git tag v${version} to recover`);
|
||||
await gitTagVersion(`v${version}`, hash);
|
||||
|
||||
version = '1.0.1';
|
||||
createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
);
|
||||
createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
);
|
||||
|
||||
t.log('$ semantic-release');
|
||||
({stderr, stdout, code} = await execa(cli, [], {env}));
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.is(code, 0);
|
||||
// Verify package.json has been updated
|
||||
t.is((await readJson('./package.json')).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env})).stdout;
|
||||
t.is(releasedVersion, version);
|
||||
t.log(`+ released ${releasedVersion}`);
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
const {code, stderr} = await t.throws(execa(cli, [], {env}));
|
||||
t.is(code, 1);
|
||||
t.regex(stderr, /Cannot find module/);
|
||||
});
|
||||
|
||||
test.serial('Dry-run', async t => {
|
||||
const packageName = 'test-module-5';
|
||||
const repo = 'test-repo';
|
||||
const packageName = 'test-dry-run';
|
||||
const owner = 'git';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
await gitRepo();
|
||||
const {repositoryUrl} = await gitbox.createRepo(packageName);
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
release: {githubUrl: mockServer.url},
|
||||
repository: {url: repositoryUrl},
|
||||
publishConfig: {registry: npmRegistry.url},
|
||||
});
|
||||
|
||||
/** Initial release **/
|
||||
/* Initial release */
|
||||
const verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
const version = '1.0.0';
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release -d');
|
||||
let {stdout, code} = await execa(cli, ['-d'], {env});
|
||||
const {stdout, code} = await execa(cli, ['-d'], {env});
|
||||
t.regex(stdout, new RegExp(`There is no previous release, the next release version is ${version}`));
|
||||
t.regex(stdout, new RegExp(`Release note for version ${version}`));
|
||||
t.regex(stdout, /Initial commit/);
|
||||
@@ -475,93 +377,135 @@ test.serial('Dry-run', async t => {
|
||||
|
||||
// Verify package.json and has not been modified
|
||||
t.is((await readJson('./package.json')).version, '0.0.0-dev');
|
||||
await mockServer.verify(verifyMock);
|
||||
});
|
||||
|
||||
test.serial('Pass options via CLI arguments', async t => {
|
||||
const packageName = 'test-module-6';
|
||||
const repo = 'test-repo';
|
||||
const githubToken = 'OTHER_TOKEN';
|
||||
test.serial('Allow local releases with "noCi" option', async t => {
|
||||
delete process.env.TRAVIS;
|
||||
delete process.env.CI;
|
||||
const packageName = 'test-no-ci';
|
||||
const owner = 'git';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
await gitRepo();
|
||||
const {repositoryUrl, authUrl} = await gitbox.createRepo(packageName);
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
release: {githubUrl: mockServer.url},
|
||||
repository: {url: repositoryUrl},
|
||||
publishConfig: {registry: npmRegistry.url},
|
||||
});
|
||||
|
||||
/** Initial release **/
|
||||
let version = '1.0.0';
|
||||
let createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${githubToken}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
/* Initial release */
|
||||
const version = '1.0.0';
|
||||
const verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
let createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
const createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${githubToken}`]}],
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
);
|
||||
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release');
|
||||
let {stdout, code} = await execa(
|
||||
cli,
|
||||
['--github-token', githubToken, '--verify-conditions', `${noop}, ${noop}`, '--debug'],
|
||||
{env}
|
||||
);
|
||||
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
|
||||
t.log('$ semantic-release --no-ci');
|
||||
const {stdout, code} = await execa(cli, ['--no-ci'], {env});
|
||||
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
|
||||
// Verify package.json and has been updated
|
||||
t.is((await readJson('./package.json')).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env})).stdout
|
||||
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
|
||||
);
|
||||
|
||||
const gitHead = await getGitHead();
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, await gitHead());
|
||||
t.is(releasedGitHead, gitHead);
|
||||
t.is(await gitTagHead(`v${version}`), gitHead);
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
|
||||
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
|
||||
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
});
|
||||
|
||||
test.serial('Run via JS API', async t => {
|
||||
const packageName = 'test-module-7';
|
||||
const repo = 'test-repo';
|
||||
const githubToken = 'OTHER_TOKEN';
|
||||
test.serial('Pass options via CLI arguments', async t => {
|
||||
const packageName = 'test-cli';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
await gitRepo();
|
||||
const {repositoryUrl, authUrl} = await gitbox.createRepo(packageName);
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
release: {githubUrl: mockServer.url},
|
||||
repository: {url: repositoryUrl},
|
||||
publishConfig: {registry: npmRegistry.url},
|
||||
});
|
||||
|
||||
/** Initial release **/
|
||||
let version = '1.0.0';
|
||||
let createRefMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/git/refs`,
|
||||
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${githubToken}`]}]},
|
||||
{body: {ref: `refs/tags/${version}`}}
|
||||
/* Initial release */
|
||||
const version = '1.0.0';
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release');
|
||||
const {stdout, code} = await execa(
|
||||
cli,
|
||||
['--verify-conditions', '@semantic-release/npm', '--publish', '@semantic-release/npm', '--debug'],
|
||||
{env}
|
||||
);
|
||||
let createReleaseMock = mockServer.mock(
|
||||
`/repos/${repo}/${packageName}/releases`,
|
||||
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
|
||||
t.is(code, 0);
|
||||
|
||||
// Verify package.json and has been updated
|
||||
t.is((await readJson('./package.json')).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
|
||||
);
|
||||
const gitHead = await getGitHead();
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, gitHead);
|
||||
t.is(await gitTagHead(`v${version}`), gitHead);
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
|
||||
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
|
||||
});
|
||||
|
||||
test.serial('Run via JS API', async t => {
|
||||
const packageName = 'test-js-api';
|
||||
const owner = 'git';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
const {repositoryUrl, authUrl} = await gitbox.createRepo(packageName);
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: repositoryUrl},
|
||||
publishConfig: {registry: npmRegistry.url},
|
||||
});
|
||||
|
||||
/* Initial release */
|
||||
const version = '1.0.0';
|
||||
const verifyMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}`,
|
||||
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
|
||||
{body: {permissions: {push: true}}, method: 'GET'}
|
||||
);
|
||||
const createReleaseMock = await mockServer.mock(
|
||||
`/repos/${owner}/${packageName}/releases`,
|
||||
{
|
||||
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
|
||||
headers: [{name: 'Authorization', values: [`token ${githubToken}`]}],
|
||||
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
|
||||
},
|
||||
{body: {html_url: `release-url/${version}`}}
|
||||
);
|
||||
@@ -571,69 +515,44 @@ test.serial('Run via JS API', async t => {
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ Call semantic-release via API');
|
||||
await semanticRelease({githubToken, verifyConditions: [noop, noop], debug: true});
|
||||
|
||||
t.true(t.context.log.calledWithMatch(/Published Github release: /, new RegExp(`release-url/${version}`)));
|
||||
t.true(t.context.log.calledWithMatch(/Publishing version .* to npm registry/, version, registry.uri));
|
||||
await semanticRelease();
|
||||
|
||||
// Verify package.json and has been updated
|
||||
t.is((await readJson('./package.json')).version, version);
|
||||
|
||||
// Retrieve the published package from the registry and check version and gitHead
|
||||
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env})).stdout
|
||||
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
|
||||
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
|
||||
);
|
||||
const gitHead = await getGitHead();
|
||||
t.is(releasedVersion, version);
|
||||
t.is(releasedGitHead, await gitHead());
|
||||
t.is(releasedGitHead, gitHead);
|
||||
t.is(await gitTagHead(`v${version}`), gitHead);
|
||||
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
|
||||
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
|
||||
|
||||
await mockServer.verify(createRefMock);
|
||||
await mockServer.verify(verifyMock);
|
||||
await mockServer.verify(createReleaseMock);
|
||||
});
|
||||
|
||||
test.serial('Returns and error code if NPM token is invalid', async t => {
|
||||
const env = {npm_config_registry: registry.uri, GH_TOKEN: 'github_token', NPM_TOKEN: 'wrong_token'};
|
||||
const packageName = 'test-module-8';
|
||||
const repo = 'test-repo';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
release: {verifyConditions: noop, githubUrl: mockServer.url},
|
||||
});
|
||||
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release');
|
||||
let {stderr, code} = await execa(cli, [], {env, reject: false});
|
||||
|
||||
t.regex(stderr, /forbidden Please log in before writing to the db/);
|
||||
t.is(code, 1);
|
||||
});
|
||||
|
||||
test.serial('Log unexpected errors from plugins and exit with 1', async t => {
|
||||
const packageName = 'test-module-9';
|
||||
const repo = 'test-repo';
|
||||
const packageName = 'test-unexpected-error';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
await gitRepo();
|
||||
const {repositoryUrl} = await gitbox.createRepo(packageName);
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
release: {githubUrl: mockServer.url, verifyConditions: pluginError},
|
||||
repository: {url: repositoryUrl},
|
||||
release: {verifyConditions: pluginError},
|
||||
});
|
||||
|
||||
/** Initial release **/
|
||||
/* Initial release */
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release');
|
||||
let {stderr, code} = await execa(cli, [], {env, reject: false});
|
||||
const {stderr, code} = await execa(cli, [], {env, reject: false});
|
||||
// Verify the type and message are logged
|
||||
t.regex(stderr, /Error: a/);
|
||||
// Verify the the stacktrace is logged
|
||||
@@ -643,47 +562,68 @@ test.serial('Log unexpected errors from plugins and exit with 1', async t => {
|
||||
t.is(code, 1);
|
||||
});
|
||||
|
||||
test.serial('Log errors inheriting SemanticReleaseError and exit with 0', async t => {
|
||||
const packageName = 'test-module-10';
|
||||
const repo = 'test-repo';
|
||||
test.serial('Log errors inheriting SemanticReleaseError and exit with 1', async t => {
|
||||
const packageName = 'test-inherited-error';
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository and package.json');
|
||||
await gitRepo();
|
||||
const {repositoryUrl} = await gitbox.createRepo(packageName);
|
||||
// Create package.json in repository root
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: `git+https://github.com/${repo}/${packageName}`},
|
||||
release: {githubUrl: mockServer.url, verifyConditions: pluginInheritedError},
|
||||
repository: {url: repositoryUrl},
|
||||
release: {verifyConditions: pluginInheritedError},
|
||||
});
|
||||
|
||||
/** Initial release **/
|
||||
/* Initial release */
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release');
|
||||
let {stdout, code} = await execa(cli, [], {env, reject: false});
|
||||
const {stdout, code} = await execa(cli, [], {env, reject: false});
|
||||
// Verify the type and message are logged
|
||||
t.regex(stdout, /EINHERITED Inherited error/);
|
||||
t.is(code, 0);
|
||||
t.is(code, 1);
|
||||
});
|
||||
|
||||
test.serial('Exit with 1 if missing permission to push to the remote repository', async t => {
|
||||
const packageName = 'unauthorized';
|
||||
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
t.log('Create git repository');
|
||||
const {repositoryUrl} = await gitbox.createRepo(packageName);
|
||||
await writeJson('./package.json', {
|
||||
name: packageName,
|
||||
version: '0.0.0-dev',
|
||||
repository: {url: repositoryUrl},
|
||||
});
|
||||
|
||||
/* Initial release */
|
||||
t.log('Commit a feature');
|
||||
await gitCommits(['feat: Initial commit']);
|
||||
t.log('$ semantic-release');
|
||||
const {stdout, code} = await execa(cli, [], {env: {...env, ...{GH_TOKEN: 'user:wrong_pass'}}, reject: false});
|
||||
// Verify the type and message are logged
|
||||
t.regex(stdout, /EGITNOPERMISSION/);
|
||||
t.is(code, 1);
|
||||
});
|
||||
|
||||
test.serial('CLI returns error code and prints help if called with a command', async t => {
|
||||
t.log('$ semantic-release pre');
|
||||
let {stdout, code} = await execa(cli, ['pre'], {env, reject: false});
|
||||
const {stdout, code} = await execa(cli, ['pre'], {env, reject: false});
|
||||
t.regex(stdout, /Usage: semantic-release/);
|
||||
t.is(code, 1);
|
||||
});
|
||||
|
||||
test.serial('CLI prints help if called with --help', async t => {
|
||||
t.log('$ semantic-release --help');
|
||||
let {stdout, code} = await execa(cli, ['--help'], {env});
|
||||
const {stdout, code} = await execa(cli, ['--help'], {env});
|
||||
t.regex(stdout, /Usage: semantic-release/);
|
||||
t.is(code, 0);
|
||||
});
|
||||
|
||||
test.serial('CLI returns error code with invalid option', async t => {
|
||||
t.log('$ semantic-release --unknown-option');
|
||||
let {stderr, code} = await execa(cli, ['--unknown-option'], {env, reject: false});
|
||||
const {stderr, code} = await execa(cli, ['--unknown-option'], {env, reject: false});
|
||||
t.regex(stderr, /unknown option/);
|
||||
t.is(code, 1);
|
||||
});
|
||||
|
||||
+13
-10
@@ -1,6 +1,6 @@
|
||||
import test from 'ava';
|
||||
import {stub, match} from 'sinon';
|
||||
import logger from '../src/lib/logger';
|
||||
import {stub} from 'sinon';
|
||||
import logger from '../lib/logger';
|
||||
|
||||
test.beforeEach(t => {
|
||||
t.context.log = stub(console, 'log');
|
||||
@@ -16,8 +16,8 @@ test.serial('Basic log', t => {
|
||||
logger.log('test log');
|
||||
logger.error('test error');
|
||||
|
||||
t.true(t.context.log.calledWithMatch(/.*test log/));
|
||||
t.true(t.context.error.calledWithMatch(/.*test error/));
|
||||
t.regex(t.context.log.args[0][0], /.*test log/);
|
||||
t.regex(t.context.error.args[0][0], /.*test error/);
|
||||
});
|
||||
|
||||
test.serial('Log object', t => {
|
||||
@@ -25,16 +25,18 @@ test.serial('Log object', t => {
|
||||
logger.log(obj);
|
||||
logger.error(obj);
|
||||
|
||||
t.true(t.context.log.calledWithMatch(match.string, obj));
|
||||
t.true(t.context.error.calledWithMatch(match.string, obj));
|
||||
t.is(t.context.log.args[0][1], obj);
|
||||
t.is(t.context.error.args[0][1], obj);
|
||||
});
|
||||
|
||||
test.serial('Log with string formatting', t => {
|
||||
logger.log('test log %s', 'log value');
|
||||
logger.error('test error %s', 'error value');
|
||||
|
||||
t.true(t.context.log.calledWithMatch(/.*test log/, 'log value'));
|
||||
t.true(t.context.error.calledWithMatch(/.*test error/, 'error value'));
|
||||
t.regex(t.context.log.args[0][0], /.*test log/);
|
||||
t.regex(t.context.error.args[0][0], /.*test error/);
|
||||
t.is(t.context.log.args[0][1], 'log value');
|
||||
t.is(t.context.error.args[0][1], 'error value');
|
||||
});
|
||||
|
||||
test.serial('Log with error stacktrace and properties', t => {
|
||||
@@ -43,6 +45,7 @@ test.serial('Log with error stacktrace and properties', t => {
|
||||
const otherError = new Error('other error message');
|
||||
logger.error('test error %O', otherError);
|
||||
|
||||
t.true(t.context.error.calledWithMatch(match.string, error));
|
||||
t.true(t.context.error.calledWithMatch(/.*test error/, otherError));
|
||||
t.is(t.context.error.args[0][1], error);
|
||||
t.regex(t.context.error.args[1][0], /.*test error/);
|
||||
t.is(t.context.error.args[1][1], otherError);
|
||||
});
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
import {promisify} from 'util';
|
||||
import test from 'ava';
|
||||
import proxyquire from 'proxyquire';
|
||||
import {stub, match} from 'sinon';
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.plugins = proxyquire('../src/lib/plugins', {'./logger': {log: t.context.log}});
|
||||
});
|
||||
|
||||
test('Export plugins', t => {
|
||||
// Call the plugin module
|
||||
const defaultPlugins = t.context.plugins({});
|
||||
|
||||
// Verify the module returns a function for each plugin
|
||||
t.is(typeof defaultPlugins.analyzeCommits, 'function');
|
||||
t.is(typeof defaultPlugins.generateNotes, 'function');
|
||||
t.is(typeof defaultPlugins.verifyConditions, 'function');
|
||||
t.is(typeof defaultPlugins.verifyRelease, 'function');
|
||||
t.is(typeof defaultPlugins.getLastRelease, 'function');
|
||||
});
|
||||
|
||||
test('Pipeline - Get all results', async t => {
|
||||
// Call the plugin module with a verifyRelease plugin pipeline
|
||||
const pipelinePlugins = t.context.plugins({
|
||||
verifyRelease: ['./src/lib/plugin-noop', './test/fixtures/plugin-result-a', './test/fixtures/plugin-result-b'],
|
||||
});
|
||||
|
||||
// Call the verifyRelease pipeline
|
||||
const results = await pipelinePlugins.verifyRelease({});
|
||||
|
||||
// Verify the pipeline return the expected result for each plugin, in order
|
||||
t.deepEqual(results, [undefined, 'a', 'b']);
|
||||
// Verify the logger has been called with the plugins path
|
||||
t.true(t.context.log.calledWith(match.string, './src/lib/plugin-noop'));
|
||||
t.true(t.context.log.calledWith(match.string, './test/fixtures/plugin-result-a'));
|
||||
t.true(t.context.log.calledWith(match.string, './test/fixtures/plugin-result-b'));
|
||||
});
|
||||
|
||||
test('Pipeline - Pass pluginConfig and options to each plugins', async t => {
|
||||
// Plugin configuration with options (plugin-result-config is a mock plugin returning its pluginConfig and options parameters)
|
||||
const pluginConfig = {path: './test/fixtures/plugin-result-config', pluginParam: 'param1'};
|
||||
// Semantic-release global options
|
||||
const options = {semanticReleaseParam: 'param2'};
|
||||
// Call the plugin module with a verifyRelease plugin pipeline
|
||||
const pipelinePlugins = t.context.plugins({
|
||||
verifyRelease: [pluginConfig, './test/fixtures/plugin-result-config'],
|
||||
});
|
||||
|
||||
// Call the verifyRelease pipeline
|
||||
const results = await pipelinePlugins.verifyRelease(options);
|
||||
|
||||
// Verify the pipeline first result is the pluginConfig and options parameters (to verify the plugin was called with the defined pluginConfig and options parameters)
|
||||
t.deepEqual(results, [{pluginConfig, options}, {pluginConfig: {}, options}]);
|
||||
// Verify the logger has been called with the plugins path
|
||||
t.true(t.context.log.calledWith(match.string, './test/fixtures/plugin-result-config'));
|
||||
});
|
||||
|
||||
test('Pipeline - Get first error', async t => {
|
||||
// Call the plugin module with a verifyRelease plugin pipeline
|
||||
const pipelinePlugins = t.context.plugins({
|
||||
verifyRelease: ['./src/lib/plugin-noop', './test/fixtures/plugin-error-a', './test/fixtures/plugin-error-b'],
|
||||
});
|
||||
|
||||
// Call the verifyRelease pipeline and verify it returns the error thrown by './test/fixtures/plugin-error-a'
|
||||
await t.throws(pipelinePlugins.verifyRelease({}), 'a');
|
||||
// Verify the logger has been called with the plugins path
|
||||
t.true(t.context.log.calledWith(match.string, './src/lib/plugin-noop'));
|
||||
t.true(t.context.log.calledWith(match.string, './test/fixtures/plugin-error-a'));
|
||||
});
|
||||
|
||||
test('Normalize and load plugin from string', t => {
|
||||
// Call the normalize function with a path
|
||||
const plugin = t.context.plugins.normalize('./src/lib/plugin-noop');
|
||||
|
||||
// Verify the plugin is loaded
|
||||
t.is(typeof plugin, 'function');
|
||||
// Verify the logger has been called with the plugins path
|
||||
t.true(t.context.log.calledWith(match.string, './src/lib/plugin-noop'));
|
||||
});
|
||||
|
||||
test('Normalize and load plugin from object', t => {
|
||||
// Call the normalize function with an object (with path property)
|
||||
const plugin = t.context.plugins.normalize({path: './src/lib/plugin-noop'});
|
||||
|
||||
// Verify the plugin is loaded
|
||||
t.is(typeof plugin, 'function');
|
||||
// Verify the logger has been called with the plugins path
|
||||
t.true(t.context.log.calledWith(match.string, './src/lib/plugin-noop'));
|
||||
});
|
||||
|
||||
test('Load from fallback', t => {
|
||||
// Call the normalize function with a fallback
|
||||
const plugin = t.context.plugins.normalize(null, '../lib/plugin-noop');
|
||||
|
||||
// Verify the fallback plugin is loaded
|
||||
t.is(typeof plugin, 'function');
|
||||
});
|
||||
|
||||
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 = t.context.plugins.normalize('./test/fixtures/plugin-result-config');
|
||||
const pluginResult = await promisify(plugin)({});
|
||||
|
||||
t.deepEqual(pluginResult.pluginConfig, {});
|
||||
});
|
||||
|
||||
test('Always pass a defined "pluginConfig" for plugin defined with path', async t => {
|
||||
// Call the normalize function with the path of a plugin that returns its config
|
||||
const plugin = t.context.plugins.normalize({path: './test/fixtures/plugin-result-config'});
|
||||
const pluginResult = await promisify(plugin)({});
|
||||
|
||||
t.deepEqual(pluginResult.pluginConfig, {path: './test/fixtures/plugin-result-config'});
|
||||
});
|
||||
|
||||
test('Always pass a defined "pluginConfig" for fallback plugin', async t => {
|
||||
// Call the normalize function with the path of a plugin that returns its config
|
||||
const plugin = t.context.plugins.normalize(null, '../../test/fixtures/plugin-result-config');
|
||||
const pluginResult = await promisify(plugin)({});
|
||||
|
||||
t.deepEqual(pluginResult.pluginConfig, {});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import test from 'ava';
|
||||
import definitions from '../../lib/plugins/definitions';
|
||||
|
||||
test('The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition', t => {
|
||||
t.false(definitions.verifyConditions.config.validator({}));
|
||||
t.false(definitions.verifyConditions.config.validator({path: null}));
|
||||
|
||||
t.true(definitions.verifyConditions.config.validator({path: 'plugin-path.js'}));
|
||||
t.true(definitions.verifyConditions.config.validator());
|
||||
t.true(definitions.verifyConditions.config.validator('plugin-path.js'));
|
||||
t.true(definitions.verifyConditions.config.validator(() => {}));
|
||||
t.true(definitions.verifyConditions.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
|
||||
});
|
||||
|
||||
test('The "analyzeCommits" plugin is mandatory, and must be a single plugin definition', t => {
|
||||
t.false(definitions.analyzeCommits.config.validator({}));
|
||||
t.false(definitions.analyzeCommits.config.validator({path: null}));
|
||||
t.false(definitions.analyzeCommits.config.validator([]));
|
||||
t.false(definitions.analyzeCommits.config.validator());
|
||||
|
||||
t.true(definitions.analyzeCommits.config.validator({path: 'plugin-path.js'}));
|
||||
t.true(definitions.analyzeCommits.config.validator('plugin-path.js'));
|
||||
t.true(definitions.analyzeCommits.config.validator(() => {}));
|
||||
});
|
||||
|
||||
test('The "verifyRelease" plugin, if defined, must be a single or an array of plugins definition', t => {
|
||||
t.false(definitions.verifyRelease.config.validator({}));
|
||||
t.false(definitions.verifyRelease.config.validator({path: null}));
|
||||
|
||||
t.true(definitions.verifyRelease.config.validator({path: 'plugin-path.js'}));
|
||||
t.true(definitions.verifyRelease.config.validator());
|
||||
t.true(definitions.verifyRelease.config.validator('plugin-path.js'));
|
||||
t.true(definitions.verifyRelease.config.validator(() => {}));
|
||||
t.true(definitions.verifyRelease.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
|
||||
});
|
||||
|
||||
test('The "generateNotes" plugin, if defined, must be a single plugin definition', t => {
|
||||
t.false(definitions.generateNotes.config.validator({}));
|
||||
t.false(definitions.generateNotes.config.validator({path: null}));
|
||||
t.false(definitions.generateNotes.config.validator([]));
|
||||
|
||||
t.true(definitions.generateNotes.config.validator());
|
||||
t.true(definitions.generateNotes.config.validator({path: 'plugin-path.js'}));
|
||||
t.true(definitions.generateNotes.config.validator('plugin-path.js'));
|
||||
t.true(definitions.generateNotes.config.validator(() => {}));
|
||||
});
|
||||
|
||||
test('The "publish" plugin is mandatory, and must be a single or an array of plugins definition', t => {
|
||||
t.false(definitions.publish.config.validator({}));
|
||||
t.false(definitions.publish.config.validator({path: null}));
|
||||
t.false(definitions.publish.config.validator());
|
||||
|
||||
t.true(definitions.publish.config.validator({path: 'plugin-path.js'}));
|
||||
t.true(definitions.publish.config.validator('plugin-path.js'));
|
||||
t.true(definitions.publish.config.validator(() => {}));
|
||||
t.true(definitions.publish.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
|
||||
});
|
||||
|
||||
test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', t => {
|
||||
t.false(definitions.analyzeCommits.output.validator('invalid'));
|
||||
t.false(definitions.analyzeCommits.output.validator(1));
|
||||
t.false(definitions.analyzeCommits.output.validator({}));
|
||||
|
||||
t.true(definitions.analyzeCommits.output.validator());
|
||||
t.true(definitions.analyzeCommits.output.validator(null));
|
||||
t.true(definitions.analyzeCommits.output.validator('major'));
|
||||
});
|
||||
|
||||
test('The "generateNotes" plugin output, if defined, must be a string', t => {
|
||||
t.false(definitions.generateNotes.output.validator(1));
|
||||
t.false(definitions.generateNotes.output.validator({}));
|
||||
|
||||
t.true(definitions.generateNotes.output.validator());
|
||||
t.true(definitions.generateNotes.output.validator(null));
|
||||
t.true(definitions.generateNotes.output.validator(''));
|
||||
t.true(definitions.generateNotes.output.validator('string'));
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user