Compare commits
@@ -0,0 +1,21 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Something not working as expected
|
||||
|
||||
---
|
||||
|
||||
## Current behavior
|
||||
|
||||
<!-- Describe how the issue manifests. -->
|
||||
|
||||
## Expected behavior
|
||||
|
||||
<!-- Describe what the desired behavior would be. -->
|
||||
|
||||
## Environment
|
||||
|
||||
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
|
||||
- CI environment: <!-- CI service name -->
|
||||
- Plugins used: <!-- List semantic-release plugin used if any -->
|
||||
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
|
||||
- CI logs: <!-- link to your CI logs or semantic-release logs -->
|
||||
@@ -0,0 +1,17 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Wouldn’t it be nice if semantic-release could ...
|
||||
|
||||
---
|
||||
|
||||
## New feature motivation
|
||||
|
||||
<!-- Describe the context, the use-case and the advantages of the feature request. -->
|
||||
|
||||
## New feature description
|
||||
|
||||
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
|
||||
|
||||
## New feature implementation
|
||||
|
||||
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
|
||||
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: New plugin suggestion
|
||||
about: Integrate with a new platform, etc
|
||||
|
||||
---
|
||||
|
||||
## New plugin motivation
|
||||
|
||||
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
|
||||
|
||||
## Third-party documentation
|
||||
|
||||
<!-- Provide explanation and documentation links for the platform to integrate with. -->
|
||||
+132
-1
@@ -1,2 +1,133 @@
|
||||
node_modules
|
||||
|
||||
# Created by https://www.gitignore.io/api/macos,windows,linux,node
|
||||
|
||||
### Linux ###
|
||||
*~
|
||||
|
||||
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||
.fuse_hidden*
|
||||
|
||||
# KDE directory preferences
|
||||
.directory
|
||||
|
||||
# Linux trash folder which might appear on any partition or disk
|
||||
.Trash-*
|
||||
|
||||
# .nfs files are created when an open file is removed but is still being accessed
|
||||
.nfs*
|
||||
|
||||
### macOS ###
|
||||
*.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
### Node ###
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Typescript v1 declaration files
|
||||
typings/
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variables file
|
||||
.env
|
||||
|
||||
|
||||
### Windows ###
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Folder config file
|
||||
Desktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
# Lockfiles
|
||||
package-lock.json
|
||||
yarn.lock
|
||||
|
||||
# Gitbook
|
||||
_book
|
||||
|
||||
+11
-18
@@ -1,18 +1,11 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- '0.10'
|
||||
sudo: false
|
||||
cache:
|
||||
directories:
|
||||
- node_modules
|
||||
notifications:
|
||||
email: false
|
||||
deploy:
|
||||
provider: npm
|
||||
email: stephan@boennemann.me
|
||||
skip_cleanup: true
|
||||
api_key:
|
||||
secure: Lq1FZweaNr/Ah8M7h3oWQ59HTswzvcksTUfzWb/dpqNn5FECN9I+4gi79EQPD62ZbJDCuDHY0EEEDLdnaB1z8N7kOj1RtmvC1k0teTEXFsGBPS4evXakRj+AfoBAGsTaXHqBYBOvYBxJT2Md/UoOgPSQjtAdZSNsmoFb1xkngQ0=
|
||||
on:
|
||||
branch: master
|
||||
repo: boennemann/semantic-release
|
||||
version: ~> 1.0
|
||||
|
||||
services:
|
||||
- docker
|
||||
|
||||
import:
|
||||
- .travis/node.yml
|
||||
- .travis/node-versions.yml
|
||||
- .travis/semantic-release.yml
|
||||
- .travis/greenkeeper.yml
|
||||
- .travis/codecov.yml
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
after_success:
|
||||
- npm run codecov
|
||||
@@ -0,0 +1,3 @@
|
||||
branches:
|
||||
only:
|
||||
- /^greenkeeper.*$/
|
||||
@@ -0,0 +1,4 @@
|
||||
node_js:
|
||||
- 12
|
||||
- 10
|
||||
- 8.16
|
||||
@@ -0,0 +1,11 @@
|
||||
language: node_js
|
||||
|
||||
cache:
|
||||
npm: false
|
||||
|
||||
# Retry install on fail to avoid failing a build on network/disk/external errors
|
||||
install:
|
||||
- travis_retry npm install
|
||||
|
||||
script:
|
||||
- npm run test
|
||||
@@ -0,0 +1,15 @@
|
||||
branches:
|
||||
only:
|
||||
- master
|
||||
- next
|
||||
- beta
|
||||
- /^\d+\.(\d+|x)(\.x)?$/
|
||||
|
||||
jobs:
|
||||
include:
|
||||
- stage: release
|
||||
node_js: lts/*
|
||||
install:
|
||||
- travis_retry npm install
|
||||
script:
|
||||
- npm run semantic-release
|
||||
@@ -0,0 +1,46 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at semantic-release+coc@martynus.net. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
|
||||
|
||||
[homepage]: http://contributor-covenant.org
|
||||
[version]: http://contributor-covenant.org/version/1/4/
|
||||
+251
@@ -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 that you 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 guidelines](#documentation).
|
||||
|
||||
### Give feedback on issues
|
||||
|
||||
Some issues are created without information requested in the [Bug report guideline](#bug-report). Help make them easier to resolve by adding any relevant information.
|
||||
|
||||
Issues with the [design label](https://github.com/issues?q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3Adesign) are meant to discuss the implementation of new features. Participating in the discussion is a good opportunity to get involved and influence the future direction of **semantic-release**.
|
||||
|
||||
### Fix bugs and implement features
|
||||
|
||||
Confirmed bugs and ready-to-implement features are marked with the [help wanted label](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22). Post a comment on an issue to indicate you would like to work on it and to request help from the [@semantic-release/maintainers](https://github.com/orgs/semantic-release/teams/contributors) and the community.
|
||||
|
||||
## 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 sure the bug or feature request hasn't been already reported or fixed.
|
||||
|
||||
### Bug report
|
||||
|
||||
A good bug report shouldn't leave others needing to chase you for more information. Please try to be as detailed as possible in your report and fill the information requested in the [Bug report template](https://github.com/semantic-release/semantic-release/issues/new?template=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 requests (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project.
|
||||
|
||||
If you have never created a pull request before, welcome 🎉 😄. [Here is a great tutorial](https://opensource.guide/how-to-contribute/#opening-a-pull-request) on how to send one :)
|
||||
|
||||
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 in the title, in order to get feedback and help from the community.
|
||||
- [Allow semantic-release maintainers to make changes to your Pull Request branch](https://help.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork). This way, we can rebase it and make some minor changes if necessary. All changes we make will be done in new commit and we'll ask for your approval before merging them.
|
||||
|
||||
## Coding rules
|
||||
|
||||
### Source code
|
||||
|
||||
To ensure consistency and quality throughout the source code, all code modifications must have:
|
||||
- No [linting](#lint) errors
|
||||
- A [test](#tests) for every possible case 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 modifications 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 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 maintains a consistent state and consists 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) repositories use [XO](https://github.com/sindresorhus/xo) for linting and [Prettier](https://prettier.io) for formatting. Prettier formatting will be automatically verified and fixed by XO.
|
||||
|
||||
Before pushing your code changes make sure there are no linting errors with `npm run lint`.
|
||||
|
||||
**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 errors directly in your editor and automatically fix them on save.
|
||||
|
||||
### Tests
|
||||
|
||||
Running the integration test requires you to install [Docker](https://docs.docker.com/engine/installation) on your machine.
|
||||
|
||||
All the [semantic-release](https://github.com/semantic-release) repositories use [AVA](https://github.com/avajs/ava) for writing and running tests.
|
||||
|
||||
Before pushing your code changes make sure all **tests 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) repositories 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.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2017 Contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,29 +1,144 @@
|
||||
# semantic-release
|
||||
[](https://travis-ci.org/boennemann/semantic-release)
|
||||
[](https://david-dm.org/boennemann/semantic-release)
|
||||
[](https://david-dm.org/boennemann/semantic-release#info=devDependencies)
|
||||
<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://spectrum.chat/semantic-release">
|
||||
<img alt="Join the community on Spectrum" src="https://withspectrum.github.io/badge/badge.svg">
|
||||
</a>
|
||||
<a href="https://travis-ci.org/semantic-release/semantic-release">
|
||||
<img alt="Travis" src="https://img.shields.io/travis/semantic-release/semantic-release/master.svg">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/semantic-release/semantic-release">
|
||||
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/semantic-release/semantic-release/master.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>
|
||||
|
||||
[](https://nodei.co/npm/semantic-release/)
|
||||
**semantic-release** automates the whole package release workflow including: determining the next version number, generating the release notes and publishing the package.
|
||||
|
||||
```bash
|
||||
npm i semantic-release
|
||||
This removes the immediate connection between human emotions and version numbers, strictly following the [Semantic Versioning](http://semver.org) specification.
|
||||
|
||||
> Trust us, this will change your workflow for the better. – [egghead.io](https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release)
|
||||
|
||||
## Highlights
|
||||
|
||||
- Fully automated release
|
||||
- Enforce [Semantic Versioning](https://semver.org) specification
|
||||
- New features and fixes are immediately available to users
|
||||
- Notify maintainers and users of new releases
|
||||
- Use formalized commit message convention to document changes in the codebase
|
||||
- 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?
|
||||
|
||||
### 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 publishes 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) or [commitlint](https://github.com/conventional-changelog/commitlint) can be used to help contributors and enforce valid commit messages.
|
||||
|
||||
Here is an example of the release type that will be done based on a commit messages:
|
||||
|
||||
| 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
|
||||
|
||||
For each new commits added to the release branch (i.e. `master`) with `git push` or by merging a pull request or merging from another branch, a CI build is triggered and runs the `semantic-release` command to make a release if there are codebase changes since the last release that affect the package functionalities.
|
||||
|
||||
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. |
|
||||
| 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 based on the commits added since the last release. |
|
||||
| Verify release | Verify the release conformity. |
|
||||
| Generate notes | Generate release notes for the commits added since the last release. |
|
||||
| Create Git tag | Create a Git tag corresponding to the new release version. |
|
||||
| Prepare | Prepare the release. |
|
||||
| Publish | Publish the release. |
|
||||
| Notify | Notify of new releases or errors. |
|
||||
|
||||
## Documentation
|
||||
|
||||
- Usage
|
||||
- [Getting started](docs/usage/getting-started.md#getting-started)
|
||||
- [Installation](docs/usage/installation.md#installation)
|
||||
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
|
||||
- [Configuration](docs/usage/configuration.md#configuration)
|
||||
- [Plugins](docs/usage/plugins.md)
|
||||
- [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#ci-configurations)
|
||||
- [Git hosted services](docs/recipes/README.md#git-hosted-services)
|
||||
- [Package managers and languages](docs/recipes/README.md#package-managers-and-languages)
|
||||
- Developer guide
|
||||
- [JavaScript API](docs/developer-guide/js-api.md)
|
||||
- [Plugins development](docs/developer-guide/plugin.md)
|
||||
- [Shareable configuration development](docs/developer-guide/shareable-configuration.md)
|
||||
- Support
|
||||
- [Resources](docs/support/resources.md)
|
||||
- [Frequently Asked Questions](docs/support/FAQ.md)
|
||||
- [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)
|
||||
- [Spectrum community](https://spectrum.chat/semantic-release)
|
||||
- [Twitter](https://twitter.com/SemanticRelease)
|
||||
|
||||
## Badge
|
||||
|
||||
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)
|
||||
|
||||
```md
|
||||
[](https://github.com/semantic-release/semantic-release)
|
||||
```
|
||||
|
||||
`semantic-release` provides "prepublish" and "postpublish" hooks so you automatically release the correct version.
|
||||
## Team
|
||||
|
||||
Run `semantic-release pre` right before `npm publish` and `semantic-release post` right after.
|
||||
| [](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) |
|
||||
|
||||
For maximum comfort you can automate this inside your `package.json`:
|
||||
|
||||
```json
|
||||
"scripts": {
|
||||
"prepublish": "semantic-release pre",
|
||||
"postpublish": "semantic-release post"
|
||||
}
|
||||
```
|
||||
|
||||
Note: Even though `semantic-release` works around a limitation in npm's "prepublish" hook using it prints an error that you can *safely ignore*.
|
||||
See [npm/npm#7118](https://github.com/npm/npm/issues/7118).
|
||||
|
||||
MIT License
|
||||
2015 Stephan Bönnemann
|
||||
<p align="center">
|
||||
<img alt="Kill all humans" src="media/bender.png">
|
||||
</p>
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# Summary
|
||||
|
||||
## Usage
|
||||
- [Getting started](docs/usage/getting-started.md#getting-started)
|
||||
- [Installation](docs/usage/installation.md#installation)
|
||||
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
|
||||
- [Configuration](docs/usage/configuration.md#configuration)
|
||||
- [Plugins](docs/usage/plugins.md)
|
||||
- [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#ci-configurations)
|
||||
- [CircleCI 2.0](docs/recipes/circleci-workflows.md)
|
||||
- [Travis CI](docs/recipes/travis.md)
|
||||
- [GitLab CI](docs/recipes/gitlab-ci.md)
|
||||
- [Git hosted services](docs/recipes/README.md#git-hosted-services)
|
||||
- [Git authentication with SSH keys](docs/recipes/git-auth-ssh-keys.md)
|
||||
- [Package managers and languages](docs/recipes/README.md#package-managers-and-languages)
|
||||
|
||||
## Developer guide
|
||||
- [JavaScript API](docs/developer-guide/js-api.md)
|
||||
- [Plugin development](docs/developer-guide/plugin.md)
|
||||
- [Shareable configuration development](docs/developer-guide/shareable-configuration.md)
|
||||
|
||||
## Support
|
||||
- [Resources](docs/support/resources.md)
|
||||
- [Frequently Asked Questions](docs/support/FAQ.md)
|
||||
- [Troubleshooting](docs/support/troubleshooting.md)
|
||||
- [Node version requirement](docs/support/node-version.md)
|
||||
- [Node Support Policy](docs/support/node-support-policy.md)
|
||||
@@ -1,88 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
'use strict'
|
||||
|
||||
var abbrev = require('abbrev')
|
||||
var confirm = require('confirm-simple')
|
||||
var minimist = require('minimist')
|
||||
|
||||
var argv = minimist(process.argv.slice(2), {
|
||||
alias: {
|
||||
d: 'debug',
|
||||
dry: 'debug',
|
||||
t: 'token'
|
||||
},
|
||||
default: {
|
||||
token: process.env.GH_TOKEN || process.env.TOKEN || process.env.GITHUB_TOKEN
|
||||
}
|
||||
})
|
||||
|
||||
var npmArgv = process.env.npm_config_argv ?
|
||||
minimist(JSON.parse(process.env.npm_config_argv).cooked) :
|
||||
{_: []}
|
||||
|
||||
if (~argv._.indexOf('pre')) {
|
||||
var publish = false
|
||||
|
||||
// see src/restart.js
|
||||
if (npmArgv['semantic-release-rerun']) process.exit(0)
|
||||
// the `prepublish` hook is also executed when the package is installed
|
||||
// in this case we abort the command and do nothing.
|
||||
if (isAbbrev(npmArgv, 'install')) process.exit(0)
|
||||
|
||||
return confirmCI(function () {
|
||||
if (isAbbrev(npmArgv, 'publish')) publish = true
|
||||
|
||||
console.log('Determining new version')
|
||||
|
||||
require('../src/pre')(argv, function (err, result) {
|
||||
if (err) {
|
||||
console.log('Something went wrong.')
|
||||
throw err
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
console.log('Nothing changed. Not publishing.')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
console.log('Publishing v' + result)
|
||||
if (publish) require('../src/restart')(function (err) {
|
||||
if (err) {
|
||||
console.log('Something went wrong.')
|
||||
throw err
|
||||
}
|
||||
|
||||
process.exit(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (~argv._.indexOf('post')) {
|
||||
return confirmCI(function () {
|
||||
require('../src/post')(argv, function (err) {
|
||||
if (err) {
|
||||
console.log('Something went wrong.')
|
||||
throw err
|
||||
}
|
||||
|
||||
// see src/restart.js
|
||||
if (npmArgv['semantic-release-rerun']) {
|
||||
console.log('Everything is alright :) npm will now print an error message that you can safely ignore.')
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function confirmCI (cb) {
|
||||
if (process.env.CI || argv.ci === false) return cb(null, true)
|
||||
|
||||
confirm('Not running in a CI enviroment. Are you sure you want to run this hook?', function (ok) {
|
||||
if (!ok) process.exit(1)
|
||||
cb(null, ok)
|
||||
})
|
||||
}
|
||||
|
||||
function isAbbrev (argv, command) {
|
||||
return argv._.some(Object.prototype.hasOwnProperty.bind(abbrev(command)))
|
||||
}
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
// 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 execa = require('execa');
|
||||
var findVersions = require('find-versions');
|
||||
var pkg = require('../package.json');
|
||||
|
||||
var MIN_GIT_VERSION = '2.0.0';
|
||||
|
||||
if (!semver.satisfies(process.version, pkg.engines.node)) {
|
||||
console.error(
|
||||
`[semantic-release]: node version ${pkg.engines.node} is required. Found ${process.version}.
|
||||
|
||||
See https://github.com/semantic-release/semantic-release/blob/master/docs/support/node-version.md for more details and solutions.`
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
execa('git', ['--version'])
|
||||
.then(({stdout}) => {
|
||||
var gitVersion = findVersions(stdout)[0];
|
||||
if (semver.lt(gitVersion, MIN_GIT_VERSION)) {
|
||||
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. Found ${gitVersion}.`);
|
||||
process.exit(1);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. No git binary found.`);
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
// Node 8+ from this point on
|
||||
require('../cli')()
|
||||
.then(exitCode => {
|
||||
process.exitCode = exitCode;
|
||||
})
|
||||
.catch(() => {
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
const {argv, env, stderr} = require('process'); // eslint-disable-line node/prefer-global/process
|
||||
const util = require('util');
|
||||
const hideSensitive = require('./lib/hide-sensitive');
|
||||
|
||||
const stringList = {
|
||||
type: 'string',
|
||||
array: true,
|
||||
coerce: values =>
|
||||
values.length === 1 && values[0].trim() === 'false'
|
||||
? []
|
||||
: values.reduce((values, value) => values.concat(value.split(',').map(value => value.trim())), []),
|
||||
};
|
||||
|
||||
module.exports = async () => {
|
||||
const cli = require('yargs')
|
||||
.command('$0', 'Run automated package publishing', yargs => {
|
||||
yargs.demandCommand(0, 0).usage(`Run automated package publishing
|
||||
|
||||
Usage:
|
||||
semantic-release [options] [plugins]`);
|
||||
})
|
||||
.option('b', {alias: 'branch', describe: 'Git branch to release from', type: 'string', group: 'Options'})
|
||||
.option('r', {alias: 'repository-url', describe: 'Git repository URL', type: 'string', group: 'Options'})
|
||||
.option('t', {alias: 'tag-format', describe: 'Git tag format', type: 'string', group: 'Options'})
|
||||
.option('p', {alias: 'plugins', describe: 'Plugins', ...stringList, group: 'Options'})
|
||||
.option('e', {alias: 'extends', describe: 'Shareable configurations', ...stringList, group: 'Options'})
|
||||
.option('ci', {describe: 'Toggle CI verifications', type: 'boolean', group: 'Options'})
|
||||
.option('verify-conditions', {...stringList, group: 'Plugins'})
|
||||
.option('analyze-commits', {type: 'string', group: 'Plugins'})
|
||||
.option('verify-release', {...stringList, group: 'Plugins'})
|
||||
.option('generate-notes', {...stringList, group: 'Plugins'})
|
||||
.option('prepare', {...stringList, group: 'Plugins'})
|
||||
.option('publish', {...stringList, group: 'Plugins'})
|
||||
.option('success', {...stringList, group: 'Plugins'})
|
||||
.option('fail', {...stringList, group: 'Plugins'})
|
||||
.option('debug', {describe: 'Output debugging information', type: 'boolean', group: 'Options'})
|
||||
.option('d', {alias: 'dry-run', describe: 'Skip publishing', type: 'boolean', group: 'Options'})
|
||||
.option('h', {alias: 'help', group: 'Options'})
|
||||
.option('v', {alias: 'version', group: 'Options'})
|
||||
.strict(false)
|
||||
.exitProcess(false);
|
||||
|
||||
try {
|
||||
const {help, version, ...opts} = cli.parse(argv.slice(2));
|
||||
|
||||
if (Boolean(help) || Boolean(version)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (opts.debug) {
|
||||
// Debug must be enabled before other requires in order to work
|
||||
require('debug').enable('semantic-release:*');
|
||||
}
|
||||
|
||||
await require('.')(opts);
|
||||
return 0;
|
||||
} catch (error) {
|
||||
if (error.name !== 'YError') {
|
||||
stderr.write(hideSensitive(env)(util.inspect(error, {colors: true})));
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,7 @@
|
||||
# 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
|
||||
- [Support](support/README.md) - FAQ and troubleshooting
|
||||
@@ -0,0 +1,5 @@
|
||||
# Developer guide
|
||||
|
||||
- [JavaScript API](js-api.md)
|
||||
- [Plugins](plugin.md)
|
||||
- [Shareable configuration](shareable-configuration.md)
|
||||
@@ -0,0 +1,270 @@
|
||||
# JavaScript API
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
const semanticRelease = require('semantic-release');
|
||||
const {WritableStreamBuffer} = require('stream-buffers');
|
||||
|
||||
const stdoutBuffer = WritableStreamBuffer();
|
||||
const stderrBuffer = WritableStreamBuffer();
|
||||
|
||||
try {
|
||||
const result = await semanticRelease({
|
||||
// Core options
|
||||
branch: 'master',
|
||||
repositoryUrl: 'https://github.com/me/my-package.git',
|
||||
// Shareable config
|
||||
extends: 'my-shareable-config',
|
||||
// Plugin options
|
||||
githubUrl: 'https://my-ghe.com',
|
||||
githubApiPathPrefix: '/api-prefix'
|
||||
}, {
|
||||
// Run semantic-release from `/path/to/git/repo/root` without having to change local process `cwd` with `process.chdir()`
|
||||
cwd: '/path/to/git/repo/root',
|
||||
// Pass the variable `MY_ENV_VAR` to semantic-release without having to modify the local `process.env`
|
||||
env: {...process.env, MY_ENV_VAR: 'MY_ENV_VAR_VALUE'},
|
||||
// Store stdout and stderr to use later instead of writing to `process.stdout` and `process.stderr`
|
||||
stdout: stdoutBuffer,
|
||||
stderr: stderrBuffer
|
||||
});
|
||||
|
||||
if (result) {
|
||||
const {lastRelease, commits, nextRelease, releases} = result;
|
||||
|
||||
console.log(`Published ${nextRelease.type} release version ${nextRelease.version} containing ${commits.length} commits.`);
|
||||
|
||||
if (lastRelease.version) {
|
||||
console.log(`The last release was "${lastRelease.version}".`);
|
||||
}
|
||||
|
||||
for (const release of releases) {
|
||||
console.log(`The release was published with plugin "${release.pluginName}".`);
|
||||
}
|
||||
} else {
|
||||
console.log('No release published.');
|
||||
}
|
||||
|
||||
// Get stdout and stderr content
|
||||
const logs = stdoutBuffer.getContentsAsString('utf8');
|
||||
const errors = stderrBuffer.getContentsAsString('utf8');
|
||||
} catch (err) {
|
||||
console.error('The automated release failed with %O', err)
|
||||
}
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### semanticRelease([options], [config]) => Promise<Result>
|
||||
|
||||
Run **semantic-release** and returns a `Promise` that resolves to a [Result](#result) object.
|
||||
|
||||
#### options
|
||||
|
||||
Type: `Object`
|
||||
|
||||
**semantic-release** options.
|
||||
|
||||
Can be used to set any [core option](../usage/configuration.md#configuration) or [plugin options](../usage/plugins.md#configuration).
|
||||
|
||||
Each option, will take precedence over options configured in the [configuration file](../usage/configuration.md#configuration) and [shareable configurations](../usage/configuration.md#extends).
|
||||
|
||||
#### config
|
||||
|
||||
Type: `Object`
|
||||
|
||||
**semantic-release** configuration specific for API usage.
|
||||
|
||||
##### cwd
|
||||
|
||||
Type: `String`<br>
|
||||
Default: `process.cwd()`
|
||||
|
||||
The current working directory to use. It should be configured to the root of the Git repository to release from.
|
||||
|
||||
It allows to run **semantic-release** from a specific path without having to change the local process `cwd` with `process.chdir()`.
|
||||
|
||||
##### env
|
||||
|
||||
Type: `Object`<br>
|
||||
Default: `process.env`
|
||||
|
||||
The environment variables to use.
|
||||
|
||||
It allows to run **semantic-release** with specific environment variables without having to modify the local `process.env`.
|
||||
|
||||
##### stdout
|
||||
|
||||
Type: [`stream.Writable`](https://nodejs.org/api/stream.html#stream_writable_streams)<br>
|
||||
Default: `process.stdout`
|
||||
|
||||
The [writable stream](https://nodejs.org/api/stream.html#stream_writable_streams) used to log information.
|
||||
|
||||
It allows to configure **semantic-release** to write logs to a specific stream rather than the local `process.stdout`.
|
||||
|
||||
##### stderr
|
||||
|
||||
Type: [`stream.Writable`](https://nodejs.org/api/stream.html#stream_writable_streams)<br>
|
||||
Default: `process.stderr`
|
||||
|
||||
The [writable stream](https://nodejs.org/api/stream.html#stream_writable_streams) used to log errors.
|
||||
|
||||
It allows to configure **semantic-release** to write errors to a specific stream rather than the local `process.stderr`.
|
||||
|
||||
### Result
|
||||
|
||||
Type: `Object` `Boolean`<br>
|
||||
|
||||
And object with [`lastRelease`](#lastrelease), [`nextRelease`](#nextrelease), [`commits`](#commits) and [`releases`](#releases) if a release is published or `false` if no release was published.
|
||||
|
||||
#### lastRelease
|
||||
|
||||
Type: `Object`
|
||||
|
||||
Information related to the last release found:
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|----------------------------------------------------------------------------------------------------|
|
||||
| version | `String` | The version of the last release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the last release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the last release. |
|
||||
|
||||
**Notes**: If no previous release is found, `lastRelease` will be an empty `Object`.
|
||||
|
||||
Example:
|
||||
```js
|
||||
{
|
||||
gitHead: 'da39a3ee5e6b4b0d3255bfef95601890afd80709',
|
||||
version: '1.0.0',
|
||||
gitTag: 'v1.0.0',
|
||||
}
|
||||
```
|
||||
|
||||
#### commits
|
||||
|
||||
Type: `Array<Object>`
|
||||
|
||||
The list of commit included in the new release.<br>
|
||||
Each commit object has the following properties:
|
||||
|
||||
| Name | Type | Description |
|
||||
|-----------------|----------|-------------------------------------------------|
|
||||
| commit | `Object` | The commit abbreviated and full hash. |
|
||||
| commit.long | `String` | The commit hash. |
|
||||
| commit.short | `String` | The commit abbreviated hash. |
|
||||
| tree | `Object` | The commit abbreviated and full tree hash. |
|
||||
| tree.long | `String` | The commit tree hash. |
|
||||
| tree.short | `String` | The commit abbreviated tree hash. |
|
||||
| author | `Object` | The commit author information. |
|
||||
| author.name | `String` | The commit author name. |
|
||||
| author.email | `String` | The commit author email. |
|
||||
| author.short | `String` | The commit author date. |
|
||||
| committer | `Object` | The committer information. |
|
||||
| committer.name | `String` | The committer name. |
|
||||
| committer.email | `String` | The committer email. |
|
||||
| committer.short | `String` | The committer date. |
|
||||
| subject | `String` | The commit subject. |
|
||||
| body | `String` | The commit body. |
|
||||
| message | `String` | The commit full message (`subject` and `body`). |
|
||||
| hash | `String` | The commit hash. |
|
||||
| committerDate | `String` | The committer date. |
|
||||
|
||||
Example:
|
||||
```js
|
||||
[
|
||||
{
|
||||
commit: {
|
||||
long: '68eb2c4d778050b0701136ca129f837d7ed494d2',
|
||||
short: '68eb2c4'
|
||||
},
|
||||
tree: {
|
||||
long: '7ab515d12bd2cf431745511ac4ee13fed15ab578',
|
||||
short: '7ab515d'
|
||||
},
|
||||
author: {
|
||||
name: 'Me',
|
||||
email: 'me@email.com',
|
||||
date: 2018-07-22T20:52:44.000Z
|
||||
},
|
||||
committer: {
|
||||
name: 'Me',
|
||||
email: 'me@email.com',
|
||||
date: 2018-07-22T20:52:44.000Z
|
||||
},
|
||||
subject: 'feat: a new feature',
|
||||
body: 'Description of the new feature',
|
||||
hash: '68eb2c4d778050b0701136ca129f837d7ed494d2',
|
||||
message: 'feat: a new feature\n\nDescription of the new feature',
|
||||
committerDate: 2018-07-22T20:52:44.000Z
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
#### nextRelease
|
||||
|
||||
Type: `Object`
|
||||
|
||||
Information related to the newly published release:
|
||||
|
||||
| Name | Type | Description |
|
||||
|---------|----------|---------------------------------------------------------------------------------------------------|
|
||||
| type | `String` | The [semver](https://semver.org) type of the release (`patch`, `minor` or `major`). |
|
||||
| version | `String` | The version of the new release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the new release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the new release. |
|
||||
| notes | `String` | The release notes for the new release. |
|
||||
|
||||
Example:
|
||||
```js
|
||||
{
|
||||
type: 'minor',
|
||||
gitHead: '68eb2c4d778050b0701136ca129f837d7ed494d2',
|
||||
version: '1.1.0',
|
||||
gitTag: 'v1.1.0',
|
||||
notes: 'Release notes for version 1.1.0...',
|
||||
}
|
||||
```
|
||||
|
||||
#### releases
|
||||
|
||||
Type: `Array<Object>`
|
||||
|
||||
The list of releases published, one release per [publish plugin](../usage/plugins.md#publish-plugin).<br>
|
||||
Each release object has the following properties:
|
||||
|
||||
| Name | Type | Description |
|
||||
|------------|----------|-----------------------------------------------------------------------------------------------|
|
||||
| name | `String` | **Optional.** The release name, only if set by the corresponding `publish` plugin. |
|
||||
| url | `String` | **Optional.** The release URL, only if set by the corresponding `publish` plugin. |
|
||||
| type | `String` | The [semver](https://semver.org) type of the release (`patch`, `minor` or `major`). |
|
||||
| version | `String` | The version of the release. |
|
||||
| gitHead | `String` | The sha of the last commit being part of the release. |
|
||||
| gitTag | `String` | The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated with the release. |
|
||||
| notes | `String` | The release notes for the release. |
|
||||
| pluginName | `String` | The name of the plugin that published the release. |
|
||||
|
||||
Example:
|
||||
```js
|
||||
[
|
||||
{
|
||||
name: 'GitHub release',
|
||||
url: 'https://github.com/me/my-package/releases/tag/v1.1.0',
|
||||
type: 'minor',
|
||||
gitHead: '68eb2c4d778050b0701136ca129f837d7ed494d2',
|
||||
version: '1.1.0',
|
||||
gitTag: 'v1.1.0',
|
||||
notes: 'Release notes for version 1.1.0...',
|
||||
pluginName: '@semantic-release/github'
|
||||
},
|
||||
{
|
||||
name: 'npm package (@latest dist-tag)',
|
||||
url: 'https://www.npmjs.com/package/my-package',
|
||||
type: 'minor',
|
||||
gitHead: '68eb2c4d778050b0701136ca129f837d7ed494d2',
|
||||
version: '1.1.0',
|
||||
gitTag: 'v1.1.0',
|
||||
notes: 'Release notes for version 1.1.0...',
|
||||
pluginName: '@semantic-release/npm'
|
||||
}
|
||||
]
|
||||
```
|
||||
@@ -0,0 +1,106 @@
|
||||
# Plugin Developer Guide
|
||||
|
||||
To create a plugin for `semantic-release`, you need to decide which parts of the release lifecycle are important to that plugin. For example, it is best to always have a `verify` step because you may be receiving inputs from a user and want to make sure they exist. A plugin can abide by any of the following lifecycles:
|
||||
|
||||
- `verify`
|
||||
- `prepare`
|
||||
- `publish`
|
||||
- `success`
|
||||
- `fail`
|
||||
|
||||
`semantic-release` will require the plugin via `node` and look through the required object for methods named like the lifecyles stated above. For example, if your plugin only had a `verify` and `success` step, the `main` file for your object would need to `export` an object with `verify` and `success` functions.
|
||||
|
||||
In addition to the lifecycle methods, each lifecyle is passed two objects:
|
||||
|
||||
1. `pluginConfig` - an object containing the options that a user may pass in via their `release.config.js` file (or similar)
|
||||
2. `context` - provided by `semantic-release` for access to things like `env` variables set on the running process.
|
||||
|
||||
For each lifecycle you create, you will want to ensure it can accept `pluginConfig` and `context` as parameters.
|
||||
|
||||
## Creating a Plugin Project
|
||||
|
||||
It is recommended that you generate a new project with `yarn init`. This will provide you with a basic node project to get started with. From there, create an `index.js` file, and make sure it is specified as the `main` in the `package.json`. We will use this file to orchestrate the lifecycle methods later on.
|
||||
|
||||
Next, create a `src` or `lib` folder in the root of the project. This is where we will store our logic and code for how our lifecycle methods work. Finally, create a `test` folder so you can write tests related to your logic.
|
||||
|
||||
We recommend you setup a linting system to ensure good javascript practices are enforced. ESLint is usually the system of choice, and the configuration can be whatever you or your team fancies.
|
||||
|
||||
## Exposing Lifecycle Methods
|
||||
|
||||
In your `index.js` file, you can start by writing the following code
|
||||
|
||||
```javascript
|
||||
const verifyConditions = require('./src/verify');
|
||||
|
||||
let verified;
|
||||
|
||||
/**
|
||||
* Called by semantic-release during the verification step
|
||||
* @param {*} pluginConfig The semantic-release plugin config
|
||||
* @param {*} context The context provided by semantic-release
|
||||
*/
|
||||
async function verify(pluginConfig, context) {
|
||||
await verifyConditions(pluginConfig, context);
|
||||
verified = true;
|
||||
}
|
||||
|
||||
module.exports = { verify };
|
||||
```
|
||||
|
||||
Then, in your `src` folder, create a file called `verify.js` and add the following
|
||||
|
||||
```javascript
|
||||
const AggregateError = require('aggregate-error');
|
||||
|
||||
/**
|
||||
* A method to verify that the user has given us a slack webhook url to post to
|
||||
*/
|
||||
module.exports = async (pluginConfig, context) => {
|
||||
const { logger } = context;
|
||||
const errors = [];
|
||||
|
||||
// Throw any errors we accumulated during the validation
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
As of right now, this code won't do anything. However, if you were to run this plugin via `semantic-release`, it would run when the `verify` step occurred.
|
||||
|
||||
Following this structure, you can create different steps and checks to run through out the release process.
|
||||
|
||||
## Supporting Options
|
||||
|
||||
Let's say we want to verify that an `option` is passed. An `option` is a configuration object that is specific to your plugin. For example, the user may set an `option` in their release config like:
|
||||
|
||||
```js
|
||||
{
|
||||
prepare: {
|
||||
path: "@semantic-release/my-special-plugin"
|
||||
message: "My cool release message"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This `message` option will be passed to the `pluginConfig` object mentioned earlier. We can use the validation method we created to verify this option exists so we can perform logic based on that knowledge. In our `verify` file, we can add the following:
|
||||
|
||||
```js
|
||||
const { message } = pluginConfig;
|
||||
|
||||
if (message.length) {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
## Supporting Environment Variables
|
||||
|
||||
Similar to `options`, environment variables exist to allow users to pass tokens and set special URLs. These are set on the `context` object instead of the `pluginConfig` object. Let's say we wanted to check for `GITHUB_TOKEN` in the environment because we want to post to GitHub on the user's behalf. To do this, we can add the following to our `verify` command:
|
||||
|
||||
```js
|
||||
const { env } = context;
|
||||
|
||||
if (env.GITHUB_TOKEN) {
|
||||
//...
|
||||
}
|
||||
```
|
||||
@@ -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,97 @@
|
||||
# Plugins list
|
||||
|
||||
## Official plugins
|
||||
- [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer)
|
||||
- **Note**: this is already part of semantic-release and does not have to be installed separately
|
||||
- `analyzeCommits`: Determine the type of release by analyzing commits with [conventional-changelog](https://github.com/conventional-changelog/conventional-changelog)
|
||||
- [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator)
|
||||
- **Note**: this is already part of semantic-release and does not have to be installed separately
|
||||
- `generateNotes`: Generate release notes for the commits added since the last release with [conventional-changelog](https://github.com/conventional-changelog/conventional-changelog)
|
||||
- [@semantic-release/github](https://github.com/semantic-release/github)
|
||||
- **Note**: this is already part of semantic-release and does not have to be installed separately
|
||||
- `verifyConditions`: Verify the presence and the validity of the GitHub authentication and release configuration
|
||||
- `publish`: Publish a [GitHub release](https://help.github.com/articles/about-releases)
|
||||
- `success`: Add a comment to GitHub issues and pull requests resolved in the release
|
||||
- `fail`: Open a GitHub issue when a release fails
|
||||
- [@semantic-release/npm](https://github.com/semantic-release/npm)
|
||||
- **Note**: this is already part of semantic-release and does not have to be installed separately
|
||||
- `verifyConditions`: Verify the presence and the validity of the npm authentication and release configuration
|
||||
- `prepare`: Update the package.json version and create the npm package tarball
|
||||
- `publish`: Publish the package on the npm registry
|
||||
- [@semantic-release/gitlab](https://github.com/semantic-release/gitlab)
|
||||
- `verifyConditions`: Verify the presence and the validity of the GitLab authentication and release configuration
|
||||
- `publish`: Publish a [GitLab release](https://docs.gitlab.com/ce/workflow/releases.html)
|
||||
- [@semantic-release/git](https://github.com/semantic-release/git)
|
||||
- `verifyConditions`: Verify the presence and the validity of the Git authentication and release configuration
|
||||
- `prepare`: Push a release commit and tag, including configurable files
|
||||
- [@semantic-release/changelog](https://github.com/semantic-release/changelog)
|
||||
- `verifyConditions`: Verify the presence and the validity of the configuration
|
||||
- `prepare`: Create or update the changelog file in the local project repository
|
||||
- [@semantic-release/exec](https://github.com/semantic-release/exec)
|
||||
- `verifyConditions`: Execute a shell command to verify if the release should happen
|
||||
- `analyzeCommits`: Execute a shell command to determine the type of release
|
||||
- `verifyRelease`: Execute a shell command to verifying a release that was determined before and is about to be published
|
||||
- `generateNotes`: Execute a shell command to generate the release note
|
||||
- `prepare`: Execute a shell command to prepare the release
|
||||
- `publish`: Execute a shell command to publish the release
|
||||
- `success`: Execute a shell command to notify of a new release
|
||||
- `fail`: Execute a shell command to notify of a failed release
|
||||
- [@semantic-release/apm](https://github.com/semantic-release/apm)
|
||||
- `verifyConditions`: Verify the presence of the `ATOM_ACCESS_TOKEN` environment variable and the [`apm`](https://github.com/atom/apm) CLI
|
||||
- `prepare`: Update the `package.json` version with [`npm version`](https://docs.npmjs.com/cli/version)
|
||||
- `publish`: Publish the [Atom package](https://flight-manual.atom.io/hacking-atom/sections/publishing)
|
||||
|
||||
## Community plugins
|
||||
|
||||
[Open a Pull Request](https://github.com/semantic-release/semantic-release/blob/master/CONTRIBUTING.md#submitting-a-pull-request) to add your plugin to the list.
|
||||
|
||||
- [semantic-release-slack-bot](https://github.com/juliuscc/semantic-release-slack-bot)
|
||||
- `verifyConditions`: Verify that the environment variable `SLACK_WEBHOOK` has been defined.
|
||||
- `success`: Publish a message about the success to a slack channel.
|
||||
- `fail`: Optionally publish a message about failure to a slack channel.
|
||||
- [semantic-release-docker](https://github.com/felixfbecker/semantic-release-docker)
|
||||
- `verifyConditions`: Verify that all needed configuration is present and login to the Docker registry.
|
||||
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag
|
||||
- [semantic-release-gcr](https://github.com/carlos-cubas/semantic-release-gcr)
|
||||
- `verifyConditions`: Verify that all needed configuration is present and login to the Docker registry
|
||||
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag
|
||||
- [semantic-release-vsce](https://github.com/raix/semantic-release-vsce)
|
||||
- `verifyConditions`: Verify the presence and the validity of the vsce authentication and release configuration
|
||||
- `prepare`: Create a `.vsix` for distribution
|
||||
- `publish`: Publish the package to the Visual Studio Code marketplace
|
||||
- [semantic-release-verify-deps](https://github.com/piercus/semantic-release-verify-deps)
|
||||
- `verifyConditions`: Check the dependencies format against a regexp before a release
|
||||
- [semantic-release-chrome](https://github.com/GabrielDuarteM/semantic-release-chrome)
|
||||
- `verifyConditions`: Verify the presence of the authentication (set via environment variables)
|
||||
- `prepare`: Write the correct version to the `manifest.json` and creates a zip file of the whole dist folder
|
||||
- `publish`: Uploads the generated zip file to the webstore, and publish the item
|
||||
- [semantic-release-firefox](https://github.com/felixfbecker/semantic-release-firefox)
|
||||
- `verifyConditions`: Verify the presence of the authentication (set via environment variables)
|
||||
- `prepare`: Write the correct version to the `manifest.json`, creates a `xpi` file of the dist folder and a zip of the sources
|
||||
- `publish`: Submit the generated archives to the webstore for review, and publish the item including release notes
|
||||
- [semantic-release-gerrit](https://github.com/pascalMN/semantic-release-gerrit)
|
||||
- `generateNotes`: Generate release notes with Gerrit reviews URL
|
||||
- [semantic-release-expo](https://github.com/bycedric/semantic-release-expo)
|
||||
- `verifyConditions`: Verify Expo manifest(s) are readable and valid.
|
||||
- `prepare`: Update version, ios build number and android version code in the Expo manifest(s).
|
||||
- [maven-semantic-release](https://github.com/conveyal/maven-semantic-release)
|
||||
- `verifyConditions`: Verifies that the `pom.xml` file and other files exist and are setup to allow releases
|
||||
- `verifyRelease`: Checks and warns (does not error by default) if the version numbers found on maven central and within the Git project differ by quite a bit
|
||||
- `prepare`: Changes the version number in the `pom.xml` (or all `pom.xml` files in maven projects with multiple `pom.xml` files) and optionally creates a commit with this version number and pushes it to `master`
|
||||
- `publish`: Runs `mvn deploy` to deploy to maven central and optionally will update to next snapshot version and merge changes to development branch
|
||||
- [semantic-release-ado](https://github.com/lluchmk/semantic-release-ado)
|
||||
- `prepare`: Stores the version number as an Azure DevOps pipeline variable availabe to downstream steps on the job
|
||||
- [gradle-semantic-release](https://github.com/KengoTODA/gradle-semantic-release-plugin)
|
||||
- `verifyConditions`: Verify that project has a Gradle wrapper script, and `build.gradle` contains a task to publish artifacts.
|
||||
- `prepare`: Changes the version number in the `gradle.properties`
|
||||
- `publish`: Triggers Gradle to publish artifacts.
|
||||
- [semantic-release-circleci-orb](https://github.com/matt-oakes/semantic-release-circleci-orb)
|
||||
- `verifyConditions`: Verify the presence of the `CIRCLECI_API_TOKEN` environment variable, `orbName` option, and the `circleci` CLI.
|
||||
- `publish`: Publish the CircleCI orb.
|
||||
- [semantic-release-github-pages](https://github.com/qiwi/semantic-release-gh-pages-plugin)
|
||||
- `verifyConditions`: Verify the presence of the auth token set via environment variables.
|
||||
- `publish`: Pushes commit to the documentation branch.
|
||||
- [leiningen-semantic-release](https://github.com/NoxHarmonium/leiningen-semantic-release)
|
||||
- `verifyConditions`: Checks the project.clj is syntactically valid.
|
||||
- `prepare`: Update the project.clj version and package the output jar file.
|
||||
- `publish`: Publish the jar (and generated Maven metadata) to a maven repository (or clojars).
|
||||
@@ -0,0 +1,21 @@
|
||||
# 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
|
||||
- [@jedmao/semantic-release-npm-github-config](https://github.com/jedmao/semantic-release-npm-github-config)
|
||||
- Provides an informative [git](https://github.com/semantic-release/git) commit message for the release commit that does not trigger continuous integration and conforms to the [conventional commits specification](https://www.conventionalcommits.org/) (e.g., "chore(release): 1.2.3 [skip ci]\n\nnotes").
|
||||
- Creates a tarball that gets uploaded with each [GitHub release](https://github.com/semantic-release/github).
|
||||
- Publishes the same tarball to [npm](https://github.com/semantic-release/npm).
|
||||
- Commits the version change in `package.json`.
|
||||
- Creates or updates a [changelog](https://github.com/semantic-release/changelog) file.
|
||||
- [semantic-release-npm-github-publish](https://github.com/oleg-koval/semantic-release-npm-github-publish)
|
||||
- Based on [angular preset](https://github.com/conventional-changelog/conventional-changelog/tree/master/packages/conventional-changelog-angular).
|
||||
- Adds more keywords for the `chore` **PATCH** release.
|
||||
- Generates or updates a [changelog](https://github.com/semantic-release/changelog) file including all **PATCH** keywords (not included in default angular package).
|
||||
- Updates GitHub release with release-notes.
|
||||
- Bumps a version in package.json.
|
||||
- Publishes the new version to [NPM](https://npmjs.org).
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Recipes
|
||||
|
||||
## CI configurations
|
||||
- [CircleCI 2.0 workflows](circleci-workflows.md)
|
||||
- [Travis CI](travis.md)
|
||||
- [GitLab CI](gitlab-ci.md)
|
||||
- [GitHub Actions](github-actions.md)
|
||||
|
||||
## Git hosted services
|
||||
- [Git authentication with SSH keys](git-auth-ssh-keys.md)
|
||||
|
||||
## Package managers and languages
|
||||
@@ -0,0 +1,65 @@
|
||||
# Using semantic-release with [CircleCI 2.0 workflows](https://circleci.com/docs/2.0/workflows)
|
||||
|
||||
## Environment variables
|
||||
|
||||
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [CircleCi Project Settings](https://circleci.com/docs/2.0/env-vars/#adding-environment-variables-in-the-app)..
|
||||
|
||||
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/getting-started.md#getting-started).
|
||||
|
||||
## Multiple Node jobs configuration
|
||||
|
||||
### `.circleci/config.yml` configuration for multiple Node jobs
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [CircleCI documentation](https://circleci.com/docs/2.0) for additional configuration options.
|
||||
|
||||
This example create the workflows `test_node_4`, `test_node_6`, `test_node_8` and `release`. The release workflows will [run `semantic-release` only after the all the `test_node_*` are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
|
||||
|
||||
```yaml
|
||||
version: 2
|
||||
jobs:
|
||||
test_node_6:
|
||||
docker:
|
||||
- image: circleci/node:6
|
||||
steps:
|
||||
# Configure your test steps here (checkout, npm install, cache management, tests etc...)
|
||||
|
||||
test_node_8:
|
||||
docker:
|
||||
- image: circleci/node:8
|
||||
steps:
|
||||
# Configure your test steps here (checkout, npm install, cache management, tests etc...)
|
||||
|
||||
release:
|
||||
docker:
|
||||
- image: circleci/node:8
|
||||
steps:
|
||||
- checkout
|
||||
- run: npm install
|
||||
# Run optional required steps before releasing
|
||||
# - run: npm run build-script
|
||||
- run: npx semantic-release
|
||||
|
||||
workflows:
|
||||
version: 2
|
||||
test_and_release:
|
||||
# Run the test jobs first, then the release only when all the test jobs are successful
|
||||
jobs:
|
||||
- test_node_6
|
||||
- test_node_8
|
||||
- release:
|
||||
requires:
|
||||
- test_node_6
|
||||
- test_node_8
|
||||
```
|
||||
|
||||
### `package.json` configuration for multiple Node jobs
|
||||
|
||||
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
|
||||
|
||||
```json
|
||||
{
|
||||
"devDependencies": {
|
||||
"semantic-release": "^15.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,163 @@
|
||||
# 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.
|
||||
|
||||
**Note:** SSH keys allow to push the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated to the released version. Some plugins might also require an API token. See each plugin documentation for additional information.
|
||||
|
||||
## 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 ${SSL_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(circle): Add the encrypted private ssh key"
|
||||
$ git push
|
||||
```
|
||||
@@ -0,0 +1,68 @@
|
||||
# Using semantic-release with [GitHub Actions](https://help.github.com/en/categories/automating-your-workflow-with-github-actions)
|
||||
|
||||
## Environment variables
|
||||
|
||||
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured with [Secret Variables](https://help.github.com/en/articles/virtual-environments-for-github-actions#creating-and-using-secrets-encrypted-variables).
|
||||
|
||||
In this example an [`NPM_TOKEN`](https://docs.npmjs.com/creating-and-viewing-authentication-tokens) is required to publish a package to the npm registry. GitHub Actions [automatically populate](https://help.github.com/en/articles/virtual-environments-for-github-actions#github_token-secret) a [`GITHUB_TOKEN`](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line) environment variable which can be used in Workflows.
|
||||
|
||||
## Node project configuration
|
||||
|
||||
[GitHub Actions](https://github.com/features/actions) support [Workflows](https://help.github.com/en/articles/configuring-workflows), allowing to run tests on multiple Node versions and publish a release only when all test pass.
|
||||
|
||||
**Note**: The publish pipeline must run on [Node version >= 8.16](../support/FAQ.md#why-does-semantic-release-require-node-version--816).
|
||||
|
||||
### `.github/workflows/release.yml` configuration for Node projects
|
||||
|
||||
The following is a minimal configuration for [`semantic-release`](https://github.com/semantic-release/semantic-release) with a build running on Node 12 when a new commit is pushed to a `master` branch. See [Configuring a Workflow](https://help.github.com/en/articles/configuring-a-workflow) for additional configuration options.
|
||||
|
||||
```yaml
|
||||
name: Release
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
jobs:
|
||||
release:
|
||||
name: Release
|
||||
runs-on: ubuntu-18.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v1
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v1
|
||||
with:
|
||||
node-version: 12
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
- name: Release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npx semantic-release
|
||||
```
|
||||
|
||||
## Pushing `package.json` changes to a `master` branch
|
||||
|
||||
To keep `package.json` updated in the `master` branch, [`@semantic-release/git`](https://github.com/semantic-release/git) plugin can be used.
|
||||
|
||||
**Note**: Automatically populated `GITHUB_TOKEN` cannot be used if branch protection is enabled for the target branch. It is **not** advised to mitigate this limitation by overriding an automatically populated `GITHUB_TOKEN` variable with a [Personal Access Tokens](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line), as it poses a security risk. Since Secret Variables are available for Workflows triggered by any branch, it becomes a potential vector of attack, where a Workflow triggered from a non-protected branch can expose and use a token with elevated permissions, yielding branch protection insignificant. One can use Personal Access Tokens in trusted environments, where all developers should have the ability to perform administrative actions in the given repository and branch protection is enabled solely for convenience purposes, to remind about required reviews or CI checks.
|
||||
|
||||
## Trigger semantic-release on demand
|
||||
|
||||
There is a way to trigger semantic-relase on demand. Use [`repository_dispatch`](https://help.github.com/en/articles/events-that-trigger-workflows#external-events-repository_dispatch) event to have control on when to generate a release by making an HTTP request, e.g.:
|
||||
|
||||
```yaml
|
||||
name: Release
|
||||
on:
|
||||
repository_dispatch:
|
||||
types: [semantic-release]
|
||||
jobs:
|
||||
# ...
|
||||
```
|
||||
|
||||
To trigger a release, call (with a [Personal Access Tokens](https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line) stored in `GITHUB_TOKEN` environment variable):
|
||||
|
||||
```
|
||||
$ curl -v -H "Accept: application/vnd.github.everest-preview+json" -H "Authorization: token ${GITHUB_TOKEN}" https://api.github.com/repos/[org-name-or-username]/[repository]/dispatches -d '{ "event_type": "semantic-release" }'
|
||||
```
|
||||
@@ -0,0 +1,59 @@
|
||||
# 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 [Protected variables](https://docs.gitlab.com/ce/ci/variables/README.html#protected-environment-variables).
|
||||
|
||||
**Note**: Make sure to configure your release branch as [protected](https://docs.gitlab.com/ce/user/project/protected_branches.html) in order for the CI/CD build to access the protected variables.
|
||||
|
||||
## Node project configuration
|
||||
|
||||
GitLab CI supports [Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html) allowing to test on multiple Node versions and publishing a release only when all test pass.
|
||||
|
||||
**Note**: The publish pipeline must run a [Node >= 8.16 version](../support/FAQ.md#why-does-semantic-release-require-node-version--816).
|
||||
|
||||
### `.gitlab-ci.yml` configuration for Node projects
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [GitLab CI - Configuration of your jobs with .gitlab-ci.yml](https://docs.gitlab.com/ee/ci/yaml/README.html) for additional configuration options.
|
||||
|
||||
**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: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:
|
||||
- npx 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": "^15.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,95 @@
|
||||
# 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/getting-started.md#getting-started).
|
||||
|
||||
## Node.js projects configuration
|
||||
|
||||
### `.travis.yml` configuration for multiple Node.js jobs
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
|
||||
|
||||
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
|
||||
|
||||
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
|
||||
|
||||
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
|
||||
|
||||
**Advanced configuration**: Running the tests in the `script` step of the `release` stage is not necessary as the previous stage(s) already ran them. To increase speed, the `script` step of the `release` stage can be overwritten to skip the tests. Note that other commands such as build or compilation might still be required.
|
||||
|
||||
```yaml
|
||||
language: node_js
|
||||
|
||||
node_js:
|
||||
- 8
|
||||
- 6
|
||||
|
||||
jobs:
|
||||
include:
|
||||
# Define the release stage that runs semantic-release
|
||||
- stage: release
|
||||
node_js: lts/*
|
||||
# Advanced: optionally overwrite your default `script` step to skip the tests
|
||||
# script: skip
|
||||
deploy:
|
||||
provider: script
|
||||
skip_cleanup: true
|
||||
script:
|
||||
- npx semantic-release
|
||||
```
|
||||
|
||||
### `package.json` configuration for multiple Node jobs
|
||||
|
||||
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
|
||||
|
||||
```json
|
||||
{
|
||||
"devDependencies": {
|
||||
"semantic-release": "^15.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Non-Node.js projects configuration
|
||||
|
||||
For projects that require to be tested with one or multiple version of a Non-JavaScript [language](https://docs.travis-ci.com/user/languages), optionally on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
|
||||
|
||||
This recipe cover the Travis specifics only. See [Non JavaScript projects recipe](../support/FAQ.md#can-i-use-semantic-release-to-publish-non-javascript-packages) for more information on the **semantic-release** configuration.
|
||||
|
||||
### `.travis.yml` configuration for non-JavaScript projects
|
||||
|
||||
This example is a minimal configuration for **semantic-release** with a build running [Go 1.6 and 1.7](https://docs.travis-ci.com/user/languages/go). See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
|
||||
|
||||
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
|
||||
|
||||
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
|
||||
|
||||
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
|
||||
|
||||
**Advanced configuration**: Running the tests in the `script` step of the `release` stage is not necessary as the previous stage(s) already ran them. To increase speed, the `script` step of the `release` stage can be overwritten to skip the tests. Note that other commands such as build or compilation might still be required.
|
||||
|
||||
```yaml
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.6
|
||||
- 1.7
|
||||
|
||||
jobs:
|
||||
include:
|
||||
# Define the release stage that runs semantic-release
|
||||
- stage: release
|
||||
# Advanced: optionally overwrite your default `script` step to skip the tests
|
||||
# script:
|
||||
# - make
|
||||
deploy:
|
||||
provider: script
|
||||
skip_cleanup: true
|
||||
script:
|
||||
# Use nvm to install and use the Node LTS version (nvm is installed on all Travis images)
|
||||
- nvm install lts/*
|
||||
- npx semantic-release
|
||||
```
|
||||
@@ -0,0 +1,245 @@
|
||||
# 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 contain the version, which is the only place where it is *really* required, but the updated `package.json` will not be pushed to the Git repository
|
||||
|
||||
However, the [`@semantic-release/git`](https://github.com/semantic-release/git) plugin can be used to push the updated `package.json` as well as other files to the Git repository.
|
||||
|
||||
## 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 the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin uses the [npm CLI](https://docs.npmjs.com/cli/npm) to update the `package.json` version and publish the package, all [npm hook scripts](https://docs.npmjs.com/misc/scripts#description) will be executed.
|
||||
|
||||
You can run your build script in:
|
||||
- the `prepublishOnly` or `prepack` hook so it will be executed during the `publish` step of `@semantic-release/npm`
|
||||
- the `postversion` hook so it will be executed during the `prepare` step of `@semantic-release/npm`, which allow for example to update files before committing them with the [`@semantic-release/git`](https://github.com/semantic-release/git) plugin
|
||||
|
||||
If using npm hook scripts is not possible, and alternative solution is to [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin to run your script in the `prepare` step:
|
||||
```json
|
||||
{
|
||||
"plugins": [
|
||||
"@semantic-release/commit-analyzer",
|
||||
"@semantic-release/release-notes-generator",
|
||||
"@semantic-release/npm",
|
||||
["@semantic-release/exec", {
|
||||
"prepareCmd": "./my-build-script.sh ${nextRelease.version}",
|
||||
}],
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Is there a way to preview which version would currently get published?
|
||||
|
||||
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.16](#why-does-semantic-release-require-node-version--816) 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.16.
|
||||
|
||||
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 global add semantic-release && semantic-release
|
||||
```
|
||||
|
||||
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
|
||||
|
||||
As `semantic-release` is recommended to be executed with [`npx`](https://www.npmjs.com/package/npx) an alternative is required for usage with Yarn. Even though it is possible to install npx with Yarn, it's not recommended. Yarn and npx would be using different cache locations.
|
||||
|
||||
For [local installation](../usage/installation.md#local-installation) replace
|
||||
`npx semantic-release` with `yarn run semantic-release`.
|
||||
|
||||
For [global installation](../usage/installation.md#global-installation) replace
|
||||
`npx semantic-release` with `yarn global add semantic-release && semantic-release`.
|
||||
|
||||
## 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.16](#why-does-semantic-release-require-node-version--816) to execute the `semantic-release` command
|
||||
|
||||
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
|
||||
|
||||
In addition you will need to configure the **semantic-release** [plugins](../usage/plugins.md#plugins) to disable the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin which is used by default and use a plugin for your project type.
|
||||
|
||||
If there is no specific plugin for your project type you can use the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin to publish the release with a shell command.
|
||||
|
||||
Here is a basic example to create [GitHub releases](https://help.github.com/articles/about-releases) and use a shell command to publish:
|
||||
|
||||
```json
|
||||
{
|
||||
"plugins": [
|
||||
"@semantic-release/commit-analyzer",
|
||||
"@semantic-release/release-notes-generator",
|
||||
"@semantic-release/github",
|
||||
["@semantic-release/exec", {
|
||||
"prepareCmd" : "set-version ${nextRelease.version}",
|
||||
"publishCmd" : "publish-package"
|
||||
}]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Note**: This is a theoretical example where the command `set-version` update the project version with the value passed as its first argument and `publish-package` publishes the package to a registry.
|
||||
|
||||
See the [package managers and languages recipes](../recipes/README.md#package-managers-and-languages) for more details on specific project types.
|
||||
|
||||
## 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](../recipes/README.md#ci-configurations) for more details on specific CI environments.
|
||||
|
||||
## Can I run semantic-release on my local machine rather than on a CI server?
|
||||
|
||||
Yes, you can by explicitly setting the [`--no-ci` CLI option](../usage/configuration.md#ci) 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> npx 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).
|
||||
|
||||
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.
|
||||
|
||||
## How can I revert a release?
|
||||
|
||||
If you have introduced a breaking bug in a release you have 2 options:
|
||||
- If you have a fix immediately ready, commit and push it (or merge it via a pull request) to the release branch
|
||||
- Otherwise, [revert the commit](https://git-scm.com/docs/git-revert) that introduced the bug and push the revert commit (or merge it via a pull request) to the release branch
|
||||
|
||||
In both cases **semantic-release** will publish a new release, so your package users will get the fixed/reverted version.
|
||||
|
||||
Depending on the package manager you are using, you might be able to un-publish or deprecate a release, in order to prevent users from downloading it by accident. For example, npm allows you to [un-publish](https://docs.npmjs.com/cli/unpublish) [within 72 hours](https://www.npmjs.com/policies/unpublish) after release. You may also [deprecate](https://docs.npmjs.com/cli/deprecate) a release if you would rather avoid un-publishing.
|
||||
|
||||
In any case **do not remove the Git tag associated with the buggy version**, otherwise **semantic-release** will later try to republish that version. Publishing a version after un-publishing is not supported by most package managers.
|
||||
|
||||
**Note**: If you are using the default [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines) be aware that it uses a different revert commit format than the standard one created by [git revert](https://git-scm.com/docs/git-revert), contrary to what is [claimed in the convention](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#revert). Therefore, if you revert a commit with [`git revert`](https://git-scm.com/docs/git-revert), use the [`--edit` option](https://git-scm.com/docs/git-revert#git-revert---edit) to format the message according to the [Angular revert commit message format](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#revert). See [conventional-changelog/conventional-changelog#348](https://github.com/conventional-changelog/conventional-changelog/issues/348) 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.
|
||||
|
||||
## How can I change the type of commits that trigger a release?
|
||||
|
||||
By default **semantic-release** uses the [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines) and triggers releases based on the following rules:
|
||||
|
||||
| Commit | Release type |
|
||||
|-----------------------------|----------------------------|
|
||||
| Commit with breaking change | ~~Major~~ Breaking release |
|
||||
| Commit with type `feat` | ~~Minor~~ Feature release |
|
||||
| Commit with type `fix` | Patch release |
|
||||
| Commit with type `perf` | Patch release |
|
||||
|
||||
See the [`@semantic-release/npm`](https://github.com/semantic-release/npm#npm-configuration) plugin documentation for more details.
|
||||
|
||||
This is fully customizable with the [`@semantic-release/commit-analyzer`](https://github.com/semantic-release/commit-analyzer) plugin's [`release-rules` option](https://github.com/semantic-release/commit-analyzer#release-rules).
|
||||
|
||||
## 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.
|
||||
|
||||
**Note**: Only the codebase changes altering the published package will trigger a release (for example new features, bug fixes or performance improvements would trigger a release while refactoring or changing code style would not). See [How can I change the type of commits that trigger a release?](#how-can-i-change-the-type-of-commits-that-trigger-a-release) for more details.
|
||||
|
||||
## 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.16?
|
||||
|
||||
**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.16 or higher**.
|
||||
|
||||
See [Node version requirement](./node-version.md#node-version-requirement) for more details and solutions.
|
||||
|
||||
## What is npx?
|
||||
|
||||
[`npx`](https://www.npmjs.com/package/npx) – short for "npm exec" – is a CLI to find and execute npm binaries within the local `node_modules` folder or in the $PATH. If a binary can't be located npx will download the required package and execute it from its cache location.
|
||||
The tool is bundled with [npm](https://www.npmjs.com/package/npm) >= 5.2, or can be installed via `npm install -g npx`.
|
||||
For more details and motivation read the [introductory blog post](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) by [@zkat](https://github.com/zkat).
|
||||
@@ -0,0 +1,7 @@
|
||||
# Support
|
||||
|
||||
- [Resources](resources.md) - Videos, articles and tutorials
|
||||
- [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,35 @@
|
||||
# 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.16 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.16
|
||||
|
||||
The recommended approach is to run the `semantic-release` command from a CI job running on Node 8.16 or higher. This can either be a job used by your project to test on Node >= 8.16 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` is included with npm >= 5.2 and can be used to download the latest [Node 8 package published on npm](https://www.npmjs.com/package/node). Use it to execute the `semantic-release` command.
|
||||
|
||||
```bash
|
||||
$ npx -p node@8 -c "npx semantic-release"
|
||||
```
|
||||
|
||||
**Note:**: See [What is npx](./FAQ.md#what-is-npx) for more details.
|
||||
|
||||
### Use `nvm`
|
||||
|
||||
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can use it to switch to Node 8 before running the `semantic-release` command.
|
||||
|
||||
```bash
|
||||
$ nvm install 8 && npx semantic-release
|
||||
```
|
||||
@@ -0,0 +1,20 @@
|
||||
# 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)
|
||||
- ["Introduction to Semantic Release" - liv](https://blog.greenkeeper.io/introduction-to-semantic-release-33f73b117c8)
|
||||
|
||||
## Tutorials
|
||||
|
||||
- ["How to Write a JavaScript Library - Automating Releases with semantic-release" – egghead.io](https://egghead.io/lessons/javascript-automating-releases-with-semantic-release)
|
||||
@@ -0,0 +1,56 @@
|
||||
# Troubleshooting
|
||||
|
||||
## You do not have permission to publish 'package-name'
|
||||
|
||||
When running semantic-release you might encounter the following error:
|
||||
|
||||
```bash
|
||||
npm ERR! publish Failed PUT 403
|
||||
npm ERR! code E403
|
||||
npm ERR! You do not have permission to publish "<package-name>". Are you logged in as the correct user? : <package-name>
|
||||
```
|
||||
|
||||
This is most likely related to a misconfiguration of the [npm registry authentication](https://github.com/semantic-release/npm#npm-registry-authentication) or to your user [missing permission](https://docs.npmjs.com/cli/team) for publishing.
|
||||
|
||||
It might also happen if the package name you are trying to publish already exists (in the case of npm, you may be trying to publish a new version of a package that is not yours, hence the permission error).
|
||||
|
||||
To verify if your package name is available you can use [npm-name-cli](https://github.com/sindresorhus/npm-name-cli):
|
||||
```bash
|
||||
$ npm install --global npm-name-cli
|
||||
$ npm-name <package-name>
|
||||
```
|
||||
|
||||
If the package name is not available, change it in your `package.json` or consider using an [npm scope](https://docs.npmjs.com/misc/scope).
|
||||
|
||||
## Squashed commits are ignored by **semantic-release**
|
||||
|
||||
**semantic-release** parses commits according to a [commit message convention](https://github.com/semantic-release/semantic-release#commit-message-format) to figure out how they affect the codebase. Commits that doesn't follow the project's commit message convention are simply ignored.
|
||||
|
||||
When [squashing commits](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#_squashing) most Git tools will by default generate a new commit message with a summary of the squashed commits. This commit message will most likely not be compliant with the project's commit message convention and therefore will be ignored by **semantic-release**.
|
||||
|
||||
When squashing commits make sure to rewrite the resulting commit message to be compliant with the project's commit message convention.
|
||||
|
||||
**Note**: if the resulting squashed commit would encompasses multiple changes (for example multiple unrelated features or fixes) then it's probably not a good idea to squash those commits together. A commit should contain exactly one self-contained functional change and a functional change should be contained in exactly one commit. See [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit).
|
||||
|
||||
## `reference already exists` error when pushing tag
|
||||
|
||||
**semantic-release** read [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging) that are present in the history of your release branch in order to determine the last release published. Then it determines the next version to release based on the commits pushed since then and create the corresponding tag.
|
||||
If a tag with the name already in your repository, Git will throw and error as tags must be unique across the repository.
|
||||
This situation happens when you have a version tag identical to the new one **semantic-release** is trying to create that is not in the history of the current branch.
|
||||
|
||||
If an actual release with that version number was published you need to merge all the commits up to that release into your release branch.
|
||||
|
||||
If there is no published release with that version number, the tag must be deleted.
|
||||
|
||||
```bash
|
||||
# Verify if the commit exists in the repository
|
||||
$ git rev-list -1 <tag name>
|
||||
# If a commit sha is returned, then the tag exists
|
||||
|
||||
# Verify the branches having the tagged commit in their history
|
||||
$ git branch --contains <tag name>
|
||||
|
||||
# Delete the tag
|
||||
$ git tag -d <tag name>
|
||||
$ git push origin :refs/tags/<tag name>
|
||||
```
|
||||
@@ -0,0 +1,8 @@
|
||||
# Usage
|
||||
|
||||
- [Getting started](getting-started.md#getting-started)
|
||||
- [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,48 @@
|
||||
# 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.
|
||||
Here is a few example of the CI services that can be used to achieve this:
|
||||
- [Travis Build Stages](https://docs.travis-ci.com/user/build-stages)
|
||||
- [CircleCI Workflows](https://circleci.com/docs/2.0/workflows)
|
||||
- [GitHub Actions](https://github.com/features/actions)
|
||||
- [Codeship Deployment Pipelines](https://documentation.codeship.com/basic/builds-and-configuration/deployment-pipelines)
|
||||
- [GitLab Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html#introduction-to-pipelines-and-jobs)
|
||||
- [Codefresh Pipelines](https://codefresh.io/docs/docs/configure-ci-cd-pipeline/introduction-to-codefresh-pipelines)
|
||||
- [Wercker Workflows](http://devcenter.wercker.com/docs/workflows)
|
||||
- [GoCD Pipelines](https://docs.gocd.org/current/introduction/concepts_in_go.html#pipeline).
|
||||
|
||||
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
|
||||
|
||||
## Authentication
|
||||
|
||||
### Push access to the remote repository
|
||||
|
||||
**semantic-release** requires push access to the project Git repository in order to create [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). The Git authentication can be set with one of the following environment variables:
|
||||
|
||||
| Variable | Description |
|
||||
|---------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `GH_TOKEN` or `GITHUB_TOKEN` | A GitHub [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line). |
|
||||
| `GL_TOKEN` or `GITLAB_TOKEN` | A GitLab [personal access token](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html). |
|
||||
| `BB_TOKEN` or `BITBUCKET_TOKEN` | A Bitbucket [personal access token](https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html). |
|
||||
| `GIT_CREDENTIALS` | [URL encoded](https://en.wikipedia.org/wiki/Percent-encoding) Git username and password in the format `<username>:<password>`. The username and password must each be individually URL encoded, not the `:` separating them. |
|
||||
|
||||
Alternatively the Git authentication can be set up via [SSH keys](../recipes/git-auth-ssh-keys.md).
|
||||
|
||||
### Authentication for plugins
|
||||
|
||||
Most **semantic-release** [plugins](plugins.md) require setting up authentication in order to publish to a package manager registry. The default [@semantic-release/npm](https://github.com/semantic-release/npm#environment-variables) and [@semantic-release/github](https://github.com/semantic-release/github#environment-variables) plugins require the following environment variables:
|
||||
|
||||
| Variable | Description |
|
||||
|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `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's documentation for the environment variables required.
|
||||
|
||||
The authentication token/credentials have to be made available in the CI service via environment variables.
|
||||
|
||||
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on how to configure environment variables in your CI service.
|
||||
|
||||
**Note**: The environment variables `GH_TOKEN`, `GITHUB_TOKEN`, `GL_TOKEN` and `GITLAB_TOKEN` can be used for both the Git authentication and the API authentication required by [@semantic-release/github](https://github.com/semantic-release/github) and [@semantic-release/gitlab](https://github.com/semantic-release/gitlab).
|
||||
@@ -0,0 +1,162 @@
|
||||
# Configuration
|
||||
|
||||
**semantic-release** configuration consists of:
|
||||
- Git repository ([URL](#repositoryurl) and options [release branch](#branch) and [tag format](#tagformat))
|
||||
- Plugins [declaration](#plugins) and options
|
||||
- Run mode ([debug](#debug), [dry run](#dryrun) and [local (no CI)](#ci))
|
||||
|
||||
All of these options can be configured through config file, CLI arguments or by extending a [shareable configuration](shareable-configurations.md).
|
||||
|
||||
Additionally, metadata of Git tags generated by **semantic-release** can be customized via standard [Git environment variables](#git-environment-variables).
|
||||
|
||||
## Configuration file
|
||||
|
||||
**semantic-release**’s [options](#options), mode and [plugins](plugins.md) can be set via either:
|
||||
- A `.releaserc` file, written in YAML or JSON, with optional extensions: .`yaml`/`.yml`/`.json`/`.js`
|
||||
- A `release.config.js` file that exports an object
|
||||
- A `release` key in the project's `package.json` file
|
||||
|
||||
Alternatively, some options can be set via CLI arguments.
|
||||
|
||||
The following three examples are the same.
|
||||
|
||||
- Via `release` key in the project's `package.json` file:
|
||||
```json
|
||||
{
|
||||
"release": {
|
||||
"branch": "next"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- Via `.releaserc` file:
|
||||
```json
|
||||
{
|
||||
"branch": "next"
|
||||
}
|
||||
```
|
||||
|
||||
- Via CLI argument:
|
||||
```bash
|
||||
$ semantic-release --branch next
|
||||
```
|
||||
|
||||
**Note**: CLI arguments take precedence over options configured in the configuration file.
|
||||
|
||||
**Note**: Plugin options cannot be defined via CLI arguments and must be defined in the configuration file.
|
||||
|
||||
**Note**: When configuring via `package.json`, the configuration must be under the `release` property. However, when using a `.releaserc` or a `release.config.js` file, the configuration must be set without a `release` property.
|
||||
|
||||
## Options
|
||||
|
||||
### extends
|
||||
|
||||
Type: `Array`, `String`<br>
|
||||
CLI arguments: `-e`, `--extends`
|
||||
|
||||
List of modules or file paths containing a [shareable configuration](shareable-configurations.md). If multiple shareable configurations 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`<br>
|
||||
Default: `master`<br>
|
||||
CLI arguments: `-b`, `--branch`
|
||||
|
||||
The branch on which releases should happen.
|
||||
|
||||
### repositoryUrl
|
||||
|
||||
Type: `String`<br>
|
||||
Default: `repository` property in `package.json` or [git origin url](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes)<br>
|
||||
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)).
|
||||
|
||||
### tagFormat
|
||||
|
||||
Type: `String`<br>
|
||||
Default: `v${version}`<br>
|
||||
CLI arguments: `-t`, `--tag-format`
|
||||
|
||||
The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) format used by **semantic-release** to identify releases. The tag name is generated with [Lodash template](https://lodash.com/docs#template) and will be compiled with the `version` variable.
|
||||
|
||||
**Note**: The `tagFormat` must contain the `version` variable exactly once and compile to a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description).
|
||||
|
||||
### plugins
|
||||
|
||||
Type: `Array`<br>
|
||||
Default: `['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator', '@semantic-release/npm', '@semantic-release/github']`<br>
|
||||
CLI arguments: `-p`, `--plugins`
|
||||
|
||||
Define the list of plugins to use. Plugins will run in series, in the order defined, for each [steps](../../README.md#release-steps) if they implement it.
|
||||
|
||||
Plugins configuration can defined by wrapping the name and an options object in an array.
|
||||
|
||||
See [Plugins configuration](plugins.md#plugins) for more details.
|
||||
|
||||
### dryRun
|
||||
|
||||
Type: `Boolean`<br>
|
||||
Default: `false` if running in a CI environment, `true` otherwise<br>
|
||||
CLI arguments: `-d`, `--dry-run`
|
||||
|
||||
Dry-run mode, skip publishing, print next version and release notes.
|
||||
|
||||
### ci
|
||||
|
||||
Type: `Boolean`<br>
|
||||
Default: `true`<br>
|
||||
CLI arguments: `--ci` / `--no-ci`
|
||||
|
||||
Set to `false` to skip Continuous Integration environment verifications. This allows for making releases from a local machine.
|
||||
|
||||
**Note**: The CLI arguments `--no-ci` is equivalent to `--ci false`.
|
||||
|
||||
### debug
|
||||
|
||||
Type: `Boolean`<br>
|
||||
Default: `false`<br>
|
||||
CLI argument: `--debug`
|
||||
|
||||
Output debugging information. This can also be enabled by setting the `DEBUG` environment variable to `semantic-release:*`.
|
||||
|
||||
**Note**: The `debug` is used only supported via CLI argument. To enable debug mode from the [JS API](../developer-guide/js-api.md#javascript-api) use `require('debug').enable('semantic-release:*')`.
|
||||
|
||||
## Git environment variables
|
||||
|
||||
| Variable | Description | Default |
|
||||
|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------|
|
||||
| `GIT_AUTHOR_NAME` | The author name associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot. |
|
||||
| `GIT_AUTHOR_EMAIL` | The author email associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot email address. |
|
||||
| `GIT_COMMITTER_NAME` | The committer name associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot. |
|
||||
| `GIT_COMMITTER_EMAIL` | The committer email associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot email address. |
|
||||
|
||||
## Existing version tags
|
||||
|
||||
**semantic-release** uses [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging) to determine the commits added since the last release.
|
||||
If a release has been published before setting up **semantic-release** you must make sure the most recent commit included in the last published release is in the [release branch](#branch) history and is tagged with the version released, formatted according to the [tag format](#tagformat) configured (defaults to `vx.y.z`).
|
||||
|
||||
If the previous releases were published with [`npm publish`](https://docs.npmjs.com/cli/publish) this should already be the case.
|
||||
|
||||
For example, if your release branch is `master`, the last release published on your project is `1.1.0` and the last commit included has the sha `1234567`, you must make sure this commit is in `master` history and is tagged with `v1.1.0`.
|
||||
|
||||
```bash
|
||||
# Make sure the commit 1234567 is in the release branch history
|
||||
$ git branch --contains 1234567
|
||||
|
||||
# If the commit is not in the branch history it means that either:
|
||||
# - you use a different branch than the one your release from before
|
||||
# - or the commit sha has been rewritten (with git rebase)
|
||||
# In both cases you need to configure your repository to have the last release commit in the history of the release branch
|
||||
|
||||
# List the tags for the commit 1234567
|
||||
$ git tag --contains 1234567
|
||||
|
||||
# If v1.1.0 is not in the list you add it with
|
||||
$ git tag v1.1.0 1234567
|
||||
$ git push origin v1.1.0
|
||||
```
|
||||
@@ -0,0 +1,22 @@
|
||||
# Getting started
|
||||
|
||||
In order to use **semantic-release** you must follow these steps:
|
||||
1. [Install](./installation.md#installation) **semantic-release** in your project
|
||||
2. Configure your Continuous Integration service to [run **semantic-release**](./ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
|
||||
3. Configure your Git repository and package manager repository [authentication](ci-configuration.md#authentication) in your Continuous Integration service
|
||||
4. Configure **semantic-release** [options and plugins](./configuration.md#configuration)
|
||||
|
||||
Alternatively those steps can be easily done with the [**semantic-release** interactive CLI](https://github.com/semantic-release/cli):
|
||||
|
||||
```bash
|
||||
npm install -g semantic-release-cli
|
||||
|
||||
cd your-module
|
||||
semantic-release-cli setup
|
||||
```
|
||||
|
||||

|
||||
|
||||
See the [semantic-release-cli](https://github.com/semantic-release/cli#what-it-does) documentation for more details.
|
||||
|
||||
**Note**: only a limited number of options, CI services and plugins are currently supported by `semantic-release-cli`.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Installation
|
||||
|
||||
## Local installation
|
||||
|
||||
For [Node modules projects](https://docs.npmjs.com/getting-started/creating-node-modules) we recommend installing **semantic-release** locally and running the `semantic-release` command with [npx](https://www.npmjs.com/package/npx):
|
||||
|
||||
```bash
|
||||
$ npm install --save-dev semantic-release
|
||||
```
|
||||
|
||||
Then in the CI environment:
|
||||
|
||||
```bash
|
||||
$ npx semantic-release
|
||||
```
|
||||
|
||||
**Note:** `npx` is a tool bundled with `npm@>=5.2.0`. It is used to conveniently find the semantic-release binary and to execute it. See [What is npx](../support/FAQ.md#what-is-npx) for more details.
|
||||
|
||||
## Global installation
|
||||
|
||||
For other type of projects we recommend installing **semantic-release** directly in the CI environment, also with [npx](https://www.npmjs.com/package/npx):
|
||||
|
||||
```bash
|
||||
$ npx semantic-release
|
||||
```
|
||||
|
||||
**Note**: For a global installation, it's recommended to specify the major **semantic-release** version to install (for example with with `npx semantic-release@15`). This way your build will not automatically use the next major **semantic-release** release that could possibly break your build. You will have to upgrade manually when a new major version is released.
|
||||
|
||||
**Note**: `npx` is a tool bundled with `npm@>=5.2.0`. It is used to conveniently install the semantic-release binary and to execute it. See [What is npx](../support/FAQ.md#what-is-npx) for more details.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Plugins
|
||||
|
||||
Each [release step](../../README.md#release-steps) is implemented by configurable plugins. This allows for support of different [commit message formats](../../README.md#commit-message-format), release note generators and publishing platforms.
|
||||
|
||||
A plugin is a npm module that can implement one or more of the following steps:
|
||||
|
||||
| Step | Required | Description |
|
||||
|--------------------|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `verifyConditions` | No | Responsible for verifying conditions necessary to proceed with the release: configuration is correct, authentication token are valid, etc... |
|
||||
| `analyzeCommits` | Yes | Responsible for determining the type of the next release (`major`, `minor` or `patch`). If multiple plugins with a `analyzeCommits` step are defined, the release type will be the highest one among plugins output. |
|
||||
| `verifyRelease` | No | Responsible for verifying the parameters (version, type, dist-tag etc...) of the release that is about to be published. |
|
||||
| `generateNotes` | No | Responsible for generating the content of the release note. If multiple plugins with a `generateNotes` step are defined, the release notes will be the result of the concatenation of each plugin output. |
|
||||
| `prepare` | No | Responsible for preparing the release, for example creating or updating files such as `package.json`, `CHANGELOG.md`, documentation or compiled assets and pushing a commit. |
|
||||
| `publish` | No | Responsible for publishing the release. |
|
||||
| `success` | No | Responsible for notifying of a new release. |
|
||||
| `fail` | No | Responsible for notifying of a failed release. |
|
||||
|
||||
**Note:** If no plugin with a `analyzeCommits` step is defined `@semantic-release/commit-analyzer` will be used.
|
||||
|
||||
## Plugins installation
|
||||
|
||||
### Default plugins
|
||||
|
||||
These four plugins are already part of **semantic-release** and don't have to be installed separately:
|
||||
```
|
||||
"@semantic-release/commit-analyzer"
|
||||
"@semantic-release/github"
|
||||
"@semantic-release/npm"
|
||||
"@semantic-release/release-notes-generator"
|
||||
```
|
||||
|
||||
### Additional plugins
|
||||
|
||||
[Additional plugins](../extending/plugins-list.md) have to be installed via npm:
|
||||
|
||||
```bash
|
||||
$ npm install @semantic-release/git @semantic-release/changelog -D
|
||||
```
|
||||
|
||||
## Plugins declaration and execution order
|
||||
|
||||
Each plugin must be configured with the [`plugins` options](./configuration.md#plugins) by specifying the list of plugins by npm module name.
|
||||
|
||||
```json
|
||||
{
|
||||
"plugins": ["@semantic-release/commit-analyzer", "@semantic-release/release-notes-generator", "@semantic-release/npm"]
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** If the `plugins` option is defined, it overrides the default plugin list, rather than merging with it.
|
||||
|
||||
For each [release step](../../README.md#release-steps) the plugins that implement that step will be executed in the order in which they are defined.
|
||||
|
||||
```json
|
||||
{
|
||||
"plugins": [
|
||||
"@semantic-release/commit-analyzer",
|
||||
"@semantic-release/release-notes-generator",
|
||||
"@semantic-release/npm",
|
||||
"@semantic-release/git"
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
With this configuration **semantic-release** will:
|
||||
- execute the `verifyConditions` implementation of `@semantic-release/npm` then `@semantic-release/git`
|
||||
- execute the `analyzeCommits` implementation of `@semantic-release/commit-analyzer`
|
||||
- execute the `prepare` implementation of `@semantic-release/npm` then `@semantic-release/git`
|
||||
- execute the `generateNotes` implementation of `@semantic-release/release-notes-generator`
|
||||
- execute the `publish` implementation of `@semantic-release/npm`
|
||||
|
||||
## Plugin options configuration
|
||||
|
||||
A plugin configuration can be specified by wrapping the name and an options object in an array. Options configured this way will be passed only to that specific plugin.
|
||||
|
||||
Global plugin configuration can be defined at the root of the **semantic-release** configuration object. Options configured this way will be passed to all plugins.
|
||||
|
||||
```json
|
||||
{
|
||||
"plugins": [
|
||||
"@semantic-release/commit-analyzer",
|
||||
"@semantic-release/release-notes-generator",
|
||||
["@semantic-release/github", {
|
||||
"assets": ["dist/**"]
|
||||
}],
|
||||
"@semantic-release/git"
|
||||
],
|
||||
"preset": "angular"
|
||||
}
|
||||
```
|
||||
|
||||
With this configuration:
|
||||
- All plugins will receive the `preset` option, which will be used by both `@semantic-release/commit-analyzer` and `@semantic-release/release-notes-generator` (and ignored by `@semantic-release/github` and `@semantic-release/git`)
|
||||
- The `@semantic-release/github` plugin will receive the `assets` options (`@semantic-release/git` will not receive it and therefore will use it's default value for that option)
|
||||
@@ -0,0 +1,7 @@
|
||||
# Shareable configurations
|
||||
|
||||
A shareable configuration is an [npm](https://www.npmjs.com/) package that exports a **semantic-release** configuration object. It allows for use of the same configuration across several projects.
|
||||
|
||||
The shareable configurations to use can be set with the [extends](configuration.md#extends) option.
|
||||
|
||||
See [shareable configurations list](../extending/shareable-configurations-list.md).
|
||||
@@ -0,0 +1,182 @@
|
||||
/* eslint require-atomic-updates: off */
|
||||
|
||||
const {template, pick} = require('lodash');
|
||||
const marked = require('marked');
|
||||
const TerminalRenderer = require('marked-terminal');
|
||||
const envCi = require('env-ci');
|
||||
const hookStd = require('hook-std');
|
||||
const pkg = require('./package.json');
|
||||
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 {extractErrors} = require('./lib/utils');
|
||||
const getGitAuthUrl = require('./lib/get-git-auth-url');
|
||||
const getLogger = require('./lib/get-logger');
|
||||
const {fetch, verifyAuth, isBranchUpToDate, getGitHead, tag, push} = require('./lib/git');
|
||||
const getError = require('./lib/get-error');
|
||||
const {COMMIT_NAME, COMMIT_EMAIL} = require('./lib/definitions/constants');
|
||||
|
||||
marked.setOptions({renderer: new TerminalRenderer()});
|
||||
|
||||
async function run(context, plugins) {
|
||||
const {cwd, env, options, logger} = context;
|
||||
const {isCi, branch: ciBranch, isPr} = envCi({env, cwd});
|
||||
|
||||
if (!isCi && !options.dryRun && !options.noCi) {
|
||||
logger.warn('This run was not triggered in a known CI environment, running in dry-run mode.');
|
||||
options.dryRun = true;
|
||||
} else {
|
||||
// When running on CI, set the commits author and commiter info and prevent the `git` CLI to prompt for username/password. See #703.
|
||||
Object.assign(env, {
|
||||
GIT_AUTHOR_NAME: COMMIT_NAME,
|
||||
GIT_AUTHOR_EMAIL: COMMIT_EMAIL,
|
||||
GIT_COMMITTER_NAME: COMMIT_NAME,
|
||||
GIT_COMMITTER_EMAIL: COMMIT_EMAIL,
|
||||
...env,
|
||||
GIT_ASKPASS: 'echo',
|
||||
GIT_TERMINAL_PROMPT: 0,
|
||||
});
|
||||
}
|
||||
|
||||
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 false;
|
||||
}
|
||||
|
||||
if (ciBranch !== options.branch) {
|
||||
logger.log(
|
||||
`This test run was triggered on the branch ${ciBranch}, while semantic-release is configured to only publish from ${options.branch}, therefore a new version won’t be published.`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
logger[options.dryRun ? 'warn' : 'success'](
|
||||
`Run automated release from branch ${ciBranch}${options.dryRun ? ' in dry-run mode' : ''}`
|
||||
);
|
||||
|
||||
await verify(context);
|
||||
|
||||
options.repositoryUrl = await getGitAuthUrl(context);
|
||||
|
||||
try {
|
||||
try {
|
||||
await verifyAuth(options.repositoryUrl, options.branch, {cwd, env});
|
||||
} catch (error) {
|
||||
if (!(await isBranchUpToDate(options.repositoryUrl, options.branch, {cwd, env}))) {
|
||||
logger.log(
|
||||
`The local branch ${options.branch} is behind the remote one, therefore a new version won't be published.`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`The command "${error.command}" failed with the error message ${error.stderr}.`);
|
||||
throw getError('EGITNOPERMISSION', {options});
|
||||
}
|
||||
|
||||
logger.success(`Allowed to push to the Git repository`);
|
||||
|
||||
await plugins.verifyConditions(context);
|
||||
|
||||
await fetch(options.repositoryUrl, {cwd, env});
|
||||
|
||||
context.lastRelease = await getLastRelease(context);
|
||||
context.commits = await getCommits(context);
|
||||
|
||||
const nextRelease = {type: await plugins.analyzeCommits(context), gitHead: await getGitHead({cwd, env})};
|
||||
|
||||
if (!nextRelease.type) {
|
||||
logger.log('There are no relevant changes, so no new version is released.');
|
||||
return false;
|
||||
}
|
||||
|
||||
context.nextRelease = nextRelease;
|
||||
nextRelease.version = getNextVersion(context);
|
||||
nextRelease.gitTag = template(options.tagFormat)({version: nextRelease.version});
|
||||
|
||||
await plugins.verifyRelease(context);
|
||||
|
||||
nextRelease.notes = await plugins.generateNotes(context);
|
||||
|
||||
await plugins.prepare(context);
|
||||
|
||||
if (options.dryRun) {
|
||||
logger.warn(`Skip ${nextRelease.gitTag} tag creation in dry-run mode`);
|
||||
} else {
|
||||
// Create the tag before calling the publish plugins as some require the tag to exists
|
||||
await tag(nextRelease.gitTag, {cwd, env});
|
||||
await push(options.repositoryUrl, {cwd, env});
|
||||
logger.success(`Created tag ${nextRelease.gitTag}`);
|
||||
}
|
||||
|
||||
context.releases = await plugins.publish(context);
|
||||
|
||||
await plugins.success(context);
|
||||
|
||||
logger.success(`Published release ${nextRelease.version}`);
|
||||
|
||||
if (options.dryRun) {
|
||||
logger.log(`Release note for version ${nextRelease.version}:`);
|
||||
if (nextRelease.notes) {
|
||||
context.stdout.write(marked(nextRelease.notes));
|
||||
}
|
||||
}
|
||||
|
||||
return pick(context, ['lastRelease', 'commits', 'nextRelease', 'releases']);
|
||||
}
|
||||
|
||||
function logErrors({logger, stderr}, err) {
|
||||
const errors = extractErrors(err).sort(error => (error.semanticRelease ? -1 : 0));
|
||||
for (const error of errors) {
|
||||
if (error.semanticRelease) {
|
||||
logger.error(`${error.code} ${error.message}`);
|
||||
if (error.details) {
|
||||
stderr.write(marked(error.details));
|
||||
}
|
||||
} else {
|
||||
logger.error('An error occurred while running semantic-release: %O', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function callFail(context, plugins, err) {
|
||||
const errors = extractErrors(err).filter(err => err.semanticRelease);
|
||||
if (errors.length > 0) {
|
||||
try {
|
||||
await plugins.fail({...context, errors});
|
||||
} catch (error) {
|
||||
logErrors(context, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = async (opts = {}, {cwd = process.cwd(), env = process.env, stdout, stderr} = {}) => {
|
||||
const {unhook} = hookStd(
|
||||
{silent: false, streams: [process.stdout, process.stderr, stdout, stderr].filter(Boolean)},
|
||||
hideSensitive(env)
|
||||
);
|
||||
const context = {cwd, env, stdout: stdout || process.stdout, stderr: stderr || process.stderr};
|
||||
context.logger = getLogger(context);
|
||||
context.logger.log(`Running ${pkg.name} version ${pkg.version}`);
|
||||
try {
|
||||
const {plugins, options} = await getConfig(context, opts);
|
||||
context.options = options;
|
||||
try {
|
||||
const result = await run(context, plugins);
|
||||
unhook();
|
||||
return result;
|
||||
} catch (error) {
|
||||
await callFail(context, plugins, error);
|
||||
throw error;
|
||||
}
|
||||
} catch (error) {
|
||||
logErrors(context, error);
|
||||
unhook();
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
const RELEASE_TYPE = ['prerelease', 'prepatch', 'patch', 'preminor', 'minor', 'premajor', 'major'];
|
||||
|
||||
const FIRST_RELEASE = '1.0.0';
|
||||
|
||||
const COMMIT_NAME = 'semantic-release-bot';
|
||||
|
||||
const COMMIT_EMAIL = 'semantic-release-bot@martynus.net';
|
||||
|
||||
const RELEASE_NOTES_SEPARATOR = '\n\n';
|
||||
|
||||
const SECRET_REPLACEMENT = '[secure]';
|
||||
|
||||
const SECRET_MIN_SIZE = 5;
|
||||
|
||||
module.exports = {
|
||||
RELEASE_TYPE,
|
||||
FIRST_RELEASE,
|
||||
COMMIT_NAME,
|
||||
COMMIT_EMAIL,
|
||||
RELEASE_NOTES_SEPARATOR,
|
||||
SECRET_REPLACEMENT,
|
||||
SECRET_MIN_SIZE,
|
||||
};
|
||||
@@ -0,0 +1,128 @@
|
||||
const {inspect} = require('util');
|
||||
const {toLower, isString} = require('lodash');
|
||||
const pkg = require('../../package.json');
|
||||
const {RELEASE_TYPE} = require('./constants');
|
||||
|
||||
const [homepage] = pkg.homepage.split('#');
|
||||
const stringify = obj => (isString(obj) ? obj : inspect(obj, {breakLength: Infinity, depth: 2, maxArrayLength: 5}));
|
||||
const linkify = file => `${homepage}/blob/master/${file}`;
|
||||
|
||||
module.exports = {
|
||||
ENOGITREPO: ({cwd}) => ({
|
||||
message: 'Not running from a git repository.',
|
||||
details: `The \`semantic-release\` command must be executed from a Git repository.
|
||||
|
||||
The current working directory is \`${cwd}\`.
|
||||
|
||||
Please verify your CI configuration to make sure the \`semantic-release\` command is executed from the root of the cloned repository.`,
|
||||
}),
|
||||
ENOREPOURL: () => ({
|
||||
message: 'The `repositoryUrl` option is required.',
|
||||
details: `The [repositoryUrl option](${linkify(
|
||||
'docs/usage/configuration.md#repositoryurl'
|
||||
)}) cannot be determined from the semantic-release configuration, the \`package.json\` nor the [git origin url](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes).
|
||||
|
||||
Please make sure to add the \`repositoryUrl\` to the [semantic-release configuration] (${linkify(
|
||||
'docs/usage/configuration.md'
|
||||
)}).`,
|
||||
}),
|
||||
EGITNOPERMISSION: ({options}) => ({
|
||||
message: 'Cannot push to the Git repository.',
|
||||
details: `**semantic-release** cannot push the version tag to the branch \`${
|
||||
options.branch
|
||||
}\` on the remote Git repository with URL \`${options.repositoryUrl}\`.
|
||||
|
||||
This can be caused by:
|
||||
- a misconfiguration of the [repositoryUrl](${linkify('docs/usage/configuration.md#repositoryurl')}) option
|
||||
- the repository being unavailable
|
||||
- or missing push permission for the user configured via the [Git credentials on your CI environment](${linkify(
|
||||
'docs/usage/ci-configuration.md#authentication'
|
||||
)})`,
|
||||
}),
|
||||
EINVALIDTAGFORMAT: ({tagFormat}) => ({
|
||||
message: 'Invalid `tagFormat` option.',
|
||||
details: `The [tagFormat](${linkify(
|
||||
'docs/usage/configuration.md#tagformat'
|
||||
)}) must compile to a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description).
|
||||
|
||||
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
|
||||
}),
|
||||
ETAGNOVERSION: ({tagFormat}) => ({
|
||||
message: 'Invalid `tagFormat` option.',
|
||||
details: `The [tagFormat](${linkify(
|
||||
'docs/usage/configuration.md#tagformat'
|
||||
)}) option must contain the variable \`version\` exactly once.
|
||||
|
||||
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
|
||||
}),
|
||||
EPLUGINCONF: ({type, required, pluginConf}) => ({
|
||||
message: `The \`${type}\` plugin configuration is invalid.`,
|
||||
details: `The [${type} plugin configuration](${linkify(`docs/usage/plugins.md#${toLower(type)}-plugin`)}) ${
|
||||
required ? 'is required and ' : ''
|
||||
} must be a single or an array of plugins definition. A plugin definition is an npm module name, optionnaly wrapped in an array with an object.
|
||||
|
||||
Your configuration for the \`${type}\` plugin is \`${stringify(pluginConf)}\`.`,
|
||||
}),
|
||||
EPLUGINSCONF: ({plugin}) => ({
|
||||
message: 'The `plugins` configuration is invalid.',
|
||||
details: `The [plugins](${linkify(
|
||||
'docs/usage/configuration.md#plugins'
|
||||
)}) option must be an array of plugin definions. A plugin definition is an npm module name, optionnaly wrapped in an array with an object.
|
||||
|
||||
The invalid configuration is \`${stringify(plugin)}\`.`,
|
||||
}),
|
||||
EPLUGIN: ({pluginName, type}) => ({
|
||||
message: `A plugin configured in the step ${type} is not a valid semantic-release plugin.`,
|
||||
details: `A valid \`${type}\` **semantic-release** plugin must be a function or an object with a function in the property \`${type}\`.
|
||||
|
||||
The plugin \`${pluginName}\` doesn't have the property \`${type}\` and cannot be used for the \`${type}\` step.
|
||||
|
||||
Please refer to the \`${pluginName}\` and [semantic-release plugins configuration](${linkify(
|
||||
'docs/usage/plugins.md'
|
||||
)}) documentation for more details.`,
|
||||
}),
|
||||
EANALYZECOMMITSOUTPUT: ({result, pluginName}) => ({
|
||||
message: 'The `analyzeCommits` plugin returned an invalid value. It must return a valid semver release type.',
|
||||
details: `The \`analyzeCommits\` plugin must return a valid [semver](https://semver.org) release type. The valid values are: ${RELEASE_TYPE.map(
|
||||
type => `\`${type}\``
|
||||
).join(', ')}.
|
||||
|
||||
The \`analyzeCommits\` function of the \`${pluginName}\` returned \`${stringify(result)}\` instead.
|
||||
|
||||
We recommend to report the issue to the \`${pluginName}\` authors, providing the following informations:
|
||||
- The **semantic-release** version: \`${pkg.version}\`
|
||||
- The **semantic-release** logs from your CI job
|
||||
- The value returned by the plugin: \`${stringify(result)}\`
|
||||
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
|
||||
'docs/developer-guide/plugin.md'
|
||||
)})`,
|
||||
}),
|
||||
EGENERATENOTESOUTPUT: ({result, pluginName}) => ({
|
||||
message: 'The `generateNotes` plugin returned an invalid value. It must return a `String`.',
|
||||
details: `The \`generateNotes\` plugin must return a \`String\`.
|
||||
|
||||
The \`generateNotes\` function of the \`${pluginName}\` returned \`${stringify(result)}\` instead.
|
||||
|
||||
We recommend to report the issue to the \`${pluginName}\` authors, providing the following informations:
|
||||
- The **semantic-release** version: \`${pkg.version}\`
|
||||
- The **semantic-release** logs from your CI job
|
||||
- The value returned by the plugin: \`${stringify(result)}\`
|
||||
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
|
||||
'docs/developer-guide/plugin.md'
|
||||
)})`,
|
||||
}),
|
||||
EPUBLISHOUTPUT: ({result, pluginName}) => ({
|
||||
message: 'A `publish` plugin returned an invalid value. It must return an `Object`.',
|
||||
details: `The \`publish\` plugins must return an \`Object\`.
|
||||
|
||||
The \`publish\` function of the \`${pluginName}\` returned \`${stringify(result)}\` instead.
|
||||
|
||||
We recommend to report the issue to the \`${pluginName}\` authors, providing the following informations:
|
||||
- The **semantic-release** version: \`${pkg.version}\`
|
||||
- The **semantic-release** logs from your CI job
|
||||
- The value returned by the plugin: \`${stringify(result)}\`
|
||||
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
|
||||
'docs/developer-guide/plugin.md'
|
||||
)})`,
|
||||
}),
|
||||
};
|
||||
@@ -0,0 +1,95 @@
|
||||
/* eslint require-atomic-updates: off */
|
||||
|
||||
const {isString, isPlainObject} = require('lodash');
|
||||
const {getGitHead} = require('../git');
|
||||
const hideSensitive = require('../hide-sensitive');
|
||||
const {hideSensitiveValues} = require('../utils');
|
||||
const {RELEASE_TYPE, RELEASE_NOTES_SEPARATOR} = require('./constants');
|
||||
|
||||
module.exports = {
|
||||
verifyConditions: {
|
||||
required: false,
|
||||
dryRun: true,
|
||||
pipelineConfig: () => ({settleAll: true}),
|
||||
},
|
||||
analyzeCommits: {
|
||||
default: ['@semantic-release/commit-analyzer'],
|
||||
required: true,
|
||||
dryRun: true,
|
||||
outputValidator: output => !output || RELEASE_TYPE.includes(output),
|
||||
preprocess: ({commits, ...inputs}) => ({
|
||||
...inputs,
|
||||
commits: commits.filter(commit => !/\[skip\s+release\]|\[release\s+skip\]/i.test(commit.message)),
|
||||
}),
|
||||
postprocess: results =>
|
||||
RELEASE_TYPE[
|
||||
results.reduce((highest, result) => {
|
||||
const typeIndex = RELEASE_TYPE.indexOf(result);
|
||||
return typeIndex > highest ? typeIndex : highest;
|
||||
}, -1)
|
||||
],
|
||||
},
|
||||
verifyRelease: {
|
||||
required: false,
|
||||
dryRun: true,
|
||||
pipelineConfig: () => ({settleAll: true}),
|
||||
},
|
||||
generateNotes: {
|
||||
required: false,
|
||||
dryRun: true,
|
||||
outputValidator: output => !output || isString(output),
|
||||
pipelineConfig: () => ({
|
||||
getNextInput: ({nextRelease, ...context}, notes) => ({
|
||||
...context,
|
||||
nextRelease: {
|
||||
...nextRelease,
|
||||
notes: `${nextRelease.notes ? `${nextRelease.notes}${RELEASE_NOTES_SEPARATOR}` : ''}${notes}`,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
postprocess: (results, {env}) => hideSensitive(env)(results.filter(Boolean).join(RELEASE_NOTES_SEPARATOR)),
|
||||
},
|
||||
prepare: {
|
||||
required: false,
|
||||
dryRun: false,
|
||||
pipelineConfig: ({generateNotes}) => ({
|
||||
getNextInput: async context => {
|
||||
const newGitHead = await getGitHead({cwd: context.cwd});
|
||||
// If previous prepare plugin has created a commit (gitHead changed)
|
||||
if (context.nextRelease.gitHead !== newGitHead) {
|
||||
context.nextRelease.gitHead = newGitHead;
|
||||
// Regenerate the release notes
|
||||
context.nextRelease.notes = await generateNotes(context);
|
||||
}
|
||||
|
||||
// Call the next prepare plugin with the updated `nextRelease`
|
||||
return context;
|
||||
},
|
||||
}),
|
||||
},
|
||||
publish: {
|
||||
required: false,
|
||||
dryRun: false,
|
||||
outputValidator: output => !output || isPlainObject(output),
|
||||
pipelineConfig: () => ({
|
||||
// Add `nextRelease` and plugin properties to published release
|
||||
transform: (release, step, {nextRelease}) => ({
|
||||
...(release === false ? {} : nextRelease),
|
||||
...release,
|
||||
...step,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
success: {
|
||||
required: false,
|
||||
dryRun: false,
|
||||
pipelineConfig: () => ({settleAll: true}),
|
||||
preprocess: ({releases, env, ...inputs}) => ({...inputs, env, releases: hideSensitiveValues(env, releases)}),
|
||||
},
|
||||
fail: {
|
||||
required: false,
|
||||
dryRun: false,
|
||||
pipelineConfig: () => ({settleAll: true}),
|
||||
preprocess: ({errors, env, ...inputs}) => ({...inputs, env, errors: hideSensitiveValues(env, errors)}),
|
||||
},
|
||||
};
|
||||
@@ -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 {Object} context semantic-release context.
|
||||
*
|
||||
* @return {Promise<Array<Object>>} The list of commits on the branch `branch` since the last release.
|
||||
*/
|
||||
module.exports = async ({cwd, env, lastRelease: {gitHead}, logger}) => {
|
||||
if (gitHead) {
|
||||
debug('Use gitHead: %s', gitHead);
|
||||
} else {
|
||||
logger.log('No previous release found, retrieving all commits');
|
||||
}
|
||||
|
||||
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
|
||||
const commits = (
|
||||
await getStream.array(
|
||||
gitLogParser.parse({_: `${gitHead ? gitHead + '..' : ''}HEAD`}, {cwd, env: {...process.env, ...env}})
|
||||
)
|
||||
).map(commit => {
|
||||
commit.message = commit.message.trim();
|
||||
commit.gitTags = commit.gitTags.trim();
|
||||
return commit;
|
||||
});
|
||||
logger.log(`Found ${commits.length} commits since last release`);
|
||||
debug('Parsed commits: %o', commits);
|
||||
return commits;
|
||||
};
|
||||
@@ -0,0 +1,90 @@
|
||||
const {castArray, pickBy, isNil, isString, isPlainObject} = require('lodash');
|
||||
const readPkgUp = require('read-pkg-up');
|
||||
const {cosmiconfig} = require('cosmiconfig');
|
||||
const resolveFrom = require('resolve-from');
|
||||
const debug = require('debug')('semantic-release:config');
|
||||
const {repoUrl} = require('./git');
|
||||
const PLUGINS_DEFINITIONS = require('./definitions/plugins');
|
||||
const plugins = require('./plugins');
|
||||
const {validatePlugin, parseConfig} = require('./plugins/utils');
|
||||
|
||||
const CONFIG_NAME = 'release';
|
||||
const CONFIG_FILES = [
|
||||
'package.json',
|
||||
`.${CONFIG_NAME}rc`,
|
||||
`.${CONFIG_NAME}rc.json`,
|
||||
`.${CONFIG_NAME}rc.yaml`,
|
||||
`.${CONFIG_NAME}rc.yml`,
|
||||
`.${CONFIG_NAME}rc.js`,
|
||||
`${CONFIG_NAME}.config.js`,
|
||||
];
|
||||
|
||||
module.exports = async (context, opts) => {
|
||||
const {cwd, env} = context;
|
||||
const {config, filepath} = (await cosmiconfig(CONFIG_NAME, {searchPlaces: CONFIG_FILES}).search(cwd)) || {};
|
||||
|
||||
debug('load config from: %s', filepath);
|
||||
|
||||
// Merge config file options and CLI/API options
|
||||
let options = {...config, ...opts};
|
||||
if (options.ci === false) {
|
||||
options.noCi = true;
|
||||
}
|
||||
|
||||
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(cwd, extendPath));
|
||||
|
||||
// For each plugin defined in a shareable config, save in `pluginsPath` the extendable config path,
|
||||
// so those plugin will be loaded relatively to the config file
|
||||
Object.entries(extendsOpts)
|
||||
.filter(([, value]) => Boolean(value))
|
||||
.reduce((pluginsPath, [option, value]) => {
|
||||
castArray(value).forEach(plugin => {
|
||||
if (option === 'plugins' && validatePlugin(plugin)) {
|
||||
pluginsPath[parseConfig(plugin)[0]] = extendPath;
|
||||
} else if (
|
||||
PLUGINS_DEFINITIONS[option] &&
|
||||
(isString(plugin) || (isPlainObject(plugin) && isString(plugin.path)))
|
||||
) {
|
||||
pluginsPath[isString(plugin) ? plugin : plugin.path] = extendPath;
|
||||
}
|
||||
});
|
||||
return pluginsPath;
|
||||
}, pluginsPath);
|
||||
|
||||
return {...result, ...extendsOpts};
|
||||
}, {}),
|
||||
...options,
|
||||
};
|
||||
}
|
||||
|
||||
// Set default options values if not defined yet
|
||||
options = {
|
||||
branch: 'master',
|
||||
repositoryUrl: (await pkgRepoUrl({normalize: false, cwd})) || (await repoUrl({cwd, env})),
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: [
|
||||
'@semantic-release/commit-analyzer',
|
||||
'@semantic-release/release-notes-generator',
|
||||
'@semantic-release/npm',
|
||||
'@semantic-release/github',
|
||||
],
|
||||
// Remove `null` and `undefined` options so they can be replaced with default ones
|
||||
...pickBy(options, option => !isNil(option)),
|
||||
};
|
||||
|
||||
debug('options values: %O', options);
|
||||
|
||||
return {options, plugins: await plugins({...context, options}, pluginsPath)};
|
||||
};
|
||||
|
||||
async function pkgRepoUrl(opts) {
|
||||
const {packageJson} = (await readPkgUp(opts)) || {};
|
||||
return packageJson && (isPlainObject(packageJson.repository) ? packageJson.repository.url : packageJson.repository);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
const ERROR_DEFINITIONS = require('./definitions/errors');
|
||||
|
||||
module.exports = (code, ctx = {}) => {
|
||||
const {message, details} = ERROR_DEFINITIONS[code](ctx);
|
||||
return new SemanticReleaseError(message, code, details);
|
||||
};
|
||||
@@ -0,0 +1,65 @@
|
||||
const {parse, format} = require('url'); // eslint-disable-line node/no-deprecated-api
|
||||
const {isNil} = require('lodash');
|
||||
const hostedGitInfo = require('hosted-git-info');
|
||||
const {verifyAuth} = require('./git');
|
||||
|
||||
/**
|
||||
* Determine the the git repository URL to use to push, either:
|
||||
* - The `repositoryUrl` as is if allowed to push
|
||||
* - The `repositoryUrl` converted to `https` or `http` with Basic Authentication
|
||||
*
|
||||
* In addition, expand shortcut URLs (`owner/repo` => `https://github.com/owner/repo.git`) and transform `git+https` / `git+http` URLs to `https` / `http`.
|
||||
*
|
||||
* @param {Object} context semantic-release context.
|
||||
*
|
||||
* @return {String} The formatted Git repository URL.
|
||||
*/
|
||||
module.exports = async ({cwd, env, options: {repositoryUrl, branch}}) => {
|
||||
const GIT_TOKENS = {
|
||||
GIT_CREDENTIALS: undefined,
|
||||
GH_TOKEN: undefined,
|
||||
// GitHub Actions require the "x-access-token:" prefix for git access
|
||||
// https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#http-based-git-access-by-an-installation
|
||||
GITHUB_TOKEN: isNil(env.GITHUB_ACTION) ? undefined : 'x-access-token:',
|
||||
GL_TOKEN: 'gitlab-ci-token:',
|
||||
GITLAB_TOKEN: 'gitlab-ci-token:',
|
||||
BB_TOKEN: 'x-token-auth:',
|
||||
BITBUCKET_TOKEN: 'x-token-auth:',
|
||||
};
|
||||
|
||||
const info = hostedGitInfo.fromUrl(repositoryUrl, {noGitPlus: true});
|
||||
const {protocol, ...parsed} = parse(repositoryUrl);
|
||||
|
||||
if (info && info.getDefaultRepresentation() === 'shortcut') {
|
||||
// Expand shorthand URLs (such as `owner/repo` or `gitlab:owner/repo`)
|
||||
repositoryUrl = info.https();
|
||||
} else if (protocol && protocol.includes('http')) {
|
||||
// Replace `git+https` and `git+http` with `https` or `http`
|
||||
repositoryUrl = format({...parsed, protocol: protocol.includes('https') ? 'https' : 'http', href: null});
|
||||
}
|
||||
|
||||
// Test if push is allowed without transforming the URL (e.g. is ssh keys are set up)
|
||||
try {
|
||||
await verifyAuth(repositoryUrl, branch, {cwd, env});
|
||||
} catch (_) {
|
||||
const envVar = Object.keys(GIT_TOKENS).find(envVar => !isNil(env[envVar]));
|
||||
const gitCredentials = `${GIT_TOKENS[envVar] || ''}${env[envVar] || ''}`;
|
||||
|
||||
if (gitCredentials) {
|
||||
// If credentials are set via environment variables, convert the URL to http/https and add basic auth, otherwise return `repositoryUrl` as is
|
||||
const [match, auth, host, path] = /^(?!.+:\/\/)(?:(.*)@)?(.*?):(.*)$/.exec(repositoryUrl) || [];
|
||||
const {port, hostname, ...parsed} = parse(
|
||||
match ? `ssh://${auth ? `${auth}@` : ''}${host}/${path}` : repositoryUrl
|
||||
);
|
||||
|
||||
return format({
|
||||
...parsed,
|
||||
auth: gitCredentials,
|
||||
host: `${hostname}${protocol === 'ssh:' ? '' : port ? `:${port}` : ''}`,
|
||||
protocol: protocol && /http[^s]/.test(protocol) ? 'http' : 'https',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return repositoryUrl;
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
const {escapeRegExp, template} = require('lodash');
|
||||
const semver = require('semver');
|
||||
const pLocate = require('p-locate');
|
||||
const debug = require('debug')('semantic-release:get-last-release');
|
||||
const {getTags, isRefInHistory, getTagHead} = require('./git');
|
||||
|
||||
/**
|
||||
* 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 or doesn't match the `tagFormat`
|
||||
* - Sort the versions
|
||||
* - Retrive the highest version
|
||||
*
|
||||
* @param {Object} context semantic-release context.
|
||||
*
|
||||
* @return {Promise<LastRelease>} The last tagged release or `undefined` if none is found.
|
||||
*/
|
||||
module.exports = async ({cwd, env, options: {tagFormat}, logger}) => {
|
||||
// Generate a regex to parse tags formatted with `tagFormat`
|
||||
// by replacing the `version` variable in the template by `(.+)`.
|
||||
// The `tagFormat` is compiled with space as the `version` as it's an invalid tag character,
|
||||
// so it's guaranteed to not be present in the `tagFormat`.
|
||||
const tagRegexp = `^${escapeRegExp(template(tagFormat)({version: ' '})).replace(' ', '(.+)')}`;
|
||||
const tags = (await getTags({cwd, env}))
|
||||
.map(tag => ({gitTag: tag, version: (tag.match(tagRegexp) || new Array(2))[1]}))
|
||||
.filter(
|
||||
tag => tag.version && semver.valid(semver.clean(tag.version)) && !semver.prerelease(semver.clean(tag.version))
|
||||
)
|
||||
.sort((a, b) => semver.rcompare(a.version, b.version));
|
||||
|
||||
debug('found tags: %o', tags);
|
||||
|
||||
const tag = await pLocate(tags, tag => isRefInHistory(tag.gitTag, {cwd, env}), {preserveOrder: true});
|
||||
|
||||
if (tag) {
|
||||
logger.log(`Found git tag ${tag.gitTag} associated with version ${tag.version}`);
|
||||
return {gitHead: await getTagHead(tag.gitTag, {cwd, env}), ...tag};
|
||||
}
|
||||
|
||||
logger.log('No git tag version found');
|
||||
return {};
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
const {Signale} = require('signale');
|
||||
const figures = require('figures');
|
||||
|
||||
module.exports = ({stdout, stderr}) =>
|
||||
new Signale({
|
||||
config: {displayTimestamp: true, underlineMessage: false, displayLabel: false},
|
||||
disabled: false,
|
||||
interactive: false,
|
||||
scope: 'semantic-release',
|
||||
stream: [stdout],
|
||||
types: {
|
||||
error: {badge: figures.cross, color: 'red', label: '', stream: [stderr]},
|
||||
log: {badge: figures.info, color: 'magenta', label: '', stream: [stdout]},
|
||||
success: {badge: figures.tick, color: 'green', label: '', stream: [stdout]},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
const semver = require('semver');
|
||||
const {FIRST_RELEASE} = require('./definitions/constants');
|
||||
|
||||
module.exports = ({nextRelease: {type}, lastRelease, logger}) => {
|
||||
let version;
|
||||
if (lastRelease.version) {
|
||||
version = semver.inc(lastRelease.version, type);
|
||||
logger.log(`The next release version is ${version}`);
|
||||
} else {
|
||||
version = FIRST_RELEASE;
|
||||
logger.log(`There is no previous release, the next release version is ${version}`);
|
||||
}
|
||||
|
||||
return version;
|
||||
};
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
const execa = require('execa');
|
||||
const debug = require('debug')('semantic-release:git');
|
||||
|
||||
/**
|
||||
* Get the commit sha for a given tag.
|
||||
*
|
||||
* @param {String} tagName Tag name for which to retrieve the commit sha.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {string} The commit sha of the tag in parameter or `null`.
|
||||
*/
|
||||
async function getTagHead(tagName, execaOpts) {
|
||||
try {
|
||||
return (await execa('git', ['rev-list', '-1', tagName], execaOpts)).stdout;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all the repository tags.
|
||||
*
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Array<String>} List of git tags.
|
||||
* @throws {Error} If the `git` command fails.
|
||||
*/
|
||||
async function getTags(execaOpts) {
|
||||
return (await execa('git', ['tag'], execaOpts)).stdout
|
||||
.split('\n')
|
||||
.map(tag => tag.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify if the `ref` is in the direct history of the current branch.
|
||||
*
|
||||
* @param {String} ref The reference to look for.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Boolean} `true` if the reference is in the history of the current branch, falsy otherwise.
|
||||
*/
|
||||
async function isRefInHistory(ref, execaOpts) {
|
||||
try {
|
||||
await execa('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], execaOpts);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error.exitCode === 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
debug(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unshallow the git repository if necessary and fetch all the tags.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
async function fetch(repositoryUrl, execaOpts) {
|
||||
try {
|
||||
await execa('git', ['fetch', '--unshallow', '--tags', repositoryUrl], execaOpts);
|
||||
} catch (_) {
|
||||
await execa('git', ['fetch', '--tags', repositoryUrl], execaOpts);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HEAD sha.
|
||||
*
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {String} the sha of the HEAD commit.
|
||||
*/
|
||||
async function getGitHead(execaOpts) {
|
||||
return (await execa('git', ['rev-parse', 'HEAD'], execaOpts)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the repository remote URL.
|
||||
*
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {string} The value of the remote git URL.
|
||||
*/
|
||||
async function repoUrl(execaOpts) {
|
||||
try {
|
||||
return (await execa('git', ['config', '--get', 'remote.origin.url'], execaOpts)).stdout;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test if the current working directory is a Git repository.
|
||||
*
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Boolean} `true` if the current working directory is in a git repository, falsy otherwise.
|
||||
*/
|
||||
async function isGitRepo(execaOpts) {
|
||||
try {
|
||||
return (await execa('git', ['rev-parse', '--git-dir'], execaOpts)).exitCode === 0;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the write access authorization to remote repository with push dry-run.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {String} branch The repositoru branch for which to verify write access.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @throws {Error} if not authorized to push.
|
||||
*/
|
||||
async function verifyAuth(repositoryUrl, branch, execaOpts) {
|
||||
try {
|
||||
await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`], execaOpts);
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tag the commit head on the local repository.
|
||||
*
|
||||
* @param {String} tagName The name of the tag.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @throws {Error} if the tag creation failed.
|
||||
*/
|
||||
async function tag(tagName, execaOpts) {
|
||||
await execa('git', ['tag', tagName], execaOpts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Push to the remote repository.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @throws {Error} if the push failed.
|
||||
*/
|
||||
async function push(repositoryUrl, execaOpts) {
|
||||
await execa('git', ['push', '--tags', repositoryUrl], execaOpts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a tag name is a valid Git reference.
|
||||
*
|
||||
* @param {String} tagName the tag name to verify.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Boolean} `true` if valid, falsy otherwise.
|
||||
*/
|
||||
async function verifyTagName(tagName, execaOpts) {
|
||||
try {
|
||||
return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOpts)).exitCode === 0;
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the local branch is up to date with the remote one.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {String} branch The repository branch for which to verify status.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Boolean} `true` is the HEAD of the current local branch is the same as the HEAD of the remote branch, falsy otherwise.
|
||||
*/
|
||||
async function isBranchUpToDate(repositoryUrl, branch, execaOpts) {
|
||||
const {stdout: remoteHead} = await execa('git', ['ls-remote', '--heads', repositoryUrl, branch], execaOpts);
|
||||
try {
|
||||
return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts);
|
||||
} catch (error) {
|
||||
debug(error);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getTagHead,
|
||||
getTags,
|
||||
isRefInHistory,
|
||||
fetch,
|
||||
getGitHead,
|
||||
repoUrl,
|
||||
isGitRepo,
|
||||
verifyAuth,
|
||||
tag,
|
||||
push,
|
||||
verifyTagName,
|
||||
isBranchUpToDate,
|
||||
};
|
||||
@@ -0,0 +1,12 @@
|
||||
const {escapeRegExp, size, isString} = require('lodash');
|
||||
const {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('./definitions/constants');
|
||||
|
||||
module.exports = env => {
|
||||
const toReplace = Object.keys(env).filter(
|
||||
envVar => /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE
|
||||
);
|
||||
|
||||
const regexp = new RegExp(toReplace.map(envVar => escapeRegExp(env[envVar])).join('|'), 'g');
|
||||
return output =>
|
||||
output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;
|
||||
};
|
||||
@@ -0,0 +1,93 @@
|
||||
const {identity, isPlainObject, omit, castArray, isNil, isString} = require('lodash');
|
||||
const AggregateError = require('aggregate-error');
|
||||
const getError = require('../get-error');
|
||||
const PLUGINS_DEFINITIONS = require('../definitions/plugins');
|
||||
const {validatePlugin, validateStep, loadPlugin, parseConfig} = require('./utils');
|
||||
const pipeline = require('./pipeline');
|
||||
const normalize = require('./normalize');
|
||||
|
||||
module.exports = (context, pluginsPath) => {
|
||||
let {options, logger} = context;
|
||||
const errors = [];
|
||||
|
||||
const plugins = options.plugins
|
||||
? castArray(options.plugins).reduce((plugins, plugin) => {
|
||||
if (validatePlugin(plugin)) {
|
||||
const [name, config] = parseConfig(plugin);
|
||||
plugin = isString(name) ? loadPlugin(context, name, pluginsPath) : name;
|
||||
|
||||
if (isPlainObject(plugin)) {
|
||||
Object.entries(plugin).forEach(([type, func]) => {
|
||||
if (PLUGINS_DEFINITIONS[type]) {
|
||||
Reflect.defineProperty(func, 'pluginName', {
|
||||
value: isPlainObject(name) ? 'Inline plugin' : name,
|
||||
writable: false,
|
||||
enumerable: true,
|
||||
});
|
||||
plugins[type] = [...(plugins[type] || []), [func, config]];
|
||||
}
|
||||
});
|
||||
} else {
|
||||
errors.push(getError('EPLUGINSCONF', {plugin}));
|
||||
}
|
||||
} else {
|
||||
errors.push(getError('EPLUGINSCONF', {plugin}));
|
||||
}
|
||||
|
||||
return plugins;
|
||||
}, {})
|
||||
: [];
|
||||
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
|
||||
options = {...plugins, ...options};
|
||||
|
||||
const pluginsConf = Object.entries(PLUGINS_DEFINITIONS).reduce(
|
||||
(pluginsConf, [type, {required, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]) => {
|
||||
let pluginOpts;
|
||||
|
||||
if (isNil(options[type]) && def) {
|
||||
pluginOpts = def;
|
||||
} else {
|
||||
// If an object is passed and the path is missing, merge it with step options
|
||||
if (isPlainObject(options[type]) && !options[type].path) {
|
||||
options[type] = castArray(plugins[type]).map(plugin =>
|
||||
plugin ? [plugin[0], Object.assign(plugin[1], options[type])] : plugin
|
||||
);
|
||||
}
|
||||
|
||||
if (!validateStep({required}, options[type])) {
|
||||
errors.push(getError('EPLUGINCONF', {type, required, pluginConf: options[type]}));
|
||||
return pluginsConf;
|
||||
}
|
||||
|
||||
pluginOpts = options[type];
|
||||
}
|
||||
|
||||
const steps = castArray(pluginOpts).map(pluginOpt =>
|
||||
normalize(
|
||||
{...context, options: omit(options, Object.keys(PLUGINS_DEFINITIONS), 'plugins')},
|
||||
type,
|
||||
pluginOpt,
|
||||
pluginsPath
|
||||
)
|
||||
);
|
||||
|
||||
pluginsConf[type] = async input =>
|
||||
postprocess(
|
||||
await pipeline(steps, pipelineConfig && pipelineConfig(pluginsConf, logger))(await preprocess(input)),
|
||||
input
|
||||
);
|
||||
|
||||
return pluginsConf;
|
||||
},
|
||||
plugins
|
||||
);
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
|
||||
return pluginsConf;
|
||||
};
|
||||
@@ -0,0 +1,67 @@
|
||||
const {isPlainObject, isFunction, noop, cloneDeep, omit} = require('lodash');
|
||||
const debug = require('debug')('semantic-release:plugins');
|
||||
const getError = require('../get-error');
|
||||
const {extractErrors} = require('../utils');
|
||||
const PLUGINS_DEFINITIONS = require('../definitions/plugins');
|
||||
const {loadPlugin, parseConfig} = require('./utils');
|
||||
|
||||
module.exports = (context, type, pluginOpt, pluginsPath) => {
|
||||
const {stdout, stderr, options, logger} = context;
|
||||
if (!pluginOpt) {
|
||||
return noop;
|
||||
}
|
||||
|
||||
const [name, config] = parseConfig(pluginOpt);
|
||||
const pluginName = name.pluginName ? name.pluginName : isFunction(name) ? `[Function: ${name.name}]` : name;
|
||||
const plugin = loadPlugin(context, name, pluginsPath);
|
||||
|
||||
debug(`options for ${pluginName}/${type}: %O`, config);
|
||||
|
||||
let func;
|
||||
if (isFunction(plugin)) {
|
||||
func = plugin.bind(null, cloneDeep({...options, ...config}));
|
||||
} else if (isPlainObject(plugin) && plugin[type] && isFunction(plugin[type])) {
|
||||
func = plugin[type].bind(null, cloneDeep({...options, ...config}));
|
||||
} else {
|
||||
throw getError('EPLUGIN', {type, pluginName});
|
||||
}
|
||||
|
||||
const validator = async input => {
|
||||
const {dryRun, outputValidator} = PLUGINS_DEFINITIONS[type] || {};
|
||||
try {
|
||||
if (!input.options.dryRun || dryRun) {
|
||||
logger.log(`Start step "${type}" of plugin "${pluginName}"`);
|
||||
const result = await func({
|
||||
...cloneDeep(omit(input, ['stdout', 'stderr', 'logger'])),
|
||||
stdout,
|
||||
stderr,
|
||||
logger: logger.scope(logger.scopeName, pluginName),
|
||||
});
|
||||
if (outputValidator && !outputValidator(result)) {
|
||||
throw getError(`E${type.toUpperCase()}OUTPUT`, {result, pluginName});
|
||||
}
|
||||
|
||||
logger.success(`Completed step "${type}" of plugin "${pluginName}"`);
|
||||
return result;
|
||||
}
|
||||
|
||||
logger.warn(`Skip step "${type}" of plugin "${pluginName}" in dry-run mode`);
|
||||
} catch (error) {
|
||||
logger.error(`Failed step "${type}" of plugin "${pluginName}"`);
|
||||
extractErrors(error).forEach(err => Object.assign(err, {pluginName}));
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
Reflect.defineProperty(validator, 'pluginName', {value: pluginName, writable: false, enumerable: true});
|
||||
|
||||
if (!isFunction(pluginOpt)) {
|
||||
if (pluginsPath[name]) {
|
||||
logger.success(`Loaded plugin "${type}" from "${pluginName}" in shareable config "${pluginsPath[name]}"`);
|
||||
} else {
|
||||
logger.success(`Loaded plugin "${type}" from "${pluginName}"`);
|
||||
}
|
||||
}
|
||||
|
||||
return validator;
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
const {identity} = require('lodash');
|
||||
const pReduce = require('p-reduce');
|
||||
const AggregateError = require('aggregate-error');
|
||||
const {extractErrors} = require('../utils');
|
||||
|
||||
/**
|
||||
* A Function that execute a list of function sequencially. If at least one Function ins the pipeline throws an Error or rejects, the pipeline function rejects as well.
|
||||
*
|
||||
* @typedef {Function} Pipeline
|
||||
* @param {Any} input Argument to pass to the first step in the pipeline.
|
||||
*
|
||||
* @return {Array<*>|*} An Array with the result of each step in the pipeline; if there is only 1 step in the pipeline, the result of this step is returned directly.
|
||||
*
|
||||
* @throws {AggregateError|Error} An AggregateError with the errors of each step in the pipeline that rejected; if there is only 1 step in the pipeline, the error of this step is thrown directly.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Create a Pipeline with a list of Functions.
|
||||
*
|
||||
* @param {Array<Function>} steps The list of Function to execute.
|
||||
* @param {Object} options Pipeline options.
|
||||
* @param {Boolean} [options.settleAll=false] If `true` all the steps in the pipeline are executed, even if one rejects, if `false` the execution stops after a steps rejects.
|
||||
* @param {Function} [options.getNextInput=identity] Function called after each step is executed, with the last step input and the current current step result; the returned value will be used as the input of the next step.
|
||||
* @param {Function} [options.transform=identity] Function called after each step is executed, with the current step result, the step function and the last step input; the returned value will be saved in the pipeline results.
|
||||
*
|
||||
* @return {Pipeline} A Function that execute the `steps` sequencially
|
||||
*/
|
||||
module.exports = (steps, {settleAll = false, getNextInput = identity, transform = identity} = {}) => async input => {
|
||||
const results = [];
|
||||
const errors = [];
|
||||
await pReduce(
|
||||
steps,
|
||||
async (lastInput, step) => {
|
||||
let result;
|
||||
try {
|
||||
// Call the step with the input computed at the end of the previous iteration and save intermediary result
|
||||
result = await transform(await step(lastInput), step, lastInput);
|
||||
results.push(result);
|
||||
} catch (error) {
|
||||
if (settleAll) {
|
||||
errors.push(...extractErrors(error));
|
||||
result = error;
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare input for the next step, passing the input of the last iteration (or initial parameter for the first iteration) and the result of the current one
|
||||
return getNextInput(lastInput, result);
|
||||
},
|
||||
input
|
||||
);
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
|
||||
return results;
|
||||
};
|
||||
@@ -0,0 +1,68 @@
|
||||
const {dirname} = require('path');
|
||||
const {isString, isFunction, castArray, isArray, isPlainObject, isNil} = require('lodash');
|
||||
const resolveFrom = require('resolve-from');
|
||||
|
||||
const validateSteps = conf => {
|
||||
return conf.every(conf => {
|
||||
if (
|
||||
isArray(conf) &&
|
||||
(conf.length === 1 || conf.length === 2) &&
|
||||
(isString(conf[0]) || isFunction(conf[0])) &&
|
||||
(isNil(conf[1]) || isPlainObject(conf[1]))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
conf = castArray(conf);
|
||||
|
||||
if (conf.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const [name, config] = parseConfig(conf[0]);
|
||||
return (isString(name) || isFunction(name)) && isPlainObject(config);
|
||||
});
|
||||
};
|
||||
|
||||
function validatePlugin(conf) {
|
||||
return (
|
||||
isString(conf) ||
|
||||
(isArray(conf) &&
|
||||
(conf.length === 1 || conf.length === 2) &&
|
||||
(isString(conf[0]) || isPlainObject(conf[0])) &&
|
||||
(isNil(conf[1]) || isPlainObject(conf[1]))) ||
|
||||
(isPlainObject(conf) && (isNil(conf.path) || isString(conf.path) || isPlainObject(conf.path)))
|
||||
);
|
||||
}
|
||||
|
||||
function validateStep({required}, conf) {
|
||||
conf = castArray(conf).filter(Boolean);
|
||||
if (required) {
|
||||
return conf.length >= 1 && validateSteps(conf);
|
||||
}
|
||||
|
||||
return conf.length === 0 || validateSteps(conf);
|
||||
}
|
||||
|
||||
function loadPlugin({cwd}, name, pluginsPath) {
|
||||
const basePath = pluginsPath[name]
|
||||
? dirname(resolveFrom.silent(__dirname, pluginsPath[name]) || resolveFrom(cwd, pluginsPath[name]))
|
||||
: __dirname;
|
||||
return isFunction(name) ? name : require(resolveFrom.silent(basePath, name) || resolveFrom(cwd, name));
|
||||
}
|
||||
|
||||
function parseConfig(plugin) {
|
||||
let path;
|
||||
let config;
|
||||
if (isArray(plugin)) {
|
||||
[path, config] = plugin;
|
||||
} else if (isPlainObject(plugin) && !isNil(plugin.path)) {
|
||||
({path, ...config} = plugin);
|
||||
} else {
|
||||
path = plugin;
|
||||
}
|
||||
|
||||
return [path, config || {}];
|
||||
}
|
||||
|
||||
module.exports = {validatePlugin, validateStep, loadPlugin, parseConfig};
|
||||
@@ -1,20 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
module.exports = function (commits) {
|
||||
var type = null
|
||||
|
||||
commits.every(function (commit) {
|
||||
if (commit.breaks.length) {
|
||||
type = 'major'
|
||||
return false
|
||||
}
|
||||
|
||||
if (commit.type === 'feat') type = 'minor'
|
||||
|
||||
if (!type && commit.type === 'fix') type = 'patch'
|
||||
|
||||
return true
|
||||
})
|
||||
|
||||
return type
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
var git = require('conventional-changelog/lib/git')
|
||||
|
||||
module.exports = function (cb) {
|
||||
git.latestTag(function (err, from) {
|
||||
if (err) return cb(err)
|
||||
|
||||
git.getCommits({from: from}, function (err, commits) {
|
||||
if (err) return cb(err)
|
||||
cb(null, commits)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
var commits = require('./commits')
|
||||
var analyze = require('./analyze')
|
||||
|
||||
module.exports = function (cb) {
|
||||
commits(function (err, commits) {
|
||||
if (err) return cb(err)
|
||||
|
||||
cb(null, analyze(commits))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
const {isFunction} = require('lodash');
|
||||
const hideSensitive = require('./hide-sensitive');
|
||||
|
||||
function extractErrors(err) {
|
||||
return err && isFunction(err[Symbol.iterator]) ? [...err] : [err];
|
||||
}
|
||||
|
||||
function hideSensitiveValues(env, objs) {
|
||||
const hideFunction = hideSensitive(env);
|
||||
return objs.map(obj => {
|
||||
Object.getOwnPropertyNames(obj).forEach(prop => {
|
||||
if (obj[prop]) {
|
||||
obj[prop] = hideFunction(obj[prop]);
|
||||
}
|
||||
});
|
||||
return obj;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {extractErrors, hideSensitiveValues};
|
||||
@@ -0,0 +1,30 @@
|
||||
const {template} = require('lodash');
|
||||
const AggregateError = require('aggregate-error');
|
||||
const {isGitRepo, verifyTagName} = require('./git');
|
||||
const getError = require('./get-error');
|
||||
|
||||
module.exports = async ({cwd, env, options: {repositoryUrl, tagFormat}}) => {
|
||||
const errors = [];
|
||||
|
||||
if (!(await isGitRepo({cwd, env}))) {
|
||||
errors.push(getError('ENOGITREPO', {cwd}));
|
||||
} else if (!repositoryUrl) {
|
||||
errors.push(getError('ENOREPOURL'));
|
||||
}
|
||||
|
||||
// Verify that compiling the `tagFormat` produce a valid Git tag
|
||||
if (!(await verifyTagName(template(tagFormat)({version: '0.0.0'})))) {
|
||||
errors.push(getError('EINVALIDTAGFORMAT', {tagFormat}));
|
||||
}
|
||||
|
||||
// Verify the `tagFormat` contains the variable `version` by compiling the `tagFormat` template
|
||||
// with a space as the `version` value and verify the result contains the space.
|
||||
// The space is used as it's an invalid tag character, so it's guaranteed to no be present in the `tagFormat`.
|
||||
if ((template(tagFormat)({version: ' '}).match(/ /g) || []).length !== 1) {
|
||||
errors.push(getError('ETAGNOVERSION', {tagFormat}));
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
throw new AggregateError(errors);
|
||||
}
|
||||
};
|
||||
@@ -1,18 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
var exec = require('child_process').exec
|
||||
var unlink = require('fs').unlinkSync
|
||||
|
||||
module.exports = function (pkg, cb) {
|
||||
if (!pkg.name) return cb('Package must have a name')
|
||||
|
||||
exec('npm show ' + pkg.name + ' version', function(err, stdout, stderr) {
|
||||
if (err) unlink('./npm-debug.log')
|
||||
|
||||
if (err && /is not in the npm registry/m.test(stderr)) return cb(null, null, true)
|
||||
|
||||
if (err) return cb(err)
|
||||
|
||||
cb(null, stdout.trim())
|
||||
})
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 117 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 65 KiB |
+111
-24
@@ -1,44 +1,131 @@
|
||||
{
|
||||
"name": "semantic-release",
|
||||
"description": "semantic semver compliant package publishing",
|
||||
"version": "0.0.5",
|
||||
"author": "Stephan Bönnemann <stephan@boennemann.me>",
|
||||
"bin": "./bin/semantic-release",
|
||||
"bugs": {
|
||||
"url": "https://github.com/boennemann/semantic-release/issues"
|
||||
"description": "Automated semver compliant package publishing",
|
||||
"version": "0.0.0-development",
|
||||
"author": "Stephan Bönnemann <stephan@boennemann.me> (http://boennemann.me)",
|
||||
"ava": {
|
||||
"files": [
|
||||
"test/**/*.test.js"
|
||||
],
|
||||
"helpers": [
|
||||
"test/helpers/**/*"
|
||||
]
|
||||
},
|
||||
"bin": {
|
||||
"semantic-release": "bin/semantic-release.js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/semantic-release/semantic-release/issues"
|
||||
},
|
||||
"contributors": [
|
||||
"Gregor Martynus (https://twitter.com/gr2m)",
|
||||
"Pierre Vanduynslager (https://twitter.com/@pvdlg_)"
|
||||
],
|
||||
"dependencies": {
|
||||
"abbrev": "^1.0.5",
|
||||
"confirm-simple": "^1.0.3",
|
||||
"conventional-changelog": "0.0.11",
|
||||
"github": "^0.2.3",
|
||||
"github-url-from-git": "^1.4.0",
|
||||
"minimist": "^1.1.0",
|
||||
"parse-github-repo-url": "^1.0.0",
|
||||
"semver": "^4.2.0"
|
||||
"@semantic-release/commit-analyzer": "^6.1.0",
|
||||
"@semantic-release/error": "^2.2.0",
|
||||
"@semantic-release/github": "^5.1.0",
|
||||
"@semantic-release/npm": "^5.0.5",
|
||||
"@semantic-release/release-notes-generator": "^7.1.2",
|
||||
"aggregate-error": "^3.0.0",
|
||||
"cosmiconfig": "^6.0.0",
|
||||
"debug": "^4.0.0",
|
||||
"env-ci": "^4.0.0",
|
||||
"execa": "^3.2.0",
|
||||
"figures": "^3.0.0",
|
||||
"find-versions": "^3.0.0",
|
||||
"get-stream": "^5.0.0",
|
||||
"git-log-parser": "^1.2.0",
|
||||
"hook-std": "^2.0.0",
|
||||
"hosted-git-info": "^3.0.0",
|
||||
"lodash": "^4.17.15",
|
||||
"marked": "^0.7.0",
|
||||
"marked-terminal": "^3.2.0",
|
||||
"p-locate": "^4.0.0",
|
||||
"p-reduce": "^2.0.0",
|
||||
"read-pkg-up": "^7.0.0",
|
||||
"resolve-from": "^5.0.0",
|
||||
"semver": "^6.0.0",
|
||||
"signale": "^1.2.1",
|
||||
"yargs": "^15.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"standard": "^2.3.1"
|
||||
"ava": "^2.0.0",
|
||||
"clear-module": "^4.0.0",
|
||||
"codecov": "^3.0.0",
|
||||
"delay": "^4.0.0",
|
||||
"dockerode": "^3.0.0",
|
||||
"file-url": "^3.0.0",
|
||||
"fs-extra": "^8.0.0",
|
||||
"got": "^9.0.0",
|
||||
"js-yaml": "^3.10.0",
|
||||
"mockserver-client": "^5.1.1",
|
||||
"nock": "^11.1.0",
|
||||
"nyc": "^14.0.0",
|
||||
"p-retry": "^4.0.0",
|
||||
"proxyquire": "^2.0.0",
|
||||
"sinon": "^7.2.7",
|
||||
"stream-buffers": "^3.0.2",
|
||||
"tempy": "^0.3.0",
|
||||
"xo": "^0.25.0"
|
||||
},
|
||||
"homepage": "https://github.com/boennemann/semantic-release",
|
||||
"engines": {
|
||||
"node": ">=8.16"
|
||||
},
|
||||
"files": [
|
||||
"bin",
|
||||
"docs",
|
||||
"lib",
|
||||
"index.js",
|
||||
"cli.js"
|
||||
],
|
||||
"homepage": "https://github.com/semantic-release/semantic-release#readme",
|
||||
"keywords": [
|
||||
"release",
|
||||
"publish",
|
||||
"author",
|
||||
"automation",
|
||||
"changelog",
|
||||
"module",
|
||||
"package",
|
||||
"publish",
|
||||
"release",
|
||||
"semver",
|
||||
"version",
|
||||
"changelog"
|
||||
"version"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "index.js",
|
||||
"nyc": {
|
||||
"include": [
|
||||
"lib/**/*.js",
|
||||
"index.js",
|
||||
"cli.js"
|
||||
],
|
||||
"reporter": [
|
||||
"json",
|
||||
"text",
|
||||
"html"
|
||||
],
|
||||
"all": true
|
||||
},
|
||||
"prettier": {
|
||||
"printWidth": 120,
|
||||
"trailingComma": "es5"
|
||||
},
|
||||
"publishConfig": {
|
||||
"tag": "next"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/boennemann/semantic-release.git"
|
||||
"url": "git+https://github.com/semantic-release/semantic-release.git"
|
||||
},
|
||||
"scripts": {
|
||||
"prepublish": "./bin/semantic-release pre",
|
||||
"postpublish": "./bin/semantic-release post",
|
||||
"test": "standard"
|
||||
"codecov": "codecov -f coverage/coverage-final.json",
|
||||
"lint": "xo",
|
||||
"pretest": "npm run lint",
|
||||
"semantic-release": "./bin/semantic-release.js",
|
||||
"test": "nyc ava -v"
|
||||
},
|
||||
"xo": {
|
||||
"prettier": true,
|
||||
"space": true
|
||||
}
|
||||
}
|
||||
|
||||
-52
@@ -1,52 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
var exec = require('child_process').exec
|
||||
var readFile = require('fs').readFileSync
|
||||
|
||||
var changelog = require('conventional-changelog')
|
||||
var GitHubApi = require('github')
|
||||
var parseSlug = require('parse-github-repo-url')
|
||||
var parseUrl = require('github-url-from-git')
|
||||
|
||||
var github = new GitHubApi({
|
||||
version: '3.0.0'
|
||||
})
|
||||
|
||||
module.exports = function (options, cb) {
|
||||
var pkg = JSON.parse(readFile('./package.json'))
|
||||
var repository = pkg.repository ? pkg.repository.url : null
|
||||
|
||||
if (!repository) return cb('Package must have a repository')
|
||||
|
||||
changelog({
|
||||
version: pkg.version,
|
||||
repository: parseUrl(repository),
|
||||
file: false
|
||||
}, function(err, log) {
|
||||
if (err) return cb(err)
|
||||
|
||||
exec('git rev-parse HEAD', function(err, hash) {
|
||||
if (err) return cb(err)
|
||||
|
||||
var ghRepo = parseSlug(repository)
|
||||
var release = {
|
||||
owner: ghRepo[0],
|
||||
repo: ghRepo[1],
|
||||
tag_name: 'v' + pkg.version,
|
||||
target_commitish: hash,
|
||||
draft: options.debug,
|
||||
body: log
|
||||
}
|
||||
|
||||
github.authenticate({
|
||||
type: 'oauth',
|
||||
token: options.token
|
||||
})
|
||||
|
||||
github.releases.createRelease(release, function(err) {
|
||||
if (err) return cb(err)
|
||||
cb(null, true)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
-26
@@ -1,26 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
var fs = require('fs')
|
||||
|
||||
var semver = require('semver')
|
||||
|
||||
var type = require('../lib/type')
|
||||
var version = require('../lib/version')
|
||||
|
||||
module.exports = function (options, cb) {
|
||||
type(function (err, type) {
|
||||
if (err) return cb(err)
|
||||
if (!type) return cb(null, null)
|
||||
|
||||
var path = './package.json'
|
||||
var pkg = JSON.parse(fs.readFileSync(path))
|
||||
version(pkg, function (err, version, unpublished) {
|
||||
if (err) return cb(err)
|
||||
|
||||
pkg.version = unpublished ? '1.0.0' : semver.inc(version, type)
|
||||
if (!options.debug) fs.writeFileSync(path, JSON.stringify(pkg, null, 2))
|
||||
|
||||
cb(null, pkg.version)
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
'use strict'
|
||||
|
||||
var spawn = require('child_process').spawn
|
||||
|
||||
var exports = module.exports = function (cb) {
|
||||
// npm loads package.json data before running the `prepublish` hook
|
||||
// changing the version on `prepublish` has no effect
|
||||
// see https://github.com/npm/npm/issues/7118
|
||||
// to circumvent this behavior we are calling `npm publish` inside `prepublish`
|
||||
// the package.json is then loaded again and the correct version will be published
|
||||
|
||||
var child = spawn('npm', ['publish', '--semantic-release-rerun'])
|
||||
var handler = exports.handleCloseAndExit.bind(null, cb)
|
||||
|
||||
child.stdout.pipe(process.stdout)
|
||||
child.stderr.pipe(process.stderr)
|
||||
|
||||
child.on('close', handler)
|
||||
child.on('exit', handler)
|
||||
child.on('error', cb)
|
||||
}
|
||||
|
||||
exports.handleCloseAndExit = function (cb, code, signal) {
|
||||
if (code === 0) return cb(null)
|
||||
cb({
|
||||
code: code,
|
||||
signal: signal,
|
||||
message: 'npm publish failed'
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import test from 'ava';
|
||||
import {escapeRegExp} from 'lodash';
|
||||
import proxyquire from 'proxyquire';
|
||||
import {stub} from 'sinon';
|
||||
import {SECRET_REPLACEMENT} from '../lib/definitions/constants';
|
||||
|
||||
const requireNoCache = proxyquire.noPreserveCache();
|
||||
|
||||
test.beforeEach(t => {
|
||||
t.context.logs = '';
|
||||
t.context.errors = '';
|
||||
t.context.stdout = stub(process.stdout, 'write').callsFake(val => {
|
||||
t.context.logs += val.toString();
|
||||
});
|
||||
t.context.stderr = stub(process.stderr, 'write').callsFake(val => {
|
||||
t.context.errors += val.toString();
|
||||
});
|
||||
});
|
||||
|
||||
test.afterEach.always(t => {
|
||||
t.context.stdout.restore();
|
||||
t.context.stderr.restore();
|
||||
});
|
||||
|
||||
test.serial('Pass options to semantic-release API', async t => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = [
|
||||
'',
|
||||
'',
|
||||
'-b',
|
||||
'master',
|
||||
'-r',
|
||||
'https://github/com/owner/repo.git',
|
||||
'-t',
|
||||
`v\${version}`,
|
||||
'-p',
|
||||
'plugin1',
|
||||
'plugin2',
|
||||
'-e',
|
||||
'config1',
|
||||
'config2',
|
||||
'--verify-conditions',
|
||||
'condition1',
|
||||
'condition2',
|
||||
'--analyze-commits',
|
||||
'analyze',
|
||||
'--verify-release',
|
||||
'verify1',
|
||||
'verify2',
|
||||
'--generate-notes',
|
||||
'notes',
|
||||
'--prepare',
|
||||
'prepare1',
|
||||
'prepare2',
|
||||
'--publish',
|
||||
'publish1',
|
||||
'publish2',
|
||||
'--success',
|
||||
'success1',
|
||||
'success2',
|
||||
'--fail',
|
||||
'fail1',
|
||||
'fail2',
|
||||
'--debug',
|
||||
'-d',
|
||||
];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.is(run.args[0][0].branch, 'master');
|
||||
t.is(run.args[0][0].repositoryUrl, 'https://github/com/owner/repo.git');
|
||||
t.is(run.args[0][0].tagFormat, `v\${version}`);
|
||||
t.deepEqual(run.args[0][0].plugins, ['plugin1', 'plugin2']);
|
||||
t.deepEqual(run.args[0][0].extends, ['config1', 'config2']);
|
||||
t.deepEqual(run.args[0][0].verifyConditions, ['condition1', 'condition2']);
|
||||
t.is(run.args[0][0].analyzeCommits, 'analyze');
|
||||
t.deepEqual(run.args[0][0].verifyRelease, ['verify1', 'verify2']);
|
||||
t.deepEqual(run.args[0][0].generateNotes, ['notes']);
|
||||
t.deepEqual(run.args[0][0].prepare, ['prepare1', 'prepare2']);
|
||||
t.deepEqual(run.args[0][0].publish, ['publish1', 'publish2']);
|
||||
t.deepEqual(run.args[0][0].success, ['success1', 'success2']);
|
||||
t.deepEqual(run.args[0][0].fail, ['fail1', 'fail2']);
|
||||
t.is(run.args[0][0].debug, true);
|
||||
t.is(run.args[0][0].dryRun, true);
|
||||
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Pass options to semantic-release API with alias arguments', async t => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = [
|
||||
'',
|
||||
'',
|
||||
'--branch',
|
||||
'master',
|
||||
'--repository-url',
|
||||
'https://github/com/owner/repo.git',
|
||||
'--tag-format',
|
||||
`v\${version}`,
|
||||
'--plugins',
|
||||
'plugin1',
|
||||
'plugin2',
|
||||
'--extends',
|
||||
'config1',
|
||||
'config2',
|
||||
'--dry-run',
|
||||
];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.is(run.args[0][0].branch, 'master');
|
||||
t.is(run.args[0][0].repositoryUrl, 'https://github/com/owner/repo.git');
|
||||
t.is(run.args[0][0].tagFormat, `v\${version}`);
|
||||
t.deepEqual(run.args[0][0].plugins, ['plugin1', 'plugin2']);
|
||||
t.deepEqual(run.args[0][0].extends, ['config1', 'config2']);
|
||||
t.is(run.args[0][0].dryRun, true);
|
||||
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Pass unknown options to semantic-release API', async t => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '--bool', '--first-option', 'value1', '--second-option', 'value2', '--second-option', 'value3'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.is(run.args[0][0].bool, true);
|
||||
t.is(run.args[0][0].firstOption, 'value1');
|
||||
t.deepEqual(run.args[0][0].secondOption, ['value2', 'value3']);
|
||||
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Pass empty Array to semantic-release API for list option set to "false"', async t => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '--publish', 'false'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.deepEqual(run.args[0][0].publish, []);
|
||||
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Do not set properties in option for which arg is not in command line', async t => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '-b', 'master'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
await cli();
|
||||
|
||||
t.false('ci' in run.args[0][0]);
|
||||
t.false('d' in run.args[0][0]);
|
||||
t.false('dry-run' in run.args[0][0]);
|
||||
t.false('debug' in run.args[0][0]);
|
||||
t.false('r' in run.args[0][0]);
|
||||
t.false('t' in run.args[0][0]);
|
||||
t.false('p' in run.args[0][0]);
|
||||
t.false('e' in run.args[0][0]);
|
||||
});
|
||||
|
||||
test.serial('Display help', async t => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '--help'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.regex(t.context.logs, /Run automated package publishing/);
|
||||
t.is(exitCode, 0);
|
||||
});
|
||||
|
||||
test.serial('Return error exitCode and prints help if called with a command', async t => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', 'pre'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.regex(t.context.errors, /Run automated package publishing/);
|
||||
t.regex(t.context.errors, /Too many non-option arguments/);
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test.serial('Return error exitCode if multiple plugin are set for single plugin', async t => {
|
||||
const run = stub().resolves(true);
|
||||
const argv = ['', '', '--analyze-commits', 'analyze1', 'analyze2'];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.regex(t.context.errors, /Run automated package publishing/);
|
||||
t.regex(t.context.errors, /Too many non-option arguments/);
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test.serial('Return error exitCode if semantic-release throw error', async t => {
|
||||
const run = stub().rejects(new Error('semantic-release error'));
|
||||
const argv = ['', ''];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.regex(t.context.errors, /semantic-release error/);
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
|
||||
test.serial('Hide sensitive environment variable values from the logs', async t => {
|
||||
const env = {MY_TOKEN: 'secret token'};
|
||||
const run = stub().rejects(new Error(`Throw error: Exposing token ${env.MY_TOKEN}`));
|
||||
const argv = ['', ''];
|
||||
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv, env: {...process.env, ...env}}});
|
||||
|
||||
const exitCode = await cli();
|
||||
|
||||
t.regex(t.context.errors, new RegExp(`Throw error: Exposing token ${escapeRegExp(SECRET_REPLACEMENT)}`));
|
||||
t.is(exitCode, 1);
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import test from 'ava';
|
||||
import plugins from '../../lib/definitions/plugins';
|
||||
import {RELEASE_NOTES_SEPARATOR, SECRET_REPLACEMENT} from '../../lib/definitions/constants';
|
||||
|
||||
test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', t => {
|
||||
t.false(plugins.analyzeCommits.outputValidator('invalid'));
|
||||
t.false(plugins.analyzeCommits.outputValidator(1));
|
||||
t.false(plugins.analyzeCommits.outputValidator({}));
|
||||
|
||||
t.true(plugins.analyzeCommits.outputValidator());
|
||||
t.true(plugins.analyzeCommits.outputValidator(null));
|
||||
t.true(plugins.analyzeCommits.outputValidator('major'));
|
||||
});
|
||||
|
||||
test('The "generateNotes" plugin output, if defined, must be a string', t => {
|
||||
t.false(plugins.generateNotes.outputValidator(1));
|
||||
t.false(plugins.generateNotes.outputValidator({}));
|
||||
|
||||
t.true(plugins.generateNotes.outputValidator());
|
||||
t.true(plugins.generateNotes.outputValidator(null));
|
||||
t.true(plugins.generateNotes.outputValidator(''));
|
||||
t.true(plugins.generateNotes.outputValidator('string'));
|
||||
});
|
||||
|
||||
test('The "publish" plugin output, if defined, must be an object or "false"', t => {
|
||||
t.false(plugins.publish.outputValidator(1));
|
||||
t.false(plugins.publish.outputValidator('string'));
|
||||
|
||||
t.true(plugins.publish.outputValidator({}));
|
||||
t.true(plugins.publish.outputValidator());
|
||||
t.true(plugins.publish.outputValidator(null));
|
||||
t.true(plugins.publish.outputValidator(''));
|
||||
t.true(plugins.publish.outputValidator(false));
|
||||
});
|
||||
|
||||
test('The "generateNotes" plugins output are concatenated with separator and sensitive data is hidden', t => {
|
||||
const env = {MY_TOKEN: 'secret token'};
|
||||
t.is(plugins.generateNotes.postprocess(['note 1', 'note 2'], {env}), `note 1${RELEASE_NOTES_SEPARATOR}note 2`);
|
||||
t.is(plugins.generateNotes.postprocess(['', 'note'], {env}), 'note');
|
||||
t.is(plugins.generateNotes.postprocess([undefined, 'note'], {env}), 'note');
|
||||
t.is(plugins.generateNotes.postprocess(['note 1', '', 'note 2'], {env}), `note 1${RELEASE_NOTES_SEPARATOR}note 2`);
|
||||
t.is(
|
||||
plugins.generateNotes.postprocess(['note 1', undefined, 'note 2'], {env}),
|
||||
`note 1${RELEASE_NOTES_SEPARATOR}note 2`
|
||||
);
|
||||
|
||||
t.is(
|
||||
plugins.generateNotes.postprocess(
|
||||
[`Note 1: Exposing token ${env.MY_TOKEN}`, `Note 2: Exposing token ${SECRET_REPLACEMENT}`],
|
||||
{env}
|
||||
),
|
||||
`Note 1: Exposing token ${SECRET_REPLACEMENT}${RELEASE_NOTES_SEPARATOR}Note 2: Exposing token ${SECRET_REPLACEMENT}`
|
||||
);
|
||||
});
|
||||
|
||||
test('The "analyzeCommits" plugins output are reduced to the highest release type', t => {
|
||||
t.is(plugins.analyzeCommits.postprocess(['major', 'minor']), 'major');
|
||||
t.is(plugins.analyzeCommits.postprocess(['', 'minor']), 'minor');
|
||||
t.is(plugins.analyzeCommits.postprocess([undefined, 'patch']), 'patch');
|
||||
t.is(plugins.analyzeCommits.postprocess([null, 'patch']), 'patch');
|
||||
t.is(plugins.analyzeCommits.postprocess(['wrong_type', 'minor']), 'minor');
|
||||
t.is(plugins.analyzeCommits.postprocess([]), undefined);
|
||||
t.is(plugins.analyzeCommits.postprocess(['wrong_type']), undefined);
|
||||
});
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
module.exports = () => {};
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
module.exports = {
|
||||
verifyConditions: () => {},
|
||||
getLastRelease: () => {},
|
||||
analyzeCommits: () => {},
|
||||
verifyRelease: () => {},
|
||||
generateNotes: () => {},
|
||||
publish: () => {},
|
||||
};
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
const SemanticReleaseError = require('@semantic-release/error');
|
||||
|
||||
class InheritedError extends SemanticReleaseError {
|
||||
constructor(message, code) {
|
||||
super(message);
|
||||
Error.captureStackTrace(this, this.constructor);
|
||||
this.name = this.constructor.name;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = () => {
|
||||
throw new InheritedError('Inherited error', 'EINHERITED');
|
||||
};
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
module.exports = () => {
|
||||
const error = new Error('a');
|
||||
error.errorProperty = 'errorProperty';
|
||||
throw error;
|
||||
};
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
const AggregateError = require('aggregate-error');
|
||||
|
||||
module.exports = () => {
|
||||
throw new AggregateError([new Error('a'), new Error('b')]);
|
||||
};
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
module.exports = (pluginConfig, context) => context;
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
module.exports = (pluginConfig, {env, logger}) => {
|
||||
console.log(`Console: Exposing token ${env.MY_TOKEN}`);
|
||||
logger.log(`Log: Exposing token ${env.MY_TOKEN}`);
|
||||
logger.error(`Error: Console token ${env.MY_TOKEN}`);
|
||||
throw new Error(`Throw error: Exposing ${env.MY_TOKEN}`);
|
||||
};
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
module.exports = () => {};
|
||||
+1
@@ -0,0 +1 @@
|
||||
module.exports = (pluginConfig, context) => ({pluginConfig, context});
|
||||
@@ -0,0 +1,95 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import getCommits from '../lib/get-commits';
|
||||
import {gitRepo, gitCommits, gitDetachedHead} from './helpers/git-utils';
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.error = stub();
|
||||
t.context.logger = {log: t.context.log, error: t.context.error};
|
||||
});
|
||||
|
||||
test('Get all commits when there is no last release', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First', 'Second'], {cwd});
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const result = await getCommits({cwd, lastRelease: {}, logger: t.context.logger});
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.length, 2);
|
||||
t.deepEqual(result, commits);
|
||||
});
|
||||
|
||||
test('Get all commits since gitHead (from lastRelease)', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First', 'Second', 'Third'], {cwd});
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First'
|
||||
const result = await getCommits({
|
||||
cwd,
|
||||
lastRelease: {gitHead: commits[commits.length - 1].hash},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
|
||||
// Verify the commits created and retrieved by the module are identical
|
||||
t.is(result.length, 2);
|
||||
t.deepEqual(result, commits.slice(0, 2));
|
||||
});
|
||||
|
||||
test('Get all commits since gitHead (from lastRelease) on a detached head repo', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First', 'Second', 'Third'], {cwd});
|
||||
// Create a detached head repo at commit 'feat: Second'
|
||||
cwd = await gitDetachedHead(repositoryUrl, commits[1].hash);
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'First'
|
||||
const result = await getCommits({
|
||||
cwd,
|
||||
lastRelease: {gitHead: commits[commits.length - 1].hash},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
|
||||
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
|
||||
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('Return empty array if lastRelease.gitHead is the last commit', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First', 'Second'], {cwd});
|
||||
|
||||
// Retrieve the commits with the commits module, since commit 'Second' (therefore none)
|
||||
const result = await getCommits({
|
||||
cwd,
|
||||
lastRelease: {gitHead: commits[0].hash},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
|
||||
// Verify no commit is retrieved
|
||||
t.deepEqual(result, []);
|
||||
});
|
||||
|
||||
test('Return empty array if there is no commits', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
// Retrieve the commits with the commits module
|
||||
const result = await getCommits({cwd, lastRelease: {}, logger: t.context.logger});
|
||||
|
||||
// Verify no commit is retrieved
|
||||
t.deepEqual(result, []);
|
||||
});
|
||||
@@ -0,0 +1,487 @@
|
||||
import path from 'path';
|
||||
import {format} from 'util';
|
||||
import test from 'ava';
|
||||
import {writeFile, outputJson} from 'fs-extra';
|
||||
import {omit} from 'lodash';
|
||||
import proxyquire from 'proxyquire';
|
||||
import {stub} from 'sinon';
|
||||
import yaml from 'js-yaml';
|
||||
import {gitRepo, gitCommits, gitShallowClone, gitAddConfig} from './helpers/git-utils';
|
||||
|
||||
const DEFAULT_PLUGINS = [
|
||||
'@semantic-release/commit-analyzer',
|
||||
'@semantic-release/release-notes-generator',
|
||||
'@semantic-release/npm',
|
||||
'@semantic-release/github',
|
||||
];
|
||||
|
||||
test.beforeEach(t => {
|
||||
t.context.plugins = stub().returns({});
|
||||
t.context.getConfig = proxyquire('../lib/get-config', {'./plugins': t.context.plugins});
|
||||
});
|
||||
|
||||
test('Default values, reading repositoryUrl from package.json', async t => {
|
||||
const pkg = {repository: 'https://host.null/owner/package.git'};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
// Add remote.origin.url config
|
||||
await gitAddConfig('remote.origin.url', 'git@host.null:owner/repo.git', {cwd});
|
||||
// Create package.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), pkg);
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(result.branch, 'master');
|
||||
t.is(result.repositoryUrl, 'https://host.null/owner/package.git');
|
||||
t.is(result.tagFormat, `v\${version}`);
|
||||
});
|
||||
|
||||
test('Default values, reading repositoryUrl from repo if not set in package.json', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add remote.origin.url config
|
||||
await gitAddConfig('remote.origin.url', 'https://host.null/owner/module.git', {cwd});
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(result.branch, 'master');
|
||||
t.is(result.repositoryUrl, 'https://host.null/owner/module.git');
|
||||
t.is(result.tagFormat, `v\${version}`);
|
||||
});
|
||||
|
||||
test('Default values, reading repositoryUrl (http url) from package.json if not set in repo', async t => {
|
||||
const pkg = {repository: 'https://host.null/owner/module.git'};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), pkg);
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the default options are set
|
||||
t.is(result.branch, 'master');
|
||||
t.is(result.repositoryUrl, 'https://host.null/owner/module.git');
|
||||
t.is(result.tagFormat, `v\${version}`);
|
||||
});
|
||||
|
||||
test('Convert "ci" option to "noCi"', async t => {
|
||||
const pkg = {repository: 'https://host.null/owner/module.git', release: {ci: false}};
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Create package.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), pkg);
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
t.is(result.noCi, true);
|
||||
});
|
||||
|
||||
test('Read options from package.json', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: options});
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
});
|
||||
|
||||
test('Read options from .releaserc.yml', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json in repository root
|
||||
await writeFile(path.resolve(cwd, '.releaserc.yml'), yaml.safeDump(options));
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
});
|
||||
|
||||
test('Read options from .releaserc.json', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json in repository root
|
||||
await outputJson(path.resolve(cwd, '.releaserc.json'), options);
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
});
|
||||
|
||||
test('Read options from .releaserc.js', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json in repository root
|
||||
await writeFile(path.resolve(cwd, '.releaserc.js'), `module.exports = ${JSON.stringify(options)}`);
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
});
|
||||
|
||||
test('Read options from release.config.js', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json in repository root
|
||||
await writeFile(path.resolve(cwd, 'release.config.js'), `module.exports = ${JSON.stringify(options)}`);
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from package.json
|
||||
t.deepEqual(result, options);
|
||||
// Verify the plugins module is called with the plugin options from package.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
});
|
||||
|
||||
test('Prioritise CLI/API parameters over file configuration and git repo', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
// Create a clone
|
||||
cwd = await gitShallowClone(repositoryUrl);
|
||||
const pkgOptions = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_pkg'},
|
||||
branch: 'branch_pkg',
|
||||
};
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_cli'},
|
||||
branch: 'branch_cli',
|
||||
repositoryUrl: 'http://cli-url.com/owner/package',
|
||||
tagFormat: `cli\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
const pkg = {release: pkgOptions, repository: 'git@host.null:owner/module.git'};
|
||||
// Create package.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), pkg);
|
||||
|
||||
const result = await t.context.getConfig({cwd}, options);
|
||||
|
||||
// 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], {cwd, options});
|
||||
});
|
||||
|
||||
test('Read configuration from file path in "extends"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {extends: './shareable.json'};
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: ['plugin-1', ['plugin-2', {plugin2Opt: 'value'}]],
|
||||
};
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
|
||||
await outputJson(path.resolve(cwd, 'shareable.json'), options);
|
||||
|
||||
const {options: result} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(result, options);
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: './shareable.json',
|
||||
generateNotes: './shareable.json',
|
||||
'plugin-1': './shareable.json',
|
||||
'plugin-2': './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test('Read configuration from module path in "extends"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {extends: 'shareable'};
|
||||
const options = {
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
generateNotes: 'generateNotes',
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
|
||||
await outputJson(path.resolve(cwd, 'node_modules/shareable/index.json'), options);
|
||||
|
||||
const {options: results} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(results, options);
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: 'shareable',
|
||||
generateNotes: 'shareable',
|
||||
});
|
||||
});
|
||||
|
||||
test('Read configuration from an array of paths in "extends"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {extends: ['./shareable1.json', './shareable2.json']};
|
||||
const options1 = {
|
||||
verifyRelease: 'verifyRelease1',
|
||||
analyzeCommits: {path: 'analyzeCommits1', param: 'analyzeCommits_param1'},
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
};
|
||||
const options2 = {
|
||||
verifyRelease: 'verifyRelease2',
|
||||
generateNotes: 'generateNotes2',
|
||||
analyzeCommits: {path: 'analyzeCommits2', param: 'analyzeCommits_param2'},
|
||||
branch: 'test_branch',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
|
||||
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
|
||||
await outputJson(path.resolve(cwd, 'shareable2.json'), options2);
|
||||
|
||||
const {options: results} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from shareable1.json and shareable2.json
|
||||
t.deepEqual(results, {...options1, ...options2});
|
||||
// Verify the plugins module is called with the plugin options from shareable1.json and shareable2.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {cwd, options: {...options1, ...options2}});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
verifyRelease1: './shareable1.json',
|
||||
verifyRelease2: './shareable2.json',
|
||||
generateNotes2: './shareable2.json',
|
||||
analyzeCommits1: './shareable1.json',
|
||||
analyzeCommits2: './shareable2.json',
|
||||
});
|
||||
});
|
||||
|
||||
test('Prioritize configuration from config file over "extends"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {
|
||||
extends: './shareable.json',
|
||||
branch: 'test_pkg',
|
||||
generateNotes: 'generateNotes',
|
||||
publish: [{path: 'publishPkg', param: 'publishPkg_param'}],
|
||||
};
|
||||
const options1 = {
|
||||
analyzeCommits: 'analyzeCommits',
|
||||
generateNotes: 'generateNotesShareable',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param'}],
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
|
||||
await outputJson(path.resolve(cwd, 'shareable.json'), options1);
|
||||
|
||||
const {options} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from package.json and shareable.json
|
||||
t.deepEqual(options, omit({...options1, ...pkgOptions}, '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], {cwd, options: omit({...options, ...pkgOptions}, 'extends')});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
analyzeCommits: './shareable.json',
|
||||
generateNotesShareable: './shareable.json',
|
||||
publishShareable: './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test('Prioritize configuration from cli/API options over "extends"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const cliOptions = {
|
||||
extends: './shareable2.json',
|
||||
branch: 'branch_opts',
|
||||
publish: [{path: 'publishOpts', param: 'publishOpts_param'}],
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
};
|
||||
const pkgOptions = {
|
||||
extends: './shareable1.json',
|
||||
branch: 'branch_pkg',
|
||||
generateNotes: 'generateNotes',
|
||||
publish: [{path: 'publishPkg', param: 'publishPkg_param'}],
|
||||
};
|
||||
const options1 = {
|
||||
analyzeCommits: 'analyzeCommits1',
|
||||
generateNotes: 'generateNotesShareable1',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param1'}],
|
||||
branch: 'test_branch1',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
};
|
||||
const options2 = {
|
||||
analyzeCommits: 'analyzeCommits2',
|
||||
publish: [{path: 'publishShareable', param: 'publishShareable_param2'}],
|
||||
branch: 'test_branch2',
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json, shareable1.json and shareable2.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
|
||||
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
|
||||
await outputJson(path.resolve(cwd, 'shareable2.json'), options2);
|
||||
|
||||
const {options} = await t.context.getConfig({cwd}, cliOptions);
|
||||
|
||||
// Verify the options contains the plugin config from package.json and shareable2.json
|
||||
t.deepEqual(options, omit({...options2, ...pkgOptions, ...cliOptions}, '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], {
|
||||
cwd,
|
||||
options: omit({...options2, ...pkgOptions, ...cliOptions}, 'extends'),
|
||||
});
|
||||
});
|
||||
|
||||
test('Allow to unset properties defined in shareable config with "null"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {
|
||||
extends: './shareable.json',
|
||||
analyzeCommits: null,
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
plugins: null,
|
||||
};
|
||||
const options1 = {
|
||||
generateNotes: 'generateNotes',
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: ['test-plugin'],
|
||||
};
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
|
||||
await outputJson(path.resolve(cwd, 'shareable.json'), options1);
|
||||
|
||||
const {options} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from shareable.json and the default `plugins`
|
||||
t.deepEqual(options, {
|
||||
...omit(options1, ['analyzeCommits']),
|
||||
...omit(pkgOptions, ['extends', 'analyzeCommits']),
|
||||
plugins: DEFAULT_PLUGINS,
|
||||
});
|
||||
// Verify the plugins module is called with the plugin options from shareable.json and the default `plugins`
|
||||
t.deepEqual(t.context.plugins.args[0][0], {
|
||||
options: {
|
||||
...omit(options1, 'analyzeCommits'),
|
||||
...omit(pkgOptions, ['extends', 'analyzeCommits']),
|
||||
plugins: DEFAULT_PLUGINS,
|
||||
},
|
||||
cwd,
|
||||
});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
generateNotes: './shareable.json',
|
||||
analyzeCommits: './shareable.json',
|
||||
'test-plugin': './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test('Allow to unset properties defined in shareable config with "undefined"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkgOptions = {
|
||||
extends: './shareable.json',
|
||||
analyzeCommits: undefined,
|
||||
branch: 'test_branch',
|
||||
repositoryUrl: 'https://host.null/owner/module.git',
|
||||
};
|
||||
const options1 = {
|
||||
generateNotes: 'generateNotes',
|
||||
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
|
||||
tagFormat: `v\${version}`,
|
||||
plugins: false,
|
||||
};
|
||||
// Create package.json and release.config.js in repository root
|
||||
await writeFile(path.resolve(cwd, 'release.config.js'), `module.exports = ${format(pkgOptions)}`);
|
||||
await outputJson(path.resolve(cwd, 'shareable.json'), options1);
|
||||
|
||||
const {options} = await t.context.getConfig({cwd});
|
||||
|
||||
// Verify the options contains the plugin config from shareable.json
|
||||
t.deepEqual(options, {...omit(options1, 'analyzeCommits'), ...omit(pkgOptions, ['extends', 'analyzeCommits'])});
|
||||
// Verify the plugins module is called with the plugin options from shareable.json
|
||||
t.deepEqual(t.context.plugins.args[0][0], {
|
||||
options: {
|
||||
...omit(options1, 'analyzeCommits'),
|
||||
...omit(pkgOptions, ['extends', 'analyzeCommits']),
|
||||
},
|
||||
cwd,
|
||||
});
|
||||
t.deepEqual(t.context.plugins.args[0][1], {
|
||||
generateNotes: './shareable.json',
|
||||
analyzeCommits: './shareable.json',
|
||||
});
|
||||
});
|
||||
|
||||
test('Throw an Error if one of the shareable config cannot be found', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const pkhOptions = {extends: ['./shareable1.json', 'non-existing-path']};
|
||||
const options1 = {analyzeCommits: 'analyzeCommits'};
|
||||
// Create package.json and shareable.json in repository root
|
||||
await outputJson(path.resolve(cwd, 'package.json'), {release: pkhOptions});
|
||||
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
|
||||
|
||||
const error = await t.throwsAsync(t.context.getConfig({cwd}), Error);
|
||||
|
||||
t.regex(error.message, /Cannot find module 'non-existing-path'/);
|
||||
t.is(error.code, 'MODULE_NOT_FOUND');
|
||||
});
|
||||
@@ -0,0 +1,319 @@
|
||||
import test from 'ava';
|
||||
import getAuthUrl from '../lib/get-git-auth-url';
|
||||
import {gitRepo} from './helpers/git-utils';
|
||||
|
||||
const env = {GIT_ASKPASS: 'echo', GIT_TERMINAL_PROMPT: 0};
|
||||
|
||||
test('Return the same "git" formatted URL if "gitCredentials" is not defined', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'}}),
|
||||
'git@host.null:owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the same "https" formatted URL if "gitCredentials" is not defined', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {branch: 'master', repositoryUrl: 'https://host.null/owner/repo.git'}}),
|
||||
'https://host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is not defined and repositoryUrl is a "git+https" URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {branch: 'master', repositoryUrl: 'git+https://host.null/owner/repo.git'}}),
|
||||
'https://host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Do not add trailing ".git" if not present in the origian URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo'}}),
|
||||
'git@host.null:owner/repo'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "https" URL with group and subgroup', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
options: {branch: 'master', repositoryUrl: 'https://host.null/group/subgroup/owner/repo.git'},
|
||||
}),
|
||||
'https://host.null/group/subgroup/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "git" URL with group and subgroup', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:group/subgroup/owner/repo.git'},
|
||||
}),
|
||||
'git@host.null:group/subgroup/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Convert shorthand URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env, options: {repositoryUrl: 'semantic-release/semantic-release'}}),
|
||||
'https://github.com/semantic-release/semantic-release.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Convert GitLab shorthand URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env,
|
||||
options: {branch: 'master', repositoryUrl: 'gitlab:semantic-release/semantic-release'},
|
||||
}),
|
||||
'https://gitlab.com/semantic-release/semantic-release.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL without user', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "https" URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'https://host.null/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "http" URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'http://host.null/owner/repo.git'},
|
||||
}),
|
||||
'http://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "http" URL with custom port', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'http://host.null:8080/owner/repo.git'},
|
||||
}),
|
||||
'http://user:pass@host.null:8080/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+https" URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'git+https://host.null/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+http" URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'git+http://host.null/owner/repo.git'},
|
||||
}),
|
||||
'http://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "ssh" URL', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'ssh://git@host.null:2222/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GH_TOKEN"', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GH_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GITHUB_TOKEN"', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GITHUB_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GL_TOKEN"', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GL_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://gitlab-ci-token:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "GITLAB_TOKEN"', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GITLAB_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://gitlab-ci-token:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "BB_TOKEN"', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, BB_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://x-token-auth:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "gitCredentials" is defined with "BITBUCKET_TOKEN"', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, BITBUCKET_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://x-token-auth:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Return the "https" formatted URL if "GITHUB_ACTION" is set', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GITHUB_ACTION: 'foo', GITHUB_TOKEN: 'token'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
|
||||
}),
|
||||
'https://x-access-token:token@host.null/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "https" URL with group and subgroup, with "GIT_CREDENTIALS"', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'https://host.null/group/subgroup/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/group/subgroup/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Handle "git" URL with group and subgroup, with "GIT_CREDENTIALS', async t => {
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({
|
||||
cwd,
|
||||
env: {...env, GIT_CREDENTIALS: 'user:pass'},
|
||||
options: {branch: 'master', repositoryUrl: 'git@host.null:group/subgroup/owner/repo.git'},
|
||||
}),
|
||||
'https://user:pass@host.null/group/subgroup/owner/repo.git'
|
||||
);
|
||||
});
|
||||
|
||||
test('Do not add git credential to repositoryUrl if push is allowed', async t => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
|
||||
t.is(
|
||||
await getAuthUrl({cwd, env: {...env, GIT_CREDENTIALS: 'user:pass'}, options: {branch: 'master', repositoryUrl}}),
|
||||
repositoryUrl
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import getLastRelease from '../lib/get-last-release';
|
||||
import {gitRepo, gitCommits, gitTagVersion, gitCheckout} from './helpers/git-utils';
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.logger = {log: t.context.log};
|
||||
});
|
||||
|
||||
test('Get the highest non-prerelease valid tag', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Create some commits and tags
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('foo', undefined, {cwd});
|
||||
const commits = await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitCommits(['Fourth'], {cwd});
|
||||
await gitTagVersion('v3.0', undefined, {cwd});
|
||||
await gitCommits(['Fifth'], {cwd});
|
||||
await gitTagVersion('v3.0.0-beta.1', undefined, {cwd});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'v2.0.0', version: '2.0.0'});
|
||||
t.deepEqual(t.context.log.args[0], ['Found git tag v2.0.0 associated with version 2.0.0']);
|
||||
});
|
||||
|
||||
test('Get the highest tag in the history of the current branch', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commit to the master branch
|
||||
await gitCommits(['First'], {cwd});
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch', true, {cwd});
|
||||
// Add commit to the 'other-branch' branch
|
||||
await gitCommits(['Second'], {cwd});
|
||||
// Create the tag corresponding to version 3.0.0
|
||||
await gitTagVersion('v3.0.0', undefined, {cwd});
|
||||
// Checkout master
|
||||
await gitCheckout('master', false, {cwd});
|
||||
// Add another commit to the master branch
|
||||
const commits = await gitCommits(['Third'], {cwd});
|
||||
// Create the tag corresponding to version 2.0.0
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'v2.0.0', version: '2.0.0'});
|
||||
});
|
||||
|
||||
test('Match the tag name from the begining of the string', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('prefix/v1.0.0', undefined, {cwd});
|
||||
await gitTagVersion('prefix/v2.0.0', undefined, {cwd});
|
||||
await gitTagVersion('other-prefix/v3.0.0', undefined, {cwd});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `prefix/v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'prefix/v2.0.0', version: '2.0.0'});
|
||||
});
|
||||
|
||||
test('Return empty object if no valid tag is found', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Create some commits and tags
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('foo', undefined, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v2.0.x', undefined, {cwd});
|
||||
await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v3.0', undefined, {cwd});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {});
|
||||
t.is(t.context.log.args[0][0], 'No git tag version found');
|
||||
});
|
||||
|
||||
test('Return empty object if no valid tag is found in history', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitCheckout('other-branch', true, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitTagVersion('v2.0.0', undefined, {cwd});
|
||||
await gitTagVersion('v3.0.0', undefined, {cwd});
|
||||
await gitCheckout('master', false, {cwd});
|
||||
|
||||
const result = await getLastRelease({cwd, options: {tagFormat: `v\${version}`}, logger: t.context.logger});
|
||||
|
||||
t.deepEqual(result, {});
|
||||
t.is(t.context.log.args[0][0], 'No git tag version found');
|
||||
});
|
||||
|
||||
test('Get the highest valid tag corresponding to the "tagFormat"', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Create some commits and tags
|
||||
const [{hash: gitHead}] = await gitCommits(['First'], {cwd});
|
||||
|
||||
await gitTagVersion('1.0.0', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `\${version}`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: '1.0.0',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('foo-1.0.0-bar', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `foo-\${version}-bar`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: 'foo-1.0.0-bar',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('foo-v1.0.0-bar', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `foo-v\${version}-bar`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: 'foo-v1.0.0-bar',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('(.+)/1.0.0/(a-z)', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `(.+)/\${version}/(a-z)`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: '(.+)/1.0.0/(a-z)',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('2.0.0-1.0.0-bar.1', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `2.0.0-\${version}-bar.1`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: '2.0.0-1.0.0-bar.1',
|
||||
version: '1.0.0',
|
||||
});
|
||||
|
||||
await gitTagVersion('3.0.0-bar.1', undefined, {cwd});
|
||||
t.deepEqual(await getLastRelease({cwd, options: {tagFormat: `\${version}-bar.1`}, logger: t.context.logger}), {
|
||||
gitHead,
|
||||
gitTag: '3.0.0-bar.1',
|
||||
version: '3.0.0',
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import test from 'ava';
|
||||
import {spy} from 'sinon';
|
||||
import getLogger from '../lib/get-logger';
|
||||
|
||||
test('Expose "error", "success" and "log" functions', t => {
|
||||
const stdout = spy();
|
||||
const stderr = spy();
|
||||
const logger = getLogger({stdout: {write: stdout}, stderr: {write: stderr}});
|
||||
|
||||
logger.log('test log');
|
||||
logger.success('test success');
|
||||
logger.error('test error');
|
||||
|
||||
t.regex(stdout.args[0][0], /.*test log/);
|
||||
t.regex(stdout.args[1][0], /.*test success/);
|
||||
t.regex(stderr.args[0][0], /.*test error/);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import test from 'ava';
|
||||
import {stub} from 'sinon';
|
||||
import getNextVersion from '../lib/get-next-version';
|
||||
|
||||
test.beforeEach(t => {
|
||||
// Stub the logger functions
|
||||
t.context.log = stub();
|
||||
t.context.logger = {log: t.context.log};
|
||||
});
|
||||
|
||||
test('Increase version for patch release', t => {
|
||||
const version = getNextVersion({
|
||||
nextRelease: {type: 'patch'},
|
||||
lastRelease: {version: '1.0.0'},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
t.is(version, '1.0.1');
|
||||
});
|
||||
|
||||
test('Increase version for minor release', t => {
|
||||
const version = getNextVersion({
|
||||
nextRelease: {type: 'minor'},
|
||||
lastRelease: {version: '1.0.0'},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
t.is(version, '1.1.0');
|
||||
});
|
||||
|
||||
test('Increase version for major release', t => {
|
||||
const version = getNextVersion({
|
||||
nextRelease: {type: 'major'},
|
||||
lastRelease: {version: '1.0.0'},
|
||||
logger: t.context.logger,
|
||||
});
|
||||
t.is(version, '2.0.0');
|
||||
});
|
||||
|
||||
test('Return 1.0.0 if there is no previous release', t => {
|
||||
const version = getNextVersion({nextRelease: {type: 'minor'}, lastRelease: {}, logger: t.context.logger});
|
||||
t.is(version, '1.0.0');
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
import test from 'ava';
|
||||
import tempy from 'tempy';
|
||||
import {
|
||||
getTagHead,
|
||||
isRefInHistory,
|
||||
fetch,
|
||||
getGitHead,
|
||||
repoUrl,
|
||||
tag,
|
||||
push,
|
||||
getTags,
|
||||
isGitRepo,
|
||||
verifyTagName,
|
||||
isBranchUpToDate,
|
||||
} from '../lib/git';
|
||||
import {
|
||||
gitRepo,
|
||||
gitCommits,
|
||||
gitCheckout,
|
||||
gitTagVersion,
|
||||
gitShallowClone,
|
||||
gitGetCommits,
|
||||
gitAddConfig,
|
||||
gitCommitTag,
|
||||
gitRemoteTagHead,
|
||||
gitPush,
|
||||
gitDetachedHead,
|
||||
} from './helpers/git-utils';
|
||||
|
||||
test('Get the last commit sha', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
|
||||
const result = await getGitHead({cwd});
|
||||
|
||||
t.is(result, commits[0].hash);
|
||||
});
|
||||
|
||||
test('Throw error if the last commit sha cannot be found', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
await t.throwsAsync(getGitHead({cwd}), Error);
|
||||
});
|
||||
|
||||
test('Unshallow and fetch repository', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First', 'Second'], {cwd});
|
||||
// Create a shallow clone with only 1 commit
|
||||
cwd = await gitShallowClone(repositoryUrl);
|
||||
|
||||
// Verify the shallow clone contains only one commit
|
||||
t.is((await gitGetCommits(undefined, {cwd})).length, 1);
|
||||
|
||||
await fetch(repositoryUrl, {cwd});
|
||||
|
||||
// Verify the shallow clone contains all the commits
|
||||
t.is((await gitGetCommits(undefined, {cwd})).length, 2);
|
||||
});
|
||||
|
||||
test('Do not throw error when unshallow a complete repository', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd, repositoryUrl} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
await gitCommits(['First'], {cwd});
|
||||
await t.notThrowsAsync(fetch(repositoryUrl, {cwd}));
|
||||
});
|
||||
|
||||
test('Fetch all tags on a detached head repository', async t => {
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitTagVersion('v1.0.1', undefined, {cwd});
|
||||
const [commit] = await gitCommits(['Third'], {cwd});
|
||||
await gitTagVersion('v1.1.0', undefined, {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
cwd = await gitDetachedHead(repositoryUrl, commit.hash);
|
||||
|
||||
await fetch(repositoryUrl, {cwd});
|
||||
|
||||
t.deepEqual((await getTags({cwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0'].sort());
|
||||
});
|
||||
|
||||
test('Verify if the commit `sha` is in the direct history of the current branch', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
// Create the new branch 'other-branch' from master
|
||||
await gitCheckout('other-branch', true, {cwd});
|
||||
// Add commits to the 'other-branch' branch
|
||||
const otherCommits = await gitCommits(['Second'], {cwd});
|
||||
await gitCheckout('master', false, {cwd});
|
||||
|
||||
t.true(await isRefInHistory(commits[0].hash, {cwd}));
|
||||
t.falsy(await isRefInHistory(otherCommits[0].hash, {cwd}));
|
||||
await t.throwsAsync(isRefInHistory('non-existant-sha', {cwd}));
|
||||
});
|
||||
|
||||
test('Get the commit sha for a given tag or falsy if the tag does not exists', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add commits to the master branch
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
// Create the tag corresponding to version 1.0.0
|
||||
await gitTagVersion('v1.0.0', undefined, {cwd});
|
||||
|
||||
t.is(await getTagHead('v1.0.0', {cwd}), commits[0].hash);
|
||||
t.falsy(await getTagHead('missing_tag', {cwd}));
|
||||
});
|
||||
|
||||
test('Return git remote repository url from config', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
// Add remote.origin.url config
|
||||
await gitAddConfig('remote.origin.url', 'git@hostname.com:owner/package.git', {cwd});
|
||||
|
||||
t.is(await repoUrl({cwd}), 'git@hostname.com:owner/package.git');
|
||||
});
|
||||
|
||||
test('Return git remote repository url set while cloning', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
let {cwd, repositoryUrl} = await gitRepo();
|
||||
await gitCommits(['First'], {cwd});
|
||||
// Create a clone
|
||||
cwd = await gitShallowClone(repositoryUrl);
|
||||
|
||||
t.is(await repoUrl({cwd}), repositoryUrl);
|
||||
});
|
||||
|
||||
test('Return falsy if git repository url is not set', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
|
||||
t.falsy(await repoUrl({cwd}));
|
||||
});
|
||||
|
||||
test('Add tag on head commit', async t => {
|
||||
// Create a git repository, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo();
|
||||
const commits = await gitCommits(['Test commit'], {cwd});
|
||||
|
||||
await tag('tag_name', {cwd});
|
||||
|
||||
await t.is(await gitCommitTag(commits[0].hash, {cwd}), 'tag_name');
|
||||
});
|
||||
|
||||
test('Push tag to remote repository', async t => {
|
||||
// Create a git repository with a remote, set the current working directory at the root of the repo
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
const commits = await gitCommits(['Test commit'], {cwd});
|
||||
|
||||
await tag('tag_name', {cwd});
|
||||
await push(repositoryUrl, {cwd});
|
||||
|
||||
t.is(await gitRemoteTagHead(repositoryUrl, 'tag_name', {cwd}), commits[0].hash);
|
||||
});
|
||||
|
||||
test('Push tag to remote repository with remote branch ahaed', async t => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
const commits = await gitCommits(['First'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
const tmpRepo = await gitShallowClone(repositoryUrl);
|
||||
await gitCommits(['Second'], {cwd: tmpRepo});
|
||||
await gitPush('origin', 'master', {cwd: tmpRepo});
|
||||
|
||||
await tag('tag_name', {cwd});
|
||||
await push(repositoryUrl, {cwd});
|
||||
|
||||
t.is(await gitRemoteTagHead(repositoryUrl, 'tag_name', {cwd}), commits[0].hash);
|
||||
});
|
||||
|
||||
test('Return "true" if in a Git repository', async t => {
|
||||
// Create a git repository with a remote, set the current working directory at the root of the repo
|
||||
const {cwd} = await gitRepo(true);
|
||||
|
||||
t.true(await isGitRepo({cwd}));
|
||||
});
|
||||
|
||||
test('Return falsy if not in a Git repository', async t => {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
t.falsy(await isGitRepo({cwd}));
|
||||
});
|
||||
|
||||
test('Return "true" for valid tag names', async t => {
|
||||
t.true(await verifyTagName('1.0.0'));
|
||||
t.true(await verifyTagName('v1.0.0'));
|
||||
t.true(await verifyTagName('tag_name'));
|
||||
t.true(await verifyTagName('tag/name'));
|
||||
});
|
||||
|
||||
test('Return falsy for invalid tag names', async t => {
|
||||
t.falsy(await verifyTagName('?1.0.0'));
|
||||
t.falsy(await verifyTagName('*1.0.0'));
|
||||
t.falsy(await verifyTagName('[1.0.0]'));
|
||||
t.falsy(await verifyTagName('1.0.0..'));
|
||||
});
|
||||
|
||||
test('Throws error if obtaining the tags fails', async t => {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
await t.throwsAsync(getTags({cwd}));
|
||||
});
|
||||
|
||||
test('Return "true" if repository is up to date', async t => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
|
||||
t.true(await isBranchUpToDate(repositoryUrl, 'master', {cwd}));
|
||||
});
|
||||
|
||||
test('Return falsy if repository is not up to date', async t => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
|
||||
t.true(await isBranchUpToDate(repositoryUrl, 'master', {cwd}));
|
||||
|
||||
const tmpRepo = await gitShallowClone(repositoryUrl);
|
||||
await gitCommits(['Third'], {cwd: tmpRepo});
|
||||
await gitPush('origin', 'master', {cwd: tmpRepo});
|
||||
|
||||
t.falsy(await isBranchUpToDate(repositoryUrl, 'master', {cwd}));
|
||||
});
|
||||
|
||||
test('Return "true" if local repository is ahead', async t => {
|
||||
const {cwd, repositoryUrl} = await gitRepo(true);
|
||||
await gitCommits(['First'], {cwd});
|
||||
await gitPush(repositoryUrl, 'master', {cwd});
|
||||
await gitCommits(['Second'], {cwd});
|
||||
|
||||
t.true(await isBranchUpToDate(repositoryUrl, 'master', {cwd}));
|
||||
});
|
||||
@@ -0,0 +1,231 @@
|
||||
import tempy from 'tempy';
|
||||
import execa from 'execa';
|
||||
import fileUrl from 'file-url';
|
||||
import pReduce from 'p-reduce';
|
||||
import gitLogParser from 'git-log-parser';
|
||||
import getStream from 'get-stream';
|
||||
|
||||
/**
|
||||
* Commit message informations.
|
||||
*
|
||||
* @typedef {Object} Commit
|
||||
* @property {String} branch The commit branch.
|
||||
* @property {String} hash The commit hash.
|
||||
* @property {String} message The commit message.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Create a temporary git repository.
|
||||
* 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} [branch='master'] The branch to initialize.
|
||||
* @return {String} The path of the clone if `withRemote` is `true`, the path of the repository otherwise.
|
||||
*/
|
||||
export async function gitRepo(withRemote, branch = 'master') {
|
||||
let cwd = tempy.directory();
|
||||
|
||||
await execa('git', ['init', ...(withRemote ? ['--bare'] : [])], {cwd});
|
||||
|
||||
const repositoryUrl = fileUrl(cwd);
|
||||
if (withRemote) {
|
||||
await initBareRepo(repositoryUrl, branch);
|
||||
cwd = await gitShallowClone(repositoryUrl, branch);
|
||||
} else {
|
||||
await gitCheckout(branch, true, {cwd});
|
||||
}
|
||||
|
||||
await execa('git', ['config', 'commit.gpgsign', false], {cwd});
|
||||
|
||||
return {cwd, repositoryUrl};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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} repositoryUrl The URL of the bare repository.
|
||||
* @param {String} [branch='master'] the branch to initialize.
|
||||
*/
|
||||
export async function initBareRepo(repositoryUrl, branch = 'master') {
|
||||
const cwd = tempy.directory();
|
||||
await execa('git', ['clone', '--no-hardlinks', repositoryUrl, cwd], {cwd});
|
||||
await gitCheckout(branch, true, {cwd});
|
||||
await gitCommits(['Initial commit'], {cwd});
|
||||
await execa('git', ['push', repositoryUrl, branch], {cwd});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create commits on the current git repository.
|
||||
*
|
||||
* @param {Array<string>} messages Commit messages.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @returns {Array<Commit>} The created commits, in reverse order (to match `git log` order).
|
||||
*/
|
||||
export async function gitCommits(messages, execaOpts) {
|
||||
await pReduce(
|
||||
messages,
|
||||
async (_, message) =>
|
||||
(await execa('git', ['commit', '-m', message, '--allow-empty', '--no-gpg-sign'], execaOpts)).stdout
|
||||
);
|
||||
return (await gitGetCommits(undefined, execaOpts)).slice(0, messages.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of parsed commits since a git reference.
|
||||
*
|
||||
* @param {String} [from] Git reference from which to seach commits.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {Array<Object>} The list of parsed commits.
|
||||
*/
|
||||
export async function gitGetCommits(from, execaOpts) {
|
||||
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
|
||||
return (
|
||||
await getStream.array(
|
||||
gitLogParser.parse({_: `${from ? from + '..' : ''}HEAD`}, {...execaOpts, env: {...process.env, ...execaOpts.env}})
|
||||
)
|
||||
).map(commit => {
|
||||
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 {Boolean} create to create the branch, `false` to checkout an existing branch.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
export async function gitCheckout(branch, create, execaOpts) {
|
||||
await execa('git', create ? ['checkout', '-b', branch] : ['checkout', branch], execaOpts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the HEAD sha.
|
||||
*
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {String} The sha of the head commit in the current git repository.
|
||||
*/
|
||||
export async function gitHead(execaOpts) {
|
||||
return (await execa('git', ['rev-parse', 'HEAD'], execaOpts)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a tag on the head commit in the current git repository.
|
||||
*
|
||||
* @param {String} tagName The tag name to create.
|
||||
* @param {String} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
export async function gitTagVersion(tagName, sha, execaOpts) {
|
||||
await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName], execaOpts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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} repositoryUrl The path of the repository to clone.
|
||||
* @param {String} [branch='master'] the branch to clone.
|
||||
* @param {Number} [depth=1] The number of commit to clone.
|
||||
* @return {String} The path of the cloned repository.
|
||||
*/
|
||||
export async function gitShallowClone(repositoryUrl, branch = 'master', depth = 1) {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, repositoryUrl, cwd], {
|
||||
cwd,
|
||||
});
|
||||
return cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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} repositoryUrl The path of the repository to clone.
|
||||
* @param {Number} head A commit sha of the remote repo that will become the detached head of the new one.
|
||||
* @return {String} The path of the new repository.
|
||||
*/
|
||||
export async function gitDetachedHead(repositoryUrl, head) {
|
||||
const cwd = tempy.directory();
|
||||
|
||||
await execa('git', ['init'], {cwd});
|
||||
await execa('git', ['remote', 'add', 'origin', repositoryUrl], {cwd});
|
||||
await execa('git', ['fetch', repositoryUrl], {cwd});
|
||||
await execa('git', ['checkout', head], {cwd});
|
||||
return cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a new Git configuration.
|
||||
*
|
||||
* @param {String} name Config name.
|
||||
* @param {String} value Config value.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*/
|
||||
export async function gitAddConfig(name, value, execaOpts) {
|
||||
await execa('git', ['config', '--add', name, value], execaOpts);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {String} The sha of the commit associated with `tagName` on the local repository.
|
||||
*/
|
||||
export async function gitTagHead(tagName, execaOpts) {
|
||||
return (await execa('git', ['rev-list', '-1', tagName], execaOpts)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the first commit sha referenced by the tag `tagName` in the remote repository.
|
||||
*
|
||||
* @param {String} repositoryUrl The repository remote URL.
|
||||
* @param {String} tagName The tag name to seach for.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {String} The sha of the commit associated with `tagName` on the remote repository.
|
||||
*/
|
||||
export async function gitRemoteTagHead(repositoryUrl, tagName, execaOpts) {
|
||||
return (await execa('git', ['ls-remote', '--tags', repositoryUrl, tagName], execaOpts)).stdout
|
||||
.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.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @return {String} The tag associatedwith the sha in parameter or `null`.
|
||||
*/
|
||||
export async function gitCommitTag(gitHead, execaOpts) {
|
||||
return (await execa('git', ['describe', '--tags', '--exact-match', gitHead], execaOpts)).stdout;
|
||||
}
|
||||
|
||||
/**
|
||||
* Push to the remote repository.
|
||||
*
|
||||
* @param {String} repositoryUrl The remote repository URL.
|
||||
* @param {String} branch The branch to push.
|
||||
* @param {Object} [execaOpts] Options to pass to `execa`.
|
||||
*
|
||||
* @throws {Error} if the push failed.
|
||||
*/
|
||||
export async function gitPush(repositoryUrl, branch, execaOpts) {
|
||||
await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`], execaOpts);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
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.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
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});
|
||||
const cwd = await gitShallowClone(authUrl);
|
||||
|
||||
return {cwd, repositoryUrl, authUrl};
|
||||
}
|
||||
|
||||
export default {start, stop, gitCredential, createRepo};
|
||||
@@ -0,0 +1,103 @@
|
||||
import Docker from 'dockerode';
|
||||
import getStream from 'get-stream';
|
||||
import got from 'got';
|
||||
import pRetry from 'p-retry';
|
||||
import {mockServerClient} from 'mockserver-client';
|
||||
|
||||
const IMAGE = 'jamesdbloom/mockserver:latest';
|
||||
const MOCK_SERVER_PORT = 1080;
|
||||
const MOCK_SERVER_HOST = 'localhost';
|
||||
const docker = new Docker();
|
||||
let container;
|
||||
|
||||
/**
|
||||
* Download the `mockserver` Docker image, create a new container and start it.
|
||||
*/
|
||||
async function start() {
|
||||
await getStream(await docker.pull(IMAGE));
|
||||
|
||||
container = await docker.createContainer({
|
||||
Tty: true,
|
||||
Image: IMAGE,
|
||||
PortBindings: {[`${MOCK_SERVER_PORT}/tcp`]: [{HostPort: `${MOCK_SERVER_PORT}`}]},
|
||||
});
|
||||
await container.start();
|
||||
|
||||
try {
|
||||
// Wait for the mock server to be ready
|
||||
await pRetry(() => got.put(`http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}/status`, {cache: false}), {
|
||||
retries: 7,
|
||||
minTimeout: 1000,
|
||||
factor: 2,
|
||||
});
|
||||
} catch (_) {
|
||||
throw new Error(`Couldn't start mock-server after 2 min`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop and remote the `mockserver` Docker container.
|
||||
*/
|
||||
async function stop() {
|
||||
await container.stop();
|
||||
await container.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* @type {Object} A `mockserver` client configured to connect to the current instance.
|
||||
*/
|
||||
const client = mockServerClient(MOCK_SERVER_HOST, MOCK_SERVER_PORT);
|
||||
/**
|
||||
* @type {string} the url of the `mockserver` instance
|
||||
*/
|
||||
const url = `http://${MOCK_SERVER_HOST}:${MOCK_SERVER_PORT}`;
|
||||
|
||||
/**
|
||||
* Set up the `mockserver` instance response for a specific request.
|
||||
*
|
||||
* @param {string} path URI for which to respond.
|
||||
* @param {Object} request Request expectation. The http request made on `path` has to match those criteria in order to be valid.
|
||||
* @param {Object} request.body The JSON body the expected request must match.
|
||||
* @param {Object} request.headers The headers the expected request must match.
|
||||
* @param {Object} response The http response to return when receiving a request on `path`.
|
||||
* @param {String} [response.method='POST'] The http method for which to respond.
|
||||
* @param {number} [response.statusCode=200] The status code to respond.
|
||||
* @param {Object} response.body The JSON object to respond in the response body.
|
||||
* @return {Object} An object representation the expectation. Pass to the `verify` function to validate the `mockserver` has been called with a `request` matching the expectations.
|
||||
*/
|
||||
async function mock(
|
||||
path,
|
||||
{body: requestBody, headers: requestHeaders},
|
||||
{method = 'POST', statusCode = 200, body: responseBody}
|
||||
) {
|
||||
await client.mockAnyResponse({
|
||||
httpRequest: {path, method},
|
||||
httpResponse: {
|
||||
statusCode,
|
||||
headers: [{name: 'Content-Type', values: ['application/json; charset=utf-8']}],
|
||||
body: JSON.stringify(responseBody),
|
||||
},
|
||||
times: {remainingTimes: 1, unlimited: false},
|
||||
});
|
||||
|
||||
return {
|
||||
method,
|
||||
path,
|
||||
headers: requestHeaders,
|
||||
body: requestBody
|
||||
? {type: 'JSON', json: JSON.stringify(requestBody), matchType: 'ONLY_MATCHING_FIELDS'}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the `mockserver` has been called with a requestion matching expectations. The `expectation` is created with the `mock` function.
|
||||
*
|
||||
* @param {Object} expectation The expectation created with `mock` function.
|
||||
* @return {Promise} A Promise that resolves if the expectation is met or reject otherwise.
|
||||
*/
|
||||
function verify(expectation) {
|
||||
return client.verify(expectation);
|
||||
}
|
||||
|
||||
export default {start, stop, mock, verify, url};
|
||||
@@ -0,0 +1,79 @@
|
||||
import Docker from 'dockerode';
|
||||
import getStream from 'get-stream';
|
||||
import got from 'got';
|
||||
import delay from 'delay';
|
||||
import pRetry from 'p-retry';
|
||||
|
||||
const IMAGE = 'semanticrelease/npm-registry-docker:latest';
|
||||
const SERVER_PORT = 15986;
|
||||
const COUCHDB_PORT = 5984;
|
||||
const SERVER_HOST = 'localhost';
|
||||
const COUCHDB_USER = 'admin';
|
||||
const COUCHDB_PASSWORD = 'password';
|
||||
const NPM_USERNAME = 'integration';
|
||||
const NPM_PASSWORD = 'suchsecure';
|
||||
const NPM_EMAIL = 'integration@test.com';
|
||||
const docker = new Docker();
|
||||
let container;
|
||||
|
||||
/**
|
||||
* Download the `npm-registry-docker` Docker image, create a new container and start it.
|
||||
*/
|
||||
async function start() {
|
||||
await getStream(await docker.pull(IMAGE));
|
||||
|
||||
container = await docker.createContainer({
|
||||
Tty: true,
|
||||
Image: IMAGE,
|
||||
PortBindings: {[`${COUCHDB_PORT}/tcp`]: [{HostPort: `${SERVER_PORT}`}]},
|
||||
Env: [`COUCHDB_USER=${COUCHDB_USER}`, `COUCHDB_PASSWORD=${COUCHDB_PASSWORD}`],
|
||||
});
|
||||
|
||||
await container.start();
|
||||
await delay(4000);
|
||||
|
||||
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 (_) {
|
||||
throw new Error(`Couldn't start npm-registry-docker after 2 min`);
|
||||
}
|
||||
|
||||
// Create user
|
||||
await got(`http://${SERVER_HOST}:${SERVER_PORT}/_users/org.couchdb.user:${NPM_USERNAME}`, {
|
||||
json: true,
|
||||
auth: `${COUCHDB_USER}:${COUCHDB_PASSWORD}`,
|
||||
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-registry-docker` Docker container.
|
||||
*/
|
||||
async function stop() {
|
||||
await container.stop();
|
||||
await container.remove();
|
||||
}
|
||||
|
||||
export default {start, stop, authEnv, url};
|
||||
@@ -0,0 +1,58 @@
|
||||
import test from 'ava';
|
||||
import {repeat} from 'lodash';
|
||||
import hideSensitive from '../lib/hide-sensitive';
|
||||
import {SECRET_REPLACEMENT, SECRET_MIN_SIZE} from '../lib/definitions/constants';
|
||||
|
||||
test('Replace multiple sensitive environment variable values', t => {
|
||||
const env = {SOME_PASSWORD: 'password', SOME_TOKEN: 'secret'};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${env.SOME_PASSWORD}@host.com?token=${env.SOME_TOKEN}`),
|
||||
`https://user:${SECRET_REPLACEMENT}@host.com?token=${SECRET_REPLACEMENT}`
|
||||
);
|
||||
});
|
||||
|
||||
test('Replace multiple occurences of sensitive environment variable values', t => {
|
||||
const env = {secretKey: 'secret'};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${env.secretKey}@host.com?token=${env.secretKey}`),
|
||||
`https://user:${SECRET_REPLACEMENT}@host.com?token=${SECRET_REPLACEMENT}`
|
||||
);
|
||||
});
|
||||
|
||||
test('Escape regexp special characters', t => {
|
||||
const env = {SOME_CREDENTIALS: 'p$^{.+}\\w[a-z]o.*rd'};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${env.SOME_CREDENTIALS}@host.com`),
|
||||
`https://user:${SECRET_REPLACEMENT}@host.com`
|
||||
);
|
||||
});
|
||||
|
||||
test('Accept "undefined" input', t => {
|
||||
t.is(hideSensitive({})(), undefined);
|
||||
});
|
||||
|
||||
test('Return same string if no environment variable has to be replaced', t => {
|
||||
t.is(hideSensitive({})('test'), 'test');
|
||||
});
|
||||
|
||||
test('Exclude empty environment variables from the regexp', t => {
|
||||
const env = {SOME_PASSWORD: 'password', SOME_TOKEN: ''};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${env.SOME_PASSWORD}@host.com?token=`),
|
||||
`https://user:${SECRET_REPLACEMENT}@host.com?token=`
|
||||
);
|
||||
});
|
||||
|
||||
test('Exclude empty environment variables from the regexp if there is only empty ones', t => {
|
||||
t.is(hideSensitive({SOME_PASSWORD: '', SOME_TOKEN: ' \n '})(`https://host.com?token=`), 'https://host.com?token=');
|
||||
});
|
||||
|
||||
test('Exclude environment variables with value shorter than SECRET_MIN_SIZE from the regexp', t => {
|
||||
const SHORT_TOKEN = repeat('a', SECRET_MIN_SIZE - 1);
|
||||
const LONG_TOKEN = repeat('b', SECRET_MIN_SIZE);
|
||||
const env = {SHORT_TOKEN, LONG_TOKEN};
|
||||
t.is(
|
||||
hideSensitive(env)(`https://user:${SHORT_TOKEN}@host.com?token=${LONG_TOKEN}`),
|
||||
`https://user:${SHORT_TOKEN}@host.com?token=${SECRET_REPLACEMENT}`
|
||||
);
|
||||
});
|
||||
+1176
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user