Compare commits

..
147 Commits
Author SHA1 Message Date
Pierre Vanduynslager d8e59cce53 fix: set default path to generateNotes object config 2018-07-10 15:50:24 -04:00
Pierre Vanduynslager 24ce560065 refactor: build plugin pipeline parameters at initialization
In addition, factorize the pipeline config function to avoid code duplication.
2018-07-10 13:18:58 -04:00
Pierre Vanduynslager eb26254b00 refactor: use Object.entries rather than Object.keys 2018-07-10 13:18:58 -04:00
Pierre Vanduynslager 50061bb267 refactor: remove unnecessary object destructuring 2018-07-10 13:18:58 -04:00
Pierre Vanduynslager 5989989452 feat: allow to define multiple generateNotes plugins
Each `generateNotes` plugin will be called in the order defined and will receive the concatenation of the previous one in `nextRelease.notes`.
That gives each plugin the ability to test if there is a notes part that will precede it's own.
Each plugin is expected to return it's own part of the release notes only. **semantic-release** will take care of concatenating all the notes parts.
2018-07-10 13:18:58 -04:00
Pierre Vanduynslager 576eb6027f refactor: simplify plugin validation 2018-07-10 13:18:58 -04:00
Pierre Vanduynslager f7f4aabe9e refactor: use the lastInput arg to compute the prepare pipeline next input
Use the `getNextInput`'s provided argument rather than relying on the closure.
2018-07-10 13:18:58 -04:00
Pierre Vanduynslager 12de6282dd refactor: fix incorrect comments in lib/plugins/pipeline.js 2018-07-10 13:18:58 -04:00
Pierre Vanduynslager d3032868d8 docs: fix default value for analyzeCommits plugin 2018-07-10 13:18:58 -04:00
Pierre Vanduynslager ed9c456f5e refactor: always return an Array of results/errors from a plugin pipeline
Always return an `Array` from a pipeline simplify the function utilization as it's more deterministic. Previously, it would return/throw a single value/error when called with a single input and an `Array` of results/errors when called with an `Array` of input.
2018-07-10 13:18:58 -04:00
Pierre Vanduynslager cac48823f1 docs: clarify verifyRelease plugin description 2018-07-10 13:18:58 -04:00
Pierre Vanduynslager 09348f1b8a style: disable max-params warning for lib/plugins/normalize.js 2018-07-10 13:18:58 -04:00
Pierre Vanduynslager f93eeb799b fix: do not set path to plugin config defined as a Function or an Array
If a plugin hook was defined as a `Function` or an `Array` the `path` property would be set to the default value.
Even if this bug had no actual negative impact, it should be fixed so the code would perform as intended.
2018-07-10 13:18:58 -04:00
Pierre Vanduynslager 071dccea4b fix: use unauthenticated URL to check if branch is up to date
In case the authentication token provided is unauthorized the call to `isBranchUpToDate` will fail due to lack of read permission if that URL is used. As a result the error about outdated local branch will be reported instead of the one about missing permission.
By using the original (unauthenticated) URL `isBranchUpToDate` shouldn't fail due to permission as it requires only read permissions, that are necessarly present as the CI wass able to clone the repo.
2018-07-10 13:07:00 -04:00
Pierre Vanduynslager eb22f9998d docs: FAQ for reverting a release 2018-07-10 11:52:39 -04:00
Pierre Vanduynslager 5847514fcc fix: allow empty release notes in dry-run mode 2018-07-10 11:42:22 -04:00
Pierre Vanduynslager a39ccb8f6c docs: add missing link in GitBook summary 2018-07-08 01:16:21 -04:00
Pierre VanduynslagerandGitHub 0862480cf0 fix(package): update hosted-git-info to version 2.7.1 2018-07-06 21:47:50 -04:00
Pierre Vanduynslager 45eee4acdd fix: fetch all tags even if the repo is not shallow 2018-07-02 18:38:24 -04:00
Pierre Vanduynslager 2d3a5e53e9 test: harmonize git-utils functions name 2018-07-02 18:38:24 -04:00
Pierre Vanduynslager 4abda31f83 fix: add debug log for git fetch command 2018-07-02 16:50:41 -04:00
Pierre Vanduynslager 3602716c0b docs: update semantic-release and travis-deploy-once versions in examples 2018-07-02 11:23:37 -04:00
Pierre Vanduynslager d4f68a5680 fix(package): update yargs to version 12.0.0 2018-06-26 15:46:19 -04:00
Pierre Vanduynslager 4454d57e02 feat: allow to disable the publish plugin hook 2018-06-19 15:03:43 -04:00
greenkeeper[bot]andPierre Vanduynslager 9137f8537b fix(package): update read-pkg-up to version 4.0.0 2018-06-18 11:15:16 -04:00
Trevor RichardsonandPierre Vanduynslager 7615fdc9bc Fix documented explanation in plugins.md
`verifyConditions` explanation was wrong previously.
2018-06-18 10:52:27 -04:00
Pierre Vanduynslager 2b6378f26f fix: use git ls-remote to verify if the remote branch is ahead 2018-06-15 16:16:55 -04:00
Pierre Vanduynslager 24a8052038 refactor: simply EGITNOPERMISSION error parameters 2018-06-15 16:16:55 -04:00
greenkeeper[bot]andPierre Vanduynslager 0ab0426075 fix(package): update p-locate to version 3.0.0 2018-06-15 12:22:47 -04:00
Pierre Vanduynslager f9d9144e3d docs: Add a troubleshooting section about squashed commits 2018-06-11 11:52:23 -04:00
greenkeeper[bot]andPierre Vanduynslager 11cef46c48 chore(package): update sinon to version 6.0.0 2018-06-11 11:33:14 -04:00
greenkeeper[bot]andPierre Vanduynslager 29e7ebfe0b fix(package): update hook-std to version 1.0.0 2018-06-11 11:21:16 -04:00
Matt TraviandGregor Martynus 6a36832398 fix(plugin-load): clarify load message
added quotes around plugin name to set it apart from the message. without the quotes, some consumers
were missunderstanding the successful loading of the `fail` plugin as a load failure and assuming
something was broken

