Compare commits

...
88 Commits
Author SHA1 Message Date
greenkeeper[bot]andPierre Vanduynslager 186950acc0 fix(package): update @semantic-release/commit-analyzer to version 4.0.0 2017-10-29 21:19:27 -04:00
Pierre VanduynslagerandGregor Martynus c90765e10d fix: Include Error properties in logs 2017-10-29 14:37:05 -07:00
Pierre VanduynslagerandGregor Martynus ad2e1d76b7 test: Fix typos: only in tests and useless console.log() 2017-10-29 14:37:05 -07:00
Pierre VanduynslagerandGregor Martynus 65d344bae8 fix: Check SemanticReleaseError by error.semanticRelease property 2017-10-29 14:37:05 -07:00
greenkeeper[bot]andGregor Martynus 8a1dd7b324 fix(package): update @semantic-release/release-notes-generator to version 5.0.0 2017-10-28 22:17:45 -07:00
Pierre-Denis VanduynslagerandGregor Martynus e2a8a5cd32 feat: Refactor CLI to run with one command, improve logs, modularize, add tests
- Run with one command and do not rely on error exit codes to stop the process when a release is not necessary
- Break `index.js` in smaller modules in order to improve testability and simplify the code
- Add several missing unit and integration tests to reach 100% coverage
- Integration tests now test end to end, including publishing to Github (with http://www.mock-server.com on Docker)
- Use `tj/commander.js` to print an help message, verify and parse CLI arguments
- Semantic-release can now be called via Javascript API: `require('semantic-release')(options)`
- Remove npmlog dependency and add more log messages
- Logger is now passed to plugins
- Add debug logs with `visionmedia/debug`. `debug` is enabled for both semantic-release and plugins with `--debug`
- Use `kevva/npm-conf` in place of the deprecated `npm/npmconf`
- Pass lastRelease, nextRelease and commits to generate-notes plugin
- In dry-run mode, print the release note instead of publishing it to Github as draft, and skip the CI verifications
- The dry-run mode does not require npm and Github TOKEN to be set anymore and can be run locally

BREAKING CHANGE: Semantic-Release must now be executed with `semantic-release` instead of `semantic-release pre && npm publish && semantic-release post`.
BREAKING CHANGE: The `semantic-release` command now returns with exit code 0 on expected exception (no release has to be done, running on a PR, gitHead not found, other CI job failed etc...). It only returns with 1 when there is an unexpected error (code error in a plugin, plugin not found, git command cannot be run etc..).
BREAKING CHANGE: Calling the `semantic-release` command with unexpected argument(s) now exit with 1 and print an help message.
BREAKING CHANGE: Semantic-Release does not rely on `npmlog` anymore and the log level cannot be configured. Debug logs can be activated with CLI option `--debug` or with environment variable `DEBUG=semantic-release:*`
BREAKING CHANGE: The CLI options `--debug` doesn't enable the dry-run mode anymore but activate the debugs. The dry run mode is now set with the CLI command `--dry-run` or `-d`.
2017-10-27 18:07:13 -07:00
Gregor Martynus 1bd095d26c chore(CODE_OF_CONDUCT): Contributor Covenant 2017-10-25 17:38:56 -07:00
greenkeeper[bot]andPierre Vanduynslager 16a02e523e fix(package): update github to version 12.0.0 2017-10-25 10:35:57 -04:00
greenkeeper[bot]andGregor Martynus 51e7579c69 chore(package): update ava to version 0.23.0 2017-10-24 14:11:22 -07:00
greenkeeper[bot]andPierre Vanduynslager acddd5a12f chore(package): update codecov to version 3.0.0 2017-10-23 11:04:25 -04:00
Jacob WejendorpandPierre Vanduynslager f6aacd2fe0 fix: Log error messages on reject 2017-10-23 10:43:56 -04:00
Pierre-Denis VanduynslagerandGregor Martynus b0bc49063b fix: handle errors when verifyConditions and verifyRelease are a pipeline 2017-10-18 14:00:20 -07:00
Pierre-Denis VanduynslagerandGregor Martynus 580ad9c3d2 feat: Allow to recover from ENOTINHISTORY with a tag and handle detached head repo
- Tag sha will now be used also if there is a gitHead in last release and it's not in the history
- Use `git merge-base` to determine if a commit is in history, allowing to use CI creating detached head repo
- Mention recovery solution by creating a version tag in `ENOTINHISTORY` and `ENOGITHEAD` error messages
- Do not mention branches containing missing commit in `ENOTINHISTORY` and `ENOGITHEAD` error messages as it's not available by default on most CI
2017-10-11 20:54:10 -07:00
Pierre-Denis VanduynslagerandGregor Martynus 8e9d9f77f3 fix: Always pass pluginConfig to plugins as a defined object 2017-10-06 10:28:37 -07:00
Pierre-Denis Vanduynslager 90417c6ffe fix: Exit with 1 if unexpected error happens 2017-10-06 00:30:08 -04:00
Pierre-Denis Vanduynslager 85dd69b3a2 feat: Retrieve version gitHead from git tags and unshallow the repo if necessary
Add several fixes and improvements in the identification of the last release gitHead:
- If there is no last release, unshallow the repo in order to retrieve all existing commits
- If git head is not present in last release, try to retrieve it from git tag with format ‘v\<version\>’ or ‘\<version\>’
- If the last release git head cannot be determined and  found in commit history, unshallow the repo and try again
- Throw a ENOGITHEAD error if the gitHead for the last release cannot be found in the npm metadata nor in the git tags, preventing to make release based on the all the commits in the repo as before
- Add integration test for the scenario with a packed repo from which `npm republish` fails to read the git head

Fix #447, Fix #393, Fix #280, Fix #276
2017-10-02 19:43:46 -04:00
Pierre-Denis Vanduynslager cbb51a495b ci(codecov): Set default branch in codecov.yml 2017-09-30 16:00:50 -04:00
Pierre-Denis Vanduynslager a58d12d5e7 chore: Update badges 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager 42b3382b0e ci(travis): Update .travis.yml
- Avoid double build on PR
- Add git fetch depth
- Remove cache
- Retry npm install
2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager cc3c8f2548 ci: Use codecov for code coverage 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager abf92ad03d refactor: Use ES6, Test with AVA
- Use async/await instead of callbacks
- Use execa to run command line
- Use AVA for tests
- Add several assertions in the unit tests
- Add documentation (comments) in the tests
- Run tests with a real git repo instead of mocking child_process and add test helpers to create repos, commits and checkout
- Simplify test directory structure
- Simplify code readability (mostly with async/await)
- Use eslint for for linting, prettier for formatting
2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager 7fe0890350 chore: Remove editorconfig 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager f10f157d79 chore: More generic .gitignore (Windows, Mac OS, Linux) 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager 40e296b00d chore: Remove lockfiles 2017-09-30 13:30:41 -04:00
Pierre-Denis Vanduynslager 266a3f72dc chore: Add license file 2017-09-30 13:30:41 -04:00
greenkeeper[bot]andGregor Martynus 42456a32b3 chore(package): update coveralls to version 3.0.0 2017-09-28 10:25:35 -07:00
greenkeeper[bot]andPierre Vanduynslager 3a4334fbfd fix(package): update @semantic-release/error to version 2.0.0 2017-09-25 13:16:40 -04:00
Richard LittauerandPierre Vanduynslager 41d9b7e984 docs: fix grammatical error in README
Just a small fix to make this sentence parse.
2017-09-22 03:11:24 -04:00
Pierre VanduynslagerandGregor Martynus 9951cf7e00 fix(package): Set minimum node version to 4 (#442) 2017-09-21 11:24:18 -07:00
greenkeeper[bot]andGregor Martynus 2d14c53b11 fix(package): update @semantic-release/last-release-npm to version 2.0.0 2017-09-21 11:08:42 -07:00
greenkeeper[bot]andPierre Vanduynslager 277d9ab4e2 chore(package): update cz-conventional-changelog to version 2.0.0
https://greenkeeper.io/
2017-09-19 18:03:30 -04:00
Stephan SchneiderandPierre Vanduynslager 4612a056a3 chore(package): update commitizen config 2017-09-19 16:42:09 -04:00
greenkeeper[bot]andGregor 8c44c3176a fix(package): update @semantic-release/commit-analyzer to version 3.0.1 2017-09-17 20:31:46 -07:00
greenkeeper[bot] dd60b461a6 fix(package): update @semantic-release/release-notes-generator to version 4.0.0 2017-09-17 19:51:43 +00:00
Richard LittauerandGregor Martynus 88b5895f80 docs(README): update commit lint suggestion (#429)
validate-commit-msg is deprecated, and points to commitlint.
2017-09-14 21:22:18 -07:00
Patrick HeneiseandGregor Martynus 1ceae83ad9 docs(troubleshooting): initial version (#399) 2017-09-13 12:10:50 -07:00
Gregor 12b35396d8 fix(package): @semantic-release/condition-travis@6.0.0
This also introduces the new build leader detecation from https://github.com/semantic-release/travis-deploy-once/releases/tag/v2.0.0
2017-08-19 14:15:28 -07:00
Gregor 33dfcffe2c fix(bin): addapt build leader error to new leader detection algorithm 2017-08-19 14:15:28 -07:00
Stephan BönnemannandGregor Martynus f534c57215 fix: remove support for node < 8
BREAKING CHANGE: Remove support for publishing a package with node < 8. [Details](https://github.com/semantic-release/semantic-release#why-does-semantic-release-require-node-version-8).
2017-08-19 14:15:28 -07:00
Stephan BönnemannandGregor Martynus 9c5288460d chore: add package-lock 2017-08-19 14:15:28 -07:00
Kaito UdagawaandGregor Martynus 0c79a9b4bf fix(post): create git tag properly
refs/heads are for branches and refs/tags for tags.
2017-08-16 20:47:29 -07:00
Kaito UdagawaandGregor Martynus 3f8559731f fix(post): Create a tag before makeing a release 2017-08-13 20:29:49 -07:00
Kaito UdagawaandGregor Martynus f148a61339 fix(post): fix target_commitish to be the default branch
target_commitish in GitHub Releases has two different meanings:
* Target commit that a new associated tag will be created on
* Target branch to compute how many "commits to since this release"

target_commitish is usually the default branch (aka master), because the
distance between the release and the latest branch is the primary concern.

Before this change, target_commitish was left to be a hash and the
feature of GitHub Releases that shows how much time passed since the
release is ruined, because no tracking branch is given.

By this change, target_commitish is changed to be the default branch
given in the configuration (options.branch) via edit a release API after
the release and tag are created via crate a release API.
2017-08-13 20:29:49 -07:00
Gregor 5b3bdd226f chore: remove console.log 2017-08-13 12:10:36 -07:00
Gregor 64d84a0e84 chore(travis): drop builds in Node <4 2017-08-13 12:10:36 -07:00
greenkeeper[bot]andGregor Martynus 1fa6d50264 fix(package): update @semantic-release/release-notes-generator to version 3.0.1
BREAKING CHANGE: Dropped support for unmaintained Node.js versions (< v4)
2017-08-13 12:10:36 -07:00
Jan Peer StöcklmairandGregor Martynus 6145bc9ba5 docs(readme): add sgc (#386) 2017-08-12 15:59:01 -07:00
Piper ChesterandGregor Martynus 609b46f1cf docs(README): minor typo (#376) 2017-06-12 13:41:42 +02:00
greenkeeper[bot]andStephan Bönnemann 76cd99c3a5 chore(package): update standard to version 9.0.0
https://greenkeeper.io/
2017-03-06 10:13:19 +01:00
greenkeeper[bot]andStephan Bönnemann 22dc640117 chore(package): update tap to version 10.0.1
https://greenkeeper.io/
2017-02-03 11:37:47 +01:00
Stephan BönnemannandGitHub af90de989e Merge pull request #355 from semantic-release/dep-updates
Misc GK dep updates
2017-01-13 12:13:30 +01:00
Stephan Bönnemann aa012b3023 Merge branch 'greenkeeper/tap-9.0.0' into dep-updates
* greenkeeper/tap-9.0.0:
  chore(package): update tap to version 9.0.0
2017-01-13 12:04:45 +01:00
Stephan Bönnemann 5724b19e23 Merge branch 'greenkeeper/github-8.0.0' into dep-updates
* greenkeeper/github-8.0.0:
  fix(package): update github to version 8.0.0
2017-01-13 12:04:25 +01:00
Stephan BönnemannandGitHub 97a8e73b01 Merge branch 'caribou' into greenkeeper/nopt-4.0.0 2017-01-13 11:51:22 +01:00
Cory ReedandStephan Bönnemann 51e12a3a4b docs(package): fix 'home' link 2017-01-13 11:51:04 +01:00
greenkeeper[bot] afd6ab754d fix(package): update github to version 8.0.0
https://greenkeeper.io/
2017-01-11 17:54:30 +00:00
greenkeeper[bot] f80e056e13 chore(package): update tap to version 9.0.0
https://greenkeeper.io/
2017-01-08 07:14:51 +00:00
greenkeeper[bot] b10c8910fb fix(package): update nopt to version 4.0.0
https://greenkeeper.io/
2016-12-13 23:38:46 +00:00
greenkeeper[bot]andChristoph Witzko 3295f9570c fix(package): update github to version 7.0.0
https://greenkeeper.io/
2016-12-02 12:33:58 +01:00
Ryan KimberandChristoph Witzko 6a172e1720 docs(README.md): discourage use of pre-patch, pre-minor and pre-release 2016-11-28 17:20:18 +01:00
greenkeeper[bot]andChristoph Witzko 68f975382d chore(package): update dependencies
https://greenkeeper.io/
2016-11-28 16:55:34 +01:00
Christoph Witzko 462c51dc2a style: standard 2016-11-28 16:37:00 +01:00
Christoph Witzko cdf705cb8a chore: update dependencies 2016-11-28 16:37:00 +01:00
Christoph Witzko 9a51b0271d chore: update github client 2016-11-28 16:36:53 +01:00
develarandChristoph Witzko 14618c81c9 chore(package): parse-github-repo-url 2016-11-28 16:14:43 +01:00
develarandChristoph Witzko 35da08d074 test: fix "/bin/bash: NO_PROMPT=yes: command not found" 2016-11-28 16:14:43 +01:00
Ben GummerandStephan Bönnemann 73138f8a8f fix: use spawn instead of exec for 'git log' to avoid maxBuffer err 2016-11-28 15:50:59 +01:00
Mark DalgleishandChristoph Witzko d7f5d19073 docs(readme): fix link to how the CLI works 2016-11-28 11:34:33 +01:00
PAkerstrandandStephan Bönnemann f239f2f402 fix(commits): Use --no-color for git branch-command
When `git branch --contains ${commit}` has colored output the `inHistory` check failed
2016-11-21 09:46:44 -03:00
Stephan Bönnemann 2be6e5d34a fix: use travis-deploy-once to reenable travis-pro support 2016-11-17 15:40:21 -03:00
Joscha FethandStephan Bönnemann a5cb9ea7f7 fix(gitlog): increase maxBuffer
This is needed for repositories with a lot of commits and/or a big changelog.

Closes #286
2016-09-01 14:35:34 +02:00
Stephan BönnemannandGitHub 15e6daf7cc Merge pull request #262 from semantic-release/greenkeeper-npmlog-4.0.0
Update npmlog to version 4.0.0 🚀
2016-07-19 10:04:35 +02:00
greenkeeperio-bot 2326cda3f0 chore(package): update npmlog to version 4.0.0
https://greenkeeper.io/
2016-07-19 02:33:25 +02:00
GreenkeeperandStephan Bönnemann 4afb280bee chore(package): update tap to version 6.2.0 (#260)
https://greenkeeper.io/
2016-07-16 19:55:45 +02:00
GreenkeeperandStephan Bönnemann 7da7695ba1 chore(package): update nyc to version 7.0.0 (#255)
https://greenkeeper.io/
2016-07-09 16:53:56 +02:00
Cory HouseandStephan Bönnemann 41125ee8aa docs(readme): fix grammar 2016-06-28 19:27:43 +02:00
Stephan Bönnemann cca50ef154 Merge pull request #212 from semantic-release/greenkeeper-nock-8.0.0
Update nock to version 8.0.0 🚀
2016-05-27 23:52:24 +02:00
Stephan Bönnemann 4807dee1e2 Merge branch 'caribou' into greenkeeper-nock-8.0.0 2016-05-27 15:31:16 +02:00
Stephan Bönnemann f89792e25b Merge pull request #226 from semantic-release/greenkeeper-run-auto-2.0.0
Update run-auto to version 2.0.0 🚀
2016-05-27 15:30:51 +02:00
Stephan Bönnemann 4078638ce9 Merge branch 'caribou' into greenkeeper-run-auto-2.0.0 2016-05-27 15:17:34 +02:00
Stephan Bönnemann 89ded2d79c refactor(pre): adapt to new run-auto api 2016-05-27 12:52:56 +02:00
Stephan Bönnemann 0a89265ae7 Merge pull request #227 from aquavitae/caribou
Expose cafile from npm config
2016-05-27 12:39:13 +02:00
David Townshend ad2a61586e feat(ssl): expose cafile from npm config 2016-05-23 10:31:14 +02:00
greenkeeperio-bot 45e04be49a chore(package): update run-auto to version 2.0.0
https://greenkeeper.io/
2016-05-18 04:45:45 +02:00
Jake TrentandStephan Bönnemann d9b95940db fix(cli): fix typo in log message 2016-05-10 11:00:47 +02:00
Stephan Bönnemann 2e18266023 Merge pull request #221 from semantic-release/greenkeeper-standard-7.0.1
Update standard to version 7.0.1 🚀
2016-05-04 19:09:04 +02:00
greenkeeperio-bot 9aef361da9 chore(package): update standard to version 7.0.1
https://greenkeeper.io/
2016-05-04 16:55:30 +02:00
greenkeeperio-bot d57cb70c56 chore(package): update nock to version 8.0.0
http://greenkeeper.io/
2016-04-06 11:59:26 +02:00
75 changed files with 3263 additions and 1222 deletions
-11
View File
@@ -1,11 +0,0 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
+133 -7
View File
@@ -1,9 +1,135 @@
coverage
node_modules
test/registry/couch
test/registry/data
test/tmp
# 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
*.dump
.DS_Store
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
# End of https://www.gitignore.io/api/macos,windows,linux,node
package-lock.json
yarn.lock
# Registry tests
test/helpers/registry/couch
test/helpers/registry/data
+1
View File
@@ -0,0 +1 @@
package-lock=false
+21 -17
View File
@@ -1,22 +1,26 @@
sudo: false
language: node_js
cache:
directories:
- node_modules
services:
- couchdb
- docker
notifications:
email: false
node_js:
- 5
- 4
- iojs
- '0.12'
- '0.10'
before_install:
- npm i -g npm@^2.0.0
before_script:
- npm prune
- 8
# Trigger a push build on caribou and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
only:
- caribou
- /^greenkeeper.*$/
# Retry install on fail to avoid failing a build on network/disk/external errors
install:
- travis_retry npm install
script:
- npm run test
after_success:
- npm run coverage:upload
- npm run semantic-release
services:
- couchdb
- npm run codecov
- npm run semantic-release
+1
View File
@@ -0,0 +1 @@
--install.no-lockfile true
+46
View File
@@ -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/
+21
View File
@@ -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.
+51 -22
View File
@@ -7,15 +7,15 @@
> [egghead.io](https://egghead.io/lessons/javascript-how-to-write-a-javascript-library-automating-releases-with-semantic-release)
[![Join the chat at https://gitter.im/semantic-release/semantic-release](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/semantic-release/semantic-release?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![npm](https://img.shields.io/npm/v/semantic-release.svg)](https://www.npmjs.com/package/semantic-release)
[![Greenkeeper badge](https://badges.greenkeeper.io/semantic-release/semantic-release.svg)](https://greenkeeper.io/)
[![license](https://img.shields.io/github/license/semantic-release/semantic-release.svg)](https://github.com/semantic-release/semantic-release/blob/master/LICENSE)
[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
[![Dependency Status](https://david-dm.org/semantic-release/semantic-release/caribou.svg)](https://david-dm.org/semantic-release/semantic-release/caribou)
[![devDependency Status](https://david-dm.org/semantic-release/semantic-release/caribou/dev-status.svg)](https://david-dm.org/semantic-release/semantic-release/caribou#info=devDependencies)
[![Build Status](https://travis-ci.org/semantic-release/semantic-release.svg?branch=caribou)](https://travis-ci.org/semantic-release/semantic-release)
[![Coverage Status](https://coveralls.io/repos/semantic-release/semantic-release/badge.svg?branch=caribou&service=github)](https://coveralls.io/github/semantic-release/semantic-release?branch=caribou)
[![Travis](https://img.shields.io/travis/semantic-release/semantic-release/caribou.svg)](https://travis-ci.org/semantic-release/semantic-release)
[![Codecov](https://img.shields.io/codecov/c/github/semantic-release/semantic-release/caribou.svg)](https://codecov.io/gh/semantic-release/semantic-release)
Out of the box this is just about _commit-messages_, but you can do so much more.
@@ -79,15 +79,21 @@ This removes the immediate connection between human emotions and version numbers
Instead of writing [meaningless commit messages](http://whatthecommit.com/), we can take our time to think about the changes in the codebase and write them down. Following formalized conventions it is then possible to generate a helpful changelog and to derive the next semantic version number from them.
When `semantic-release` got setup it will do that after every successful continuous integration build of your master branch (or any other branch you specify) and publish the new version for you. That way no human is directly involved in the release process and your releases are guaranteed to be [unromantic and unsentimental](http://sentimentalversioning.org/).
When `semantic-release` is set up it will do that after every successful continuous integration build of your master branch (or any other branch you specify) and publish the new version for you. This way no human is directly involved in the release process and your releases are guaranteed to be [unromantic and unsentimental](http://sentimentalversioning.org/).
If you fear the loss of control over timing and marketing implications of software releases you should know that `semantic-release` supports [release channels](https://github.com/npm/npm/issues/2718) using `npm`s [dist-tags](https://docs.npmjs.com/cli/dist-tag). This way you can keep control over what your users end up using by default, you can decide when to promote an automatically released version to the stable channel and you can choose which versions to write blogposts and tweets about. You can use the same mechanism to [support older versions of your software](https://gist.github.com/boennemann/54042374e49c7ade8910), for example with important security fixes.
If you fear the loss of control over timing and marketing implications of software releases you should know that `semantic-release` supports [release channels](https://github.com/npm/npm/issues/2718) using `npm`s [dist-tags](https://docs.npmjs.com/cli/dist-tag). This way you can keep control over what your users end up using by default, you can decide when to promote an automatically released version to the stable channel, and you can choose which versions to write blogposts and tweets about. You can use the same mechanism to [support older versions of your software](https://gist.github.com/boennemann/54042374e49c7ade8910), for example with important security fixes.
This is what happens in series:
When pushing new commits with `git push` a CI build is triggered. After running the tests the command `semantic-release` will execute the following tasks in series:
| 1. `git push` | 2. `semantic-release pre` | 3. `npm publish` | 4. `semantic-release post` |
| :--- | :--- | :--- | :---- |
| New code is pushed and triggers a CI build. | Based on all commits that happened since the last release, the new version number gets written to the `package.json`. | The new version gets published to `npm`. | A changelog gets generated and a [release](https://help.github.com/articles/about-releases/) (including a git tag) on GitHub gets created. |
| Step | Description |
| ------------------ | ------------------------------------------------------------------------------------------- |
| Verify Conditions` | Run the [verifyConditions](#verifyConditions) plugin) |
| Get last release` | Obtain last release with the [getLastRelease](#getLastRelease) plugin |
| Analyze commits | Determine the type of release to do with the [analyzeCommits](#analyzeCommits) plugin |
| Verify release | Call the [verifyRelease](#verifyRelease) plugin |
| npm publish | Update the version in `package.json` and call `npm publish` |
| Generate notes | Generate release notes with plugin [generateNotes](#generateNotes) |
| Github release | A git tag and [Github release](https://help.github.com/articles/about-releases/) is created |
_Note:_ The current release/tag implementation is tied to GitHub, but could be opened up to Bitbucket, GitLab, et al. Feel free to send PRs for these services.
@@ -106,7 +112,7 @@ format that includes a **type**, a **scope** and a **subject** ([full explanatio
<footer>
```
You can simplify using this convention for yourself and contributors by using [commitizen](https://github.com/commitizen/cz-cli) and [validate-commit-msg](https://github.com/kentcdodds/validate-commit-msg).
You can simplify using this convention for yourself and contributors by using [commitizen](https://github.com/commitizen/cz-cli) and [commitlint](https://github.com/marionebl/commitlint) or [semantic-git-commit-cli](https://github.com/JPeer264/node-semantic-git-commit-cli).
### Patch Release
@@ -125,7 +131,7 @@ feat(pencil): add 'graphiteWidth' option
```
perf(pencil): remove graphiteWidth option
BREAKING CHANGE: The graphiteWidth option has been removed. The default graphite width of 10mm is always used for performance reason.
BREAKING CHANGE: The graphiteWidth option has been removed. The default graphite width of 10mm is always used for performance reasons.
```
## Setup
@@ -141,20 +147,31 @@ semantic-release-cli setup
![dialogue](https://cloud.githubusercontent.com/assets/908178/9428123/3628dfec-499f-11e5-8bdd-8f3042dd95ed.png)
_[This is what happens under the hood.](https://github.com/semantic-release/cli#manual-setup)_
_[This is what happens under the hood.](https://github.com/semantic-release/cli#what-it-does)_
## Options
You can pass options either via command line (in [kebab-case](https://lodash.com/docs#kebabCase)) or in the `release` field of your `package.json` (in [camelCase](https://lodash.com/docs#camelCase)). The following two examples are the same, but CLI arguments take precedence.
| CLI | package.json |
| --- | --- |
| <pre><code>semantic-release pre --no-debug</code><pre> | <pre><code><div>//package.json</div><div>"release": {</div><div> "debug": false</div><div>}</div></code></pre><pre><code>semantic-release pre</code></pre> |
##### CLI
```bash
semantic-release --branch next
```
##### package.json
```json
"release": {
"branch": "next"
}
```
```bash
semantic-release
```
These options are currently available:
- `branch`: The branch on which releases should happen. Default: `'master'`
- `debug`: If true doesnt actually publish to npm or write things to file. Default: `!process.env.CI`
- `dry-run`: Dry-run mode, skipping verifyConditions, publishing and release, printing next version and release notes
- `debug`: Output debugging information
- `githubToken`: The token used to authenticate with GitHub. Default: `process.env.GH_TOKEN`
- `githubUrl`: Optional. Pass your GitHub Enterprise endpoint.
- `githubApiPathPrefix`: Optional. The path prefix for your GitHub Enterprise API.
@@ -181,11 +198,12 @@ There are numerous steps where you can customize `semantic-release`s behaviou
"path": "./path/to/a/module",
"additional": "config"
}
}
}
```
```
semantic-release pre --analyze-commits="npm-module-name"
semantic-release --analyze-commits="npm-module-name"
```
A plugin itself is an async function that always receives three arguments.
@@ -206,11 +224,16 @@ module.exports = function (pluginConfig, config, callback) {}
### `analyzeCommits`
This plugin is responsible for determining the type of the next release. It additionally receives a `commits` array inside `config`. One commit is an object with a `message` and `hash` property. Call the callback with `'major'`, `'premajor'`, `'minor'`, `'preminor'`, `'patch'`, `'prepatch'`, `'prerelease'`, or `null` if nothing changed. Have a look at the [default implementation](https://github.com/semantic-release/commit-analyzer/).
This plugin is responsible for determining the type of the next release. It additionally receives a `commits` array inside `config`. One commit is an object with a `message` and `hash` property. Call the callback with `'major'`, `'premajor'`, `'minor'`, `'preminor'`, `'patch'`, `'prepatch'`, `'prerelease'`, or `null` if nothing changed.
While it may be tempting to use `'prepatch'`, `'preminor'` & `'prerelease'` as part of a release process, this is strongly discouraged. A better approach is to use [dist-tags](https://docs.npmjs.com/cli/dist-tag) to create release channels (such as 'latest', 'next', 'stable') and to return only `'major'`, `'premajor'` and `'minor'` from the commit analyzer.
Have a look at the [default implementation](https://github.com/semantic-release/commit-analyzer/).
### `generateNotes`
This plugin is responsible for generating release notes. Call the callback with the notes as a string. Have a look at the [default implementation](https://github.com/semantic-release/release-notes-generator/).
It receives a `commits` array, the `lastRelease` and `nextRelease` inside `config`.
### `verifyConditions`
@@ -258,7 +281,13 @@ It is indeed a great idea because it _forces_ you to follow best practices. If y
### Why should I trust `semantic-release` with my releases?
`semantic-release` has a full unit- and integration-test-suite that tests _actual_ `npm` publishes against the [npm-registry-couchapp](https://github.com/npm/npm-registry-couchapp/) on all major node.js versions from `^0.10` on. A new version wont get published if it doesnt pass on all these engines.
`semantic-release` has a full unit- and integration-test-suite that tests _actual_ `npm` publishes against the [npm-registry-couchapp](https://github.com/npm/npm-registry-couchapp/). A new version wont get published if it doesnt pass on all these engines.
### Why does `semantic-release` require node version >= 8
Being able to write code for just the most recent node versions greatly simplifies development. More language features are available, no transpilation is required, less test builds are to be run, awaited and debugged.
For a special purpose tool like `semantic-release`, that's only meant to be used in controlled CI environments, we think it's okay to have such a high version requirement. As `semantic-release` handles package publishing we expect almost every project to have at least one build job running node 8 already and that's all it takes. Even if that's not that case `semantic-release` can still be executed with the help of [npx](https://www.npmjs.com/package/npx) (`npx -p node@8 npm run semantic-release`).
## Badge
+34
View File
@@ -0,0 +1,34 @@
# Troubleshooting semantic-release
### ENOTINHISTORY Commit not in history
```
semantic-release ERR! commits The commit the last release of this package was derived from is not in the direct history of the "master" branch.
semantic-release ERR! commits This means semantic-release can not extract the commits between now and then.
semantic-release ERR! commits This is usually caused by force pushing, releasing from an unrelated branch, or using an already existing package name.
semantic-release ERR! commits You can recover from this error by publishing manually or restoring the commit "123".
semantic-release ERR! pre Failed to determine new version.
semantic-release ERR! pre ENOTINHISTORY Commit not in history
```
To restore semantic-release, follow these steps:
```
git pull
git reset --hard origin/master
npm version x.y.z # check your current version and set this based on semver rules manually
# if you have a PR workflow, create a new branch, otherwise commit to master
git checkout -B chore/release
git commit -am 'chore: release'
git push
# merge (not squash-merge) on github (this is important before running git push). This is only required when you work with branches
git checkout master
# definitely required
git pull
git push --tags
npm publish
```
+22 -158
View File
@@ -1,164 +1,28 @@
#!/usr/bin/env node
var fs = require('fs')
var path = require('path')
var url = require('url')
// Bad news: We have to write plain ES5 in this file
// Good news: It's the only file of the entire project
var _ = require('lodash')
var log = require('npmlog')
var nopt = require('nopt')
var npmconf = require('npmconf')
var normalizeData = require('normalize-package-data')
var semver = require('semver');
log.heading = 'semantic-release'
var env = process.env
var pkg = JSON.parse(fs.readFileSync('./package.json'))
var originalPkg = _.cloneDeep(pkg)
normalizeData(pkg)
var knownOptions = {
branch: String,
debug: Boolean,
'github-token': String,
'github-url': String,
'analyze-commits': [path, String],
'generate-notes': [path, String],
'verify-conditions': [path, String],
'verify-release': [path, String]
if (semver.lt(process.version, '8.0.0')) {
console.error(
`semantic-release: node version >= 8 is required. Found ${process.version}.
If there is another job running on node version >= 8, it will be picked as
the build leader and you can safely ignore this message.
If you don't have node 8 in your build matrix you can use "npx" to restore
compatibility with minimal overhead:
$ npx -p node@8 npm run semantic-release
npx is bundled with npm >= 5.4, or available via npm. More info: npm.im/npx`
);
process.exit(1);
}
var options = _.defaults(
_.mapKeys(nopt(knownOptions), function (value, key) {
return _.camelCase(key)
}),
pkg.release,
{
branch: 'master',
fallbackTags: {
next: 'latest'
},
debug: !env.CI,
githubToken: env.GH_TOKEN || env.GITHUB_TOKEN,
githubUrl: env.GH_URL
}
)
var plugins = require('../src/lib/plugins')(options)
npmconf.load({}, function (err, conf) {
if (err) {
log.error('init', 'Failed to load npm config.', err)
process.exit(1)
}
var npm = {
auth: {
token: env.NPM_TOKEN
},
loglevel: conf.get('loglevel'),
registry: require('../src/lib/get-registry')(pkg, conf),
tag: (pkg.publishConfig || {}).tag || conf.get('tag') || 'latest'
}
// normalize trailing slash
npm.registry = url.format(url.parse(npm.registry))
log.level = npm.loglevel
var config = {
env: env,
pkg: pkg,
options: options,
plugins: plugins,
npm: npm
}
var hide = {}
if (options.githubToken) hide.githubToken = '***'
log.verbose('init', 'options:', _.assign({}, options, hide))
log.verbose('init', 'Verifying config.')
var errors = require('../src/lib/verify')(config)
errors.forEach(function (err) {
log.error('init', err.message + ' ' + err.code)
})
if (errors.length) process.exit(1)
if (options.argv.remain[0] === 'pre') {
log.verbose('pre', 'Running pre-script.')
log.verbose('pre', 'Veriying conditions.')
plugins.verifyConditions(config, function (err) {
if (err) {
log[options.debug ? 'warn' : 'error']('pre', err.message)
if (!options.debug) process.exit(1)
}
var nerfDart = require('nerf-dart')(npm.registry)
var wroteNpmRc = false
if (env.NPM_OLD_TOKEN && env.NPM_EMAIL) {
// Using the old auth token format is not considered part of the public API
// This might go away anytime (i.e. once we have a better testing strategy)
conf.set('_auth', '${NPM_OLD_TOKEN}', 'project')
conf.set('email', '${NPM_EMAIL}', 'project')
wroteNpmRc = true
} else if (env.NPM_TOKEN) {
conf.set(nerfDart + ':_authToken', '${NPM_TOKEN}', 'project')
wroteNpmRc = true
}
conf.save('project', function (err) {
if (err) return log.error('pre', 'Failed to save npm config.', err)
if (wroteNpmRc) log.verbose('pre', 'Wrote authToken to .npmrc.')
require('../src/pre')(config, function (err, release) {
if (err) {
log.error('pre', 'Failed to determine new version.')
var args = ['pre', (err.code ? err.code + ' ' : '') + err.message]
if (err.stack) args.push(err.stack)
log.error.apply(log, args)
process.exit(1)
}
var message = 'Determined version ' + release.version + ' as "' + npm.tag + '".'
log.verbose('pre', message)
if (options.debug) {
log.error('pre', message + ' Not publishing in debug mode.', release)
process.exit(1)
}
try {
var shrinkwrap = JSON.parse(fs.readFileSync('./npm-shrinkwrap.json'))
shrinkwrap.version = release.version
fs.writeFileSync('./npm-shrinkwrap.json', JSON.stringify(shrinkwrap, null, 2))
log.verbose('pre', 'Wrote version ' + release.version + 'to npm-shrinkwrap.json.')
} catch (e) {
log.silly('pre', 'Couldn\'t find npm-shrinkwrap.json.')
}
fs.writeFileSync('./package.json', JSON.stringify(_.assign(originalPkg, {
version: release.version
}), null, 2))
log.verbose('pre', 'Wrote version ' + release.version + ' to package.json.')
})
})
})
} else if (options.argv.remain[0] === 'post') {
log.verbose('post', 'Running post-script.')
require('../src/post')(config, function (err, published, release) {
if (err) {
log.error('post', 'Failed to publish release notes.', err)
process.exit(1)
}
log.verbose('post', (published ? 'Published' : 'Generated') + ' release notes.', release)
})
} else {
log.error('post', 'Command "' + options.argv.remain[0] + '" not recognized. User either "pre" or "post"')
}
})
// node 8+ from this point on
require('../src/cli')().catch(() => {
process.exitCode = 1;
});
+2
View File
@@ -0,0 +1,2 @@
codecov:
branch: caribou
+89 -41
View File
@@ -1,7 +1,7 @@
{
"name": "semantic-release",
"description": "automated semver compliant package publishing",
"version": "0.0.0-placeholder",
"description": "Automated semver compliant package publishing",
"version": "0.0.0-development",
"author": "Stephan Bönnemann <stephan@boennemann.me> (http://boennemann.me)",
"bin": {
"semantic-release": "bin/semantic-release.js"
@@ -9,47 +9,82 @@
"bugs": {
"url": "https://github.com/semantic-release/semantic-release/issues"
},
"czConfig": {
"path": "node_modules/cz-conventional-changelog/"
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
},
"dependencies": {
"@bahmutov/parse-github-repo-url": "^0.1.0",
"@semantic-release/commit-analyzer": "^2.0.0",
"@semantic-release/condition-travis": "^5.0.0",
"@semantic-release/error": "^1.0.0",
"@semantic-release/last-release-npm": "^1.2.1",
"@semantic-release/release-notes-generator": "^2.0.0",
"@semantic-release/commit-analyzer": "^4.0.0",
"@semantic-release/condition-travis": "^6.0.0",
"@semantic-release/error": "^2.1.0",
"@semantic-release/last-release-npm": "^2.0.0",
"@semantic-release/release-notes-generator": "^5.0.0",
"chalk": "^2.3.0",
"commander": "^2.11.0",
"debug": "^3.1.0",
"execa": "^0.8.0",
"fs-extra": "^4.0.2",
"git-head": "^1.2.1",
"github": "^0.2.4",
"github": "^12.0.0",
"lodash": "^4.0.0",
"marked": "^0.3.6",
"marked-terminal": "^2.0.0",
"nerf-dart": "^1.0.0",
"nopt": "^3.0.3",
"normalize-package-data": "^2.3.4",
"npmconf": "^2.1.2",
"npmlog": "^2.0.0",
"npm-conf": "^1.1.2",
"p-series": "^1.0.0",
"parse-github-repo-url": "^1.3.0",
"require-relative": "^0.8.7",
"run-auto": "^1.1.2",
"run-series": "^1.1.3",
"semver": "^5.0.3"
"semver": "^5.4.1"
},
"devDependencies": {
"coveralls": "^2.11.4",
"cz-conventional-changelog": "^1.1.4",
"mkdirp": "^0.5.1",
"nixt": "^0.5.0",
"nock": "^7.0.1",
"npm-registry-couchapp": "^2.6.11",
"nyc": "^6.1.1",
"proxyquire": "^1.7.3",
"ava": "^0.23.0",
"codecov": "^3.0.0",
"commitizen": "^2.9.6",
"cz-conventional-changelog": "^2.0.0",
"dockerode": "^2.5.2",
"eslint": "^4.7.0",
"eslint-config-prettier": "^2.5.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-prettier": "^2.3.0",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1",
"get-stream": "^3.0.0",
"mockserver-client": "^1.0.16",
"nock": "^9.0.2",
"npm-registry-couchapp": "^2.6.12",
"nyc": "^11.2.1",
"p-map-series": "^1.0.0",
"prettier": "^1.7.0",
"proxyquire": "^1.8.0",
"rimraf": "^2.5.0",
"standard": "^6.0.3",
"tap": "^5.0.0"
"sinon": "^4.0.0",
"tempy": "^0.2.1"
},
"engines": {
"node": ">=0.10",
"node": ">=4",
"npm": ">=2"
},
"homepage": "https://github.com/semantic-release/semantic-release/tree/next#readme",
"eslintConfig": {
"extends": [
"standard",
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": 2
}
},
"files": [
"bin",
"src"
],
"homepage": "https://github.com/semantic-release/semantic-release#readme",
"keywords": [
"author",
"automation",
@@ -62,11 +97,24 @@
"version"
],
"license": "MIT",
"main": "bin/semantic-release.js",
"files": [
"bin",
"src"
],
"main": "index.js",
"nyc": {
"include": [
"src/**/*.js"
],
"reporter": [
"json",
"text",
"html"
],
"all": true
},
"prettier": {
"printWidth": 120,
"singleQuote": true,
"bracketSpacing": false,
"trailingComma": "es5"
},
"publishConfig": {
"tag": "next"
},
@@ -78,12 +126,12 @@
"url": "git+https://github.com/semantic-release/semantic-release.git"
},
"scripts": {
"coverage": "nyc report",
"coverage:upload": "npm run coverage -s -- --reporter=text-lcov | coveralls",
"pretest": "standard",
"semantic-release": "./bin/semantic-release.js pre && npm publish && ./bin/semantic-release.js post",
"test": "npm run test:unit && npm run test:integration",
"test:integration": "tap --no-cov test/scenarios/*.js",
"test:unit": "nyc tap --no-cov test/specs/*.js"
"clean": "rimraf coverage && rimraf .nyc_output",
"cm": "git-cz",
"codecov": "codecov -f coverage/coverage-final.json",
"lint": "eslint .",
"pretest": "npm run clean && npm run lint",
"semantic-release": "./bin/semantic-release.js",
"test": "nyc ava -v"
}
}
Executable
+58
View File
@@ -0,0 +1,58 @@
const program = require('commander');
const logger = require('./lib/logger');
function list(values) {
return values.split(',').map(value => value.trim());
}
module.exports = async () => {
program
.name('semantic-release')
.description('Run automated package publishing')
.option('-b, --branch <branch>', 'Branch to release from')
.option('--github-token <token>', 'Token to authenticate with Github API')
.option('--github-url <url>', 'GitHub Enterprise endpoint')
.option('--github-api-path-prefix <prefix>', 'Prefix of the GitHub Enterprise endpoint')
.option(
'--verify-conditions <paths>',
'Comma separated list of paths or packages name for the verifyConditions plugin',
list
)
.option('--get-last-release <path>', 'Path or package name for the getLastRelease plugin')
.option('--analyze-commits <path>', 'Path or package name for the analyzeCommits plugin')
.option(
'--verify-release <paths>',
'Comma separated list of paths or packages name for the verifyRelease plugin',
list
)
.option('--generate-notes <path>', 'Path or package name for the generateNotes plugin')
.option('--debug', 'Output debugging information')
.option(
'-d, --dry-run',
'Dry-run mode, skipping verifyConditions, publishing and release, printing next version and release notes'
)
.parse(process.argv);
if (program.debug) {
// Debug must be enabled before other requires in order to work
require('debug').enable('semantic-release:*');
}
try {
if (program.args.length > 0) {
program.outputHelp();
process.exitCode = 1;
} else {
await require('./index')(program);
}
} catch (err) {
// If error is a SemanticReleaseError then it's an expected exception case (no release to be done, running on a PR etc..) and the cli will return with 0
// Otherwise it's an unexpected error (configuration issue, code issue, plugin issue etc...) and the cli will return 1
if (err.semanticRelease) {
logger.log(`%s ${err.message}`, err.code);
} else {
process.exitCode = 1;
logger.error('An error occurred while running semantic-release: %O', err);
}
}
};
+60
View File
@@ -0,0 +1,60 @@
const marked = require('marked');
const TerminalRenderer = require('marked-terminal');
const SemanticReleaseError = require('@semantic-release/error');
const getConfig = require('./lib/get-config');
const getNextVersion = require('./lib/get-next-version');
const verifyPkg = require('./lib/verify-pkg');
const verifyAuth = require('./lib/verify-auth');
const getCommits = require('./lib/get-commits');
const publishNpm = require('./lib/publish-npm');
const githubRelease = require('./lib/github-release');
const logger = require('./lib/logger');
module.exports = async opts => {
const config = await getConfig(opts);
const {plugins, env, options, pkg, npm} = config;
logger.log('Run automated release for %s on branch %s', pkg.name, options.branch);
verifyPkg(pkg);
if (!options.dryRun) {
verifyAuth(options, env);
}
if (!options.dryRun) {
logger.log('Call plugin %s', 'verify-conditions');
await plugins.verifyConditions({env, options, pkg, npm, logger});
}
logger.log('Call plugin %s', 'get-last-release');
const {commits, lastRelease} = await getCommits(
await plugins.getLastRelease({env, options, pkg, npm, logger}),
options.branch
);
logger.log('Call plugin %s', 'analyze-commits');
const type = await plugins.analyzeCommits({env, options, pkg, npm, logger, lastRelease, commits});
if (!type) {
throw new SemanticReleaseError('There are no relevant changes, so no new version is released.', 'ENOCHANGE');
}
const nextRelease = {type, version: getNextVersion(type, lastRelease)};
logger.log('Call plugin %s', 'verify-release');
await plugins.verifyRelease({env, options, pkg, npm, logger, lastRelease, commits, nextRelease});
if (!options.dryRun) {
await publishNpm(pkg, npm, nextRelease);
}
logger.log('Call plugin %s', 'generate-notes');
const notes = await plugins.generateNotes({env, options, pkg, npm, logger, lastRelease, commits, nextRelease});
if (options.dryRun) {
marked.setOptions({renderer: new TerminalRenderer()});
logger.log('Release note for version %s:\n', nextRelease.version);
console.log(marked(notes));
} else {
const releaseUrl = await githubRelease(pkg, notes, nextRelease.version, options);
logger.log('Published Github release: %s', releaseUrl);
}
};
-71
View File
@@ -1,71 +0,0 @@
var exec = require('child_process').exec
var log = require('npmlog')
var SemanticReleaseError = require('@semantic-release/error')
module.exports = function (config, cb) {
var lastRelease = config.lastRelease
var options = config.options
var branch = options.branch
var from = lastRelease.gitHead
var range = (from ? from + '..' : '') + 'HEAD'
if (!from) return extract()
exec('git branch --contains ' + from, function (err, stdout) {
var inHistory = false
var branches
if (!err && stdout) {
branches = stdout.split('\n')
.map(function (result) {
if (branch === result.replace('*', '').trim()) {
inHistory = true
return null
}
return result.trim()
})
.filter(function (branch) {
return !!branch
})
}
if (!inHistory) {
log.error('commits',
'The commit the last release of this package was derived from is not in the direct history of the "' + branch + '" branch.\n' +
'This means semantic-release can not extract the commits between now and then.\n' +
'This is usually caused by force pushing, releasing from an unrelated branch, or using an already existing package name.\n' +
'You can recover from this error by publishing manually or restoring the commit "' + from + '".' + (branches && branches.length
? '\nHere is a list of branches that still contain the commit in question: \n * ' + branches.join('\n * ')
: ''
))
return cb(new SemanticReleaseError('Commit not in history', 'ENOTINHISTORY'))
}
extract()
})
function extract () {
exec(
'git log -E --format=%H==SPLIT==%B==END== ' + range,
function (err, stdout) {
if (err) return cb(err)
cb(null, String(stdout).split('==END==\n')
.filter(function (raw) {
return !!raw.trim()
})
.map(function (raw) {
var data = raw.split('==SPLIT==')
return {
hash: data[0],
message: data[1]
}
}))
}
)
}
}
+9
View File
@@ -0,0 +1,9 @@
function debugShell(message, shell, debug) {
debug(message);
debug('cmd: %O', shell.cmd);
debug('stdout: %O', shell.stdout);
debug('stderr: %O', shell.stderr);
debug('code: %O', shell.code);
}
module.exports = {debugShell};
+112
View File
@@ -0,0 +1,112 @@
const execa = require('execa');
const debug = require('debug')('semantic-release:get-commits');
const getVersionHead = require('./get-version-head');
const {debugShell} = require('./debug');
const logger = require('./logger');
/**
* Commit message.
*
* @typedef {Object} Commit
* @property {string} hash The commit hash.
* @property {string} message The commit message.
*/
/**
* Last release.
*
* @typedef {Object} LastRelease
* @property {string} version The version number of the last release.
* @property {string} [gitHead] The commit sha used to make the last release.
*/
/**
* Result object.
*
* @typedef {Object} Result
* @property {Array<Commit>} commits The list of commits since the last release.
* @property {LastRelease} lastRelease The updated lastRelease.
*/
/**
* Retrieve the list of commits on the current branch since the last released version, or all the commits of the current branch if there is no last released version.
*
* The commit correspoding to the last released version is determined as follow:
* - Use `lastRelease.gitHead` if defined and present in `branch` history.
* - If `lastRelease.gitHead` is not in the `branch` history, unshallow the repository and try again.
* - If `lastRelease.gitHead` is still not in the `branch` history, search for a tag named `v<version>` or `<version>` and verify if it's associated commit sha is present in `branch` history.
*
* @param {LastRelease} lastRelease The lastRelease object obtained from the getLastRelease plugin.
* @param {string} branch The branch to release from.
* @param {Object} logger Global logger.
*
* @return {Promise<Result>} The list of commits on the branch `branch` since the last release and the updated lastRelease with the gitHead used to retrieve the commits.
*
* @throws {SemanticReleaseError} with code `ENOTINHISTORY` if `lastRelease.gitHead` or the commit sha derived from `config.lastRelease.version` is not in the direct history of `branch`.
* @throws {SemanticReleaseError} with code `ENOGITHEAD` if `lastRelease.gitHead` is undefined and no commit sha can be found for the `config.lastRelease.version`.
*/
module.exports = async ({version, gitHead}, branch) => {
if (gitHead || version) {
try {
gitHead = await getVersionHead(gitHead, version, branch);
} catch (err) {
if (err.code === 'ENOTINHISTORY') {
logger.error(notInHistoryMessage(err.gitHead, branch, version));
} else {
logger.error(noGitHeadMessage(branch, version));
}
throw err;
}
logger.log('Retrieving commits since %s, corresponding to version %s', gitHead, version);
} else {
logger.log('No previous release found, retrieving all commits');
// If there is no gitHead nor a version, there is no previous release. Unshallow the repo in order to retrieve all commits
const shell = await execa('git', ['fetch', '--unshallow', '--tags'], {reject: false});
debugShell('Unshallow repo', shell, debug);
}
try {
const shell = await execa('git', [
'log',
'--format=format:%H==SPLIT==%B==END==',
`${gitHead ? gitHead + '..' : ''}HEAD`,
]);
debugShell('Get commits', shell, debug);
const commits = shell.stdout
.split('==END==')
.filter(raw => !!raw.trim())
.map(raw => {
const [hash, message] = raw.trim().split('==SPLIT==');
return {hash, message};
});
logger.log('Found %s commits since last release', commits.length);
debug('Parsed commits: %o', commits);
return {commits, lastRelease: {version, gitHead}};
} catch (err) {
debug(err);
logger.log('Found no commit since last release');
return {commits: [], lastRelease: {version, gitHead}};
}
};
function noGitHeadMessage(branch, version) {
return `The commit the last release of this package was derived from cannot be determined from the release metadata nor from the repository tags.
This means semantic-release can not extract the commits between now and then.
This is usually caused by releasing from outside the repository directory or with innaccessible git metadata.
You can recover from this error by creating a tag for the version "${version}" on the commit corresponding to this release:
$ git tag -f v${version} <commit sha1 corresponding to last release>
$ git push -f --tags origin ${branch}
`;
}
function notInHistoryMessage(gitHead, branch, version) {
return `The commit the last release of this package was derived from is not in the direct history of the "${branch}" branch.
This means semantic-release can not extract the commits between now and then.
This is usually caused by force pushing, releasing from an unrelated branch, or using an already existing package name.
You can recover from this error by restoring the commit "${gitHead}" or by creating a tag for the version "${version}" on the commit corresponding to this release:
$ git tag -f v${version || '<version>'} <commit sha1 corresponding to last release>
$ git push -f --tags origin ${branch}
`;
}
+43
View File
@@ -0,0 +1,43 @@
const url = require('url');
const {readJson} = require('fs-extra');
const {defaults} = require('lodash');
const npmConf = require('npm-conf');
const normalizeData = require('normalize-package-data');
const debug = require('debug')('semantic-release:config');
const logger = require('./logger');
const getPlugins = require('./plugins');
const getRegistry = require('./get-registry');
module.exports = async opts => {
const pkg = await readJson('./package.json');
const {GH_TOKEN, GITHUB_TOKEN, GH_URL} = process.env;
normalizeData(pkg);
const options = defaults(opts, pkg.release, {
branch: 'master',
fallbackTags: {next: 'latest'},
githubToken: GH_TOKEN || GITHUB_TOKEN,
githubUrl: GH_URL,
});
debug('branch: %O', options.branch);
debug('fallbackTags: %O', options.fallbackTags);
debug('analyzeCommits: %O', options.analyzeCommits);
debug('generateNotes: %O', options.generateNotes);
debug('verifyConditions: %O', options.verifyConditions);
debug('verifyRelease: %O', options.verifyRelease);
const plugins = await getPlugins(options);
const conf = npmConf();
const npm = {
auth: {token: process.env.NPM_TOKEN},
registry: getRegistry(pkg, conf),
tag: (pkg.publishConfig || {}).tag || conf.get('tag'),
conf,
};
// normalize trailing slash
npm.registry = url.format(url.parse(npm.registry));
debug('npm registry: %O', npm.registry);
debug('npm tag: %O', npm.tag);
return {env: process.env, pkg, options, plugins, npm, logger};
};
+19
View File
@@ -0,0 +1,19 @@
const semver = require('semver');
const SemanticReleaseError = require('@semantic-release/error');
const logger = require('./logger');
module.exports = (type, lastRelease) => {
let version;
if (!lastRelease.version) {
version = '1.0.0';
logger.log('There is no previous release, the next release version is %s', version);
} else {
version = semver.inc(lastRelease.version, type);
if (!version) {
throw new SemanticReleaseError(`Invalid release type ${type}`, 'EINVALIDTYPE');
}
logger.log('The next release version is %s', version);
}
return version;
};
+9 -10
View File
@@ -1,12 +1,11 @@
module.exports = function (pkg, conf) {
if (pkg.publishConfig && pkg.publishConfig.registry) return pkg.publishConfig.registry
module.exports = ({publishConfig, name}, conf) => {
if (publishConfig && publishConfig.registry) {
return publishConfig.registry;
}
if (pkg.name[0] !== '@') return conf.get('registry') || 'https://registry.npmjs.org/'
if (name[0] !== '@') {
return conf.get('registry') || 'https://registry.npmjs.org/';
}
var scope = pkg.name.split('/')[0]
var scopedRegistry = conf.get(scope + '/registry')
if (scopedRegistry) return scopedRegistry
return conf.get('registry') || 'https://registry.npmjs.org/'
}
return conf.get(`${name.split('/')[0]}/registry`) || conf.get('registry') || 'https://registry.npmjs.org/';
};
+86
View File
@@ -0,0 +1,86 @@
const execa = require('execa');
const debug = require('debug')('semantic-release:get-version-head');
const SemanticReleaseError = require('@semantic-release/error');
const {debugShell} = require('./debug');
/**
* Get the commit sha for a given tag.
*
* @param {string} tagName Tag name for which to retrieve the commit sha.
*
* @return {string} The commit sha of the tag in parameter or `null`.
*/
async function gitTagHead(tagName) {
try {
const shell = await execa('git', ['rev-list', '-1', '--tags', tagName]);
debugShell('Get git tag head', shell, debug);
return shell.stdout;
} catch (err) {
debug(err);
return null;
}
}
/**
* Verify if the commist `sha` is in the direct history of the current branch.
*
* @param {string} sha The sha of the commit to look for.
*
* @return {boolean} `true` if the commit `sha` is in the history of the current branch, `false` otherwise.
*/
async function isCommitInHistory(sha) {
const shell = await execa('git', ['merge-base', '--is-ancestor', sha, 'HEAD'], {reject: false});
debugShell('Check if commit is in history', shell, debug);
return shell.code === 0;
}
/**
* Get the commit sha for a given version, if it's contained in the given branch.
*
* @param {string} gitHead The commit sha to look for.
* @param {string} version The version corresponding to the commit sha to look for. Used to search in git tags.
*
* @return {Promise<string>} A Promise that resolves to the commit sha of the version, either `gitHead` of the commit associated with the `version` tag.
*
* @throws {SemanticReleaseError} with code `ENOTINHISTORY` if `gitHead` or the commit sha dereived from `version` is not in the direct history of `branch`.
* @throws {SemanticReleaseError} with code `ENOGITHEAD` if `gitHead` is undefined and no commit sha can be found for the `version`.
*/
module.exports = async (gitHead, version) => {
// Check if gitHead is defined and exists in release branch
if (gitHead && (await isCommitInHistory(gitHead))) {
debug('Use gitHead: %s', gitHead);
return gitHead;
}
// Ushallow the repository
const shell = await execa('git', ['fetch', '--unshallow', '--tags'], {reject: false});
debugShell('Unshallow repo', shell, debug);
// Check if gitHead is defined and exists in release branch again
if (gitHead && (await isCommitInHistory(gitHead))) {
debug('Use gitHead: %s', gitHead);
return gitHead;
}
let tagHead;
if (version) {
// If a version is defined search a corresponding tag
tagHead = (await gitTagHead(`v${version}`)) || (await gitTagHead(version));
// Check if tagHead is found and exists in release branch again
if (tagHead && (await isCommitInHistory(tagHead))) {
debug('Use tagHead: %s', tagHead);
return tagHead;
}
}
// Either gitHead is defined or a tagHead has been found but none is in the branch history
if (gitHead || tagHead) {
const error = new SemanticReleaseError('Commit not in history', 'ENOTINHISTORY');
error.gitHead = gitHead || tagHead;
throw error;
}
// There is no gitHead in the last release and there is no tags correponsing to the last release version
throw new SemanticReleaseError('There is no commit associated with last release', 'ENOGITHEAD');
};
+36
View File
@@ -0,0 +1,36 @@
const {promisify} = require('util');
const url = require('url');
const gitHead = require('git-head');
const GitHubApi = require('github');
const parseSlug = require('parse-github-repo-url');
const debug = require('debug')('semantic-release:github-release');
module.exports = async (pkg, notes, version, {branch, githubUrl, githubToken, githubApiPathPrefix}) => {
const [owner, repo] = parseSlug(pkg.repository.url);
let {port, protocol, hostname: host} = githubUrl ? url.parse(githubUrl) : {};
protocol = (protocol || '').split(':')[0] || null;
const pathPrefix = githubApiPathPrefix || null;
const github = new GitHubApi({port, protocol, host, pathPrefix});
debug('Github host: %o', host);
debug('Github port: %o', port);
debug('Github protocol: %o', protocol);
debug('Github pathPrefix: %o', pathPrefix);
github.authenticate({type: 'token', token: githubToken});
const name = `v${version}`;
const release = {owner, repo, tag_name: name, name, target_commitish: branch, body: notes};
debug('release owner: %o', owner);
debug('release repo: %o', repo);
debug('release name: %o', name);
debug('release branch: %o', branch);
const sha = await promisify(gitHead)();
const ref = `refs/tags/${name}`;
debug('Create git tag %o with commit %o', ref, sha);
await github.gitdata.createReference({owner, repo, ref, sha});
const {data: {html_url: releaseUrl}} = await github.repos.createRelease(release);
return releaseUrl;
};
+23
View File
@@ -0,0 +1,23 @@
const chalk = require('chalk');
/**
* Logger with `log` and `error` function.
*/
module.exports = {
log(...args) {
const [format, ...rest] = args;
console.log(
`${chalk.grey('[Semantic release]:')}${typeof format === 'string'
? ` ${format.replace(/%[^%]/g, seq => chalk.magenta(seq))}`
: ''}`,
...(typeof format === 'string' ? [] : [format]).concat(rest)
);
},
error(...args) {
const [format, ...rest] = args;
console.error(
`${chalk.grey('[Semantic release]:')}${typeof format === 'string' ? ` ${chalk.red(format)}` : ''}`,
...(typeof format === 'string' ? [] : [format]).concat(rest)
);
},
};
+3 -4
View File
@@ -1,4 +1,3 @@
/* istanbul ignore next */
module.exports = function (config, options, cb) {
cb(null)
}
module.exports = (config, options, cb) => {
cb(null);
};
+37 -34
View File
@@ -1,42 +1,45 @@
var relative = require('require-relative')
var series = require('run-series')
const {promisify} = require('util');
const relative = require('require-relative');
const pSeries = require('p-series');
const logger = require('./logger');
var exports = module.exports = function (options) {
var plugins = {
analyzeCommits: exports.normalize(options.analyzeCommits, '@semantic-release/commit-analyzer'),
generateNotes: exports.normalize(options.generateNotes, '@semantic-release/release-notes-generator'),
getLastRelease: exports.normalize(options.getLastRelease, '@semantic-release/last-release-npm')
}
;['verifyConditions', 'verifyRelease'].forEach(function (plugin) {
module.exports = options => {
const plugins = {
analyzeCommits: normalize(options.analyzeCommits, '@semantic-release/commit-analyzer'),
generateNotes: normalize(options.generateNotes, '@semantic-release/release-notes-generator'),
getLastRelease: normalize(options.getLastRelease, '@semantic-release/last-release-npm'),
};
['verifyConditions', 'verifyRelease'].forEach(plugin => {
if (!Array.isArray(options[plugin])) {
plugins[plugin] = exports.normalize(
plugins[plugin] = normalize(
options[plugin],
plugin === 'verifyConditions'
? '@semantic-release/condition-travis'
: './plugin-noop'
)
return
plugin === 'verifyConditions' ? '@semantic-release/condition-travis' : './plugin-noop'
);
} else {
plugins[plugin] = async pluginOptions => {
return pSeries(
options[plugin].map(step => {
return () => normalize(step, './plugin-noop')(pluginOptions);
})
);
};
}
});
plugins[plugin] = function (pluginOptions, cb) {
var tasks = options[plugin].map(function (step) {
return exports.normalize(step, './plugin-noop').bind(null, pluginOptions)
})
return plugins;
};
series(tasks, cb)
}
})
return plugins
}
exports.normalize = function (pluginConfig, fallback) {
if (typeof pluginConfig === 'string') return relative(pluginConfig).bind(null, {})
if (pluginConfig && (typeof pluginConfig.path === 'string')) {
return relative(pluginConfig.path).bind(null, pluginConfig)
const normalize = (pluginConfig, fallback) => {
if (typeof pluginConfig === 'string') {
logger.log('Load plugin %s', pluginConfig);
return promisify(relative(pluginConfig).bind(null, {}));
}
return require(fallback).bind(null, pluginConfig)
}
if (pluginConfig && typeof pluginConfig.path === 'string') {
logger.log('Load plugin %s', pluginConfig.path);
return promisify(relative(pluginConfig.path).bind(null, pluginConfig));
}
return promisify(require(fallback).bind(null, pluginConfig || {}));
};
module.exports.normalize = normalize;
+35
View File
@@ -0,0 +1,35 @@
const {appendFile, readJson, writeJson, pathExists} = require('fs-extra');
const execa = require('execa');
const nerfDart = require('nerf-dart');
const debug = require('debug')('semantic-release:publish-npm');
const {debugShell} = require('./debug');
const logger = require('./logger');
module.exports = async (pkg, {conf, registry, auth}, {version}) => {
const pkgFile = await readJson('./package.json');
if (await pathExists('./npm-shrinkwrap.json')) {
const shrinkwrap = await readJson('./npm-shrinkwrap.json');
shrinkwrap.version = version;
await writeJson('./npm-shrinkwrap.json', shrinkwrap);
logger.log('Wrote version %s to npm-shrinkwrap.json', version);
}
await writeJson('./package.json', Object.assign(pkgFile, {version}));
logger.log('Wrote version %s to package.json', version);
if (process.env.NPM_OLD_TOKEN && process.env.NPM_EMAIL) {
// Using the old auth token format is not considered part of the public API
// This might go away anytime (i.e. once we have a better testing strategy)
await appendFile('./.npmrc', `_auth = \${NPM_OLD_TOKEN}\nemail = \${NPM_EMAIL}`);
logger.log('Wrote NPM_OLD_TOKEN and NPM_EMAIL to .npmrc.');
} else {
await appendFile('./.npmrc', `${nerfDart(registry)}:_authToken = \${NPM_TOKEN}`);
logger.log('Wrote NPM_TOKEN to .npmrc.');
}
logger.log('Publishing version %s to npm registry %s', version, registry);
const shell = await execa('npm', ['publish']);
console.log(shell.stdout);
debugShell('Publishing on npm', shell, debug);
};
-21
View File
@@ -1,21 +0,0 @@
var SemanticReleaseError = require('@semantic-release/error')
module.exports = function (config, cb) {
var plugins = config.plugins
var lastRelease = config.lastRelease
plugins.analyzeCommits(config, function (err, type) {
if (err) return cb(err)
if (!type) {
return cb(new SemanticReleaseError(
'There are no relevant changes, so no new version is released.',
'ENOCHANGE'
))
}
if (!lastRelease.version) return cb(null, 'initial')
cb(null, type)
})
}
+11
View File
@@ -0,0 +1,11 @@
const SemanticReleaseError = require('@semantic-release/error');
module.exports = (options, env) => {
if (!options.githubToken) {
throw new SemanticReleaseError('No github token specified.', 'ENOGHTOKEN');
}
if (!(env.NPM_TOKEN || (env.NPM_OLD_TOKEN && env.NPM_EMAIL))) {
throw new SemanticReleaseError('No npm token specified.', 'ENONPMTOKEN');
}
};
+11
View File
@@ -0,0 +1,11 @@
const SemanticReleaseError = require('@semantic-release/error');
module.exports = pkg => {
if (!pkg.name) {
throw new SemanticReleaseError('No "name" found in package.json.', 'ENOPKGNAME');
}
if (!pkg.repository || !pkg.repository.url) {
throw new SemanticReleaseError('No "repository" found in package.json.', 'ENOPKGREPO');
}
};
-40
View File
@@ -1,40 +0,0 @@
var SemanticReleaseError = require('@semantic-release/error')
module.exports = function (config) {
var pkg = config.pkg
var options = config.options
var env = config.env
var errors = []
if (!pkg.name) {
errors.push(new SemanticReleaseError(
'No "name" found in package.json.',
'ENOPKGNAME'
))
}
if (!pkg.repository || !pkg.repository.url) {
errors.push(new SemanticReleaseError(
'No "repository" found in package.json.',
'ENOPKGREPO'
))
}
if (options.debug) return errors
if (!options.githubToken) {
errors.push(new SemanticReleaseError(
'No github token specified.',
'ENOGHTOKEN'
))
}
if (!(env.NPM_TOKEN || (env.NPM_OLD_TOKEN && env.NPM_EMAIL))) {
errors.push(new SemanticReleaseError(
'No npm token specified.',
'ENONPMTOKEN'
))
}
return errors
}
-54
View File
@@ -1,54 +0,0 @@
var url = require('url')
var gitHead = require('git-head')
var GitHubApi = require('github')
var parseSlug = require('@bahmutov/parse-github-repo-url')
module.exports = function (config, cb) {
var pkg = config.pkg
var options = config.options
var plugins = config.plugins
var ghConfig = options.githubUrl ? url.parse(options.githubUrl) : {}
var github = new GitHubApi({
version: '3.0.0',
port: ghConfig.port,
protocol: (ghConfig.protocol || '').split(':')[0] || null,
host: ghConfig.hostname,
pathPrefix: options.githubApiPathPrefix || null
})
plugins.generateNotes(config, function (err, log) {
if (err) return cb(err)
gitHead(function (err, hash) {
if (err) return cb(err)
var ghRepo = parseSlug(pkg.repository.url)
var release = {
owner: ghRepo[0],
repo: ghRepo[1],
name: 'v' + pkg.version,
tag_name: 'v' + pkg.version,
target_commitish: hash,
draft: !!options.debug,
body: log
}
if (options.debug && !options.githubToken) {
return cb(null, false, release)
}
github.authenticate({
type: 'oauth',
token: options.githubToken
})
github.releases.createRelease(release, function (err) {
if (err) return cb(err)
cb(null, true, release)
})
})
})
}
-45
View File
@@ -1,45 +0,0 @@
var _ = require('lodash')
var auto = require('run-auto')
var semver = require('semver')
var getCommits = require('./lib/commits')
var getType = require('./lib/type')
module.exports = function (config, cb) {
var plugins = config.plugins
auto({
lastRelease: plugins.getLastRelease.bind(null, config),
commits: ['lastRelease', function (cb, results) {
getCommits(_.assign({
lastRelease: results.lastRelease
}, config),
cb)
}],
type: ['commits', 'lastRelease', function (cb, results) {
getType(_.assign({
commits: results.commits,
lastRelease: results.lastRelease
}, config),
cb)
}]
}, function (err, results) {
if (err) return cb(err)
var nextRelease = {
type: results.type,
version: results.type === 'initial'
? '1.0.0'
: semver.inc(results.lastRelease.version, results.type)
}
plugins.verifyRelease(_.assign({
commits: results.commits,
lastRelease: results.lastRelease,
nextRelease: nextRelease
}, config), function (err) {
if (err) return cb(err)
cb(null, nextRelease)
})
})
}
+5
View File
@@ -0,0 +1,5 @@
module.exports = function(config, options, cb) {
const error = new Error('a');
error.errorProperty = 'errorProperty';
cb(error);
};
+3
View File
@@ -0,0 +1,3 @@
module.exports = function(config, options, cb) {
cb(new Error('b'));
};
+14
View File
@@ -0,0 +1,14 @@
const SemanticReleaseError = require('@semantic-release/error');
class InheritedError extends SemanticReleaseError {
constructor(message, code, newProperty) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.code = code;
}
}
module.exports = function(config, options, cb) {
cb(new InheritedError('Inherited error', 'EINHERITED'));
};
+3
View File
@@ -0,0 +1,3 @@
module.exports = function(config, options, cb) {
cb(null, 'a');
};
+3
View File
@@ -0,0 +1,3 @@
module.exports = function(config, options, cb) {
cb(null, 'b');
};
+3
View File
@@ -0,0 +1,3 @@
module.exports = function(pluginConfig, options, cb) {
cb(null, {pluginConfig, options});
};
+417
View File
@@ -0,0 +1,417 @@
import test from 'ava';
import proxyquire from 'proxyquire';
import {stub} from 'sinon';
import SemanticReleaseError from '@semantic-release/error';
import {
gitRepo,
gitCommits,
gitCheckout,
gitTagVersion,
gitShallowClone,
gitTags,
gitLog,
gitDetachedHead,
} from './helpers/git-utils';
test.beforeEach(t => {
// Save the current working diretory
t.context.cwd = process.cwd();
// Stub the logger functions
t.context.log = stub();
t.context.error = stub();
t.context.getCommits = proxyquire('../src/lib/get-commits', {
'./logger': {log: t.context.log, error: t.context.error},
});
});
test.afterEach.always(t => {
// Restore the current working directory
process.chdir(t.context.cwd);
});
test.serial('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
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module
const result = await t.context.getCommits({}, 'master');
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
});
test.serial('Get all commits when there is no last release, including the ones not in the shallow clone', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second']);
// Create a shallow clone with only 1 commit
await gitShallowClone(repo);
// Verify the shallow clone contains only one commit
t.is((await gitLog()).length, 1);
// Retrieve the commits with the commits module
const result = await t.context.getCommits({}, 'master');
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
});
test.serial('Get all commits since gitHead (from lastRelease)', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second', 'Third']);
// Retrieve the commits with the commits module, since commit 'First'
const result = await t.context.getCommits({gitHead: commits[commits.length - 1].hash}, 'master');
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead, commits[commits.length - 1].hash);
t.falsy(result.lastRelease.version);
});
test.serial('Get all commits since gitHead (from lastRelease) on a detached head repo', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second', 'Third']);
// Create a detached head repo at commit 'feat: Second'
await gitDetachedHead(repo, commits[1].hash);
// Retrieve the commits with the commits module, since commit 'First'
const result = await t.context.getCommits({gitHead: commits[commits.length - 1].hash}, 'master');
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
t.is(result.commits.length, 1);
t.is(result.commits[0].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[0].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead, commits[commits.length - 1].hash);
t.falsy(result.lastRelease.version);
});
test.serial('Get all commits since gitHead (from tag) ', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
const result = await t.context.getCommits({version: '1.0.0'}, 'master');
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get all commits since gitHead (from tag) on a detached head repo', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Create a detached head repo at commit 'feat: Second'
await gitDetachedHead(repo, commits[1].hash);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag 1.0.0)
const result = await t.context.getCommits({version: '1.0.0'}, 'master');
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
t.is(result.commits.length, 1);
t.is(result.commits[0].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[0].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get all commits since gitHead (from tag formatted like v<version>) ', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
const result = await t.context.getCommits({version: '1.0.0'}, 'master');
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get commits when last release gitHead is missing but a tag match the version', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
const result = await t.context.getCommits({version: '1.0.0', gitHead: 'missing'}, 'master');
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get all commits since gitHead, when gitHead are mising from the shallow clone', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second', 'Third']);
// Create a shallow clone with only 1 commit and no tags
await gitShallowClone(repo);
// Retrieve the commits with the commits module, since commit 'First'
const result = await t.context.getCommits({version: '1.0.0', gitHead: commits[commits.length - 1].hash}, 'master');
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get all commits since gitHead from tag, when tags are mising from the shallow clone', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second', 'Third'])).concat(commits);
// Create a shallow clone with only 1 commit and no tags
await gitShallowClone(repo);
// Verify the shallow clone does not contains any tags
t.is((await gitTags()).length, 0);
// Retrieve the commits with the commits module, since commit 'First' (associated with tag v1.0.0)
const result = await t.context.getCommits({version: '1.0.0'}, 'master');
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('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
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module, since commit 'Second' (therefore none)
const result = await t.context.getCommits({gitHead: commits[0].hash, version: '1.0.0'}, 'master');
// Verify no commit is retrieved
t.deepEqual(result.commits, []);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[0].hash);
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('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
await gitRepo();
// Retrieve the commits with the commits module
const result = await t.context.getCommits({}, 'master');
// Verify no commit is retrieved
t.deepEqual(result.commits, []);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
});
test.serial('Throws ENOGITHEAD error if the gitHead of the last release cannot be found', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module
const error = await t.throws(t.context.getCommits({version: '1.0.0'}, 'master'));
// Verify error code and type
t.is(error.code, 'ENOGITHEAD');
t.true(error instanceof SemanticReleaseError);
// Verify the log function has been called with a message explaining the error
t.regex(
t.context.error.firstCall.args[0],
/The commit the last release of this package was derived from cannot be determined from the release metadata nor from the repository tags/
);
});
test.serial('Throws ENOTINHISTORY error if gitHead is not in history', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module
const error = await t.throws(t.context.getCommits({gitHead: 'notinhistory'}, 'master'));
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.true(error instanceof SemanticReleaseError);
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.firstCall.args[0], /history of the "master" branch/);
// Verify the log function has been called with a message mentionning the missing gitHead
t.regex(t.context.error.firstCall.args[0], /restoring the commit "notinhistory"/);
});
test.serial('Throws ENOTINHISTORY error if gitHead is not in branch history but present in others', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First', 'Second']);
// Create the new branch 'other-branch' from master
await gitCheckout('other-branch');
// Add commits to the 'other-branch' branch
const commitsBranch = await gitCommits(['Third', 'Fourth']);
await gitCheckout('master', false);
// Retrieve the commits with the commits module
const error = await t.throws(t.context.getCommits({version: '1.0.1', gitHead: commitsBranch[0].hash}, 'master'));
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.true(error instanceof SemanticReleaseError);
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.firstCall.args[0], /history of the "master" branch/);
// Verify the log function has been called with a message mentionning the missing gitHead
t.regex(t.context.error.firstCall.args[0], new RegExp(`restoring the commit "${commitsBranch[0].hash}"`));
});
test.serial('Throws ENOTINHISTORY error if gitHead is not in detached head but present in other branch', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commit to the master branch
await gitCommits(['First']);
// Create the new branch 'other-branch' from master
await gitCheckout('other-branch');
// Add commits to the 'other-branch' branch
const commitsBranch = await gitCommits(['Second', 'Third']);
await gitCheckout('master', false);
// Add new commit to master branch
const commitsMaster = await gitCommits(['Fourth']);
// Create a detached head repo at commit 'Fourth'
await gitDetachedHead(repo, commitsMaster[0].hash);
// Retrieve the commits with the commits module, since commit 'Second'
const error = await t.throws(t.context.getCommits({version: '1.0.1', gitHead: commitsBranch[0].hash}, 'master'));
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.true(error instanceof SemanticReleaseError);
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.firstCall.args[0], /history of the "master" branch/);
// Verify the log function has been called with a message mentionning the missing gitHead
t.regex(t.context.error.firstCall.args[0], new RegExp(`restoring the commit "${commitsBranch[0].hash}"`));
});
test.serial('Throws ENOTINHISTORY error when a tag is not in branch history but present in others', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['First', 'Second']);
// Create the new branch 'other-branch' from master
await gitCheckout('other-branch');
// Add commits to the 'other-branch' branch
await gitCommits(['Third']);
// Create the tag corresponding to version 1.0.0
const shaTag = await gitTagVersion('v1.0.0');
await gitCheckout('master', false);
// Add new commit to the master branch
await gitCommits(['Forth']);
// Retrieve the commits with the commits module
const error = await t.throws(t.context.getCommits({version: '1.0.0'}, 'master'));
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.true(error instanceof SemanticReleaseError);
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.firstCall.args[0], /history of the "master" branch/);
// Verify the log function has been called with a message mentionning the missing gitHead
t.regex(t.context.error.firstCall.args[0], new RegExp(`restoring the commit "${shaTag}"`));
});
+154
View File
@@ -0,0 +1,154 @@
import url from 'url';
import test from 'ava';
import {writeJson, writeFile} from 'fs-extra';
import proxyquire from 'proxyquire';
import {stub} from 'sinon';
import normalizeData from 'normalize-package-data';
import {gitRepo} from './helpers/git-utils';
test.beforeEach(t => {
// Save the current process.env
t.context.env = Object.assign({}, process.env);
// Save the current working diretory
t.context.cwd = process.cwd();
t.context.plugins = stub().returns({});
t.context.getConfig = proxyquire('../src/lib/get-config', {'./plugins': t.context.plugins});
});
test.afterEach.always(t => {
// Restore the current working directory
process.chdir(t.context.cwd);
// Restore process.env
process.env = Object.assign({}, t.context.env);
});
test.serial('Default values', async t => {
const pkg = {name: 'package_name', release: {}};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', pkg);
process.env.GH_TOKEN = 'GH_TOKEN';
const result = await t.context.getConfig();
// Verify the normalized package is returned
normalizeData(pkg);
t.deepEqual(result.pkg, pkg);
// Verify the default options are set
t.is(result.options.branch, 'master');
t.is(result.options.githubToken, process.env.GH_TOKEN);
// Verify the default npm options are set
t.is(result.npm.tag, 'latest');
// Use the environment variable npm_config_registry as the default so the test works on both npm and yarn
t.is(result.npm.registry, url.format(url.parse(process.env.npm_config_registry || 'https://registry.npmjs.org/')));
});
test.serial('Read package.json configuration', async t => {
const release = {
analyzeCommits: 'analyzeCommits',
generateNotes: 'generateNotes',
getLastRelease: {
path: 'getLastRelease',
param: 'getLastRelease_param',
},
branch: 'test_branch',
};
const pkg = {name: 'package_name', release};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', pkg);
delete process.env.GH_TOKEN;
process.env.GITHUB_TOKEN = 'GITHUB_TOKEN';
const result = await t.context.getConfig();
// Verify the options contains the plugin config from package.json
t.is(result.options.analyzeCommits, release.analyzeCommits);
t.is(result.options.generateNotes, release.generateNotes);
t.deepEqual(result.options.getLastRelease, release.getLastRelease);
t.is(result.options.branch, release.branch);
// Verify the plugins module is called with the plugin options from package.json
t.is(t.context.plugins.firstCall.args[0].analyzeCommits, release.analyzeCommits);
t.is(t.context.plugins.firstCall.args[0].generateNotes, release.generateNotes);
t.deepEqual(t.context.plugins.firstCall.args[0].getLastRelease, release.getLastRelease);
t.is(t.context.plugins.firstCall.args[0].branch, release.branch);
t.is(result.options.githubToken, process.env.GITHUB_TOKEN);
});
test.serial('Priority cli parameters over package.json configuration', async t => {
const release = {
analyzeCommits: 'analyzeCommits',
generateNotes: 'generateNotes',
getLastRelease: {
path: 'getLastRelease',
param: 'getLastRelease_pkg',
},
branch: 'branch_pkg',
};
const options = {
getLastRelease: {
path: 'getLastRelease',
param: 'getLastRelease_cli',
},
branch: 'branch_cli',
};
const pkg = {name: 'package_name', release};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', pkg);
delete process.env.GH_TOKEN;
process.env.GITHUB_TOKEN = 'GITHUB_TOKEN';
const result = await t.context.getConfig(options);
// Verify the options contains the plugin config from cli
t.deepEqual(result.options.getLastRelease, options.getLastRelease);
t.is(result.options.branch, options.branch);
// Verify the plugins module is called with the plugin options from cli
t.deepEqual(t.context.plugins.firstCall.args[0].getLastRelease, options.getLastRelease);
t.is(t.context.plugins.firstCall.args[0].branch, options.branch);
});
test.serial('Get tag from .npmrc', async t => {
const pkg = {name: 'package_name'};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', pkg);
// Create local .npmrc
await writeFile('.npmrc', 'tag=npmrc_tag');
// Make sure to not use the environment variable set by npm when running tests with npm run test
delete process.env.npm_config_tag;
const result = await t.context.getConfig();
// Verify the tag used in the one in .npmrc
t.is(result.npm.tag, 'npmrc_tag');
});
test.serial('Get tag from package.json, even if defined in .npmrc', async t => {
const publishConfig = {tag: 'pkg_tag'};
const pkg = {name: 'package_name', publishConfig};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', pkg);
// Create local .npmrc
await writeFile('.npmrc', 'tag=npmrc_tag');
const result = await t.context.getConfig();
// Verify the tag used in the one in package.json
t.is(result.npm.tag, 'pkg_tag');
});
+36
View File
@@ -0,0 +1,36 @@
import test from 'ava';
import {stub} from 'sinon';
import proxyquire from 'proxyquire';
import SemanticReleaseError from '@semantic-release/error';
test.beforeEach(t => {
// Stub the logger functions
t.context.log = stub();
t.context.getNextVersion = proxyquire('../src/lib/get-next-version', {'./logger': {log: t.context.log}});
});
test('Increase version for patch release', t => {
const version = t.context.getNextVersion('patch', {version: '1.0.0'});
t.is(version, '1.0.1');
});
test('Increase version for minor release', t => {
const version = t.context.getNextVersion('minor', {version: '1.0.0'});
t.is(version, '1.1.0');
});
test('Increase version for major release', t => {
const version = t.context.getNextVersion('major', {version: '1.0.0'});
t.is(version, '2.0.0');
});
test('Return 1.0.0 if there is no previous release', t => {
const version = t.context.getNextVersion('minor', {});
t.is(version, '1.0.0');
});
test('Return an error if the release type is invalid', t => {
const error = t.throws(() => t.context.getNextVersion('invalid', {version: '1.0.0'}));
t.is(error.code, 'EINVALIDTYPE');
t.true(error instanceof SemanticReleaseError);
});
+82
View File
@@ -0,0 +1,82 @@
import test from 'ava';
import {stub} from 'sinon';
const getRegistry = require('../src/lib/get-registry');
test('Get registry from package.json', t => {
// Retrieve the registry with the get-registry module and verify it returns the one from the package.json in parameter
t.is(getRegistry({name: 'publish-config', publishConfig: {registry: 'a'}}, {}), 'a');
});
test('Prioritize the package.json registry config', t => {
// Stub the npmconf object
const get = stub();
// Retrieve the registry with the get-registry module and verify it returns the one from the package.json in parameter
t.is(getRegistry({name: 'publish-config', publishConfig: {registry: 'b'}}, {get}), 'b');
// Verify the registry has been retrieved from the package.json without trying the stubbed npmconf
t.true(get.notCalled);
});
test('Get registry for regular package name', t => {
// Stub the npmconf object returns 'b' for 'registry' property
const get = stub()
.withArgs('registry')
.returns('b');
// Retrieve the registry with the get-registry module and verify it returns the one configured in the stubbed npmconf
t.is(getRegistry({name: 'normal'}, {get}), 'b');
// Verify the registry has been retrieved by calling the stubbed npmconf
t.true(get.calledWithExactly('registry'));
});
test('Get default registry', t => {
// Stub the npmconf object, returns 'null'
const get = stub().returns(null);
// Retrieve the registry with the get-registry module and verify it returns default one
t.is(getRegistry({name: 'normal'}, {get}), 'https://registry.npmjs.org/');
// Verify the module tried first to retrieve the registry by calling the stubbed npmconf
t.true(get.calledWithExactly('registry'));
});
test('Get registry for scoped package name', t => {
// Stub the npmconf object, returns 'c' for '@scoped/registry' property
const get = stub()
.withArgs('@scoped/registry')
.returns('c');
// Retrieve the registry with the get-registry module and verify it returns the one configured in the stubbed npmconf
t.is(getRegistry({name: '@scoped/foo'}, {get}), 'c');
// Verify the registry for the scope '@scoped' has been retrieved by calling the stubbed npmconf
t.true(get.calledWithExactly('@scoped/registry'));
});
test('Get regular registry for scoped package name', t => {
// Stub the npmconf object, returns 'd' for 'registry' property
const get = stub()
.withArgs('registry')
.returns('d');
// Retrieve the registry with the get-registry module and verify it returns the regular default one for `@scoped` packages
t.is(getRegistry({name: '@scoped/baz'}, {get}), 'd');
// Verify the module tried to retrieve the @scoped registry by calling the stubbed npmconf
t.true(get.calledWithExactly('@scoped/registry'));
});
test('Get default registry for scoped package name', t => {
// Stub the npmconf object, returns 'd' for 'registry' property
const get = stub().returns(null);
// Retrieve the registry with the get-registry module and verify it returns default one for `@scoped` packages
t.is(getRegistry({name: '@scoped/baz'}, {get}), 'https://registry.npmjs.org/');
// Verify the module tried to retrieve the @scoped registry by calling the stubbed npmconf
t.true(get.calledWithExactly('@scoped/registry'));
// Verify the module tried to retrieve the regular registry by calling the stubbed npmconf
t.true(get.calledWithExactly('registry'));
});
+91
View File
@@ -0,0 +1,91 @@
import test from 'ava';
import {gitRepo, gitCommits, gitHead} from './helpers/git-utils';
import nock from 'nock';
import {authenticate} from './helpers/mock-github';
import githubRelease from '../src/lib/github-release';
test.beforeEach(t => {
// Save the current working diretory
t.context.cwd = process.cwd();
});
test.afterEach.always(t => {
// Restore the current working directory
process.chdir(t.context.cwd);
// Reset nock
nock.cleanAll();
});
test.serial('Github release with default url', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['fix: First fix', 'feat: Second feature']);
const sha = await gitHead();
const owner = 'test_user';
const repo = 'test_repo';
const githubToken = 'github_token';
const notes = 'Test release note body';
const version = '1.0.0';
const branch = 'master';
const tagName = `v${version}`;
const options = {branch, githubToken};
const pkg = {version, repository: {url: `git+https://othertesturl.com/${owner}/${repo}.git`}};
const releaseUrl = `https://othertesturl.com/${owner}/${repo}/releases/${version}`;
// Mock github API for releases and git/refs endpoints
const github = authenticate({githubToken})
.post(`/repos/${owner}/${repo}/releases`, {
tag_name: tagName,
target_commitish: branch,
name: tagName,
body: notes,
})
.reply(200, {html_url: releaseUrl})
.post(`/repos/${owner}/${repo}/git/refs`, {ref: `refs/tags/${tagName}`, sha})
.reply({});
// Call the post module
t.is(releaseUrl, await githubRelease(pkg, notes, version, options));
// Verify the releases and git/refs endpoint have been call with expected requests
t.true(github.isDone());
});
test.serial('Github release with custom url', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
await gitCommits(['fix: First fix', 'feat: Second feature']);
const sha = await gitHead();
const owner = 'test_user';
const repo = 'test_repo';
const githubUrl = 'https://testurl.com:443';
const githubToken = 'github_token';
const githubApiPathPrefix = 'prefix';
const notes = 'Test release note body';
const version = '1.0.0';
const branch = 'master';
const tagName = `v${version}`;
const options = {branch, githubUrl, githubToken, githubApiPathPrefix};
const pkg = {version, repository: {url: `git@othertesturl.com:${owner}/${repo}.git`}};
const releaseUrl = `https://othertesturl.com/${owner}/${repo}/releases/${version}`;
// Mock github API for releases and git/refs endpoints
const github = authenticate({githubUrl, githubToken, githubApiPathPrefix})
.post(`/repos/${owner}/${repo}/releases`, {
tag_name: tagName,
target_commitish: branch,
name: tagName,
body: notes,
})
.reply(200, {html_url: releaseUrl})
.post(`/repos/${owner}/${repo}/git/refs`, {ref: `refs/tags/${tagName}`, sha})
.reply({});
// Call the post module
t.is(releaseUrl, await githubRelease(pkg, notes, version, options));
// Verify the releases and git/refs endpoint have been call with expected requests
t.true(github.isDone());
});
+144
View File
@@ -0,0 +1,144 @@
import {mkdir} from 'fs-extra';
import tempy from 'tempy';
import execa from 'execa';
import pMapSeries from 'p-map-series';
/**
* 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 and change the current working directory to the repository root.
*
* @method gitCommits
* @param {Array<Commit>} commits the created commits.
*
* @return {string} The path of the repository.
*/
export async function gitRepo() {
const dir = tempy.directory();
process.chdir(dir);
await mkdir('git-templates');
await execa('git', ['init', '--template=./git-templates']);
await gitCheckout('master');
return dir;
}
/**
* Create commits on the current git repository.
*
* @param {Array<string>} messages commit messages.
*
* @returns {Array<Commit>} The created commits, in reverse order (to match `git log` order).
*/
export async function gitCommits(messages) {
return (await pMapSeries(messages, async msg => {
const {stdout} = await execa('git', ['commit', '-m', msg, '--allow-empty', '--no-gpg-sign']);
const [, branch, hash, message] = /^\[(\w+)\(?.*?\)?(\w+)\] (.+)$/.exec(stdout);
return {branch, hash, message};
})).reverse();
}
/**
* Amend a commit (rewriting the sha) on the current git repository.
*
* @param {string} messages commit message.
*
* @returns {Array<Commit>} the created commits.
*/
export async function gitAmmendCommit(msg) {
const {stdout} = await execa('git', ['commit', '--amend', '-m', msg, '--allow-empty']);
const [, branch, hash, message] = /^\[(\w+)\(?.*?\)?(\w+)\] (.+)(.|\s)+$/.exec(stdout);
return {branch, hash, message};
}
/**
* Checkout a branch on the current git repository.
*
* @param {string} branch Branch name.
* @param {boolean} create `true` to create the branche ans switch, `false` to only switch.
*/
export async function gitCheckout(branch, create = true) {
await execa('git', create ? ['checkout', '-b', branch] : ['checkout', branch]);
}
/**
* @return {string} The sha of the head commit in the current git repository.
*/
export async function gitHead() {
return (await execa('git', ['rev-parse', 'HEAD'])).stdout;
}
/**
* Create a tag on the head commit in the current git repository.
*
* @param {string} tagName The tag name to create.
* @param {string} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit.
*
* @return {string} The commit sha of the created tag.
*/
export async function gitTagVersion(tagName, sha) {
await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName]);
return (await execa('git', ['rev-list', '-1', '--tags', tagName])).stdout;
}
/**
* @return {Array<string>} The list of tags from the current git repository.
*/
export async function gitTags() {
return (await execa('git', ['tag'])).stdout.split('\n').filter(tag => !!tag);
}
/**
* @return {Array<string>} The list of commit sha from the current git repository.
*/
export async function gitLog() {
return (await execa('git', ['log', '--format=format:%H'])).stdout.split('\n').filter(sha => !!sha);
}
/**
* Create a shallow clone of a git repository and change the current working directory to the cloned repository root.
* The shallow will contain a limited number of commit and no tags.
*
* @param {string} origin The path of the repository to clone.
* @param {number} [depth=1] The number of commit to clone.
* @return {string} The path of the cloned repository.
*/
export async function gitShallowClone(origin, branch = 'master', depth = 1) {
const dir = tempy.directory();
process.chdir(dir);
await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, `file://${origin}`, dir]);
return dir;
}
/**
* Create a git repo with a detached head from another git repository and change the current working directory to the new repository root.
*
* @param {string} origin The path of the repository to clone.
* @param {number} head A commit sha of the origin repo that will become the detached head of the new one.
* @return {string} The path of the new repository.
*/
export async function gitDetachedHead(origin, head) {
const dir = tempy.directory();
process.chdir(dir);
await execa('git', ['init']);
await execa('git', ['remote', 'add', 'origin', origin]);
await execa('git', ['fetch']);
await execa('git', ['checkout', head]);
return dir;
}
/**
* Pack heads and tags of the current git repository.
*/
export async function gitPackRefs() {
await execa('git', ['pack-refs', '--all']);
}
+14
View File
@@ -0,0 +1,14 @@
import nock from 'nock';
/**
* Retun a `nock` object setup to respond to a github authentication request. Other expectation and responses can be chained.
*
* @param {String} [githubToken='GH_TOKEN'] The github token to return in the authentication response.
* @param {String} [githubUrl='https://api.github.com'] The url on which to intercept http requests.
* @return {Object} A `nock` object ready to respond to a github authentication request.
*/
export function authenticate(
{githubToken = 'GH_TOKEN', githubUrl = 'https://api.github.com', githubApiPathPrefix = ''} = {}
) {
return nock(`${githubUrl}/${githubApiPathPrefix}`, {reqheaders: {Authorization: `token ${githubToken}`}});
}
+89
View File
@@ -0,0 +1,89 @@
import Docker from 'dockerode';
import getStream from 'get-stream';
import {mockServerClient} from 'mockserver-client';
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.
*
* @return {Promise} Promise that resolves when the container is started.
*/
async function start() {
await getStream(await docker.pull('jamesdbloom/mockserver:latest'));
container = await docker.createContainer({
Image: 'jamesdbloom/mockserver',
PortBindings: {[`${MOCK_SERVER_PORT}/tcp`]: [{HostPort: `${MOCK_SERVER_PORT}`}]},
});
return container.start();
}
/**
* Stop the `mockserver` Docker container.
*
* @return {Promise} Promise that resolves when the container is stopped.
*/
async function stop() {
return container.stop();
}
/**
* @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.
*/
function mock(
path,
{body: requestBody, headers: requestHeaders},
{method = 'POST', statusCode = 200, body: responseBody}
) {
client.mockAnyResponse({
httpRequest: {path},
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: {type: 'JSON', json: JSON.stringify(requestBody), matchType: 'ONLY_MATCHING_FIELDS'},
};
}
/**
* 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.
*/
async function verify(expectation) {
return client.verify(expectation);
}
export default {start, stop, mock, verify, url};
+14
View File
@@ -0,0 +1,14 @@
import execa from 'execa';
const opts = {cwd: __dirname};
const uri = 'http://localhost:' + (process.env.TRAVIS === 'true' ? 5984 : 15986) + '/registry/_design/app/_rewrite/';
function start() {
return execa('./start.sh', opts);
}
function stop() {
return execa('./stop.sh', opts);
}
export default {start, stop, uri};
@@ -2,6 +2,7 @@
database_dir = data
view_index_dir = data
delayed_commits = false
uuid = bf4ecd84a7c89d60b5b2540fdf8c322c
[couch_httpd_auth]
public_fields = appdotnet, avatar, avatarMedium, avatarLarge, date, email, fields, freenode, fullname, github, homepage, name, roles, twitter, type, _id, _rev
@@ -37,4 +37,5 @@ export DEPLOY_VERSION=nope
# setup npm-registry-couchapp
npm explore npm-registry-couchapp -- npm start --npm-registry-couchapp:couch=$COUCH/registry
npm explore npm-registry-couchapp -- npm run load --npm-registry-couchapp:couch=$COUCH/registry
npm explore npm-registry-couchapp -- NO_PROMPT=yes npm run copy --npm-registry-couchapp:couch=$COUCH/registry
export NO_PROMPT=yes
npm explore npm-registry-couchapp -- npm run copy --npm-registry-couchapp:couch=$COUCH/registry
+278
View File
@@ -0,0 +1,278 @@
import test from 'ava';
import proxyquire from 'proxyquire';
import {stub} from 'sinon';
import SemanticReleaseError from '@semantic-release/error';
const consoleLog = stub(console, 'log');
test.beforeEach(t => {
// Save the current process.env
t.context.env = Object.assign({}, process.env);
// Save the current working diretory
t.context.cwd = process.cwd();
});
test.afterEach.always(t => {
// Restore the current working directory
process.chdir(t.context.cwd);
// Restore process.env
process.env = Object.assign({}, t.context.env);
});
test.after.always(t => {
consoleLog.restore();
});
test('Plugins are called with expected values', async t => {
const env = {NPM_TOKEN: 'NPM_TOKEN'};
const pkgOptions = {branch: 'master'};
const cliOptions = {githubToken: 'GH_TOKEN'};
const options = Object.assign({}, pkgOptions, cliOptions);
const pkg = {name: 'available', release: options, repository: {url: 'http://github.com/whats/up.git'}};
const npm = {registry: 'http://test.registry.com'};
const lastRelease = {version: '1.0.0', gitHead: 'test_commit_head'};
const commitsLastRelease = {version: '1.0.0', gitHead: 'tag_head'};
const commits = [{hash: '1', message: 'fix: First fix'}, {hash: '2', message: 'feat: First feature'}];
const nextRelease = {type: 'major', version: '2.0.0'};
const notes = 'Release notes';
// Stub modules
const log = stub();
const error = stub();
const logger = {log, error};
const verifyAuth = stub().returns();
const publishNpm = stub().resolves();
const githubRelease = stub().resolves();
const getCommits = stub().resolves({commits, lastRelease: commitsLastRelease});
const getNextVersion = stub().returns(nextRelease.version);
// Stub plugins
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves(lastRelease);
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves(notes);
const getConfig = stub().resolves({
plugins: {getLastRelease, analyzeCommits, verifyRelease, verifyConditions, generateNotes},
env,
options,
pkg,
npm,
});
const semanticRelease = proxyquire('../src/index', {
'./lib/logger': logger,
'./lib/verify-auth': verifyAuth,
'./lib/get-config': getConfig,
'./lib/get-commits': getCommits,
'./lib/publish-npm': publishNpm,
'./lib/github-release': githubRelease,
'./lib/get-next-version': getNextVersion,
});
// Call the index module
await semanticRelease(cliOptions);
// Verify the sub-modules have been called with expected parameters
t.true(getConfig.calledOnce);
t.true(getConfig.calledWithExactly(cliOptions));
t.true(verifyAuth.calledOnce);
t.true(verifyAuth.calledWithExactly(options, env));
t.true(publishNpm.calledOnce);
t.true(publishNpm.calledWithExactly(pkg, npm, nextRelease));
t.true(githubRelease.calledOnce);
t.true(githubRelease.calledWithExactly(pkg, notes, nextRelease.version, options));
// Verify plugins have been called with expected parameters
t.true(verifyConditions.calledOnce);
t.true(verifyConditions.calledWithExactly({env, options, pkg, npm, logger}));
t.true(getLastRelease.calledOnce);
t.true(getLastRelease.calledWithExactly({env, options, pkg, npm, logger}));
t.true(analyzeCommits.calledOnce);
t.true(analyzeCommits.calledWithExactly({env, options, pkg, npm, logger, lastRelease: commitsLastRelease, commits}));
t.true(verifyRelease.calledOnce);
t.true(
verifyRelease.calledWithExactly({
env,
options,
pkg,
npm,
logger,
lastRelease: commitsLastRelease,
commits,
nextRelease,
})
);
t.true(generateNotes.calledOnce);
t.true(
generateNotes.calledWithExactly({
env,
options,
pkg,
npm,
logger,
lastRelease: commitsLastRelease,
commits,
nextRelease,
})
);
});
test('Dry-run skips verifyAuth, verifyConditions, publishNpm and githubRelease', async t => {
const env = {NPM_TOKEN: 'NPM_TOKEN'};
const pkgOptions = {branch: 'master'};
const cliOptions = {githubToken: 'GH_TOKEN', dryRun: true};
const options = Object.assign({}, pkgOptions, cliOptions);
const pkg = {name: 'available', release: options, repository: {url: 'http://github.com/whats/up.git'}};
const npm = {registry: 'http://test.registry.com'};
const lastRelease = {version: '1.0.0', gitHead: 'test_commit_head'};
const commitsLastRelease = {version: '1.0.0', gitHead: 'tag_head'};
const commits = [{hash: '1', message: 'fix: First fix'}, {hash: '2', message: 'feat: First feature'}];
const nextRelease = {type: 'major', version: '2.0.0'};
const notes = 'Release notes';
// Stub modules
const log = stub();
const error = stub();
const logger = {log, error};
const verifyAuth = stub().returns();
const publishNpm = stub().resolves();
const githubRelease = stub().resolves();
const getCommits = stub().resolves({commits, lastRelease: commitsLastRelease});
const getNextVersion = stub().returns(nextRelease.version);
// Stub plugins
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves(lastRelease);
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves(notes);
const getConfig = stub().resolves({
plugins: {getLastRelease, analyzeCommits, verifyRelease, verifyConditions, generateNotes},
env,
options,
pkg,
npm,
});
const semanticRelease = proxyquire('../src/index', {
'./lib/logger': logger,
'./lib/verify-auth': verifyAuth,
'./lib/get-config': getConfig,
'./lib/get-commits': getCommits,
'./lib/publish-npm': publishNpm,
'./lib/github-release': githubRelease,
'./lib/get-next-version': getNextVersion,
});
// Call the index module
await semanticRelease(cliOptions);
// Verify that publishNpm, githubRelease, verifyAuth, verifyConditions have not been called in a dry run
t.true(publishNpm.notCalled);
t.true(githubRelease.notCalled);
t.true(verifyAuth.notCalled);
t.true(verifyConditions.notCalled);
// Verify the release notes are logged
t.true(consoleLog.calledWithMatch(notes));
// Verify the sub-modules have been called with expected parameters
t.true(getConfig.calledOnce);
t.true(getConfig.calledWithExactly(cliOptions));
// Verify plugins have been called with expected parameters
t.true(getLastRelease.calledOnce);
t.true(getLastRelease.calledWithExactly({env, options, pkg, npm, logger}));
t.true(analyzeCommits.calledOnce);
t.true(analyzeCommits.calledWithExactly({env, options, pkg, npm, logger, lastRelease: commitsLastRelease, commits}));
t.true(verifyRelease.calledOnce);
t.true(
verifyRelease.calledWithExactly({
env,
options,
pkg,
npm,
logger,
lastRelease: commitsLastRelease,
commits,
nextRelease,
})
);
t.true(generateNotes.calledOnce);
t.true(
generateNotes.calledWithExactly({
env,
options,
pkg,
npm,
logger,
lastRelease: commitsLastRelease,
commits,
nextRelease,
})
);
});
test('Throw SemanticReleaseError if there is no release to be done', async t => {
const env = {NPM_TOKEN: 'NPM_TOKEN'};
const pkgOptions = {branch: 'master'};
const cliOptions = {githubToken: 'GH_TOKEN'};
const options = Object.assign({}, pkgOptions, cliOptions);
const pkg = {name: 'available', release: options, repository: {url: 'http://github.com/whats/up.git'}};
const npm = {registry: 'http://test.registry.com'};
const lastRelease = {version: '1.0.0', gitHead: 'test_commit_head'};
const commitsLastRelease = {version: '1.0.0', gitHead: 'tag_head'};
const commits = [{hash: '1', message: 'fix: First fix'}, {hash: '2', message: 'feat: First feature'}];
const nextRelease = {type: undefined};
// Stub modules
const log = stub();
const error = stub();
const logger = {log, error};
const verifyAuth = stub().returns();
const publishNpm = stub().resolves();
const githubRelease = stub().resolves();
const getCommits = stub().resolves({commits, lastRelease: commitsLastRelease});
const getNextVersion = stub().returns(null);
// Stub plugins
const verifyConditions = stub().resolves();
const getLastRelease = stub().resolves(lastRelease);
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves();
const getConfig = stub().resolves({
plugins: {getLastRelease, analyzeCommits, verifyRelease, verifyConditions, generateNotes},
env,
options,
pkg,
npm,
});
const semanticRelease = proxyquire('../src/index', {
'./lib/logger': logger,
'./lib/verify-auth': verifyAuth,
'./lib/get-config': getConfig,
'./lib/get-commits': getCommits,
'./lib/publish-npm': publishNpm,
'./lib/github-release': githubRelease,
'./lib/get-next-version': getNextVersion,
});
// Call the index module
const err = await t.throws(semanticRelease(cliOptions));
// Verify error code and type
t.is(err.code, 'ENOCHANGE');
t.true(err instanceof SemanticReleaseError);
// Verify the sub-modules have been called with expected parameters
t.true(getConfig.calledOnce);
t.true(getConfig.calledWithExactly(cliOptions));
t.true(verifyAuth.calledOnce);
t.true(verifyAuth.calledWithExactly(options, env));
// Verify plugins have been called with expected parameters
t.true(verifyConditions.calledOnce);
t.true(verifyConditions.calledWithExactly({env, options, pkg, npm, logger}));
t.true(getLastRelease.calledOnce);
t.true(getLastRelease.calledWithExactly({env, options, pkg, npm, logger}));
t.true(analyzeCommits.calledOnce);
t.true(analyzeCommits.calledWithExactly({env, options, pkg, npm, logger, lastRelease: commitsLastRelease, commits}));
// Verify that verifyRelease, publishNpm, generateNotes, githubRelease have not been called when no release is done
t.true(verifyRelease.notCalled);
t.true(generateNotes.notCalled);
t.true(publishNpm.notCalled);
t.true(githubRelease.notCalled);
});
+689
View File
@@ -0,0 +1,689 @@
import test from 'ava';
import {writeJson, readJson} from 'fs-extra';
import {stub} from 'sinon';
import execa from 'execa';
import {gitRepo, gitCommits, gitHead, gitTagVersion, gitPackRefs, gitAmmendCommit} from './helpers/git-utils';
import registry from './helpers/registry';
import mockServer from './helpers/mockserver';
import semanticRelease from '../src';
// Environment variables used with cli
const env = {
npm_config_registry: registry.uri,
GH_TOKEN: 'github_token',
NPM_OLD_TOKEN: 'aW50ZWdyYXRpb246c3VjaHNlY3VyZQ==',
NPM_EMAIL: 'integration@test.com',
};
const cli = require.resolve('../bin/semantic-release');
const noop = require.resolve('../src/lib/plugin-noop');
const pluginError = require.resolve('./fixtures/plugin-error-a');
const pluginInheritedError = require.resolve('./fixtures/plugin-error-inherited');
test.before(async t => {
await mockServer.start();
// Start the local NPM registry
await registry.start();
});
test.beforeEach(async t => {
// Save the current process.env
t.context.env = Object.assign({}, process.env);
// Save the current working diretory
t.context.cwd = process.cwd();
t.context.log = stub(console, 'log');
t.context.error = stub(console, 'error');
});
test.afterEach.always(async t => {
// Restore process.env
process.env = Object.assign({}, t.context.env);
// Restore the current working directory
process.chdir(t.context.cwd);
t.context.log.restore();
t.context.error.restore();
});
test.after.always(async t => {
await mockServer.stop();
// Stop the local NPM registry
await registry.stop();
});
test.serial('Release patch, minor and major versions', async t => {
const packageName = 'test-module';
const repo = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {verifyConditions: noop, githubUrl: mockServer.url},
});
// Create a npm-shrinkwrap.json file
await execa('npm', ['shrinkwrap'], {env});
/** No release **/
t.log('Commit a chore');
await gitCommits(['chore: Init repository']);
t.log('$ semantic-release');
let {stdout, code} = await execa(cli, [], {env});
t.regex(stdout, /There are no relevant changes, so no new version is released/);
t.is(code, 0);
/** Initial release **/
let version = '1.0.0';
let createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json and npm-shrinkwrap.json have been updated
t.is((await readJson('./package.json')).version, version);
t.is((await readJson('./npm-shrinkwrap.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/** Patch release **/
version = '1.0.1';
createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a fix');
await gitCommits(['fix: bar']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json and npm-shrinkwrap.json have been updated
t.is((await readJson('./package.json')).version, version);
t.is((await readJson('./npm-shrinkwrap.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', 'test-module', 'version', 'gitHead'], {env})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/** Minor release **/
version = '1.1.0';
createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: baz']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json and npm-shrinkwrap.json have been updated
t.is((await readJson('./package.json')).version, version);
t.is((await readJson('./npm-shrinkwrap.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', 'test-module', 'version', 'gitHead'], {env})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/** Major release **/
version = '2.0.0';
createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a breaking change');
await gitCommits(['feat: foo\n\n BREAKING CHANGE: bar']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json and npm-shrinkwrap.json have been updated
t.is((await readJson('./package.json')).version, version);
t.is((await readJson('./npm-shrinkwrap.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', 'test-module', 'version', 'gitHead'], {env})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Release versions from a packed git repository, using tags to determine last release gitHead', async t => {
const packageName = 'test-module-2';
const repo = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git@github.com:${repo}/${packageName}.git`},
release: {verifyConditions: noop, githubUrl: mockServer.url},
});
/** Initial release **/
let version = '1.0.0';
let createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ git pack-refs --all');
await gitPackRefs();
t.log('$ semantic-release');
let {stdout, code} = await execa(cli, [], {env});
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version
let releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
// Create a tag version so the tag can be used later to determine the commit associated with the version
await gitTagVersion(`v${version}`);
t.log(`Create git tag v${version}`);
/** Patch release **/
version = '1.0.1';
createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a fix');
await gitCommits(['fix: bar']);
t.log('$ semantic-release');
({stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version
releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Exit with 1 if a plugin is not found', async t => {
const packageName = 'test-module-3';
const repo = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {analyzeCommits: 'non-existing-path'},
});
const {code, stderr} = await t.throws(execa(cli, [], {env}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
test.serial('Create a tag as a recovery solution for "ENOTINHISTORY" error', async t => {
const packageName = 'test-module-4';
const repo = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {verifyConditions: noop, githubUrl: mockServer.url},
});
/** Initial release **/
let version = '1.0.0';
let createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
let {stderr, stdout, code} = await execa(cli, [], {env});
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env})).stdout
);
const head = await gitHead();
t.is(releasedGitHead, head);
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
// Create a tag version so the tag can be used later to determine the commit associated with the version
await gitTagVersion(`v${version}`);
t.log(`Create git tag v${version}`);
/** Rewrite sha of commit used for release **/
t.log('Amend release commit');
const {hash} = await gitAmmendCommit('feat: Initial commit');
/** Patch release **/
t.log('Commit a fix');
await gitCommits(['fix: bar']);
t.log('$ semantic-release');
({stderr, stdout, code} = await execa(cli, [], {env, reject: false}));
t.log('Log "ENOTINHISTORY" message');
t.is(code, 0);
t.regex(
stderr,
new RegExp(
`You can recover from this error by restoring the commit "${head}" or by creating a tag for the version "${version}" on the commit corresponding to this release`
)
);
/** Create a tag to recover and redo release **/
t.log(`Create git tag v${version} to recover`);
await gitTagVersion(`v${version}`, hash);
version = '1.0.1';
createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('$ semantic-release');
({stderr, stdout, code} = await execa(cli, [], {env}));
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
releasedVersion = (await execa('npm', ['show', packageName, 'version'], {env})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Dry-run', async t => {
const packageName = 'test-module-5';
const repo = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {githubUrl: mockServer.url},
});
/** Initial release **/
const version = '1.0.0';
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release -d');
let {stdout, code} = await execa(cli, ['-d'], {env});
t.regex(stdout, new RegExp(`There is no previous release, the next release version is ${version}`));
t.regex(stdout, new RegExp(`Release note for version ${version}`));
t.regex(stdout, /Initial commit/);
t.is(code, 0);
// Verify package.json and has not been modified
t.is((await readJson('./package.json')).version, '0.0.0-dev');
});
test.serial('Pass options via CLI arguments', async t => {
const packageName = 'test-module-6';
const repo = 'test-repo';
const githubToken = 'OTHER_TOKEN';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {githubUrl: mockServer.url},
});
/** Initial release **/
let version = '1.0.0';
let createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${githubToken}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${githubToken}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
let {stdout, code} = await execa(
cli,
['--github-token', githubToken, '--verify-conditions', `${noop}, ${noop}`, '--debug'],
{env}
);
t.regex(stdout, new RegExp(`Published Github release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry ${registry.uri}`));
t.is(code, 0);
// Verify package.json and has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Run via JS API', async t => {
const packageName = 'test-module-7';
const repo = 'test-repo';
const githubToken = 'OTHER_TOKEN';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {githubUrl: mockServer.url},
});
/** Initial release **/
let version = '1.0.0';
let createRefMock = mockServer.mock(
`/repos/${repo}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${githubToken}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = mockServer.mock(
`/repos/${repo}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${githubToken}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
process.env = Object.assign(process.env, env);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ Call semantic-release via API');
await semanticRelease({githubToken, verifyConditions: [noop, noop], debug: true});
t.true(t.context.log.calledWithMatch(/Published Github release: /, new RegExp(`release-url/${version}`)));
t.true(t.context.log.calledWithMatch(/Publishing version .* to npm registry/, version, registry.uri));
// Verify package.json and has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env})).stdout
);
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Returns and error code if NPM token is invalid', async t => {
const env = {npm_config_registry: registry.uri, GH_TOKEN: 'github_token', NPM_TOKEN: 'wrong_token'};
const packageName = 'test-module-8';
const repo = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {verifyConditions: noop, githubUrl: mockServer.url},
});
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
let {stderr, code} = await execa(cli, [], {env, reject: false});
t.regex(stderr, /forbidden Please log in before writing to the db/);
t.is(code, 1);
});
test.serial('Log unexpected errors from plugins and exit with 1', async t => {
const packageName = 'test-module-9';
const repo = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {githubUrl: mockServer.url, verifyConditions: pluginError},
});
/** Initial release **/
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
let {stderr, code} = await execa(cli, [], {env, reject: false});
// Verify the type and message are logged
t.regex(stderr, /Error: a/);
// Verify the the stacktrace is logged
t.regex(stderr, new RegExp(pluginError));
// Verify the Error properties are logged
t.regex(stderr, /errorProperty: 'errorProperty'/);
t.is(code, 1);
});
test.serial('Log errors inheriting SemanticReleaseError and exit with 0', async t => {
const packageName = 'test-module-10';
const repo = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${repo}/${packageName}`},
release: {githubUrl: mockServer.url, verifyConditions: pluginInheritedError},
});
/** Initial release **/
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release');
let {stdout, code} = await execa(cli, [], {env, reject: false});
// Verify the type and message are logged
t.regex(stdout, /EINHERITED Inherited error/);
t.is(code, 0);
});
test.serial('CLI returns error code and prints help if called with a command', async t => {
t.log('$ semantic-release pre');
let {stdout, code} = await execa(cli, ['pre'], {env, reject: false});
t.regex(stdout, /Usage: semantic-release/);
t.is(code, 1);
});
test.serial('CLI prints help if called with --help', async t => {
t.log('$ semantic-release --help');
let {stdout, code} = await execa(cli, ['--help'], {env});
t.regex(stdout, /Usage: semantic-release/);
t.is(code, 0);
});
test.serial('CLI returns error code with invalid option', async t => {
t.log('$ semantic-release --unknown-option');
let {stderr, code} = await execa(cli, ['--unknown-option'], {env, reject: false});
t.regex(stderr, /unknown option/);
t.is(code, 1);
});
-12
View File
@@ -1,12 +0,0 @@
var nixt = require('nixt')
module.exports = function (cwd, uri) {
return nixt()
.cwd(cwd)
.env('NPM_OLD_TOKEN', 'aW50ZWdyYXRpb246c3VjaHNlY3VyZQ==')
.env('NPM_EMAIL', 'integration@test.com')
.env('GH_TOKEN', 'ghtoken')
.env('CI', 'true')
.env('npm_config_registry', uri)
.clone()
}
-36
View File
@@ -1,36 +0,0 @@
var exec = require('child_process').exec
var join = require('path').join
var writeFileSync = require('fs').writeFileSync
var mkdirp = require('mkdirp')
module.exports = function (name, registry, cb) {
var cwd = join(__dirname, '../tmp', name)
mkdirp.sync(cwd)
writeFileSync(join(cwd, 'package.json'), JSON.stringify({
name: name,
repository: {
url: 'git+https://github.com/semantic-release/test'
},
release: {
verifyConditions: '../../../src/lib/plugin-noop'
}
}, null, 2))
exec(
'git init && ' +
'git config user.email "integration@test" && ' +
'git config user.name "Integration Test" && ' +
'git add . && ' +
'git commit -m "chore: root"'
, {cwd: cwd}, function (err, stdout, stderr) {
if (err) {
console.log(stdout, stderr)
return cb(err)
}
cb(null, cwd)
})
}
+48
View File
@@ -0,0 +1,48 @@
import test from 'ava';
import {stub, match} from 'sinon';
import logger from '../src/lib/logger';
test.beforeEach(t => {
t.context.log = stub(console, 'log');
t.context.error = stub(console, 'error');
});
test.afterEach.always(t => {
t.context.log.restore();
t.context.error.restore();
});
test.serial('Basic log', t => {
logger.log('test log');
logger.error('test error');
t.true(t.context.log.calledWithMatch(/.*test log/));
t.true(t.context.error.calledWithMatch(/.*test error/));
});
test.serial('Log object', t => {
const obj = {a: 1, b: '2'};
logger.log(obj);
logger.error(obj);
t.true(t.context.log.calledWithMatch(match.string, obj));
t.true(t.context.error.calledWithMatch(match.string, obj));
});
test.serial('Log with string formatting', t => {
logger.log('test log %s', 'log value');
logger.error('test error %s', 'error value');
t.true(t.context.log.calledWithMatch(/.*test log/, 'log value'));
t.true(t.context.error.calledWithMatch(/.*test error/, 'error value'));
});
test.serial('Log with error stacktrace and properties', t => {
const error = new Error('error message');
logger.error(error);
const otherError = new Error('other error message');
logger.error('test error %O', otherError);
t.true(t.context.error.calledWithMatch(match.string, error));
t.true(t.context.error.calledWithMatch(/.*test error/, otherError));
});
-21
View File
@@ -1,21 +0,0 @@
const rawCommits = [
'hash-one==SPLIT==commit-one==END==\n',
'hash-two==SPLIT==commit-two==END==\n'
]
module.exports = {
exec: function (command, cb) {
if (/contains/.test(command)) {
if (/notinhistory/.test(command)) return cb(new Error())
return cb(null, 'whatever\nmaster\n')
}
cb(
null,
/\.\.HEAD/.test(command)
? rawCommits[0]
: rawCommits.join()
)
},
'@noCallThru': true
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (cb) {
cb(null, 'bar')
}
-12
View File
@@ -1,12 +0,0 @@
module.exports = function () {
return {
authenticate: function () {
return true
},
releases: {
createRelease: function (release, cb) {
cb(null)
}
}
}
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (config, options, cb) {
cb(new Error('a'))
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (config, options, cb) {
cb(new Error('b'))
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (config, options, cb) {
cb(null, 'a')
}
-3
View File
@@ -1,3 +0,0 @@
module.exports = function (config, options, cb) {
cb(null, 'b')
}
-28
View File
@@ -1,28 +0,0 @@
const nock = require('nock')
const availableModule = {
'dist-tags': {
latest: '1.33.7',
foo: '0.8.15'
},
versions: {
'0.8.15': {
gitHead: 'bar'
},
'1.33.7': {
gitHead: 'HEAD'
}
}
}
module.exports = nock('http://registry.npmjs.org')
.get('/available')
.reply(200, availableModule)
.get('/tagged')
.reply(200, availableModule)
.get('/untagged')
.reply(200, availableModule)
.get('/@scoped%2Favailable')
.reply(200, availableModule)
.get('/unavailable')
.reply(404, {})
+123
View File
@@ -0,0 +1,123 @@
import {promisify} from 'util';
import test from 'ava';
import proxyquire from 'proxyquire';
import {stub, match} from 'sinon';
test.beforeEach(t => {
// Stub the logger functions
t.context.log = stub();
t.context.plugins = proxyquire('../src/lib/plugins', {'./logger': {log: t.context.log}});
});
test('Export plugins', t => {
// Call the plugin module
const defaultPlugins = t.context.plugins({});
// Verify the module returns a function for each plugin
t.is(typeof defaultPlugins.analyzeCommits, 'function');
t.is(typeof defaultPlugins.generateNotes, 'function');
t.is(typeof defaultPlugins.verifyConditions, 'function');
t.is(typeof defaultPlugins.verifyRelease, 'function');
t.is(typeof defaultPlugins.getLastRelease, 'function');
});
test('Pipeline - Get all results', async t => {
// Call the plugin module with a verifyRelease plugin pipeline
const pipelinePlugins = t.context.plugins({
verifyRelease: ['./src/lib/plugin-noop', './test/fixtures/plugin-result-a', './test/fixtures/plugin-result-b'],
});
// Call the verifyRelease pipeline
const results = await pipelinePlugins.verifyRelease({});
// Verify the pipeline return the expected result for each plugin, in order
t.deepEqual(results, [undefined, 'a', 'b']);
// Verify the logger has been called with the plugins path
t.true(t.context.log.calledWith(match.string, './src/lib/plugin-noop'));
t.true(t.context.log.calledWith(match.string, './test/fixtures/plugin-result-a'));
t.true(t.context.log.calledWith(match.string, './test/fixtures/plugin-result-b'));
});
test('Pipeline - Pass pluginConfig and options to each plugins', async t => {
// Plugin configuration with options (plugin-result-config is a mock plugin returning its pluginConfig and options parameters)
const pluginConfig = {path: './test/fixtures/plugin-result-config', pluginParam: 'param1'};
// Semantic-release global options
const options = {semanticReleaseParam: 'param2'};
// Call the plugin module with a verifyRelease plugin pipeline
const pipelinePlugins = t.context.plugins({
verifyRelease: [pluginConfig, './test/fixtures/plugin-result-config'],
});
// Call the verifyRelease pipeline
const results = await pipelinePlugins.verifyRelease(options);
// Verify the pipeline first result is the pluginConfig and options parameters (to verify the plugin was called with the defined pluginConfig and options parameters)
t.deepEqual(results, [{pluginConfig, options}, {pluginConfig: {}, options}]);
// Verify the logger has been called with the plugins path
t.true(t.context.log.calledWith(match.string, './test/fixtures/plugin-result-config'));
});
test('Pipeline - Get first error', async t => {
// Call the plugin module with a verifyRelease plugin pipeline
const pipelinePlugins = t.context.plugins({
verifyRelease: ['./src/lib/plugin-noop', './test/fixtures/plugin-error-a', './test/fixtures/plugin-error-b'],
});
// Call the verifyRelease pipeline and verify it returns the error thrown by './test/fixtures/plugin-error-a'
await t.throws(pipelinePlugins.verifyRelease({}), 'a');
// Verify the logger has been called with the plugins path
t.true(t.context.log.calledWith(match.string, './src/lib/plugin-noop'));
t.true(t.context.log.calledWith(match.string, './test/fixtures/plugin-error-a'));
});
test('Normalize and load plugin from string', t => {
// Call the normalize function with a path
const plugin = t.context.plugins.normalize('./src/lib/plugin-noop');
// Verify the plugin is loaded
t.is(typeof plugin, 'function');
// Verify the logger has been called with the plugins path
t.true(t.context.log.calledWith(match.string, './src/lib/plugin-noop'));
});
test('Normalize and load plugin from object', t => {
// Call the normalize function with an object (with path property)
const plugin = t.context.plugins.normalize({path: './src/lib/plugin-noop'});
// Verify the plugin is loaded
t.is(typeof plugin, 'function');
// Verify the logger has been called with the plugins path
t.true(t.context.log.calledWith(match.string, './src/lib/plugin-noop'));
});
test('Load from fallback', t => {
// Call the normalize function with a fallback
const plugin = t.context.plugins.normalize(null, '../lib/plugin-noop');
// Verify the fallback plugin is loaded
t.is(typeof plugin, 'function');
});
test('Always pass a defined "pluginConfig" for plugin defined with string', async t => {
// Call the normalize function with the path of a plugin that returns its config
const plugin = t.context.plugins.normalize('./test/fixtures/plugin-result-config');
const pluginResult = await promisify(plugin)({});
t.deepEqual(pluginResult.pluginConfig, {});
});
test('Always pass a defined "pluginConfig" for plugin defined with path', async t => {
// Call the normalize function with the path of a plugin that returns its config
const plugin = t.context.plugins.normalize({path: './test/fixtures/plugin-result-config'});
const pluginResult = await promisify(plugin)({});
t.deepEqual(pluginResult.pluginConfig, {path: './test/fixtures/plugin-result-config'});
});
test('Always pass a defined "pluginConfig" for fallback plugin', async t => {
// Call the normalize function with the path of a plugin that returns its config
const plugin = t.context.plugins.normalize(null, '../../test/fixtures/plugin-result-config');
const pluginResult = await promisify(plugin)({});
t.deepEqual(pluginResult.pluginConfig, {});
});
-11
View File
@@ -1,11 +0,0 @@
var exec = require('child_process').exec
var opts = {
cwd: __dirname
}
module.exports = {
start: exec.bind(null, './start.sh', opts),
stop: exec.bind(null, './stop.sh', opts),
uri: 'http://localhost:' + (process.env.TRAVIS === 'true' ? 5984 : 15986) + '/registry/_design/app/_rewrite/'
}
-96
View File
@@ -1,96 +0,0 @@
var join = require('path').join
var tap = require('tap')
var rimraf = require('rimraf')
var registry = require('../registry')
var testModule = require('../lib/test-module')
var baseScenario = require('../lib/base-scenario')
var tearDown = tap.tearDown
var test = tap.test
test('change version', {bail: process.env.TRAVIS === 'true'}, function (t) {
t.plan(7)
registry.start(function (err, stdout, stderr) {
t.error(err, 'registry started')
if (err) return t.end()
testModule('change-version', registry.uri, function (err, cwd) {
t.error(err, 'test-module created')
if (err) return t.end()
t.test('no version', function (tt) {
tt.plan(1)
baseScenario(cwd, registry.uri)
.env('npm_config_loglevel', 'info')
.run('node ../../../bin/semantic-release.js pre')
.stderr(/ENOCHANGE/)
.code(1)
.end(tt.error)
})
t.test('initial version', function (tt) {
tt.plan(1)
baseScenario(cwd, registry.uri)
.exec('git commit -m "feat: initial" --allow-empty')
.exec('node ../../../bin/semantic-release.js pre')
.run('npm publish')
.stdout(/1\.0\.0/)
.code(0)
.end(tt.error)
})
t.test('patch version', function (tt) {
tt.plan(1)
baseScenario(cwd, registry.uri)
.exec('git commit -m "fix: foo" --allow-empty')
.exec('node ../../../bin/semantic-release.js pre')
.run('npm publish')
.stdout(/1\.0\.1/)
.code(0)
.end(tt.error)
})
t.test('feature version', function (tt) {
tt.plan(1)
baseScenario(cwd, registry.uri)
.exec('git commit -m "feat: foo" --allow-empty')
.exec('node ../../../bin/semantic-release.js pre')
.run('npm publish')
.code(0)
.stdout(/1\.1\.0/)
.end(tt.error)
})
t.test('breaking version', function (tt) {
tt.plan(1)
baseScenario(cwd, registry.uri)
.exec('git commit -m "feat: foo\n\n BREAKING CHANGE: bar" --allow-empty')
.exec('node ../../../bin/semantic-release.js pre')
.run('npm publish')
.code(0)
.stdout(/2\.0\.0/)
.end(tt.error)
})
})
})
})
tearDown(function () {
if (process.env.TRAVIS === 'true') return
function cb (err, stdout, stderr) {
if (err) console.log(err)
if (stderr) console.log(stderr)
}
rimraf(join(__dirname, '../tmp'), cb)
registry.stop(cb)
})
-43
View File
@@ -1,43 +0,0 @@
var test = require('tap').test
var proxyquire = require('proxyquire')
var commits = proxyquire('../../src/lib/commits', {
'npmlog': {
error: function () {}
},
'child_process': require('../mocks/child-process')
})
test('commits since last release', function (t) {
t.test('get all commits', function (tt) {
commits({lastRelease: {}, options: {branch: 'master'}}, function (err, commits) {
tt.error(err)
tt.is(commits.length, 2, 'all commits')
tt.is(commits[0].hash, 'hash-one', 'parsed hash')
tt.is(commits[1].message, 'commit-two', 'parsed message')
tt.end()
})
})
t.test('get commits since hash', function (tt) {
commits({lastRelease: {gitHead: 'hash'}, options: {branch: 'master'}}, function (err, commits) {
tt.error(err)
tt.is(commits.length, 1, 'specified commits')
tt.is(commits[0].hash, 'hash-one', 'parsed hash')
tt.is(commits[0].message, 'commit-one', 'parsed message')
tt.end()
})
})
t.test('get commits since hash', function (tt) {
commits({lastRelease: {gitHead: 'notinhistory'}, options: {branch: 'notmaster'}}, function (err, commits) {
tt.ok(err)
tt.is(err.code, 'ENOTINHISTORY')
tt.end()
})
})
t.end()
})
-44
View File
@@ -1,44 +0,0 @@
const test = require('tap').test
const getRegistry = require('../../src/lib/get-registry')
test('get correct registry', function (t) {
t.is(getRegistry({
name: 'publish-config',
publishConfig: {
registry: 'a'
}},
{}), 'a')
t.is(getRegistry({name: 'normal'}, {
get: function () {
return 'b'
}
}), 'b')
t.is(getRegistry({name: 'normal'}, {
get: function () {
return null
}
}), 'https://registry.npmjs.org/')
t.is(getRegistry({name: '@scoped/foo'}, {
get: function (input) {
return input === '@scoped/registry' ? 'c' : 'd'
}
}), 'c')
t.is(getRegistry({name: '@scoped/bar'}, {
get: function () {
return 'e'
}
}), 'e')
t.is(getRegistry({name: '@scoped/baz'}, {
get: function () {
return null
}
}), 'https://registry.npmjs.org/')
t.end()
})
-97
View File
@@ -1,97 +0,0 @@
var test = require('tap').test
var plugins = require('../../src/lib/plugins')
test('export plugins', function (t) {
t.plan(5)
var defaultPlugins = plugins({})
t.is(typeof defaultPlugins.analyzeCommits, 'function')
t.is(typeof defaultPlugins.generateNotes, 'function')
t.is(typeof defaultPlugins.verifyConditions, 'function')
t.is(typeof defaultPlugins.verifyRelease, 'function')
t.is(typeof defaultPlugins.getLastRelease, 'function')
})
test('plugin pipelines', function (t) {
t.plan(3)
t.test('get all results', function (tt) {
var pipelinePlugins = plugins({
verifyRelease: [
'./src/lib/plugin-noop',
'./test/mocks/plugin-result-a',
'./test/mocks/plugin-result-b'
]
})
pipelinePlugins.verifyRelease({}, function (err, results) {
tt.error(err)
tt.same(results, [undefined, 'a', 'b'])
tt.end()
})
})
t.test('get first error', function (tt) {
var pipelinePlugins = plugins({
verifyConditions: [
'./src/lib/plugin-noop',
'./test/mocks/plugin-error-a',
'./test/mocks/plugin-error-b'
]
})
pipelinePlugins.verifyConditions({}, function (err) {
tt.is(err.message, 'a')
tt.end()
})
})
t.test('get error and only results before', function (tt) {
var pipelinePlugins = plugins({
verifyRelease: [
'./src/lib/plugin-noop',
'./test/mocks/plugin-result-a',
'./test/mocks/plugin-error-b',
'./test/mocks/plugin-result-b'
]
})
pipelinePlugins.verifyRelease({}, function (err, results) {
tt.is(err.message, 'b')
tt.same(results, [undefined, 'a', undefined])
tt.end()
})
})
})
test('normalize and load plugin', function (t) {
t.test('load from string', function (tt) {
var plugin = plugins.normalize('./src/lib/plugin-noop')
tt.is(typeof plugin, 'function')
tt.end()
})
t.test('load from object', function (tt) {
var plugin = plugins.normalize({
path: './src/lib/plugin-noop'
})
tt.is(typeof plugin, 'function')
tt.end()
})
t.test('load from fallback', function (tt) {
var plugin = plugins.normalize(null, '../../src/lib/plugin-noop')
tt.is(typeof plugin, 'function')
tt.end()
})
t.end()
})
-74
View File
@@ -1,74 +0,0 @@
var defaults = require('lodash').defaults
var test = require('tap').test
var proxyquire = require('proxyquire')
var post = proxyquire('../../src/post', {
'git-head': require('../mocks/git-head'),
github: require('../mocks/github')
})
var pkg = {
version: '1.0.0',
repository: {url: 'http://github.com/whats/up.git'}
}
var plugins = {
generateNotes: function (pkg, cb) {
cb(null, 'the log')
}
}
var defaultRelease = {
owner: 'whats',
repo: 'up',
name: 'v1.0.0',
tag_name: 'v1.0.0',
target_commitish: 'bar',
body: 'the log'
}
test('full post run', function (t) {
t.test('in debug mode w/o token', function (tt) {
post({
options: {debug: true},
pkg: pkg,
plugins: plugins
}, function (err, published, release) {
tt.error(err)
tt.is(published, false)
tt.match(release, defaults({draft: true}, defaultRelease))
tt.end()
})
})
t.test('in debug mode w/token', function (tt) {
post({
options: {debug: true, githubToken: 'yo'},
pkg: pkg,
plugins: plugins
}, function (err, published, release) {
tt.error(err)
tt.is(published, true)
tt.match(release, defaults({draft: true}, defaultRelease))
tt.end()
})
})
t.test('production', function (tt) {
post({
options: {githubToken: 'yo'},
pkg: pkg,
plugins: plugins
}, function (err, published, release) {
tt.error(err)
tt.is(published, true)
tt.match(release, defaultRelease)
tt.end()
})
})
t.end()
})
-64
View File
@@ -1,64 +0,0 @@
var test = require('tap').test
var proxyquire = require('proxyquire')
require('../mocks/registry')
var pre = proxyquire('../../src/pre', {
'./lib/commits': proxyquire('../../src/lib/commits', {
'child_process': require('../mocks/child-process')
})
})
var versions = {
available: '1.0.0'
}
var plugins = {
verifyRelease: function (release, cb) {
cb(null, release)
},
analyzeCommits: function (commits, cb) {
cb(null, 'major')
},
getLastRelease: function (config, cb) {
cb(null, {version: versions[config.pkg.name] || null, gitHead: 'HEAD'})
}
}
var npm = {
registry: 'http://registry.npmjs.org/',
tag: 'latest'
}
test('full pre run', function (t) {
t.test('increase version', function (tt) {
tt.plan(3)
pre({
options: {branch: 'master'},
npm: npm,
pkg: {name: 'available'},
plugins: plugins
}, function (err, release) {
tt.error(err)
tt.is(release.type, 'major')
tt.is(release.version, '2.0.0')
})
})
t.test('increase version', function (tt) {
tt.plan(3)
pre({
options: {branch: 'master'},
npm: npm,
pkg: {name: 'unavailable'},
plugins: plugins
}, function (err, release) {
tt.error(err)
tt.is(release.type, 'initial')
tt.is(release.version, '1.0.0')
})
})
t.end()
})
-60
View File
@@ -1,60 +0,0 @@
var test = require('tap').test
var type = require('../../src/lib/type')
test('get type from commits', function (t) {
t.test('get type from plugin', function (tt) {
tt.plan(2)
type({
commits: [{
hash: '0',
message: 'a'
}],
lastRelease: {version: '1.0.0'},
plugins: {
analyzeCommits: function (config, cb) {
cb(null, 'major')
}
}
}, function (err, type) {
tt.error(err)
tt.is(type, 'major')
})
})
t.test('error when no changes', function (tt) {
tt.plan(1)
type({
commits: [],
lastRelease: {},
plugins: {
analyzeCommits: function (config, cb) {
cb(null, null)
}
}
}, function (err) {
tt.is(err.code, 'ENOCHANGE')
})
})
t.test('initial version', function (tt) {
tt.plan(2)
type({
commits: [],
lastRelease: {},
plugins: {
analyzeCommits: function (config, cb) {
cb(null, 'major')
}
}
}, function (err, type) {
tt.error(err)
tt.is(type, 'initial')
})
})
t.end()
})
-73
View File
@@ -1,73 +0,0 @@
var test = require('tap').test
var verify = require('../../src/lib/verify')
test('verify pkg, options and env', function (t) {
t.test('dry run verification', function (tt) {
var noErrors = verify({
options: {debug: true},
pkg: {
name: 'package',
repository: {
url: 'http://github.com/whats/up.git'
}
}
})
tt.is(noErrors.length, 0)
var errors = verify({
options: {debug: true},
pkg: {}
})
tt.is(errors.length, 2)
tt.is(errors[0].code, 'ENOPKGNAME')
tt.is(errors[1].code, 'ENOPKGREPO')
tt.end()
})
t.test('dry run verification for gitlab repo', function (tt) {
var noErrors = verify({
options: {debug: true},
pkg: {
name: 'package',
repository: {
url: 'http://gitlab.corp.com/whats/up.git'
}
}
})
console.log(noErrors)
tt.is(noErrors.length, 0)
tt.end()
})
t.test('publish verification', function (tt) {
var noErrors = verify({
env: {NPM_TOKEN: 'yo'},
options: {githubToken: 'sup'},
pkg: {
name: 'package',
repository: {
url: 'http://github.com/whats/up.git'
}
}
})
tt.is(noErrors.length, 0)
var errors = verify({env: {}, options: {}, pkg: {}})
tt.is(errors.length, 4)
tt.is(errors[0].code, 'ENOPKGNAME')
tt.is(errors[1].code, 'ENOPKGREPO')
tt.is(errors[2].code, 'ENOGHTOKEN')
tt.is(errors[3].code, 'ENONPMTOKEN')
tt.end()
})
t.end()
})
+45
View File
@@ -0,0 +1,45 @@
import test from 'ava';
import SemanticReleaseError from '@semantic-release/error';
import verify from '../src/lib/verify-auth';
test('Verify npm and github auth', t => {
// Call the verify module with options and env
t.notThrows(() => verify({githubToken: 'sup'}, {NPM_TOKEN: 'yo'}));
});
test('Verify npm (old token and mail) and github auth', t => {
// Call the verify module with options and env
t.notThrows(() => verify({githubToken: 'sup'}, {NPM_OLD_TOKEN: 'yo', NPM_EMAIL: 'test@email.com'}));
});
test('Return error for missing github token', t => {
// Call the verify module with options and env
const error = t.throws(() => verify({}, {NPM_TOKEN: 'yo'}));
// Verify error code and type
t.is(error.code, 'ENOGHTOKEN');
t.true(error instanceof SemanticReleaseError);
});
test('Return error for missing npm token', t => {
// Call the verify module with options and env
const error = t.throws(() => verify({githubToken: 'sup'}, {}));
// Verify error code and type
t.is(error.code, 'ENONPMTOKEN');
t.true(error instanceof SemanticReleaseError);
});
test('Return error for missing old npm token', t => {
// Call the verify module with options and env
const error = t.throws(() => verify({githubToken: 'sup'}, {NPM_EMAIL: 'test@email.com'}));
// Verify error code and type
t.is(error.code, 'ENONPMTOKEN');
t.true(error instanceof SemanticReleaseError);
});
test('Return error for missing npm email', t => {
// Call the verify module with options and env
const error = t.throws(() => verify({githubToken: 'sup'}, {NPM_OLD_TOKEN: 'yo'}));
// Verify error code and type
t.is(error.code, 'ENONPMTOKEN');
t.true(error instanceof SemanticReleaseError);
});
+32
View File
@@ -0,0 +1,32 @@
import test from 'ava';
import SemanticReleaseError from '@semantic-release/error';
import verify from '../src/lib/verify-pkg';
test('Verify name and repository', t => {
// Call the verify module with package
t.notThrows(() => verify({name: 'package', repository: {url: 'http://github.com/whats/up.git'}}));
});
test('Return error for missing package name', t => {
// Call the verify module with package
const error = t.throws(() => verify({repository: {url: 'http://github.com/whats/up.git'}}));
// Verify error code and type
t.is(error.code, 'ENOPKGNAME');
t.true(error instanceof SemanticReleaseError);
});
test('Return error for missing repository', t => {
// Call the verify module with package
const error = t.throws(() => verify({name: 'package'}));
// Verify error code and type
t.is(error.code, 'ENOPKGREPO');
t.true(error instanceof SemanticReleaseError);
});
test('Return error for missing repository url', t => {
// Call the verify module with package
const error = t.throws(() => verify({name: 'package', repository: {}}));
// Verify error code and type
t.is(error.code, 'ENOPKGREPO');
t.true(error instanceof SemanticReleaseError);
});