resolves #811
2018-06-05 22:27:05 -07:00
Pierre Vanduynslager 4d47b20831 docs: clarify config file format 2018-06-04 15:12:46 -04:00
greenkeeper[bot]andGregor Martynus ddcf29acf7 chore(package): update nyc to version 12.0.1 2018-06-02 10:24:04 -07:00
Felix BeckerandGregor Martynus 4c157f3bfd docs(plugins): add semantic-release-vsce 2018-05-30 16:35:46 -07:00
Felix BeckerandGregor Martynus c6636abfd2 docs(plugins): remove warning
semantic-release-docker is compatible with latest semantic-release now,
see peerDependency: https://david-dm.org/felixfbecker/semantic-release-docker?type=peer
2018-05-30 16:34:59 -07:00
greenkeeper[bot]andPierre Vanduynslager 44fd7fe3f6 chore(package): update delay to version 3.0.0 2018-05-25 14:38:20 -04:00
Pierre Vanduynslager db1cc60c41 feat: verify minimum required git version is installed 2018-05-21 17:52:52 -04:00
Pierre Vanduynslager 47c73eb672 feat: add support for git version 2.0.0 2018-05-21 17:52:52 -04:00
greenkeeper[bot]andPierre Vanduynslager cd8ff5df43 fix(package): update marked-terminal to version 3.0.0 2018-05-21 15:59:09 -04:00
greenkeeper[bot]andPierre Vanduynslager a387c045a7 fix(package): update marked to version 0.4.0 2018-05-21 18:02:52 +03:00
Pierre VanduynslagerandGregor Martynus 228451b7c9 docs: fix typo 2018-05-20 15:16:55 -07:00
Pierre Vanduynslager 3503407bf4 docs: clarify which commit types trigger a release 2018-05-20 23:55:47 +03:00
Pierre Vanduynslager 5025fcab55 docs: fix FAQ heading level 2018-05-20 23:55:47 +03:00
Pierre Vanduynslager 6693080b51 style: fix table indentation 2018-05-20 23:55:47 +03:00
Pierre Vanduynslager a72d8f52af fix: add clarification in EGITNOPERMISSION error message
Clarify that the error might be due to an invalid `repositoryUrl` configuration.
2018-05-20 23:14:44 +03:00
Pierre VanduynslagerandGregor Martynus d7081fadb1 fix: use git rev-parse origin/${branch} to verify origin head 2018-05-09 13:27:33 -07:00
Pierre Vanduynslager 61d7d38ec2 feat: set tag author and committer name/email
Use [Git Environment Variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#Committing). Set default values if environement variables are not set.
2018-05-08 14:25:23 -04:00
Cory ReedandGregor Martynus 4352144a98 fix: correct git merge-base error code handling 2018-05-08 10:03:46 -07:00
Even StensbergandPierre Vanduynslager 20245b733a docs: add comment about publishing with ssh keys 2018-05-08 12:01:06 -04:00
greenkeeper[bot]andPierre Vanduynslager 349b2e8d77 fix(package): update cosmiconfig to version 5.0.0 2018-05-05 15:04:42 -04:00
pvdlg 1ed466e337 ci: run test on Node.js 10 2018-05-04 21:55:30 -04:00
Pierre ColleandPierre Vanduynslager f0f325dd7f docs: add link to shareable configs and plugins list 2018-05-04 20:32:45 -04:00
greenkeeper[bot]andPierre Vanduynslager f3e4991819 chore(package): update xo to version 0.21.0 2018-05-04 16:06:24 -04:00
pvdlgandGregor Martynus cd9f2bdd44 feat: log git error message when authentication verification fails 2018-05-04 12:19:24 -07:00
Gregor d1c3ad0b57 docs: issue templates order 2018-05-02 16:01:16 -07:00
Gregor e3da17247c docs: remove old issue templates 2018-05-02 09:47:45 -07:00
Gregor Martynus 05b09b1738 docs(ISSUE_TEMPLATES): initial version 2018-05-02 09:47:45 -07:00
pvdlgandGregor Martynus c93775cc38 feat: add support for Bitbucket token in environment variables 2018-05-01 12:02:29 -07:00
greenkeeper[bot]andGregor Martynus 22c5bbe06b chore(package): update fs-extra to version 6.0.0 2018-05-01 08:27:42 -07:00
pvdlg e88ac6300c fix: fix Bitbucket authenticated URL 2018-05-01 10:44:02 -04:00
pvdlg a52f258fa4 refactor: rename origin parameters to repositoryUrl 2018-05-01 09:59:57 -04:00
pvdlg 3f614530a0 test: prevent username/password prompt in get-git-auth-url tests 2018-05-01 09:59:57 -04:00
pvdlg d15905c0d5 fix: verify the local branch is up to date with the remote one 2018-05-01 09:59:57 -04:00
pvdlg a11da0d5e3 docs: fix jsdoc typos 2018-05-01 09:59:57 -04:00
pvdlg 65aaa77e95 refactor: remove unused test util function 2018-05-01 09:59:57 -04:00
Anshuk KumarandPierre Vanduynslager 45d7e6f25f fix: unshallow repository with credentials 2018-05-01 09:47:15 -04:00
greenkeeper[bot]andPierre Vanduynslager c02b5cac6b chore(package): update sinon to version 5.0.1 2018-04-30 10:30:37 -04:00
greenkeeper[bot]andPierre Vanduynslager b9bd650967 fix(package): update env-ci to version 2.0.0 2018-04-29 16:13:22 -04:00
greenkeeper[bot]andPierre Vanduynslager 6e15c18bea chore(package): update p-retry to version 2.0.0 2018-04-26 16:31:39 -04:00
Schalk NeethlingandPierre Vanduynslager 5af90319a1 docs: add details on NPM error 403 to troubleshooting doc 2018-04-26 11:49:32 -04:00
Gabriel DuarteandPierre Vanduynslager 218aa32f79 docs: add semantic-release-chrome to the list of community plugins 2018-04-23 12:04:26 -04:00
Pierre Vanduynslager cb1f80cb56 fix: add trailing .git to repositoryUrl only if it's present in the configured URL 2018-04-12 17:42:53 -04:00
greenkeeper[bot]andPierre Vanduynslager 7c9ec41dd7 fix(package): update git-url-parse to version 9.0.0 2018-04-12 17:42:53 -04:00
Kévin BerthommierandPierre Vanduynslager a1138a6a80 docs: update plugins package name 2018-04-11 18:40:19 -04:00
Pierre ColleandPierre Vanduynslager 6172eb807c docs: add plugins to the community list 2018-04-11 18:40:19 -04:00
Pierre Vanduynslager 31ad23125a fix: match tag to tagFormat from the begining of the string 2018-04-11 17:11:33 -04:00
Pierre Vanduynslager a8a07b7d51 docs: clarify FAQ to publish non-JavaScript packages 2018-04-10 12:11:24 -04:00
greenkeeper[bot]andPierre Vanduynslager 02746aa276 fix(package): update git-url-parse to version 8.3.1 2018-04-03 16:04:39 -04:00
William HosfordandGregor Martynus e41726cb96 docs: fix grammar and typos in CI configuration, configuration, and shareable configurations 2018-03-21 20:03:21 -07:00
Pierre Vanduynslager 51e340f44e fix: handle case with no last release in history 2018-03-21 21:41:50 -04:00
Pierre Vanduynslager 30ee231116 fix: prevent git prompt before permissions verification 2018-03-20 11:24:08 -04:00
Pierre Vanduynslager 3c46455929 fix: remove execa timeout 2018-03-20 11:24:08 -04:00
Pierre Vanduynslager dff0a34ab2 docs: add "Introduction to Semantic Release" article 2018-03-16 16:17:07 -04:00
Pierre Vanduynslager 7c48afad47 fix: prevent git CLI to prompt user/password on CI 2018-03-16 14:33:18 -04:00
Honza JavorekandPierre Vanduynslager c84ac15020 fix(package): Remove commander.js dependency (#704) 2018-03-16 14:18:49 -04:00
Pierre VanduynslagerandGregor Martynus 5f1d530e2a feat: allow to use shorthand for repositoryUrl
- `owner/repo` => `https://github.com/owner/repo.git`
- `gitlab:owner/repo` => `https://gitlab.com/owner/repo.git`
- `bitbucket:owner/repo` => `https://bitbucket.com/owner/repo.git`
2018-03-15 22:40:09 +00:00
greenkeeper[bot]andPierre Vanduynslager f13ec6a615 fix(package): update execa to version 0.10.0 2018-03-15 08:18:04 -04:00
Pierre VanduynslagerandGregor Martynus b0b4fc82de fix: convert git+https URL in package.json to https 2018-03-13 00:54:32 +00:00
Pierre VanduynslagerandGregor Martynus 6f74dcbd4a fix: use correct debug namespace 2018-03-13 00:54:32 +00:00
Gregor MartynusandPierre Vanduynslager 1129d47e1d docs(configuration): environment variable DEBUG must be set to semantic-release:*, not semantic-release 2018-03-12 16:39:46 -04:00
Pierre VanduynslagerandGregor Martynus e4618a2fbc fix: exclude prereleases from version retrived by getLastRelease 2018-03-08 17:25:40 +00:00
Pierre VanduynslagerandGregor Martynus e5a73d8628 fix: remove unecessary console.log 2018-03-07 23:01:08 +00:00
robertandPierre Vanduynslager 50f3c6e140 docs(README): correct pluralization 2018-03-07 09:39:20 -05:00
greenkeeper[bot]andPierre Vanduynslager 78f0937f24 chore(package): update proxyquire to version 2.0.0 2018-03-03 16:42:54 -05:00
William HosfordandGregor Martynus a7c187f31b docs: fix grammar and typos in README, CONTRIBUTING, installation guide, and plugin guide 2018-02-25 17:43:51 +00:00
Pierre Vanduynslager c2beb643fa feat: add the prepare plugin hook
BREAKING CHANGE: Committing or creating files in the `publish` plugin hook is not supported anymore and now must be done in the `prepare` hook

Plugins with a `publish` hook that makes a commit or create a file that can be committed must use the `prepare` hook.
2018-02-19 00:28:50 -05:00
Pierre Vanduynslager 20246c02b1 fix: exclude empty env var value from replacement 2018-02-19 00:01:06 -05:00
Pierre Vanduynslager 857d4180e9 fix: allow boolean option to be set in config file 2018-02-16 00:51:58 -05:00
Pierre Vanduynslager 4d0490122c style: lint 2018-02-15 23:19:57 -05:00
Pierre Vanduynslager aa724e80f7 chore(package): simplify xo configuration 2018-02-15 23:19:57 -05:00
greenkeeper[bot]andPierre Vanduynslager ce15b75edf chore(package): update xo to version 0.20.0 2018-02-15 23:19:57 -05:00
Pierre VanduynslagerandGregor Martynus 1966f0e3e2 fix: verify branch first 2018-02-15 18:35:37 +00:00
Pierre Vanduynslager 305f4ee8eb fix: do not transform repositoryUrl if it allow to push
Even the user set Git credentials via environment variable, use the configured URL (with authentication) if it works.
This allow users to push tags and commits via ssh while still using the GitHub/GitLab API.
2018-02-14 10:45:44 -05:00
Pierre Vanduynslager 9788fcad4e feat: use @semantic-release/github as default for success and fail hooks
BREAKING CHANGE: `success` and `fail` hooks are now enabled by default

In order to disable the `@semantic-release/github` plugin for the `success` and `fail` hook, the corresponding options have to be set to `false` in the **semantic-release** configuration:

```json
{
  "release": {
    "success": false,
    "fail": false
  }
}
```

Users who do not use the `@semantic-release/github` plugin, should disable it in the `success` and `fail` by setting the corresponding options to `false` or to alternative plugin providing `success` and `fail` hooks.
2018-02-13 16:33:37 -05:00
Pierre Vanduynslager 04f3061bed fix: remove the github plugin from default success and fail hooks 2018-02-13 16:06:30 -05:00
Pierre Vanduynslager 1b3c51d624 docs: add missing success and fail options 2018-02-13 16:06:30 -05:00
Pierre Vanduynslager 8a2ef48308 test: revert to mockserver:latest docker container 2018-02-12 21:40:47 -05:00
Pierre Vanduynslager ce1e74f611 fix: set repository authentication when repositoryUrl is set as an option 2018-02-12 16:17:09 -05:00
Pierre Vanduynslager b6837a20a8 test: use older version of mockserver
Due to https://github.com/jamesdbloom/mockserver/issues/435
2018-02-12 16:17:09 -05:00
Pierre VanduynslagerandGregor Martynus 97cb354fea feat: improve CLI
- Replace `commander.js` with `yargs`
- Add CLI unit tests
- Add a `--version` option
- Improve `--help` output
- Remove `commander.js` related workaround
- Allow to set list option with arg repetition or space separated list
- Maintain the list options defined as comma separated list
2018-02-12 11:01:09 -08:00
Pierre VanduynslagerandGregor Martynus f92677b092 fix: log current version of semantic-release 2018-02-12 11:01:09 -08:00
Pierre Vanduynslager 9dd127ba98 fix: fix EPLUGINCONF error details 2018-02-12 00:36:06 -05:00
Pierre Vanduynslager c9bd5de075 docs: simplify GitLAb-ci config
- remove Node 4
2018-02-11 22:17:12 -05:00
Pierre Vanduynslager 51f6e5fd60 docs: simplify travis config
- remove OSs
- remove Node 4
2018-02-11 22:17:12 -05:00
Pierre Vanduynslager c6e95b0885 docs: add CircleCI workflows recipe 2018-02-11 22:17:12 -05:00
Pierre Vanduynslager 7fbd2721c4 docs: add Travis Build Stages recipe 2018-02-11 22:17:12 -05:00
Pierre Vanduynslager fcb64e6fef docs: remove unnecessary script override in travis recipe 2018-02-11 22:17:12 -05:00
Pierre Vanduynslager d72cfc2546 docs: fix typo in travis recipe 2018-02-11 22:17:12 -05:00
Pierre Vanduynslager 49f5e704ba feat: add success and fail notification plugins
- Allow `publish` plugins to return an `Object` with information related to the releases
- Add the `success` plugin hook, called when all `publish` are successful, receiving a list of release
- Add the `fail` plugin hook, called when an error happens at any point, receiving a list of errors
- Add detailed message for each error
2018-02-11 19:53:41 -05:00
Pierre Vanduynslager 9b2f6bfed2 feat: allow plugins to throw an iterable list of errors 2018-02-11 19:53:41 -05:00
Pierre Vanduynslager 9360caf253 docs: fix minor typo in FAQ 2018-02-10 23:38:12 -05:00
mchao409andGregor Martynus 2f8d71644d docs: make some grammatical, spelling, typo fixes. 2018-02-09 21:26:21 -08:00
Pierre Vanduynslager 5fd990acef docs: fix typo in extending link 2018-02-09 18:43:56 -05:00
Pierre Vanduynslager 687435b9a2 feat: add debug logs for git commands 2018-02-08 16:43:17 -05:00
Pierre Vanduynslager 7e785fa757 fix: debug log all options 2018-02-08 16:13:04 -05:00
Pierre Vanduynslager 053c9edf9b test: add test to parse GitLab/Bitbucket URLs with groups 2018-02-07 21:03:36 -05:00
Pierre Vanduynslager 2edd9da598 fix(package): update git-url-parse to version 8.1.0 2018-02-07 21:03:36 -05:00
Pierre Vanduynslager cbf57851fb fix: always transform git+https url to https 2018-02-02 15:33:36 -05:00
Pierre VanduynslagerandGitHub af8c830335 fix(package): update @semantic-release/github to version 4.0.2 2018-02-02 13:55:21 -05:00
Christian MusaandPierre Vanduynslager d8208237f2 fix: use long option to delete tag in git push 2018-01-31 16:22:04 -05:00
Pierre Vanduynslager 39536fa34e feat: add tagFormat option to customize Git tag name 2018-01-29 00:55:32 -05:00
Pierre Vanduynslager faabffb208 fix: log all core verification errors 2018-01-29 00:55:32 -05:00
Anthony NgandGregor Martynus 2f75dff3fc docs: fix image path (#625) 2018-01-28 14:01:12 -08:00
Stephan BönnemannandGregor Martynus dc416b2ce9 docs: explain npx alternatives for Yarn 2018-01-27 19:04:12 -08:00
Stephan BönnemannandGregor Martynus e3c9bb8bd4 docs: recommend to execute semantic-release via npx 2018-01-27 19:04:12 -08:00
Pierre Vanduynslager 467635bc14 fix: prioritize GIT_CREDENTIALS for gtit credentials
Allow to defined a both `GIT_CREDENTIALS` for repository access and `GH_TOKEN` or `GL_TOKEN` for API access
2018-01-27 20:31:59 -05:00
Pierre Vanduynslager 8b3605dd04 fix: hide sensitive info for Buffer and undefined 2018-01-27 18:24:24 -05:00
Pierre Vanduynslager cb36dd4890 fix: rename the --repositoryUrl CLI option to --repository-url
Harmonize the CLI option format.

BREAKING CHANGE: The `--repositoryUrl` CLI options is replaced by `--repository-url`
2018-01-27 16:50:29 -05:00
Pierre Vanduynslager d0b304e240 feat: get last release with git tags
- Remove the `getLastRelease` plugin type
- Retrieve the last release based on Git tags
- Create the next release Git tag before calling the `publish` plugins

BREAKING CHANGE: Remove the `getLastRelease` plugin type

The `getLastRelease` plugins will not be called anymore.

BREAKING CHANGE: Git repository authentication is now mandatory

The Git authentication is now mandatory and must be set via `GH_TOKEN`, `GITHUB_TOKEN`,  `GL_TOKEN`, `GITLAB_TOKEN` or `GIT_CREDENTIALS` as described in [CI configuration](https://github.com/semantic-release/semantic-release/blob/caribou/docs/usage/ci-configuration.md#authentication).
2018-01-27 16:50:29 -05:00
Pierre Vanduynslager fb0caa005b feat: hide sensitive info in stdout/sdtin 2018-01-27 14:00:06 -05:00
Pierre Vanduynslager cdb98f919f feat: log all verification errors 2018-01-27 13:24:39 -05:00
greenkeeper[bot]andPierre Vanduynslager 03e117be10 chore(package): update ava to version 0.25.0 2018-01-26 10:59:15 -05:00
Pierre VanduynslagerandGregor Martynus 0d2d1f2376 fix: fix the --no-ci arg parsing
The `noCi` is no properly set based on the `--no-ci` CLI arg and it is overwritten by the `noCi` option
2018-01-24 22:22:16 -08:00
Pierre VanduynslagerandGregor Martynus 7e860c7915 docs(travis): recommend to use the deploy step instead of script
The `script` step can be used with Build Stage if `semantic-release` is the only `script` ran in the `release` stage.

See https://github.com/travis-ci/travis-ci/issues/1066
2018-01-21 15:00:05 -08:00
Pierre VanduynslagerandGregor Martynus e0fa20b8a0 ci(travis): use Build Stages 2018-01-21 15:00:05 -08:00
68 changed files with 3916 additions and 1949 deletions
-48
View File
@@ -1,48 +0,0 @@
<!--
Please fill the informations requested or use one of the following url:
- Bug report: https://github.com/semantic-release/semantic-release/issues/new?template=bug-report.md
- Feature request: https://github.com/semantic-release/semantic-release/issues/new?template=feature-request.md
- New plugin request: https://github.com/semantic-release/semantic-release/issues/new?template=plugin-request.md
-->
<!--------------------- FOR BUG REPORT ONLY --------------------->
## Current behavior
<!-- Describe how the issue manifests. -->
## Expected behavior
<!-- Describe what the desired behavior would be. -->
## Environment
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
- CI environment: <!-- CI service name -->
- Plugins used: <!-- List semantic-release plugin used if any -->
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
- CI logs: <!-- link to your CI logs or semantic-release logs -->
<!--------------------- FOR FEATURE REQUEST ONLY --------------------->
## New feature motivation
<!-- Describe the context, the use-case and the advantages of the feature request. -->
## New feature description
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
## New feature implementation
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
<!--------------------- FOR NEW PLUGIN REQUEST ONLY --------------------->
## New plugin motivation
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
## Third-party documentation
<!-- Provide explanation and documentation links for the platform to integrate with. -->
@@ -1,17 +1,21 @@
# Bug report
## Current behavior
<!-- Describe how the issue manifests. -->
## Expected behavior
<!-- Describe what the desired behavior would be. -->
## Environment
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
- CI environment: <!-- CI service name -->
- Plugins used: <!-- List semantic-release plugin used if any -->
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
- CI logs: <!-- link to your CI logs or semantic-release logs -->
---
name: Bug report
about: Something not working as expected
---
## Current behavior
<!-- Describe how the issue manifests. -->
## Expected behavior
<!-- Describe what the desired behavior would be. -->
## Environment
- **semantic-release** version: <!-- Version set in package.json devDpendencies -->
- CI environment: <!-- CI service name -->
- Plugins used: <!-- List semantic-release plugin used if any -->
- **semantic-release** configuration: <!-- link to your repository or relevant part of the semantic-release config -->
- CI logs: <!-- link to your CI logs or semantic-release logs -->
@@ -1,13 +1,17 @@
# Feature request
## New feature motivation
<!-- Describe the context, the use-case and the advantages of the feature request. -->
## New feature description
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
## New feature implementation
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
---
name: Feature request
about: Wouldnt it be nice if semantic-release could ...
---
## New feature motivation
<!-- Describe the context, the use-case and the advantages of the feature request. -->
## New feature description
<!-- Describe the functional changes that would have to be made in semantic-release or its plugins. -->
## New feature implementation
<!-- Optionally describe the technical changes to be made in semantic-release or its plugins. -->
@@ -1,9 +1,13 @@
# New plugin request
## New plugin motivation
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
## Third-party documentation
<!-- Provide explanation and documentation links for the platform to integrate with. -->
---
name: New plugin suggestion
about: Integrate with a new platform, etc
---
## New plugin motivation
<!-- Describe the reasons to create a new plugin and why it's not covered by the existing ones. -->
## Third-party documentation
<!-- Provide explanation and documentation links for the platform to integrate with. -->
+10 -7
View File
@@ -1,13 +1,11 @@
language: node_js
services:
- docker
notifications:
email: false
node_js:
- 9
- 10
- 8
os:
- linux
# 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)
@@ -25,5 +23,10 @@ script:
after_success:
- npm run codecov
- npm install -g travis-deploy-once@4
- travis-deploy-once "npm run semantic-release"
jobs:
include:
- stage: release
node_js: lts/*
script:
- npm run semantic-release
+25 -25
View File
@@ -10,7 +10,7 @@ As a contributor, here are the guidelines we would like you to follow:
- [Coding rules](#coding-rules)
- [Working with the code](#working-with-the-code)
We also recommend to read [How to Contribute to Open Source](https://opensource.guide/how-to-contribute).
We also recommend that you read [How to Contribute to Open Source](https://opensource.guide/how-to-contribute).
## Code of conduct
@@ -20,33 +20,33 @@ Help us keep **semantic-release** open and inclusive. Please read and follow our
### Improve documentation
As a **semantic-release** user you are the perfect candidate to help us improve our documentation: typo corrections, clarifications, more examples, new [recipes](docs/recipes/README.md) etc. Take a look at the [documentation issues that need help](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22+label%3Adocs+).
As a **semantic-release** user, you are the perfect candidate to help us improve our documentation: typo corrections, clarifications, more examples, new [recipes](docs/recipes/README.md), etc. Take a look at the [documentation issues that need help](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22+label%3Adocs+).
Please follow the [Documentation guideline](#documentation).
Please follow the [Documentation guidelines](#documentation).
### Give feedback on issues
Some issues are created without information requested in the [Bug report guideline](#bug-report). Help making them easier to resolve by adding any relevant informations.
Some issues are created without information requested in the [Bug report guideline](#bug-report). Help make them easier to resolve by adding any relevant information.
Issues with the [design label](https://github.com/issues?q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3Adesign) are meant to discuss the implementation of new features. Participating in the discussion is a good opportunity to get involved and influence the future direction of **semantic-release**.
### Fix bugs and implement features
Confirmed bug and ready to implement features are marked with the [help wanted label](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22). Post a comment on an issue to indicate you would like to work on it and to request help from the [@semantic-release/maintainers](https://github.com/orgs/semantic-release/teams/contributors) and the community.
Confirmed bugs and ready-to-implement features are marked with the [help wanted label](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22). Post a comment on an issue to indicate you would like to work on it and to request help from the [@semantic-release/maintainers](https://github.com/orgs/semantic-release/teams/contributors) and the community.
## Using the issue tracker
The issue tracker is the channel for [bug reports](#bug-report), [features requests](#feature-request) and [submitting pull requests](#submitting-a-pull-request) only. Please use the [Support](docs/support/README.md) and [Get help](README.md#get-help) sections for support, troubleshooting and questions.
Before opening an Issue or a Pull Request, please use the [GitHub issue search](https://github.com/issues?utf8=%E2%9C%93&q=user%3Asemantic-release) to make the bug or feature request hasn't been already reported or fixed.
Before opening an issue or a Pull Request, please use the [GitHub issue search](https://github.com/issues?utf8=%E2%9C%93&q=user%3Asemantic-release) to make sure the bug or feature request hasn't been already reported or fixed.
### Bug report
A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report and fill the information requested in the [Bug report template](https://github.com/semantic-release/semantic-release/issues/new?template=bug-report.md).
A good bug report shouldn't leave others needing to chase you for more information. Please try to be as detailed as possible in your report and fill the information requested in the [Bug report template](https://github.com/semantic-release/semantic-release/issues/new?template=bug-report.md).
### Feature request
Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible and fill the information requested in the [Feature request template](https://github.com/semantic-release/semantic-release/issues/new?template=feature-request.md).
Feature requests are welcome, but take a moment to find out whether your idea fits with the scope and aims of the project. It's up to you to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible and fill the information requested in the [Feature request template](https://github.com/semantic-release/semantic-release/issues/new?template=feature-request.md).
### New plugin request
@@ -54,11 +54,11 @@ Feature requests are welcome. But take a moment to find out whether your idea fi
## Submitting a Pull Request
Good pull requests whether patches, improvements or new features are a fantastic help. They should remain focused in scope and avoid containing unrelated commits.
Good pull requests, whether patches, improvements, or new features, are a fantastic help. They should remain focused in scope and avoid containing unrelated commits.
**Please ask first** before embarking on any significant pull request (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project.
**Please ask first** before embarking on any significant pull requests (e.g. implementing features, refactoring code), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project.
If you never created a pull request before, welcome 🎉 😄. [Here is a great tutorial](https://opensource.guide/how-to-contribute/#opening-a-pull-request) on how to send one :)
If you have never created a pull request before, welcome 🎉 😄. [Here is a great tutorial](https://opensource.guide/how-to-contribute/#opening-a-pull-request) on how to send one :)
Here is a summary of the steps to follow:
@@ -82,16 +82,16 @@ $ git push origin <topic-branch-name>
6. [Open a Pull Request](https://help.github.com/articles/creating-a-pull-request/#creating-the-pull-request) with a clear title and description.
**Tips**:
- For ambitious tasks, open a Pull Request as soon as possible with the `[WIP]` prefix i nthe title, in order to get feedback and help from the community.
- [Allow semantic-release maintainers to make changes to you Pull Request branch](https://help.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork) this way we can rebase it and make some minor changes if necessary. All changes we make will be done in new commit and we'll ask for your approval before merging them.
- For ambitious tasks, open a Pull Request as soon as possible with the `[WIP]` prefix in the title, in order to get feedback and help from the community.
- [Allow semantic-release maintainers to make changes to your Pull Request branch](https://help.github.com/articles/allowing-changes-to-a-pull-request-branch-created-from-a-fork). This way, we can rebase it and make some minor changes if necessary. All changes we make will be done in new commit and we'll ask for your approval before merging them.
## Coding rules
### Source code
To ensure consistency and quality throughout the source code, all code modification must have:
To ensure consistency and quality throughout the source code, all code modifications must have:
- No [linting](#lint) errors
- A [test](#tests) for every possible cases introduced by your code change
- A [test](#tests) for every possible case introduced by your code change
- **100%** test coverage
- [Valid commit message(s)](#commit-message-guidelines)
- Documentation for new features
@@ -99,10 +99,10 @@ To ensure consistency and quality throughout the source code, all code modificat
### Documentation
To ensure consistency and quality all documentation modification must:
To ensure consistency and quality, all documentation modifications must:
- Refer to brand in [bold](https://help.github.com/articles/basic-writing-and-formatting-syntax/#styling-text) with proper capitalization, i.e. **GitHub**, **semantic-release**, **npm**
- Prefer [tables](https://help.github.com/articles/organizing-information-with-tables) over [lists](https://help.github.com/articles/basic-writing-and-formatting-syntax/#lists) when listing key values, i.e. List of options with their description
- Use [links](https://help.github.com/articles/basic-writing-and-formatting-syntax/#links) when, the first you are referring to:
- Use [links](https://help.github.com/articles/basic-writing-and-formatting-syntax/#links) when you are referring to:
- a **semantic-release** concept described somewhere else in the documentation, i.e. How to [contribute](CONTRIBUTING.md)
- a third-party product/brand/service, i.e. Integrate with [GitHub](https://github.com)
- an external concept or feature, i.e. Create a [GitHub release](https://help.github.com/articles/creating-releases)
@@ -125,7 +125,7 @@ If possible, make [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit),
- a functional change should be contained in exactly one commit
- a commit should not create an inconsistent state (such as test errors, linting errors, partial fix, feature with documentation etc...)
A complex feature can be broken down into multiple commits as long as each one keep a consistent state and consist of a self-contained change.
A complex feature can be broken down into multiple commits as long as each one maintains a consistent state and consists of a self-contained change.
#### Commit message format
@@ -219,21 +219,21 @@ $ npm install
### Lint
All the [semantic-release](https://github.com/semantic-release) repository use [XO](https://github.com/sindresorhus/xo) for linting and [Prettier](https://prettier.io) for formatting. Prettier formatting will be automatically verified and fixed by XO.
All the [semantic-release](https://github.com/semantic-release) repositories use [XO](https://github.com/sindresorhus/xo) for linting and [Prettier](https://prettier.io) for formatting. Prettier formatting will be automatically verified and fixed by XO.
Before pushing your code changes make sure there is no linting errors with `npm run lint`.
Before pushing your code changes make sure there are no linting errors with `npm run lint`.
**Tips**:
- Most linting errors can be automatically fixed with `npm run lint --fix`.
- Install the [XO plugin](https://github.com/sindresorhus/xo#editor-plugins) for your editor to see linting error directly in your editor and automatically fix them on save.
- Install the [XO plugin](https://github.com/sindresorhus/xo#editor-plugins) for your editor to see linting errors directly in your editor and automatically fix them on save.
### Tests
Running the integration test require to install [Docker](https://docs.docker.com/engine/installation) on your machine.
Running the integration test requires you to install [Docker](https://docs.docker.com/engine/installation) on your machine.
All the [semantic-release](https://github.com/semantic-release) repository use [AVA](https://github.com/avajs/ava) for writing and running tests.
All the [semantic-release](https://github.com/semantic-release) repositories use [AVA](https://github.com/avajs/ava) for writing and running tests.
Before pushing your code changes make sure all **test pass** and the **coverage is 100%**:
Before pushing your code changes make sure all **tests pass** and the **coverage is 100%**:
```bash
$ npm run test
@@ -246,6 +246,6 @@ $ npm run test
### Commits
All the [semantic-release](https://github.com/semantic-release) repository use [Commitizen](https://github.com/commitizen/cz-cli) to help you create [valid commit messages](#commit-message-guidelines).
All the [semantic-release](https://github.com/semantic-release) repositories use [Commitizen](https://github.com/commitizen/cz-cli) to help you create [valid commit messages](#commit-message-guidelines).
After staging your changes with `git add`, run `npm run cm` to start the interactive commit message CLI.
+11 -7
View File
@@ -37,21 +37,22 @@ This removes the immediate connection between human emotions and version numbers
- Fully automated release
- Enforce [Semantic Versioning](https://semver.org) specification
- New features and fixes are immediately available to users
- Notify maintainers and users of new releases
- Use formalized commit message convention to document changes in the codebase
- Integrate with your [continuous integration workflow](docs/recipes/README.md#ci-configurations)
- Avoid potential errors associated with manual releases
- Support any [package managers and languages](docs/recipes/README.md#package-managers-and-languages) via [plugins](docs/usage/plugins.md)
- Support any [package managers and languages](docs/recipes/README.md#package-managers-and-languages) via [plugins](docs/usage/plugins.md)
- Simple and reusable configuration via [shareable configurations](docs/usage/shareable-configurations.md)
## How does it work?
### Commit message format
**semantic-release** uses the commit messages to determine the type of changes in the codebase. Following formalized conventions for commit messages, **semantic-release** automatically determines the next [semantic version](https://semver.org) number, generates a changelog and publish the release.
**semantic-release** uses the commit messages to determine the type of changes in the codebase. Following formalized conventions for commit messages, **semantic-release** automatically determines the next [semantic version](https://semver.org) number, generates a changelog and publishes the release.
By default **semantic-release** uses [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines). The commit message format can be changed with the [`preset` or `config` options](docs/usage/configuration.md#options) of the [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer#options) and [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator#options) plugins.
Tools such as [commitizen](https://github.com/commitizen/cz-cli), [commitlint](https://github.com/marionebl/commitlint) or [semantic-git-commit-cli](https://github.com/JPeer264/node-semantic-git-commit-cli) can be used to help contributor and enforce valid commits message.
Tools such as [commitizen](https://github.com/commitizen/cz-cli), [commitlint](https://github.com/marionebl/commitlint) or [semantic-git-commit-cli](https://github.com/JPeer264/node-semantic-git-commit-cli) can be used to help contributors and enforce valid commit messages.
Here is an example of the release type that will be done based on a commit messages:
@@ -67,9 +68,9 @@ Here is an example of the release type that will be done based on a commit messa
### Triggering a release
When pushing new commits to the release branch (i.e. `master`) with `git push` or by merging a pull request or merging from another branch, a CI build is triggered and runs the `semantic-release` command to make a release if there is relevant codebase changes since the last release.
For each new commits added to the release branch (i.e. `master`) with `git push` or by merging a pull request or merging from another branch, a CI build is triggered and runs the `semantic-release` command to make a release if there are codebase changes since the last release that affect the package functionalities.
By default a release will be done for each push to the release branch that contains relevant code changes. If you need more control over the timing of releases you have a couple of options:
If you need more control over the timing of releases you have a couple of options:
- Publish releases on a distribution channel (for example npms [dist-tags](https://docs.npmjs.com/cli/dist-tag)). This way you can keep control over what your users end up using by default, and you can decide when to make an automatically released version available to the stable channel, and promote it.
- Develop on a `dev` branch and merge it to the release branch (i.e. `master`) once you are ready to publish. **semantic-release** will run only on pushes to the release branch.
@@ -80,11 +81,14 @@ After running the tests the command `semantic-release` will execute the followin
| Step | Description |
|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Verify Conditions | Verify all the conditions to proceed with the release with the [verify conditions plugins](docs/usage/plugins.md#verifyconditions-plugin). |
| Get last release | Obtain last release with the [get last release plugin](docs/usage/plugins.md#getlastrelease-plugin). |
| Analyze commits | Determine the type of release to do with the [analyze commits plugin](docs/usage/plugins.md#analyzecommits-plugin) based on the commits added since the last release. |
| Get last release | Obtain the commit corresponding to the last release by analyzing [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). |
| Analyze commits | Determine the type of release with the [analyze commits plugin](docs/usage/plugins.md#analyzecommits-plugin) based on the commits added since the last release. |
| Verify release | Verify the release conformity with the [verify release plugins](docs/usage/plugins.md#verifyrelease-plugin). |
| Generate notes | Generate release notes with the [generate notes plugin](docs/usage/plugins.md#generatenotes-plugin) for the commits added since the last release. |
| Create Git tag | Create a Git tag corresponding to the new release version |
| Prepare | Prepare the release with the [prepare plugins](docs/usage/plugins.md#prepare-plugin). |
| Publish | Publish the release with the [publish plugins](docs/usage/plugins.md#publish-plugin). |
| Notify | Notify of new releases or errors with the [success](docs/usage/plugins.md#success-plugin) and [fail](docs/usage/plugins.md#fail-plugin) plugins. |
## Documentation
+2
View File
@@ -21,6 +21,8 @@
- [Travis CI](docs/recipes/travis.md)
- [Travis CI with build stages](docs/recipes/travis-build-stages.md)
- [GitLab CI](docs/recipes/gitlab-ci.md)
- [Git hosted services](docs/recipes/README.md)
- [Git authentication with SSH keys](docs/recipes/git-auth-ssh-keys.md)
- [Package managers and languages](docs/recipes/README.md)
## Developer guide
+20 -1
View File
@@ -3,11 +3,15 @@
// Bad news: We have to write plain ES5 in this file
// Good news: It's the only file of the entire project
/* eslint-disable no-var */
/* eslint-disable no-var, promise/prefer-await-to-then, prefer-destructuring */
var semver = require('semver');
var execa = require('execa');
var findVersions = require('find-versions');
var pkg = require('../package.json');
var MIN_GIT_VERSION = '2.0.0';
if (!semver.satisfies(process.version, pkg.engines.node)) {
console.error(
`[semantic-release]: node version ${pkg.engines.node} is required. Found ${process.version}.
@@ -17,6 +21,21 @@ See https://github.com/semantic-release/semantic-release/blob/caribou/docs/suppo
process.exit(1);
}
execa
.stdout('git', ['--version'])
.then(stdout => {
var gitVersion = findVersions(stdout)[0];
if (semver.lt(gitVersion, MIN_GIT_VERSION)) {
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. Found ${gitVersion}.`);
process.exit(1);
}
})
.catch(err => {
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. No git binary found.`);
console.error(err);
process.exit(1);
});
// Node 8+ from this point on
require('../cli')().catch(() => {
process.exitCode = 1;
+54 -52
View File
@@ -1,62 +1,64 @@
const program = require('commander');
const {pickBy, isUndefined} = require('lodash');
const logger = require('./lib/logger');
function list(values) {
return values.split(',').map(value => value.trim());
}
const stringList = {
type: 'string',
array: true,
coerce: values =>
values.length === 1 && values[0].trim() === 'false'
? []
: values.reduce((values, value) => values.concat(value.split(',').map(value => value.trim())), []),
};
module.exports = async () => {
program
.name('semantic-release')
.description('Run automated package publishing')
.option('-b, --branch <branch>', 'Branch to release from')
.option('-r, --repositoryUrl <repositoryUrl>', 'Git repository URL')
.option('-e, --extends <paths>', 'Comma separated list of shareable config paths or packages name', list)
.option(
'--verify-conditions <paths>',
'Comma separated list of paths or packages name for the verifyConditions plugin(s)',
list
)
.option('--get-last-release <path>', 'Path or package name for the getLastRelease plugin')
.option('--analyze-commits <path>', 'Path or package name for the analyzeCommits plugin')
.option(
'--verify-release <paths>',
'Comma separated list of paths or packages name for the verifyRelease plugin(s)',
list
)
.option('--generate-notes <path>', 'Path or package name for the generateNotes plugin')
.option('--publish <paths>', 'Comma separated list of paths or packages name for the publish plugin(s)', list)
.option(
'--no-ci',
'Skip Continuous Integration environment verifications, allowing to make releases from a local machine'
)
.option('--debug', 'Output debugging information')
.option(
'-d, --dry-run',
'Dry-run mode, skipping verifyConditions, publishing and release, printing next version and release notes'
)
.parse(process.argv);
const cli = require('yargs')
.command('$0', 'Run automated package publishing', yargs => {
yargs.demandCommand(0, 0).usage(`Run automated package publishing
if (program.debug) {
// Debug must be enabled before other requires in order to work
require('debug').enable('semantic-release:*');
}
Usage:
semantic-release [options] [plugins]`);
})
.option('b', {alias: 'branch', describe: 'Git branch to release from', type: 'string', group: 'Options'})
.option('r', {alias: 'repository-url', describe: 'Git repository URL', type: 'string', group: 'Options'})
.option('t', {alias: 'tag-format', describe: 'Git tag format', type: 'string', group: 'Options'})
.option('e', {alias: 'extends', describe: 'Shareable configurations', ...stringList, group: 'Options'})
.option('ci', {describe: 'Toggle CI verifications', type: 'boolean', group: 'Options'})
.option('verify-conditions', {...stringList, group: 'Plugins'})
.option('analyze-commits', {type: 'string', group: 'Plugins'})
.option('verify-release', {...stringList, group: 'Plugins'})
.option('generate-notes', {type: 'string', group: 'Plugins'})
.option('prepare', {...stringList, group: 'Plugins'})
.option('publish', {...stringList, group: 'Plugins'})
.option('success', {...stringList, group: 'Plugins'})
.option('fail', {...stringList, group: 'Plugins'})
.option('debug', {describe: 'Output debugging information', type: 'boolean', group: 'Options'})
.option('d', {alias: 'dry-run', describe: 'Skip publishing', type: 'boolean', group: 'Options'})
.option('h', {alias: 'help', group: 'Options'})
.option('v', {alias: 'version', group: 'Options'})
.strict(false)
.exitProcess(false);
try {
if (program.args.length > 0) {
program.outputHelp();
process.exitCode = 1;
} else {
// Remove option with undefined values, as commander.js sets non defined options as `undefined`
await require('.')(pickBy(program.opts(), value => !isUndefined(value)));
const {help, version, ...opts} = cli.argv;
if (Boolean(help) || Boolean(version)) {
process.exitCode = 0;
return;
}
// Set the `noCi` options as yargs sets the `ci` options instead (because arg starts with `--no`)
if (opts.ci === false) {
opts.noCi = true;
}
if (opts.debug) {
// Debug must be enabled before other requires in order to work
require('debug').enable('semantic-release:*');
}
await require('.')(opts);
process.exitCode = 0;
} catch (err) {
process.exitCode = 1;
if (err.semanticRelease) {
logger.log(`%s ${err.message}`, err.code);
} else {
logger.error('An error occurred while running semantic-release: %O', err);
if (err.name !== 'YError') {
console.error(err);
}
process.exitCode = 1;
}
};
+1 -1
View File
@@ -1,7 +1,7 @@
# semantic-release documentation
- [Usage](usage/README.md) - **semantic-release** installation and configuration
- [Extending][extending/README.md]- Extending **semantic-release** with plugins and shareable configurations
- [Extending](extending/README.md)- Extending **semantic-release** with plugins and shareable configurations
- [Recipes](recipes/README.md) - Community written recipes for common **semantic-release** use-cases
- [Developer Guide](developer-guide/README.md) - The essentials of writing a **semantic-release** plugin or shareable configurations
- [Resources](resources.md) - Videos, articles and tutorials
+25 -6
View File
@@ -5,9 +5,11 @@
- [@semantic-release/github](https://github.com/semantic-release/github)
- [verifyConditions](https://github.com/semantic-release/github#verifyconditions): Verify the presence and the validity of the GitHub authentication and release configuration
- [publish](https://github.com/semantic-release/github#publish): Publish a [GitHub release](https://help.github.com/articles/about-releases)
- [success](https://github.com/semantic-release/github#success): Add a comment to GitHub issues and pull requests resolved in the release
- [fail](https://github.com/semantic-release/github#fail): Open a GitHub issue when a release fails
- [@semantic-release/npm](https://github.com/semantic-release/npm)
- [verifyConditions](https://github.com/semantic-release/npm#verifyconditions): Verify the presence and the validity of the npm authentication and release configuration
- [getLastRelease](https://github.com/semantic-release/npm#getlastrelease): Determine the last release of the package on the npm registry
- [prepare](https://github.com/semantic-release/npm#prepare): Update the package.json version and create the npm package tarball
- [publish](https://github.com/semantic-release/npm#publish): Publish the package on the npm registry
## Official plugins
@@ -17,17 +19,34 @@
- [publish](https://github.com/semantic-release/gitlab#publish): Publish a [GitLab release](https://docs.gitlab.com/ce/workflow/releases.html)
- [@semantic-release/git](https://github.com/semantic-release/git)
- [verifyConditions](https://github.com/semantic-release/git#verifyconditions): Verify the presence and the validity of the Git authentication and release configuration
- [getLastRelease](https://github.com/semantic-release/git#getlastrelease): Determine the last release via Git tags on the repository
- [publish](https://github.com/semantic-release/git#publish): Push a release commit and tag, including configurable files
- [prepare](https://github.com/semantic-release/git#prepare): Push a release commit and tag, including configurable files
- [@semantic-release/changelog](https://github.com/semantic-release/changelog)
- [verifyConditions](https://github.com/semantic-release/changelog#verifyconditions): Verify the presence and the validity of the configuration
- [publish](https://github.com/semantic-release/changelog#publish): Create or update the changelog file in the local project repository
- [prepare](https://github.com/semantic-release/changelog#prepare): Create or update the changelog file in the local project repository
- [@semantic-release/exec](https://github.com/semantic-release/exec)
- [verifyConditions](https://github.com/semantic-release/exec#verifyconditions): Execute a shell command to verify if the release should happen
- [getLastRelease](https://github.com/semantic-release/exec#getlastrelease): Execute a shell command to determine the last release
- [analyzeCommits](https://github.com/semantic-release/exec#analyzecommits): Execute a shell command to determine the type of release
- [verifyRelease](https://github.com/semantic-release/exec#verifyrelease): Execute a shell command to verifying a release that was determined before and is about to be published.
- [generateNotes](https://github.com/semantic-release/exec#analyzecommits): Execute a shell command to generate the release note
- [publish](https://github.com/semantic-release/exec#publish): Execute a shell command to publish the release.
- [prepare](https://github.com/semantic-release/exec#prepare): Execute a shell command to prepare the release
- [publish](https://github.com/semantic-release/exec#publish): Execute a shell command to publish the release
- [success](https://github.com/semantic-release/exec#success): Execute a shell command to notify of a new release
- [fail](https://github.com/semantic-release/exec#fail): Execute a shell command to notify of a failed release
## Community plugins
[Open a Pull Request](https://github.com/semantic-release/semantic-release/blob/caribou/CONTRIBUTING.md#submitting-a-pull-request) to add your plugin to the list.
- [semantic-release-docker](https://github.com/felixfbecker/semantic-release-docker) Set of semantic-release plugins for publishing a docker image to Docker Hub
- [verifyConditions](https://github.com/felixfbecker/semantic-release-docker#verifyconditions) Verify that all needed configuration is present and login to the Docker registry.
- [publish](https://github.com/felixfbecker/semantic-release-docker#publish) Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag.
- [semantic-release-vsce](https://github.com/raix/semantic-release-vsce) Set of semantic-release plugins for publishing Visual Studio Code extensions to the marketplace
- **verifyConditions** Verify the presence and the validity of the vsce authentication and release configuration
- **prepare** Create a `.vsix` for distribution
- **publish** Publish the package to the Visual Studio Code marketplace
- [semantic-release-verify-deps](https://github.com/piercus/semantic-release-verify-deps)
- [verifyConditions](https://github.com/piercus/semantic-release-verify-deps) Check the dependencies format against a regexp before a release
- [semantic-release-chrome](https://github.com/GabrielDuarteM/semantic-release-chrome) Set of semantic-release plugins for publishing a Chrome extension release.
- [verifyConditions](https://github.com/GabrielDuarteM/semantic-release-chrome#verifyconditions) Verify the presence of the authentication (set via environment variables).
- [prepare](https://github.com/GabrielDuarteM/semantic-release-chrome#prepare) Write the correct version to the manifest.json and creates a zip file of the whole dist folder.
- [publish](https://github.com/GabrielDuarteM/semantic-release-chrome#publish) Uploads the generated zip file to the webstore, and publish the item.
+3
View File
@@ -6,4 +6,7 @@
- [Travis CI with build stages](travis-build-stages.md)
- [GitLab CI](gitlab-ci.md)
## Git hosted services
- [Git authentication with SSH keys](git-auth-ssh-keys.md)
## Package managers and languages
+65 -1
View File
@@ -1 +1,65 @@
# CircleCI 2.0 workflows
# Using semantic-release with [CircleCI 2.0 workflows](https://circleci.com/docs/2.0/workflows)
## Environment variables
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [CircleCi Project Settings](https://circleci.com/docs/2.0/env-vars/#adding-environment-variables-in-the-app)..
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/ci-configuration.md#automatic-setup-with-semantic-release-cli).
## Multiple Node jobs configuration
### `.circleci/config.yml` configuration for multiple Node jobs
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [CircleCI documentation](https://circleci.com/docs/2.0) for additional configuration options.
This example create the workflows `test_node_4`, `test_node_6`, `test_node_8` and `release`. The release workflows will [run `semantic-release` only after the all the `test_node_*` are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
```yaml
version: 2
jobs:
test_node_6:
docker:
- image: circleci/node:6
steps:
# Configure your test steps here (checkout, npm install, cache management, tests etc...)
test_node_8:
docker:
- image: circleci/node:8
steps:
# Configure your test steps here (checkout, npm install, cache management, tests etc...)
release:
docker:
- image: circleci/node:8
steps:
- checkout
- run: npm install
# Run optional required steps before releasing
# - run: npm run build-script
- run: npx semantic-release
workflows:
version: 2
test_and_release:
# Run the test jobs first, then the release only when all the test jobs are successful
jobs:
- test_node_6
- test_node_8
- release:
requires:
- test_node_6
- test_node_8
```
### `package.json` configuration for multiple Node jobs
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
"devDependencies": {
"semantic-release": "^15.0.0"
}
}
```
+163
View File
@@ -0,0 +1,163 @@
# Git authentication with SSH keys
When using [environment variables](../usage/ci-configuration.md#authentication) to set up the Git authentication, the remote Git repository will automatically be accessed via [https](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_http_protocols), independently of the [`repositoryUrl`](../usage/configuration.md#repositoryurl) format configured in the **semantic-release** [Configuration](../usage/configuration.md#configuration) (the format will be automatically converted as needed).
Alternatively the Git repository can be accessed via [SSH](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_ssh_protocol) by creating SSH keys, adding the public one to your Git hosted account and making the private one available on the CI environment.
**Note:** SSH keys allow to push the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) associated to the released version. Some plugins might also require an API token. See each plugin documentation for additional information.
## Generating the SSH keys
In your local repository root:
```bash
$ ssh-keygen -t rsa -b 4096 -C "<your_email>" -f git_deploy_key -N "<ssh_passphrase>"
```
`your_email` must be the email associated with your Git hosted account. `ssh_passphrase` must be a long and hard to guess string. It will be used later.
This will generate a public key in `git_deploy_key.pub` and a private key in `git_deploy_key`.
## Adding the SSH public key to the Git hosted account
Step by step instructions are provided for the following Git hosted services:
- [GitHub](#adding-the-ssh-public-key-to-github)
### Adding the SSH public key to GitHub
Open the `git_deploy_key.pub` file (public key) and copy the entire content.
In GitHub **Settings**, click on **SSH and GPG keys** in the sidebar, then on the **New SSH Key** button.
Paste the entire content of `git_deploy_key.pub` file (public key) and click the **Add SSH Key** button.
Delete the `git_deploy_key.pub` file:
```bash
$ rm git_deploy_key.pub
```
See [Adding a new SSH key to your GitHub account](https://help.github.com/articles/adding-a-new-ssh-key-to-your-github-account/) for more details.
## Adding the SSH private key to the CI environment
In order to be available on the CI environment, the SSH private key must be encrypted, committed to the Git repository and decrypted by the CI service.
Step by step instructions are provided for the following environments:
- [Travis CI](#adding-the-ssh-private-key-to-travis-ci)
- [Circle CI](#adding-the-ssh-private-key-to-circle-ci)
### Adding the SSH private key to Travis CI
Install the [Travis CLI](https://github.com/travis-ci/travis.rb#installation):
```bash
$ gem install travis
```
[Login](https://github.com/travis-ci/travis.rb#login) to Travis with the CLI:
```bash
$ travis login
```
Add the [environment](https://github.com/travis-ci/travis.rb#env) variable `SSH_PASSPHRASE` to Travis with the value set during the [SSH keys generation](#generating-the-ssh-keys) step:
```bash
$ travis env set SSH_PASSPHRASE <ssh_passphrase>
```
[Encrypt](https://github.com/travis-ci/travis.rb#encrypt) the `git_deploy_key` (private key) using a symmetric encryption (AES-256), and store the secret in a secure environment variable in the Travis environment:
```bash
$ travis encrypt-file git_deploy_key
```
The `travis encrypt-file` will encrypt the private key into the `git_deploy_key.enc` file and output in the console the command to add to your `.travis.yml` file. It should look like `openssl aes-256-cbc -K $encrypted_KKKKKKKKKKKK_key -iv $encrypted_VVVVVVVVVVVV_iv -in git_deploy_key.enc -out git_deploy_key -d`.
Copy this command to your `.travis.yml` file in the `before_install` step. Change the output path to write the unencrypted key in `/tmp`: `-out git_deploy_key` => `/tmp/git_deploy_key`. This will avoid to commit / modify / delete the unencrypted key by mistake on the CI. Then add the commands to decrypt the ssh private key and make it available to `git`:
```yaml
before_install:
# Decrypt the git_deploy_key.enc key into /tmp/git_deploy_key
- openssl aes-256-cbc -K $encrypted_KKKKKKKKKKKK_key -iv $encrypted_VVVVVVVVVVVV_iv -in git_deploy_key.enc -out /tmp/git_deploy_key -d
# Make sure only the current user can read the private key
- chmod 600 /tmp/git_deploy_key
# Create a script to return the passphrase environment variable to ssh-add
- echo 'echo ${SSH_PASSPHRASE}' > /tmp/askpass && chmod +x /tmp/askpass
# Start the authentication agent
- eval "$(ssh-agent -s)"
# Add the key to the authentication agent
- DISPLAY=":0.0" SSH_ASKPASS="/tmp/askpass" setsid ssh-add /tmp/git_deploy_key </dev/null
```
See [Encrypting Files](https://docs.travis-ci.com/user/encrypting-files) for more details.
Delete the local private key as it won't be used anymore:
```bash
$ rm git_deploy_key
```
Commit the encrypted private key and the `.travis.yml` file to your repository:
```bash
$ git add git_deploy_key.enc .travis.yml
$ git commit -m "ci(travis): Add the encrypted private ssh key"
$ git push
```
### Adding the SSH private key to Circle CI
First we encrypt the `git_deploy_key` (private key) using a symmetric encryption (AES-256). Run the following `openssl` command and *make sure to note the output which we'll need later*:
```bash
$ openssl aes-256-cbc -e -p -in git_deploy_key -out git_deploy_key.enc -K `openssl rand -hex 32` -iv `openssl rand -hex 16`
salt=SSSSSSSSSSSSSSSS
key=KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK
iv =VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV
```
Add the following [environment variables](https://circleci.com/docs/2.0/env-vars/#adding-environment-variables-in-the-app) to Circle CI:
- `SSL_PASSPHRASE` - the value set during the [SSH keys generation](#generating-the-ssh-keys) step.
- `REPO_ENC_KEY` - the `key` (KKK) value from the `openssl` step above.
- `REPO_ENC_IV` - the `iv` (VVV) value from the `openssl` step above.
Then add to your `.circleci/config.yml` the commands to decrypt the ssh private key and make it available to `git`:
```yaml
version: 2
jobs:
coverage_test_publish:
# docker, working_dir, etc
steps:
- run:
# Decrypt the git_deploy_key.enc key into /tmp/git_deploy_key
- openssl aes-256-cbc -d -K $REPO_ENC_KEY -iv $REPO_ENC_IV -in git_deploy_key.enc -out /tmp/git_deploy_key
# Make sure only the current user can read the private key
- chmod 600 /tmp/git_deploy_key
# Create a script to return the passphrase environment variable to ssh-add
- echo 'echo ${SSH_PASSPHRASE}' > /tmp/askpass && chmod +x /tmp/askpass
# Start the authentication agent
- eval "$(ssh-agent -s)"
# Add the key to the authentication agent
- DISPLAY=":0.0" SSH_ASKPASS="/tmp/askpass" setsid ssh-add /tmp/git_deploy_key </dev/null
# checkout, restore_cache, run: yarn install, save_cache, etc.
# Run semantic-release after all the above is set.
```
The unencrypted key is written to `/tmp` to avoid to commit / modify / delete the unencrypted key by mistake on the CI environment.
Delete the local private key as it won't be used anymore:
```bash
$ rm git_deploy_key
```
Commit the encrypted private key and the `.circleci/config.yml` file to your repository:
```bash
$ git add git_deploy_key.enc .circleci/config.yml
$ git commit -m "ci(cicle): Add the encrypted private ssh key"
$ git push
```
+4 -18
View File
@@ -8,11 +8,11 @@ The [Authentication](../usage/ci-configuration.md#authentication) environment va
GitLab CI supports [Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html) allowing to test on multiple Node versions and publishing a release only when all test pass.
**Note**: The publish pipeline must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--8).
**Note**: The publish pipeline must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--83).
### `.gitlab-ci.yml` configuration for Node projects
This example is a minimal configuration for **semantic-release** with a build running Node 4, 6 and 8 on Linux. See [GitLab CI - Configuration of your jobs with .gitlab-ci.yml](https://docs.gitlab.com/ee/ci/yaml/README.html) for additional configuration options.
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [GitLab CI - Configuration of your jobs with .gitlab-ci.yml](https://docs.gitlab.com/ee/ci/yaml/README.html) for additional configuration options.
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
@@ -25,12 +25,6 @@ stages:
before_script:
- npm install
node:4:
image: node:4
stage: test
script:
- npm test
node:6:
image: node:6
stage: test
@@ -47,12 +41,7 @@ publish:
image: node:8
stage: release
script:
# Only for a local semantic-release installation
- npm run semantic-release
# Only for a global semantic-release installation
- npm install -g semantic-release
- semantic-release
- npx semantic-release
```
### `package.json` configuration
@@ -62,10 +51,7 @@ A `package.json` is required only for [local](../usage/installation.md#local-ins
```json
{
"devDependencies": {
"semantic-release": "^12.0.0"
},
"scripts": {
"semantic-release": "semantic-release"
"semantic-release": "^15.0.0"
}
}
```
+94
View File
@@ -1 +1,95 @@
# Using semantic-release with [Travis CI build stages](https://docs.travis-ci.com/user/build-stages)
## Environment variables
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [Travis Repository Settings](https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-Settings) or with the [travis env set CLI](https://github.com/travis-ci/travis.rb#env).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/ci-configuration.md#automatic-setup-with-semantic-release-cli).
## Multiple Node jobs configuration
### `.travis.yml` configuration for multiple Node jobs
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
**Advanced configuration**: Running the tests in the `script` step of the `release` stage is not necessary as the previous stage(s) already ran them. To increase speed, the `script` step of the `release` stage can be overwritten to skip the tests. Note that other commands such as build or compilation might still be required.
```yaml
language: node_js
node_js:
- 8
- 6
jobs:
include:
# Define the release stage that runs semantic-release
- stage: release
node_js: lts/*
# Advanced: optionally overwrite your default `script` step to skip the tests
# script: skip
deploy:
provider: script
skip_cleanup: true
script:
- npx semantic-release
```
### `package.json` configuration for multiple Node jobs
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
"devDependencies": {
"semantic-release": "^15.0.0"
}
}
```
## Non-JavaScript projects configuration
For projects that require to be tested with one or multiple version of a Non-JavaScript [language](https://docs.travis-ci.com/user/languages), optionally on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
This recipe cover the Travis specifics only. See [Non JavaScript projects recipe](../support/FAQ.md#can-i-use-semantic-release-to-publish-non-javascript-packages) for more information on the **semantic-release** configuration.
### `.travis.yml` configuration for non-JavaScript projects
This example is a minimal configuration for **semantic-release** with a build running [Go 1.6 and 1.7](https://docs.travis-ci.com/user/languages/go). See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
**Advanced configuration**: Running the tests in the `script` step of the `release` stage is not necessary as the previous stage(s) already ran them. To increase speed, the `script` step of the `release` stage can be overwritten to skip the tests. Note that other commands such as build or compilation might still be required.
```yaml
language: go
go:
- 1.6
- 1.7
jobs:
include:
# Define the release stage that runs semantic-release
- stage: release
# Advanced: optionally overwrite your default `script` step to skip the tests
# script:
# - make
deploy:
provider: script
skip_cleanup: true
script:
# Use nvm to install and use the Node LTS version (nvm is installed on all Travis images)
- nvm install lts/*
- npx semantic-release
```
+32 -54
View File
@@ -10,31 +10,26 @@ Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with
For projects that require to be tested only with a single [Node version](https://docs.travis-ci.com/user/getting-started/#Selecting-a-different-programming-language) on [one Operating System](https://docs.travis-ci.com/user/getting-started/#Selecting-infrastructure-(optional)).
**Note**: [Node 8 is the minimal version required](../support/FAQ.md#why-does-semantic-release-require-node-version--8).
**Note**: [Node 8 is the minimal version required](../support/FAQ.md#why-does-semantic-release-require-node-version--83).
### `.travis.yml` configuration for single Node job
This example is a minimal configuration for semantic-release with a build running Node 8 on Linux. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
It's recommended to run the `semantic-release` command in the [Travis `script` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error happen the build will fail and Travis will send a notification.
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) semantic-release installation.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
```yaml
language: node_js
node_js: 8
script:
# Run tests
- npm run test
# Only for a local semantic-release installation
- npm run semantic-release
# Only for a global semantic-release installation
- npm install -g semantic-release
- semantic-release
deploy:
provider: script
skip_cleanup: true
script:
- npx semantic-release
```
### `package.json` configuration for single Node job
@@ -45,9 +40,6 @@ A `package.json` is required only for [local](../usage/installation.md#local-ins
{
"devDependencies": {
"semantic-release": "^11.0.0"
},
"scripts": {
"semantic-release": "semantic-release"
}
}
```
@@ -56,17 +48,17 @@ A `package.json` is required only for [local](../usage/installation.md#local-ins
For projects that require to be tested with multiple [Node versions](https://docs.travis-ci.com/user/languages/javascript-with-nodejs/#Specifying-Node.js-versions) and/or on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
**Note**: At least one job must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--8).
**Note**: At least one job must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--83).
### `.travis.yml` configuration for multiple Node jobs
This example is a minimal configuration for **semantic-release** with a build running Node 4, 6 and 8 on Linux and OSX. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example uses [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once) in order to command [Run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
This example uses [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once) in order to [Run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
It's recommended to run the `semantic-release` command in the [Travis `script` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error happen the build will fail and Travis will send a notification.
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../usage/installation.md#local-installation) or [global](../usage/installation.md#global-installation) **semantic-release** installation.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
```yaml
language: node_js
@@ -74,22 +66,12 @@ language: node_js
node_js:
- 8
- 6
- 4
os:
- linux
- osx
script:
# Run tests
- npm run test
# Only for a local semantic-release installation
- npm run travis-deploy-once "npm run semantic-release"
# Only for a global semantic-release installation
- npm install -g travis-deploy-once semantic-release
- travis-deploy-once "semantic-release"
deploy:
provider: script
skip_cleanup: true
script:
- npx travis-deploy-once "npx semantic-release"
```
**Note**: See the `travis-deploy-once` [`pro`](https://github.com/semantic-release/travis-deploy-once#-p---pro) and [`travis-url`](https://github.com/semantic-release/travis-deploy-once#-u---travis-url) options for using with [Travis Pro](https://docs.travis-ci.com/user/travis-pro) and [Travis Enterprise](https://enterprise.travis-ci.com).
@@ -101,12 +83,8 @@ A `package.json` is required only for [local](../usage/installation.md#local-ins
```json
{
"devDependencies": {
"semantic-release": "^12.0.0",
"travis-deploy-once": "^4.0.0"
},
"scripts": {
"semantic-release": "semantic-release",
"travis-deploy-once": "travis-deploy-once"
"semantic-release": "^15.0.0",
"travis-deploy-once": "^5.0.0"
}
}
```
@@ -119,11 +97,13 @@ This recipe cover the Travis specifics only. See [Non JavaScript projects recipe
### `.travis.yml` configuration for non-JavaScript projects
This example is a minimal configuration for semantic-release with a build running [Go 1.6 and 1.7](https://docs.travis-ci.com/user/languages/go) on Linux and OSX. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example is a minimal configuration for **semantic-release** with a build running [Go 1.6 and 1.7](https://docs.travis-ci.com/user/languages/go) on Linux and OSX. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example uses [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once) in order to [run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
It's recommended to run the `semantic-release` command in the [Travis `script` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error happen the build will fail and Travis will send a notification.
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
```yaml
language: go
@@ -136,16 +116,14 @@ os:
- linux
- osx
script:
# Run tests
- go test -v ./...
# Use nvm to install and use the Node LTS version (nvm is installed on Travis images)
- nvm install lts/*
# Install travis-deploy-once and semantic-release
- npm install -g travis-deploy-once semantic-release
# Run semantic-release only on job, after all other are successful
- travis-deploy-once "semantic-release"
deploy:
provider: script
skip_cleanup: true
script:
# Use nvm to install and use the Node LTS version (nvm is installed on all Travis images)
- nvm install lts/*
# Run semantic-release only on one job, after all other are successful
- npx travis-deploy-once "npx semantic-release"
```
**Note**: See the `travis-deploy-once` [`pro`](https://github.com/semantic-release/travis-deploy-once#-p---pro) and [`travis-url`](https://github.com/semantic-release/travis-deploy-once#-u---travis-url) options for using with [Travis Pro](https://docs.travis-ci.com/user/travis-pro) and [Travis Enterprise](https://enterprise.travis-ci.com).
+1
View File
@@ -13,6 +13,7 @@
## Articles
- [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2)
- ["Introduction to Semantic Release" - liv](https://blog.greenkeeper.io/introduction-to-semantic-release-33f73b117c8)
## Tutorials
+79 -5
View File
@@ -35,11 +35,19 @@ Alternatively you can use a [global](../usage/installation.md#global-installatio
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can switch to Node 8 before installing and running the `semantic-release` command:
```bash
$ nvm install 8 && yarn install -g semantic-release && semantic-release
$ nvm install 8 && yarn global add semantic-release && semantic-release
```
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
As `semantic-release` is recommended to be executed with [`npx`](https://www.npmjs.com/package/npx) an alternative is required for usage with Yarn. Even though it is possible to install npx with Yarn, it's not recommended. Yarn and npx would be using different cache locations.
For [local installation](../usage/installation.md#local-installation) replace
`npx semantic-release` with `yarn run semantic-release`.
For [global installation](../usage/installation.md#global-installation) replace
`npx semantic-release` with `yarn global add semantic-release && semantic-release`.
## Can I use semantic-release to publish non-JavaScript packages?
Yes, **semantic-release** is a Node CLI application but it can be used to publish any type of packages.
@@ -49,7 +57,36 @@ To publish a non-Node package (without a `package.json`) you would need to:
- Set **semantic-release** [options](../usage/configuration.md#options) via [CLI arguments or rc file](../usage/configuration.md#configuration)
- Make sure your CI job executing the `semantic-release` command has access to [Node >= 8](#why-does-semantic-release-require-node-version--83) to execute the `semantic-release` command
See the [CI configuration recipes](../usage/ci-configuration.md) for more details on specific CI environments.
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
In addition you will need to configure the **semantic-release** [plugins](../usage/plugins.md#plugins) to:
- Disable the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin
- Define plugins for the [verifyConditions](../usage/plugins.md#verifyconditions-plugin), [prepare](../usage/plugins.md#prepare-plugin) and [publish](../usage/plugins.md#publish-plugin) steps to release on your package registry. The [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin is recommended for situation where a release can be done with a shell command.
Here is a basic example to create [GitHub releases](https://help.github.com/articles/about-releases) and use shell command to publish:
```json
{
"verifyConditions": ["@semantic-release/github"],
"prepare": [
{
"path": "@semantic-release/exec",
"cmd": "set-version ${nextRelease.version}"
}
],
"publish": [
"@semantic-release/github",
{
"path": "@semantic-release/exec",
"cmd": "publish-package"
}
],
}
```
**Note**: This is a theoretical example where the command `set-version` update the project version with the value passed as its first argument and `publish-package` publishes the package to a registry.
See the [package managers and languages recipes](../recipes/README.md#package-managers-and-languages) for more details on specific project types.
## Can I use semantic-release with any CI service?
@@ -57,14 +94,14 @@ Yes, **semantic-release** can be used with any CI service, as long as it provide
- A way to set [authentication](../usage/ci-configuration.md#authentication) via environment variables
- A way to guarantee that the `semantic-release` command is [executed only after all the tests of all the jobs in the CI build pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
See the [CI configuration recipes](../usage/ci-configuration.md) for more details on specific CI environments.
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
## Can I run semantic-release on my local machine rather than on a CI server?
Yes, you can by explicitly setting the [`--no-ci` CLI option](../usage/configuration.md#options) option. You will also have to set the required [authentication](../usage/ci-configuration.md#authentication) via environment variables on your local machine, for example:
```bash
$ NPM_TOKEN=<your_npm_token> GH_TOKEN=<your_github_token> npm run semantic-release --no-ci
$ NPM_TOKEN=<your_npm_token> GH_TOKEN=<your_github_token> npx semantic-release --no-ci
```
However this is not the recommended approach, as running unit and integration tests on an independent machine before publishing software is a crucial part of the release workflow.
@@ -87,6 +124,20 @@ Yes, the publishing to the npm registry can be disabled with the [`npmPublish`](
See the [`@semantic-release/npm`](https://github.com/semantic-release/npm#semantic-releasenpm) plugin documentation for more details.
## How can I revert a release?
If you have introduced a breaking bug in a release you have 2 options:
- If you have a fix immediately ready, commit and push it (or merge it via a pull request) to the release branch
- Otherwise [revert the commit](https://git-scm.com/docs/git-revert) that introduced the bug and push the revert commit (or merge it via a pull request) to the release branch
In both cases **semantic-release** will publish a new release, so your package users' will get the fixed/reverted version.
Depending on the package manager you are using, you might be able to un-publish or deprecate a release, in order to prevent users to download it by accident. For example npm allows you to [un-publish](https://docs.npmjs.com/cli/unpublish) in [next 72 hours](https://www.npmjs.com/policies/unpublish) after releasing or to [deprecate](https://docs.npmjs.com/cli/deprecate) a release.
In any case **do not remove the Git tag associated with the buggy version**, otherwise **semantic-release** will later try to republish that version. Publishing a version after un-publishing is not supported by most package managers.
**Note**: If you are using the default [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines) be aware that it uses a different revert commit format than the standard one created by [git revert](https://git-scm.com/docs/git-revert), contrary to what is [claimed in the convention](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#revert). Therefore, if you revert a commit with [`git revert`](https://git-scm.com/docs/git-revert), use the [`--edit` option](https://git-scm.com/docs/git-revert#git-revert---edit) to format the message according to the [Angular revert commit message format](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#revert). See [conventional-changelog/conventional-changelog#348](https://github.com/conventional-changelog/conventional-changelog/issues/348) for more details.
## Can I use `.npmrc` options?
Yes, all the [npm configuration options](https://docs.npmjs.com/misc/config) are supported via the [`.npmrc`](https://docs.npmjs.com/files/npmrc) file at the root of your repository.
@@ -123,10 +174,25 @@ See [Artifactory - npm Registry](https://www.jfrog.com/confluence/display/RTF/Np
You can trigger a release by pushing to your Git repository. You deliberately cannot trigger a *specific* version release, because this is the whole point of semantic-release.
### Can I exclude commits from the analysis?
## Can I exclude commits from the analysis?
Yes, every commits that contains `[skip release]` or `[release skip]` in their message will be excluded from the commit analysis and won't participate in the release type determination.
## How can I change the type of commits that trigger a release?
By default **semantic-release** uses the [Angular Commit Message Conventions](https://github.com/angular/angular.js/blob/master/DEVELOPERS.md#-git-commit-guidelines) and triggers releases based on the following rules:
| Commit | Release type |
|-----------------------------|----------------------------|
| Commit with breaking change | ~~Major~~ Breaking release |
| Commit with type `feat` | ~~Minor~~ Feature release |
| Commit with type `fix` | Patch release |
| Commit with type `perf` | Patch release |
See the [`@semantic-release/npm`](https://github.com/semantic-release/npm#npm-configuration) plugin documentation for more details.
This is fully customizable with the [`@semantic-release/commit-analyzer`](https://github.com/semantic-release/commit-analyzer) plugin's [`release-rules` option](https://github.com/semantic-release/commit-analyzer#release-rules).
## Is it *really* a good idea to release on every push?
It is indeed a great idea because it *forces* you to follow best practices. If you dont feel comfortable releasing every feature or fix on your `master` you might not treat your `master` branch as intended.
@@ -137,6 +203,8 @@ From [Understanding the GitHub Flow](https://guides.github.com/introduction/flow
If you need more control over the timing of releases, see [Triggering a release](../../README.md#triggering-a-release) for different options.
**Note**: Only the codebase changes altering the published package will trigger a release (for example new features, bug fixes or performance improvements would trigger a release while refactoring or changing code style would not). See [How can I change the type of commits that trigger a release?](#how-can-i-change-the-type-of-commits-that-trigger-a-release) for more details.
## Can I set the initial release version of my package to `0.0.1`?
This is not supported by **semantic-release** as it's not considered a good practice, mostly because [Semantic Versioning](https://semver.org) rules applies differently to major version zero.
@@ -156,3 +224,9 @@ In addition the [verify conditions step](../../README.md#release-steps) verifies
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which **requires Node version 8.3 or higher**.
See [Node version requirement](../support/node-version.md#node-version-requirement) for more details and solutions.
## What is npx?
[`npx`](https://www.npmjs.com/package/npx) short for "npm exec" is a CLI to find and execute npm binaries within the local `node_modules` folder or in the $PATH. If a binary can't be located npx will download the required package and execute it from its cache location.
The tool is bundled with [npm](https://www.npmjs.com/package/npm) >= 5.2, or can be installed via `npm install -g npx`.
For more details and motivation read the [introductory blog post](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) by [@zkat](https://github.com/zkat).
+4 -21
View File
@@ -18,35 +18,18 @@ See [CI configuration](../usage/ci-configuration.md) and [CI configuration recip
### Use `npx`
[`npx`](https://github.com/zkat/npx) is a CLI to execute npm binaries. It is bundled with [npm](https://www.npmjs.com/package/npm) >= 5.4, or can be installed via `npm install -g npx`.
`npx` can be used to download the latest [Node 8 package published on npm](https://www.npmjs.com/package/node) and use it to execute the `semantic-release` command.
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation:
`npx` is included with npm >= 5.2 and can be used to download the latest [Node 8 package published on npm](https://www.npmjs.com/package/node). Use it to execute the `semantic-release` command.
```bash
$ npm install -g npx && npx -p node@8 -c "npm run semantic-release"
$ npx -p node@8 -c "npx semantic-release"
```
If you are using a [global](../usage/installation.md#global-installation) **semantic-release** installation:
```bash
# For global semantic-release install
$ npm install -g semantic-release npx && npx -p node@8 -c "semantic-release"
```
**Note:**: See [What is npx](./FAQ.md#what-is-npx) for more details.
### Use `nvm`
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can use it to switch to Node 8 before running the `semantic-release` command.
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation:
```bash
$ nvm install 8 && npm run semantic-release
```
If you are using a [global](../usage/installation.md#global-installation) **semantic-release** installation:
```bash
$ nvm install 8 && npm install -g semantic-release && semantic-release
$ nvm install 8 && npx semantic-release
```
+25
View File
@@ -29,3 +29,28 @@ You can recover from that issue by identifying the commit in your branch history
$ git tag -f v<version of the last release> <commit sha1 corresponding to last release>
$ git push -f --tags origin <your release branch>
```
## You do not have permission to publish 'package-name'
When running semantic-release you may encounter the following error:
```
An error occurred while running semantic-release: { Error: Command failed: npm publish ./. --registry https://registry.npmjs.org/
npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! You do not have permission to publish "<package-name>". Are you logged in as the correct user? : <package-name>
```
This message is a little unclear, and might not have anything to with your `NPM_TOKEN` or authentication method. It might instead be related to the package name itself. If there is already a package with the same name as yours or, there is a very close match, it could trigger this error.
Best way to be sure, is to search [npmjs.org](https://www.npmjs.com/)) using your package name. If there is a name conflict, rename your package in your `package.json`
## Squashed commits are ignored by **semantic-release**
**semantic-release** parses commits according to a [commit message convention](https://github.com/semantic-release/semantic-release#commit-message-format) to figure out how they affect the codebase. Commits that doesn't follow the project's commit message convention are simply ignored.
When [squashing commits](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#_squashing) most Git tools will by default generate a new commit message with a summary of the squashed commits. This commit message will most likely not be compliant with the project's commit message convention and therefore will be ignored by **semantic-release**.
When squashing commits make sure to rewrite the resulting commit message to be compliant with the project's commit message convention.
**Note**: if the resulting squashed commit would encompasses multiple changes (for example multiple unrelated features or fixes) then it's probably not a good idea to squash those commits together. A commit should contain exactly one self-contained functional change and a functional change should be contained in exactly one commit. See [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit).
+18 -5
View File
@@ -8,22 +8,35 @@ See [CI configuration recipes](../recipes/README.md#ci-configurations) for more
## Authentication
Most **semantic-release** [plugins](plugins.md) require to set up authentication in order to publish to your package manager's registry or to access your project's Git hosted service. The authentication token/credentials have to be made available in the CI serice via environment variables.
**semantic-release** requires push access to the project Git repository in order to create [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). The Git authentication can be set with one of the following environment variables:
See each plugin documentation for the environment variable to set up.
| Variable | Description |
|---------------------------------|-------------------------------------------------------------------------------------------------------------------------------|
| `GH_TOKEN` or `GITHUB_TOKEN` | A GitHub [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line). |
| `GL_TOKEN` or `GITLAB_TOKEN` | A GitLab [personal access token](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html). |
| `BB_TOKEN` or `BITBUCKET_TOKEN` | A Bitbucket [personal access token](https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html). |
| `GIT_CREDENTIALS` | [URL encoded basic HTTP Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication#URL_encoding) credentials). |
The default [npm](https://github.com/semantic-release/npm#environment-variables) and [github](https://github.com/semantic-release/github#environment-variables) plugins require the following environment variables:
`GIT_CREDENTIALS` must be the Git username and password in the format `<username>:<password>`.
Alternatively the Git authentication can be set up via [SSH keys](../recipes/git-auth-ssh-keys.md).
Most **semantic-release** [plugins](plugins.md) require setting up authentication in order to publish to a package manager registry. The default [@semantic-release/npm](https://github.com/semantic-release/npm#environment-variables) and [@semantic-release/github](https://github.com/semantic-release/github#environment-variables) plugins require the following environment variables:
| Variable | Description |
|-------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `NPM_TOKEN` | npm token created via [npm token create](https://docs.npmjs.com/getting-started/working_with_tokens#how-to-create-new-tokens).<br/>**Note**: Only the `auth-only` [level of npm two-factor authentication](https://docs.npmjs.com/getting-started/using-two-factor-authentication#levels-of-authentication) is supported. |
| `GH_TOKEN` | GitHub authentication token.<br/>**Note**: Only the [personal token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line) authentication is supported. |
See each plugin documentation for the environment variables to set up.
The authentication token/credentials have to be made available in the CI service via environment variables.
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on how to configure environment variables in your CI service.
## Automatic setup with `semantic-release-cli`
[`semantic-release-cli`](https://github.com/semantic-release/cli) allow to easily [install](installation.md) **semantic-release** in your Node project and set up the CI configuration:
[`semantic-release-cli`](https://github.com/semantic-release/cli) allows for easy [installation](installation.md) of **semantic-release** in your Node project as well as setting up the CI configuration:
```bash
npm install -g semantic-release-cli
@@ -32,6 +45,6 @@ cd your-module
semantic-release-cli setup
```
![dialogue](media/semantic-release-cli.png)
![dialogue](../../media/semantic-release-cli.png)
See the [semantic-release-cli](https://github.com/semantic-release/cli#what-it-does) documentation for more details.
+82 -24
View File
@@ -6,7 +6,7 @@ In order to customize **semantic-release**s behavior, [options](#options) and
- A `release` key in the project's `package.json` file
- CLI arguments
The following two examples are the same.
The following three examples are the same.
Via CLI argument:
@@ -17,7 +17,20 @@ $ semantic-release --branch next
Via `release` key in the project's `package.json` file:
```json
"release": {
{
"release": {
"branch": "next"
}
}
```
```bash
$ semantic-release
```
Via `.releaserc` file:
```json
{
"branch": "next"
}
```
@@ -27,7 +40,18 @@ $ semantic-release
**Note**: CLI arguments take precedence over options configured in the configuration file.
**Note**: Plugins options cannot be defined via CLI arguments and must be defined in the configuration file.
**Note**: Plugin options cannot be defined via CLI arguments and must be defined in the configuration file.
**Note**: When configuring via `package.json`, the configuration must be under the `release` property. However, when using a `.releaserc` or a `release.config.js` file, the configuration must be set without a `release` property.
## Environment variables
| Variable | Description | Default |
|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------|
| `GIT_AUTHOR_NAME` | The author name associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot. |
| `GIT_AUTHOR_EMAIL` | The author email associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot email address. |
| `GIT_COMMITTER_NAME` | The committer name associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot. |
| `GIT_COMMITTER_EMAIL` | The committer email associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot email address. |
## Options
@@ -37,7 +61,7 @@ Type: `Array`, `String`
CLI arguments: `-e`, `--extends`
List of modules or file paths containing a [shareable configuration](shareable-configurations.md). If multiple shareable configuration are set, they will be imported in the order defined with each configuration option taking precedence over the options defined in a previous shareable configuration.
List of modules or file paths containing a [shareable configuration](shareable-configurations.md). If multiple shareable configurations are set, they will be imported in the order defined with each configuration option taking precedence over the options defined in a previous shareable configuration.
**Note**: Options defined via CLI arguments or in the configuration file will take precedence over the ones defined in any shareable configuration.
@@ -59,17 +83,27 @@ Default: `repository` property in `package.json` or [git origin url](https://git
CLI arguments: `-r`, `--repository-url`
The git repository URL
The git repository URL.
Any valid git url format is supported (See [Git protocols](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols)).
**Note**: If the [Github plugin](https://github.com/semantic-release/github) is used the URL must be a valid Github URL that include the `owner`, the `repository` name and the `host`. **The Github shorthand URL is not supported.**
### tagFormat
Type: `String`
Default: `v${version}`
CLI arguments: `-t`, `--tag-format`
The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) format used by **semantic-release** to identify releases. The tag name is generated with [Lodash template](https://lodash.com/docs#template) and will be compiled with the `version` variable.
**Note**: The `tagFormat` must contain the `version` variable exactly once and compile to a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description).
### dryRun
Type: `Boolean`
Default: `false` if running in a CI environment, `false` otherwise
Default: `false` if running in a CI environment, `true` otherwise
CLI arguments: `-d`, `--dry-run`
@@ -83,7 +117,7 @@ Default: `false`
CLI arguments: `--no-ci`
Skip Continuous Integration environment verifications, allowing to make releases from a local machine.
Skip Continuous Integration environment verifications. This allows for making releases from a local machine.
### debug
@@ -93,7 +127,7 @@ Default: `false`
CLI argument: `--debug`
Output debugging information. It can also be enabled by set the `DEBUG` environment variable to `semantic-release`.
Output debugging information. It can also be enabled by setting the `DEBUG` environment variable to `semantic-release:*`.
### verifyConditions
@@ -107,23 +141,11 @@ Define the list of [verify conditions plugins](plugins.md#verifyconditions-plugi
See [Plugins configuration](plugins.md#configuration) for more details.
### getLastRelease
Type: `String`, `Object`
Default: `['@semantic-release/npm']`
CLI argument: `--get-last-release`
Define the [get last release plugin](plugins.md#getlastrelease-plugin).
See [Plugins configuration](plugins.md#configuration) for more details.
### analyzeCommits
Type: `String`, `Object`
Default: `['@semantic-release/commit-analyzer']`
Default: `'@semantic-release/commit-analyzer'`
CLI argument: `--analyze-commits`
@@ -145,13 +167,25 @@ See [Plugins configuration](plugins.md#configuration) for more details.
### generateNotes
Type: `String`, `Object`
Type: `Array`, `String`, `Object`
Default: `['@semantic-release/release-notes-generator']`
CLI argument: `--generate-notes`
Define the [generate notes plugin](plugins.md#generatenotes-plugin).
Define the [generate notes plugins](plugins.md#generatenotes-plugin).
See [Plugins configuration](plugins.md#configuration) for more details.
### prepare
Type: `Array`, `String`, `Object`
Default: `['@semantic-release/npm']`
CLI argument: `--prepare`
Define the list of [prepare plugins](plugins.md#prepare-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
@@ -166,3 +200,27 @@ CLI argument: `--publish`
Define the list of [publish plugins](plugins.md#publish-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
### success
Type: `Array`, `String`, `Object`
Default: `['@semantic-release/github']`
CLI argument: `--success`
Define the list of [success plugins](plugins.md#success-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
### fail
Type: `Array`, `String`, `Object`
Default: `['@semantic-release/github']`
CLI argument: `--fail`
Define the list of [fail plugins](plugins.md#fail-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
+10 -14
View File
@@ -2,32 +2,28 @@
## Local installation
For [Node modules projects](https://docs.npmjs.com/getting-started/creating-node-modules) we recommend to install **semantic-release** locally and to run the `semantic-release` command with a [npm script](https://docs.npmjs.com/misc/scripts):
For [Node modules projects](https://docs.npmjs.com/getting-started/creating-node-modules) we recommend installing **semantic-release** locally and running the `semantic-release` command with [npx](https://www.npmjs.com/package/npx):
```bash
$ npm install --save-dev semantic-release
```
In your `package.json`:
```json
"scripts": {
"semantic-release": "semantic-release"
}
```
Then in the CI environment:
```bash
$ npm run semantic-release
$ npx semantic-release
```
**Note:** `npx` is a tool bundled with `npm@>=5.2.0`. It is used to conveniently find the semantic-release binary and to execute it. See [What is npx](../support/FAQ.md#what-is-npx) for more details.
## Global installation
For other type of projects we recommend to install **semantic-release** globally directly in the CI environment:
For other type of projects we recommend installing **semantic-release** directly in the CI environment, also with [npx](https://www.npmjs.com/package/npx):
```bash
$ npm install -g semantic-release
$ semantic-release
$ npx semantic-release
```
**Note:**: For a global installation, it's recommended to specify the major **semantic-release** version to install (for example with with `npm install -g semantic-release@12`). This way your build will not automatically use the next major **semantic-release** release that could possibly break your build. You will have to upgrade manually when a new major version is released.
**Note:** For a global installation, it's recommended to specify the major **semantic-release** version to install (for example with with `npx semantic-release@15`, or `npm install -g semantic-release@15`). This way your build will not automatically use the next major **semantic-release** release that could possibly break your build. You will have to upgrade manually when a new major version is released.
**Note:** `npx` is a tool bundled with `npm@>=5.2.0`. It is used to conveniently install the semantic-release binary and to execute it. See [What is npx](../support/FAQ.md#what-is-npx) for more details.
+32 -16
View File
@@ -1,50 +1,66 @@
# Plugins
Each [release steps](../../README.md#release-steps) is implemented within a plugin or a list of plugins that can be configured, allowing to support different [commit message format](../../README.md#commit-message-format), release not generator and publishing platforms.
Each [release step](../../README.md#release-steps) is implemented within a plugin or a list of plugins that can be configured. This allows for support of different [commit message formats](../../README.md#commit-message-format), release note generators and publishing platforms.
See [plugins list](../extending/plugins-list.md).
## Plugin types
### verifyConditions plugin
Plugin responsible for verifying all the conditions to proceed with the release: configuration is correct, authentication token are valid, etc...
Responsible for verifying conditions necessary to proceed with the release: configuration is correct, authentication token are valid, etc...
Default implementation: [npm](https://github.com/semantic-release/npm#verifyconditions) and [github](https://github.com/semantic-release/github#verifyconditions).
### getLastRelease plugin
Plugin responsible for determining the version of the package last release.
Default implementation: [@semantic-release/npm](https://github.com/semantic-release/npm#getlastrelease).
Default implementation: [@semantic-release/npm](https://github.com/semantic-release/npm#verifyconditions) and [@semantic-release/github](https://github.com/semantic-release/github#verifyconditions).
### analyzeCommits plugin
Plugin responsible for determining the type of the next release (`major`, `minor` or `patch`).
Responsible for determining the type of the next release (`major`, `minor` or `patch`).
Default implementation: [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer).
### verifyRelease plugin
Plugin responsible for verifying the parameters (version, type, dist-tag etc...) of the release that is about to be published match certain expectations. For example the [cracks plugin](https://github.com/semantic-release/cracks) allows to verify that if a release contains breaking changes, its type must be `major`.
Responsible for verifying the parameters (version, type, dist-tag etc...) of the release that is about to be published. For example the [cracks plugin](https://github.com/semantic-release/cracks) is able to verify that if a release contains breaking changes, its type must be `major`.
Default implementation: none.
### generateNotes plugin
Plugin responsible for generating release notes.
Responsible for generating release notes. If multiple `generateNotes` plugins are defined, the release notes will be the result of the concatenation of plugin output.
Default implementation: [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator).
### prepare plugin
Responsible for preparing the release, including:
- Creating or updating files such as `package.json`, `CHANGELOG.md`, documentation or compiled assets.
- Create and push commits
Default implementation: [@semantic-release/npm](https://github.com/semantic-release/npm#prepare).
### publish plugin
Plugin responsible for publishing the release.
Responsible for publishing the release.
Default implementation: [npm](https://github.com/semantic-release/npm#publish) and [github](https://github.com/semantic-release/github#publish).
Default implementation: [@semantic-release/npm](https://github.com/semantic-release/npm#publish) and [@semantic-release/github](https://github.com/semantic-release/github#publish).
### success plugin
Responsible for notifying of a new release.
Default implementation: [@semantic-release/github](https://github.com/semantic-release/github#success).
### fail plugin
Responsible for notifying of a failed release.
Default implementation: [@semantic-release/github](https://github.com/semantic-release/github#fail).
## Configuration
Plugin can be configured by specifying the plugin's module name or file path directly as a `String` or within the `path` key of an `Object`.
Plugins specific options can be set similarly to the other **semantic-release** [options](configuration.md#options) or within the plugin `Object`. Plugins options defined along the other **semantic-release** [options](configuration.md#options) will apply to all plugins, while the one defined within the plugin `Object` will apply only to this specific plugin.
Plugins specific options can be set similarly to the other **semantic-release** [options](configuration.md#options) or within the plugin `Object`. Plugins options defined along with the other **semantic-release** [options](configuration.md#options) will apply to all plugins. Options defined within the plugin `Object` will apply to that specific plugin.
For example:
```json
@@ -75,7 +91,7 @@ For example:
With this configuration:
- the `custom-plugin` npm module will be used to [analyze commits](#analyzecommits-plugin)
- the `./build/my-plugin.js` script will be used to [generate release notes](#generatenotes-plugin)
- the [`@semantic-release/exec`](https://github.com/semantic-release/exec), [`@semantic-release/npm`](https://github.com/semantic-release/npm) and [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugins will be used to [verify conditions](#verifyconditions-plugin)
- the [`@semantic-release/exec`](https://github.com/semantic-release/exec), [`@semantic-release/npm`](https://github.com/semantic-release/npm) and [`@semantic-release/github`](https://github.com/semantic-release/github) plugins will be used to [verify conditions](#verifyconditions-plugin)
- the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin will be used to [verify the release](#verifyrelease-plugin)
- the `cmd` option will be set to `verify-conditions.sh` only for the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin used to [verify conditions](#verifyconditions-plugin)
- the `cmd` option will be set to `verify-release.sh` only for the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin used to [verify the release](#verifyrelease-plugin)
+3 -1
View File
@@ -1,5 +1,7 @@
# Shareable configurations
A sharable configuration is an [npm](https://www.npmjs.com/) package that exports a **semantic-release** configuration object. It allows to easily use the same configuration across several projects.
A sharable configuration is an [npm](https://www.npmjs.com/) package that exports a **semantic-release** configuration object. It allows for use of the same configuration across several projects.
The shareable configurations to use can be set with the [extends](configuration.md#extends) option.
See [shareable configurations list](../extending/shareable-configurations-list.md).
+114 -47
View File
@@ -1,97 +1,164 @@
const {template} = require('lodash');
const marked = require('marked');
const TerminalRenderer = require('marked-terminal');
const envCi = require('env-ci');
const hookStd = require('hook-std');
const pkg = require('./package.json');
const hideSensitive = require('./lib/hide-sensitive');
const getConfig = require('./lib/get-config');
const verify = require('./lib/verify');
const getNextVersion = require('./lib/get-next-version');
const getCommits = require('./lib/get-commits');
const getLastRelease = require('./lib/get-last-release');
const {extractErrors} = require('./lib/utils');
const getGitAuthUrl = require('./lib/get-git-auth-url');
const logger = require('./lib/logger');
const {gitHead: getGitHead, isGitRepo} = require('./lib/git');
const {fetch, verifyAuth, isBranchUpToDate, gitHead: getGitHead, tag, push} = require('./lib/git');
const getError = require('./lib/get-error');
const {COMMIT_NAME, COMMIT_EMAIL} = require('./lib/definitions/constants');
module.exports = async opts => {
marked.setOptions({renderer: new TerminalRenderer()});
async function run(options, plugins) {
const {isCi, branch, isPr} = envCi();
if (!isCi && !opts.dryRun && !opts.noCi) {
if (!isCi && !options.dryRun && !options.noCi) {
logger.log('This run was not triggered in a known CI environment, running in dry-run mode.');
opts.dryRun = true;
options.dryRun = true;
} else {
// When running on CI, set the commits author and commiter info and prevent the `git` CLI to prompt for username/password. See #703.
process.env = {
GIT_AUTHOR_NAME: COMMIT_NAME,
GIT_AUTHOR_EMAIL: COMMIT_EMAIL,
GIT_COMMITTER_NAME: COMMIT_NAME,
GIT_COMMITTER_EMAIL: COMMIT_EMAIL,
...process.env,
GIT_ASKPASS: 'echo',
GIT_TERMINAL_PROMPT: 0,
};
}
if (isCi && isPr && !opts.noCi) {
if (isCi && isPr && !options.noCi) {
logger.log("This run was triggered by a pull request and therefore a new version won't be published.");
return;
}
if (!await isGitRepo()) {
logger.error('Semantic-release must run from a git repository.');
return;
}
const config = await getConfig(opts, logger);
const {plugins, options} = config;
if (branch !== options.branch) {
logger.log(
`This test run was triggered on the branch ${branch}, while semantic-release is configured to only publish from ${
options.branch
}, therefore a new version wont be published.`
);
return;
return false;
}
await verify(options);
options.repositoryUrl = await getGitAuthUrl(options);
try {
await verifyAuth(options.repositoryUrl, options.branch);
} catch (err) {
if (!(await isBranchUpToDate(options.branch))) {
logger.log(
"The local branch %s is behind the remote one, therefore a new version won't be published.",
options.branch
);
return false;
}
logger.error(`The command "${err.cmd}" failed with the error message %s.`, err.stderr);
throw getError('EGITNOPERMISSION', {options});
}
logger.log('Run automated release from branch %s', options.branch);
logger.log('Call plugin %s', 'verify-conditions');
await plugins.verifyConditions({options, logger});
logger.log('Call plugin %s', 'get-last-release');
const {commits, lastRelease} = await getCommits(
await plugins.getLastRelease({options, logger}),
options.branch,
logger
);
await fetch(options.repositoryUrl);
logger.log('Call plugin %s', 'analyze-commits');
const type = await plugins.analyzeCommits({
options,
logger,
lastRelease,
commits: commits.filter(commit => !/\[skip\s+release\]|\[release\s+skip\]/i.test(commit.message)),
});
const lastRelease = await getLastRelease(options.tagFormat, logger);
const commits = await getCommits(lastRelease.gitHead, options.branch, logger);
const type = await plugins.analyzeCommits({options, logger, lastRelease, commits});
if (!type) {
logger.log('There are no relevant changes, so no new version is released.');
return;
}
const version = getNextVersion(type, lastRelease, logger);
const nextRelease = {type, version, gitHead: await getGitHead(), gitTag: `v${version}`};
const nextRelease = {type, version, gitHead: await getGitHead(), gitTag: template(options.tagFormat)({version})};
logger.log('Call plugin %s', 'verify-release');
await plugins.verifyRelease({options, logger, lastRelease, commits, nextRelease});
const generateNotesParam = {options, logger, lastRelease, commits, nextRelease};
if (options.dryRun) {
logger.log('Call plugin %s', 'generate-notes');
const notes = await plugins.generateNotes(generateNotesParam);
marked.setOptions({renderer: new TerminalRenderer()});
logger.log('Release note for version %s:\n', nextRelease.version);
process.stdout.write(`${marked(notes)}\n`);
if (notes) {
process.stdout.write(`${marked(notes)}\n`);
}
} else {
logger.log('Call plugin %s', 'generateNotes');
nextRelease.notes = await plugins.generateNotes(generateNotesParam);
await plugins.prepare({options, logger, lastRelease, commits, nextRelease});
// Create the tag before calling the publish plugins as some require the tag to exists
logger.log('Create tag %s', nextRelease.gitTag);
await tag(nextRelease.gitTag);
await push(options.repositoryUrl, branch);
const releases = await plugins.publish({options, logger, lastRelease, commits, nextRelease});
await plugins.success({options, logger, lastRelease, commits, nextRelease, releases});
logger.log('Call plugin %s', 'publish');
await plugins.publish({options, logger, lastRelease, commits, nextRelease}, async prevInput => {
const newGitHead = await getGitHead();
// If previous publish plugin has created a commit (gitHead changed)
if (prevInput.nextRelease.gitHead !== newGitHead) {
nextRelease.gitHead = newGitHead;
// Regenerate the release notes
logger.log('Call plugin %s', 'generateNotes');
nextRelease.notes = await plugins.generateNotes(generateNotesParam);
}
// Call the next publish plugin with the updated `nextRelease`
return {options, logger, lastRelease, commits, nextRelease};
});
logger.log('Published release: %s', nextRelease.version);
}
return true;
}
function logErrors(err) {
const errors = extractErrors(err).sort(error => (error.semanticRelease ? -1 : 0));
for (const error of errors) {
if (error.semanticRelease) {
logger.log(`%s ${error.message}`, error.code);
if (error.details) {
process.stdout.write(`${marked(error.details)}\n`);
}
} else {
logger.error('An error occurred while running semantic-release: %O', error);
}
}
}
async function callFail(plugins, options, error) {
const errors = extractErrors(error).filter(error => error.semanticRelease);
if (errors.length > 0) {
try {
await plugins.fail({options, logger, errors});
} catch (err) {
logErrors(err);
}
}
}
module.exports = async opts => {
logger.log(`Running %s version %s`, pkg.name, pkg.version);
const {unhook} = hookStd({silent: false}, hideSensitive);
try {
const config = await getConfig(opts, logger);
const {plugins, options} = config;
try {
const result = await run(options, plugins);
unhook();
return result;
} catch (err) {
if (!options.dryRun) {
await callFail(plugins, options, err);
}
throw err;
}
} catch (err) {
logErrors(err);
unhook();
throw err;
}
};
-9
View File
@@ -1,9 +0,0 @@
function debugShell(message, shell, debug) {
debug(message);
debug('cmd: %O', shell.cmd);
debug('stdout: %O', shell.stdout);
debug('stderr: %O', shell.stderr);
debug('code: %O', shell.code);
}
module.exports = {debugShell};
+11
View File
@@ -0,0 +1,11 @@
const RELEASE_TYPE = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'];
const FIRST_RELEASE = '1.0.0';
const COMMIT_NAME = 'semantic-release-bot';
const COMMIT_EMAIL = 'semantic-release-bot@martynus.net';
const RELEASE_NOTES_SEPARATOR = '\n\n';
module.exports = {RELEASE_TYPE, FIRST_RELEASE, COMMIT_NAME, COMMIT_EMAIL, RELEASE_NOTES_SEPARATOR};
+120
View File
@@ -0,0 +1,120 @@
const url = require('url');
const {inspect} = require('util');
const {toLower, isString} = require('lodash');
const pkg = require('../../package.json');
const {RELEASE_TYPE} = require('./constants');
const homepage = url.format({...url.parse(pkg.homepage), hash: null});
const stringify = obj => (isString(obj) ? obj : inspect(obj, {breakLength: Infinity, depth: 2, maxArrayLength: 5}));
const linkify = file => `${homepage}/blob/caribou/${file}`;
module.exports = {
ENOGITREPO: () => ({
message: 'Not running from a git repository.',
details: `The \`semantic-release\` command must be executed from a Git repository.
The current working directory is \`${process.cwd()}\`.
Please verify your CI configuration to make sure the \`semantic-release\` command is executed from the root of the cloned repository.`,
}),
ENOREPOURL: () => ({
message: 'The `repositoryUrl` option is required.',
details: `The [repositoryUrl option](${linkify(
'docs/usage/configuration.md#repositoryurl'
)}) cannot be determined from the semantic-release configuration, the \`package.json\` nor the [git origin url](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes).
Please make sure to add the \`repositoryUrl\` to the [semantic-release configuration] (${linkify(
'docs/usage/configuration.md'
)}).`,
}),
EGITNOPERMISSION: ({options}) => ({
message: 'The push permission to the Git repository is required.',
details: `**semantic-release** cannot push the version tag to the branch \`${
options.branch
}\` on remote Git repository with URL \`${options.repositoryUrl}\`.
Please refer to the [authentication configuration documentation](${linkify(
'docs/usage/ci-configuration.md#authentication'
)}) to configure the Git credentials on your CI environment and make sure the [repositoryUrl](${linkify(
'docs/usage/configuration.md#repositoryurl'
)}) is configured with a [valid Git URL](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols).`,
}),
EINVALIDTAGFORMAT: ({tagFormat}) => ({
message: 'Invalid `tagFormat` option.',
details: `The [tagFormat](${linkify(
'docs/usage/configuration.md#tagformat'
)}) must compile to a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description).
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
}),
ETAGNOVERSION: ({tagFormat}) => ({
message: 'Invalid `tagFormat` option.',
details: `The [tagFormat](${linkify(
'docs/usage/configuration.md#tagformat'
)}) option must contain the variable \`version\` exactly once.
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
}),
EPLUGINCONF: ({type, pluginConf}) => ({
message: `The \`${type}\` plugin configuration is invalid.`,
details: `The [${type} plugin configuration](${linkify(
`docs/usage/plugins.md#${toLower(type)}-plugin`
)}) if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a \`path\` property.
Your configuration for the \`${type}\` plugin is \`${stringify(pluginConf)}\`.`,
}),
EPLUGIN: ({pluginName, type}) => ({
message: `A plugin configured in the step ${type} is not a valid semantic-release plugin.`,
details: `A valid \`${type}\` **semantic-release** plugin must be a function or an object with a function in the property \`${type}\`.
The plugin \`${pluginName}\` doesn't have the property \`${type}\` and cannot be used for the \`${type}\` step.
Please refer to the \`${pluginName}\` and [semantic-release plugins configuration](${linkify(
'docs/usage/plugins.md'
)}) documentation for more details.`,
}),
EANALYZECOMMITSOUTPUT: ({result, pluginName}) => ({
message: 'The `analyzeCommits` plugin returned an invalid value. It must return a valid semver release type.',
details: `The \`analyzeCommits\` plugin must return a valid [semver](https://semver.org) release type. The valid values are: ${RELEASE_TYPE.map(
type => `\`${type}\``
).join(', ')}.
The \`analyzeCommits\` function of the \`${pluginName}\` returned \`${stringify(result)}\` instead.
We recommend to report the issue to the \`${pluginName}\` authors, providing the following informations:
- The **semantic-release** version: \`${pkg.version}\`
- The **semantic-release** logs from your CI job
- The value returned by the plugin: \`${stringify(result)}\`
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
'docs/developer-guide/plugin.md'
)})`,
}),
EGENERATENOTESOUTPUT: ({result, pluginName}) => ({
message: 'The `generateNotes` plugin returned an invalid value. It must return a `String`.',
details: `The \`generateNotes\` plugin must return a \`String\`.
The \`generateNotes\` function of the \`${pluginName}\` returned \`${stringify(result)}\` instead.
We recommend to report the issue to the \`${pluginName}\` authors, providing the following informations:
- The **semantic-release** version: \`${pkg.version}\`
- The **semantic-release** logs from your CI job
- The value returned by the plugin: \`${stringify(result)}\`
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
'docs/developer-guide/plugin.md'
)})`,
}),
EPUBLISHOUTPUT: ({result, pluginName}) => ({
message: 'A `publish` plugin returned an invalid value. It must return an `Object`.',
details: `The \`publish\` plugins must return an \`Object\`.
The \`publish\` function of the \`${pluginName}\` returned \`${stringify(result)}\` instead.
We recommend to report the issue to the \`${pluginName}\` authors, providing the following informations:
- The **semantic-release** version: \`${pkg.version}\`
- The **semantic-release** logs from your CI job
- The value returned by the plugin: \`${stringify(result)}\`
- A link to the **semantic-release** plugin developer guide: [${linkify('docs/developer-guide/plugin.md')}](${linkify(
'docs/developer-guide/plugin.md'
)})`,
}),
};
+84
View File
@@ -0,0 +1,84 @@
const {isString, isFunction, isArray, isPlainObject} = require('lodash');
const {gitHead} = require('../git');
const {RELEASE_TYPE, RELEASE_NOTES_SEPARATOR} = require('./constants');
const validatePluginConfig = conf => isString(conf) || isString(conf.path) || isFunction(conf);
module.exports = {
verifyConditions: {
default: ['@semantic-release/npm', '@semantic-release/github'],
configValidator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
pipelineConfig: () => ({settleAll: true}),
},
analyzeCommits: {
default: '@semantic-release/commit-analyzer',
configValidator: conf => Boolean(conf) && validatePluginConfig(conf),
outputValidator: output => !output || RELEASE_TYPE.includes(output),
preprocess: ({commits, ...inputs}) => ({
...inputs,
commits: commits.filter(commit => !/\[skip\s+release\]|\[release\s+skip\]/i.test(commit.message)),
}),
postprocess: ([result]) => result,
},
verifyRelease: {
default: false,
configValidator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
pipelineConfig: () => ({settleAll: true}),
},
generateNotes: {
default: ['@semantic-release/release-notes-generator'],
configValidator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
outputValidator: output => !output || isString(output),
pipelineConfig: () => ({
getNextInput: ({nextRelease, ...generateNotesParam}, notes) => ({
...generateNotesParam,
nextRelease: {
...nextRelease,
notes: `${nextRelease.notes ? `${nextRelease.notes}${RELEASE_NOTES_SEPARATOR}` : ''}${notes}`,
},
}),
}),
postprocess: results => results.filter(Boolean).join(RELEASE_NOTES_SEPARATOR),
},
prepare: {
default: ['@semantic-release/npm'],
configValidator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
pipelineConfig: ({generateNotes}, logger) => ({
getNextInput: async ({nextRelease, ...prepareParam}) => {
const newGitHead = await gitHead();
// If previous prepare plugin has created a commit (gitHead changed)
if (nextRelease.gitHead !== newGitHead) {
nextRelease.gitHead = newGitHead;
// Regenerate the release notes
logger.log('Call plugin %s', 'generateNotes');
nextRelease.notes = await generateNotes({nextRelease, ...prepareParam});
}
// Call the next publish plugin with the updated `nextRelease`
return {...prepareParam, nextRelease};
},
}),
},
publish: {
default: ['@semantic-release/npm', '@semantic-release/github'],
configValidator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
outputValidator: output => !output || isPlainObject(output),
pipelineConfig: () => ({
// Add `nextRelease` and plugin properties to published release
transform: (release, step, {nextRelease}) => ({
...(isPlainObject(release) ? release : {}),
...nextRelease,
...step,
}),
}),
},
success: {
default: ['@semantic-release/github'],
configValidator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
pipelineConfig: () => ({settleAll: true}),
},
fail: {
default: ['@semantic-release/github'],
configValidator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
pipelineConfig: () => ({settleAll: true}),
},
};
+6 -71
View File
@@ -1,75 +1,21 @@
const gitLogParser = require('git-log-parser');
const getStream = require('get-stream');
const debug = require('debug')('semantic-release:get-commits');
const SemanticReleaseError = require('@semantic-release/error');
const {unshallow, gitCommitTag, gitTagHead, isCommitInHistory} = require('./git');
/**
* Commit message.
* Retrieve the list of commits on the current branch since the commit sha associated with the last release, or all the commits of the current branch if there is no last released version.
*
* @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.
* @property {string} [gitTag] The tag 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 {String} gitHead The commit sha associated with the last release.
* @param {String} branch The branch to release from.
* @param {Object} logger Global logger.
*
* @return {Promise<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`.
* @return {Promise<Array<Object>>} The list of commits on the branch `branch` since the last release.
*/
module.exports = async ({version, gitHead} = {}, branch, logger) => {
module.exports = async (gitHead, branch, logger) => {
if (gitHead) {
// If gitHead doesn't exists in release branch
if (!await isCommitInHistory(gitHead)) {
// Unshallow the repository
await unshallow();
}
// If gitHead still doesn't exists in release branch
if (!await isCommitInHistory(gitHead)) {
// Try to find the commit corresponding to the version, using got tags
const tagHead = (await gitTagHead(`v${version}`)) || (await gitTagHead(version));
// If tagHead doesn't exists in release branch
if (!tagHead || !await isCommitInHistory(tagHead)) {
// Then the commit corresponding to the version cannot be found in the bracnh hsitory
logger.error(notInHistoryMessage(gitHead, branch, version));
throw new SemanticReleaseError('Commit not in history', 'ENOTINHISTORY');
}
gitHead = tagHead;
}
debug('Use gitHead: %s', gitHead);
} 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
await unshallow();
}
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
@@ -82,16 +28,5 @@ module.exports = async ({version, gitHead} = {}, branch, logger) => {
);
logger.log('Found %s commits since last release', commits.length);
debug('Parsed commits: %o', commits);
return {commits, lastRelease: {version, gitHead, gitTag: await gitCommitTag(gitHead)}};
return commits;
};
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}
`;
}
+21 -22
View File
@@ -1,15 +1,25 @@
const readPkgUp = require('read-pkg-up');
const {castArray, pickBy, isUndefined, isNull, isString, isPlainObject} = require('lodash');
const readPkgUp = require('read-pkg-up');
const cosmiconfig = require('cosmiconfig');
const resolveFrom = require('resolve-from');
const SemanticReleaseError = require('@semantic-release/error');
const debug = require('debug')('semantic-release:config');
const {repoUrl} = require('./git');
const PLUGINS_DEFINITION = require('./plugins/definitions');
const PLUGINS_DEFINITIONS = require('./definitions/plugins');
const plugins = require('./plugins');
const CONFIG_NAME = 'release';
const CONFIG_FILES = [
'package.json',
`.${CONFIG_NAME}rc`,
`.${CONFIG_NAME}rc.json`,
`.${CONFIG_NAME}rc.yaml`,
`.${CONFIG_NAME}rc.yml`,
`.${CONFIG_NAME}rc.js`,
`${CONFIG_NAME}.config.js`,
];
module.exports = async (opts, logger) => {
const {config} = (await cosmiconfig('release', {rcExtensions: true}).load(process.cwd())) || {};
const {config} = (await cosmiconfig(CONFIG_NAME, {searchPlaces: CONFIG_FILES}).search()) || {};
// Merge config file options and CLI/API options
let options = {...config, ...opts};
const pluginsPath = {};
@@ -24,9 +34,9 @@ module.exports = async (opts, logger) => {
// For each plugin defined in a shareable config, save in `pluginsPath` the extendable config path,
// so those plugin will be loaded relatively to the config file
Object.keys(extendsOpts).reduce((pluginsPath, option) => {
if (PLUGINS_DEFINITION[option]) {
castArray(extendsOpts[option])
Object.entries(extendsOpts).reduce((pluginsPath, [option, value]) => {
if (PLUGINS_DEFINITIONS[option]) {
castArray(value)
.filter(plugin => isString(plugin) || (isPlainObject(plugin) && isString(plugin.path)))
.map(plugin => (isString(plugin) ? plugin : plugin.path))
.forEach(plugin => {
@@ -46,28 +56,17 @@ module.exports = async (opts, logger) => {
options = {
branch: 'master',
repositoryUrl: (await pkgRepoUrl()) || (await repoUrl()),
tagFormat: `v\${version}`,
// Remove `null` and `undefined` options so they can be replaced with default ones
...pickBy(options, option => !isUndefined(option) && !isNull(option)),
};
debug('options values: %O', Object.keys(options));
debug('name: %O', options.name);
debug('branch: %O', options.branch);
debug('repositoryUrl: %O', options.repositoryUrl);
debug('analyzeCommits: %O', options.analyzeCommits);
debug('generateNotes: %O', options.generateNotes);
debug('verifyConditions: %O', options.verifyConditions);
debug('verifyRelease: %O', options.verifyRelease);
debug('publish: %O', options.publish);
if (!options.repositoryUrl) {
throw new SemanticReleaseError('The repositoryUrl option is required', 'ENOREPOURL');
}
debug('options values: %O', options);
return {options, plugins: await plugins(options, pluginsPath, logger)};
};
async function pkgRepoUrl() {
const {pkg} = await readPkgUp();
return pkg && pkg.repository ? pkg.repository.url : undefined;
const {pkg} = await readPkgUp({normalize: false});
return pkg && (isPlainObject(pkg.repository) ? pkg.repository.url : pkg.repository);
}
+7
View File
@@ -0,0 +1,7 @@
const SemanticReleaseError = require('@semantic-release/error');
const ERROR_DEFINITIONS = require('./definitions/errors');
module.exports = (code, ctx = {}) => {
const {message, details} = ERROR_DEFINITIONS[code](ctx);
return new SemanticReleaseError(message, code, details);
};
+56
View File
@@ -0,0 +1,56 @@
const {parse, format} = require('url');
const {isUndefined} = require('lodash');
const gitUrlParse = require('git-url-parse');
const hostedGitInfo = require('hosted-git-info');
const {verifyAuth} = require('./git');
const GIT_TOKENS = {
GIT_CREDENTIALS: undefined,
GH_TOKEN: undefined,
GITHUB_TOKEN: undefined,
GL_TOKEN: 'gitlab-ci-token:',
GITLAB_TOKEN: 'gitlab-ci-token:',
BB_TOKEN: 'x-token-auth:',
BITBUCKET_TOKEN: 'x-token-auth:',
};
/**
* Determine the the git repository URL to use to push, either:
* - The `repositoryUrl` as is if allowed to push
* - The `repositoryUrl` converted to `https` or `http` with Basic Authentication
*
* In addition, expand shortcut URLs (`owner/repo` => `https://github.com/owner/repo.git`) and transform `git+https` / `git+http` URLs to `https` / `http`.
*
* @param {String} repositoryUrl The user provided Git repository URL.
* @return {String} The formatted Git repository URL.
*/
module.exports = async ({repositoryUrl, branch}) => {
const info = hostedGitInfo.fromUrl(repositoryUrl, {noGitPlus: true});
if (info && info.getDefaultRepresentation() === 'shortcut') {
// Expand shorthand URLs (such as `owner/repo` or `gitlab:owner/repo`)
repositoryUrl = info.https();
} else {
const {protocols} = gitUrlParse(repositoryUrl);
// Replace `git+https` and `git+http` with `https` or `http`
if (protocols.includes('http') || protocols.includes('https')) {
repositoryUrl = format({...parse(repositoryUrl), protocol: protocols.includes('https') ? 'https' : 'http'});
}
}
// Test if push is allowed without transforming the URL (e.g. is ssh keys are set up)
try {
await verifyAuth(repositoryUrl, branch);
} catch (err) {
const envVar = Object.keys(GIT_TOKENS).find(envVar => !isUndefined(process.env[envVar]));
const gitCredentials = `${GIT_TOKENS[envVar] || ''}${process.env[envVar] || ''}`;
const {protocols, ...parsed} = gitUrlParse(repositoryUrl);
const protocol = protocols.includes('https') ? 'https' : protocols.includes('http') ? 'http' : 'https';
// If credentials are set via anvironment variables, convert the URL to http/https and add basic auth, otherwise return `repositoryUrl` as is
return gitCredentials ? {...parsed, protocols: [protocol], user: gitCredentials}.toString(protocol) : repositoryUrl;
}
return repositoryUrl;
};
+52
View File
@@ -0,0 +1,52 @@
const {escapeRegExp, template} = require('lodash');
const semver = require('semver');
const pLocate = require('p-locate');
const debug = require('debug')('semantic-release:get-last-release');
const {gitTags, isRefInHistory, gitTagHead} = require('./git');
/**
* Last release.
*
* @typedef {Object} LastRelease
* @property {string} version The version number of the last release.
* @property {string} [gitHead] The Git reference used to make the last release.
*/
/**
* Determine the Git tag and version of the last tagged release.
*
* - Obtain all the tags referencing commits in the current branch history
* - Filter out the ones that are not valid semantic version or doesn't match the `tagFormat`
* - Sort the versions
* - Retrive the highest version
*
* @param {String} tagFormat Git tag format.
* @param {Object} logger Global logger.
* @return {Promise<LastRelease>} The last tagged release or `undefined` if none is found.
*/
module.exports = async (tagFormat, logger) => {
// Generate a regex to parse tags formatted with `tagFormat`
// by replacing the `version` variable in the template by `(.+)`.
// The `tagFormat` is compiled with space as the `version` as it's an invalid tag character,
// so it's guaranteed to no be present in the `tagFormat`.
const tagRegexp = `^${escapeRegExp(template(tagFormat)({version: ' '})).replace(' ', '(.+)')}`;
const tags = (await gitTags())
.map(tag => ({gitTag: tag, version: (tag.match(tagRegexp) || new Array(2))[1]}))
.filter(
tag => tag.version && semver.valid(semver.clean(tag.version)) && !semver.prerelease(semver.clean(tag.version))
)
.sort((a, b) => semver.rcompare(a.version, b.version));
debug('found tags: %o', tags);
const tag = await pLocate(tags, tag => isRefInHistory(tag.gitTag), {concurrency: 1, preserveOrder: true});
if (tag) {
logger.log('Found git tag %s associated with version %s', tag.gitTag, tag.version);
return {gitHead: await gitTagHead(tag.gitTag), ...tag};
}
logger.log('No git tag version found');
return {};
};
+2 -1
View File
@@ -1,4 +1,5 @@
const semver = require('semver');
const {FIRST_RELEASE} = require('./definitions/constants');
module.exports = (type, lastRelease, logger) => {
let version;
@@ -6,7 +7,7 @@ module.exports = (type, lastRelease, logger) => {
version = semver.inc(lastRelease.version, type);
logger.log('The next release version is %s', version);
} else {
version = '1.0.0';
version = FIRST_RELEASE;
logger.log('There is no previous release, the next release version is %s', version);
}
+128 -44
View File
@@ -1,6 +1,5 @@
const execa = require('execa');
const debug = require('debug')('semantic-release:get-version-head');
const {debugShell} = require('./debug');
const debug = require('debug')('semantic-release:git');
/**
* Get the commit sha for a given tag.
@@ -11,81 +10,166 @@ const {debugShell} = require('./debug');
*/
async function gitTagHead(tagName) {
try {
const shell = await execa('git', ['rev-list', '-1', tagName]);
debugShell('Get git tag head', shell, debug);
return shell.stdout;
return await execa.stdout('git', ['rev-list', '-1', tagName]);
} catch (err) {
debug(err);
return null;
}
}
/**
* Get the tag associated with a commit sha.
*
* @param {string} gitHead The commit sha for which to retrieve the associated tag.
*
* @return {string} The tag associatedwith the sha in parameter or `undefined`.
* @return {Array<String>} List of git tags.
* @throws {Error} If the `git` command fails.
*/
async function gitCommitTag(gitHead) {
async function gitTags() {
return (await execa.stdout('git', ['tag']))
.split('\n')
.map(tag => tag.trim())
.filter(tag => Boolean(tag));
}
/**
* Verify if the `ref` is in the direct history of the current branch.
*
* @param {string} ref The reference to look for.
*
* @return {boolean} `true` if the reference is in the history of the current branch, falsy otherwise.
*/
async function isRefInHistory(ref) {
try {
const shell = await execa('git', ['describe', '--tags', '--exact-match', gitHead]);
debugShell('Get git commit tag', shell, debug);
return shell.stdout;
await execa('git', ['merge-base', '--is-ancestor', ref, 'HEAD']);
return true;
} catch (err) {
if (err.code === 1) {
return false;
}
debug(err);
return undefined;
throw err;
}
}
/**
* Verify if the commit `sha` is in the direct history of the current branch.
* Unshallow the git repository if necessary and fetch all the tags.
*
* @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.
* @param {String} repositoryUrl The remote repository URL.
*/
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;
}
/**
* Unshallow the git repository (retriving every commits and tags).
*/
async function unshallow() {
await execa('git', ['fetch', '--unshallow', '--tags'], {reject: false});
async function fetch(repositoryUrl) {
try {
await execa('git', ['fetch', '--unshallow', '--tags', repositoryUrl]);
} catch (err) {
await execa('git', ['fetch', '--tags', repositoryUrl]);
}
}
/**
* @return {string} the sha of the HEAD commit.
*/
async function gitHead() {
return execa.stdout('git', ['rev-parse', 'HEAD']);
}
/**
* @return {string} The value of the remote git URL.
*/
async function repoUrl() {
try {
const shell = await execa('git', ['rev-parse', 'HEAD']);
debugShell('Get git head', shell, debug);
return shell.stdout;
return await execa.stdout('git', ['config', '--get', 'remote.origin.url']);
} catch (err) {
debug(err);
throw new Error(err.stderr);
}
}
/**
* @return {string|undefined} The value of the remote git URL.
* @return {Boolean} `true` if the current working directory is in a git repository, falsy otherwise.
*/
async function repoUrl() {
return (await execa.stdout('git', ['remote', 'get-url', 'origin'], {reject: false})) || undefined;
async function isGitRepo() {
try {
return (await execa('git', ['rev-parse', '--git-dir'])).code === 0;
} catch (err) {
debug(err);
}
}
/**
* @return {Boolean} `true` if the current working directory is in a git repository, `false` otherwise.
* Verify the write access authorization to remote repository with push dry-run.
*
* @param {String} repositoryUrl The remote repository URL.
* @param {String} branch The repositoru branch for which to verify write access.
*
* @throws {Error} if not authorized to push.
*/
async function isGitRepo() {
const shell = await execa('git', ['rev-parse', '--git-dir'], {reject: false});
debugShell('Check if the current working directory is a git repository', shell, debug);
return shell.code === 0;
async function verifyAuth(repositoryUrl, branch) {
try {
await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`]);
} catch (err) {
debug(err);
throw err;
}
}
module.exports = {gitTagHead, gitCommitTag, isCommitInHistory, unshallow, gitHead, repoUrl, isGitRepo};
/**
* Tag the commit head on the local repository.
*
* @param {String} tagName The name of the tag.
* @throws {Error} if the tag creation failed.
*/
async function tag(tagName) {
await execa('git', ['tag', tagName]);
}
/**
* Push to the remote repository.
*
* @param {String} repositoryUrl The remote repository URL.
* @param {String} branch The branch to push.
* @throws {Error} if the push failed.
*/
async function push(repositoryUrl, branch) {
await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`]);
}
/**
* Verify a tag name is a valid Git reference.
*
* @param {string} tagName the tag name to verify.
* @return {boolean} `true` if valid, falsy otherwise.
*/
async function verifyTagName(tagName) {
try {
return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`])).code === 0;
} catch (err) {
debug(err);
}
}
/**
* Verify the local branch is up to date with the remote one.
*
* @param {String} branch The repository branch for which to verify status.
*
* @return {Boolean} `true` is the HEAD of the current local branch is the same as the HEAD of the remote branch, falsy otherwise.
*/
async function isBranchUpToDate(branch) {
try {
return await isRefInHistory(
(await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch])).match(/^(\w+)?/)[1]
);
} catch (err) {
debug(err);
}
}
module.exports = {
gitTagHead,
gitTags,
isRefInHistory,
fetch,
gitHead,
repoUrl,
isGitRepo,
verifyAuth,
tag,
push,
verifyTagName,
isBranchUpToDate,
};
+11
View File
@@ -0,0 +1,11 @@
const {escapeRegExp} = require('lodash');
const toReplace = Object.keys(process.env).filter(
envVar => /token|password|credential|secret|private/i.test(envVar) && process.env[envVar].trim()
);
const regexp = new RegExp(toReplace.map(envVar => escapeRegExp(process.env[envVar])).join('|'), 'g');
module.exports = output => {
return output && toReplace.length > 0 ? output.toString().replace(regexp, '[secure]') : output;
};
-72
View File
@@ -1,72 +0,0 @@
const {isString, isObject, isFunction, isArray} = require('lodash');
const semver = require('semver');
const RELEASE_TYPE = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'];
const validatePluginConfig = conf => isString(conf) || isString(conf.path) || isFunction(conf);
module.exports = {
verifyConditions: {
default: ['@semantic-release/npm', '@semantic-release/github'],
config: {
validator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
message:
'The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
},
},
getLastRelease: {
default: '@semantic-release/npm',
config: {
validator: conf => Boolean(conf) && validatePluginConfig(conf),
message:
'The "getLastRelease" plugin is mandatory, and must be a single plugin definition. A plugin definition is either a string or an object with a path property.',
},
output: {
validator: output =>
!output ||
(isObject(output) && !output.version) ||
(isString(output.version) && Boolean(semver.valid(semver.clean(output.version))) && Boolean(output.gitHead)),
message:
'The "getLastRelease" plugin output if defined, must be an object with a valid semver version in the "version" property and the corresponding git reference in "gitHead" property.',
},
},
analyzeCommits: {
default: '@semantic-release/commit-analyzer',
config: {
validator: conf => Boolean(conf) && validatePluginConfig(conf),
message:
'The "analyzeCommits" plugin is mandatory, and must be a single plugin definition. A plugin definition is either a string or an object with a path property.',
},
output: {
validator: output => !output || RELEASE_TYPE.includes(output),
message: 'The "analyzeCommits" plugin output, if defined, must be a valid semver release type.',
},
},
verifyRelease: {
default: false,
config: {
validator: conf => !conf || (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
message:
'The "verifyRelease" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
},
},
generateNotes: {
default: '@semantic-release/release-notes-generator',
config: {
validator: conf => !conf || validatePluginConfig(conf),
message:
'The "generateNotes" plugin, if defined, must be a single plugin definition. A plugin definition is either a string or an object with a path property.',
},
output: {
validator: output => !output || isString(output),
message: 'The "generateNotes" plugin output, if defined, must be a string.',
},
},
publish: {
default: ['@semantic-release/npm', '@semantic-release/github'],
config: {
validator: conf => Boolean(conf) && (isArray(conf) ? conf : [conf]).every(conf => validatePluginConfig(conf)),
message:
'The "publish" plugin is mandatory, and must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.',
},
},
};
+39 -24
View File
@@ -1,31 +1,46 @@
const {isArray, isObject, omit} = require('lodash');
const SemanticReleaseError = require('@semantic-release/error');
const PLUGINS_DEFINITION = require('./definitions');
const {identity, isPlainObject, omit, castArray, isUndefined} = require('lodash');
const AggregateError = require('aggregate-error');
const getError = require('../get-error');
const PLUGINS_DEFINITIONS = require('../definitions/plugins');
const pipeline = require('./pipeline');
const normalize = require('./normalize');
module.exports = (options, pluginsPath, logger) =>
Object.keys(PLUGINS_DEFINITION).reduce((plugins, pluginType) => {
const {config, output, default: def} = PLUGINS_DEFINITION[pluginType];
let pluginConfs;
if (options[pluginType]) {
// If an object is passed and the path is missing, set the default one for single plugins
if (isObject(options[pluginType]) && !options[pluginType].path && !isArray(def)) {
options[pluginType].path = def;
module.exports = (options, pluginsPath, logger) => {
const errors = [];
const plugins = Object.entries(PLUGINS_DEFINITIONS).reduce(
(
plugins,
[type, {configValidator, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]
) => {
let pluginConfs;
if (isUndefined(options[type])) {
pluginConfs = def;
} else {
const defaultPaths = castArray(def);
// If an object is passed and the path is missing, set the default one for single plugins
if (isPlainObject(options[type]) && !options[type].path && defaultPaths.length === 1) {
[options[type].path] = defaultPaths;
}
if (configValidator && !configValidator(options[type])) {
errors.push(getError('EPLUGINCONF', {type, pluginConf: options[type]}));
return plugins;
}
pluginConfs = options[type];
}
if (config && !config.validator(options[pluginType])) {
throw new SemanticReleaseError(config.message, 'EPLUGINCONF');
}
pluginConfs = options[pluginType];
} else {
pluginConfs = def;
}
const globalOpts = omit(options, Object.keys(PLUGINS_DEFINITION));
const globalOpts = omit(options, Object.keys(PLUGINS_DEFINITIONS));
const steps = castArray(pluginConfs).map(conf => normalize(type, pluginsPath, globalOpts, conf, logger));
plugins[pluginType] = isArray(pluginConfs)
? pipeline(pluginConfs.map(conf => normalize(pluginType, pluginsPath, globalOpts, conf, logger, output)))
: normalize(pluginType, pluginsPath, globalOpts, pluginConfs, logger, output);
plugins[type] = async input =>
postprocess(await pipeline(steps, pipelineConfig && pipelineConfig(plugins, logger))(await preprocess(input)));
return plugins;
}, {});
return plugins;
},
{}
);
if (errors.length > 0) {
throw new AggregateError(errors);
}
return plugins;
};
+29 -18
View File
@@ -1,20 +1,25 @@
const {dirname} = require('path');
const {inspect} = require('util');
const SemanticReleaseError = require('@semantic-release/error');
const {isString, isObject, isFunction, noop, cloneDeep} = require('lodash');
const {isString, isPlainObject, isFunction, noop, cloneDeep} = require('lodash');
const resolveFrom = require('resolve-from');
const getError = require('../get-error');
const {extractErrors} = require('../utils');
const PLUGINS_DEFINITIONS = require('../definitions/plugins');
module.exports = (pluginType, pluginsPath, globalOpts, pluginOpts, logger, validator) => {
/* eslint max-params: ["error", 5] */
module.exports = (type, pluginsPath, globalOpts, pluginOpts, logger) => {
if (!pluginOpts) {
return noop;
}
const {path, ...config} = isString(pluginOpts) || isFunction(pluginOpts) ? {path: pluginOpts} : pluginOpts;
const pluginName = isFunction(path) ? `[Function: ${path.name}]` : path;
if (!isFunction(pluginOpts)) {
if (pluginsPath[path]) {
logger.log('Load plugin %s from %s in shareable config %s', pluginType, path, pluginsPath[path]);
logger.log('Load plugin "%s" from %s in shareable config %s', type, path, pluginsPath[path]);
} else {
logger.log('Load plugin %s from %s', pluginType, path);
logger.log('Load plugin "%s" from %s', type, path);
}
}
@@ -28,21 +33,27 @@ module.exports = (pluginType, pluginsPath, globalOpts, pluginOpts, logger, valid
let func;
if (isFunction(plugin)) {
func = plugin.bind(null, cloneDeep({...globalOpts, ...config}));
} else if (isObject(plugin) && plugin[pluginType] && isFunction(plugin[pluginType])) {
func = plugin[pluginType].bind(null, cloneDeep({...globalOpts, ...config}));
} else if (isPlainObject(plugin) && plugin[type] && isFunction(plugin[type])) {
func = plugin[type].bind(null, cloneDeep({...globalOpts, ...config}));
} else {
throw new SemanticReleaseError(
`The ${pluginType} plugin must be a function, or an object with a function in the property ${pluginType}.`,
'EPLUGINCONF'
);
throw getError('EPLUGIN', {type, pluginName});
}
return async input => {
const result = await func(cloneDeep(input));
if (validator && !validator.validator(result)) {
throw new Error(`${validator.message} Received: ${inspect(result)}`);
const validator = async input => {
const {outputValidator} = PLUGINS_DEFINITIONS[type] || {};
try {
logger.log('Call plugin "%s"', type);
const result = await func(cloneDeep(input));
if (outputValidator && !outputValidator(result)) {
throw getError(`E${type.toUpperCase()}OUTPUT`, {result, pluginName});
}
return result;
} catch (err) {
extractErrors(err).forEach(err => Object.assign(err, {pluginName}));
throw err;
}
return result;
};
Reflect.defineProperty(validator, 'pluginName', {value: pluginName, writable: false, enumerable: true});
return validator;
};
+45 -8
View File
@@ -1,19 +1,56 @@
const {identity} = require('lodash');
const pReduce = require('p-reduce');
const AggregateError = require('aggregate-error');
const {extractErrors} = require('../utils');
module.exports = steps => async (input, getNextInput = identity) => {
/**
* A Function that execute a list of function sequencially. If at least one Function ins the pipeline throw an Error or rejects, the pipeline function rejects as well.
*
* @typedef {Function} Pipeline
* @param {Any} input Argument to pass to the first step in the pipeline.
*
* @return {Array<*>|*} An Array with the result of each step in the pipeline; if there is only 1 step in the pipeline, the result of this step is returned directly.
*
* @throws {AggregateError|Error} An AggregateError with the errors of each step in the pipeline that rejected; if there is only 1 step in the pipeline, the error of this step is thrown directly.
*/
/**
* Create a Pipeline with a list of Functions.
*
* @param {Array<Function>} steps The list of Function to execute.
* @param {Object} options Pipeline options.
* @param {Boolean} [options.settleAll=false] If `true` all the steps in the pipeline are executed, even if one rejects, if `false` the execution stops after a steps rejects.
* @param {Function} [options.getNextInput=identity] Function called after each step is executed, with the last step input and the current current step result; the returned value will be used as the input of the next step.
* @param {Function} [options.transform=identity] Function called after each step is executed, with the current step result, the step function and the last step input; the returned value will be saved in the pipeline results.
*
* @return {Pipeline} A Function that execute the `steps` sequencially
*/
module.exports = (steps, {settleAll = false, getNextInput = identity, transform = identity} = {}) => async input => {
const results = [];
const errors = [];
await pReduce(
steps,
async (prevResult, nextStep) => {
// Call the next step with the input computed at the end of the previous iteration
const result = await nextStep(prevResult);
// Save intermediary result
results.push(result);
// Prepare input for next step, passing the result of the previous iteration and the current one
return getNextInput(prevResult, result);
async (lastInput, step) => {
let result;
try {
// Call the step with the input computed at the end of the previous iteration and save intermediary result
result = await transform(await step(lastInput), step, lastInput);
results.push(result);
} catch (err) {
if (settleAll) {
errors.push(...extractErrors(err));
result = err;
} else {
throw err;
}
}
// Prepare input for the next step, passing the input of the last iteration (or initial parameter for the first iteration) and the result of the current one
return getNextInput(lastInput, result);
},
input
);
if (errors.length > 0) {
throw new AggregateError(errors);
}
return results;
};
+7
View File
@@ -0,0 +1,7 @@
const {isFunction} = require('lodash');
function extractErrors(err) {
return err && isFunction(err[Symbol.iterator]) ? [...err] : [err];
}
module.exports = {extractErrors};
+30
View File
@@ -0,0 +1,30 @@
const {template} = require('lodash');
const AggregateError = require('aggregate-error');
const {isGitRepo, verifyTagName} = require('./git');
const getError = require('./get-error');
module.exports = async options => {
const errors = [];
if (!(await isGitRepo())) {
errors.push(getError('ENOGITREPO'));
} else if (!options.repositoryUrl) {
errors.push(getError('ENOREPOURL'));
}
// Verify that compiling the `tagFormat` produce a valid Git tag
if (!(await verifyTagName(template(options.tagFormat)({version: '0.0.0'})))) {
errors.push(getError('EINVALIDTAGFORMAT', {tagFormat: options.tagFormat}));
}
// Verify the `tagFormat` contains the variable `version` by compiling the `tagFormat` template
// with a space as the `version` value and verify the result contains the space.
// The space is used as it's an invalid tag character, so it's guaranteed to no be present in the `tagFormat`.
if ((template(options.tagFormat)({version: ' '}).match(/ /g) || []).length !== 1) {
errors.push(getError('ETAGNOVERSION', {tagFormat: options.tagFormat}));
}
if (errors.length > 0) {
throw new AggregateError(errors);
}
};
+28 -33
View File
@@ -20,48 +20,52 @@
],
"dependencies": {
"@semantic-release/commit-analyzer": "^5.0.0",
"@semantic-release/error": "^2.1.0",
"@semantic-release/github": "^3.0.1",
"@semantic-release/npm": "^2.0.0",
"@semantic-release/error": "^2.2.0",
"@semantic-release/github": "^4.1.0",
"@semantic-release/npm": "^3.2.0",
"@semantic-release/release-notes-generator": "^6.0.0",
"aggregate-error": "^1.0.0",
"chalk": "^2.3.0",
"commander": "^2.11.0",
"cosmiconfig": "^4.0.0",
"cosmiconfig": "^5.0.1",
"debug": "^3.1.0",
"env-ci": "^1.0.0",
"execa": "^0.9.0",
"env-ci": "^2.0.0",
"execa": "^0.10.0",
"find-versions": "^2.0.0",
"get-stream": "^3.0.0",
"git-log-parser": "^1.2.0",
"git-url-parse": "^9.0.0",
"hook-std": "^1.0.1",
"hosted-git-info": "^2.7.1",
"lodash": "^4.17.4",
"marked": "^0.3.9",
"marked-terminal": "^2.0.0",
"marked": "^0.4.0",
"marked-terminal": "^3.0.0",
"p-locate": "^3.0.0",
"p-reduce": "^1.0.0",
"read-pkg-up": "^3.0.0",
"read-pkg-up": "^4.0.0",
"resolve-from": "^4.0.0",
"semver": "^5.4.1"
"semver": "^5.4.1",
"yargs": "^12.0.0"
},
"devDependencies": {
"ava": "^0.24.0",
"ava": "^0.25.0",
"clear-module": "^2.1.0",
"codecov": "^3.0.0",
"commitizen": "^2.9.6",
"cz-conventional-changelog": "^2.0.0",
"delay": "^2.0.0",
"delay": "^3.0.0",
"dockerode": "^2.5.2",
"eslint-config-prettier": "^2.5.0",
"eslint-plugin-prettier": "^2.3.0",
"file-url": "^2.0.2",
"fs-extra": "^5.0.0",
"fs-extra": "^6.0.0",
"got": "^8.0.0",
"js-yaml": "^3.10.0",
"mockserver-client": "^5.1.1",
"nock": "^9.0.2",
"nyc": "^11.2.1",
"p-retry": "^1.0.0",
"prettier": "~1.10.0",
"proxyquire": "^1.8.0",
"sinon": "^4.0.0",
"nyc": "^12.0.1",
"p-retry": "^2.0.0",
"proxyquire": "^2.0.0",
"sinon": "^6.0.0",
"tempy": "^0.2.1",
"xo": "^0.18.2"
"xo": "^0.21.0"
},
"engines": {
"node": ">=8.3"
@@ -102,8 +106,6 @@
},
"prettier": {
"printWidth": 120,
"singleQuote": true,
"bracketSpacing": false,
"trailingComma": "es5"
},
"publishConfig": {
@@ -125,14 +127,7 @@
"test": "nyc ava -v"
},
"xo": {
"extends": [
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": 2
}
"prettier": true,
"space": true
}
}
+237
View File
@@ -0,0 +1,237 @@
import test from 'ava';
import proxyquire from 'proxyquire';
import clearModule from 'clear-module';
import {stub} from 'sinon';
// Save the current process.env and process.argv
const envBackup = Object.assign({}, process.env);
const argvBackup = Object.assign({}, process.argv);
test.beforeEach(t => {
clearModule('yargs');
t.context.logs = '';
t.context.errors = '';
t.context.stdout = stub(process.stdout, 'write').callsFake(val => {
t.context.logs += val.toString();
});
t.context.stderr = stub(process.stderr, 'write').callsFake(val => {
t.context.errors += val.toString();
});
});
test.afterEach.always(t => {
process.env = envBackup;
process.argv = argvBackup;
t.context.stdout.restore();
t.context.stderr.restore();
delete process.exitCode;
});
test.serial('Pass options to semantic-release API', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = [
'',
'',
'-b',
'master',
'-r',
'https://github/com/owner/repo.git',
'-t',
`v\${version}`,
'-e',
'config1',
'config2',
'--verify-conditions',
'condition1',
'condition2',
'--analyze-commits',
'analyze',
'--verify-release',
'verify1',
'verify2',
'--generate-notes',
'notes',
'--prepare',
'prepare1',
'prepare2',
'--publish',
'publish1',
'publish2',
'--success',
'success1',
'success2',
'--fail',
'fail1',
'fail2',
'--debug',
'-d',
];
await cli();
t.is(run.args[0][0].branch, 'master');
t.is(run.args[0][0].repositoryUrl, 'https://github/com/owner/repo.git');
t.is(run.args[0][0].tagFormat, `v\${version}`);
t.deepEqual(run.args[0][0].extends, ['config1', 'config2']);
t.deepEqual(run.args[0][0].verifyConditions, ['condition1', 'condition2']);
t.is(run.args[0][0].analyzeCommits, 'analyze');
t.deepEqual(run.args[0][0].verifyRelease, ['verify1', 'verify2']);
t.is(run.args[0][0].generateNotes, 'notes');
t.deepEqual(run.args[0][0].prepare, ['prepare1', 'prepare2']);
t.deepEqual(run.args[0][0].publish, ['publish1', 'publish2']);
t.deepEqual(run.args[0][0].success, ['success1', 'success2']);
t.deepEqual(run.args[0][0].fail, ['fail1', 'fail2']);
t.is(run.args[0][0].debug, true);
t.is(run.args[0][0].dryRun, true);
t.is(process.exitCode, 0);
});
test.serial('Pass options to semantic-release API with alias arguments', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = [
'',
'',
'--branch',
'master',
'--repository-url',
'https://github/com/owner/repo.git',
'--tag-format',
`v\${version}`,
'--extends',
'config1',
'config2',
'--dry-run',
];
await cli();
t.is(run.args[0][0].branch, 'master');
t.is(run.args[0][0].repositoryUrl, 'https://github/com/owner/repo.git');
t.is(run.args[0][0].tagFormat, `v\${version}`);
t.deepEqual(run.args[0][0].extends, ['config1', 'config2']);
t.is(run.args[0][0].dryRun, true);
t.is(process.exitCode, 0);
});
test.serial('Pass unknown options to semantic-release API', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = [
'',
'',
'--bool',
'--first-option',
'value1',
'--second-option',
'value2',
'--second-option',
'value3',
];
await cli();
t.is(run.args[0][0].bool, true);
t.is(run.args[0][0].firstOption, 'value1');
t.deepEqual(run.args[0][0].secondOption, ['value2', 'value3']);
t.is(process.exitCode, 0);
});
test.serial('Pass empty Array to semantic-release API for list option set to "false"', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = ['', '', '--publish', 'false'];
await cli();
t.deepEqual(run.args[0][0].publish, []);
t.is(process.exitCode, 0);
});
test.serial('Do not set properties in option for which arg is not in command line', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = ['', '', '-b', 'master'];
await cli();
t.false(Reflect.apply(Object.prototype.hasOwnProperty, run.args[0][0], ['ci']));
t.false(Reflect.apply(Object.prototype.hasOwnProperty, run.args[0][0], ['d']));
t.false(Reflect.apply(Object.prototype.hasOwnProperty, run.args[0][0], ['dry-run']));
t.false(Reflect.apply(Object.prototype.hasOwnProperty, run.args[0][0], ['debug']));
t.false(Reflect.apply(Object.prototype.hasOwnProperty, run.args[0][0], ['r']));
t.false(Reflect.apply(Object.prototype.hasOwnProperty, run.args[0][0], ['t']));
});
test.serial('Set "noCi" options to "true" with "--no-ci"', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = ['', '', '--no-ci'];
await cli();
t.is(run.args[0][0].noCi, true);
t.is(process.exitCode, 0);
});
test.serial('Display help', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = ['', '', '--help'];
await cli();
t.regex(t.context.logs, /Run automated package publishing/);
t.is(process.exitCode, 0);
});
test.serial('Returns error code and prints help if called with a command', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = ['', '', 'pre'];
await cli();
t.regex(t.context.errors, /Run automated package publishing/);
t.regex(t.context.errors, /Too many non-option arguments/);
t.is(process.exitCode, 1);
});
test.serial('Return error code if multiple plugin are set for single plugin', async t => {
const run = stub().resolves(true);
const cli = proxyquire('../cli', {'.': run});
process.argv = ['', '', '--analyze-commits', 'analyze1', 'analyze2'];
await cli();
t.regex(t.context.errors, /Run automated package publishing/);
t.regex(t.context.errors, /Too many non-option arguments/);
t.is(process.exitCode, 1);
});
test.serial('Return error code if semantic-release throw error', async t => {
const run = stub().rejects(new Error('semantic-release error'));
const cli = proxyquire('../cli', {'.': run});
process.argv = ['', ''];
await cli();
t.regex(t.context.errors, /semantic-release error/);
t.is(process.exitCode, 1);
});
+129
View File
@@ -0,0 +1,129 @@
import test from 'ava';
import plugins from '../../lib/definitions/plugins';
import {RELEASE_NOTES_SEPARATOR} from '../../lib/definitions/constants';
test('The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(plugins.verifyConditions.configValidator({}));
t.false(plugins.verifyConditions.configValidator({path: null}));
t.true(plugins.verifyConditions.configValidator({path: 'plugin-path.js'}));
t.true(plugins.verifyConditions.configValidator());
t.true(plugins.verifyConditions.configValidator('plugin-path.js'));
t.true(plugins.verifyConditions.configValidator(() => {}));
t.true(plugins.verifyConditions.configValidator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "analyzeCommits" plugin is mandatory, and must be a single plugin definition', t => {
t.false(plugins.analyzeCommits.configValidator({}));
t.false(plugins.analyzeCommits.configValidator({path: null}));
t.false(plugins.analyzeCommits.configValidator([]));
t.false(plugins.analyzeCommits.configValidator());
t.true(plugins.analyzeCommits.configValidator({path: 'plugin-path.js'}));
t.true(plugins.analyzeCommits.configValidator('plugin-path.js'));
t.true(plugins.analyzeCommits.configValidator(() => {}));
});
test('The "verifyRelease" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(plugins.verifyRelease.configValidator({}));
t.false(plugins.verifyRelease.configValidator({path: null}));
t.true(plugins.verifyRelease.configValidator({path: 'plugin-path.js'}));
t.true(plugins.verifyRelease.configValidator());
t.true(plugins.verifyRelease.configValidator('plugin-path.js'));
t.true(plugins.verifyRelease.configValidator(() => {}));
t.true(plugins.verifyRelease.configValidator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "generateNotes" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(plugins.generateNotes.configValidator({}));
t.false(plugins.generateNotes.configValidator({path: null}));
t.true(plugins.generateNotes.configValidator({path: 'plugin-path.js'}));
t.true(plugins.generateNotes.configValidator());
t.true(plugins.generateNotes.configValidator('plugin-path.js'));
t.true(plugins.generateNotes.configValidator(() => {}));
t.true(plugins.generateNotes.configValidator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "prepare" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(plugins.verifyRelease.configValidator({}));
t.false(plugins.verifyRelease.configValidator({path: null}));
t.true(plugins.verifyRelease.configValidator({path: 'plugin-path.js'}));
t.true(plugins.verifyRelease.configValidator());
t.true(plugins.verifyRelease.configValidator('plugin-path.js'));
t.true(plugins.verifyRelease.configValidator(() => {}));
t.true(plugins.verifyRelease.configValidator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "publish" plugin is mandatory, and must be a single or an array of plugins definition', t => {
t.false(plugins.publish.configValidator({}));
t.false(plugins.publish.configValidator({path: null}));
t.true(plugins.publish.configValidator({path: 'plugin-path.js'}));
t.true(plugins.publish.configValidator());
t.true(plugins.publish.configValidator('plugin-path.js'));
t.true(plugins.publish.configValidator(() => {}));
t.true(plugins.publish.configValidator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "success" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(plugins.success.configValidator({}));
t.false(plugins.success.configValidator({path: null}));
t.true(plugins.success.configValidator({path: 'plugin-path.js'}));
t.true(plugins.success.configValidator());
t.true(plugins.success.configValidator('plugin-path.js'));
t.true(plugins.success.configValidator(() => {}));
t.true(plugins.success.configValidator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "fail" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(plugins.fail.configValidator({}));
t.false(plugins.fail.configValidator({path: null}));
t.true(plugins.fail.configValidator({path: 'plugin-path.js'}));
t.true(plugins.fail.configValidator());
t.true(plugins.fail.configValidator('plugin-path.js'));
t.true(plugins.fail.configValidator(() => {}));
t.true(plugins.fail.configValidator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', t => {
t.false(plugins.analyzeCommits.outputValidator('invalid'));
t.false(plugins.analyzeCommits.outputValidator(1));
t.false(plugins.analyzeCommits.outputValidator({}));
t.true(plugins.analyzeCommits.outputValidator());
t.true(plugins.analyzeCommits.outputValidator(null));
t.true(plugins.analyzeCommits.outputValidator('major'));
});
test('The "generateNotes" plugin output, if defined, must be a string', t => {
t.false(plugins.generateNotes.outputValidator(1));
t.false(plugins.generateNotes.outputValidator({}));
t.true(plugins.generateNotes.outputValidator());
t.true(plugins.generateNotes.outputValidator(null));
t.true(plugins.generateNotes.outputValidator(''));
t.true(plugins.generateNotes.outputValidator('string'));
});
test('The "publish" plugin output, if defined, must be an object', t => {
t.false(plugins.publish.outputValidator(1));
t.false(plugins.publish.outputValidator('string'));
t.true(plugins.publish.outputValidator({}));
t.true(plugins.publish.outputValidator());
t.true(plugins.publish.outputValidator(null));
t.true(plugins.publish.outputValidator(''));
});
test('The "generateNotes" plugins output are concatenated with separator', t => {
t.is(plugins.generateNotes.postprocess(['note 1', 'note 2']), `note 1${RELEASE_NOTES_SEPARATOR}note 2`);
t.is(plugins.generateNotes.postprocess(['', 'note']), 'note');
t.is(plugins.generateNotes.postprocess([undefined, 'note']), 'note');
t.is(plugins.generateNotes.postprocess(['note 1', '', 'note 2']), `note 1${RELEASE_NOTES_SEPARATOR}note 2`);
t.is(plugins.generateNotes.postprocess(['note 1', undefined, 'note 2']), `note 1${RELEASE_NOTES_SEPARATOR}note 2`);
});
+5
View File
@@ -0,0 +1,5 @@
const AggregateError = require('aggregate-error');
module.exports = () => {
throw new AggregateError([new Error('a'), new Error('b')]);
};
+1
View File
@@ -0,0 +1 @@
module.exports = (pluginConfig, options) => options;
+18 -391
View File
@@ -1,16 +1,7 @@
import test from 'ava';
import {stub} from 'sinon';
import getCommits from '../lib/get-commits';
import {
gitRepo,
gitCommits,
gitCheckout,
gitTagVersion,
gitShallowClone,
gitTags,
gitLog,
gitDetachedHead,
} from './helpers/git-utils';
import {gitRepo, gitCommits, gitDetachedHead} from './helpers/git-utils';
// Save the current working diretory
const cwd = process.cwd();
@@ -34,86 +25,11 @@ test.serial('Get all commits when there is no last release', async t => {
const commits = await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module
const result = await getCommits({}, 'master', t.context.logger);
const result = await getCommits(undefined, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
t.falsy(result.lastRelease.gitTag);
});
test.serial('Get all commits with gitTags', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
let commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
// Add new commits to the master branch
commits = (await gitCommits(['Second'])).concat(commits);
// Retrieve the commits with the commits module
const result = await getCommits({}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[0].gitTags, '(HEAD -> master)');
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
t.is(result.commits[1].gitTags, '(tag: v1.0.0)');
});
test.serial('Get all commits when there is no last release, including the ones not in the shallow clone', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First', 'Second']);
// Create a shallow clone with only 1 commit
await gitShallowClone(repo);
// Verify the shallow clone contains only one commit
t.is((await gitLog()).length, 1);
// Retrieve the commits with the commits module
const result = await getCommits({}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
t.falsy(result.lastRelease.gitTag);
t.is(result.length, 2);
t.deepEqual(result, commits);
});
test.serial('Get all commits since gitHead (from lastRelease)', async t => {
@@ -123,25 +39,11 @@ test.serial('Get all commits since gitHead (from lastRelease)', async t => {
const commits = await gitCommits(['First', 'Second', 'Third']);
// Retrieve the commits with the commits module, since commit 'First'
const result = await getCommits({gitHead: commits[commits.length - 1].hash}, 'master', t.context.logger);
const result = await getCommits(commits[commits.length - 1].hash, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead, commits[commits.length - 1].hash);
t.falsy(result.lastRelease.version);
t.falsy(result.lastRelease.gitTag);
t.is(result.length, 2);
t.deepEqual(result, commits.slice(0, 2));
});
test.serial('Get all commits since gitHead (from lastRelease) on a detached head repo', async t => {
@@ -153,183 +55,15 @@ test.serial('Get all commits since gitHead (from lastRelease) on a detached head
await gitDetachedHead(repo, commits[1].hash);
// Retrieve the commits with the commits module, since commit 'First'
const result = await getCommits({gitHead: commits[commits.length - 1].hash}, 'master', t.context.logger);
const result = await getCommits(commits[commits.length - 1].hash, 'master', t.context.logger);
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
t.is(result.commits.length, 1);
t.is(result.commits[0].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[0].message, commits[1].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead, commits[commits.length - 1].hash);
t.falsy(result.lastRelease.version);
t.falsy(result.lastRelease.gitTag);
});
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 getCommits({version: '1.0.0', gitHead: 'missing_ref'}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.gitTag, '1.0.0');
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 getCommits({version: '1.0.0', gitHead: 'missing_ref'}, 'master', t.context.logger);
// Verify the module retrieved only the commit 'feat: Second' (included in the detached and after 'fix: First')
t.is(result.commits.length, 1);
t.is(result.commits[0].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[0].message, commits[1].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.gitTag, '1.0.0');
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 getCommits({version: '1.0.0', gitHead: 'missing_ref'}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.gitTag, 'v1.0.0');
t.is(result.lastRelease.version, '1.0.0');
});
test.serial('Get all commits since gitHead, when gitHead is missing 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 getCommits(
{version: '1.0.0', gitHead: commits[commits.length - 1].hash},
'master',
t.context.logger
);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.version, '1.0.0');
t.falsy(result.lastRelease.gitTag);
});
test.serial('Get all commits since gitHead from tag, when tags is missing 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 getCommits({version: '1.0.0', gitHead: 'missing_ref'}, 'master', t.context.logger);
// Verify the commits created and retrieved by the module are identical
t.is(result.commits.length, 2);
t.is(result.commits[0].hash.substring(0, 7), commits[0].hash);
t.is(result.commits[0].message, commits[0].message);
t.truthy(result.commits[0].committerDate);
t.truthy(result.commits[0].author.name);
t.truthy(result.commits[0].committer.name);
t.is(result.commits[1].hash.substring(0, 7), commits[1].hash);
t.is(result.commits[1].message, commits[1].message);
t.truthy(result.commits[1].committerDate);
t.truthy(result.commits[1].author.name);
t.truthy(result.commits[1].committer.name);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[commits.length - 1].hash);
t.is(result.lastRelease.gitTag, 'v1.0.0');
t.is(result.lastRelease.version, '1.0.0');
t.is(result.length, 1);
t.is(result[0].hash, commits[1].hash);
t.is(result[0].message, commits[1].message);
t.truthy(result[0].committerDate);
t.truthy(result[0].author.name);
t.truthy(result[0].committer.name);
});
test.serial('Return empty array if lastRelease.gitHead is the last commit', async t => {
@@ -339,15 +73,10 @@ test.serial('Return empty array if lastRelease.gitHead is the last commit', asyn
const commits = await gitCommits(['First', 'Second']);
// Retrieve the commits with the commits module, since commit 'Second' (therefore none)
const result = await getCommits({gitHead: commits[0].hash, version: '1.0.0'}, 'master', t.context.logger);
const result = await getCommits(commits[0].hash, 'master', t.context.logger);
// Verify no commit is retrieved
t.deepEqual(result.commits, []);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.is(result.lastRelease.gitHead.substring(0, 7), commits[0].hash);
t.is(result.lastRelease.version, '1.0.0');
t.falsy(result.lastRelease.gitTag);
t.deepEqual(result, []);
});
test.serial('Return empty array if there is no commits', async t => {
@@ -355,110 +84,8 @@ test.serial('Return empty array if there is no commits', async t => {
await gitRepo();
// Retrieve the commits with the commits module
const result = await getCommits({}, 'master', t.context.logger);
const result = await getCommits(undefined, 'master', t.context.logger);
// Verify no commit is retrieved
t.deepEqual(result.commits, []);
// Verify the last release is returned and updated
t.truthy(result.lastRelease);
t.falsy(result.lastRelease.gitHead);
t.falsy(result.lastRelease.version);
});
test.serial('Throws 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(getCommits({gitHead: 'notinhistory'}, 'master', t.context.logger));
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.is(error.name, 'SemanticReleaseError');
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.args[0][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.args[0][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(
getCommits({version: '1.0.1', gitHead: commitsBranch[0].hash}, 'master', t.context.logger)
);
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.is(error.name, 'SemanticReleaseError');
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.args[0][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.args[0][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(
getCommits({version: '1.0.1', gitHead: commitsBranch[0].hash}, 'master', t.context.logger)
);
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.is(error.name, 'SemanticReleaseError');
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.args[0][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.args[0][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(getCommits({version: '1.0.0', gitHead: shaTag}, 'master', t.context.logger));
// Verify error code and type
t.is(error.code, 'ENOTINHISTORY');
t.is(error.name, 'SemanticReleaseError');
// Verify the log function has been called with a message mentionning the branch
t.regex(t.context.error.args[0][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.args[0][0], new RegExp(`restoring the commit "${shaTag}"`));
t.deepEqual(result, []);
});
+71 -54
View File
@@ -13,6 +13,12 @@ const envBackup = Object.assign({}, process.env);
const cwd = process.cwd();
test.beforeEach(t => {
delete process.env.GIT_CREDENTIALS;
delete process.env.GH_TOKEN;
delete process.env.GITHUB_TOKEN;
delete process.env.GL_TOKEN;
delete process.env.GITLAB_TOKEN;
// Delete environment variables that could have been set on the machine running the tests
t.context.plugins = stub().returns({});
t.context.getConfig = proxyquire('../lib/get-config', {'./plugins': t.context.plugins});
});
@@ -25,12 +31,12 @@ test.afterEach.always(() => {
});
test.serial('Default values, reading repositoryUrl from package.json', async t => {
const pkg = {repository: 'git@package.com:owner/module.git'};
const pkg = {repository: 'https://host.null/owner/package.git'};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
await gitCommits(['First']);
// Add remote.origin.url config
await gitAddConfig('remote.origin.url', 'git@repo.com:owner/module.git');
await gitAddConfig('remote.origin.url', 'git@host.null:owner/repo.git');
// Create package.json in repository root
await outputJson('./package.json', pkg);
@@ -38,24 +44,26 @@ test.serial('Default values, reading repositoryUrl from package.json', async t =
// Verify the default options are set
t.is(options.branch, 'master');
t.is(options.repositoryUrl, 'git@package.com:owner/module.git');
t.is(options.repositoryUrl, 'https://host.null/owner/package.git');
t.is(options.tagFormat, `v\${version}`);
});
test.serial('Default values, reading repositoryUrl from repo if not set in package.json', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add remote.origin.url config
await gitAddConfig('remote.origin.url', 'git@repo.com:owner/module.git');
await gitAddConfig('remote.origin.url', 'https://host.null/owner/module.git');
const {options} = await t.context.getConfig();
// Verify the default options are set
t.is(options.branch, 'master');
t.is(options.repositoryUrl, 'git@repo.com:owner/module.git');
t.is(options.repositoryUrl, 'https://host.null/owner/module.git');
t.is(options.tagFormat, `v\${version}`);
});
test.serial('Default values, reading repositoryUrl (http url) from package.json if not set in repo', async t => {
const pkg = {repository: 'git+https://hostname.com/owner/module.git'};
const pkg = {repository: 'https://host.null/owner/module.git'};
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create package.json in repository root
@@ -65,16 +73,17 @@ test.serial('Default values, reading repositoryUrl (http url) from package.json
// Verify the default options are set
t.is(options.branch, 'master');
t.is(options.repositoryUrl, pkg.repository);
t.is(options.repositoryUrl, 'https://host.null/owner/module.git');
t.is(options.tagFormat, `v\${version}`);
});
test.serial('Read options from package.json', async t => {
const release = {
analyzeCommits: 'analyzeCommits',
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -92,9 +101,10 @@ test.serial('Read options from package.json', async t => {
test.serial('Read options from .releaserc.yml', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -112,9 +122,10 @@ test.serial('Read options from .releaserc.yml', async t => {
test.serial('Read options from .releaserc.json', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -132,9 +143,10 @@ test.serial('Read options from .releaserc.json', async t => {
test.serial('Read options from .releaserc.js', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -152,9 +164,10 @@ test.serial('Read options from .releaserc.js', async t => {
test.serial('Read options from release.config.js', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -172,15 +185,16 @@ test.serial('Read options from release.config.js', async t => {
test.serial('Prioritise CLI/API parameters over file configuration and git repo', async t => {
const release = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_pkg'},
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_pkg'},
branch: 'branch_pkg',
};
const options = {
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_cli'},
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_cli'},
branch: 'branch_cli',
repositoryUrl: 'http://cli-url.com/owner/package',
tagFormat: `cli\${version}`,
};
const pkg = {release, repository: 'git@hostname.com:owner/module.git'};
const pkg = {release, repository: 'git@host.null:owner/module.git'};
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
await gitCommits(['First']);
@@ -200,11 +214,11 @@ test.serial('Prioritise CLI/API parameters over file configuration and git repo'
test.serial('Read configuration from file path in "extends"', async t => {
const release = {extends: './shareable.json'};
const shareable = {
analyzeCommits: 'analyzeCommits',
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -222,18 +236,17 @@ test.serial('Read configuration from file path in "extends"', async t => {
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: './shareable.json',
generateNotes: './shareable.json',
getLastRelease: './shareable.json',
});
});
test.serial('Read configuration from module path in "extends"', async t => {
const release = {extends: 'shareable'};
const shareable = {
analyzeCommits: 'analyzeCommits',
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -251,24 +264,24 @@ test.serial('Read configuration from module path in "extends"', async t => {
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: 'shareable',
generateNotes: 'shareable',
getLastRelease: 'shareable',
});
});
test.serial('Read configuration from an array of paths in "extends"', async t => {
const release = {extends: ['./shareable1.json', './shareable2.json']};
const shareable1 = {
analyzeCommits: 'analyzeCommits1',
getLastRelease: {path: 'getLastRelease1', param: 'getLastRelease_param1'},
verifyRelease: 'verifyRelease1',
analyzeCommits: {path: 'analyzeCommits1', param: 'analyzeCommits_param1'},
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
};
const shareable2 = {
analyzeCommits: 'analyzeCommits2',
verifyRelease: 'verifyRelease2',
generateNotes: 'generateNotes2',
getLastRelease: {path: 'getLastRelease2', param: 'getLastRelease_param2'},
analyzeCommits: {path: 'analyzeCommits2', param: 'analyzeCommits_param2'},
branch: 'test_branch',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -285,11 +298,11 @@ test.serial('Read configuration from an array of paths in "extends"', async t =>
// Verify the plugins module is called with the plugin options from shareable1.json and shareable2.json
t.deepEqual(t.context.plugins.args[0][0], {...shareable1, ...shareable2});
t.deepEqual(t.context.plugins.args[0][1], {
verifyRelease1: './shareable1.json',
verifyRelease2: './shareable2.json',
generateNotes2: './shareable2.json',
analyzeCommits1: './shareable1.json',
analyzeCommits2: './shareable2.json',
generateNotes2: './shareable2.json',
getLastRelease1: './shareable1.json',
getLastRelease2: './shareable2.json',
});
});
@@ -305,7 +318,8 @@ test.serial('Prioritize configuration from config file over "extends"', async t
generateNotes: 'generateNotesShareable',
publish: [{path: 'publishShareable', param: 'publishShareable_param'}],
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -332,7 +346,7 @@ test.serial('Prioritize configuration from cli/API options over "extends"', asyn
extends: './shareable2.json',
branch: 'branch_opts',
publish: [{path: 'publishOpts', param: 'publishOpts_param'}],
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
};
const release = {
extends: './shareable1.json',
@@ -345,12 +359,13 @@ test.serial('Prioritize configuration from cli/API options over "extends"', asyn
generateNotes: 'generateNotesShareable1',
publish: [{path: 'publishShareable', param: 'publishShareable_param1'}],
branch: 'test_branch1',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
};
const shareable2 = {
analyzeCommits: 'analyzeCommits2',
publish: [{path: 'publishShareable', param: 'publishShareable_param2'}],
branch: 'test_branch2',
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -371,13 +386,14 @@ test.serial('Prioritize configuration from cli/API options over "extends"', asyn
test.serial('Allow to unset properties defined in shareable config with "null"', async t => {
const release = {
extends: './shareable.json',
getLastRelease: null,
analyzeCommits: null,
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
};
const shareable = {
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -389,28 +405,29 @@ test.serial('Allow to unset properties defined in shareable config with "null"',
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from shareable.json
t.deepEqual(options, {...omit(shareable, 'getLastRelease'), ...omit(release, ['extends', 'getLastRelease'])});
t.deepEqual(options, {...omit(shareable, 'analyzeCommits'), ...omit(release, ['extends', 'analyzeCommits'])});
// Verify the plugins module is called with the plugin options from shareable.json
t.deepEqual(t.context.plugins.args[0][0], {
...omit(shareable, 'getLastRelease'),
...omit(release, ['extends', 'getLastRelease']),
...omit(shareable, 'analyzeCommits'),
...omit(release, ['extends', 'analyzeCommits']),
});
t.deepEqual(t.context.plugins.args[0][1], {
generateNotes: './shareable.json',
getLastRelease: './shareable.json',
analyzeCommits: './shareable.json',
});
});
test.serial('Allow to unset properties defined in shareable config with "undefined"', async t => {
const release = {
extends: './shareable.json',
getLastRelease: undefined,
analyzeCommits: undefined,
branch: 'test_branch',
repositoryUrl: 'git+https://hostname.com/owner/module.git',
repositoryUrl: 'https://host.null/owner/module.git',
};
const shareable = {
generateNotes: 'generateNotes',
getLastRelease: {path: 'getLastRelease', param: 'getLastRelease_param'},
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
tagFormat: `v\${version}`,
};
// Create a git repository, set the current working directory at the root of the repo
@@ -423,15 +440,15 @@ test.serial('Allow to unset properties defined in shareable config with "undefin
const {options} = await t.context.getConfig();
// Verify the options contains the plugin config from shareable.json
t.deepEqual(options, {...omit(shareable, 'getLastRelease'), ...omit(release, ['extends', 'getLastRelease'])});
t.deepEqual(options, {...omit(shareable, 'analyzeCommits'), ...omit(release, ['extends', 'analyzeCommits'])});
// Verify the plugins module is called with the plugin options from shareable.json
t.deepEqual(t.context.plugins.args[0][0], {
...omit(shareable, 'getLastRelease'),
...omit(release, ['extends', 'getLastRelease']),
...omit(shareable, 'analyzeCommits'),
...omit(release, ['extends', 'analyzeCommits']),
});
t.deepEqual(t.context.plugins.args[0][1], {
generateNotes: './shareable.json',
getLastRelease: './shareable.json',
analyzeCommits: './shareable.json',
});
});
+195
View File
@@ -0,0 +1,195 @@
import test from 'ava';
import getAuthUrl from '../lib/get-git-auth-url';
import {gitRepo} from './helpers/git-utils';
// Save the current process.env
const envBackup = Object.assign({}, process.env);
// Save the current working diretory
const cwd = process.cwd();
test.beforeEach(() => {
delete process.env.GIT_CREDENTIALS;
delete process.env.GH_TOKEN;
delete process.env.GITHUB_TOKEN;
delete process.env.GL_TOKEN;
delete process.env.GITLAB_TOKEN;
delete process.env.BB_TOKEN;
delete process.env.BITBUCKET_TOKEN;
process.env.GIT_ASKPASS = 'echo';
process.env.GIT_TERMINAL_PROMPT = 0;
});
test.afterEach.always(() => {
// Restore process.env
process.env = envBackup;
// Restore the current working directory
process.chdir(cwd);
});
test.serial('Return the same "git" formatted URL if "gitCredentials" is not defined', async t => {
t.is(await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo.git'}), 'git@host.null:owner/repo.git');
});
test.serial('Return the same "https" formatted URL if "gitCredentials" is not defined', async t => {
t.is(await getAuthUrl({repositoryUrl: 'https://host.null/owner/repo.git'}), 'https://host.null/owner/repo.git');
});
test.serial(
'Return the "https" formatted URL if "gitCredentials" is not defined and repositoryUrl is a "git+https" URL',
async t => {
t.is(await getAuthUrl({repositoryUrl: 'git+https://host.null/owner/repo.git'}), 'https://host.null/owner/repo.git');
}
);
test.serial('Do not add trailing ".git" if not present in the origian URL', async t => {
t.is(await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo'}), 'git@host.null:owner/repo');
});
test.serial('Handle "https" URL with group and subgroup', async t => {
t.is(
await getAuthUrl({repositoryUrl: 'https://host.null/group/subgroup/owner/repo.git'}),
'https://host.null/group/subgroup/owner/repo.git'
);
});
test.serial('Handle "git" URL with group and subgroup', async t => {
t.is(
await getAuthUrl({repositoryUrl: 'git@host.null:group/subgroup/owner/repo.git'}),
'git@host.null:group/subgroup/owner/repo.git'
);
});
test.serial('Convert shorthand URL', async t => {
t.is(
await getAuthUrl({repositoryUrl: 'semanitc-release/semanitc-release'}),
'https://github.com/semanitc-release/semanitc-release.git'
);
});
test.serial('Convert GitLab shorthand URL', async t => {
t.is(
await getAuthUrl({repositoryUrl: 'gitlab:semanitc-release/semanitc-release'}),
'https://gitlab.com/semanitc-release/semanitc-release.git'
);
});
test.serial(
'Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL',
async t => {
process.env.GIT_CREDENTIALS = 'user:pass';
t.is(
await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo.git'}),
'https://user:pass@host.null/owner/repo.git'
);
}
);
test.serial(
'Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "https" URL',
async t => {
process.env.GIT_CREDENTIALS = 'user:pass';
t.is(
await getAuthUrl({repositoryUrl: 'https://host.null/owner/repo.git'}),
'https://user:pass@host.null/owner/repo.git'
);
}
);
test.serial(
'Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "http" URL',
async t => {
process.env.GIT_CREDENTIALS = 'user:pass';
t.is(
await getAuthUrl({repositoryUrl: 'http://host.null/owner/repo.git'}),
'http://user:pass@host.null/owner/repo.git'
);
}
);
test.serial(
'Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+https" URL',
async t => {
process.env.GIT_CREDENTIALS = 'user:pass';
t.is(
await getAuthUrl({repositoryUrl: 'git+https://host.null/owner/repo.git'}),
'https://user:pass@host.null/owner/repo.git'
);
}
);
test.serial(
'Return the "http" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git+http" URL',
async t => {
process.env.GIT_CREDENTIALS = 'user:pass';
t.is(
await getAuthUrl({repositoryUrl: 'git+http://host.null/owner/repo.git'}),
'http://user:pass@host.null/owner/repo.git'
);
}
);
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "GH_TOKEN"', async t => {
process.env.GH_TOKEN = 'token';
t.is(await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo.git'}), 'https://token@host.null/owner/repo.git');
});
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "GITHUB_TOKEN"', async t => {
process.env.GITHUB_TOKEN = 'token';
t.is(await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo.git'}), 'https://token@host.null/owner/repo.git');
});
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "GL_TOKEN"', async t => {
process.env.GL_TOKEN = 'token';
t.is(
await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo.git'}),
'https://gitlab-ci-token:token@host.null/owner/repo.git'
);
});
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "GITLAB_TOKEN"', async t => {
process.env.GITLAB_TOKEN = 'token';
t.is(
await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo.git'}),
'https://gitlab-ci-token:token@host.null/owner/repo.git'
);
});
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "BB_TOKEN"', async t => {
process.env.BB_TOKEN = 'token';
t.is(
await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo.git'}),
'https://x-token-auth:token@host.null/owner/repo.git'
);
});
test.serial('Return the "https" formatted URL if "gitCredentials" is defined with "BITBUCKET_TOKEN"', async t => {
process.env.BITBUCKET_TOKEN = 'token';
t.is(
await getAuthUrl({repositoryUrl: 'git@host.null:owner/repo.git'}),
'https://x-token-auth:token@host.null/owner/repo.git'
);
});
test.serial('Handle "https" URL with group and subgroup, with "GIT_CREDENTIALS"', async t => {
process.env.GIT_CREDENTIALS = 'user:pass';
t.is(
await getAuthUrl({repositoryUrl: 'https://host.null/group/subgroup/owner/repo.git'}),
'https://user:pass@host.null/group/subgroup/owner/repo.git'
);
});
test.serial('Handle "git" URL with group and subgroup, with "GIT_CREDENTIALS', async t => {
process.env.GIT_CREDENTIALS = 'user:pass';
t.is(
await getAuthUrl({repositoryUrl: 'git@host.null:group/subgroup/owner/repo.git'}),
'https://user:pass@host.null/group/subgroup/owner/repo.git'
);
});
test.serial('Do not add git credential to repositoryUrl if push is allowed', async t => {
process.env.GIT_CREDENTIALS = 'user:pass';
// Create a git repository, set the current working directory at the root of the repo
const repositoryUrl = await gitRepo(true);
t.is(await getAuthUrl({repositoryUrl}), repositoryUrl);
});
+159
View File
@@ -0,0 +1,159 @@
import test from 'ava';
import {stub} from 'sinon';
import getLastRelease from '../lib/get-last-release';
import {gitRepo, gitCommits, gitTagVersion, gitCheckout} from './helpers/git-utils';
// Save the current working diretory
const cwd = process.cwd();
test.beforeEach(t => {
// Stub the logger functions
t.context.log = stub();
t.context.logger = {log: t.context.log};
});
test.afterEach.always(() => {
// Restore the current working directory
process.chdir(cwd);
});
test.serial('Get the highest non-prerelease valid tag', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create some commits and tags
await gitCommits(['First']);
await gitTagVersion('foo');
const commits = await gitCommits(['Second']);
await gitTagVersion('v2.0.0');
await gitCommits(['Third']);
await gitTagVersion('v1.0.0');
await gitCommits(['Fourth']);
await gitTagVersion('v3.0');
await gitCommits(['Fifth']);
await gitTagVersion('v3.0.0-beta.1');
const result = await getLastRelease(`v\${version}`, t.context.logger);
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'v2.0.0', version: '2.0.0'});
t.deepEqual(t.context.log.args[0], ['Found git tag %s associated with version %s', 'v2.0.0', '2.0.0']);
});
test.serial('Get the highest tag in the history of the current branch', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commit to the master branch
await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
// Create the new branch 'other-branch' from master
await gitCheckout('other-branch');
// Add commit to the 'other-branch' branch
await gitCommits(['Second']);
// Create the tag corresponding to version 3.0.0
await gitTagVersion('v3.0.0');
// Checkout master
await gitCheckout('master', false);
// Add another commit to the master branch
const commits = await gitCommits(['Third']);
// Create the tag corresponding to version 2.0.0
await gitTagVersion('v2.0.0');
const result = await getLastRelease(`v\${version}`, t.context.logger);
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'v2.0.0', version: '2.0.0'});
});
test.serial('Match the tag name from the begining of the string', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
const commits = await gitCommits(['First']);
await gitTagVersion('prefix/v1.0.0');
await gitTagVersion('prefix/v2.0.0');
await gitTagVersion('other-prefix/v3.0.0');
const result = await getLastRelease(`prefix/v\${version}`, t.context.logger);
t.deepEqual(result, {gitHead: commits[0].hash, gitTag: 'prefix/v2.0.0', version: '2.0.0'});
});
test.serial('Return empty object if no valid tag is found', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create some commits and tags
await gitCommits(['First']);
await gitTagVersion('foo');
await gitCommits(['Second']);
await gitTagVersion('v2.0.x');
await gitCommits(['Third']);
await gitTagVersion('v3.0');
const result = await getLastRelease(`v\${version}`, t.context.logger);
t.deepEqual(result, {});
t.is(t.context.log.args[0][0], 'No git tag version found');
});
test.serial('Return empty object if no valid tag is found in history', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
await gitCommits(['First']);
await gitCheckout('other-branch');
await gitCommits(['Second']);
await gitTagVersion('v1.0.0');
await gitTagVersion('v2.0.0');
await gitTagVersion('v3.0.0');
await gitCheckout('master', false);
const result = await getLastRelease(`v\${version}`, t.context.logger);
t.deepEqual(result, {});
t.is(t.context.log.args[0][0], 'No git tag version found');
});
test.serial('Get the highest valid tag corresponding to the "tagFormat"', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Create some commits and tags
const [{hash: gitHead}] = await gitCommits(['First']);
await gitTagVersion('1.0.0');
t.deepEqual(await getLastRelease(`\${version}`, t.context.logger), {
gitHead,
gitTag: '1.0.0',
version: '1.0.0',
});
await gitTagVersion('foo-1.0.0-bar');
t.deepEqual(await getLastRelease(`foo-\${version}-bar`, t.context.logger), {
gitHead,
gitTag: 'foo-1.0.0-bar',
version: '1.0.0',
});
await gitTagVersion('foo-v1.0.0-bar');
t.deepEqual(await getLastRelease(`foo-v\${version}-bar`, t.context.logger), {
gitHead,
gitTag: 'foo-v1.0.0-bar',
version: '1.0.0',
});
await gitTagVersion('(.+)/1.0.0/(a-z)');
t.deepEqual(await getLastRelease(`(.+)/\${version}/(a-z)`, t.context.logger), {
gitHead,
gitTag: '(.+)/1.0.0/(a-z)',
version: '1.0.0',
});
await gitTagVersion('2.0.0-1.0.0-bar.1');
t.deepEqual(await getLastRelease(`2.0.0-\${version}-bar.1`, t.context.logger), {
gitHead,
gitTag: '2.0.0-1.0.0-bar.1',
version: '1.0.0',
});
await gitTagVersion('3.0.0-bar.1');
t.deepEqual(await getLastRelease(`\${version}-bar.1`, t.context.logger), {
gitHead,
gitTag: '3.0.0-bar.1',
version: '3.0.0',
});
});
+141 -29
View File
@@ -1,14 +1,30 @@
import test from 'ava';
import fileUrl from 'file-url';
import {gitTagHead, gitCommitTag, isCommitInHistory, unshallow, gitHead, repoUrl} from '../lib/git';
import tempy from 'tempy';
import {
gitTagHead,
isRefInHistory,
fetch,
gitHead,
repoUrl,
tag,
push,
gitTags,
isGitRepo,
verifyTagName,
isBranchUpToDate,
} from '../lib/git';
import {
gitRepo,
gitCommits,
gitCheckout,
gitTagVersion,
gitShallowClone,
gitLog,
gitGetCommits,
gitAddConfig,
gitCommitTag,
gitRemoteTagHead,
gitPush,
gitDetachedHead,
} from './helpers/git-utils';
// Save the current working diretory
@@ -27,7 +43,7 @@ test.serial('Get the last commit sha', async t => {
const result = await gitHead();
t.is(result.substring(0, 7), commits[0].hash);
t.is(result, commits[0].hash);
});
test.serial('Throw error if the last commit sha cannot be found', async t => {
@@ -37,7 +53,7 @@ test.serial('Throw error if the last commit sha cannot be found', async t => {
await t.throws(gitHead(), Error);
});
test.serial('Unshallow repository', async t => {
test.serial('Unshallow and fetch repository', async t => {
// Create a git repository, set the current working directory at the root of the repo
const repo = await gitRepo();
// Add commits to the master branch
@@ -46,20 +62,37 @@ test.serial('Unshallow repository', async t => {
await gitShallowClone(repo);
// Verify the shallow clone contains only one commit
t.is((await gitLog()).length, 1);
t.is((await gitGetCommits()).length, 1);
await unshallow();
await fetch(repo);
// Verify the shallow clone contains all the commits
t.is((await gitLog()).length, 2);
t.is((await gitGetCommits()).length, 2);
});
test.serial('Do not throw error when unshallow a complete repository', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
const repo = await gitRepo();
// Add commits to the master branch
await gitCommits(['First']);
await t.notThrows(unshallow());
await t.notThrows(fetch(repo));
});
test.serial('Fetch all tags on a detached head repository', async t => {
const repo = await gitRepo(true);
await gitCommits(['First']);
await gitTagVersion('v1.0.0');
await gitCommits(['Second']);
await gitTagVersion('v1.0.1');
const [commit] = await gitCommits(['Third']);
await gitTagVersion('v1.1.0');
await gitPush();
await gitDetachedHead(repo, commit.hash);
await fetch(repo);
t.deepEqual((await gitTags()).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0'].sort());
});
test.serial('Verify if the commit `sha` is in the direct history of the current branch', async t => {
@@ -73,11 +106,12 @@ test.serial('Verify if the commit `sha` is in the direct history of the current
const otherCommits = await gitCommits(['Second']);
await gitCheckout('master', false);
t.true(await isCommitInHistory(commits[0].hash));
t.false(await isCommitInHistory(otherCommits[0].hash));
t.true(await isRefInHistory(commits[0].hash));
t.falsy(await isRefInHistory(otherCommits[0].hash));
await t.throws(isRefInHistory('non-existant-sha'));
});
test.serial('Get the tag associated with a commit sha or "null" if the commit does not exists', async t => {
test.serial('Get the commit sha for a given tag or falsy if the tag does not exists', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
@@ -85,19 +119,7 @@ test.serial('Get the tag associated with a commit sha or "null" if the commit do
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
t.is(await gitCommitTag(commits[0].hash), 'v1.0.0');
t.falsy(await gitCommitTag('missing_sha'));
});
test.serial('Get the commit sha for a given tag or "null" if the tag does not exists', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
// Add commits to the master branch
const commits = await gitCommits(['First']);
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0');
t.is((await gitTagHead('v1.0.0')).substring(0, 7), commits[0].hash);
t.is(await gitTagHead('v1.0.0'), commits[0].hash);
t.falsy(await gitTagHead('missing_tag'));
});
@@ -117,12 +139,102 @@ test.serial('Return git remote repository url set while cloning', async t => {
// Create a clone
await gitShallowClone(repo);
t.is(await repoUrl(), fileUrl(repo));
t.is(await repoUrl(), repo);
});
test.serial('Return "undefined" if git repository url is not set', async t => {
test.serial('Return falsy if git repository url is not set', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
t.is(await repoUrl(), undefined);
t.falsy(await repoUrl());
});
test.serial('Add tag on head commit', async t => {
// Create a git repository, set the current working directory at the root of the repo
await gitRepo();
const commits = await gitCommits(['Test commit']);
await tag('tag_name');
await t.is(await gitCommitTag(commits[0].hash), 'tag_name');
});
test.serial('Push tag and commit to remote repository', async t => {
// Create a git repository with a remote, set the current working directory at the root of the repo
const repo = await gitRepo(true);
const commits = await gitCommits(['Test commit']);
await tag('tag_name');
await push(repo, 'master');
t.is(await gitRemoteTagHead(repo, 'tag_name'), commits[0].hash);
});
test.serial('Return "true" if in a Git repository', async t => {
// Create a git repository with a remote, set the current working directory at the root of the repo
await gitRepo(true);
t.true(await isGitRepo());
});
test.serial('Return falsy if not in a Git repository', async t => {
const dir = tempy.directory();
process.chdir(dir);
t.falsy(await isGitRepo());
});
test.serial('Return "true" for valid tag names', async t => {
t.true(await verifyTagName('1.0.0'));
t.true(await verifyTagName('v1.0.0'));
t.true(await verifyTagName('tag_name'));
t.true(await verifyTagName('tag/name'));
});
test.serial('Return falsy for invalid tag names', async t => {
t.falsy(await verifyTagName('?1.0.0'));
t.falsy(await verifyTagName('*1.0.0'));
t.falsy(await verifyTagName('[1.0.0]'));
t.falsy(await verifyTagName('1.0.0..'));
});
test.serial('Throws error if obtaining the tags fails', async t => {
const dir = tempy.directory();
process.chdir(dir);
await t.throws(gitTags());
});
test.serial('Return "true" if repository is up to date', async t => {
await gitRepo(true);
await gitCommits(['First']);
await gitPush();
t.true(await isBranchUpToDate('master'));
});
test.serial('Return falsy if repository is not up to date', async t => {
const repositoryUrl = await gitRepo(true);
const repoDir = process.cwd();
await gitCommits(['First']);
await gitCommits(['Second']);
await gitPush();
t.true(await isBranchUpToDate('master'));
await gitShallowClone(repositoryUrl);
await gitCommits(['Third']);
await gitPush();
process.chdir(repoDir);
t.falsy(await isBranchUpToDate('master'));
});
test.serial('Return "true" if local repository is ahead', async t => {
await gitRepo(true);
await gitCommits(['First']);
await gitPush();
await gitCommits(['Second']);
t.true(await isBranchUpToDate('master'));
});
+124 -65
View File
@@ -2,28 +2,60 @@ import tempy from 'tempy';
import execa from 'execa';
import fileUrl from 'file-url';
import pReduce from 'p-reduce';
import gitLogParser from 'git-log-parser';
import getStream from 'get-stream';
/**
* Commit message informations.
*
* @typedef {Object} Commit
* @property {string} branch The commit branch.
* @property {string} hash The commit hash.
* @property {string} message The commit message.
* @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.
* Create a temporary git repository.
* If `withRemote` is `true`, creates a bare repository, initialize it and create a shallow clone. Change the current working directory to the clone root.
* If `withRemote` is `false`, creates a regular repository and initialize it. Change the current working directory to the repository root.
*
* @return {string} The path of the repository.
* @param {Boolean} withRemote `true` to create a shallow clone of a bare repository.
* @param {String} [branch='master'] The branch to initialize.
* @return {String} The path of the clone if `withRemote` is `true`, the path of the repository otherwise.
*/
export async function gitRepo() {
export async function gitRepo(withRemote, branch = 'master') {
const dir = tempy.directory();
process.chdir(dir);
await execa('git', ['init']);
await gitCheckout('master');
return dir;
await execa('git', ['init'].concat(withRemote ? ['--bare'] : []));
if (withRemote) {
await initBareRepo(fileUrl(dir), branch);
await gitShallowClone(fileUrl(dir));
} else {
await gitCheckout(branch);
}
return fileUrl(dir);
}
/**
* Initialize an existing bare repository:
* - Clone the repository
* - Change the current working directory to the clone root
* - Create a default branch
* - Create an initial commits
* - Push to origin
*
* @param {String} repositoryUrl The URL of the bare repository.
* @param {String} [branch='master'] the branch to initialize.
*/
export async function initBareRepo(repositoryUrl, branch = 'master') {
const clone = tempy.directory();
await execa('git', ['clone', '--no-hardlinks', repositoryUrl, clone]);
process.chdir(clone);
await gitCheckout(branch);
await gitCommits(['Initial commit']);
await execa('git', ['push', repositoryUrl, branch]);
}
/**
@@ -34,122 +66,149 @@ export async function gitRepo() {
* @returns {Array<Commit>} The created commits, in reverse order (to match `git log` order).
*/
export async function gitCommits(messages) {
return (await pReduce(
await pReduce(
messages,
async (commits, msg) => {
const {stdout} = await execa('git', ['commit', '-m', msg, '--allow-empty', '--no-gpg-sign']);
const [, branch, hash, message] = /^\[(\w+)\(?.*?\)?(\w+)\] (.+)$/.exec(stdout);
commits.push({branch, hash, message});
const stdout = await execa.stdout('git', ['commit', '-m', msg, '--allow-empty', '--no-gpg-sign']);
const [, hash] = /^\[(?:\w+)\(?.*?\)?(\w+)\] .+(?:\n|$)/.exec(stdout);
commits.push(hash);
return commits;
},
[]
)).reverse();
);
return (await gitGetCommits()).slice(0, messages.length);
}
/**
* Amend a commit (rewriting the sha) on the current git repository.
* Get the list of parsed commits since a git reference.
*
* @param {string} messages commit message.
*
* @returns {Array<Commit>} the created commits.
* @param {String} [from] Git reference from which to seach commits.
* @return {Array<Object>} The list of parsed commits.
*/
export async function gitAmmendCommit(msg) {
const {stdout} = await execa('git', ['commit', '--amend', '-m', msg, '--allow-empty']);
const [, branch, hash, message] = /^\[(\w+)\(?.*?\)?(\w+)\] (.+)(.|\s)+$/.exec(stdout);
return {branch, hash, message};
export async function gitGetCommits(from) {
Object.assign(gitLogParser.fields, {hash: 'H', message: 'B', gitTags: 'd', committerDate: {key: 'ci', type: Date}});
return (await getStream.array(gitLogParser.parse({_: `${from ? from + '..' : ''}HEAD`}))).map(commit => {
commit.message = commit.message.trim();
commit.gitTags = commit.gitTags.trim();
return commit;
});
}
/**
* Checkout a branch on the current git repository.
*
* @param {string} branch Branch name.
* @param {boolean} create `true` to create the branche ans switch, `false` to only switch.
* @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.
* @return {String} The sha of the head commit in the current git repository.
*/
export async function gitHead() {
return (await execa('git', ['rev-parse', 'HEAD'])).stdout;
return execa.stdout('git', ['rev-parse', 'HEAD']);
}
/**
* Create a tag on the head commit in the current git repository.
*
* @param {string} tagName The tag name to create.
* @param {string} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit.
*
* @return {string} The commit sha of the created tag.
* @param {String} tagName The tag name to create.
* @param {String} [sha] The commit on which to create the tag. If undefined the tag is created on the last commit.
*/
export async function gitTagVersion(tagName, sha) {
await execa('git', sha ? ['tag', '-f', tagName, sha] : ['tag', tagName]);
return (await execa('git', ['rev-list', '-1', '--tags', tagName])).stdout;
}
/**
* @return {Array<string>} The list of tags from the current git repository.
*/
export async function gitTags() {
return (await execa('git', ['tag'])).stdout.split('\n').filter(tag => Boolean(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 => Boolean(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.
* @param {String} repositoryUrl The path of the repository to clone.
* @param {String} [branch='master'] the branch to clone.
* @param {Number} [depth=1] The number of commit to clone.
* @return {String} The path of the cloned repository.
*/
export async function gitShallowClone(origin, branch = 'master', depth = 1) {
export async function gitShallowClone(repositoryUrl, branch = 'master', depth = 1) {
const dir = tempy.directory();
process.chdir(dir);
await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, fileUrl(origin), dir]);
await execa('git', ['clone', '--no-hardlinks', '--no-tags', '-b', branch, '--depth', depth, repositoryUrl, dir]);
return dir;
}
/**
* Create a git repo with a detached head from another git repository and change the current working directory to the new repository root.
*
* @param {string} origin The path of the repository to clone.
* @param {number} head A commit sha of the origin repo that will become the detached head of the new one.
* @return {string} The path of the new repository.
* @param {String} repositoryUrl The path of the repository to clone.
* @param {Number} head A commit sha of the remote repo that will become the detached head of the new one.
* @return {String} The path of the new repository.
*/
export async function gitDetachedHead(origin, head) {
export async function gitDetachedHead(repositoryUrl, 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', ['remote', 'add', 'origin', repositoryUrl]);
await execa('git', ['fetch', repositoryUrl]);
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']);
}
/**
* Add a new Git configuration.
*
* @param {string} name Config name.
* @param {string} value Config value.
* @param {String} name Config name.
* @param {String} value Config value.
*/
export async function gitAddConfig(name, value) {
await execa('git', ['config', '--add', name, value]);
}
/**
* Get the first commit sha referenced by the tag `tagName` in the local repository.
*
* @param {String} tagName Tag name for which to retrieve the commit sha.
*
* @return {String} The sha of the commit associated with `tagName` on the local repository.
*/
export async function gitTagHead(tagName) {
return execa.stdout('git', ['rev-list', '-1', tagName]);
}
/**
* Get the first commit sha referenced by the tag `tagName` in the remote repository.
*
* @param {String} repositoryUrl The repository remote URL.
* @param {String} tagName The tag name to seach for.
* @return {String} The sha of the commit associated with `tagName` on the remote repository.
*/
export async function gitRemoteTagHead(repositoryUrl, tagName) {
return (await execa.stdout('git', ['ls-remote', '--tags', repositoryUrl, tagName]))
.split('\n')
.filter(tag => Boolean(tag))
.map(tag => tag.match(/^(\S+)/)[1])[0];
}
/**
* Get the tag associated with a commit sha.
*
* @param {String} gitHead The commit sha for which to retrieve the associated tag.
*
* @return {String} The tag associatedwith the sha in parameter or `null`.
*/
export async function gitCommitTag(gitHead) {
return execa.stdout('git', ['describe', '--tags', '--exact-match', gitHead]);
}
/**
* Push to the remote repository.
*
* @param {String} repositoryUrl The remote repository URL.
* @param {String} branch The branch to push.
* @throws {Error} if the push failed.
*/
export async function gitPush(repositoryUrl = 'origin', branch = 'master') {
await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`]);
}
+71
View File
@@ -0,0 +1,71 @@
import Docker from 'dockerode';
import getStream from 'get-stream';
import pRetry from 'p-retry';
import {initBareRepo, gitShallowClone} from './git-utils';
const IMAGE = 'pvdlg/docker-gitbox';
const SERVER_PORT = 80;
const HOST_PORT = 2080;
const SERVER_HOST = 'localhost';
const GIT_USERNAME = 'integration';
const GIT_PASSWORD = 'suchsecure';
const docker = new Docker();
let container;
const gitCredential = `${GIT_USERNAME}:${GIT_PASSWORD}`;
/**
* Download the `gitbox` Docker image, create a new container and start it.
*/
async function start() {
await getStream(await docker.pull(IMAGE));
container = await docker.createContainer({
Tty: true,
Image: IMAGE,
PortBindings: {[`${SERVER_PORT}/tcp`]: [{HostPort: `${HOST_PORT}`}]},
});
await container.start();
const exec = await container.exec({
Cmd: ['ng-auth', '-u', GIT_USERNAME, '-p', GIT_PASSWORD],
AttachStdout: true,
AttachStderr: true,
});
await exec.start();
}
/**
* Stop and remote the `mockserver` Docker container.
*/
async function stop() {
await container.stop();
await container.remove();
}
/**
* Initialize a remote repository and creates a shallow clone.
*
* @param {String} name The remote repository name.
* @param {String} [branch='master'] The branch to initialize.
* @param {String} [description=`Repository ${name}`] The repository description.
* @return {Object} The `repositoryUrl` (URL without auth) and `authUrl` (URL with auth).
*/
async function createRepo(name, branch = 'master', description = `Repository ${name}`) {
const exec = await container.exec({
Cmd: ['repo-admin', '-n', name, '-d', description],
AttachStdout: true,
AttachStderr: true,
});
await exec.start();
const repositoryUrl = `http://${SERVER_HOST}:${HOST_PORT}/git/${name}.git`;
const authUrl = `http://${gitCredential}@${SERVER_HOST}:${HOST_PORT}/git/${name}.git`;
// Retry as the server might take a few ms to make the repo available push
await pRetry(() => initBareRepo(authUrl, branch), {retries: 3, minTimeout: 500, factor: 2});
await gitShallowClone(authUrl);
return {repositoryUrl, authUrl};
}
export default {start, stop, gitCredential, createRepo};
-4
View File
@@ -12,8 +12,6 @@ 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(IMAGE));
@@ -39,8 +37,6 @@ async function start() {
/**
* Stop and remote the `mockserver` Docker container.
*
* @return {Promise} Promise that resolves when the container is stopped.
*/
async function stop() {
await container.stop();
-4
View File
@@ -16,8 +16,6 @@ let container;
/**
* Download the `npm-docker-couchdb` Docker image, create a new container and start it.
*
* @return {Promise} Promise that resolves when the container is started.
*/
async function start() {
await getStream(await docker.pull(IMAGE));
@@ -69,8 +67,6 @@ const authEnv = {
/**
* Stop and remote the `npm-docker-couchdb` Docker container.
*
* @return {Promise} Promise that resolves when the container is stopped.
*/
async function stop() {
await container.stop();
+57
View File
@@ -0,0 +1,57 @@
import test from 'ava';
import clearModule from 'clear-module';
test.beforeEach(() => {
process.env = {};
clearModule('../lib/hide-sensitive');
});
test.serial('Replace multiple sensitive environment variable values', t => {
process.env.SOME_PASSWORD = 'password';
process.env.SOME_TOKEN = 'secret';
t.is(
require('../lib/hide-sensitive')(
`https://user:${process.env.SOME_PASSWORD}@host.com?token=${process.env.SOME_TOKEN}`
),
'https://user:[secure]@host.com?token=[secure]'
);
});
test.serial('Replace multiple occurences of sensitive environment variable values', t => {
process.env.secretKey = 'secret';
t.is(
require('../lib/hide-sensitive')(`https://user:${process.env.secretKey}@host.com?token=${process.env.secretKey}`),
'https://user:[secure]@host.com?token=[secure]'
);
});
test.serial('Escape regexp special characters', t => {
process.env.SOME_CREDENTIALS = 'p$^{.+}\\w[a-z]o.*rd';
t.is(
require('../lib/hide-sensitive')(`https://user:${process.env.SOME_CREDENTIALS}@host.com`),
'https://user:[secure]@host.com'
);
});
test.serial('Accept "undefined" input', t => {
t.is(require('../lib/hide-sensitive')(), undefined);
});
test.serial('Return same string if no environment variable has to be replaced', t => {
t.is(require('../lib/hide-sensitive')('test'), 'test');
});
test.serial('Exclude empty environment variables from the regexp', t => {
process.env.SOME_PASSWORD = 'password';
process.env.SOME_TOKEN = '';
t.is(
require('../lib/hide-sensitive')(`https://user:${process.env.SOME_PASSWORD}@host.com?token=`),
'https://user:[secure]@host.com?token='
);
});
test.serial('Exclude empty environment variables from the regexp if there is only empty ones', t => {
process.env.SOME_PASSWORD = '';
process.env.SOME_TOKEN = ' \n ';
t.is(require('../lib/hide-sensitive')(`https://host.com?token=`), 'https://host.com?token=');
});
+622 -184
View File
File diff suppressed because it is too large Load Diff
+153 -367
View File
@@ -2,7 +2,8 @@ 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 {gitHead as getGitHead, gitTagHead, gitRepo, gitCommits, gitRemoteTagHead, gitPush} from './helpers/git-utils';
import gitbox from './helpers/gitbox';
import mockServer from './helpers/mockserver';
import npmRegistry from './helpers/npm-registry';
import semanticRelease from '..';
@@ -11,7 +12,7 @@ import semanticRelease from '..';
// Environment variables used with semantic-release cli (similar to what a user would setup)
const env = {
GH_TOKEN: 'github_token',
GH_TOKEN: gitbox.gitCredential,
GITHUB_URL: mockServer.url,
NPM_EMAIL: 'integration@test.com',
NPM_USERNAME: 'integration',
@@ -35,6 +36,8 @@ stub(process.stdout, 'write');
stub(process.stderr, 'write');
test.before(async () => {
// Start the Git server
await gitbox.start();
// Start the local NPM registry
await npmRegistry.start();
// Start Mock Server
@@ -42,17 +45,20 @@ test.before(async () => {
});
test.beforeEach(() => {
// Delete env paramaters that could have been set on the machine running the tests
// Delete environment variables that could have been set on the machine running the tests
delete process.env.NPM_TOKEN;
delete process.env.NPM_USERNAME;
delete process.env.NPM_PASSWORD;
delete process.env.NPM_EMAIL;
delete process.env.GH_TOKEN;
delete process.env.GITHUB_TOKEN;
delete process.env.GH_URL;
delete process.env.GITHUB_URL;
delete process.env.GH_PREFIX;
delete process.env.GITHUB_PREFIX;
delete process.env.GIT_CREDENTIALS;
delete process.env.GH_TOKEN;
delete process.env.GITHUB_TOKEN;
delete process.env.GL_TOKEN;
delete process.env.GITLAB_TOKEN;
process.env.TRAVIS = 'true';
process.env.CI = 'true';
@@ -61,7 +67,7 @@ test.beforeEach(() => {
// Delete all `npm_config` environment variable set by CI as they take precedence over the `.npmrc` because the process that runs the tests is started before the `.npmrc` is created
for (let i = 0, keys = Object.keys(process.env); i < keys.length; i++) {
if (keys[i].startsWith('npm_config')) {
if (keys[i].startsWith('npm_')) {
delete process.env[keys[i]];
}
}
@@ -75,6 +81,8 @@ test.afterEach.always(() => {
});
test.after.always(async () => {
// Stop the Git server
await gitbox.stop();
// Stop the local NPM registry
await npmRegistry.stop();
// Stop Mock Server
@@ -83,16 +91,17 @@ test.after.always(async () => {
test.serial('Release patch, minor and major versions', async t => {
const packageName = 'test-release';
const owner = 'test-owner';
const owner = 'git';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
const {repositoryUrl, authUrl} = await gitbox.createRepo(packageName);
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
repository: {url: repositoryUrl},
publishConfig: {registry: npmRegistry.url},
release: {success: false, fail: false},
});
// Create a npm-shrinkwrap.json file
await execa('npm', ['shrinkwrap'], {env: testEnv});
@@ -118,16 +127,6 @@ test.serial('Release patch, minor and major versions', async t => {
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
let getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
let createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
@@ -153,13 +152,14 @@ test.serial('Release patch, minor and major versions', async t => {
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
let gitHead = await getGitHead();
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/* Patch release */
@@ -169,16 +169,6 @@ test.serial('Release patch, minor and major versions', async t => {
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
@@ -204,13 +194,14 @@ test.serial('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
gitHead = await getGitHead();
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/* Minor release */
@@ -220,16 +211,6 @@ test.serial('Release patch, minor and major versions', async t => {
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
@@ -255,13 +236,14 @@ test.serial('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
gitHead = await getGitHead();
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
/* Major release */
@@ -271,16 +253,6 @@ test.serial('Release patch, minor and major versions', async t => {
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
@@ -306,121 +278,14 @@ test.serial('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
gitHead = await getGitHead();
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
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-git-packed';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git@github.com:${owner}/${packageName}.git`},
publishConfig: {registry: npmRegistry.url},
});
/* Initial release */
let version = '1.0.0';
let verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
let createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
let createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{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`));
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: testEnv})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
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';
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{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`));
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: testEnv})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
@@ -434,7 +299,7 @@ test.serial('Exit with 1 if a plugin is not found', async t => {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {analyzeCommits: 'non-existing-path'},
release: {analyzeCommits: 'non-existing-path', success: false, fail: false},
});
const {code, stderr} = await t.throws(execa(cli, [], {env}));
@@ -452,7 +317,7 @@ test.serial('Exit with 1 if a shareable config is not found', async t => {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {extends: 'non-existing-path'},
release: {extends: 'non-existing-path', success: false, fail: false},
});
const {code, stderr} = await t.throws(execa(cli, [], {env}));
@@ -463,7 +328,7 @@ test.serial('Exit with 1 if a shareable config is not found', async t => {
test.serial('Exit with 1 if a shareable config reference a not found plugin', async t => {
const packageName = 'test-config-ref-not-found';
const owner = 'test-repo';
const shareable = {getLastRelease: 'non-existing-path'};
const shareable = {analyzeCommits: 'non-existing-path'};
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
@@ -472,7 +337,7 @@ test.serial('Exit with 1 if a shareable config reference a not found plugin', as
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {extends: './shareable.json'},
release: {extends: './shareable.json', success: false, fail: false},
});
await writeJson('./shareable.json', shareable);
@@ -481,158 +346,19 @@ test.serial('Exit with 1 if a shareable config reference a not found plugin', as
t.regex(stderr, /Cannot find module/);
});
test.serial('Create a tag as a recovery solution for "ENOTINHISTORY" error', async t => {
const packageName = 'test-recovery';
const owner = 'test-repo';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitRepo();
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
publishConfig: {registry: npmRegistry.url},
});
/* Initial release */
let version = '1.0.0';
let verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
let getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
let createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
let createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{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`));
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: testEnv})).stdout
);
const head = await gitHead();
t.is(releasedGitHead, head);
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
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 */
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
t.log('Commit a 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, 1);
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';
verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{body: {ref: `refs/tags/v${version}`}, headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {ref: `refs/tags/${version}`}}
);
createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{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`));
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: testEnv})).stdout;
t.is(releasedVersion, version);
t.log(`+ released ${releasedVersion}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Dry-run', async t => {
const packageName = 'test-dry-run';
const owner = 'test-repo';
const owner = 'git';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
const {repositoryUrl} = await gitbox.createRepo(packageName);
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
repository: {url: repositoryUrl},
publishConfig: {registry: npmRegistry.url},
release: {success: false, fail: false},
});
/* Initial release */
@@ -656,17 +382,76 @@ test.serial('Dry-run', async t => {
await mockServer.verify(verifyMock);
});
test.serial('Pass options via CLI arguments', async t => {
const packageName = 'test-cli';
const owner = 'test-repo';
test.serial('Allow local releases with "noCi" option', async t => {
delete process.env.TRAVIS;
delete process.env.CI;
const packageName = 'test-no-ci';
const owner = 'git';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
const {repositoryUrl, authUrl} = await gitbox.createRepo(packageName);
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
repository: {url: repositoryUrl},
publishConfig: {registry: npmRegistry.url},
release: {success: false, fail: false},
});
/* Initial release */
const version = '1.0.0';
const verifyMock = await mockServer.mock(
`/repos/${owner}/${packageName}`,
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
const createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
body: {tag_name: `v${version}`, target_commitish: 'master', name: `v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {html_url: `release-url/${version}`}}
);
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ semantic-release --no-ci');
const {stdout, code} = await execa(cli, ['--no-ci'], {env});
t.regex(stdout, new RegExp(`Published GitHub release: release-url/${version}`));
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
t.is(code, 0);
// Verify package.json and has been updated
t.is((await readJson('./package.json')).version, version);
// Retrieve the published package from the registry and check version and gitHead
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
const gitHead = await getGitHead();
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Pass options via CLI arguments', async t => {
const packageName = 'test-cli';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
const {repositoryUrl, authUrl} = await gitbox.createRepo(packageName);
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: repositoryUrl},
publishConfig: {registry: npmRegistry.url},
});
@@ -677,7 +462,17 @@ test.serial('Pass options via CLI arguments', async t => {
t.log('$ semantic-release');
const {stdout, code} = await execa(
cli,
['--verify-conditions', '@semantic-release/npm', '--publish', '@semantic-release/npm', '--debug'],
[
'--verify-conditions',
'@semantic-release/npm',
'--publish',
'@semantic-release/npm',
`--success`,
false,
`--fail`,
false,
'--debug',
],
{env}
);
t.regex(stdout, new RegExp(`Publishing version ${version} to npm registry`));
@@ -690,22 +485,25 @@ test.serial('Pass options via CLI arguments', async t => {
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
const gitHead = await getGitHead();
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
});
test.serial('Run via JS API', async t => {
const packageName = 'test-js-api';
const owner = 'test-repo';
const owner = 'git';
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository and package.json');
await gitRepo();
const {repositoryUrl, authUrl} = await gitbox.createRepo(packageName);
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
repository: {url: repositoryUrl},
publishConfig: {registry: npmRegistry.url},
});
@@ -716,19 +514,6 @@ test.serial('Run via JS API', async t => {
{headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}]},
{body: {permissions: {push: true}}, method: 'GET'}
);
const getRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs/tags/v${version}`,
{},
{body: {}, statusCode: 404, method: 'GET'}
);
const createRefMock = await mockServer.mock(
`/repos/${owner}/${packageName}/git/refs`,
{
body: {ref: `refs/tags/v${version}`},
headers: [{name: 'Authorization', values: [`token ${env.GH_TOKEN}`]}],
},
{body: {ref: `refs/tags/${version}`}}
);
const createReleaseMock = await mockServer.mock(
`/repos/${owner}/${packageName}/releases`,
{
@@ -743,7 +528,7 @@ test.serial('Run via JS API', async t => {
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
t.log('$ Call semantic-release via API');
await semanticRelease();
await semanticRelease({fail: false, success: false});
// Verify package.json and has been updated
t.is((await readJson('./package.json')).version, version);
@@ -752,28 +537,28 @@ test.serial('Run via JS API', async t => {
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv})).stdout
);
const gitHead = await getGitHead();
t.is(releasedVersion, version);
t.is(releasedGitHead, await gitHead());
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(getRefMock);
await mockServer.verify(createRefMock);
await mockServer.verify(createReleaseMock);
});
test.serial('Log unexpected errors from plugins and exit with 1', async t => {
const packageName = 'test-unexpected-error';
const owner = '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();
const {repositoryUrl} = await gitbox.createRepo(packageName);
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {verifyConditions: pluginError},
repository: {url: repositoryUrl},
release: {verifyConditions: pluginError, fail: false, success: false},
});
/* Initial release */
@@ -792,16 +577,15 @@ test.serial('Log unexpected errors from plugins and exit with 1', async t => {
test.serial('Log errors inheriting SemanticReleaseError and exit with 1', async t => {
const packageName = 'test-inherited-error';
const owner = '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();
const {repositoryUrl} = await gitbox.createRepo(packageName);
// Create package.json in repository root
await writeJson('./package.json', {
name: packageName,
version: '0.0.0-dev',
repository: {url: `git+https://github.com/${owner}/${packageName}`},
release: {verifyConditions: pluginInheritedError},
repository: {url: repositoryUrl},
release: {verifyConditions: pluginInheritedError, fail: false, success: false},
});
/* Initial release */
@@ -814,23 +598,25 @@ test.serial('Log errors inheriting SemanticReleaseError and exit with 1', async
t.is(code, 1);
});
test.serial('CLI returns error code and prints help if called with a command', async t => {
t.log('$ semantic-release pre');
const {stdout, code} = await execa(cli, ['pre'], {env, reject: false});
t.regex(stdout, /Usage: semantic-release/);
t.is(code, 1);
});
test.serial('Exit with 1 if missing permission to push to the remote repository', async t => {
const packageName = 'unauthorized';
test.serial('CLI prints help if called with --help', async t => {
t.log('$ semantic-release --help');
const {stdout, code} = await execa(cli, ['--help'], {env});
t.regex(stdout, /Usage: semantic-release/);
t.is(code, 0);
});
// Create a git repository, set the current working directory at the root of the repo
t.log('Create git repository');
await gitbox.createRepo(packageName);
await writeJson('./package.json', {name: packageName, version: '0.0.0-dev'});
test.serial('CLI returns error code with invalid option', async t => {
t.log('$ semantic-release --unknown-option');
const {stderr, code} = await execa(cli, ['--unknown-option'], {env, reject: false});
t.regex(stderr, /unknown option/);
/* Initial release */
t.log('Commit a feature');
await gitCommits(['feat: Initial commit']);
await gitPush();
t.log('$ semantic-release');
const {stdout, code} = await execa(
cli,
['--repository-url', 'http://user:wrong_pass@localhost:2080/git/unauthorized.git'],
{env: {...env, GH_TOKEN: 'user:wrong_pass'}, reject: false}
);
// Verify the type and message are logged
t.regex(stdout, /EGITNOPERMISSION/);
t.is(code, 1);
});
-101
View File
@@ -1,101 +0,0 @@
import test from 'ava';
import definitions from '../../lib/plugins/definitions';
test('The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(definitions.verifyConditions.config.validator({}));
t.false(definitions.verifyConditions.config.validator({path: null}));
t.true(definitions.verifyConditions.config.validator({path: 'plugin-path.js'}));
t.true(definitions.verifyConditions.config.validator());
t.true(definitions.verifyConditions.config.validator('plugin-path.js'));
t.true(definitions.verifyConditions.config.validator(() => {}));
t.true(definitions.verifyConditions.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "getLastRelease" plugin is mandatory, and must be a single plugin definition', t => {
t.false(definitions.getLastRelease.config.validator({}));
t.false(definitions.getLastRelease.config.validator({path: null}));
t.false(definitions.getLastRelease.config.validator([]));
t.false(definitions.getLastRelease.config.validator());
t.true(definitions.getLastRelease.config.validator({path: 'plugin-path.js'}));
t.true(definitions.getLastRelease.config.validator('plugin-path.js'));
t.true(definitions.getLastRelease.config.validator(() => {}));
});
test('The "analyzeCommits" plugin is mandatory, and must be a single plugin definition', t => {
t.false(definitions.analyzeCommits.config.validator({}));
t.false(definitions.analyzeCommits.config.validator({path: null}));
t.false(definitions.analyzeCommits.config.validator([]));
t.false(definitions.analyzeCommits.config.validator());
t.true(definitions.analyzeCommits.config.validator({path: 'plugin-path.js'}));
t.true(definitions.analyzeCommits.config.validator('plugin-path.js'));
t.true(definitions.analyzeCommits.config.validator(() => {}));
});
test('The "verifyRelease" plugin, if defined, must be a single or an array of plugins definition', t => {
t.false(definitions.verifyRelease.config.validator({}));
t.false(definitions.verifyRelease.config.validator({path: null}));
t.true(definitions.verifyRelease.config.validator({path: 'plugin-path.js'}));
t.true(definitions.verifyRelease.config.validator());
t.true(definitions.verifyRelease.config.validator('plugin-path.js'));
t.true(definitions.verifyRelease.config.validator(() => {}));
t.true(definitions.verifyRelease.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "generateNotes" plugin, if defined, must be a single plugin definition', t => {
t.false(definitions.generateNotes.config.validator({}));
t.false(definitions.generateNotes.config.validator({path: null}));
t.false(definitions.generateNotes.config.validator([]));
t.true(definitions.generateNotes.config.validator());
t.true(definitions.generateNotes.config.validator({path: 'plugin-path.js'}));
t.true(definitions.generateNotes.config.validator('plugin-path.js'));
t.true(definitions.generateNotes.config.validator(() => {}));
});
test('The "publish" plugin is mandatory, and must be a single or an array of plugins definition', t => {
t.false(definitions.publish.config.validator({}));
t.false(definitions.publish.config.validator({path: null}));
t.false(definitions.publish.config.validator());
t.true(definitions.publish.config.validator({path: 'plugin-path.js'}));
t.true(definitions.publish.config.validator('plugin-path.js'));
t.true(definitions.publish.config.validator(() => {}));
t.true(definitions.publish.config.validator([{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
});
test('The "getLastRelease" plugin output if defined, must be an object with a valid semver version in the "version" property and the corresponding git reference in "gitHead" property', t => {
t.false(definitions.getLastRelease.output.validator('string'));
t.false(definitions.getLastRelease.output.validator(1));
t.false(definitions.getLastRelease.output.validator({version: 'v1.0.0'}));
t.false(definitions.getLastRelease.output.validator({version: 'invalid'}));
t.true(definitions.getLastRelease.output.validator());
t.true(definitions.getLastRelease.output.validator({}));
t.true(definitions.getLastRelease.output.validator({version: 'v1.0.0', gitHead: '123'}));
t.true(definitions.getLastRelease.output.validator({version: '1.0.0', gitHead: '123'}));
t.true(definitions.getLastRelease.output.validator({version: null}));
});
test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', t => {
t.false(definitions.analyzeCommits.output.validator('invalid'));
t.false(definitions.analyzeCommits.output.validator(1));
t.false(definitions.analyzeCommits.output.validator({}));
t.true(definitions.analyzeCommits.output.validator());
t.true(definitions.analyzeCommits.output.validator(null));
t.true(definitions.analyzeCommits.output.validator('major'));
});
test('The "generateNotes" plugin output, if defined, must be a string', t => {
t.false(definitions.generateNotes.output.validator(1));
t.false(definitions.generateNotes.output.validator({}));
t.true(definitions.generateNotes.output.validator());
t.true(definitions.generateNotes.output.validator(null));
t.true(definitions.generateNotes.output.validator(''));
t.true(definitions.generateNotes.output.validator('string'));
});
+83 -21
View File
@@ -12,15 +12,17 @@ test.beforeEach(t => {
test('Normalize and load plugin from string', t => {
const plugin = normalize('verifyConditions', {}, {}, './test/fixtures/plugin-noop', t.context.logger);
t.is(plugin.pluginName, './test/fixtures/plugin-noop');
t.is(typeof plugin, 'function');
t.deepEqual(t.context.log.args[0], ['Load plugin %s from %s', 'verifyConditions', './test/fixtures/plugin-noop']);
t.deepEqual(t.context.log.args[0], ['Load plugin "%s" from %s', 'verifyConditions', './test/fixtures/plugin-noop']);
});
test('Normalize and load plugin from object', t => {
const plugin = normalize('publish', {}, {}, {path: './test/fixtures/plugin-noop'}, t.context.logger);
t.is(plugin.pluginName, './test/fixtures/plugin-noop');
t.is(typeof plugin, 'function');
t.deepEqual(t.context.log.args[0], ['Load plugin %s from %s', 'publish', './test/fixtures/plugin-noop']);
t.deepEqual(t.context.log.args[0], ['Load plugin "%s" from %s', 'publish', './test/fixtures/plugin-noop']);
});
test('Normalize and load plugin from a base file path', t => {
@@ -32,18 +34,50 @@ test('Normalize and load plugin from a base file path', t => {
t.context.logger
);
t.is(plugin.pluginName, './plugin-noop');
t.is(typeof plugin, 'function');
t.deepEqual(t.context.log.args[0], [
'Load plugin %s from %s in shareable config %s',
'Load plugin "%s" from %s in shareable config %s',
'verifyConditions',
'./plugin-noop',
'./test/fixtures',
]);
});
test('Normalize and load plugin from function', t => {
const plugin = normalize('', {}, {}, () => {}, t.context.logger);
test('Wrap plugin in a function that add the "pluginName" to the error"', async t => {
const plugin = normalize(
'verifyConditions',
{'./plugin-error': './test/fixtures'},
{},
'./plugin-error',
t.context.logger
);
const error = await t.throws(plugin());
t.is(error.pluginName, './plugin-error');
});
test('Wrap plugin in a function that add the "pluginName" to multiple errors"', async t => {
const plugin = normalize(
'verifyConditions',
{'./plugin-errors': './test/fixtures'},
{},
'./plugin-errors',
t.context.logger
);
const errors = [...(await t.throws(plugin()))];
for (const error of errors) {
t.is(error.pluginName, './plugin-errors');
}
});
test('Normalize and load plugin from function', t => {
const pluginFunction = () => {};
const plugin = normalize('', {}, {}, pluginFunction, t.context.logger);
t.is(plugin.pluginName, '[Function: pluginFunction]');
t.is(typeof plugin, 'function');
});
@@ -51,21 +85,51 @@ test('Normalize and load plugin that retuns multiple functions', t => {
const plugin = normalize('verifyConditions', {}, {}, './test/fixtures/multi-plugin', t.context.logger);
t.is(typeof plugin, 'function');
t.deepEqual(t.context.log.args[0], ['Load plugin %s from %s', 'verifyConditions', './test/fixtures/multi-plugin']);
t.deepEqual(t.context.log.args[0], ['Load plugin "%s" from %s', 'verifyConditions', './test/fixtures/multi-plugin']);
});
test('Wrap plugin in a function that validate the output of the plugin', async t => {
const pluginFunction = stub().resolves(1);
const plugin = normalize('', {}, {}, pluginFunction, t.context.logger, {
validator: output => output === 1,
message: 'The output must be 1.',
});
test('Wrap "analyzeCommits" plugin in a function that validate the output of the plugin', async t => {
const analyzeCommits = stub().resolves(2);
const plugin = normalize('analyzeCommits', {}, {}, analyzeCommits, t.context.logger);
await t.notThrows(plugin());
const error = await t.throws(plugin());
pluginFunction.resolves(2);
const error = await t.throws(plugin(), Error);
t.is(error.message, 'The output must be 1. Received: 2');
t.is(error.code, 'EANALYZECOMMITSOUTPUT');
t.is(error.name, 'SemanticReleaseError');
t.truthy(error.message);
t.truthy(error.details);
t.regex(error.details, /2/);
});
test('Wrap "generateNotes" plugin in a function that validate the output of the plugin', async t => {
const generateNotes = stub().resolves(2);
const plugin = normalize('generateNotes', {}, {}, generateNotes, t.context.logger);
const error = await t.throws(plugin());
t.is(error.code, 'EGENERATENOTESOUTPUT');
t.is(error.name, 'SemanticReleaseError');
t.truthy(error.message);
t.truthy(error.details);
t.regex(error.details, /2/);
});
test('Wrap "publish" plugin in a function that validate the output of the plugin', async t => {
const plugin = normalize(
'publish',
{'./plugin-identity': './test/fixtures'},
{},
'./plugin-identity',
t.context.logger
);
const error = await t.throws(plugin(2));
t.is(error.code, 'EPUBLISHOUTPUT');
t.is(error.name, 'SemanticReleaseError');
t.truthy(error.message);
t.truthy(error.details);
t.regex(error.details, /2/);
});
test('Plugin is called with "pluginConfig" (omitting "path", adding global config) and input', async t => {
@@ -127,12 +191,10 @@ test('Always pass a defined "pluginConfig" for plugin defined with path', async
test('Throws an error if the plugin return an object without the expected plugin function', t => {
const error = t.throws(() => normalize('inexistantPlugin', {}, {}, './test/fixtures/multi-plugin', t.context.logger));
t.is(error.code, 'EPLUGINCONF');
t.is(error.code, 'EPLUGIN');
t.is(error.name, 'SemanticReleaseError');
t.is(
error.message,
'The inexistantPlugin plugin must be a function, or an object with a function in the property inexistantPlugin.'
);
t.truthy(error.message);
t.truthy(error.details);
});
test('Throws an error if the plugin is not found', t => {
+122 -7
View File
@@ -1,5 +1,6 @@
import test from 'ava';
import {stub} from 'sinon';
import AggregateError from 'aggregate-error';
import pipeline from '../../lib/plugins/pipeline';
test('Execute each function in series passing the same input', async t => {
@@ -12,24 +13,74 @@ test('Execute each function in series passing the same input', async t => {
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
t.true(step3.calledWith(0));
t.true(step1.calledBefore(step2));
t.true(step2.calledBefore(step3));
});
test('Execute each function in series passing a transformed input', async t => {
test('Execute each function in series passing a transformed input from "getNextInput"', async t => {
const step1 = stub().resolves(1);
const step2 = stub().resolves(2);
const step3 = stub().resolves(3);
const step4 = stub().resolves(4);
const getNextInput = (lastResult, result) => lastResult + result;
const result = await pipeline([step1, step2, step3])(0, (prevResult, result) => prevResult + result);
const result = await pipeline([step1, step2, step3, step4], {settleAll: false, getNextInput})(0);
t.deepEqual(result, [1, 2, 3]);
t.deepEqual(result, [1, 2, 3, 4]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(1));
t.true(step3.calledWith(3));
t.true(step2.calledWith(0 + 1));
t.true(step3.calledWith(0 + 1 + 2));
t.true(step4.calledWith(0 + 1 + 2 + 3));
t.true(step1.calledBefore(step2));
t.true(step2.calledBefore(step3));
t.true(step3.calledBefore(step4));
});
test('Stop execution and throw error is a step rejects', async t => {
test('Execute each function in series passing the "lastResult" and "result" to "getNextInput"', async t => {
const step1 = stub().resolves(1);
const step2 = stub().throws(new Error('test error'));
const step2 = stub().resolves(2);
const step3 = stub().resolves(3);
const step4 = stub().resolves(4);
const getNextInput = stub().returnsArg(0);
const result = await pipeline([step1, step2, step3, step4], {settleAll: false, getNextInput})(5);
t.deepEqual(result, [1, 2, 3, 4]);
t.deepEqual(getNextInput.args, [[5, 1], [5, 2], [5, 3], [5, 4]]);
});
test('Execute each function in series calling "transform" to modify the results', async t => {
const step1 = stub().resolves(1);
const step2 = stub().resolves(2);
const step3 = stub().resolves(3);
const step4 = stub().resolves(4);
const getNextInput = stub().returnsArg(0);
const transform = stub().callsFake(result => result + 1);
const result = await pipeline([step1, step2, step3, step4], {getNextInput, transform})(5);
t.deepEqual(result, [1 + 1, 2 + 1, 3 + 1, 4 + 1]);
t.deepEqual(getNextInput.args, [[5, 1 + 1], [5, 2 + 1], [5, 3 + 1], [5, 4 + 1]]);
});
test('Execute each function in series calling "transform" to modify the results with "settleAll"', async t => {
const step1 = stub().resolves(1);
const step2 = stub().resolves(2);
const step3 = stub().resolves(3);
const step4 = stub().resolves(4);
const getNextInput = stub().returnsArg(0);
const transform = stub().callsFake(result => result + 1);
const result = await pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput, transform})(5);
t.deepEqual(result, [1 + 1, 2 + 1, 3 + 1, 4 + 1]);
t.deepEqual(getNextInput.args, [[5, 1 + 1], [5, 2 + 1], [5, 3 + 1], [5, 4 + 1]]);
});
test('Stop execution and throw error if a step rejects', async t => {
const step1 = stub().resolves(1);
const step2 = stub().rejects(new Error('test error'));
const step3 = stub().resolves(3);
const error = await t.throws(pipeline([step1, step2, step3])(0), Error);
@@ -38,3 +89,67 @@ test('Stop execution and throw error is a step rejects', async t => {
t.true(step2.calledWith(0));
t.true(step3.notCalled);
});
test('Throw all errors from the first step throwing an AggregateError', async t => {
const error1 = new Error('test error 1');
const error2 = new Error('test error 2');
const step1 = stub().resolves(1);
const step2 = stub().rejects(new AggregateError([error1, error2]));
const step3 = stub().resolves(3);
const errors = await t.throws(pipeline([step1, step2, step3])(0));
t.deepEqual([...errors], [error1, error2]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
t.true(step3.notCalled);
});
test('Execute all even if a Promise rejects', async t => {
const error1 = new Error('test error 1');
const error2 = new Error('test error 2');
const step1 = stub().resolves(1);
const step2 = stub().rejects(error1);
const step3 = stub().rejects(error2);
const errors = await t.throws(pipeline([step1, step2, step3], {settleAll: true})(0));
t.deepEqual([...errors], [error1, error2]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
t.true(step3.calledWith(0));
});
test('Throw all errors from all steps throwing an AggregateError', async t => {
const error1 = new Error('test error 1');
const error2 = new Error('test error 2');
const error3 = new Error('test error 3');
const error4 = new Error('test error 4');
const step1 = stub().rejects(new AggregateError([error1, error2]));
const step2 = stub().rejects(new AggregateError([error3, error4]));
const errors = await t.throws(pipeline([step1, step2], {settleAll: true})(0));
t.deepEqual([...errors], [error1, error2, error3, error4]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
});
test('Execute each function in series passing a transformed input even if a step rejects', async t => {
const error2 = new Error('test error 2');
const error3 = new Error('test error 3');
const step1 = stub().resolves(1);
const step2 = stub().rejects(error2);
const step3 = stub().rejects(error3);
const step4 = stub().resolves(4);
const getNextInput = (prevResult, result) => prevResult + result;
const errors = await t.throws(pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput})(0));
t.deepEqual([...errors], [error2, error3]);
t.true(step1.calledWith(0));
t.true(step2.calledWith(0 + 1));
t.true(step3.calledWith(0 + 1 + error2));
t.true(step4.calledWith(0 + 1 + error2 + error3));
});
+39 -28
View File
@@ -24,18 +24,20 @@ test('Export default plugins', t => {
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.prepare, 'function');
t.is(typeof plugins.publish, 'function');
t.is(typeof plugins.success, 'function');
t.is(typeof plugins.fail, 'function');
});
test('Export plugins based on config', t => {
const plugins = getPlugins(
{
verifyConditions: ['./test/fixtures/plugin-noop', {path: './test/fixtures/plugin-noop'}],
getLastRelease: './test/fixtures/plugin-noop',
generateNotes: './test/fixtures/plugin-noop',
analyzeCommits: {path: './test/fixtures/plugin-noop'},
verifyRelease: () => {},
},
@@ -45,11 +47,13 @@ test('Export plugins based on config', t => {
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.prepare, 'function');
t.is(typeof plugins.publish, 'function');
t.is(typeof plugins.success, 'function');
t.is(typeof plugins.fail, 'function');
});
test.serial('Export plugins loaded from the dependency of a shareable config module', async t => {
@@ -64,7 +68,7 @@ test.serial('Export plugins loaded from the dependency of a shareable config mod
const plugins = getPlugins(
{
verifyConditions: ['custom-plugin', {path: 'custom-plugin'}],
getLastRelease: 'custom-plugin',
generateNotes: 'custom-plugin',
analyzeCommits: {path: 'custom-plugin'},
verifyRelease: () => {},
},
@@ -74,11 +78,13 @@ test.serial('Export plugins loaded from the dependency of a shareable config mod
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.prepare, 'function');
t.is(typeof plugins.publish, 'function');
t.is(typeof plugins.success, 'function');
t.is(typeof plugins.fail, 'function');
});
test.serial('Export plugins loaded from the dependency of a shareable config file', async t => {
@@ -90,7 +96,7 @@ test.serial('Export plugins loaded from the dependency of a shareable config fil
const plugins = getPlugins(
{
verifyConditions: ['./plugin/plugin-noop', {path: './plugin/plugin-noop'}],
getLastRelease: './plugin/plugin-noop',
generateNotes: './plugin/plugin-noop',
analyzeCommits: {path: './plugin/plugin-noop'},
verifyRelease: () => {},
},
@@ -100,19 +106,32 @@ test.serial('Export plugins loaded from the dependency of a shareable config fil
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, 'function');
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.verifyRelease, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.prepare, 'function');
t.is(typeof plugins.publish, 'function');
t.is(typeof plugins.success, 'function');
t.is(typeof plugins.fail, 'function');
});
test('Use default when only options are passed for a single plugin', t => {
const plugins = getPlugins({getLastRelease: {}, analyzeCommits: {}}, {}, t.context.logger);
const analyzeCommits = {};
const generateNotes = {};
const success = () => {};
const fail = [() => {}];
const plugins = getPlugins({analyzeCommits, generateNotes, success, fail}, {}, t.context.logger);
// Verify the module returns a function for each plugin
t.is(typeof plugins.getLastRelease, 'function');
t.is(typeof plugins.analyzeCommits, 'function');
t.is(typeof plugins.generateNotes, 'function');
t.is(typeof plugins.success, 'function');
t.is(typeof plugins.fail, 'function');
// Verify only the plugins defined as an object with no `path` are set to the default value
t.falsy(success.path);
t.falsy(fail.path);
});
test('Merge global options with plugin options', async t => {
@@ -120,37 +139,29 @@ test('Merge global options with plugin options', async t => {
{
globalOpt: 'global',
otherOpt: 'globally-defined',
getLastRelease: {path: './test/fixtures/plugin-result-config', localOpt: 'local', otherOpt: 'locally-defined'},
verifyRelease: {path: './test/fixtures/plugin-result-config', localOpt: 'local', otherOpt: 'locally-defined'},
},
{},
t.context.logger
);
const result = await plugins.getLastRelease();
const [result] = await plugins.verifyRelease();
t.deepEqual(result.pluginConfig, {localOpt: 'local', globalOpt: 'global', otherOpt: 'locally-defined'});
});
test('Throw an error if plugin configuration is missing a path for plugin pipeline', t => {
const error = t.throws(() => getPlugins({verifyConditions: {}}, {}, t.context.logger));
test('Throw an error if plugins configuration are missing a path for plugin pipeline', t => {
const errors = [...t.throws(() => getPlugins({verifyConditions: {}}, {}, t.context.logger))];
t.is(error.name, 'SemanticReleaseError');
t.is(error.code, 'EPLUGINCONF');
t.is(
error.message,
'The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.'
);
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EPLUGINCONF');
});
test('Throw an error if an array of plugin configuration is missing a path for plugin pipeline', t => {
const error = t.throws(() =>
getPlugins({verifyConditions: [{path: '@semantic-release/npm'}, {}]}, {}, t.context.logger)
);
const errors = [
...t.throws(() => getPlugins({verifyConditions: [{path: '@semantic-release/npm'}, {}]}, {}, t.context.logger)),
];
t.is(error.name, 'SemanticReleaseError');
t.is(error.code, 'EPLUGINCONF');
t.is(
error.message,
'The "verifyConditions" plugin, if defined, must be a single or an array of plugins definition. A plugin definition is either a string or an object with a path property.'
);
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EPLUGINCONF');
});
+85
View File
@@ -0,0 +1,85 @@
import test from 'ava';
import tempy from 'tempy';
import verify from '../lib/verify';
import {gitRepo} from './helpers/git-utils';
// Save the current process.env
const envBackup = Object.assign({}, process.env);
// Save the current working diretory
const cwd = process.cwd();
test.beforeEach(() => {
// Delete environment variables that could have been set on the machine running the tests
delete process.env.GIT_CREDENTIALS;
delete process.env.GH_TOKEN;
delete process.env.GITHUB_TOKEN;
delete process.env.GL_TOKEN;
delete process.env.GITLAB_TOKEN;
});
test.afterEach.always(() => {
// Restore process.env
process.env = envBackup;
// Restore the current working directory
process.chdir(cwd);
});
test.serial('Throw a AggregateError', async t => {
await gitRepo();
const errors = [...(await t.throws(verify({})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ENOREPOURL');
t.is(errors[1].name, 'SemanticReleaseError');
t.is(errors[1].code, 'EINVALIDTAGFORMAT');
t.is(errors[2].name, 'SemanticReleaseError');
t.is(errors[2].code, 'ETAGNOVERSION');
});
test.serial('Throw a SemanticReleaseError if does not run on a git repository', async t => {
const dir = tempy.directory();
process.chdir(dir);
const errors = [...(await t.throws(verify({})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ENOGITREPO');
});
test.serial('Throw a SemanticReleaseError if the "tagFormat" is not valid', async t => {
const repositoryUrl = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `?\${version}`};
const errors = [...(await t.throws(verify(options, 'master', t.context.logger)))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EINVALIDTAGFORMAT');
});
test.serial('Throw a SemanticReleaseError if the "tagFormat" does not contains the "version" variable', async t => {
const repositoryUrl = await gitRepo(true);
const options = {repositoryUrl, tagFormat: 'test'};
const errors = [...(await t.throws(verify(options, 'master', t.context.logger)))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ETAGNOVERSION');
});
test.serial('Throw a SemanticReleaseError if the "tagFormat" contains multiple "version" variables', async t => {
const repositoryUrl = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `\${version}v\${version}`};
const errors = [...(await t.throws(verify(options)))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ETAGNOVERSION');
});
test.serial('Return "true" if all verification pass', async t => {
const repositoryUrl = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `v\${version}`, branch: 'master'};
await t.notThrows(verify(options));
});