Compare commits

...
154 Commits
Author SHA1 Message Date
greenkeeper[bot]andPierre Vanduynslager 3c2fe35ded fix(package): update yargs to version 14.0.0 2019-08-19 19:50:25 -04:00
Florian KellerandGregor Martynus 1eb302545e fix(definitions): Repository documentation links 2019-08-16 10:17:24 -07:00
GoisandPierre Vanduynslager d2230fab7e docs: broken link docs/03-recipes/travis.md
Fixed the link for `setup with semantic-release-cli.` in 'Environment Variables' section, refering a old file of this repo,
2019-08-13 14:15:28 -04:00
greenkeeper[bot]andGregor Martynus 391af986be fix(package): update hosted-git-info to version 3.0.0 2019-08-12 11:21:36 -07:00
Crhistian RamirezandGregor Martynus d45d8b6170 docs: fix typo 2019-08-11 09:32:29 -07:00
Pierre Vanduynslager 519df0d5c1 chore: remove commitizen from our dependencies 2019-08-09 14:13:09 -04:00
EmandGregor Martynus e168802379 docs: tried to fix #1250 2019-08-05 21:19:32 -07:00
Alvaro Pinot @alvaropinotandGregor Martynus 3bd63eb6a8 docs: update semantic-release-cli broken link
* Remove extra `01-`
2019-08-05 21:18:30 -07:00
Philipp RudloffandGregor Martynus 9a8a36ce45 fix(package): update dependency lodash to address security warnings (#1253) 2019-08-05 21:17:22 -07:00
Emmanuel SciaraandGregor Martynus 7cb5446bb5 docs: corrections and further clarifications
- (correction) removed comments from code samples.
-(correction) remove recommendation for global
install on CI environemnts.
- Synched README.md and SUMMARY.md
2019-07-31 14:40:10 -07:00
Emmanuel SciaraandGregor Martynus 5a5eaec3da docs: made doc file org clearer and augmented content
This is a first step to improving the doc: - renamed directories; - augmented a fair bit of content.
To be continued
2019-07-31 14:40:10 -07:00
Jed MaoandGregor Martynus 2d2bb38e61 docs(shareable-configurations-list): add @jedmao/semantic-release-npm-github-config (#1222) 2019-07-31 08:57:19 -07:00
Emmanuel SciaraandGregor Martynus cd00c2dc86 docs(contributing): copy/pasted "Use gitbook locally" instruction from original url 2019-07-30 17:44:23 -07:00
Emmanuel SciaraandGregor Martynus a3da21a544 docs(contributing): added instructions on how to run gitbook locally 2019-07-30 17:44:23 -07:00
Emmanuel SciaraandGregor Martynus 813e5f65ed docs: synched README.md and SUMMARY.md 2019-07-30 16:13:59 -07:00
Emmanuel SciaraandGregor Martynus b08486327d docs: cleaned "Developer guide" section navigation 2019-07-30 16:13:59 -07:00
Emmanuel SciaraandGregor Martynus 3f22978623 docs: repared broken links to "CI configuration recipes" 2019-07-30 16:13:59 -07:00
Emmanuel SciaraandGregor Martynus a8f8bffa37 docs(recipes): cleaned doc and navigation
Corrected inconsistancies between the sidebar and the actual pages. Remove non existing pages.
Clarified status of "Package managers and languages" to "to be completed".
2019-07-30 16:13:59 -07:00
scott willekeandGregor Martynus 490d86d0d5 docs: note publishing on distribution channels in beta
Since the readme hints at doing this, note that features to automate this are in beta. Also discussed at https://spectrum.chat/semantic-release/general/im-trying-to-configure-a-next-release~5bb8e692-a0cd-49be-8379-9fb6b25261fe
2019-07-21 19:03:45 -07:00
greenkeeper[bot]andGregor Martynus 665a582930 chore(package): update commitizen to version 4.0.0 2019-07-18 14:20:20 -07:00
David AghassiandGregor Martynus 9e28fd9da9 docs: added plugin developer guide docs 2019-07-18 14:20:11 -07:00
mehrad-rafighandGregor Martynus 6e60c58873 ci(node): set node 8 to node 8.3 and add node 12 2019-07-15 14:50:24 -07:00
greenkeeper[bot]andGregor Martynus 75f08302a9 fix(package): update marked to version 0.7.0 2019-07-06 10:15:52 -07:00
greenkeeper[bot]andGregor Martynus 4b2b2fb780 chore(package): update clear-module to version 4.0.0 2019-07-04 20:04:48 -07:00
Debjeet BiswasandGregor Martynus 3b8cae91fa docs: fix typo
fix misspelled `they`
2019-07-02 15:09:54 -07:00
Pierre Vanduynslager 6b3adf6bbe fix: revert to execa ^1.0.0 2019-06-26 12:33:59 -04:00
Rob CresswellandGregor Martynus 228fed7a0b docs: document that plugins config is an override (#1216)
This patch documents that the `plugin` config option is an override, not
a merge with the default. This is significant, for example, if you
customise the github plugin as it will then prevent npm publishing by
default unless the npm plugin is also defined manually.
2019-06-25 13:01:55 -07:00
Pierre Vanduynslager 01a0b2d08a test: use regexp to check missing module message 2019-06-25 11:30:37 -04:00
greenkeeper[bot]andPierre Vanduynslager 52c48be17b fix(package): update execa to version 2.0.0 2019-06-25 11:30:37 -04:00
Pierre Vanduynslager 4ed6213977 style: fix prettier style 2019-06-07 11:47:28 -04:00
greenkeeper[bot]andPierre Vanduynslager 8051294ffd fix(package): update env-ci to version 4.0.0 2019-06-07 11:21:44 -04:00
greenkeeper[bot]andPierre Vanduynslager 95a0456a85 chore(package): update ava to version 2.0.0 2019-06-05 14:43:18 -04:00
GregorandPierre Vanduynslager 038e640d5e fix: prefix git auth with "x-access-token:" when run in a GitHub Action 2019-06-05 12:17:21 -04:00
GregorandPierre Vanduynslager f3f9d1ef58 test: prefix git auth with "x-access-token:" when run in a GitHub Action 2019-06-05 12:17:21 -04:00
Johannes KleinandGregor Martynus 7e824b2c18 doc: add note to default plugins 2019-06-04 14:07:01 -07:00
Johannes KleinandGregor Martynus d4520e10ed doc: add info about default plugins 2019-06-04 14:07:01 -07:00
Niels HofmansandGregor Martynus bcf3a853f2 docs:optimize images (#1185)
*Total -- 258.67kb -> 182.47kb (29.46%)

/media/semantic-release-cli.png -- 116.80kb -> 65.42kb (43.99%)
/media/bender.png -- 141.88kb -> 117.05kb (17.5%)
2019-05-20 14:36:57 -07:00
Jan PiotrowskiandGregor Martynus d034ce5249 docs: Remove broken waffle.io 💀 badge 2019-05-20 14:08:48 -07:00
greenkeeper[bot]andPierre Vanduynslager 74103abac4 fix(package): update read-pkg-up to version 6.0.0 2019-05-14 15:00:17 -04:00
greenkeeper[bot]andPierre Vanduynslager 6e64745f6b chore(package): update fs-extra to version 8.0.0 2019-05-14 14:29:40 -04:00
Anton GolubandPierre Vanduynslager 4e001c34f9 docs: add semantic-release-github-pages to community plugins 2019-05-09 13:41:04 -04:00
Matt OakesandPierre Vanduynslager edf382f888 docs: add semantic-release-circleci-orb to the community plugin list 2019-05-08 16:01:01 -04:00
Hannes RaboandPierre Vanduynslager 39d15b37f9 docs: add semantic-release-slack-bot to community plugins 2019-05-08 15:45:30 -04:00
greenkeeper[bot]andPierre Vanduynslager 079251c6b8 chore(package): update tempy to version 0.3.0 2019-05-08 15:13:27 -04:00
greenkeeper[bot]andPierre Vanduynslager f4cf7c8b51 fix(package): update figures to version 3.0.0 2019-05-08 14:44:56 -04:00
Brett ZamirandPierre Vanduynslager c8ec0fd67f docs: fix grammar 2019-05-08 14:32:55 -04:00
greenkeeper[bot]andPierre Vanduynslager 1d776db143 chore(package): update nyc to version 14.0.0 2019-05-08 14:30:48 -04:00
Kengo TODAandPierre Vanduynslager 6b1938fd7e docs: add a plugin for Gradle project 2019-04-15 13:32:14 -04:00
greenkeeper[bot]andPierre Vanduynslager 6f3c21a10e fix(package): update resolve-from to version 5.0.0 2019-04-15 13:22:40 -04:00
greenkeeper[bot]andPierre Vanduynslager 06fe435254 fix(package): update aggregate-error to version 3.0.0 2019-04-15 11:38:39 -04:00
Ben HuttonandPierre Vanduynslager 61762e67a0 docs: update commitlint URL
The current commitlint URL goes to a repo which contains a redirect message and new URL.
Replace the outdated URL with the new URL for the commitlint repo.
2019-04-15 11:19:51 -04:00
greenkeeper[bot]andPierre Vanduynslager 5072fef3e4 chore(package): update file-url to version 3.0.0 2019-04-15 11:11:58 -04:00
greenkeeper[bot]andPierre Vanduynslager d61e3bce2e fix(package): update semver to version 6.0.0 2019-04-15 10:52:25 -04:00
Julien VialaandPierre Vanduynslager 0cd8a57b4f docs: correct way to print release plugin name 2019-04-15 09:58:35 -04:00
greenkeeper[bot]andPierre Vanduynslager db3fc3eaf7 fix(package): update hook-std to version 2.0.0 2019-04-13 23:57:25 -04:00
greenkeeper[bot]andPierre Vanduynslager a90a1038e7 fix(package): update read-pkg-up to version 5.0.0 2019-03-21 12:09:56 -04:00
greenkeeper[bot]andPierre Vanduynslager 30723c5998 fix(package): update p-reduce to version 2.0.0 2019-03-13 13:23:05 -04:00
greenkeeper[bot]andPierre Vanduynslager 840af0d734 chore(package): update p-retry to version 4.0.0 2019-03-13 11:34:08 -04:00
greenkeeper[bot]andPierre Vanduynslager 0a584def20 fix(package): update get-stream to version 5.0.0 2019-03-13 11:22:34 -04:00
greenkeeper[bot]andPierre Vanduynslager a5babc6157 fix(package): update p-locate to version 4.0.0 2019-03-13 11:02:21 -04:00
greenkeeper[bot]andPierre Vanduynslager 322c1c69ec chore(package): update ava to version 1.3.1 2019-03-06 13:22:00 -05:00
greenkeeper[bot]andPierre Vanduynslager 20e5d83456 chore(package): update sinon to version 7.2.7 2019-03-04 13:21:34 -05:00
Nicolas DelperdangeandPierre Vanduynslager e5a5867e82 docs(circle): fix incorrect script example
Little mistake in the example to add a ssh key for circleCi
2019-03-04 12:13:08 -05:00
greenkeeper[bot]andPierre Vanduynslager aed4ea2edc fix(package): update yargs to version 13.1.0 2019-02-15 12:11:12 -05:00
greenkeeper[bot]andPierre Vanduynslager 448a0ff977 chore(package): update xo to version 0.24.0 2019-01-30 17:27:04 -05:00
Kevin LluchandPierre Vanduynslager 1b7d8b2d21 docs: add semantic-release-ado to community plugins 2019-01-29 16:15:23 -05:00
Austin Cawley-EdwardsandPierre Vanduynslager 952e3fdf64 docs: fix typo in CircleCI recipe 2019-01-22 11:32:41 -05:00
David AghassiandPierre Vanduynslager 6a8eede96f docs: cleaned up wording and typos in docs 2019-01-12 14:27:56 -05:00
David AghassiandPierre Vanduynslager 4652cef1e6 docs: corrected typos in jsdocs 2019-01-12 14:27:56 -05:00
greenkeeper[bot]andPierre Vanduynslager b7aeabad93 fix(package): update marked to version 0.6.0 2019-01-10 16:14:04 -05:00
greenkeeper[bot]andPierre Vanduynslager 3819ca56a9 chore(package): update ava to version 1.0.1 2018-12-27 14:43:11 -05:00
greenkeeper[bot]andPierre Vanduynslager 1aefd98d31 fix(package): update aggregate-error to version 2.0.0 2018-12-26 13:22:26 -05:00
Pierre Vanduynslager 1243f79064 fix: correctly handle skipped releases 2018-12-16 16:28:52 -05:00
Pierre Vanduynslager 70c68ef3ed feat: allow publish plugins to return false in order to signify no release was done 2018-12-14 16:16:27 -05:00
Pierre VanduynslagerandGregor Martynus 048292baa5 docs: fix broken link in CircleCI recipe 2018-12-14 10:48:58 -08:00
Pierre VanduynslagerandGregor Martynus 0f642ffe4d docs: remove mentions of travis-deploy-once 2018-12-14 10:48:58 -08:00
greenkeeper[bot]andPierre Vanduynslager 89ad3a0b61 chore(package): update p-retry to version 3.0.0 2018-12-12 11:59:37 -05:00
Pierre Vanduynslager 649b53087a docs: mention that debug option is CLI only 2018-12-11 13:33:06 -05:00
Pierre Vanduynslager 862ec4c087 fix: allow to set ci option via API and config file 2018-12-11 13:33:06 -05:00
Pierre Vanduynslager 6b110b6e9e docs: switch to spectrum.chat 2018-12-03 17:48:15 -05:00
Pierre Vanduynslager e4c6649714 docs: syntax fixes in plugins list 2018-11-30 03:25:05 -05:00
Pierre Vanduynslager 6220641aba docs: add @semantic-release/apm to plugins list 2018-11-30 03:25:05 -05:00
Evan SirokyandPierre Vanduynslager a45273e921 docs: add maven-semantic-release to list of community plugins 2018-11-30 03:12:00 -05:00
Pierre Vanduynslager d1091133b9 chore(package): update nyc and sinon 2018-11-30 02:10:04 -05:00
Pierre Vanduynslager cd69583746 test: delete unused test helper file 2018-11-30 01:24:16 -05:00
Pierre Vanduynslager ffe1062830 fix: remove unnecessary branch parameter from push function 2018-11-29 20:08:25 -05:00
Pierre Vanduynslager 7a9922a492 fix: rename default branch 2018-11-28 17:32:05 -05:00
Andy EdwardsandPierre Vanduynslager d6d1bc954e docs: grammar corrections 2018-11-27 16:04:50 -05:00
Pierre Vanduynslager eafbb343dd fix: correctly resolve plugins installed globally with npx
This bug affects only plugins defined with the `plugins` option and wrapped in an Array to add a configuration
2018-11-26 18:39:28 -05:00
Pierre Vanduynslager 2b082acc73 fix: push only tags to remote repo 2018-11-21 12:32:01 -05:00
Pierre Vanduynslager aa022e0ac2 test: clarify variables name 2018-11-21 12:32:01 -05:00
Pierre Vanduynslager f2ede5bdde docs: typo in JS docs 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager 9742712957 test: verify errors have message and details 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager 5937f13bdf test: fix typo 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager 43dbd10046 refactor: prefer filter shorter form 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager 9f5645cfa0 refactor: harmonize git utils function names 2018-11-19 18:34:16 -05:00
Pierre Vanduynslager e594638a96 test: prefer array spread 2018-11-19 18:34:16 -05:00
Kostis (Codefresh)andPierre Vanduynslager 244f014a91 docs: add Codefresh in list of CIs with pipelines 2018-11-18 14:59:12 -05:00
Waldir PimentaandPierre Vanduynslager 218d830af0 docs: fix quote marks (#986) 2018-11-16 13:06:48 -05:00
Pierre Vanduynslager 90da6a0bc1 feat: add logs about prepare, publish, success and fail plugins skipped in dry-run mode 2018-11-14 11:27:06 -05:00
Pierre Vanduynslager 90b497464e test: test that dry-run also skips prepare step 2018-11-14 11:27:06 -05:00
Pierre Vanduynslager c86518a050 fix: do not underline log messages 2018-11-14 11:27:06 -05:00
Pierre Vanduynslager e92c84ec08 fix: indicate in logs if running in dry-run mode 2018-11-14 11:27:06 -05:00
Pierre Vanduynslager 5180001ae6 feat: support multiple plugins for the analyzeCommits step
In case multiple plugins with a `analyzeCommits` step are configured, all of them will be executed and the highest release type (`major` > `minor`, `patch`) will be used.
2018-11-12 15:06:46 -05:00
Pierre Vanduynslager 728ea34dda fix: remove redundant log 2018-11-12 15:06:46 -05:00
Pierre Vanduynslager 83af7acf69 docs: mention default analyzeCommits plugin 2018-11-12 15:06:46 -05:00
Pierre Vanduynslager 8e564ebc9d docs: update FAQ to reflect new plugins option 2018-11-09 17:08:49 -05:00
Pierre Vanduynslager dff1f1056f docs: mention postversion npm script hook to run build scripts 2018-11-09 17:08:49 -05:00
Pierre Vanduynslager ae4995c867 style: fix prettier errors 2018-11-07 12:19:19 -05:00
greenkeeper[bot]andPierre Vanduynslager 669c9ed300 fix(package): update find-versions to version 3.0.0 2018-11-06 12:59:37 -05:00
Pierre Vanduynslager 3c8177aed8 fix: add debug logs for config file path 2018-11-02 15:00:12 -04:00
Pierre Vanduynslager 6d0bd8c9b1 fix: add debug logs for plugins resolved options 2018-11-02 15:00:12 -04:00
Pierre Vanduynslager a99355effa fix: remove dependency to git-url-parse 2018-10-27 09:35:45 -04:00
Pierre Vanduynslager cc06d8999a test: fix errors ordering in assertions 2018-10-27 09:35:45 -04:00
Lucas CorreiaandPierre Vanduynslager 3411520ea7 fix: include release notes in JS API result for dry mode 2018-10-20 12:37:11 -04:00
Pierre Vanduynslager 3d5db1f8b0 fix: remove debugging console.error 2018-10-20 04:24:21 -04:00
Cedric van PuttenandPierre Vanduynslager cfc10039f3 docs: add semantic-release-expo to plugins list 2018-10-18 11:10:52 -04:00
Pierre Vanduynslager 0578c8b91c fix: do not log outated branch error for missing permission cases 2018-10-17 15:33:16 -04:00
Pierre Vanduynslager e29110103b docs: add section existing tags in configuration docs 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager 88539222f4 docs: add troubleshooting section for reference already exists Git error 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager d45861b989 docs: clarify the "npm missing permission" troubleshooting section 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager 2ba0b81f39 docs: remove troubleshooting section related to legacy error messages 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager e93a663490 docs: fix markdown link in configuration docs 2018-10-09 22:02:34 -04:00
Pierre Vanduynslager 58c25beeb6 fix: fix logs for plugins loaded with plugins option 2018-10-09 16:33:37 -04:00
Pierre Vanduynslager ff275a5cd4 fix: use module name in logs for plugins loaded with plugins option 2018-10-09 15:29:04 -04:00
Jamie BartonandPierre Vanduynslager 3e8216ab35 docs: typo in configuration docs 2018-10-09 12:20:35 -04:00
Pierre Vanduynslager aa9d5c6efe docs: add a Getting started section and clarify config steps 2018-10-08 13:24:51 -04:00
Pierre Vanduynslager 5ba5010c80 feat: add new plugins option 2018-10-08 13:24:51 -04:00
Pierre Vanduynslager 9930dac69e fix: add cwd to ENOGITREPO error message 2018-10-04 01:49:44 -04:00
Pierre Vanduynslager bc8551c025 fix: typo in EPLUGINCONF error message 2018-10-04 01:49:44 -04:00
Pierre Vanduynslager 234a9105f6 docs: add Waffle.io README badge 2018-10-04 01:41:37 -04:00
greenkeeper[bot]andPierre Vanduynslager 68fce9616e chore(package): update commitizen to version 3.0.0 2018-10-01 13:41:09 -04:00
Mateusz NikielandPierre Vanduynslager fb6e2d80a8 docs: add semantic-release-gerrit to plugins list 2018-09-25 16:40:24 -04:00
greenkeeper[bot]andPierre Vanduynslager b9ae7d25ea fix(package): update env-ci to version 3.0.0 2018-09-19 17:00:16 -04:00
greenkeeper[bot]andPierre Vanduynslager c27e18ea3a chore(package): update nock to version 10.0.0 2018-09-14 16:59:05 -04:00
greenkeeper[bot]andPierre Vanduynslager 7b8cd9918b fix(package): update debug to version 4.0.0 2018-09-11 12:42:39 -04:00
Pierre Vanduynslager 540d4fa764 fix: pass custom env and cwd to env-ci 2018-09-07 17:21:21 -04:00
Pierre Vanduynslager 4f75cb3376 fix: support multiple generate-notes plugin in CLI arg 2018-09-07 10:46:04 -04:00
Patrick MowrerandPierre Vanduynslager 1348985b6c docs: analyzeCommits does not accept an Array
[Fixes #924]
2018-09-07 10:17:06 -04:00
Pierre Vanduynslager dfbb9f2429 docs: clarify the URL encoding of GIT_CREDENTIALS 2018-09-05 14:05:08 -04:00
greenkeeper[bot]andPierre Vanduynslager fa62d427b6 chore(package): update xo to version 0.23.0 2018-09-03 16:54:31 -04:00
greenkeeper[bot]andPierre Vanduynslager 42e9d1192f chore(package): update delay to version 4.0.0 2018-09-03 15:28:41 -04:00
Pierre Vanduynslager 468f8a8bda docs: clarify the --ci / --no-ci CLI option 2018-09-03 14:21:55 -04:00
Pierre Vanduynslager dffe148e33 fix: hide sensitive data in relesae notes and fail/success plugin params 2018-08-27 16:20:36 -04:00
greenkeeper[bot]andPierre Vanduynslager 1aed97e577 fix(package): update execa to version 1.0.0 2018-08-26 22:46:48 +02:00
greenkeeper[bot]andPierre Vanduynslager edd8bc2889 fix(package): update execa to version 0.11.0 2018-08-24 10:43:59 +02:00
greenkeeper[bot]andPierre Vanduynslager 2f4befed75 fix(package): update marked to version 0.5.0 2018-08-18 10:57:38 -04:00
Pierre Vanduynslager cfeaf49233 test: use real writable stream
This way plugins can pipe a stream to `stdout` and `stderr` in integration tests.
2018-08-15 16:27:55 -04:00
greenkeeper[bot]andPierre Vanduynslager e8820960ce fix(package): update get-stream to version 4.0.0 2018-08-10 15:02:13 -04:00
Pierre Vanduynslager 93377eb636 revert: "fix: do not convert ssh repositoryUrl to https"
This reverts commit b89523105c.
2018-08-10 13:16:29 -04:00
Pierre Vanduynslager b89523105c fix: do not convert ssh repositoryUrl to https 2018-08-08 12:02:02 -04:00
Felix BeckerandPierre Vanduynslager 8b8e40c91e docs(plugins): add semantic-release-firefox 2018-08-06 12:09:46 -04:00
greenkeeper[bot]andPierre Vanduynslager 06695a1af8 chore(package): update xo to version 0.22.0 2018-08-06 11:48:44 -04:00
Pierre Vanduynslager 63d422ed5c fix: do not clone stdout/stderr passed to pugins 2018-08-04 20:33:26 -04:00
86 changed files with 2259 additions and 1377 deletions
+2
View File
@@ -1,3 +1,5 @@
# Jetbrains IDEs
.idea
# Created by https://www.gitignore.io/api/macos,windows,linux,node
+4 -3
View File
@@ -4,14 +4,15 @@ services:
- docker
node_js:
- 12
- 10
- 8
- 8.3
# Trigger a push build on caribou and greenkeeper branches + PRs build on every branches
# Trigger a push build on master and greenkeeper branches + PRs build on every branches
# Avoid double build on PRs (See https://github.com/travis-ci/travis-ci/issues/1147)
branches:
only:
- caribou
- master
- /^greenkeeper.*$/
# Retry install on fail to avoid failing a build on network/disk/external errors
+42 -3
View File
@@ -9,6 +9,7 @@ As a contributor, here are the guidelines we would like you to follow:
- [Submitting a Pull Request](#submitting-a-pull-request)
- [Coding rules](#coding-rules)
- [Working with the code](#working-with-the-code)
- [Working with the doc](#working-with-the-doc)
We also recommend that you read [How to Contribute to Open Source](https://opensource.guide/how-to-contribute).
@@ -20,7 +21,7 @@ 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/03-recipes/README.md), etc. Take a look at the [documentation issues that need help](https://github.com/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+user%3Asemantic-release+archived%3Afalse+label%3A%22help+wanted%22+label%3Adocs+).
Please follow the [Documentation guidelines](#documentation).
@@ -36,7 +37,7 @@ Confirmed bugs and ready-to-implement features are marked with the [help wanted
## Using the issue tracker
The issue tracker is the channel for [bug reports](#bug-report), [features requests](#feature-request) and [submitting pull requests](#submitting-a-pull-request) only. Please use the [Support](docs/support/README.md) and [Get help](README.md#get-help) sections for support, troubleshooting and questions.
The issue tracker is the channel for [bug reports](#bug-report), [features requests](#feature-request) and [submitting pull requests](#submitting-a-pull-request) only. Please use the [Support](docs/05-support/README.md) and [Get help](README.md#get-help) sections for support, troubleshooting and questions.
Before opening an issue or a Pull Request, please use the [GitHub issue search](https://github.com/issues?utf8=%E2%9C%93&q=user%3Asemantic-release) to make sure the bug or feature request hasn't been already reported or fixed.
@@ -50,7 +51,7 @@ Feature requests are welcome, but take a moment to find out whether your idea fi
### New plugin request
[Plugins](docs/usage/plugins.md) are a great way to extend **semantic-release** capabilities, integrate with other systems and support new project type. Please provide as much detail and context as possible and fill the information requested in the [New plugin request template](https://github.com/semantic-release/semantic-release/issues/new?template=plugin-request.md).
[Plugins](docs/01-usage/plugins.md) are a great way to extend **semantic-release** capabilities, integrate with other systems and support new project type. Please provide as much detail and context as possible and fill the information requested in the [New plugin request template](https://github.com/semantic-release/semantic-release/issues/new?template=plugin-request.md).
## Submitting a Pull Request
@@ -249,3 +250,41 @@ $ npm run test
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.
## Working with the doc
Working with the doc is like [working with the code](#working-with-the-code), with the difference that you might find useful to see your changes locally before submitting.
You can do that by following the instructions below (copy/paste-ish from "[Use gitbook locally](https://til.secretgeek.net/gitbook/use_gitbook_locally.html)"):
Install `gitbook-cli` globally:
```
$ npm install --global gitbook-cli
```
> **WARNING**: `gitbook-cli` will install the `gitbook` package when it is building the doc. If you have `gitbook` already installed, uninstall it first with a `npm uninstall -g gitbook` before installing `gitbook-cli`.
Once `gitbook-cli` is installed, from the root of the repo you're working on, you run...
```
$ gitbook build .
Installing GitBook 3.2.3 # it installs the gitbook package automatically
[..]
```
And it will generate a subfolder called `_book` which contains `index.html` and all the other html of the finished book. (You may want to add `_book` to your `.gitignore`)
You can view that `_book\index.html` file directly in a browser, or serve the content locally from a mini webserver by running:
```
gitbook serve .
```
And then browse the result on the `port` 4000:
```
http://localhost:4000/
```
You can use a different `port` by using the `--port` argument, e.g. `gitbook serve . --port 4003`.
You can output as `html`, `pdf`, `epub` or `mobi`. To find out how, use `gitbook help`.
+46 -40
View File
@@ -1,14 +1,14 @@
<h1 align="center" style="border-bottom: none;">📦🚀 semantic-release</h1>
<h3 align="center">Fully automated version management and package publishing</h3>
<p align="center">
<a href="https://gitter.im/semantic-release/semantic-release">
<img alt="Gitter" src="https://badges.gitter.im/semantic-release/semantic-release.svg">
<a href="https://spectrum.chat/semantic-release">
<img alt="Join the community on Spectrum" src="https://withspectrum.github.io/badge/badge.svg">
</a>
<a href="https://travis-ci.org/semantic-release/semantic-release">
<img alt="Travis" src="https://img.shields.io/travis/semantic-release/semantic-release/caribou.svg">
<img alt="Travis" src="https://img.shields.io/travis/semantic-release/semantic-release/master.svg">
</a>
<a href="https://codecov.io/gh/semantic-release/semantic-release">
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/semantic-release/semantic-release/caribou.svg">
<img alt="Codecov" src="https://img.shields.io/codecov/c/github/semantic-release/semantic-release/master.svg">
</a>
<a href="https://greenkeeper.io">
<img alt="Greenkeeper" src="https://badges.greenkeeper.io/semantic-release/semantic-release.svg">
@@ -39,10 +39,10 @@ This removes the immediate connection between human emotions and version numbers
- 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)
- Integrate with your [continuous integration workflow](docs/03-recipes/README.md#ci-configurations)
- Avoid potential errors associated with manual releases
- Support any [package managers and languages](docs/recipes/README.md#package-managers-and-languages) via [plugins](docs/usage/plugins.md)
- Simple and reusable configuration via [shareable configurations](docs/usage/shareable-configurations.md)
- Support any [package managers and languages](docs/03-recipes/README.md#package-managers-and-languages) via [plugins](docs/01-usage/plugins.md)
- Simple and reusable configuration via [shareable configurations](docs/01-usage/shareable-configurations.md)
## How does it work?
@@ -50,9 +50,9 @@ This removes the immediate connection between human emotions and version numbers
**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.
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/01-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 contributors and enforce valid commit messages.
Tools such as [commitizen](https://github.com/commitizen/cz-cli), [commitlint](https://github.com/conventional-changelog/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:
@@ -71,54 +71,60 @@ Here is an example of the release type that will be done based on a commit messa
For each new commits added to the release branch (i.e. `master`) with `git push` or by merging a pull request or merging from another branch, a CI build is triggered and runs the `semantic-release` command to make a release if there are codebase changes since the last release that affect the package functionalities.
If you need more control over the timing of releases you have a couple of options:
- Publish releases on a distribution channel (for example npm’s [dist-tags](https://docs.npmjs.com/cli/dist-tag)). This way you can keep control over what your users end up using by default, and you can decide when to make an automatically released version available to the stable channel, and promote it.
- Publish releases on a distribution channel (for example npm’s [dist-tags](https://docs.npmjs.com/cli/dist-tag)). This way you can keep control over what your users end up using by default, and you can decide when to make an automatically released version available to the stable channel, and promote it. **NOTE**: `16.0.0-beta` of semantic-release, includes new features to automate the release of different branches to different npm distribution tags. The corresponding documentation can be found [on the beta branch of this repo](https://github.com/semantic-release/semantic-release/blob/beta/docs/recipes/distribution-channels.md#publishing-on-distribution-channels).
- Develop on a `dev` branch and merge it to the release branch (i.e. `master`) once you are ready to publish. **semantic-release** will run only on pushes to the release branch.
### Release steps
After running the tests the command `semantic-release` will execute the following steps:
After running the tests, the command `semantic-release` will execute the following steps:
| Step | Description |
|-------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Verify Conditions | Verify all the conditions to proceed with the release with the [verify conditions plugins](docs/usage/plugins.md#verifyconditions-plugin). |
| Get last release | Obtain the commit corresponding to the last release by analyzing [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). |
| Analyze commits | Determine the type of release 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. |
| Step | Step Hook | Description |
|-------------------|----------------------|---------------------------------------------------------------------------------------------------------------------------------|
| Verify Conditions | `verifyConditions` | Verify all the conditions to proceed with the release. |
| Get last release | N/A | Obtain the commit corresponding to the last release by analyzing [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). |
| Analyze commits | N/A | Determine the type of release based on the commits added since the last release. |
| Verify release | `verifyRelease` | Verify the release conformity. |
| Generate notes | `generateNotes` | Generate release notes for the commits added since the last release. |
| Create Git tag | N/A | Create a Git tag corresponding to the new release version. |
| Prepare | `prepare` | Prepare the release. |
| Publish | `publish` | Publish the release. |
| Notify | `success`, `failure` | Notify of new releases or errors. |
## Documentation
- Usage
- [Installation](docs/usage/installation.md#installation)
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
- [Configuration](docs/usage/configuration.md#configuration)
- [Plugins](docs/usage/plugins.md)
- [Shareable configurations](docs/usage/shareable-configurations.md)
- [Getting started](docs/01-usage/getting-started.md)
- [Installation](docs/01-usage/installation.md#installation)
- [CI Configuration](docs/01-usage/ci-configuration.md#ci-configuration)
- [Configuration](docs/01-usage/configuration.md#configuration)
- [Plugins](docs/01-usage/plugins.md)
- [Shareable configurations](docs/01-usage/shareable-configurations.md)
- Extending
- [Plugins](docs/extending/plugins-list.md)
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
- [Available plugins](docs/02-extending/plugins-list.md)
- [Available shareable configuration](docs/02-extending/shareable-configurations-list.md)
- Recipes
- [CI configurations](docs/recipes/README.md)
- [Package managers and languages](docs/recipes/README.md)
- [CI pipelines recipes](docs/03-recipes/ci-pipelines-recipes.md)
- [CircleCI 2.0 workflows](docs/03-recipes/circleci-workflows.md)
- [Travis CI](docs/03-recipes/travis.md)
- [GitLab CI](docs/03-recipes/gitlab-ci.md)
- [Git hosted services](docs/03-recipes/git-hosted-services.md)
- [Git authentication with SSH keys](docs/03-recipes/git-auth-ssh-keys.md)
- [Package managers and languages](docs/03-recipes/package-managers-and-languages.md)
- Developer guide
- [JavaScript API](docs/developer-guide/js-api.md)
- [Plugins](docs/developer-guide/plugin.md)
- [Shareable configuration](docs/developer-guide/shareable-configuration.md)
- [JavaScript API](docs/04-developer-guide/js-api.md)
- [Plugin development](docs/04-developer-guide/plugin.md)
- [Shareable configuration development](docs/04-developer-guide/shareable-configuration.md)
- Support
- [Resources](docs/support/resources.md)
- [Frequently Asked Questions](docs/support/FAQ.md)
- [Troubleshooting](docs/support/troubleshooting.md)
- [Node version requirement](docs/support/node-version.md)
- [Node Support Policy](docs/support/node-support-policy.md)
- [Resources](docs/05-support/resources.md)
- [Frequently Asked Questions](docs/05-support/FAQ.md)
- [Troubleshooting](docs/05-support/troubleshooting.md)
- [Node version requirement](docs/05-support/node-version.md)
- [Node Support Policy](docs/05-support/node-support-policy.md)
## Get help
- [Stack Overflow](https://stackoverflow.com/questions/tagged/semantic-release)
- [Gitter chat](https://gitter.im/semantic-release/semantic-release)
- [Spectrum community](https://spectrum.chat/semantic-release)
- [Twitter](https://twitter.com/SemanticRelease)
## Badge
+24 -24
View File
@@ -1,34 +1,34 @@
# Summary
## Usage
- [Installation](docs/usage/installation.md#installation)
- [CI Configuration](docs/usage/ci-configuration.md#ci-configuration)
- [Configuration](docs/usage/configuration.md#configuration)
- [Plugins](docs/usage/plugins.md)
- [Shareable configurations](docs/usage/shareable-configurations.md)
- [Getting started](docs/01-usage/getting-started.md)
- [Installation](docs/01-usage/installation.md#installation)
- [CI Configuration](docs/01-usage/ci-configuration.md#ci-configuration)
- [Configuration](docs/01-usage/configuration.md#configuration)
- [Plugins](docs/01-usage/plugins.md)
- [Shareable configurations](docs/01-usage/shareable-configurations.md)
## Extending
- [Plugins](docs/extending/plugins-list.md)
- [Shareable configuration](docs/extending/shareable-configurations-list.md)
## Extensions
- [Available plugins](docs/02-extending/plugins-list.md)
- [Available shareable configuration](docs/02-extending/shareable-configurations-list.md)
## Recipes
- [CI configurations](docs/recipes/README.md)
- [CircleCI 2.0 workflows](docs/recipes/circleci-workflows.md)
- [Travis CI](docs/recipes/travis.md)
- [Travis CI with build stages](docs/recipes/travis-build-stages.md)
- [GitLab CI](docs/recipes/gitlab-ci.md)
- [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)
- [CI pipelines recipes](docs/03-recipes/ci-pipelines-recipes.md)
- [CircleCI 2.0 workflows](docs/03-recipes/circleci-workflows.md)
- [Travis CI](docs/03-recipes/travis.md)
- [GitLab CI](docs/03-recipes/gitlab-ci.md)
- [Git hosted services](docs/03-recipes/git-hosted-services.md)
- [Git authentication with SSH keys](docs/03-recipes/git-auth-ssh-keys.md)
- [Package managers and languages](docs/03-recipes/package-managers-and-languages.md)
## Developer guide
- [JavaScript API](docs/developer-guide/js-api.md)
- [Plugin](docs/developer-guide/plugin.md)
- [Shareable configuration](docs/developer-guide/shareable-configuration.md)
- [JavaScript API](docs/04-developer-guide/js-api.md)
- [Plugin development](docs/04-developer-guide/plugin.md)
- [Shareable configuration development](docs/04-developer-guide/shareable-configuration.md)
## Support
- [Resources](docs/support/resources.md)
- [Frequently Asked Questions](docs/support/FAQ.md)
- [Troubleshooting](docs/support/troubleshooting.md)
- [Node version requirement](docs/support/node-version.md)
- [Node Support Policy](docs/support/node-support-policy.md)
- [Resources](docs/05-support/resources.md)
- [Frequently Asked Questions](docs/05-support/FAQ.md)
- [Troubleshooting](docs/05-support/troubleshooting.md)
- [Node version requirement](docs/05-support/node-version.md)
- [Node Support Policy](docs/05-support/node-support-policy.md)
+6 -7
View File
@@ -3,7 +3,7 @@
// 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, promise/prefer-await-to-then, prefer-destructuring */
/* eslint-disable no-var */
var semver = require('semver');
var execa = require('execa');
@@ -16,23 +16,22 @@ if (!semver.satisfies(process.version, pkg.engines.node)) {
console.error(
`[semantic-release]: node version ${pkg.engines.node} is required. Found ${process.version}.
See https://github.com/semantic-release/semantic-release/blob/caribou/docs/support/node-version.md for more details and solutions.`
See https://github.com/semantic-release/semantic-release/blob/master/docs/05-support/node-version.md for more details and solutions.`
);
process.exit(1);
}
execa
.stdout('git', ['--version'])
.then(stdout => {
execa('git', ['--version'])
.then(({stdout}) => {
var gitVersion = findVersions(stdout)[0];
if (semver.lt(gitVersion, MIN_GIT_VERSION)) {
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. Found ${gitVersion}.`);
process.exit(1);
}
})
.catch(err => {
.catch(error => {
console.error(`[semantic-release]: Git version ${MIN_GIT_VERSION} is required. No git binary found.`);
console.error(err);
console.error(error);
process.exit(1);
});
+8 -10
View File
@@ -1,4 +1,4 @@
const {argv, env, stderr} = require('process');
const {argv, env, stderr} = require('process'); // eslint-disable-line node/prefer-global/process
const util = require('util');
const hideSensitive = require('./lib/hide-sensitive');
@@ -22,12 +22,13 @@ Usage:
.option('b', {alias: 'branch', describe: 'Git branch to release from', type: 'string', group: 'Options'})
.option('r', {alias: 'repository-url', describe: 'Git repository URL', type: 'string', group: 'Options'})
.option('t', {alias: 'tag-format', describe: 'Git tag format', type: 'string', group: 'Options'})
.option('p', {alias: 'plugins', describe: 'Plugins', ...stringList, group: 'Options'})
.option('e', {alias: 'extends', describe: 'Shareable configurations', ...stringList, group: 'Options'})
.option('ci', {describe: 'Toggle CI verifications', type: 'boolean', group: 'Options'})
.option('verify-conditions', {...stringList, group: 'Plugins'})
.option('analyze-commits', {type: 'string', group: 'Plugins'})
.option('verify-release', {...stringList, group: 'Plugins'})
.option('generate-notes', {type: 'string', group: 'Plugins'})
.option('generate-notes', {...stringList, group: 'Plugins'})
.option('prepare', {...stringList, group: 'Plugins'})
.option('publish', {...stringList, group: 'Plugins'})
.option('success', {...stringList, group: 'Plugins'})
@@ -46,21 +47,18 @@ Usage:
return 0;
}
// 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);
return 0;
} catch (err) {
if (err.name !== 'YError') {
stderr.write(hideSensitive(env)(util.inspect(err, {colors: true})));
} catch (error) {
if (error.name !== 'YError') {
stderr.write(hideSensitive(env)(util.inspect(error, {colors: true})));
}
return 1;
}
};
-2
View File
@@ -1,2 +0,0 @@
codecov:
branch: caribou
@@ -1,5 +1,6 @@
# Usage
- [Getting started](getting-started.md#getting-started)
- [Installation](installation.md#installation)
- [CI Configuration](ci-configuration.md#ci-configuration)
- [Configuration](configuration.md#configuration)
+53
View File
@@ -0,0 +1,53 @@
# CI configuration
## Running `semantic-release`
The `semantic-release` command will only run fully in a CI environment. If it does not detect that it is in a CI environment, it will automatically run in `dry-run` mode.
Within a CI environment, the `semantic-release` command must be executed only after all the tests in the CI build pass, otherwise it will release potentially faulty code. If the build runs multiple jobs (for example to test on multiple Operating Systems or Node versions) the CI has to be configured to guarantee that the `semantic-release` command is executed only after all jobs are successful.
Follow the CI system's documentation to find out how to do this:
- [Travis Build Stages](https://docs.travis-ci.com/user/build-stages)
- [CircleCI Workflows](https://circleci.com/docs/2.0/workflows)
- [Codeship Deployment Pipelines](https://documentation.codeship.com/basic/builds-and-configuration/deployment-pipelines)
- [GitLab Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html#introduction-to-pipelines-and-jobs)
- [Codefresh Pipelines](https://codefresh.io/docs/docs/configure-ci-cd-pipeline/introduction-to-codefresh-pipelines)
- [Wercker Workflows](http://devcenter.wercker.com/docs/workflows)
- [GoCD Pipelines](https://docs.gocd.org/current/introduction/concepts_in_go.html#pipeline).
This documentation provides a few [CI pipelines recipes](../03-recipes/ci-pipelines-recipes.md) for more details.
## Authentication
### Push access to remote repos
**semantic-release** requires push access to remote Git repositories in order to push the [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging) it created.
The Git authentication can be set with one of the following environment variables:
| Variable | Description |
|---------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `GH_TOKEN` or `GITHUB_TOKEN` | A GitHub [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line). |
| `GL_TOKEN` or `GITLAB_TOKEN` | A GitLab [personal access token](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html). |
| `BB_TOKEN` or `BITBUCKET_TOKEN` | A Bitbucket [personal access token](https://confluence.atlassian.com/bitbucketserver/personal-access-tokens-939515499.html). |
| `GIT_CREDENTIALS` | [URL encoded](https://en.wikipedia.org/wiki/Percent-encoding) Git username and password in the format `<username>:<password>`. The username and password must each be individually URL encoded, not the `:` separating them. |
Alternatively the Git authentication **can be set up via [SSH keys](../03-recipes/git-auth-ssh-keys.md)**.
### Authentication needs for plugins
Most **semantic-release** [plugins](plugins.md) require setting up authentication in order to publish to a package manager registry. See each plugin's documentation for the environment variables required.
It is to note, however, that:
- The default [@semantic-release/github](https://github.com/semantic-release/github#environment-variables) plugin requires the same `GH_TOKEN` environment variable as above
- The default [@semantic-release/npm](https://github.com/semantic-release/npm#environment-variables) plugin requires 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. |
See each plugin's documentation for the environment variables required.
> **Note**: The authentication token/credentials have to be made available in the CI service via environment variables.
>
> See [CI pipelines recipes](../03-recipes/ci-pipelines-recipes.md) for more details on how to configure environment variables in your CI service.
+245
View File
@@ -0,0 +1,245 @@
# Configuration
**semantic-release** configuration consists of:
- Git repository [url](#repositoryurl) and options ([release branch](#branch) and [tag format](#tagformat)). ([Access credentials](ci-configuration.md) are setup through environment variables)
- Plugins [declaration](#plugins) and [options](plugins.md).
- Run mode ([`--dry-run`](#dryrun), [`--no-ci`](#ci) (local), [`--debug`](#debug)).
All of these options can be configured:
- In a config file.
- Through the cli.
- By extending a [shareable configuration](shareable-configurations.md).
Additionally, metadata of Git tags generated by **semantic-release** can be customized via standard [Git environment variables](#git-environment-variables).
## Configuring/passing options to `semantic-release`
### Configuration file
> **Note**: CLI arguments take precedence over options configured in the configuration file and shareable configuration.
**semantic-release**’s options, mode and plugins can be set via a config file in different ways:
- A `.releaserc` file, written in YAML or JSON, with optional extensions `.yaml`, `.yml`, `.json` or `.js`.
- A `release.config.js` file that exports an object.
- A `release` key in the project's `package.json` file.
The following two examples are the same:
- Via `.releaserc` or `release.config.js` file:
```json
{
"branch": "next"
}
```
- Via `release` key in the project's `package.json` file (the configuration must be under the `release` property):
```json
{
"release": {
"branch": "next"
}
}
```
### Using CLI arguments
> **Note**: CLI arguments take precedence over options configured in the configuration file and shareable configuration.
Plugin options cannot be defined via CLI arguments and must be defined in the configuration file.
The following configuration example via CLI argument is equivalent to the configuration file's example:
```bash
$ semantic-release --branch next
```
### Extending a shareable configuration
> **Note**: CLI arguments take precedence over options configured in the configuration file and shareable configuration.
Please see [shareable configuration](shareable-configurations.md) for more details.
## Options
### `extends`
Type: `Array`, `String`<br>
CLI arguments: `-e`, `--extends`
Contains a list of:
- Modules.
- File paths containing a [shareable configuration](shareable-configurations.md).
> **Note**: 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.
Examples (`.releaserc` file content):
- `Array`:
```json
{
"extends": [
"./my_config_dir/my.config",
"@semantic-release/gitlab-config",
]
}
```
- `String`:
```json
{
"extends": "@semantic-release/gitlab-config"
}
```
### `branch`
Type: `String`<br>
Default: `master`<br>
CLI arguments: `-b`, `--branch`
The branch on which releases should happen.
Example (`.releaserc` file content):
```json
{
"branch": "next"
}
```
### `repositoryUrl`
Type: `String`<br>
Default: `repository` property in `package.json` or [git origin url](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes)<br>
CLI arguments: `-r`, `--repository-url`
The git repository URL.
Any valid git url format is supported (See [Git protocols](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols)).
Example (`.releaserc` file content):
```json
{
"repositoryUrl": "https://github.com/username/project.git"
}
```
### `tagFormat`
Type: `String`<br>
Default: `v${version}`<br>
CLI arguments: `-t`, `--tag-format`
The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) format used by **semantic-release** to identify releases. The tag name is generated with [Lodash template](https://lodash.com/docs#template) and will be compiled with the `version` variable.
> **Note**: The `tagFormat` must contain the `version` variable exactly once and compile to a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description).
Example (`.releaserc` file content):
```json
{
"tagFormat": "version-${version}"
}
```
### `plugins`
Type: `Array`<br>
Default: `['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator', '@semantic-release/npm', '@semantic-release/github']`<br>
CLI arguments: `-p`, `--plugins`
Define the list of plugins to use. Plugins will run in series, **in the order defined**, for **each [steps](../../README.md#release-steps)** if they implement it.
Plugin specific configuration can defined by wrapping the name and an options object in an array. See [Plugins configuration options](plugins.md#plugins-configuration-options) for more details.
Example (`.releaserc` file content):
```json
{
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release-docker",
["@semantic-release/exec", {
"verifyConditionsCmd": "./verify.sh"
}],
"@semantic-release/git",
"@semantic-release/gitlab",
]
}
```
### `dryRun`
Type: `Boolean`<br>
Default: `false` if running in a CI environment, `true` otherwise<br>
CLI arguments: `-d`, `--dry-run`
Dry-run mode, skip publishing, print next version and release notes.
Example (`.releaserc` file content):
```json
{
"dryRun": "true"
}
```
### `ci`
Type: `Boolean`<br>
Default: `true`<br>
CLI arguments: `--ci` / `--no-ci`
Set to `false` to skip Continuous Integration environment verifications. This allows for making releases from a local machine.
> **Note**: The CLI arguments `--no-ci` is equivalent to `--ci false`.
Example (`.releaserc` file content):
```json
{
"ci": "false"
}
```
### `debug` (only through CLI)
Type: `Boolean`<br>
Default: `false`<br>
CLI argument: `--debug`
Output debugging information. This can also be enabled by setting the `DEBUG` environment variable to `semantic-release:*`.
> **Note**: The `debug` is used only supported via CLI argument. To enable debug mode from the [JS API](../04-developer-guide/js-api.md#javascript-api) use `require('debug').enable('semantic-release:*')`.
Example:
```bash
$ semantic-release --debug
```
## Git environment variables
| Variable | Description | Default |
|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------|
| `GIT_AUTHOR_NAME` | The author name associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot. |
| `GIT_AUTHOR_EMAIL` | The author email associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot email address. |
| `GIT_COMMITTER_NAME` | The committer name associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot. |
| `GIT_COMMITTER_EMAIL` | The committer email associated with the [Git release tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging). See [Git environment variables](https://git-scm.com/book/en/v2/Git-Internals-Environment-Variables#_committing). | @semantic-release-bot email address. |
## Existing version tags, and how semantic-release deals with them
**semantic-release** uses [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging) to determine the commits added since the last release.
If a release has been published before setting up **semantic-release** you must make sure the most recent commit included in the last published release is in the [release branch](#branch) history and is tagged with the version released, formatted according to the [tag format](#tagformat) configured (defaults to `vx.y.z`).
If the previous releases were published with [`npm publish`](https://docs.npmjs.com/cli/publish) this should already be the case.
For example, if your release branch is `master`, the last release published on your project is `1.1.0` and the last commit included has the sha `1234567`, you must make sure this commit is in `master` history and is tagged with `v1.1.0`.
```bash
# Make sure the commit 1234567 is in the release branch history
$ git branch --contains 1234567
# If the commit is not in the branch history it means that either:
# - you use a different branch than the one your release from before
# - or the commit sha has been rewritten (with git rebase)
# In both cases you need to configure your repository to have the last release commit in the history of the release branch
# List the tags for the commit 1234567
$ git tag --contains 1234567
# If v1.1.0 is not in the list you add it with
$ git tag v1.1.0 1234567
$ git push origin v1.1.0
```
+32
View File
@@ -0,0 +1,32 @@
# Getting started
## Manual setup
You can use **semantic-release** with the following manual setup steps:
1. [Install **semantic-release**](installation.md) either locally for your project or globally
1. Configure:
1. Your Continuous Integration service to [run **semantic-release**](ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
1. Your Git repository and package manager repository [authentication](ci-configuration.md#authentication) in your Continuous Integration service
1. **semantic-release**'s [options and plugins](configuration.md)
## Guided setup through `semantic-release-cli`
Alternatively you can be guided through those setup steps thanks to the [interactive CLI `semantic-release-cli`](https://github.com/semantic-release/cli).
First install `semantic-release-cli`:
```bash
$ npm install -g semantic-release-cli
```
Then go to your project's directory and run the command:
```bash
$ cd your-module
$ semantic-release-cli setup
```
The output looks something like this:
![dialogue](../../media/semantic-release-cli.png)
Available options and other information can be found on [`semantic-release-cli`'s doc](https://github.com/semantic-release/cli#semantic-release-cli).
> **Note**: only a limited number of options, CI services and plugins are currently supported by `semantic-release-cli`.
+22
View File
@@ -0,0 +1,22 @@
# Installation
## Local installation
For [Node modules projects](https://docs.npmjs.com/getting-started/creating-node-modules) we recommend installing **semantic-release** locally and running the `semantic-release` command with [npx](https://www.npmjs.com/package/npx):
```bash
$ npm install --save-dev semantic-release
```
Then in the CI environment:
```bash
$ npx semantic-release
```
> **Note:** `npx` is a tool bundled with `npm@>=5.2.0`. It is used to conveniently find the semantic-release binary and to execute it. See [What is npx](../05-support/FAQ.md#what-is-npx) for more details.
## Global installation
> **Note:** Global installation is no longer recommended. Please use local installation and `npx` instead.
+88
View File
@@ -0,0 +1,88 @@
# Plugins
## Plugins implement actions for release steps
Actions that should be performed for each [release step](../../README.md#release-steps) are implemented through configurable plugins, and [a number of them are installed by default](#plugins-installed-by-default). This allows for support of different [commit message formats](../../README.md#commit-message-format), release note generators and publishing platforms.
A plugin is a npm module (for instance `@semantic-release/github` or `semantic-release-docker`) that can implement one or more of the following steps through their step hooks:
| Step hook | Required | Description |
|--------------------|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `verifyConditions` | No | Responsible for verifying conditions necessary to proceed with the release: configuration is correct, authentication token are valid, etc... |
| `analyzeCommits` | Yes | Responsible for determining the type of the next release (`major`, `minor` or `patch`). If multiple plugins with a `analyzeCommits` step are defined, the release type will be the highest one among plugins output. <br> **Note**: If no plugin with an `analyzeCommits` step is defined, then `@semantic-release/commit-analyzer` will be used.|
| `verifyRelease` | No | Responsible for verifying the parameters (version, type, dist-tag etc...) of the release that is about to be published. |
| `generateNotes` | No | Responsible for generating the content of the release note. If multiple plugins with a `generateNotes` step are defined, the release notes will be the result of the concatenation of each plugin output. |
| `prepare` | No | Responsible for preparing the release, for example creating or updating files such as `package.json`, `CHANGELOG.md`, documentation or compiled assets and pushing a commit. |
| `publish` | No | Responsible for publishing the release. |
| `success` | No | Responsible for notifying of a new release. |
| `fail` | No | Responsible for notifying of a failed release. |
## Plugins installation
### Plugins installed by default
These five plugins are already part of **semantic-release** and don't have to be installed separately:
```
"@semantic-release/commit-analyzer"
"@semantic-release/error"
"@semantic-release/github"
"@semantic-release/npm"
"@semantic-release/release-notes-generator"
```
### Installing additional plugins
[Additional plugins](../02-extending/plugins-list.md) have to be installed via npm:
```bash
$ npm install @semantic-release/git @semantic-release/changelog -D
```
## Plugins declaration and execution order
Each plugin (which is an npm module) must be declared using the [`plugins` option](./configuration.md#plugins). If the `plugins` option is defined, then the default is overriden (rather than merge with the option's default).
For example:
```json
{
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/npm",
"@semantic-release/git"
]
}
```
For each [release step](../../README.md#release-steps) the plugins that implement that step will be executed **in the order in which they are declared**.
Hence, with this configuration above, **semantic-release** will:
- execute the `verifyConditions` implementation of `@semantic-release/npm` then `@semantic-release/git`
- execute the `analyzeCommits` implementation of `@semantic-release/commit-analyzer`
- execute the `prepare` implementation of `@semantic-release/npm` then `@semantic-release/git`
- execute the `generateNotes` implementation of `@semantic-release/release-notes-generator`
- execute the `publish` implementation of `@semantic-release/npm`
## Plugins configuration options
A plugin configuration options can specified by wrapping the name and an options object in an array. Options configured this way will be passed only to that specific plugin.
Global plugin options can defined at the root of the **semantic-release** configuration object. Options configured this way will be passed to all plugins.
```json
{
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
["@semantic-release/github", {
"assets": ["dist/**"]
}],
"@semantic-release/git"
],
"preset": "angular"
}
```
With this configuration:
- All plugins will receive the `preset` option, which will be used by both `@semantic-release/commit-analyzer` and `@semantic-release/release-notes-generator` (and ignored by `@semantic-release/github` and `@semantic-release/git`)
- The `@semantic-release/github` plugin will receive the `assets` options (`@semantic-release/git` will not receive it and therefore will use it's default value for that option)
@@ -0,0 +1,7 @@
# Shareable configurations
A shareable configuration is an npm package that exports a **semantic-release** configuration object. It allows for use of the same configuration across several projects.
Shareable configurations to be use can be declared with the [`extends` option](configuration.md#extends).
See [shareable configurations list](../02-extending/shareable-configurations-list.md) for examples.
+93
View File
@@ -0,0 +1,93 @@
# Plugins list
## Official plugins
- [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer)
- **Note**: this is already part of semantic-release and does not have to be installed separately
- `analyzeCommits`: Determine the type of release by analyzing commits with [conventional-changelog](https://github.com/conventional-changelog/conventional-changelog)
- [@semantic-release/release-notes-generator](https://github.com/semantic-release/release-notes-generator)
- **Note**: this is already part of semantic-release and does not have to be installed separately
- `generateNotes`: Generate release notes for the commits added since the last release with [conventional-changelog](https://github.com/conventional-changelog/conventional-changelog)
- [@semantic-release/github](https://github.com/semantic-release/github)
- **Note**: this is already part of semantic-release and does not have to be installed separately
- `verifyConditions`: Verify the presence and the validity of the GitHub authentication and release configuration
- `publish`: Publish a [GitHub release](https://help.github.com/articles/about-releases)
- `success`: Add a comment to GitHub issues and pull requests resolved in the release
- `fail`: Open a GitHub issue when a release fails
- [@semantic-release/npm](https://github.com/semantic-release/npm)
- **Note**: this is already part of semantic-release and does not have to be installed separately
- `verifyConditions`: Verify the presence and the validity of the npm authentication and release configuration
- `prepare`: Update the package.json version and create the npm package tarball
- `publish`: Publish the package on the npm registry
- [@semantic-release/gitlab](https://github.com/semantic-release/gitlab)
- `verifyConditions`: Verify the presence and the validity of the GitLab authentication and release configuration
- `publish`: Publish a [GitLab release](https://docs.gitlab.com/ce/workflow/releases.html)
- [@semantic-release/git](https://github.com/semantic-release/git)
- `verifyConditions`: Verify the presence and the validity of the Git authentication and release configuration
- `prepare`: Push a release commit and tag, including configurable files
- [@semantic-release/changelog](https://github.com/semantic-release/changelog)
- `verifyConditions`: Verify the presence and the validity of the configuration
- `prepare`: Create or update the changelog file in the local project repository
- [@semantic-release/exec](https://github.com/semantic-release/exec)
- `verifyConditions`: Execute a shell command to verify if the release should happen
- `analyzeCommits`: Execute a shell command to determine the type of release
- `verifyRelease`: Execute a shell command to verifying a release that was determined before and is about to be published
- `generateNotes`: Execute a shell command to generate the release note
- `prepare`: Execute a shell command to prepare the release
- `publish`: Execute a shell command to publish the release
- `success`: Execute a shell command to notify of a new release
- `fail`: Execute a shell command to notify of a failed release
- [@semantic-release/apm](https://github.com/semantic-release/apm)
- `verifyConditions`: Verify the presence of the `ATOM_ACCESS_TOKEN` environment variable and the [`apm`](https://github.com/atom/apm) CLI
- `prepare`: Update the `package.json` version with [`npm version`](https://docs.npmjs.com/cli/version)
- `publish`: Publish the [Atom package](https://flight-manual.atom.io/hacking-atom/sections/publishing)
## Community plugins
[Open a Pull Request](https://github.com/semantic-release/semantic-release/blob/master/CONTRIBUTING.md#submitting-a-pull-request) to add your plugin to the list.
- [semantic-release-slack-bot](https://github.com/juliuscc/semantic-release-slack-bot)
- `verifyConditions`: Verify that the environment variable `SLACK_WEBHOOK` has been defined.
- `success`: Publish a message about the success to a slack channel.
- `fail`: Optionally publish a message about failure to a slack channel.
- [semantic-release-docker](https://github.com/felixfbecker/semantic-release-docker)
- `verifyConditions`: Verify that all needed configuration is present and login to the Docker registry.
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag
- [semantic-release-gcr](https://github.com/carlos-cubas/semantic-release-gcr)
- `verifyConditions`: Verify that all needed configuration is present and login to the Docker registry
- `publish`: Tag the image specified by `name` with the new version, push it to Docker Hub and update the latest tag
- [semantic-release-vsce](https://github.com/raix/semantic-release-vsce)
- `verifyConditions`: Verify the presence and the validity of the vsce authentication and release configuration
- `prepare`: Create a `.vsix` for distribution
- `publish`: Publish the package to the Visual Studio Code marketplace
- [semantic-release-verify-deps](https://github.com/piercus/semantic-release-verify-deps)
- `verifyConditions`: Check the dependencies format against a regexp before a release
- [semantic-release-chrome](https://github.com/GabrielDuarteM/semantic-release-chrome)
- `verifyConditions`: Verify the presence of the authentication (set via environment variables)
- `prepare`: Write the correct version to the `manifest.json` and creates a zip file of the whole dist folder
- `publish`: Uploads the generated zip file to the webstore, and publish the item
- [semantic-release-firefox](https://github.com/felixfbecker/semantic-release-firefox)
- `verifyConditions`: Verify the presence of the authentication (set via environment variables)
- `prepare`: Write the correct version to the `manifest.json`, creates a `xpi` file of the dist folder and a zip of the sources
- `publish`: Submit the generated archives to the webstore for review, and publish the item including release notes
- [semantic-release-gerrit](https://github.com/pascalMN/semantic-release-gerrit)
- `generateNotes`: Generate release notes with Gerrit reviews URL
- [semantic-release-expo](https://github.com/bycedric/semantic-release-expo)
- `verifyConditions`: Verify Expo manifest(s) are readable and valid.
- `prepare`: Update version, ios build number and android version code in the Expo manifest(s).
- [maven-semantic-release](https://github.com/conveyal/maven-semantic-release)
- `verifyConditions`: Verifies that the `pom.xml` file and other files exist and are setup to allow releases
- `verifyRelease`: Checks and warns (does not error by default) if the version numbers found on maven central and within the Git project differ by quite a bit
- `prepare`: Changes the version number in the `pom.xml` (or all `pom.xml` files in maven projects with multiple `pom.xml` files) and optionally creates a commit with this version number and pushes it to `master`
- `publish`: Runs `mvn deploy` to deploy to maven central and optionally will update to next snapshot version and merge changes to development branch
- [semantic-release-ado](https://github.com/lluchmk/semantic-release-ado)
- `prepare`: Stores the version number as an Azure DevOps pipeline variable availabe to downstream steps on the job
- [gradle-semantic-release](https://github.com/KengoTODA/gradle-semantic-release-plugin)
- `verifyConditions`: Verify that project has a Gradle wrapper script, and `build.gradle` contains a task to publish artifacts.
- `prepare`: Changes the version number in the `gradle.properties`
- `publish`: Triggers Gradle to publish artifacts.
- [semantic-release-circleci-orb](https://github.com/matt-oakes/semantic-release-circleci-orb)
- `verifyConditions`: Verify the presence of the `CIRCLECI_API_TOKEN` environment variable, `orbName` option, and the `circleci` CLI.
- `publish`: Publish the CircleCI orb.
- [semantic-release-github-pages](https://github.com/qiwi/semantic-release-gh-pages-plugin)
- `verifyConditions`: Verify the presence of the auth token set via environment variables.
- `publish`: Pushes commit to the documentation branch.
@@ -0,0 +1,13 @@
# Shareable configurations list
## Official configurations
- [@semantic-release/apm-config](https://github.com/semantic-release/apm-config) - semantic-release shareable configuration for releasing atom packages
- [@semantic-release/gitlab-config](https://github.com/semantic-release/gitlab-config) - semantic-release shareable configuration for GitLab
## Community configurations
- [@jedmao/semantic-release-npm-github-config](https://github.com/jedmao/semantic-release-npm-github-config)
- Provides an informative [git](https://github.com/semantic-release/git) commit message for the release commit that does not trigger continuous integration and conforms to the [conventional commits specification](https://www.conventionalcommits.org/) (e.g., "chore(release): 1.2.3 [skip ci]\n\nnotes").
- Creates a tarball that gets uploaded with each [GitHub release](https://github.com/semantic-release/github).
- Publishes the same tarball to [npm](https://github.com/semantic-release/npm).
- Commits the version change in `package.json`.
- Creates or updates a [changelog](https://github.com/semantic-release/changelog) file.
+3
View File
@@ -0,0 +1,3 @@
# Git hosted services
- [Git authentication with SSH keys](git-auth-ssh-keys.md)
+4
View File
@@ -0,0 +1,4 @@
# CI pipelines recipes
- [CircleCI 2.0 workflows](circleci-workflows.md)
- [Travis CI](travis.md)
- [GitLab CI](gitlab-ci.md)
@@ -2,9 +2,9 @@
## Environment variables
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [CircleCi Project Settings](https://circleci.com/docs/2.0/env-vars/#adding-environment-variables-in-the-app)..
The [Authentication](../01-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).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../01-usage/getting-started.md#guided-setup-through-semantic-release-cli).
## Multiple Node jobs configuration
@@ -12,7 +12,7 @@ Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with
This example is a minimal configuration for **semantic-release** with a build running Node 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).
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](../01-usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
```yaml
version: 2
@@ -54,7 +54,7 @@ workflows:
### `package.json` configuration for multiple Node jobs
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
A `package.json` is required only for [local](../01-usage/installation.md#local-installation) **semantic-release** installation.
```json
{
@@ -1,6 +1,6 @@
# Git authentication with SSH keys
When using [environment variables](../usage/ci-configuration.md#authentication) to set up the Git authentication, the remote Git repository will automatically be accessed via [https](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_http_protocols), independently of the [`repositoryUrl`](../usage/configuration.md#repositoryurl) format configured in the **semantic-release** [Configuration](../usage/configuration.md#configuration) (the format will be automatically converted as needed).
When using [environment variables](../01-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`](../01-usage/configuration.md#repositoryurl) format configured in the **semantic-release** [Configuration](../01-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.
@@ -137,7 +137,7 @@ jobs:
# 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
- echo 'echo ${SSL_PASSPHRASE}' > /tmp/askpass && chmod +x /tmp/askpass
# Start the authentication agent
- eval "$(ssh-agent -s)"
# Add the key to the authentication agent
@@ -158,6 +158,6 @@ Commit the encrypted private key and the `.circleci/config.yml` file to your rep
```bash
$ git add git_deploy_key.enc .circleci/config.yml
$ git commit -m "ci(cicle): Add the encrypted private ssh key"
$ git commit -m "ci(circle): Add the encrypted private ssh key"
$ git push
```
+2
View File
@@ -0,0 +1,2 @@
# Git hosted services
- [Git authentication with SSH keys](git-auth-ssh-keys.md)
@@ -2,19 +2,19 @@
## Environment variables
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured with [Secret variables](https://docs.gitlab.com/ce/ci/variables/README.html#secret-variables).
The [Authentication](../01-usage/ci-configuration.md#authentication) environment variables can be configured with [Secret variables](https://docs.gitlab.com/ce/ci/variables/README.html#secret-variables).
## Node project configuration
GitLab CI supports [Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html) allowing to test on multiple Node versions and publishing a release only when all test pass.
**Note**: The publish pipeline must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--83).
**Note**: The publish pipeline must run a [Node >= 8 version](../05-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 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.
**Note**: The`semantic-release` execution command varies depending if you are using a [local](../01-usage/installation.md#local-installation) or [global](../01-usage/installation.md#global-installation) **semantic-release** installation.
```yaml
# The release pipeline will run only if all jobs in the test pipeline are successful
@@ -46,7 +46,7 @@ publish:
### `package.json` configuration
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
A `package.json` is required only for [local](../01-usage/installation.md#local-installation) **semantic-release** installation.
```json
{
@@ -0,0 +1,2 @@
# Package managers and languages (to be completed)
@@ -1,18 +1,18 @@
# Using semantic-release with [Travis CI build stages](https://docs.travis-ci.com/user/build-stages)
# Using semantic-release with [Travis CI](https://travis-ci.org)
## Environment variables
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [Travis Repository Settings](https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-Settings) or with the [travis env set CLI](https://github.com/travis-ci/travis.rb#env).
The [Authentication](../01-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).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../01-usage/getting-started.md).
## Multiple Node jobs configuration
## Node.js projects configuration
### `.travis.yml` configuration for multiple Node jobs
### `.travis.yml` configuration for multiple Node.js jobs
This example is a minimal configuration for **semantic-release** with a build running Node 6 and 8. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
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](../01-usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
@@ -43,7 +43,7 @@ jobs:
### `package.json` configuration for multiple Node jobs
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
A `package.json` is required only for [local](../01-usage/installation.md#local-installation) **semantic-release** installation.
```json
{
@@ -53,17 +53,17 @@ A `package.json` is required only for [local](../usage/installation.md#local-ins
}
```
## Non-JavaScript projects configuration
## Non-Node.js projects configuration
For projects that require to be tested with one or multiple version of a Non-JavaScript [language](https://docs.travis-ci.com/user/languages), optionally on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
This recipe cover the Travis specifics only. See [Non JavaScript projects recipe](../support/FAQ.md#can-i-use-semantic-release-to-publish-non-javascript-packages) for more information on the **semantic-release** configuration.
This recipe cover the Travis specifics only. See [Non JavaScript projects recipe](../05-support/FAQ.md#can-i-use-semantic-release-to-publish-non-javascript-packages) for more information on the **semantic-release** configuration.
### `.travis.yml` configuration for non-JavaScript projects
This example is a minimal configuration for **semantic-release** with a build running [Go 1.6 and 1.7](https://docs.travis-ci.com/user/languages/go). See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
This example creates a `release` [build stage](https://docs.travis-ci.com/user/build-stages) that [runs `semantic-release` only after all test jobs are successful](../01-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.
@@ -39,7 +39,7 @@ try {
}
for (const release of releases) {
console.log(`The release was published with plugin "${pluginName}".`);
console.log(`The release was published with plugin "${release.pluginName}".`);
}
} else {
console.log('No release published.');
@@ -65,9 +65,9 @@ Type: `Object`
**semantic-release** options.
Can be used to set any [core option](../usage/configuration.md#configuration) or [plugin options](../usage/plugins.md#configuration).
Can be used to set any [core option](../01-usage/configuration.md#configuration) or [plugin options](../01-usage/plugins.md#configuration).
Each option, will take precedence over options configured in the [configuration file](../usage/configuration.md#configuration) and [shareable configurations](../usage/configuration.md#extends).
Each option, will take precedence over options configured in the [configuration file](../01-usage/configuration.md#configuration) and [shareable configurations](../01-usage/configuration.md#extends).
#### config
@@ -229,7 +229,7 @@ Example:
Type: `Array<Object>`
The list of releases published, one release per [publish plugin](../usage/plugins.md#publish-plugin).<br>
The list of releases published, one release per [publish plugin](../01-usage/plugins.md#publish-plugin).<br>
Each release object has the following properties:
| Name | Type | Description |
+106
View File
@@ -0,0 +1,106 @@
# Plugin Developer Guide
To create a plugin for `semantic-release`, you need to decide which parts of the release lifecycle are important to that plugin. For example, it is best to always have a `verify` step because you may be receiving inputs from a user and want to make sure they exist. A plugin can abide by any of the following lifecycles:
- `verify`
- `prepare`
- `publish`
- `success`
- `fail`
`semantic-release` will require the plugin via `node` and look through the required object for methods named like the lifecyles stated above. For example, if your plugin only had a `verify` and `success` step, the `main` file for your object would need to `export` an object with `verify` and `success` functions.
In addition to the lifecycle methods, each lifecyle is passed two objects:
1. `pluginConfig` - an object containing the options that a user may pass in via their `release.config.js` file (or similar)
2. `context` - provided by `semantic-release` for access to things like `env` variables set on the running process.
For each lifecycle you create, you will want to ensure it can accept `pluginConfig` and `context` as parameters.
## Creating a Plugin Project
It is recommended that you generate a new project with `yarn init`. This will provide you with a basic node project to get started with. From there, create an `index.js` file, and make sure it is specified as the `main` in the `package.json`. We will use this file to orchestrate the lifecycle methods later on.
Next, create a `src` or `lib` folder in the root of the project. This is where we will store our logic and code for how our lifecycle methods work. Finally, create a `test` folder so you can write tests related to your logic.
We recommend you setup a linting system to ensure good javascript practices are enforced. ESLint is usually the system of choice, and the configuration can be whatever you or your team fancies.
## Exposing Lifecycle Methods
In your `index.js` file, you can start by writing the following code
```javascript
const verifyConditions = require('./src/verify');
let verified;
/**
* Called by semantic-release during the verification step
* @param {*} pluginConfig The semantic-release plugin config
* @param {*} context The context provided by semantic-release
*/
async function verify(pluginConfig, context) {
await verifyConditions(pluginConfig, context);
verified = true;
}
module.exports = { verify };
```
Then, in your `src` folder, create a file called `verify.js` and add the following
```javascript
const AggregateError = require('aggregate-error');
/**
* A method to verify that the user has given us a slack webhook url to post to
*/
module.exports = async (pluginConfig, context) => {
const { logger } = context;
const errors = [];
// Throw any errors we accumulated during the validation
if (errors.length > 0) {
throw new AggregateError(errors);
}
};
```
As of right now, this code won't do anything. However, if you were to run this plugin via `semantic-release`, it would run when the `verify` step occurred.
Following this structure, you can create different steps and checks to run through out the release process.
## Supporting Options
Let's say we want to verify that an `option` is passed. An `option` is a configuration object that is specific to your plugin. For example, the user may set an `option` in their release config like:
```js
{
prepare: {
path: "@semantic-release/my-special-plugin"
message: "My cool release message"
}
}
```
This `message` option will be passed to the `pluginConfig` object mentioned earlier. We can use the validation method we created to verify this option exists so we can perform logic based on that knowledge. In our `verify` file, we can add the following:
```js
const { message } = pluginConfig;
if (message.length) {
//...
}
```
## Supporting Environment Variables
Similar to `options`, environment variables exist to allow users to pass tokens and set special URLs. These are set on the `context` object instead of the `pluginConfig` object. Let's say we wanted to check for `GITHUB_TOKEN` in the environment because we want to post to GitHub on the user's behalf. To do this, we can add the following to our `verify` command:
```js
const { env } = context;
if (env.GITHUB_TOKEN) {
//...
}
```
+50 -37
View File
@@ -12,15 +12,33 @@ However, the [`@semantic-release/git`](https://github.com/semantic-release/git)
The `package.json`’s version will be updated by the `semantic-release` command just before publishing to [npm](https://www.npmjs.com), therefore it won't be available for scripts ran before the `semantic-release` command.
As semantic-release uses the [npm CLI](https://docs.npmjs.com/cli/npm) to publish, all [npm hook scripts](https://docs.npmjs.com/misc/scripts#hook-scripts) will be executed. Therefore you can run your build script in the [`prepublishOnly`](https://docs.npmjs.com/misc/scripts#prepublish-and-prepare) hook. It will be executed after the `semantic-release` command update the `package.json`’s version and before publishing.
As the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin uses the [npm CLI](https://docs.npmjs.com/cli/npm) to update the `package.json` version and publish the package, all [npm hook scripts](https://docs.npmjs.com/misc/scripts#description) will be executed.
You can run your build script in:
- the `prepublishOnly` or `prepack` hook so it will be executed during the `publish` step of `@semantic-release/npm`
- the `postversion` hook so it will be executed during the `prepare` step of `@semantic-release/npm`, which allow for example to update files before committing them with the [`@semantic-release/git`](https://github.com/semantic-release/git) plugin
If using npm hook scripts is not possible, and alternative solution is to [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin to run your script in the `prepare` step:
```json
{
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/npm",
["@semantic-release/exec", {
"prepareCmd": "./my-build-script.sh ${nextRelease.version}",
}],
]
}
```
## Is there a way to preview which version would currently get published?
Yes with the [dry-run options](../usage/configuration.md#dryrun) which prints to the console the next version to be published and the release notes.
Yes with the [dry-run options](../01-usage/configuration.md#dryrun) which prints to the console the next version to be published and the release notes.
## Can I use semantic-release with Yarn?
If you are using a [local](../usage/installation.md#local-installation) **semantic-release** installation and run multiple CI jobs with different versions, the `yarn install` command will fail on jobs running with Node < 8 as **semantic-release** requires [Node >= 8.3](#why-does-semantic-release-require-node-version--83) and specifies it in its `package.json`s [`engines`](https://docs.npmjs.com/files/package.json#engines) key.
If you are using a [local](../01-usage/installation.md#local-installation) **semantic-release** installation and run multiple CI jobs with different versions, the `yarn install` command will fail on jobs running with Node < 8 as **semantic-release** requires [Node >= 8.3](#why-does-semantic-release-require-node-version--83) and specifies it in its `package.json`s [`engines`](https://docs.npmjs.com/files/package.json#engines) key.
The recommended solution is to use the [Yarn](https://yarnpkg.com) [--ignore-engines](https://yarnpkg.com/en/docs/cli/install#toc-yarn-install-ignore-engines) option to install the project dependencies on the CI environment, so Yarn will ignore the **semantic-release**'s `engines` key:
@@ -30,7 +48,7 @@ $ yarn install --ignore-engines
**Note**: Several CI services use Yarn by default if your repository contains a `yarn.lock` file. So you should override the install step to specify `yarn install --ignore-engines`.
Alternatively you can use a [global](../usage/installation.md#global-installation) **semantic-release** installation and make sure to install and run the `semantic-release` command only in a CI jobs running with Node >= 8.3.
Alternatively you can use a [global](../01-usage/installation.md#global-installation) **semantic-release** installation and make sure to install and run the `semantic-release` command only in a CI jobs running with Node >= 8.3.
If your CI environment provides [nvm](https://github.com/creationix/nvm) you can switch to Node 8 before installing and running the `semantic-release` command:
@@ -38,14 +56,14 @@ If your CI environment provides [nvm](https://github.com/creationix/nvm) you can
$ 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.
See the [CI pipelines recipes](../03-recipes/ci-pipelines-recipes.md) 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
For [local installation](../01-usage/installation.md#local-installation) replace
`npx semantic-release` with `yarn run semantic-release`.
For [global installation](../usage/installation.md#global-installation) replace
For [global installation](../01-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?
@@ -53,52 +71,47 @@ For [global installation](../usage/installation.md#global-installation) replace
Yes, **semantic-release** is a Node CLI application but it can be used to publish any type of packages.
To publish a non-Node package (without a `package.json`) you would need to:
- Use a [global](../usage/installation.md#global-installation) **semantic-release** installation
- Set **semantic-release** [options](../usage/configuration.md#options) via [CLI arguments or rc file](../usage/configuration.md#configuration)
- Use a [global](../01-usage/installation.md#global-installation) **semantic-release** installation
- Set **semantic-release** [options](../01-usage/configuration.md#options) via [CLI arguments or rc file](../01-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](../recipes/README.md#ci-configurations) for more details on specific CI environments.
See the [CI pipelines recipes](../03-recipes/ci-pipelines-recipes.md) 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.
In addition you will need to configure the **semantic-release** [plugins](../01-usage/plugins.md#plugins) to disable the [`@semantic-release/npm`](https://github.com/semantic-release/npm) plugin which is used by default and use a plugin for your project type.
Here is a basic example to create [GitHub releases](https://help.github.com/articles/about-releases) and use shell command to publish:
If there is no specific plugin for your project type you can use the [`@semantic-release/exec`](https://github.com/semantic-release/exec) plugin to publish the release with a shell command.
Here is a basic example to create [GitHub releases](https://help.github.com/articles/about-releases) and use a shell command to publish:
```json
{
"verifyConditions": ["@semantic-release/github"],
"prepare": [
{
"path": "@semantic-release/exec",
"cmd": "set-version ${nextRelease.version}"
}
],
"publish": [
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/github",
{
"path": "@semantic-release/exec",
"cmd": "publish-package"
}
],
["@semantic-release/exec", {
"prepareCmd" : "set-version ${nextRelease.version}",
"publishCmd" : "publish-package"
}]
]
}
```
**Note**: This is a theoretical example where the command `set-version` update the project version with the value passed as its first argument and `publish-package` publishes the package to a registry.
See the [package managers and languages recipes](../recipes/README.md#package-managers-and-languages) for more details on specific project types.
See the [package managers and languages recipes](../03-recipes/README.md#package-managers-and-languages) for more details on specific project types.
## Can I use semantic-release with any CI service?
Yes, **semantic-release** can be used with any CI service, as long as it provides:
- A way to set [authentication](../usage/ci-configuration.md#authentication) via environment variables
- A way to guarantee that the `semantic-release` command is [executed only after all the tests of all the jobs in the CI build pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
- A way to set [authentication](../01-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](../01-usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded)
See the [CI configuration recipes](../recipes/README.md#ci-configurations) for more details on specific CI environments.
See the [CI pipelines recipes](../03-recipes/ci-pipelines-recipes.md) for more details on specific CI environments.
## Can I run semantic-release on my local machine rather than on a CI server?
Yes, you can by explicitly setting the [`--no-ci` CLI option](../usage/configuration.md#options) option. You will also have to set the required [authentication](../usage/ci-configuration.md#authentication) via environment variables on your local machine, for example:
Yes, you can by explicitly setting the [`--no-ci` CLI option](../01-usage/configuration.md#ci) option. You will also have to set the required [authentication](../01-usage/ci-configuration.md#authentication) via environment variables on your local machine, for example:
```bash
$ NPM_TOKEN=<your_npm_token> GH_TOKEN=<your_github_token> npx semantic-release --no-ci
@@ -110,11 +123,11 @@ However this is not the recommended approach, as running unit and integration te
Yes, with the [`@semantic-release/gitlab-config`](https://github.com/semantic-release/gitlab-config) shareable configuration.
See the [GitLab CI recipes](../recipes/gitlab-ci.md#using-semantic-release-with-gitlab-ci) for the CI configuration.
See the [GitLab CI recipes](../03-recipes/gitlab-ci.md#using-semantic-release-with-gitlab-ci) for the CI configuration.
## Can I use semantic-release with any Git hosted environment?
By default **semantic-release** uses the [`@semantic-release/github`](https://github.com/semantic-release/github) plugin to publish a [GitHub release](https://help.github.com/articles/about-releases). For other Git hosted environment the [`@semantic-release/git`](https://github.com/semantic-release/git) and [`@semantic-release/changelog`](https://github.com/semantic-release/changelog) plugins can be used via [plugins configuration](../usage/plugins.md#configuration).
By default **semantic-release** uses the [`@semantic-release/github`](https://github.com/semantic-release/github) plugin to publish a [GitHub release](https://help.github.com/articles/about-releases). For other Git hosted environment the [`@semantic-release/git`](https://github.com/semantic-release/git) and [`@semantic-release/changelog`](https://github.com/semantic-release/changelog) plugins can be used via [plugins configuration](../01-usage/plugins.md).
See the [`@semantic-release/git`](https://github.com/semantic-release/git#semantic-releasegit) [`@semantic-release/changelog`](https://github.com/semantic-release/changelog#semantic-releasechangelog) plugins documentation for more details.
@@ -132,7 +145,7 @@ If you have introduced a breaking bug in a release you have 2 options:
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.
Depending on the package manager you are using, you might be able to un-publish or deprecate a release, in order to prevent users from downloading it by accident. For example npm allows you to [un-publish](https://docs.npmjs.com/cli/unpublish) [within 72 hours](https://www.npmjs.com/policies/unpublish) after releasing. You may also [deprecate](https://docs.npmjs.com/cli/deprecate) a release if you would rather avoid un-publishing.
In any case **do not remove the Git tag associated with the buggy version**, otherwise **semantic-release** will later try to republish that version. Publishing a version after un-publishing is not supported by most package managers.
@@ -217,13 +230,13 @@ See [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/i
**semantic-release** has a full unit and integration test suite that tests `npm` publishes against the [npm-registry-couchapp](https://github.com/npm/npm-registry-couchapp).
In addition the [verify conditions step](../../README.md#release-steps) verifies that all necessary conditions for proceeding with a release are met, and a new release will be performed [only if all your tests pass](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
In addition the [verify conditions step](../../README.md#release-steps) verifies that all necessary conditions for proceeding with a release are met, and a new release will be performed [only if all your tests pass](../01-usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded).
## Why does semantic-release require Node version >= 8.3?
**semantic-release** is written using the latest [ECMAScript 2017](https://www.ecma-international.org/publications/standards/Ecma-262.htm) features, without transpilation which **requires Node version 8.3 or higher**.
See [Node version requirement](../support/node-version.md#node-version-requirement) for more details and solutions.
See [Node version requirement](/node-version.md#node-version-requirement) for more details and solutions.
## What is npx?
@@ -12,7 +12,7 @@ See our [Node Support Policy](node-support-policy.md) for our long-term promise
The recommended approach is to run the `semantic-release` command from a CI job running on Node 8.3 or higher. This can either be a job used by your project to test on Node >= 8.3 or a dedicated job for the release steps.
See [CI configuration](../usage/ci-configuration.md) and [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
See [CI configuration](../01-usage/ci-configuration.md) and [CI pipelines recipes](../03-recipes/ci-pipelines-recipes.md) for more details.
## Alternative solutions
+20
View File
@@ -0,0 +1,20 @@
# Resources
## Videos
- ["Introducing Reliable Dependency and Release Management for npm Packages" - Gregor Martynus](https://www.youtube.com/watch?v=R2RJWLcfzwc)
- ["Kill all humans" - Jan Lehnardt](https://www.youtube.com/watch?v=ZXyx_1kN1L8&t=2s)
- ["Publishing JavaScript Packages" - JavaScript Air](https://javascriptair.com/episodes/2016-07-20)
- ["Managing Dependencies like a boss 😎" - JavaScript Air](https://javascriptair.com/episodes/2016-08-17)
- ["Dependency Hell Just Froze Over" - Stephan Bönnemann](https://www.youtube.com/watch?v=PA139CERNbc)
- ["semantic-release Q&A with Kent C. Dodds"](https://www.youtube.com/watch?v=g6y3DnhkjrI)
- ["We fail to follow SemVer – and why it needn’t matter" - Stephan Bönnemann](https://www.youtube.com/watch?v=tc2UgG5L7WM)
## Articles
- ["Introduction to SemVer" - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2)
- ["Introduction to Semantic Release" - liv](https://blog.greenkeeper.io/introduction-to-semantic-release-33f73b117c8)
## Tutorials
- ["How to Write a JavaScript Library - Automating Releases with semantic-release" – egghead.io](https://egghead.io/lessons/javascript-automating-releases-with-semantic-release)
+56
View File
@@ -0,0 +1,56 @@
# Troubleshooting
## You do not have permission to publish 'package-name'
When running semantic-release you might encounter the following error:
```bash
npm ERR! publish Failed PUT 403
npm ERR! code E403
npm ERR! You do not have permission to publish "<package-name>". Are you logged in as the correct user? : <package-name>
```
This is most likely related to a misconfiguration of the [npm registry authentication](https://github.com/semantic-release/npm#npm-registry-authentication) or to your user [missing permission](https://docs.npmjs.com/cli/team) for publishing.
It might also happen if the package name you are trying to publish already exists (in the case of npm, you may be trying to publish a new version of a package that is not yours, hence the permission error).
To verify if your package name is available you can use [npm-name-cli](https://github.com/sindresorhus/npm-name-cli):
```bash
$ npm install --global npm-name-cli
$ npm-name <package-name>
```
If the package name is not available, change it in your `package.json` or consider using an [npm scope](https://docs.npmjs.com/misc/scope).
## Squashed commits are ignored by **semantic-release**
**semantic-release** parses commits according to a [commit message convention](https://github.com/semantic-release/semantic-release#commit-message-format) to figure out how they affect the codebase. Commits that doesn't follow the project's commit message convention are simply ignored.
When [squashing commits](https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#_squashing) most Git tools will by default generate a new commit message with a summary of the squashed commits. This commit message will most likely not be compliant with the project's commit message convention and therefore will be ignored by **semantic-release**.
When squashing commits make sure to rewrite the resulting commit message to be compliant with the project's commit message convention.
**Note**: if the resulting squashed commit would encompasses multiple changes (for example multiple unrelated features or fixes) then it's probably not a good idea to squash those commits together. A commit should contain exactly one self-contained functional change and a functional change should be contained in exactly one commit. See [atomic commits](https://en.wikipedia.org/wiki/Atomic_commit).
## `reference already exists` error when pushing tag
**semantic-release** read [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging) that are present in the history of your release branch in order to determine the last release published. Then it determines the next version to release based on the commits pushed since then and create the corresponding tag.
If a tag with the name already in your repository, Git will throw and error as tags must be unique across the repository.
This situation happens when you have a version tag identical to the new one **semantic-release** is trying to create that is not in the history of the current branch.
If an actual release with that version number was published you need to merge all the commits up to that release into your release branch.
If there is no published release with that version number, the tag must be deleted.
```bash
# Verify if the commit exists in the repository
$ git rev-list -1 <tag name>
# If a commit sha is returned, then the tag exists
# Verify the branches having the tagged commit in their history
$ git branch --contains <tag name>
# Delete the tag
$ git tag -d <tag name>
$ git push origin :refs/tags/<tag name>
```
+5 -5
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
- [Recipes](recipes/README.md) - Community written recipes for common **semantic-release** use-cases
- [Developer Guide](developer-guide/README.md) - The essentials of writing a **semantic-release** plugin or shareable configurations
- [Support](support/README.md) - FAQ and troubleshooting
- [Usage](01-usage/README.md) - **semantic-release** installation and configuration
- [Extending](02-extending/README.md)- Extending **semantic-release** with plugins and shareable configurations
- [Recipes](03-recipes/README.md) - Community written recipes for common **semantic-release** use-cases
- [Developer Guide](04-developer-guide/README.md) - The essentials of writing a **semantic-release** plugin or shareable configurations
- [Support](05-support/README.md) - FAQ and troubleshooting
-1
View File
@@ -1 +0,0 @@
# Plugin developer guide
-55
View File
@@ -1,55 +0,0 @@
# Plugins list
## Default plugins
- [@semantic-release/github](https://github.com/semantic-release/github)
- [verifyConditions](https://github.com/semantic-release/github#verifyconditions): Verify the presence and the validity of the GitHub authentication and release configuration
- [publish](https://github.com/semantic-release/github#publish): Publish a [GitHub release](https://help.github.com/articles/about-releases)
- [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
- [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
- [@semantic-release/gitlab](https://github.com/semantic-release/gitlab)
- [verifyConditions](https://github.com/semantic-release/gitlab#verifyconditions): Verify the presence and the validity of the GitLab authentication and release configuration
- [publish](https://github.com/semantic-release/gitlab#publish): Publish a [GitLab release](https://docs.gitlab.com/ce/workflow/releases.html)
- [@semantic-release/git](https://github.com/semantic-release/git)
- [verifyConditions](https://github.com/semantic-release/git#verifyconditions): Verify the presence and the validity of the Git authentication and release configuration
- [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
- [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
- [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
- [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-gcr](https://github.com/carlos-cubas/semantic-release-gcr) Set of semantic-release plugins for publishing a docker image to Google Container Registry
- [verifyConditions](https://github.com/carlos-cubas/semantic-release-gcr#verifyconditions) Verify that all needed configuration is present and login to the Docker registry.
- [publish](https://github.com/carlos-cubas/semantic-release-gcr#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.
@@ -1,7 +0,0 @@
# Shareable configurations list
## Official configurations
- [@semantic-release/apm-config](https://github.com/semantic-release/apm-config) - semantic-release shareable configuration for releasing atom packages
- [@semantic-release/gitlab-config](https://github.com/semantic-release/gitlab-config) - semantic-release shareable configuration for GitLab
## Community configurations
-12
View File
@@ -1,12 +0,0 @@
# Recipes
## CI configurations
- [CircleCI 2.0 workflows](circleci-workflows.md)
- [Travis CI](travis.md)
- [Travis CI with build stages](travis-build-stages.md)
- [GitLab CI](gitlab-ci.md)
## Git hosted services
- [Git authentication with SSH keys](git-auth-ssh-keys.md)
## Package managers and languages
-129
View File
@@ -1,129 +0,0 @@
# Using semantic-release with [Travis CI](https://travis-ci.org)
## Environment variables
The [Authentication](../usage/ci-configuration.md#authentication) environment variables can be configured in [Travis Repository Settings](https://docs.travis-ci.com/user/environment-variables/#defining-variables-in-repository-Settings) or with the [travis env set CLI](https://github.com/travis-ci/travis.rb#env).
Alternatively, the default `NPM_TOKEN` and `GH_TOKEN` can be easily [setup with semantic-release-cli](../usage/ci-configuration.md#automatic-setup-with-semantic-release-cli).
## Single Node job configuration
For projects that require to be tested only with a single [Node version](https://docs.travis-ci.com/user/getting-started/#Selecting-a-different-programming-language) on [one Operating System](https://docs.travis-ci.com/user/getting-started/#Selecting-infrastructure-(optional)).
**Note**: [Node 8 is the minimal version required](../support/FAQ.md#why-does-semantic-release-require-node-version--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 `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: node_js
node_js: 8
deploy:
provider: script
skip_cleanup: true
script:
- npx semantic-release
```
### `package.json` configuration for single Node job
A `package.json` is required only for [local](../usage/installation.md#local-installation) **semantic-release** installation.
```json
{
"devDependencies": {
"semantic-release": "^11.0.0"
}
}
```
## Multiple Node jobs configuration
For projects that require to be tested with multiple [Node versions](https://docs.travis-ci.com/user/languages/javascript-with-nodejs/#Specifying-Node.js-versions) and/or on multiple [Operating Systems](https://docs.travis-ci.com/user/multi-os).
**Note**: At least one job must run a [Node >= 8 version](../support/FAQ.md#why-does-semantic-release-require-node-version--83).
### `.travis.yml` configuration for multiple Node jobs
This example is a minimal configuration for **semantic-release** with a build running Node 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 [Run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
```yaml
language: node_js
node_js:
- 8
- 6
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).
### `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",
"travis-deploy-once": "^5.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) on Linux and OSX. See [Travis - Customizing the Build](https://docs.travis-ci.com/user/customizing-the-build) for additional configuration options.
This example uses [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once) in order to [run `semantic-release` only after all tests succeeded](../usage/ci-configuration.md#run-semantic-release-only-after-all-tests-succeeded). Alternatively you can use [Travis CI Build Stages recipe](travis-build-stages.md).
It's recommended to run the `semantic-release` command in the [Travis `deploy` step](https://docs.travis-ci.com/user/customizing-the-build/#The-Build-Lifecycle) so if an error occurs the build will fail and Travis will send a notification.
**Note**: It's not recommended to run the `semantic-release` command in the Travis `script` step as each script in this step will be executed regardless of the outcome of the previous one. See [travis-ci/travis-ci#1066](https://github.com/travis-ci/travis-ci/issues/1066).
```yaml
language: go
go:
- 1.6
- 1.7
os:
- linux
- osx
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).
-20
View File
@@ -1,20 +0,0 @@
# Resources
## Videos
- ["Introducing Reliable Dependency and Release Management for npm Packages" - Gregor Martynus](https://www.youtube.com/watch?v=R2RJWLcfzwc)
- ["Kill all humans" - Jan Lehnardt](https://www.youtube.com/watch?v=ZXyx_1kN1L8&t=2s)
- [Publishing JavaScript Packages" - JavaScript Air](https://javascriptair.com/episodes/2016-07-20)
- ["Managing Dependencies like a boss 😎" - JavaScript Air](https://javascriptair.com/episodes/2016-08-17)
- ["Dependency Hell Just Froze Over" - Stephan Bönnemann](https://www.youtube.com/watch?v=PA139CERNbc)
- [“semantic-release Q&A with Kent C. Dodds”](https://www.youtube.com/watch?v=g6y3DnhkjrI)
- [“We fail to follow SemVer – and why it needn’t matter” - Stephan Bönnemann](https://www.youtube.com/watch?v=tc2UgG5L7WM)
## Articles
- [“Introduction to SemVer” - Irina Gebauer](https://blog.greenkeeper.io/introduction-to-semver-d272990c44f2)
- ["Introduction to Semantic Release" - liv](https://blog.greenkeeper.io/introduction-to-semantic-release-33f73b117c8)
## Tutorials
- [“How to Write a JavaScript Library - Automating Releases with semantic-release” – egghead.io](https://egghead.io/lessons/javascript-automating-releases-with-semantic-release)
-56
View File
@@ -1,56 +0,0 @@
# Troubleshooting
## ENOTINHISTORY Commit not in history
This error happens when the commit associated with the last release cannot be found in the branch history.
Multiple situation can cause this issue:
- The package name configured in your `package.json` already exists and **semantic-release** obtains the last release of that package, which is unrelated to yours
- The commit history has been rewritten since the last release (with `git rebase` and `git push -f`)
If the package name configured in your `package.json` already exits, you should change it, and commit the `package.json`. Then **semantic-release** will proceed normally and make the initial release.
If you can identify the commit in your branch history that should be associated with the release version mentioned in the error message you can recover by tagging this commit:
```bash
$ git tag -f v<version of the last release> <commit sha1 corresponding to last release>
$ git push -f --tags origin <your release branch>
```
## ENOGITHEAD There is no commit associated with last release
This error happens when there is no commit associated with the last release that can be found in the package metadata on the npm registry.
This usually happen when the last release has been made without access to the git repository informations.
You can recover from that issue by identifying the commit in your branch history that should have been associated with the release version mentioned in the error message and tagging this commit:
```bash
$ git tag -f v<version of the last release> <commit sha1 corresponding to last release>
$ git push -f --tags origin <your release branch>
```
## 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).
-50
View File
@@ -1,50 +0,0 @@
# CI configuration
## Run `semantic-release` only after all tests succeeded
The `semantic-release` command must be executed only after all the tests in the CI build pass. If the build runs multiple jobs (for example to test on multiple Operating Systems or Node versions) the CI has to be configured to guarantee that the `semantic-release` command is executed only after all jobs are successful. This can be achieved with [Travis Build Stages](https://docs.travis-ci.com/user/build-stages), [CircleCI Workflows](https://circleci.com/docs/2.0/workflows), [Codeship Deployment Pipelines](https://documentation.codeship.com/basic/builds-and-configuration/deployment-pipelines), [GitLab Pipelines](https://docs.gitlab.com/ee/ci/pipelines.html#introduction-to-pipelines-and-jobs), [Wercker Workflows](http://devcenter.wercker.com/docs/workflows), [GoCD Pipelines](https://docs.gocd.org/current/introduction/concepts_in_go.html#pipeline) or specific tools like [`travis-deploy-once`](https://github.com/semantic-release/travis-deploy-once).
See [CI configuration recipes](../recipes/README.md#ci-configurations) for more details.
## Authentication
**semantic-release** requires push access to the project Git repository in order to create [Git tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging). The Git authentication can be set with one of the following environment variables:
| Variable | Description |
|---------------------------------|-------------------------------------------------------------------------------------------------------------------------------|
| `GH_TOKEN` or `GITHUB_TOKEN` | A GitHub [personal access token](https://help.github.com/articles/creating-a-personal-access-token-for-the-command-line). |
| `GL_TOKEN` or `GITLAB_TOKEN` | A GitLab [personal access token](https://docs.gitlab.com/ce/user/profile/personal_access_tokens.html). |
| `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). |
`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) 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
cd your-module
semantic-release-cli setup
```
![dialogue](../../media/semantic-release-cli.png)
See the [semantic-release-cli](https://github.com/semantic-release/cli#what-it-does) documentation for more details.
-197
View File
@@ -1,197 +0,0 @@
# Configuration
In order to customize **semantic-release**’s behavior, [options](#options) and [plugins](plugins.md) can be set via:
- A `.releaserc` file, written in YAML or JSON, with optional extensions: .`yaml`/`.yml`/`.json`/`.js`
- A `release.config.js` file that exports an object
- A `release` key in the project's `package.json` file
- CLI arguments
The following three examples are the same.
Via CLI argument:
```bash
$ semantic-release --branch next
```
Via `release` key in the project's `package.json` file:
```json
{
"release": {
"branch": "next"
}
}
```
```bash
$ semantic-release
```
Via `.releaserc` file:
```json
{
"branch": "next"
}
```
```bash
$ semantic-release
```
**Note**: CLI arguments take precedence over options configured in the configuration file.
**Note**: Plugin options cannot be defined via CLI arguments and must be defined in the configuration file.
**Note**: When configuring via `package.json`, the configuration must be under the `release` property. However, when using a `.releaserc` or a `release.config.js` file, the configuration must be set without a `release` property.
## 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
### extends
Type: `Array`, `String`<br>
CLI arguments: `-e`, `--extends`
List of modules or file paths containing a [shareable configuration](shareable-configurations.md). If multiple shareable configurations are set, they will be imported in the order defined with each configuration option taking precedence over the options defined in a previous shareable configuration.
**Note**: Options defined via CLI arguments or in the configuration file will take precedence over the ones defined in any shareable configuration.
### branch
Type: `String`<br>
Default: `master`<br>
CLI arguments: `-b`, `--branch`
The branch on which releases should happen.
### repositoryUrl
Type: `String`<br>
Default: `repository` property in `package.json` or [git origin url](https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes)<br>
CLI arguments: `-r`, `--repository-url`
The git repository URL.
Any valid git url format is supported (See [Git protocols](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols)).
### tagFormat
Type: `String`<br>
Default: `v${version}`<br>
CLI arguments: `-t`, `--tag-format`
The [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) format used by **semantic-release** to identify releases. The tag name is generated with [Lodash template](https://lodash.com/docs#template) and will be compiled with the `version` variable.
**Note**: The `tagFormat` must contain the `version` variable exactly once and compile to a [valid Git reference](https://git-scm.com/docs/git-check-ref-format#_description).
### dryRun
Type: `Boolean`<br>
Default: `false` if running in a CI environment, `true` otherwise<br>
CLI arguments: `-d`, `--dry-run`
Dry-run mode, skip publishing, print next version and release notes.
### noCi
Type: `Boolean`<br>
Default: `false`<br>
CLI arguments: `--no-ci`
Skip Continuous Integration environment verifications. This allows for making releases from a local machine.
### debug
Type: `Boolean`<br>
Default: `false`<br>
CLI argument: `--debug`
Output debugging information. It can also be enabled by setting the `DEBUG` environment variable to `semantic-release:*`.
### verifyConditions
Type: `Array`, `String`, `Object`<br>
Default: `['@semantic-release/npm', '@semantic-release/github']`<br>
CLI argument: `--verify-conditions`
Define the list of [verify conditions plugins](plugins.md#verifyconditions-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
### analyzeCommits
Type: `Array`, `String`, `Object`<br>
Default: `'@semantic-release/commit-analyzer'`<br>
CLI argument: `--analyze-commits`
Define the [analyze commits plugin](plugins.md#analyzecommits-plugin).
See [Plugins configuration](plugins.md#configuration) for more details.
### verifyRelease
Type: `Array`, `String`, `Object`<br>
Default: `[]`<br>
CLI argument: `--verify-release`
Define the list of [verify release plugins](plugins.md#verifyrelease-plugin). Plugins will run in series, in the order defined in the `Array`.
See [Plugins configuration](plugins.md#configuration) for more details.
### generateNotes
Type: `Array`, `String`, `Object`<br>
Default: `['@semantic-release/release-notes-generator']`<br>
CLI argument: `--generate-notes`
Define the [generate notes plugins](plugins.md#generatenotes-plugin).
See [Plugins configuration](plugins.md#configuration) for more details.
### prepare
Type: `Array`, `String`, `Object`<br>
Default: `['@semantic-release/npm']`<br>
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.
### publish
Type: `Array`, `String`, `Object`<br>
Default: `['@semantic-release/npm', '@semantic-release/github']`<br>
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`<br>
Default: `['@semantic-release/github']`<br>
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`<br>
Default: `['@semantic-release/github']`<br>
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.
-29
View File
@@ -1,29 +0,0 @@
# Installation
## Local installation
For [Node modules projects](https://docs.npmjs.com/getting-started/creating-node-modules) we recommend installing **semantic-release** locally and running the `semantic-release` command with [npx](https://www.npmjs.com/package/npx):
```bash
$ npm install --save-dev semantic-release
```
Then in the CI environment:
```bash
$ npx semantic-release
```
**Note:** `npx` is a tool bundled with `npm@>=5.2.0`. It is used to conveniently find the semantic-release binary and to execute it. See [What is npx](../support/FAQ.md#what-is-npx) for more details.
## Global installation
For other type of projects we recommend installing **semantic-release** directly in the CI environment, also with [npx](https://www.npmjs.com/package/npx):
```bash
$ npx semantic-release
```
**Note:** For a global installation, it's recommended to specify the major **semantic-release** version to install (for example with with `npx semantic-release@15`, 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.
-114
View File
@@ -1,114 +0,0 @@
# Plugins
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
Responsible for verifying conditions necessary to proceed with the release: configuration is correct, authentication token are valid, etc...
Default implementation: [@semantic-release/npm](https://github.com/semantic-release/npm#verifyconditions) and [@semantic-release/github](https://github.com/semantic-release/github#verifyconditions).<br>
Optional.<br>
Accept multiple plugins.
### analyzeCommits plugin
Responsible for determining the type of the next release (`major`, `minor` or `patch`).
Default implementation: [@semantic-release/commit-analyzer](https://github.com/semantic-release/commit-analyzer).<br>
Required.<br>
Accept only one plugin.
### verifyRelease plugin
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.<br>
Optional.<br>
Accept multiple plugins.
### generateNotes plugin
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).<br>
Optional.<br>
Accept multiple plugins.
### 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).<br>
Optional.<br>
Accept multiple plugins.
### publish plugin
Responsible for publishing the release.
Default implementation: [@semantic-release/npm](https://github.com/semantic-release/npm#publish) and [@semantic-release/github](https://github.com/semantic-release/github#publish).<br>
Optional.<br>
Accept multiple plugins.
### success plugin
Responsible for notifying of a new release.
Default implementation: [@semantic-release/github](https://github.com/semantic-release/github#success).<br>
Optional.<br>
Accept multiple plugins.
### fail plugin
Responsible for notifying of a failed release.
Default implementation: [@semantic-release/github](https://github.com/semantic-release/github#fail).<br>
Optional.<br>
Accept multiple plugins.
## 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 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
{
"release": {
"verifyConditions": [
{
"path": "@semantic-release/exec",
"cmd": "verify-conditions.sh"
},
"@semantic-release/npm",
"@semantic-release/github"
],
"analyzeCommits": "custom-plugin",
"verifyRelease": [
{
"path": "@semantic-release/exec",
"cmd": "verify-release.sh"
},
],
"generateNotes": "./build/my-plugin.js",
"githubUrl": "https://my-ghe.com",
"githubApiPathPrefix": "/api-prefix"
}
}
```
With this configuration:
- the `custom-plugin` npm module will be used to [analyze commits](#analyzecommits-plugin)
- the `./build/my-plugin.js` script will be used to [generate release notes](#generatenotes-plugin)
- the [`@semantic-release/exec`](https://github.com/semantic-release/exec), [`@semantic-release/npm`](https://github.com/semantic-release/npm) and [`@semantic-release/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)
- the `githubUrl` and `githubApiPathPrefix` options will be set to respectively `https://my-ghe.com` and `/api-prefix` for all plugins
-7
View File
@@ -1,7 +0,0 @@
# Shareable configurations
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).
+49 -41
View File
@@ -1,4 +1,3 @@
const process = require('process');
const {template, pick} = require('lodash');
const marked = require('marked');
const TerminalRenderer = require('marked-terminal');
@@ -14,18 +13,18 @@ const getLastRelease = require('./lib/get-last-release');
const {extractErrors} = require('./lib/utils');
const getGitAuthUrl = require('./lib/get-git-auth-url');
const getLogger = require('./lib/get-logger');
const {fetch, verifyAuth, isBranchUpToDate, gitHead: getGitHead, tag, push} = require('./lib/git');
const {fetch, verifyAuth, isBranchUpToDate, getGitHead, tag, push} = require('./lib/git');
const getError = require('./lib/get-error');
const {COMMIT_NAME, COMMIT_EMAIL} = require('./lib/definitions/constants');
marked.setOptions({renderer: new TerminalRenderer()});
async function run(context, plugins) {
const {isCi, branch: ciBranch, isPr} = envCi();
const {cwd, env, options, logger} = context;
const {isCi, branch: ciBranch, isPr} = envCi({env, cwd});
if (!isCi && !options.dryRun && !options.noCi) {
logger.log('This run was not triggered in a known CI environment, running in dry-run mode.');
logger.warn('This run was not triggered in a known CI environment, running in dry-run mode.');
options.dryRun = true;
} else {
// When running on CI, set the commits author and commiter info and prevent the `git` CLI to prompt for username/password. See #703.
@@ -47,28 +46,34 @@ async function run(context, plugins) {
if (ciBranch !== options.branch) {
logger.log(
`This test run was triggered on the branch ${ciBranch}, while semantic-release is configured to only publish from ${
options.branch
}, therefore a new version won’t be published.`
`This test run was triggered on the branch ${ciBranch}, while semantic-release is configured to only publish from ${options.branch}, therefore a new version won’t be published.`
);
return false;
}
logger.success(`Run automated release from branch ${ciBranch}`);
logger[options.dryRun ? 'warn' : 'success'](
`Run automated release from branch ${ciBranch}${options.dryRun ? ' in dry-run mode' : ''}`
);
await verify(context);
options.repositoryUrl = await getGitAuthUrl(context);
try {
await verifyAuth(options.repositoryUrl, options.branch, {cwd, env});
} catch (err) {
if (!(await isBranchUpToDate(options.branch, {cwd, env}))) {
logger.log(
`The local branch ${options.branch} is behind the remote one, therefore a new version won't be published.`
);
return false;
try {
await verifyAuth(options.repositoryUrl, options.branch, {cwd, env});
} catch (error) {
if (!(await isBranchUpToDate(options.branch, {cwd, env}))) {
logger.log(
`The local branch ${options.branch} is behind the remote one, therefore a new version won't be published.`
);
return false;
}
throw error;
}
logger.error(`The command "${err.cmd}" failed with the error message ${err.stderr}.`);
} catch (error) {
logger.error(`The command "${error.cmd}" failed with the error message ${error.stderr}.`);
throw getError('EGITNOPERMISSION', {options});
}
@@ -87,32 +92,37 @@ async function run(context, plugins) {
logger.log('There are no relevant changes, so no new version is released.');
return false;
}
context.nextRelease = nextRelease;
nextRelease.version = getNextVersion(context);
nextRelease.gitTag = template(options.tagFormat)({version: nextRelease.version});
await plugins.verifyRelease(context);
if (options.dryRun) {
const notes = await plugins.generateNotes(context);
logger.log(`Release note for version ${nextRelease.version}:`);
if (notes) {
context.stdout.write(marked(notes));
}
} else {
nextRelease.notes = await plugins.generateNotes(context);
await plugins.prepare(context);
nextRelease.notes = await plugins.generateNotes(context);
await plugins.prepare(context);
if (options.dryRun) {
logger.warn(`Skip ${nextRelease.gitTag} tag creation in dry-run mode`);
} else {
// Create the tag before calling the publish plugins as some require the tag to exists
await tag(nextRelease.gitTag, {cwd, env});
await push(options.repositoryUrl, options.branch, {cwd, env});
await push(options.repositoryUrl, {cwd, env});
logger.success(`Created tag ${nextRelease.gitTag}`);
}
context.releases = await plugins.publish(context);
context.releases = await plugins.publish(context);
await plugins.success(context);
await plugins.success(context);
logger.success(`Published release ${nextRelease.version}`);
logger.success(`Published release ${nextRelease.version}`);
if (options.dryRun) {
logger.log(`Release note for version ${nextRelease.version}:`);
if (nextRelease.notes) {
context.stdout.write(marked(nextRelease.notes));
}
}
return pick(context, ['lastRelease', 'commits', 'nextRelease', 'releases']);
@@ -132,13 +142,13 @@ function logErrors({logger, stderr}, err) {
}
}
async function callFail(context, plugins, error) {
const errors = extractErrors(error).filter(error => error.semanticRelease);
async function callFail(context, plugins, err) {
const errors = extractErrors(err).filter(err => err.semanticRelease);
if (errors.length > 0) {
try {
await plugins.fail({...context, errors});
} catch (err) {
logErrors(context, err);
} catch (error) {
logErrors(context, error);
}
}
}
@@ -158,15 +168,13 @@ module.exports = async (opts = {}, {cwd = process.cwd(), env = process.env, stdo
const result = await run(context, plugins);
unhook();
return result;
} catch (err) {
if (!options.dryRun) {
await callFail(context, plugins, err);
}
throw err;
} catch (error) {
await callFail(context, plugins, error);
throw error;
}
} catch (err) {
logErrors(context, err);
} catch (error) {
logErrors(context, error);
unhook();
throw err;
throw error;
}
};
+1 -1
View File
@@ -1,4 +1,4 @@
const RELEASE_TYPE = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'];
const RELEASE_TYPE = ['prerelease', 'prepatch', 'patch', 'preminor', 'minor', 'premajor', 'major'];
const FIRST_RELEASE = '1.0.0';
+32 -27
View File
@@ -1,30 +1,29 @@
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 [homepage] = pkg.homepage.split('#');
const stringify = obj => (isString(obj) ? obj : inspect(obj, {breakLength: Infinity, depth: 2, maxArrayLength: 5}));
const linkify = file => `${homepage}/blob/caribou/${file}`;
const linkify = file => `${homepage}/blob/master/${file}`;
module.exports = {
ENOGITREPO: () => ({
ENOGITREPO: ({cwd}) => ({
message: 'Not running from a git repository.',
details: `The \`semantic-release\` command must be executed from a Git repository.
The current working directory is \`${process.cwd()}\`.
The current working directory is \`${cwd}\`.
Please verify your CI configuration to make sure the \`semantic-release\` command is executed from the root of the cloned repository.`,
}),
ENOREPOURL: () => ({
message: 'The `repositoryUrl` option is required.',
details: `The [repositoryUrl option](${linkify(
'docs/usage/configuration.md#repositoryurl'
'docs/01-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'
'docs/01-usage/configuration.md'
)}).`,
}),
EGITNOPERMISSION: ({options}) => ({
@@ -34,15 +33,15 @@ Please make sure to add the \`repositoryUrl\` to the [semantic-release configura
}\` on remote Git repository with URL \`${options.repositoryUrl}\`.
Please refer to the [authentication configuration documentation](${linkify(
'docs/usage/ci-configuration.md#authentication'
'docs/01-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'
'docs/01-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'
'docs/01-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)}\`.`,
@@ -50,20 +49,26 @@ Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`
ETAGNOVERSION: ({tagFormat}) => ({
message: 'Invalid `tagFormat` option.',
details: `The [tagFormat](${linkify(
'docs/usage/configuration.md#tagformat'
'docs/01-usage/configuration.md#tagformat'
)}) option must contain the variable \`version\` exactly once.
Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`,
}),
EPLUGINCONF: ({type, multiple, required, pluginConf}) => ({
EPLUGINCONF: ({type, required, pluginConf}) => ({
message: `The \`${type}\` plugin configuration is invalid.`,
details: `The [${type} plugin configuration](${linkify(`docs/usage/plugins.md#${toLower(type)}-plugin`)}) ${
details: `The [${type} plugin configuration](${linkify(`docs/01-usage/plugins.md#${toLower(type)}-plugin`)}) ${
required ? 'is required and ' : ''
}must be ${
multiple ? 'a single or an array of plugins' : 'a single plugin'
} definition. A plugin definition is either a string or an object with a \`path\` property.
} must be a single or an array of plugins definition. A plugin definition is an npm module name, optionnaly wrapped in an array with an object.
Your configuration for the \`${type}\` plugin is \`${stringify(pluginConf)}\`.`,
Your configuration for the \`${type}\` plugin is \`${stringify(pluginConf)}\`.`,
}),
EPLUGINSCONF: ({plugin}) => ({
message: 'The `plugins` configuration is invalid.',
details: `The [plugins](${linkify(
'docs/01-usage/configuration.md#plugins'
)}) option must be an array of plugin definions. A plugin definition is an npm module name, optionnaly wrapped in an array with an object.
The invalid configuration is \`${stringify(plugin)}\`.`,
}),
EPLUGIN: ({pluginName, type}) => ({
message: `A plugin configured in the step ${type} is not a valid semantic-release plugin.`,
@@ -72,7 +77,7 @@ Your configuration for the \`tagFormat\` option is \`${stringify(tagFormat)}\`.`
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'
'docs/01-usage/plugins.md'
)}) documentation for more details.`,
}),
EANALYZECOMMITSOUTPUT: ({result, pluginName}) => ({
@@ -87,9 +92,9 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the
- 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'
)})`,
- A link to the **semantic-release** plugin developer guide: [${linkify(
'docs/04-developer-guide/plugin.md'
)}](${linkify('docs/04-developer-guide/plugin.md')})`,
}),
EGENERATENOTESOUTPUT: ({result, pluginName}) => ({
message: 'The `generateNotes` plugin returned an invalid value. It must return a `String`.',
@@ -101,9 +106,9 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the
- 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'
)})`,
- A link to the **semantic-release** plugin developer guide: [${linkify(
'docs/04-developer-guide/plugin.md'
)}](${linkify('docs/04-developer-guide/plugin.md')})`,
}),
EPUBLISHOUTPUT: ({result, pluginName}) => ({
message: 'A `publish` plugin returned an invalid value. It must return an `Object`.',
@@ -115,8 +120,8 @@ We recommend to report the issue to the \`${pluginName}\` authors, providing the
- 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'
)})`,
- A link to the **semantic-release** plugin developer guide: [${linkify(
'docs/04-developer-guide/plugin.md'
)}](${linkify('docs/04-developer-guide/plugin.md')})`,
}),
};
+27 -24
View File
@@ -1,35 +1,40 @@
const {isString, isPlainObject} = require('lodash');
const {gitHead} = require('../git');
const {getGitHead} = require('../git');
const hideSensitive = require('../hide-sensitive');
const {hideSensitiveValues} = require('../utils');
const {RELEASE_TYPE, RELEASE_NOTES_SEPARATOR} = require('./constants');
module.exports = {
verifyConditions: {
default: ['@semantic-release/npm', '@semantic-release/github'],
multiple: true,
required: false,
dryRun: true,
pipelineConfig: () => ({settleAll: true}),
},
analyzeCommits: {
default: '@semantic-release/commit-analyzer',
multiple: false,
default: ['@semantic-release/commit-analyzer'],
required: true,
dryRun: true,
outputValidator: output => !output || RELEASE_TYPE.includes(output),
preprocess: ({commits, ...inputs}) => ({
...inputs,
commits: commits.filter(commit => !/\[skip\s+release\]|\[release\s+skip\]/i.test(commit.message)),
}),
postprocess: ([result]) => result,
postprocess: results =>
RELEASE_TYPE[
results.reduce((highest, result) => {
const typeIndex = RELEASE_TYPE.indexOf(result);
return typeIndex > highest ? typeIndex : highest;
}, -1)
],
},
verifyRelease: {
default: false,
multiple: true,
required: false,
dryRun: true,
pipelineConfig: () => ({settleAll: true}),
},
generateNotes: {
default: ['@semantic-release/release-notes-generator'],
multiple: true,
required: false,
dryRun: true,
outputValidator: output => !output || isString(output),
pipelineConfig: () => ({
getNextInput: ({nextRelease, ...context}, notes) => ({
@@ -40,51 +45,49 @@ module.exports = {
},
}),
}),
postprocess: results => results.filter(Boolean).join(RELEASE_NOTES_SEPARATOR),
postprocess: (results, {env}) => hideSensitive(env)(results.filter(Boolean).join(RELEASE_NOTES_SEPARATOR)),
},
prepare: {
default: ['@semantic-release/npm'],
multiple: true,
required: false,
pipelineConfig: ({generateNotes}, logger) => ({
dryRun: false,
pipelineConfig: ({generateNotes}) => ({
getNextInput: async context => {
const newGitHead = await gitHead({cwd: context.cwd});
const newGitHead = await getGitHead({cwd: context.cwd});
// If previous prepare plugin has created a commit (gitHead changed)
if (context.nextRelease.gitHead !== newGitHead) {
context.nextRelease.gitHead = newGitHead;
// Regenerate the release notes
logger.log('Call plugin %s', 'generateNotes');
context.nextRelease.notes = await generateNotes(context);
}
// Call the next prepare plugin with the updated `nextRelease`
return context;
},
}),
},
publish: {
default: ['@semantic-release/npm', '@semantic-release/github'],
multiple: true,
required: false,
dryRun: false,
outputValidator: output => !output || isPlainObject(output),
pipelineConfig: () => ({
// Add `nextRelease` and plugin properties to published release
transform: (release, step, {nextRelease}) => ({
...(isPlainObject(release) ? release : {}),
...nextRelease,
...(release === false ? {} : nextRelease),
...release,
...step,
}),
}),
},
success: {
default: ['@semantic-release/github'],
multiple: true,
required: false,
dryRun: false,
pipelineConfig: () => ({settleAll: true}),
preprocess: ({releases, env, ...inputs}) => ({...inputs, env, releases: hideSensitiveValues(env, releases)}),
},
fail: {
default: ['@semantic-release/github'],
multiple: true,
required: false,
dryRun: false,
pipelineConfig: () => ({settleAll: true}),
preprocess: ({errors, env, ...inputs}) => ({...inputs, env, errors: hideSensitiveValues(env, errors)}),
},
};
+33 -15
View File
@@ -1,4 +1,4 @@
const {castArray, pickBy, isUndefined, isNull, isString, isPlainObject} = require('lodash');
const {castArray, pickBy, isNil, isString, isPlainObject} = require('lodash');
const readPkgUp = require('read-pkg-up');
const cosmiconfig = require('cosmiconfig');
const resolveFrom = require('resolve-from');
@@ -6,6 +6,7 @@ const debug = require('debug')('semantic-release:config');
const {repoUrl} = require('./git');
const PLUGINS_DEFINITIONS = require('./definitions/plugins');
const plugins = require('./plugins');
const {validatePlugin, parseConfig} = require('./plugins/utils');
const CONFIG_NAME = 'release';
const CONFIG_FILES = [
@@ -20,9 +21,16 @@ const CONFIG_FILES = [
module.exports = async (context, opts) => {
const {cwd, env} = context;
const {config} = (await cosmiconfig(CONFIG_NAME, {searchPlaces: CONFIG_FILES}).search(cwd)) || {};
const {config, filepath} = (await cosmiconfig(CONFIG_NAME, {searchPlaces: CONFIG_FILES}).search(cwd)) || {};
debug('load config from: %s', filepath);
// Merge config file options and CLI/API options
let options = {...config, ...opts};
if (options.ci === false) {
options.noCi = true;
}
const pluginsPath = {};
let extendPaths;
({extends: extendPaths, ...options} = options);
@@ -34,17 +42,21 @@ module.exports = async (context, opts) => {
// For each plugin defined in a shareable config, save in `pluginsPath` the extendable config path,
// so those plugin will be loaded relatively to the config file
Object.entries(extendsOpts).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 => {
pluginsPath[plugin] = extendPath;
});
}
return pluginsPath;
}, pluginsPath);
Object.entries(extendsOpts)
.filter(([, value]) => Boolean(value))
.reduce((pluginsPath, [option, value]) => {
castArray(value).forEach(plugin => {
if (option === 'plugins' && validatePlugin(plugin)) {
pluginsPath[parseConfig(plugin)[0]] = extendPath;
} else if (
PLUGINS_DEFINITIONS[option] &&
(isString(plugin) || (isPlainObject(plugin) && isString(plugin.path)))
) {
pluginsPath[isString(plugin) ? plugin : plugin.path] = extendPath;
}
});
return pluginsPath;
}, pluginsPath);
return {...result, ...extendsOpts};
}, {}),
@@ -57,8 +69,14 @@ module.exports = async (context, opts) => {
branch: 'master',
repositoryUrl: (await pkgRepoUrl({normalize: false, cwd})) || (await repoUrl({cwd, env})),
tagFormat: `v\${version}`,
plugins: [
'@semantic-release/commit-analyzer',
'@semantic-release/release-notes-generator',
'@semantic-release/npm',
'@semantic-release/github',
],
// Remove `null` and `undefined` options so they can be replaced with default ones
...pickBy(options, option => !isUndefined(option) && !isNull(option)),
...pickBy(options, option => !isNil(option)),
};
debug('options values: %O', options);
@@ -67,6 +85,6 @@ module.exports = async (context, opts) => {
};
async function pkgRepoUrl(opts) {
const {pkg} = await readPkgUp(opts);
const {package: pkg} = (await readPkgUp(opts)) || {};
return pkg && (isPlainObject(pkg.repository) ? pkg.repository.url : pkg.repository);
}
+28 -25
View File
@@ -1,19 +1,8 @@
const {parse, format} = require('url');
const {isUndefined} = require('lodash');
const gitUrlParse = require('git-url-parse');
const {parse, format} = require('url'); // eslint-disable-line node/no-deprecated-api
const {isNil} = require('lodash');
const hostedGitInfo = require('hosted-git-info');
const {verifyAuth} = require('./git');
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
@@ -26,31 +15,45 @@ const GIT_TOKENS = {
* @return {String} The formatted Git repository URL.
*/
module.exports = async ({cwd, env, options: {repositoryUrl, branch}}) => {
const GIT_TOKENS = {
GIT_CREDENTIALS: undefined,
GH_TOKEN: undefined,
// GitHub Actions require the "x-access-token:" prefix for git access
// https://developer.github.com/apps/building-github-apps/authenticating-with-github-apps/#http-based-git-access-by-an-installation
GITHUB_TOKEN: isNil(env.GITHUB_ACTION) ? undefined : 'x-access-token:',
GL_TOKEN: 'gitlab-ci-token:',
GITLAB_TOKEN: 'gitlab-ci-token:',
BB_TOKEN: 'x-token-auth:',
BITBUCKET_TOKEN: 'x-token-auth:',
};
const info = hostedGitInfo.fromUrl(repositoryUrl, {noGitPlus: true});
const {protocol, ...parsed} = parse(repositoryUrl);
if (info && info.getDefaultRepresentation() === 'shortcut') {
// Expand shorthand URLs (such as `owner/repo` or `gitlab:owner/repo`)
repositoryUrl = info.https();
} else {
const {protocols} = gitUrlParse(repositoryUrl);
} else if (protocol && protocol.includes('http')) {
// 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'});
}
repositoryUrl = format({...parsed, protocol: protocol.includes('https') ? 'https' : 'http', href: null});
}
// Test if push is allowed without transforming the URL (e.g. is ssh keys are set up)
try {
await verifyAuth(repositoryUrl, branch, {cwd, env});
} catch (err) {
const envVar = Object.keys(GIT_TOKENS).find(envVar => !isUndefined(env[envVar]));
} catch (error) {
const envVar = Object.keys(GIT_TOKENS).find(envVar => !isNil(env[envVar]));
const gitCredentials = `${GIT_TOKENS[envVar] || ''}${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;
if (gitCredentials) {
// If credentials are set via environment variables, convert the URL to http/https and add basic auth, otherwise return `repositoryUrl` as is
const [match, auth, host, path] = /^(?!.+:\/\/)(?:(.*)@)?(.*?):(.*)$/.exec(repositoryUrl) || [];
return format({
...parse(match ? `ssh://${auth ? `${auth}@` : ''}${host}/${path}` : repositoryUrl),
auth: gitCredentials,
protocol: protocol && /http[^s]/.test(protocol) ? 'http' : 'https',
});
}
}
return repositoryUrl;
+4 -4
View File
@@ -2,7 +2,7 @@ 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');
const {getTags, isRefInHistory, getTagHead} = require('./git');
/**
* Last release.
@@ -28,9 +28,9 @@ module.exports = async ({cwd, env, options: {tagFormat}, logger}) => {
// Generate a regex to parse tags formatted with `tagFormat`
// by replacing the `version` variable in the template by `(.+)`.
// The `tagFormat` is compiled with space as the `version` as it's an invalid tag character,
// so it's guaranteed to no be present in the `tagFormat`.
// so it's guaranteed to not be present in the `tagFormat`.
const tagRegexp = `^${escapeRegExp(template(tagFormat)({version: ' '})).replace(' ', '(.+)')}`;
const tags = (await gitTags({cwd, env}))
const tags = (await getTags({cwd, env}))
.map(tag => ({gitTag: tag, version: (tag.match(tagRegexp) || new Array(2))[1]}))
.filter(
tag => tag.version && semver.valid(semver.clean(tag.version)) && !semver.prerelease(semver.clean(tag.version))
@@ -43,7 +43,7 @@ module.exports = async ({cwd, env, options: {tagFormat}, logger}) => {
if (tag) {
logger.log(`Found git tag ${tag.gitTag} associated with version ${tag.version}`);
return {gitHead: await gitTagHead(tag.gitTag, {cwd, env}), ...tag};
return {gitHead: await getTagHead(tag.gitTag, {cwd, env}), ...tag};
}
logger.log('No git tag version found');
+1 -1
View File
@@ -3,7 +3,7 @@ const figures = require('figures');
module.exports = ({stdout, stderr}) =>
new Signale({
config: {displayTimestamp: true, underlineMessage: true, displayLabel: false},
config: {displayTimestamp: true, underlineMessage: false, displayLabel: false},
disabled: false,
interactive: false,
scope: 'semantic-release',
+39 -42
View File
@@ -4,16 +4,16 @@ const debug = require('debug')('semantic-release:git');
/**
* Get the commit sha for a given tag.
*
* @param {string} tagName Tag name for which to retrieve the commit sha.
* @param {String} tagName Tag name for which to retrieve the commit sha.
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @return {string} The commit sha of the tag in parameter or `null`.
*/
async function gitTagHead(tagName, execaOpts) {
async function getTagHead(tagName, execaOpts) {
try {
return await execa.stdout('git', ['rev-list', '-1', tagName], execaOpts);
} catch (err) {
debug(err);
return (await execa('git', ['rev-list', '-1', tagName], execaOpts)).stdout;
} catch (error) {
debug(error);
}
}
@@ -25,32 +25,32 @@ async function gitTagHead(tagName, execaOpts) {
* @return {Array<String>} List of git tags.
* @throws {Error} If the `git` command fails.
*/
async function gitTags(execaOpts) {
return (await execa.stdout('git', ['tag'], execaOpts))
async function getTags(execaOpts) {
return (await execa('git', ['tag'], execaOpts)).stdout
.split('\n')
.map(tag => tag.trim())
.filter(tag => Boolean(tag));
.filter(Boolean);
}
/**
* Verify if the `ref` is in the direct history of the current branch.
*
* @param {string} ref The reference to look for.
* @param {String} ref The reference to look for.
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @return {boolean} `true` if the reference is in the history of the current branch, falsy otherwise.
* @return {Boolean} `true` if the reference is in the history of the current branch, falsy otherwise.
*/
async function isRefInHistory(ref, execaOpts) {
try {
await execa('git', ['merge-base', '--is-ancestor', ref, 'HEAD'], execaOpts);
return true;
} catch (err) {
if (err.code === 1) {
} catch (error) {
if (error.code === 1) {
return false;
}
debug(err);
throw err;
debug(error);
throw error;
}
}
@@ -63,7 +63,7 @@ async function isRefInHistory(ref, execaOpts) {
async function fetch(repositoryUrl, execaOpts) {
try {
await execa('git', ['fetch', '--unshallow', '--tags', repositoryUrl], execaOpts);
} catch (err) {
} catch (error) {
await execa('git', ['fetch', '--tags', repositoryUrl], execaOpts);
}
}
@@ -73,10 +73,10 @@ async function fetch(repositoryUrl, execaOpts) {
*
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @return {string} the sha of the HEAD commit.
* @return {String} the sha of the HEAD commit.
*/
async function gitHead(execaOpts) {
return execa.stdout('git', ['rev-parse', 'HEAD'], execaOpts);
async function getGitHead(execaOpts) {
return (await execa('git', ['rev-parse', 'HEAD'], execaOpts)).stdout;
}
/**
@@ -88,9 +88,9 @@ async function gitHead(execaOpts) {
*/
async function repoUrl(execaOpts) {
try {
return await execa.stdout('git', ['config', '--get', 'remote.origin.url'], execaOpts);
} catch (err) {
debug(err);
return (await execa('git', ['config', '--get', 'remote.origin.url'], execaOpts)).stdout;
} catch (error) {
debug(error);
}
}
@@ -104,8 +104,8 @@ async function repoUrl(execaOpts) {
async function isGitRepo(execaOpts) {
try {
return (await execa('git', ['rev-parse', '--git-dir'], execaOpts)).code === 0;
} catch (err) {
debug(err);
} catch (error) {
debug(error);
}
}
@@ -121,9 +121,9 @@ async function isGitRepo(execaOpts) {
async function verifyAuth(repositoryUrl, branch, execaOpts) {
try {
await execa('git', ['push', '--dry-run', repositoryUrl, `HEAD:${branch}`], execaOpts);
} catch (err) {
debug(err);
throw err;
} catch (error) {
debug(error);
throw error;
}
}
@@ -143,28 +143,27 @@ async function tag(tagName, execaOpts) {
* Push to the remote repository.
*
* @param {String} repositoryUrl The remote repository URL.
* @param {String} branch The branch to push.
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @throws {Error} if the push failed.
*/
async function push(repositoryUrl, branch, execaOpts) {
await execa('git', ['push', '--tags', repositoryUrl, `HEAD:${branch}`], execaOpts);
async function push(repositoryUrl, execaOpts) {
await execa('git', ['push', '--tags', repositoryUrl], execaOpts);
}
/**
* Verify a tag name is a valid Git reference.
*
* @param {string} tagName the tag name to verify.
* @param {String} tagName the tag name to verify.
* @param {Object} [execaOpts] Options to pass to `execa`.
*
* @return {boolean} `true` if valid, falsy otherwise.
* @return {Boolean} `true` if valid, falsy otherwise.
*/
async function verifyTagName(tagName, execaOpts) {
try {
return (await execa('git', ['check-ref-format', `refs/tags/${tagName}`], execaOpts)).code === 0;
} catch (err) {
debug(err);
} catch (error) {
debug(error);
}
}
@@ -177,22 +176,20 @@ async function verifyTagName(tagName, execaOpts) {
* @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, execaOpts) {
const {stdout: remoteHead} = await execa('git', ['ls-remote', '--heads', 'origin', branch], execaOpts);
try {
return await isRefInHistory(
(await execa.stdout('git', ['ls-remote', '--heads', 'origin', branch], execaOpts)).match(/^(\w+)?/)[1],
execaOpts
);
} catch (err) {
debug(err);
return await isRefInHistory(remoteHead.match(/^(\w+)?/)[1], execaOpts);
} catch (error) {
debug(error);
}
}
module.exports = {
gitTagHead,
gitTags,
getTagHead,
getTags,
isRefInHistory,
fetch,
gitHead,
getGitHead,
repoUrl,
isGitRepo,
verifyAuth,
+3 -2
View File
@@ -1,4 +1,4 @@
const {escapeRegExp, size} = require('lodash');
const {escapeRegExp, size, isString} = require('lodash');
const {SECRET_REPLACEMENT, SECRET_MIN_SIZE} = require('./definitions/constants');
module.exports = env => {
@@ -7,5 +7,6 @@ module.exports = env => {
);
const regexp = new RegExp(toReplace.map(envVar => escapeRegExp(env[envVar])).join('|'), 'g');
return output => (output && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output);
return output =>
output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;
};
+66 -22
View File
@@ -1,49 +1,93 @@
const {identity, isPlainObject, omit, castArray, isUndefined} = require('lodash');
const {identity, isPlainObject, omit, castArray, isNil, isString} = require('lodash');
const AggregateError = require('aggregate-error');
const getError = require('../get-error');
const PLUGINS_DEFINITIONS = require('../definitions/plugins');
const {validateConfig} = require('./utils');
const {validatePlugin, validateStep, loadPlugin, parseConfig} = require('./utils');
const pipeline = require('./pipeline');
const normalize = require('./normalize');
module.exports = (context, pluginsPath) => {
const {options, logger} = context;
let {options, logger} = context;
const errors = [];
const plugins = Object.entries(PLUGINS_DEFINITIONS).reduce(
(
plugins,
[type, {multiple, required, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]
) => {
const plugins = options.plugins
? castArray(options.plugins).reduce((plugins, plugin) => {
if (validatePlugin(plugin)) {
const [name, config] = parseConfig(plugin);
plugin = isString(name) ? loadPlugin(context, name, pluginsPath) : name;
if (isPlainObject(plugin)) {
Object.entries(plugin).forEach(([type, func]) => {
if (PLUGINS_DEFINITIONS[type]) {
Reflect.defineProperty(func, 'pluginName', {
value: isPlainObject(name) ? 'Inline plugin' : name,
writable: false,
enumerable: true,
});
plugins[type] = [...(plugins[type] || []), [func, config]];
}
});
} else {
errors.push(getError('EPLUGINSCONF', {plugin}));
}
} else {
errors.push(getError('EPLUGINSCONF', {plugin}));
}
return plugins;
}, {})
: [];
if (errors.length > 0) {
throw new AggregateError(errors);
}
options = {...plugins, ...options};
const pluginsConf = Object.entries(PLUGINS_DEFINITIONS).reduce(
(pluginsConf, [type, {required, default: def, pipelineConfig, postprocess = identity, preprocess = identity}]) => {
let pluginOpts;
if (isUndefined(options[type])) {
if (isNil(options[type]) && def) {
pluginOpts = 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 an object is passed and the path is missing, merge it with step options
if (isPlainObject(options[type]) && !options[type].path) {
options[type] = castArray(plugins[type]).map(plugin =>
plugin ? [plugin[0], Object.assign(plugin[1], options[type])] : plugin
);
}
if (!validateConfig({multiple, required}, options[type])) {
errors.push(getError('EPLUGINCONF', {type, multiple, required, pluginConf: options[type]}));
return plugins;
if (!validateStep({required}, options[type])) {
errors.push(getError('EPLUGINCONF', {type, required, pluginConf: options[type]}));
return pluginsConf;
}
pluginOpts = options[type];
}
const steps = castArray(pluginOpts).map(pluginOpt =>
normalize({...context, options: omit(options, Object.keys(PLUGINS_DEFINITIONS))}, type, pluginOpt, pluginsPath)
normalize(
{...context, options: omit(options, Object.keys(PLUGINS_DEFINITIONS), 'plugins')},
type,
pluginOpt,
pluginsPath
)
);
plugins[type] = async input =>
postprocess(await pipeline(steps, pipelineConfig && pipelineConfig(plugins, logger))(await preprocess(input)));
pluginsConf[type] = async input =>
postprocess(
await pipeline(steps, pipelineConfig && pipelineConfig(pluginsConf, logger))(await preprocess(input)),
input
);
return plugins;
return pluginsConf;
},
{}
plugins
);
if (errors.length > 0) {
throw new AggregateError(errors);
}
return plugins;
return pluginsConf;
};
+32 -23
View File
@@ -1,22 +1,21 @@
const {dirname} = require('path');
const {isString, isPlainObject, isFunction, noop, cloneDeep} = require('lodash');
const resolveFrom = require('resolve-from');
const {isPlainObject, isFunction, noop, cloneDeep, omit} = require('lodash');
const debug = require('debug')('semantic-release:plugins');
const getError = require('../get-error');
const {extractErrors} = require('../utils');
const PLUGINS_DEFINITIONS = require('../definitions/plugins');
const {loadPlugin, parseConfig} = require('./utils');
module.exports = ({cwd, options, logger}, type, pluginOpt, pluginsPath) => {
module.exports = (context, type, pluginOpt, pluginsPath) => {
const {stdout, stderr, options, logger} = context;
if (!pluginOpt) {
return noop;
}
const {path, ...config} = isString(pluginOpt) || isFunction(pluginOpt) ? {path: pluginOpt} : pluginOpt;
const pluginName = isFunction(path) ? `[Function: ${path.name}]` : path;
const [name, config] = parseConfig(pluginOpt);
const pluginName = name.pluginName ? name.pluginName : isFunction(name) ? `[Function: ${name.name}]` : name;
const plugin = loadPlugin(context, name, pluginsPath);
const basePath = pluginsPath[path]
? dirname(resolveFrom.silent(__dirname, pluginsPath[path]) || resolveFrom(cwd, pluginsPath[path]))
: __dirname;
const plugin = isFunction(path) ? path : require(resolveFrom.silent(basePath, path) || resolveFrom(cwd, path));
debug(`options for ${pluginName}/${type}: %O`, config);
let func;
if (isFunction(plugin)) {
@@ -28,29 +27,39 @@ module.exports = ({cwd, options, logger}, type, pluginOpt, pluginsPath) => {
}
const validator = async input => {
const {outputValidator} = PLUGINS_DEFINITIONS[type] || {};
const {dryRun, outputValidator} = PLUGINS_DEFINITIONS[type] || {};
try {
logger.log(`Start step "${type}" of plugin "${pluginName}"`);
const result = await func({...cloneDeep(input), logger: logger.scope(logger.scopeName, pluginName)});
if (outputValidator && !outputValidator(result)) {
throw getError(`E${type.toUpperCase()}OUTPUT`, {result, pluginName});
if (!input.options.dryRun || dryRun) {
logger.log(`Start step "${type}" of plugin "${pluginName}"`);
const result = await func({
...cloneDeep(omit(input, ['stdout', 'stderr', 'logger'])),
stdout,
stderr,
logger: logger.scope(logger.scopeName, pluginName),
});
if (outputValidator && !outputValidator(result)) {
throw getError(`E${type.toUpperCase()}OUTPUT`, {result, pluginName});
}
logger.success(`Completed step "${type}" of plugin "${pluginName}"`);
return result;
}
logger.success(`Completed step "${type}" of plugin "${pluginName}"`);
return result;
} catch (err) {
logger.warn(`Skip step "${type}" of plugin "${pluginName}" in dry-run mode`);
} catch (error) {
logger.error(`Failed step "${type}" of plugin "${pluginName}"`);
extractErrors(err).forEach(err => Object.assign(err, {pluginName}));
throw err;
extractErrors(error).forEach(err => Object.assign(err, {pluginName}));
throw error;
}
};
Reflect.defineProperty(validator, 'pluginName', {value: pluginName, writable: false, enumerable: true});
if (!isFunction(pluginOpt)) {
if (pluginsPath[path]) {
logger.success(`Loaded plugin "${type}" from "${path}" in shareable config "${pluginsPath[path]}"`);
if (pluginsPath[name]) {
logger.success(`Loaded plugin "${type}" from "${pluginName}" in shareable config "${pluginsPath[name]}"`);
} else {
logger.success(`Loaded plugin "${type}" from "${path}"`);
logger.success(`Loaded plugin "${type}" from "${pluginName}"`);
}
}
+7 -5
View File
@@ -4,7 +4,7 @@ const AggregateError = require('aggregate-error');
const {extractErrors} = require('../utils');
/**
* A Function that execute a list of function sequencially. If at least one Function ins the pipeline throw an Error or rejects, the pipeline function rejects as well.
* A Function that execute a list of function sequencially. If at least one Function ins the pipeline throws an Error or rejects, the pipeline function rejects as well.
*
* @typedef {Function} Pipeline
* @param {Any} input Argument to pass to the first step in the pipeline.
@@ -36,14 +36,15 @@ module.exports = (steps, {settleAll = false, getNextInput = identity, transform
// 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) {
} catch (error) {
if (settleAll) {
errors.push(...extractErrors(err));
result = err;
errors.push(...extractErrors(error));
result = error;
} else {
throw err;
throw error;
}
}
// Prepare input for the next step, passing the input of the last iteration (or initial parameter for the first iteration) and the result of the current one
return getNextInput(lastInput, result);
},
@@ -52,5 +53,6 @@ module.exports = (steps, {settleAll = false, getNextInput = identity, transform
if (errors.length > 0) {
throw new AggregateError(errors);
}
return results;
};
+60 -10
View File
@@ -1,18 +1,68 @@
const {isString, isFunction, castArray} = require('lodash');
const {dirname} = require('path');
const {isString, isFunction, castArray, isArray, isPlainObject, isNil} = require('lodash');
const resolveFrom = require('resolve-from');
const validateSingleConfig = conf => {
conf = castArray(conf);
return conf.length === 1 && (isString(conf[0]) || isString(conf[0].path) || isFunction(conf[0]));
const validateSteps = conf => {
return conf.every(conf => {
if (
isArray(conf) &&
(conf.length === 1 || conf.length === 2) &&
(isString(conf[0]) || isFunction(conf[0])) &&
(isNil(conf[1]) || isPlainObject(conf[1]))
) {
return true;
}
conf = castArray(conf);
if (conf.length !== 1) {
return false;
}
const [name, config] = parseConfig(conf[0]);
return (isString(name) || isFunction(name)) && isPlainObject(config);
});
};
const validateMultipleConfig = conf => castArray(conf).every(conf => validateSingleConfig(conf));
function validatePlugin(conf) {
return (
isString(conf) ||
(isArray(conf) &&
(conf.length === 1 || conf.length === 2) &&
(isString(conf[0]) || isPlainObject(conf[0])) &&
(isNil(conf[1]) || isPlainObject(conf[1]))) ||
(isPlainObject(conf) && (isNil(conf.path) || isString(conf.path) || isPlainObject(conf.path)))
);
}
const validateConfig = ({multiple, required}, conf) => {
function validateStep({required}, conf) {
conf = castArray(conf).filter(Boolean);
if (required) {
return Boolean(conf) && conf.length >= 1 && (multiple ? validateMultipleConfig : validateSingleConfig)(conf);
return conf.length >= 1 && validateSteps(conf);
}
return conf.length === 0 || (multiple ? validateMultipleConfig : validateSingleConfig)(conf);
};
module.exports = {validateConfig};
return conf.length === 0 || validateSteps(conf);
}
function loadPlugin({cwd}, name, pluginsPath) {
const basePath = pluginsPath[name]
? dirname(resolveFrom.silent(__dirname, pluginsPath[name]) || resolveFrom(cwd, pluginsPath[name]))
: __dirname;
return isFunction(name) ? name : require(resolveFrom.silent(basePath, name) || resolveFrom(cwd, name));
}
function parseConfig(plugin) {
let path;
let config;
if (isArray(plugin)) {
[path, config] = plugin;
} else if (isPlainObject(plugin) && !isNil(plugin.path)) {
({path, ...config} = plugin);
} else {
path = plugin;
}
return [path, config || {}];
}
module.exports = {validatePlugin, validateStep, loadPlugin, parseConfig};
+14 -1
View File
@@ -1,7 +1,20 @@
const {isFunction} = require('lodash');
const hideSensitive = require('./hide-sensitive');
function extractErrors(err) {
return err && isFunction(err[Symbol.iterator]) ? [...err] : [err];
}
module.exports = {extractErrors};
function hideSensitiveValues(env, objs) {
const hideFunction = hideSensitive(env);
return objs.map(obj => {
Object.getOwnPropertyNames(obj).forEach(prop => {
if (obj[prop]) {
obj[prop] = hideFunction(obj[prop]);
}
});
return obj;
});
}
module.exports = {extractErrors, hideSensitiveValues};
+1 -1
View File
@@ -7,7 +7,7 @@ module.exports = async ({cwd, env, options: {repositoryUrl, tagFormat}}) => {
const errors = [];
if (!(await isGitRepo({cwd, env}))) {
errors.push(getError('ENOGITREPO'));
errors.push(getError('ENOGITREPO', {cwd}));
} else if (!repositoryUrl) {
errors.push(getError('ENOREPOURL'));
}
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 142 KiB

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 117 KiB

After

Width:  |  Height:  |  Size: 65 KiB

+42 -45
View File
@@ -3,70 +3,71 @@
"description": "Automated semver compliant package publishing",
"version": "0.0.0-development",
"author": "Stephan Bönnemann <stephan@boennemann.me> (http://boennemann.me)",
"ava": {
"files": [
"test/**/*.test.js"
],
"helpers": [
"test/helpers/**/*"
]
},
"bin": {
"semantic-release": "bin/semantic-release.js"
},
"bugs": {
"url": "https://github.com/semantic-release/semantic-release/issues"
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
},
"contributors": [
"Gregor Martynus (https://twitter.com/gr2m)",
"Pierre Vanduynslager (https://twitter.com/@pvdlg_)"
],
"dependencies": {
"@semantic-release/commit-analyzer": "^6.0.0",
"@semantic-release/commit-analyzer": "^6.1.0",
"@semantic-release/error": "^2.2.0",
"@semantic-release/github": "^5.0.0",
"@semantic-release/npm": "^5.0.1",
"@semantic-release/release-notes-generator": "^7.0.0",
"aggregate-error": "^1.0.0",
"@semantic-release/github": "^5.1.0",
"@semantic-release/npm": "^5.0.5",
"@semantic-release/release-notes-generator": "^7.1.2",
"aggregate-error": "^3.0.0",
"cosmiconfig": "^5.0.1",
"debug": "^3.1.0",
"env-ci": "^2.0.0",
"execa": "^0.10.0",
"figures": "^2.0.0",
"find-versions": "^2.0.0",
"get-stream": "^3.0.0",
"debug": "^4.0.0",
"env-ci": "^4.0.0",
"execa": "^1.0.0",
"figures": "^3.0.0",
"find-versions": "^3.0.0",
"get-stream": "^5.0.0",
"git-log-parser": "^1.2.0",
"git-url-parse": "^10.0.1",
"hook-std": "^1.1.0",
"hosted-git-info": "^2.7.1",
"lodash": "^4.17.4",
"marked": "^0.4.0",
"marked-terminal": "^3.0.0",
"p-locate": "^3.0.0",
"p-reduce": "^1.0.0",
"read-pkg-up": "^4.0.0",
"resolve-from": "^4.0.0",
"semver": "^5.4.1",
"hook-std": "^2.0.0",
"hosted-git-info": "^3.0.0",
"lodash": "^4.17.15",
"marked": "^0.7.0",
"marked-terminal": "^3.2.0",
"p-locate": "^4.0.0",
"p-reduce": "^2.0.0",
"read-pkg-up": "^6.0.0",
"resolve-from": "^5.0.0",
"semver": "^6.0.0",
"signale": "^1.2.1",
"yargs": "^12.0.0"
"yargs": "^14.0.0"
},
"devDependencies": {
"ava": "^0.25.0",
"clear-module": "^3.0.0",
"ava": "^2.0.0",
"clear-module": "^4.0.0",
"codecov": "^3.0.0",
"commitizen": "^2.9.6",
"cz-conventional-changelog": "^2.0.0",
"delay": "^3.0.0",
"delay": "^4.0.0",
"dockerode": "^2.5.2",
"file-url": "^2.0.2",
"fs-extra": "^7.0.0",
"file-url": "^3.0.0",
"fs-extra": "^8.0.0",
"got": "^9.0.0",
"js-yaml": "^3.10.0",
"mockserver-client": "^5.1.1",
"nock": "^9.0.2",
"nyc": "^12.0.1",
"p-retry": "^2.0.0",
"nock": "^10.0.0",
"nyc": "^14.0.0",
"p-retry": "^4.0.0",
"proxyquire": "^2.0.0",
"sinon": "^6.0.0",
"tempy": "^0.2.1",
"xo": "^0.21.0"
"sinon": "^7.2.7",
"stream-buffers": "^3.0.2",
"tempy": "^0.3.0",
"xo": "^0.24.0"
},
"engines": {
"node": ">=8.3"
@@ -112,15 +113,11 @@
"publishConfig": {
"tag": "next"
},
"release": {
"branch": "caribou"
},
"repository": {
"type": "git",
"url": "git+https://github.com/semantic-release/semantic-release.git"
},
"scripts": {
"cm": "git-cz",
"codecov": "codecov -f coverage/coverage-final.json",
"lint": "xo",
"pretest": "npm run lint",
+30 -32
View File
@@ -33,6 +33,9 @@ test.serial('Pass options to semantic-release API', async t => {
'https://github/com/owner/repo.git',
'-t',
`v\${version}`,
'-p',
'plugin1',
'plugin2',
'-e',
'config1',
'config2',
@@ -63,16 +66,17 @@ test.serial('Pass options to semantic-release API', async t => {
];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
const code = await cli();
t.is(run.args[0][0].branch, 'master');
t.is(run.args[0][0].repositoryUrl, 'https://github/com/owner/repo.git');
t.is(run.args[0][0].tagFormat, `v\${version}`);
t.deepEqual(run.args[0][0].plugins, ['plugin1', 'plugin2']);
t.deepEqual(run.args[0][0].extends, ['config1', 'config2']);
t.deepEqual(run.args[0][0].verifyConditions, ['condition1', 'condition2']);
t.is(run.args[0][0].analyzeCommits, 'analyze');
t.deepEqual(run.args[0][0].verifyRelease, ['verify1', 'verify2']);
t.is(run.args[0][0].generateNotes, 'notes');
t.deepEqual(run.args[0][0].generateNotes, ['notes']);
t.deepEqual(run.args[0][0].prepare, ['prepare1', 'prepare2']);
t.deepEqual(run.args[0][0].publish, ['publish1', 'publish2']);
t.deepEqual(run.args[0][0].success, ['success1', 'success2']);
@@ -80,7 +84,7 @@ test.serial('Pass options to semantic-release API', async t => {
t.is(run.args[0][0].debug, true);
t.is(run.args[0][0].dryRun, true);
t.is(exitCode, 0);
t.is(code, 0);
});
test.serial('Pass options to semantic-release API with alias arguments', async t => {
@@ -94,6 +98,9 @@ test.serial('Pass options to semantic-release API with alias arguments', async t
'https://github/com/owner/repo.git',
'--tag-format',
`v\${version}`,
'--plugins',
'plugin1',
'plugin2',
'--extends',
'config1',
'config2',
@@ -101,15 +108,16 @@ test.serial('Pass options to semantic-release API with alias arguments', async t
];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
const code = await cli();
t.is(run.args[0][0].branch, 'master');
t.is(run.args[0][0].repositoryUrl, 'https://github/com/owner/repo.git');
t.is(run.args[0][0].tagFormat, `v\${version}`);
t.deepEqual(run.args[0][0].plugins, ['plugin1', 'plugin2']);
t.deepEqual(run.args[0][0].extends, ['config1', 'config2']);
t.is(run.args[0][0].dryRun, true);
t.is(exitCode, 0);
t.is(code, 0);
});
test.serial('Pass unknown options to semantic-release API', async t => {
@@ -117,13 +125,13 @@ test.serial('Pass unknown options to semantic-release API', async t => {
const argv = ['', '', '--bool', '--first-option', 'value1', '--second-option', 'value2', '--second-option', 'value3'];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
const code = await cli();
t.is(run.args[0][0].bool, true);
t.is(run.args[0][0].firstOption, 'value1');
t.deepEqual(run.args[0][0].secondOption, ['value2', 'value3']);
t.is(exitCode, 0);
t.is(code, 0);
});
test.serial('Pass empty Array to semantic-release API for list option set to "false"', async t => {
@@ -131,11 +139,11 @@ test.serial('Pass empty Array to semantic-release API for list option set to "fa
const argv = ['', '', '--publish', 'false'];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
const code = await cli();
t.deepEqual(run.args[0][0].publish, []);
t.is(exitCode, 0);
t.is(code, 0);
});
test.serial('Do not set properties in option for which arg is not in command line', async t => {
@@ -151,18 +159,8 @@ test.serial('Do not set properties in option for which arg is not in command lin
t.false('debug' in run.args[0][0]);
t.false('r' in run.args[0][0]);
t.false('t' in run.args[0][0]);
});
test.serial('Set "noCi" options to "true" with "--no-ci"', async t => {
const run = stub().resolves(true);
const argv = ['', '', '--no-ci'];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
t.is(run.args[0][0].noCi, true);
t.is(exitCode, 0);
t.false('p' in run.args[0][0]);
t.false('e' in run.args[0][0]);
});
test.serial('Display help', async t => {
@@ -170,22 +168,22 @@ test.serial('Display help', async t => {
const argv = ['', '', '--help'];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
const code = await cli();
t.regex(t.context.logs, /Run automated package publishing/);
t.is(exitCode, 0);
t.is(code, 0);
});
test.serial('Returns error code and prints help if called with a command', async t => {
test.serial('Return error code and prints help if called with a command', async t => {
const run = stub().resolves(true);
const argv = ['', '', 'pre'];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
const code = await cli();
t.regex(t.context.errors, /Run automated package publishing/);
t.regex(t.context.errors, /Too many non-option arguments/);
t.is(exitCode, 1);
t.is(code, 1);
});
test.serial('Return error code if multiple plugin are set for single plugin', async t => {
@@ -193,11 +191,11 @@ test.serial('Return error code if multiple plugin are set for single plugin', as
const argv = ['', '', '--analyze-commits', 'analyze1', 'analyze2'];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
const code = await cli();
t.regex(t.context.errors, /Run automated package publishing/);
t.regex(t.context.errors, /Too many non-option arguments/);
t.is(exitCode, 1);
t.is(code, 1);
});
test.serial('Return error code if semantic-release throw error', async t => {
@@ -205,10 +203,10 @@ test.serial('Return error code if semantic-release throw error', async t => {
const argv = ['', ''];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv}});
const exitCode = await cli();
const code = await cli();
t.regex(t.context.errors, /semantic-release error/);
t.is(exitCode, 1);
t.is(code, 1);
});
test.serial('Hide sensitive environment variable values from the logs', async t => {
@@ -217,8 +215,8 @@ test.serial('Hide sensitive environment variable values from the logs', async t
const argv = ['', ''];
const cli = requireNoCache('../cli', {'.': run, process: {...process, argv, env: {...process.env, ...env}}});
const exitCode = await cli();
const code = await cli();
t.regex(t.context.errors, new RegExp(`Throw error: Exposing token ${escapeRegExp(SECRET_REPLACEMENT)}`));
t.is(exitCode, 1);
t.is(code, 1);
});
+31 -8
View File
@@ -1,6 +1,6 @@
import test from 'ava';
import plugins from '../../lib/definitions/plugins';
import {RELEASE_NOTES_SEPARATOR} from '../../lib/definitions/constants';
import {RELEASE_NOTES_SEPARATOR, SECRET_REPLACEMENT} from '../../lib/definitions/constants';
test('The "analyzeCommits" plugin output must be either undefined or a valid semver release type', t => {
t.false(plugins.analyzeCommits.outputValidator('invalid'));
@@ -22,7 +22,7 @@ test('The "generateNotes" plugin output, if defined, must be a string', t => {
t.true(plugins.generateNotes.outputValidator('string'));
});
test('The "publish" plugin output, if defined, must be an object', t => {
test('The "publish" plugin output, if defined, must be an object or "false"', t => {
t.false(plugins.publish.outputValidator(1));
t.false(plugins.publish.outputValidator('string'));
@@ -30,12 +30,35 @@ test('The "publish" plugin output, if defined, must be an object', t => {
t.true(plugins.publish.outputValidator());
t.true(plugins.publish.outputValidator(null));
t.true(plugins.publish.outputValidator(''));
t.true(plugins.publish.outputValidator(false));
});
test('The "generateNotes" plugins output are concatenated with separator', 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`);
test('The "generateNotes" plugins output are concatenated with separator and sensitive data is hidden', t => {
const env = {MY_TOKEN: 'secret token'};
t.is(plugins.generateNotes.postprocess(['note 1', 'note 2'], {env}), `note 1${RELEASE_NOTES_SEPARATOR}note 2`);
t.is(plugins.generateNotes.postprocess(['', 'note'], {env}), 'note');
t.is(plugins.generateNotes.postprocess([undefined, 'note'], {env}), 'note');
t.is(plugins.generateNotes.postprocess(['note 1', '', 'note 2'], {env}), `note 1${RELEASE_NOTES_SEPARATOR}note 2`);
t.is(
plugins.generateNotes.postprocess(['note 1', undefined, 'note 2'], {env}),
`note 1${RELEASE_NOTES_SEPARATOR}note 2`
);
t.is(
plugins.generateNotes.postprocess(
[`Note 1: Exposing token ${env.MY_TOKEN}`, `Note 2: Exposing token ${SECRET_REPLACEMENT}`],
{env}
),
`Note 1: Exposing token ${SECRET_REPLACEMENT}${RELEASE_NOTES_SEPARATOR}Note 2: Exposing token ${SECRET_REPLACEMENT}`
);
});
test('The "analyzeCommits" plugins output are reduced to the highest release type', t => {
t.is(plugins.analyzeCommits.postprocess(['major', 'minor']), 'major');
t.is(plugins.analyzeCommits.postprocess(['', 'minor']), 'minor');
t.is(plugins.analyzeCommits.postprocess([undefined, 'patch']), 'patch');
t.is(plugins.analyzeCommits.postprocess([null, 'patch']), 'patch');
t.is(plugins.analyzeCommits.postprocess(['wrong_type', 'minor']), 'minor');
t.is(plugins.analyzeCommits.postprocess([]), undefined);
t.is(plugins.analyzeCommits.postprocess(['wrong_type']), undefined);
});
-1
View File
@@ -1,2 +1 @@
module.exports = () => {};
+1 -1
View File
@@ -1,7 +1,7 @@
const SemanticReleaseError = require('@semantic-release/error');
class InheritedError extends SemanticReleaseError {
constructor(message, code, newProperty) {
constructor(message, code) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
+46 -5
View File
@@ -8,6 +8,13 @@ import {stub} from 'sinon';
import yaml from 'js-yaml';
import {gitRepo, gitCommits, gitShallowClone, gitAddConfig} from './helpers/git-utils';
const DEFAULT_PLUGINS = [
'@semantic-release/commit-analyzer',
'@semantic-release/release-notes-generator',
'@semantic-release/npm',
'@semantic-release/github',
];
test.beforeEach(t => {
t.context.plugins = stub().returns({});
t.context.getConfig = proxyquire('../lib/get-config', {'./plugins': t.context.plugins});
@@ -60,6 +67,18 @@ test('Default values, reading repositoryUrl (http url) from package.json if not
t.is(result.tagFormat, `v\${version}`);
});
test('Convert "ci" option to "noCi"', async t => {
const pkg = {repository: 'https://host.null/owner/module.git', release: {ci: false}};
// Create a git repository, set the current working directory at the root of the repo
const {cwd} = await gitRepo();
// Create package.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), pkg);
const {options: result} = await t.context.getConfig({cwd});
t.is(result.noCi, true);
});
test('Read options from package.json', async t => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd} = await gitRepo();
@@ -69,6 +88,7 @@ test('Read options from package.json', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: options});
@@ -89,6 +109,7 @@ test('Read options from .releaserc.yml', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json in repository root
await writeFile(path.resolve(cwd, '.releaserc.yml'), yaml.safeDump(options));
@@ -109,6 +130,7 @@ test('Read options from .releaserc.json', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json in repository root
await outputJson(path.resolve(cwd, '.releaserc.json'), options);
@@ -129,6 +151,7 @@ test('Read options from .releaserc.js', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json in repository root
await writeFile(path.resolve(cwd, '.releaserc.js'), `module.exports = ${JSON.stringify(options)}`);
@@ -149,6 +172,7 @@ test('Read options from release.config.js', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json in repository root
await writeFile(path.resolve(cwd, 'release.config.js'), `module.exports = ${JSON.stringify(options)}`);
@@ -176,6 +200,7 @@ test('Prioritise CLI/API parameters over file configuration and git repo', async
branch: 'branch_cli',
repositoryUrl: 'http://cli-url.com/owner/package',
tagFormat: `cli\${version}`,
plugins: false,
};
const pkg = {release: pkgOptions, repository: 'git@host.null:owner/module.git'};
// Create package.json in repository root
@@ -199,6 +224,7 @@ test('Read configuration from file path in "extends"', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: ['plugin-1', ['plugin-2', {plugin2Opt: 'value'}]],
};
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
@@ -213,6 +239,8 @@ test('Read configuration from file path in "extends"', async t => {
t.deepEqual(t.context.plugins.args[0][1], {
analyzeCommits: './shareable.json',
generateNotes: './shareable.json',
'plugin-1': './shareable.json',
'plugin-2': './shareable.json',
});
});
@@ -226,6 +254,7 @@ test('Read configuration from module path in "extends"', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
@@ -259,6 +288,7 @@ test('Read configuration from an array of paths in "extends"', async t => {
analyzeCommits: {path: 'analyzeCommits2', param: 'analyzeCommits_param2'},
branch: 'test_branch',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
@@ -296,6 +326,7 @@ test('Prioritize configuration from config file over "extends"', async t => {
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
@@ -341,6 +372,7 @@ test('Prioritize configuration from cli/API options over "extends"', async t =>
publish: [{path: 'publishShareable', param: 'publishShareable_param2'}],
branch: 'test_branch2',
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json, shareable1.json and shareable2.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
@@ -366,11 +398,13 @@ test('Allow to unset properties defined in shareable config with "null"', async
analyzeCommits: null,
branch: 'test_branch',
repositoryUrl: 'https://host.null/owner/module.git',
plugins: null,
};
const options1 = {
generateNotes: 'generateNotes',
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
tagFormat: `v\${version}`,
plugins: ['test-plugin'],
};
// Create package.json and shareable.json in repository root
await outputJson(path.resolve(cwd, 'package.json'), {release: pkgOptions});
@@ -378,19 +412,25 @@ test('Allow to unset properties defined in shareable config with "null"', async
const {options} = await t.context.getConfig({cwd});
// Verify the options contains the plugin config from shareable.json
t.deepEqual(options, {...omit(options1, 'analyzeCommits'), ...omit(pkgOptions, ['extends', 'analyzeCommits'])});
// Verify the plugins module is called with the plugin options from shareable.json
// Verify the options contains the plugin config from shareable.json and the default `plugins`
t.deepEqual(options, {
...omit(options1, ['analyzeCommits']),
...omit(pkgOptions, ['extends', 'analyzeCommits']),
plugins: DEFAULT_PLUGINS,
});
// Verify the plugins module is called with the plugin options from shareable.json and the default `plugins`
t.deepEqual(t.context.plugins.args[0][0], {
options: {
...omit(options1, 'analyzeCommits'),
...omit(pkgOptions, ['extends', 'analyzeCommits']),
plugins: DEFAULT_PLUGINS,
},
cwd,
});
t.deepEqual(t.context.plugins.args[0][1], {
generateNotes: './shareable.json',
analyzeCommits: './shareable.json',
'test-plugin': './shareable.json',
});
});
@@ -407,6 +447,7 @@ test('Allow to unset properties defined in shareable config with "undefined"', a
generateNotes: 'generateNotes',
analyzeCommits: {path: 'analyzeCommits', param: 'analyzeCommits_param'},
tagFormat: `v\${version}`,
plugins: false,
};
// Create package.json and release.config.js in repository root
await writeFile(path.resolve(cwd, 'release.config.js'), `module.exports = ${format(pkgOptions)}`);
@@ -439,8 +480,8 @@ test('Throw an Error if one of the shareable config cannot be found', async t =>
await outputJson(path.resolve(cwd, 'package.json'), {release: pkhOptions});
await outputJson(path.resolve(cwd, 'shareable1.json'), options1);
const error = await t.throws(t.context.getConfig({cwd}), Error);
const error = await t.throwsAsync(t.context.getConfig({cwd}), Error);
t.is(error.message, "Cannot find module 'non-existing-path'");
t.regex(error.message, /Cannot find module 'non-existing-path'/);
t.is(error.code, 'MODULE_NOT_FOUND');
});
+26
View File
@@ -101,6 +101,19 @@ test('Return the "https" formatted URL if "gitCredentials" is defined and reposi
);
});
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "git" URL without user', async t => {
const {cwd} = await gitRepo();
t.is(
await getAuthUrl({
cwd,
env: {...env, GIT_CREDENTIALS: 'user:pass'},
options: {branch: 'master', repositoryUrl: 'host.null:owner/repo.git'},
}),
'https://user:pass@host.null/owner/repo.git'
);
});
test('Return the "https" formatted URL if "gitCredentials" is defined and repositoryUrl is a "https" URL', async t => {
const {cwd} = await gitRepo();
@@ -231,6 +244,19 @@ test('Return the "https" formatted URL if "gitCredentials" is defined with "BITB
);
});
test('Return the "https" formatted URL if "GITHUB_ACTION" is set', async t => {
const {cwd} = await gitRepo();
t.is(
await getAuthUrl({
cwd,
env: {...env, GITHUB_ACTION: 'foo', GITHUB_TOKEN: 'token'},
options: {branch: 'master', repositoryUrl: 'git@host.null:owner/repo.git'},
}),
'https://x-access-token:token@host.null/owner/repo.git'
);
});
test('Handle "https" URL with group and subgroup, with "GIT_CREDENTIALS"', async t => {
const {cwd} = await gitRepo();
+32 -19
View File
@@ -1,14 +1,14 @@
import test from 'ava';
import tempy from 'tempy';
import {
gitTagHead,
getTagHead,
isRefInHistory,
fetch,
gitHead,
getGitHead,
repoUrl,
tag,
push,
gitTags,
getTags,
isGitRepo,
verifyTagName,
isBranchUpToDate,
@@ -33,7 +33,7 @@ test('Get the last commit sha', async t => {
// Add commits to the master branch
const commits = await gitCommits(['First'], {cwd});
const result = await gitHead({cwd});
const result = await getGitHead({cwd});
t.is(result, commits[0].hash);
});
@@ -42,7 +42,7 @@ test('Throw error if the last commit sha cannot be found', async t => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd} = await gitRepo();
await t.throws(gitHead({cwd}), Error);
await t.throwsAsync(getGitHead({cwd}), Error);
});
test('Unshallow and fetch repository', async t => {
@@ -67,7 +67,7 @@ test('Do not throw error when unshallow a complete repository', async t => {
const {cwd, repositoryUrl} = await gitRepo();
// Add commits to the master branch
await gitCommits(['First'], {cwd});
await t.notThrows(fetch(repositoryUrl, {cwd}));
await t.notThrowsAsync(fetch(repositoryUrl, {cwd}));
});
test('Fetch all tags on a detached head repository', async t => {
@@ -84,7 +84,7 @@ test('Fetch all tags on a detached head repository', async t => {
await fetch(repositoryUrl, {cwd});
t.deepEqual((await gitTags({cwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0'].sort());
t.deepEqual((await getTags({cwd})).sort(), ['v1.0.0', 'v1.0.1', 'v1.1.0'].sort());
});
test('Verify if the commit `sha` is in the direct history of the current branch', async t => {
@@ -100,7 +100,7 @@ test('Verify if the commit `sha` is in the direct history of the current branch'
t.true(await isRefInHistory(commits[0].hash, {cwd}));
t.falsy(await isRefInHistory(otherCommits[0].hash, {cwd}));
await t.throws(isRefInHistory('non-existant-sha', {cwd}));
await t.throwsAsync(isRefInHistory('non-existant-sha', {cwd}));
});
test('Get the commit sha for a given tag or falsy if the tag does not exists', async t => {
@@ -111,8 +111,8 @@ test('Get the commit sha for a given tag or falsy if the tag does not exists', a
// Create the tag corresponding to version 1.0.0
await gitTagVersion('v1.0.0', undefined, {cwd});
t.is(await gitTagHead('v1.0.0', {cwd}), commits[0].hash);
t.falsy(await gitTagHead('missing_tag', {cwd}));
t.is(await getTagHead('v1.0.0', {cwd}), commits[0].hash);
t.falsy(await getTagHead('missing_tag', {cwd}));
});
test('Return git remote repository url from config', async t => {
@@ -151,13 +151,27 @@ test('Add tag on head commit', async t => {
await t.is(await gitCommitTag(commits[0].hash, {cwd}), 'tag_name');
});
test('Push tag and commit to remote repository', async t => {
test('Push tag to remote repository', async t => {
// Create a git repository with a remote, set the current working directory at the root of the repo
const {cwd, repositoryUrl} = await gitRepo(true);
const commits = await gitCommits(['Test commit'], {cwd});
await tag('tag_name', {cwd});
await push(repositoryUrl, 'master', {cwd});
await push(repositoryUrl, {cwd});
t.is(await gitRemoteTagHead(repositoryUrl, 'tag_name', {cwd}), commits[0].hash);
});
test('Push tag to remote repository with remote branch ahaed', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const commits = await gitCommits(['First'], {cwd});
await gitPush(repositoryUrl, 'master', {cwd});
const tmpRepo = await gitShallowClone(repositoryUrl);
await gitCommits(['Second'], {cwd: tmpRepo});
await gitPush('origin', 'master', {cwd: tmpRepo});
await tag('tag_name', {cwd});
await push(repositoryUrl, {cwd});
t.is(await gitRemoteTagHead(repositoryUrl, 'tag_name', {cwd}), commits[0].hash);
});
@@ -192,7 +206,7 @@ test('Return falsy for invalid tag names', async t => {
test('Throws error if obtaining the tags fails', async t => {
const cwd = tempy.directory();
await t.throws(gitTags({cwd}));
await t.throwsAsync(getTags({cwd}));
});
test('Return "true" if repository is up to date', async t => {
@@ -204,19 +218,18 @@ test('Return "true" if repository is up to date', async t => {
});
test('Return falsy if repository is not up to date', async t => {
let {cwd, repositoryUrl} = await gitRepo(true);
const repoDir = cwd;
const {cwd, repositoryUrl} = await gitRepo(true);
await gitCommits(['First'], {cwd});
await gitCommits(['Second'], {cwd});
await gitPush(repositoryUrl, 'master', {cwd});
t.true(await isBranchUpToDate('master', {cwd}));
cwd = await gitShallowClone(repositoryUrl);
await gitCommits(['Third'], {cwd});
await gitPush('origin', 'master', {cwd});
const tmpRepo = await gitShallowClone(repositoryUrl);
await gitCommits(['Third'], {cwd: tmpRepo});
await gitPush('origin', 'master', {cwd: tmpRepo});
t.falsy(await isBranchUpToDate('master', {cwd: repoDir}));
t.falsy(await isBranchUpToDate('master', {cwd}));
});
test('Return "true" if local repository is ahead', async t => {
+9 -7
View File
@@ -26,7 +26,7 @@ import getStream from 'get-stream';
export async function gitRepo(withRemote, branch = 'master') {
let cwd = tempy.directory();
await execa('git', ['init'].concat(withRemote ? ['--bare'] : []), {cwd});
await execa('git', ['init', ...(withRemote ? ['--bare'] : [])], {cwd});
const repositoryUrl = fileUrl(cwd);
if (withRemote) {
@@ -69,8 +69,10 @@ export async function initBareRepo(repositoryUrl, branch = 'master') {
* @returns {Array<Commit>} The created commits, in reverse order (to match `git log` order).
*/
export async function gitCommits(messages, execaOpts) {
await pReduce(messages, async (_, message) =>
execa.stdout('git', ['commit', '-m', message, '--allow-empty', '--no-gpg-sign'], execaOpts)
await pReduce(
messages,
async (_, message) =>
(await execa('git', ['commit', '-m', message, '--allow-empty', '--no-gpg-sign'], execaOpts)).stdout
);
return (await gitGetCommits(undefined, execaOpts)).slice(0, messages.length);
}
@@ -113,7 +115,7 @@ export async function gitCheckout(branch, create = true, execaOpts) {
* @return {String} The sha of the head commit in the current git repository.
*/
export async function gitHead(execaOpts) {
return execa.stdout('git', ['rev-parse', 'HEAD'], execaOpts);
return (await execa('git', ['rev-parse', 'HEAD'], execaOpts)).stdout;
}
/**
@@ -182,7 +184,7 @@ export async function gitAddConfig(name, value, execaOpts) {
* @return {String} The sha of the commit associated with `tagName` on the local repository.
*/
export async function gitTagHead(tagName, execaOpts) {
return execa.stdout('git', ['rev-list', '-1', tagName], execaOpts);
return (await execa('git', ['rev-list', '-1', tagName], execaOpts)).stdout;
}
/**
@@ -195,7 +197,7 @@ export async function gitTagHead(tagName, execaOpts) {
* @return {String} The sha of the commit associated with `tagName` on the remote repository.
*/
export async function gitRemoteTagHead(repositoryUrl, tagName, execaOpts) {
return (await execa.stdout('git', ['ls-remote', '--tags', repositoryUrl, tagName], execaOpts))
return (await execa('git', ['ls-remote', '--tags', repositoryUrl, tagName], execaOpts)).stdout
.split('\n')
.filter(tag => Boolean(tag))
.map(tag => tag.match(/^(\S+)/)[1])[0];
@@ -210,7 +212,7 @@ export async function gitRemoteTagHead(repositoryUrl, tagName, execaOpts) {
* @return {String} The tag associatedwith the sha in parameter or `null`.
*/
export async function gitCommitTag(gitHead, execaOpts) {
return execa.stdout('git', ['describe', '--tags', '--exact-match', gitHead], execaOpts);
return (await execa('git', ['describe', '--tags', '--exact-match', gitHead], execaOpts)).stdout;
}
/**
-16
View File
@@ -1,16 +0,0 @@
import nock from 'nock';
/**
* Retun a `nock` object setup to respond to a github authentication request. Other expectation and responses can be chained.
*
* @param {String} [githubToken='GH_TOKEN'] The github token to return in the authentication response.
* @param {String} [githubUrl='https://api.github.com'] The url on which to intercept http requests.
* @return {Object} A `nock` object ready to respond to a github authentication request.
*/
export default function authenticate({
githubToken = 'GH_TOKEN',
githubUrl = 'https://api.github.com',
githubApiPathPrefix = '',
} = {}) {
return nock(`${githubUrl}/${githubApiPathPrefix}`, {reqheaders: {Authorization: `token ${githubToken}`}});
}
+2 -2
View File
@@ -30,7 +30,7 @@ async function start() {
minTimeout: 1000,
factor: 2,
});
} catch (err) {
} catch (error) {
throw new Error(`Couldn't start mock-server after 2 min`);
}
}
@@ -96,7 +96,7 @@ async function mock(
* @param {Object} expectation The expectation created with `mock` function.
* @return {Promise} A Promise that resolves if the expectation is met or reject otherwise.
*/
async function verify(expectation) {
function verify(expectation) {
return client.verify(expectation);
}
+1 -1
View File
@@ -39,7 +39,7 @@ async function start() {
minTimeout: 1000,
factor: 2,
});
} catch (err) {
} catch (error) {
throw new Error(`Couldn't start npm-registry-docker after 2 min`);
}
+245 -49
View File
@@ -1,9 +1,11 @@
import test from 'ava';
import {escapeRegExp, isString, sortBy} from 'lodash';
import proxyquire from 'proxyquire';
import {spy, stub} from 'sinon';
import {WritableStreamBuffer} from 'stream-buffers';
import AggregateError from 'aggregate-error';
import SemanticReleaseError from '@semantic-release/error';
import {COMMIT_NAME, COMMIT_EMAIL} from '../lib/definitions/constants';
import {COMMIT_NAME, COMMIT_EMAIL, SECRET_REPLACEMENT} from '../lib/definitions/constants';
import {
gitHead as getGitHead,
gitTagHead,
@@ -23,10 +25,12 @@ test.beforeEach(t => {
t.context.log = spy();
t.context.error = spy();
t.context.success = spy();
t.context.warn = spy();
t.context.logger = {
log: t.context.log,
error: t.context.error,
success: t.context.success,
warn: t.context.warn,
scope: () => t.context.logger,
};
});
@@ -62,6 +66,7 @@ test('Plugins are called with expected values', async t => {
const config = {branch: 'master', repositoryUrl, globalOpt: 'global', tagFormat: `v\${version}`};
const options = {
...config,
plugins: false,
verifyConditions: [verifyConditions1, verifyConditions2],
analyzeCommits,
verifyRelease,
@@ -78,8 +83,8 @@ test('Plugins are called with expected values', async t => {
const result = await semanticRelease(options, {
cwd,
env,
stdout: {write: () => {}},
stderr: {write: () => {}},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
});
t.is(verifyConditions1.callCount, 1);
@@ -164,7 +169,7 @@ test('Plugins are called with expected values', async t => {
t.deepEqual(success.args[0][1].commits[0].message, commits[0].message);
t.deepEqual(success.args[0][1].nextRelease, {...nextRelease, notes: `${notes1}\n\n${notes2}\n\n${notes3}`});
t.deepEqual(success.args[0][1].releases, [
{...release1, ...nextRelease, notes: `${notes1}\n\n${notes2}\n\n${notes3}`, pluginName: '[Function: proxy]'},
{...release1, ...nextRelease, notes: `${notes1}\n\n${notes2}\n\n${notes3}`, pluginName: '[Function: functionStub]'},
{...nextRelease, notes: `${notes1}\n\n${notes2}\n\n${notes3}`, pluginName: pluginNoop},
]);
@@ -173,7 +178,12 @@ test('Plugins are called with expected values', async t => {
commits: [commits[0]],
nextRelease: {...nextRelease, notes: `${notes1}\n\n${notes2}\n\n${notes3}`},
releases: [
{...release1, ...nextRelease, notes: `${notes1}\n\n${notes2}\n\n${notes3}`, pluginName: '[Function: proxy]'},
{
...release1,
...nextRelease,
notes: `${notes1}\n\n${notes2}\n\n${notes3}`,
pluginName: '[Function: functionStub]',
},
{...nextRelease, notes: `${notes1}\n\n${notes2}\n\n${notes3}`, pluginName: pluginNoop},
],
});
@@ -215,7 +225,14 @@ test('Use custom tag format', async t => {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.truthy(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
// Verify the tag has been created on the local and remote repo and reference the gitHead
t.is(await gitTagHead(nextRelease.gitTag, {cwd}), nextRelease.gitHead);
@@ -260,7 +277,14 @@ test('Use new gitHead, and recreate release notes if a prepare plugin create a c
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.truthy(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.is(generateNotes.callCount, 2);
t.deepEqual(generateNotes.args[0][1].nextRelease, nextRelease);
@@ -318,13 +342,19 @@ test('Call all "success" plugins even if one errors out', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await t.throws(semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
);
t.is(success1.callCount, 1);
t.deepEqual(success1.args[0][1].releases, [{...release, ...nextRelease, notes, pluginName: '[Function: proxy]'}]);
t.deepEqual(success1.args[0][1].releases, [
{...release, ...nextRelease, notes, pluginName: '[Function: functionStub]'},
]);
t.is(success2.callCount, 1);
t.deepEqual(success2.args[0][1].releases, [{...release, ...nextRelease, notes, pluginName: '[Function: proxy]'}]);
t.deepEqual(success2.args[0][1].releases, [
{...release, ...nextRelease, notes, pluginName: '[Function: functionStub]'},
]);
});
test('Log all "verifyConditions" errors', async t => {
@@ -341,6 +371,7 @@ test('Log all "verifyConditions" errors', async t => {
const config = {branch: 'master', repositoryUrl, tagFormat: `v\${version}`};
const options = {
...config,
plugins: false,
verifyConditions: [stub().rejects(new AggregateError([error1, error2])), stub().rejects(error3)],
fail,
};
@@ -350,16 +381,15 @@ test('Log all "verifyConditions" errors', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const errors = [
...(await t.throws(semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}))),
...(await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
)),
];
t.deepEqual(errors, [error1, error2, error3]);
t.deepEqual(t.context.error.args[t.context.error.args.length - 2], ['ERR2 error 2']);
t.deepEqual(t.context.error.args[t.context.error.args.length - 1], ['ERR3 error 3']);
t.deepEqual(t.context.error.args[t.context.error.args.length - 3], [
'An error occurred while running semantic-release: %O',
error1,
]);
t.deepEqual(sortBy(errors, ['message']), sortBy([error1, error2, error3], ['message']));
t.true(t.context.error.calledWith('An error occurred while running semantic-release: %O', error1));
t.true(t.context.error.calledWith('ERR2 error 2'));
t.true(t.context.error.calledWith('ERR3 error 3'));
t.true(t.context.error.calledAfter(t.context.log));
t.is(fail.callCount, 1);
t.deepEqual(fail.args[0][0], config);
@@ -396,18 +426,20 @@ test('Log all "verifyRelease" errors', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const errors = [
...(await t.throws(semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}))),
...(await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
)),
];
t.deepEqual(errors, [error1, error2]);
t.deepEqual(t.context.error.args[t.context.error.args.length - 2], ['ERR1 error 1']);
t.deepEqual(t.context.error.args[t.context.error.args.length - 1], ['ERR2 error 2']);
t.deepEqual(sortBy(errors, ['message']), sortBy([error1, error2], ['message']));
t.true(t.context.error.calledWith('ERR1 error 1'));
t.true(t.context.error.calledWith('ERR2 error 2'));
t.is(fail.callCount, 1);
t.deepEqual(fail.args[0][0], config);
t.deepEqual(fail.args[0][1].errors, [error1, error2]);
});
test('Dry-run skips publish and success', async t => {
test('Dry-run skips prepare, publish and success', async t => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd, repositoryUrl} = await gitRepo(true);
// Add commits to the master branch
@@ -425,6 +457,7 @@ test('Dry-run skips publish and success', async t => {
const analyzeCommits = stub().resolves(nextRelease.type);
const verifyRelease = stub().resolves();
const generateNotes = stub().resolves(notes);
const prepare = stub().resolves();
const publish = stub().resolves();
const success = stub().resolves();
@@ -436,7 +469,7 @@ test('Dry-run skips publish and success', async t => {
analyzeCommits,
verifyRelease,
generateNotes,
prepare: stub().resolves(),
prepare,
publish,
success,
};
@@ -445,15 +478,26 @@ test('Dry-run skips publish and success', async t => {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.truthy(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.not(t.context.log.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
t.not(t.context.warn.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
t.is(verifyConditions.callCount, 1);
t.is(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 1);
t.is(generateNotes.callCount, 1);
t.is(prepare.callCount, 0);
t.true(t.context.warn.calledWith(`Skip step "prepare" of plugin "[Function: ${prepare.name}]" in dry-run mode`));
t.is(publish.callCount, 0);
t.true(t.context.warn.calledWith(`Skip step "publish" of plugin "[Function: ${publish.name}]" in dry-run mode`));
t.is(success.callCount, 0);
t.true(t.context.warn.calledWith(`Skip step "success" of plugin "[Function: ${success.name}]" in dry-run mode`));
});
test('Dry-run skips fail', async t => {
@@ -484,13 +528,16 @@ test('Dry-run skips fail', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const errors = [
...(await t.throws(semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}))),
...(await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
)),
];
t.deepEqual(errors, [error1, error2]);
t.deepEqual(t.context.error.args[t.context.error.args.length - 2], ['ERR1 error 1']);
t.deepEqual(t.context.error.args[t.context.error.args.length - 1], ['ERR2 error 2']);
t.deepEqual(sortBy(errors, ['message']), sortBy([error1, error2], ['message']));
t.true(t.context.error.calledWith('ERR1 error 1'));
t.true(t.context.error.calledWith('ERR2 error 2'));
t.is(fail.callCount, 0);
t.true(t.context.warn.calledWith(`Skip step "fail" of plugin "[Function: ${fail.name}]" in dry-run mode`));
});
test('Force a dry-run if not on a CI and "noCi" is not explicitly set', async t => {
@@ -532,9 +579,16 @@ test('Force a dry-run if not on a CI and "noCi" is not explicitly set', async t
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: false, branch: 'master'}),
});
t.truthy(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.truthy(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.is(t.context.log.args[1][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
t.true(t.context.warn.calledWith('This run was not triggered in a known CI environment, running in dry-run mode.'));
t.is(verifyConditions.callCount, 1);
t.is(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 1);
@@ -575,7 +629,14 @@ test('Dry-run does not print changelog if "generateNotes" return "undefined"', a
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.truthy(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.deepEqual(t.context.log.args[t.context.log.args.length - 1], ['Release note for version 2.0.0:']);
});
@@ -619,7 +680,14 @@ test('Allow local releases with "noCi" option', async t => {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: false, branch: 'master', isPr: true}),
});
t.truthy(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.truthy(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.not(t.context.log.args[0][0], 'This run was not triggered in a known CI environment, running in dry-run mode.');
t.not(
@@ -634,7 +702,7 @@ test('Allow local releases with "noCi" option', async t => {
t.is(success.callCount, 1);
});
test('Accept "undefined" value returned by the "generateNotes" plugins', async t => {
test('Accept "undefined" value returned by "generateNotes" and "false" by "publish"', async t => {
// Create a git repository, set the current working directory at the root of the repo
const {cwd, repositoryUrl} = await gitRepo(true);
// Add commits to the master branch
@@ -652,7 +720,8 @@ test('Accept "undefined" value returned by the "generateNotes" plugins', async t
const generateNotes1 = stub().resolves();
const notes2 = 'Release notes 2';
const generateNotes2 = stub().resolves(notes2);
const publish = stub().resolves();
const publish = stub().resolves(false);
const success = stub().resolves();
const options = {
branch: 'master',
@@ -663,7 +732,7 @@ test('Accept "undefined" value returned by the "generateNotes" plugins', async t
generateNotes: [generateNotes1, generateNotes2],
prepare: stub().resolves(),
publish,
success: stub().resolves(),
success,
fail: stub().resolves(),
};
@@ -671,7 +740,14 @@ test('Accept "undefined" value returned by the "generateNotes" plugins', async t
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.truthy(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.is(analyzeCommits.callCount, 1);
t.deepEqual(analyzeCommits.args[0][1].lastRelease, lastRelease);
@@ -688,6 +764,9 @@ test('Accept "undefined" value returned by the "generateNotes" plugins', async t
t.is(publish.callCount, 1);
t.deepEqual(publish.args[0][1].lastRelease, lastRelease);
t.is(publish.args[0][1].nextRelease.notes, notes2);
t.is(success.callCount, 1);
t.deepEqual(success.args[0][1].releases, [{pluginName: '[Function: functionStub]'}]);
});
test('Returns false if triggered by a PR', async t => {
@@ -700,7 +779,10 @@ test('Returns false if triggered by a PR', async t => {
});
t.false(
await semanticRelease({cwd, repositoryUrl}, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}})
await semanticRelease(
{cwd, repositoryUrl},
{cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()}
)
);
t.is(
t.context.log.args[t.context.log.args.length - 1][0],
@@ -728,7 +810,7 @@ test('Returns false if triggered on an outdated clone', async t => {
t.false(
await semanticRelease(
{repositoryUrl},
{cwd: repoDir, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}
{cwd: repoDir, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()}
)
);
t.deepEqual(t.context.log.args[t.context.log.args.length - 1], [
@@ -757,7 +839,14 @@ test('Returns false if not running from the configured branch', async t => {
'env-ci': () => ({isCi: true, branch: 'other-branch', isPr: false}),
});
t.false(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.false(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.is(
t.context.log.args[1][0],
'This test run was triggered on the branch other-branch, while semantic-release is configured to only publish from master, therefore a new version won’t be published.'
@@ -794,7 +883,14 @@ test('Returns false if there is no relevant changes', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.false(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.false(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.is(analyzeCommits.callCount, 1);
t.is(verifyRelease.callCount, 0);
t.is(generateNotes.callCount, 0);
@@ -841,7 +937,12 @@ test('Exclude commits with [skip release] or [release skip] from analysis', asyn
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}});
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
});
t.is(analyzeCommits.callCount, 1);
t.is(analyzeCommits.args[0][1].commits.length, 2);
@@ -865,7 +966,9 @@ test('Log both plugins errors and errors thrown by "fail" plugin', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await t.throws(semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
);
t.is(t.context.error.args[t.context.error.args.length - 1][0], 'ERR Plugin error');
t.is(t.context.error.args[t.context.error.args.length - 3][1], failError1);
@@ -888,7 +991,9 @@ test('Call "fail" only if a plugin returns a SemanticReleaseError', async t => {
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await t.throws(semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
);
t.true(fail.notCalled);
t.is(t.context.error.args[t.context.error.args.length - 1][1], pluginError);
@@ -903,7 +1008,9 @@ test('Throw SemanticReleaseError if repositoryUrl is not set and cannot be found
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const errors = [
...(await t.throws(semanticRelease({}, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}))),
...(await t.throwsAsync(
semanticRelease({}, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()})
)),
];
// Verify error code and type
@@ -938,13 +1045,95 @@ test('Throw an Error if plugin returns an unexpected value', async t => {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
const error = await t.throws(
semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}),
const error = await t.throwsAsync(
semanticRelease(options, {cwd, env: {}, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()}),
Error
);
t.regex(error.details, /string/);
});
test('Hide sensitive information passed to "fail" plugin', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const fail = stub().resolves();
const env = {MY_TOKEN: 'secret token'};
const options = {
branch: 'master',
repositoryUrl,
verifyConditions: stub().throws(
new SemanticReleaseError(
`Message: Exposing token ${env.MY_TOKEN}`,
'ERR',
`Details: Exposing token ${env.MY_TOKEN}`
)
),
success: stub().resolves(),
fail,
};
const semanticRelease = requireNoCache('..', {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await t.throwsAsync(
semanticRelease(options, {cwd, env, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()}),
Error
);
const error = fail.args[0][1].errors[0];
t.is(error.message, `Message: Exposing token ${SECRET_REPLACEMENT}`);
t.is(error.details, `Details: Exposing token ${SECRET_REPLACEMENT}`);
Object.getOwnPropertyNames(error).forEach(prop => {
if (isString(error[prop])) {
t.notRegex(error[prop], new RegExp(escapeRegExp(env.MY_TOKEN)));
}
});
});
test('Hide sensitive information passed to "success" plugin', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
await gitCommits(['feat: initial release'], {cwd});
await gitTagVersion('v1.0.0', undefined, {cwd});
await gitCommits(['feat: new feature'], {cwd});
await gitPush(repositoryUrl, 'master', {cwd});
const success = stub().resolves();
const env = {MY_TOKEN: 'secret token'};
const options = {
branch: 'master',
repositoryUrl,
verifyConditions: false,
verifyRelease: false,
prepare: false,
generateNotes: stub().resolves(`Exposing token ${env.MY_TOKEN}`),
publish: stub().resolves({
name: `Name: Exposing token ${env.MY_TOKEN}`,
url: `URL: Exposing token ${env.MY_TOKEN}`,
}),
success,
fail: stub().resolves(),
};
const semanticRelease = requireNoCache('..', {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
await semanticRelease(options, {cwd, env, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()});
const release = success.args[0][1].releases[0];
t.is(release.name, `Name: Exposing token ${SECRET_REPLACEMENT}`);
t.is(release.url, `URL: Exposing token ${SECRET_REPLACEMENT}`);
Object.getOwnPropertyNames(release).forEach(prop => {
if (isString(release[prop])) {
t.notRegex(release[prop], new RegExp(escapeRegExp(env.MY_TOKEN)));
}
});
});
test('Get all commits including the ones not in the shallow clone', async t => {
let {cwd, repositoryUrl} = await gitRepo(true);
await gitTagVersion('v1.0.0', undefined, {cwd});
@@ -974,7 +1163,14 @@ test('Get all commits including the ones not in the shallow clone', async t => {
'./lib/get-logger': () => t.context.logger,
'env-ci': () => ({isCi: true, branch: 'master', isPr: false}),
});
t.truthy(await semanticRelease(options, {cwd, env: {}, stdout: {write: () => {}}, stderr: {write: () => {}}}));
t.truthy(
await semanticRelease(options, {
cwd,
env: {},
stdout: new WritableStreamBuffer(),
stderr: new WritableStreamBuffer(),
})
);
t.is(analyzeCommits.args[0][1].commits.length, 3);
});
+41 -40
View File
@@ -4,8 +4,9 @@ import test from 'ava';
import {escapeRegExp} from 'lodash';
import {writeJson, readJson} from 'fs-extra';
import execa from 'execa';
import {WritableStreamBuffer} from 'stream-buffers';
import {SECRET_REPLACEMENT} from '../lib/definitions/constants';
import {gitHead as getGitHead, gitTagHead, gitRepo, gitCommits, gitRemoteTagHead, gitPush} from './helpers/git-utils';
import {gitHead, 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';
@@ -107,12 +108,12 @@ test('Release patch, minor and major versions', async t => {
let [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
let gitHead = await getGitHead({cwd});
let head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -149,12 +150,12 @@ test('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
gitHead = await getGitHead({cwd});
head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -191,12 +192,12 @@ test('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
gitHead = await getGitHead({cwd});
head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -233,12 +234,12 @@ test('Release patch, minor and major versions', async t => {
[, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
gitHead = await getGitHead({cwd});
head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -257,7 +258,7 @@ test('Exit with 1 if a plugin is not found', async t => {
release: {analyzeCommits: 'non-existing-path', success: false, fail: false},
});
const {code, stderr} = await t.throws(execa(cli, [], {env, cwd}));
const {code, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
@@ -275,7 +276,7 @@ test('Exit with 1 if a shareable config is not found', async t => {
release: {extends: 'non-existing-path', success: false, fail: false},
});
const {code, stderr} = await t.throws(execa(cli, [], {env, cwd}));
const {code, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
@@ -296,7 +297,7 @@ test('Exit with 1 if a shareable config reference a not found plugin', async t =
});
await writeJson(path.resolve(cwd, 'shareable.json'), shareable);
const {code, stderr} = await t.throws(execa(cli, [], {env, cwd}));
const {code, stderr} = await t.throwsAsync(execa(cli, [], {env, cwd}));
t.is(code, 1);
t.regex(stderr, /Cannot find module/);
});
@@ -387,12 +388,12 @@ test('Allow local releases with "noCi" option', async t => {
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
const gitHead = await getGitHead({cwd});
const head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
@@ -441,12 +442,12 @@ test('Pass options via CLI arguments', async t => {
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
const gitHead = await getGitHead({cwd});
const head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
});
test('Run via JS API', async t => {
@@ -490,7 +491,7 @@ test('Run via JS API', async t => {
t.log('Commit a feature');
await gitCommits(['feat: Initial commit'], {cwd});
t.log('$ Call semantic-release via API');
await semanticRelease(undefined, {cwd, env, stdout: {write: () => {}}, stderr: {write: () => {}}});
await semanticRelease(undefined, {cwd, env, stdout: new WritableStreamBuffer(), stderr: new WritableStreamBuffer()});
// Verify package.json and has been updated
t.is((await readJson(path.resolve(cwd, 'package.json'))).version, version);
@@ -499,12 +500,12 @@ test('Run via JS API', async t => {
const [, releasedVersion, releasedGitHead] = /^version = '(.+)'\s+gitHead = '(.+)'$/.exec(
(await execa('npm', ['show', packageName, 'version', 'gitHead'], {env: testEnv, cwd})).stdout
);
const gitHead = await getGitHead({cwd});
const head = await gitHead({cwd});
t.is(releasedVersion, version);
t.is(releasedGitHead, gitHead);
t.is(await gitTagHead(`v${version}`, {cwd}), gitHead);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), gitHead);
t.log(`+ released ${releasedVersion} with gitHead ${releasedGitHead}`);
t.is(releasedGitHead, head);
t.is(await gitTagHead(`v${version}`, {cwd}), head);
t.is(await gitRemoteTagHead(authUrl, `v${version}`, {cwd}), head);
t.log(`+ released ${releasedVersion} with head ${releasedGitHead}`);
await mockServer.verify(verifyMock);
await mockServer.verify(createReleaseMock);
+31 -13
View File
@@ -62,7 +62,7 @@ test('Wrap plugin in a function that add the "pluginName" to the error"', async
'./plugin-error': './test/fixtures',
});
const error = await t.throws(plugin());
const error = await t.throwsAsync(plugin({options: {}}));
t.is(error.pluginName, './plugin-error');
});
@@ -72,7 +72,7 @@ test('Wrap plugin in a function that add the "pluginName" to multiple errors"',
'./plugin-errors': './test/fixtures',
});
const errors = [...(await t.throws(plugin()))];
const errors = [...(await t.throwsAsync(plugin({options: {}})))];
for (const error of errors) {
t.is(error.pluginName, './plugin-errors');
}
@@ -107,7 +107,7 @@ test('Wrap "analyzeCommits" plugin in a function that validate the output of the
{}
);
const error = await t.throws(plugin());
const error = await t.throwsAsync(plugin({options: {}}));
t.is(error.code, 'EANALYZECOMMITSOUTPUT');
t.is(error.name, 'SemanticReleaseError');
@@ -125,7 +125,7 @@ test('Wrap "generateNotes" plugin in a function that validate the output of the
{}
);
const error = await t.throws(plugin());
const error = await t.throwsAsync(plugin({options: {}}));
t.is(error.code, 'EGENERATENOTESOUTPUT');
t.is(error.name, 'SemanticReleaseError');
@@ -143,7 +143,7 @@ test('Wrap "publish" plugin in a function that validate the output of the plugin
{}
);
const error = await t.throws(plugin());
const error = await t.throwsAsync(plugin({options: {}}));
t.is(error.code, 'EPUBLISHOUTPUT');
t.is(error.name, 'SemanticReleaseError');
@@ -152,15 +152,33 @@ test('Wrap "publish" plugin in a function that validate the output of the plugin
t.regex(error.details, /2/);
});
test('Plugin is called with "pluginConfig" (omitting "path", adding global config) and input', async t => {
test('Plugin is called with "pluginConfig" (with object definition) and input', async t => {
const pluginFunction = stub().resolves();
const pluginConf = {path: pluginFunction, conf: 'confValue'};
const options = {global: 'globalValue'};
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin({param: 'param'});
await plugin({options: {}, param: 'param'});
t.true(
pluginFunction.calledWith({conf: 'confValue', global: 'globalValue'}, {param: 'param', logger: t.context.logger})
pluginFunction.calledWithMatch(
{conf: 'confValue', global: 'globalValue'},
{param: 'param', logger: t.context.logger}
)
);
});
test('Plugin is called with "pluginConfig" (with array definition) and input', async t => {
const pluginFunction = stub().resolves();
const pluginConf = [pluginFunction, {conf: 'confValue'}];
const options = {global: 'globalValue'};
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin({options: {}, param: 'param'});
t.true(
pluginFunction.calledWithMatch(
{conf: 'confValue', global: 'globalValue'},
{param: 'param', logger: t.context.logger}
)
);
});
@@ -171,7 +189,7 @@ test('Prevent plugins to modify "pluginConfig"', async t => {
const pluginConf = {path: pluginFunction, conf: {subConf: 'originalConf'}};
const options = {globalConf: {globalSubConf: 'originalGlobalConf'}};
const plugin = normalize({cwd, options, logger: t.context.logger}, '', pluginConf, {});
await plugin();
await plugin({options: {}});
t.is(pluginConf.conf.subConf, 'originalConf');
t.is(options.globalConf.globalSubConf, 'originalGlobalConf');
@@ -181,7 +199,7 @@ test('Prevent plugins to modify its input', async t => {
const pluginFunction = stub().callsFake((pluginConfig, options) => {
options.param.subParam = 'otherParam';
});
const input = {param: {subParam: 'originalSubParam'}};
const input = {param: {subParam: 'originalSubParam'}, options: {}};
const plugin = normalize({cwd, options: {}, logger: t.context.logger}, '', pluginFunction, {});
await plugin(input);
@@ -202,7 +220,7 @@ test('Always pass a defined "pluginConfig" for plugin defined with string', asyn
'./test/fixtures/plugin-result-config',
{}
);
const pluginResult = await plugin();
const pluginResult = await plugin({options: {}});
t.deepEqual(pluginResult.pluginConfig, {});
});
@@ -215,7 +233,7 @@ test('Always pass a defined "pluginConfig" for plugin defined with path', async
{path: './test/fixtures/plugin-result-config'},
{}
);
const pluginResult = await plugin();
const pluginResult = await plugin({options: {}});
t.deepEqual(pluginResult.pluginConfig, {});
});
@@ -237,6 +255,6 @@ test('Throws an error if the plugin is not found', t => {
Error
);
t.is(error.message, "Cannot find module 'non-existing-path'");
t.regex(error.message, /Cannot find module 'non-existing-path'/);
t.is(error.code, 'MODULE_NOT_FOUND');
});
+5 -5
View File
@@ -83,7 +83,7 @@ test('Stop execution and throw error if a step rejects', async t => {
const step2 = stub().rejects(new Error('test error'));
const step3 = stub().resolves(3);
const error = await t.throws(pipeline([step1, step2, step3])(0), Error);
const error = await t.throwsAsync(pipeline([step1, step2, step3])(0), Error);
t.is(error.message, 'test error');
t.true(step1.calledWith(0));
t.true(step2.calledWith(0));
@@ -98,7 +98,7 @@ test('Throw all errors from the first step throwing an AggregateError', async t
const step2 = stub().rejects(new AggregateError([error1, error2]));
const step3 = stub().resolves(3);
const errors = await t.throws(pipeline([step1, step2, step3])(0));
const errors = await t.throwsAsync(pipeline([step1, step2, step3])(0));
t.deepEqual([...errors], [error1, error2]);
t.true(step1.calledWith(0));
@@ -113,7 +113,7 @@ test('Execute all even if a Promise rejects', async t => {
const step2 = stub().rejects(error1);
const step3 = stub().rejects(error2);
const errors = await t.throws(pipeline([step1, step2, step3], {settleAll: true})(0));
const errors = await t.throwsAsync(pipeline([step1, step2, step3], {settleAll: true})(0));
t.deepEqual([...errors], [error1, error2]);
t.true(step1.calledWith(0));
@@ -129,7 +129,7 @@ test('Throw all errors from all steps throwing an AggregateError', async t => {
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));
const errors = await t.throwsAsync(pipeline([step1, step2], {settleAll: true})(0));
t.deepEqual([...errors], [error1, error2, error3, error4]);
t.true(step1.calledWith(0));
@@ -145,7 +145,7 @@ test('Execute each function in series passing a transformed input even if a step
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));
const errors = await t.throwsAsync(pipeline([step1, step2, step3, step4], {settleAll: true, getNextInput})(0));
t.deepEqual([...errors], [error2, error3]);
t.true(step1.calledWith(0));
+140 -5
View File
@@ -29,7 +29,7 @@ test('Export default plugins', t => {
t.is(typeof plugins.fail, 'function');
});
test('Export plugins based on config', t => {
test('Export plugins based on steps config', t => {
const plugins = getPlugins(
{
cwd,
@@ -55,6 +55,88 @@ test('Export plugins based on config', t => {
t.is(typeof plugins.fail, 'function');
});
test('Export plugins based on "plugins" config (array)', async t => {
const plugin1 = {verifyConditions: stub(), publish: stub()};
const plugin2 = {verifyConditions: stub(), verifyRelease: stub()};
const plugins = getPlugins(
{cwd, logger: t.context.logger, options: {plugins: [plugin1, [plugin2, {}]], verifyRelease: () => {}}},
{}
);
await plugins.verifyConditions({options: {}});
t.true(plugin1.verifyConditions.calledOnce);
t.true(plugin2.verifyConditions.calledOnce);
await plugins.publish({options: {}});
t.true(plugin1.publish.calledOnce);
await plugins.verifyRelease({options: {}});
t.true(plugin2.verifyRelease.notCalled);
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, '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 "plugins" config (single definition)', async t => {
const plugin1 = {verifyConditions: stub(), publish: stub()};
const plugins = getPlugins({cwd, logger: t.context.logger, options: {plugins: plugin1}}, {});
await plugins.verifyConditions({options: {}});
t.true(plugin1.verifyConditions.calledOnce);
await plugins.publish({options: {}});
t.true(plugin1.publish.calledOnce);
// Verify the module returns a function for each plugin
t.is(typeof plugins.verifyConditions, '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('Merge global options, "plugins" options and step options', async t => {
const plugin1 = [{verifyConditions: stub(), publish: stub()}, {pluginOpt1: 'plugin1'}];
const plugin2 = [{verifyConditions: stub()}, {pluginOpt2: 'plugin2'}];
const plugin3 = [stub(), {pluginOpt3: 'plugin3'}];
const plugins = getPlugins(
{
cwd,
logger: t.context.logger,
options: {globalOpt: 'global', plugins: [plugin1, plugin2], verifyRelease: [plugin3]},
},
{}
);
await plugins.verifyConditions({options: {}});
t.deepEqual(plugin1[0].verifyConditions.args[0][0], {globalOpt: 'global', pluginOpt1: 'plugin1'});
t.deepEqual(plugin2[0].verifyConditions.args[0][0], {globalOpt: 'global', pluginOpt2: 'plugin2'});
await plugins.publish({options: {}});
t.deepEqual(plugin1[0].publish.args[0][0], {globalOpt: 'global', pluginOpt1: 'plugin1'});
await plugins.verifyRelease({options: {}});
t.deepEqual(plugin3[0].args[0][0], {globalOpt: 'global', pluginOpt3: 'plugin3'});
});
test('Unknown steps of plugins configured in "plugins" are ignored', t => {
const plugin1 = {verifyConditions: () => {}, unknown: () => {}};
const plugins = getPlugins({cwd, logger: t.context.logger, options: {plugins: [plugin1]}}, {});
t.is(typeof plugins.verifyConditions, 'function');
t.is(plugins.unknown, undefined);
});
test('Export plugins loaded from the dependency of a shareable config module', async t => {
const cwd = tempy.directory();
await copy(
@@ -121,11 +203,23 @@ test('Export plugins loaded from the dependency of a shareable config file', asy
test('Use default when only options are passed for a single plugin', t => {
const analyzeCommits = {};
const generateNotes = {};
const publish = {};
const success = () => {};
const fail = [() => {}];
const plugins = getPlugins(
{cwd, logger: t.context.logger, options: {analyzeCommits, generateNotes, success, fail}},
{
cwd,
logger: t.context.logger,
options: {
plugins: ['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator'],
analyzeCommits,
generateNotes,
publish,
success,
fail,
},
},
{}
);
@@ -154,19 +248,25 @@ test('Merge global options with plugin options', async t => {
{}
);
const [result] = await plugins.verifyRelease();
const [result] = await plugins.verifyRelease({options: {}});
t.deepEqual(result.pluginConfig, {localOpt: 'local', globalOpt: 'global', otherOpt: 'locally-defined'});
});
test('Throw an error if plugins configuration are invalid', t => {
test('Throw an error for each invalid plugin configuration', t => {
const errors = [
...t.throws(() =>
getPlugins(
{
cwd,
logger: t.context.logger,
options: {verifyConditions: {}, analyzeCommits: [], verifyRelease: [{}], generateNotes: [{path: null}]},
options: {
plugins: ['@semantic-release/commit-analyzer', '@semantic-release/release-notes-generator'],
verifyConditions: 1,
analyzeCommits: [],
verifyRelease: [{}],
generateNotes: [{path: null}],
},
},
{}
)
@@ -182,3 +282,38 @@ test('Throw an error if plugins configuration are invalid', t => {
t.is(errors[3].name, 'SemanticReleaseError');
t.is(errors[3].code, 'EPLUGINCONF');
});
test('Throw EPLUGINSCONF error if the "plugins" option contains an old plugin definition (returns a function)', t => {
const errors = [
...t.throws(() =>
getPlugins(
{
cwd,
logger: t.context.logger,
options: {plugins: ['./test/fixtures/multi-plugin', './test/fixtures/plugin-noop', () => {}]},
},
{}
)
),
];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EPLUGINSCONF');
t.is(errors[1].name, 'SemanticReleaseError');
t.is(errors[1].code, 'EPLUGINSCONF');
});
test('Throw EPLUGINSCONF error for each invalid definition if the "plugins" option', t => {
const errors = [
...t.throws(() =>
getPlugins({cwd, logger: t.context.logger, options: {plugins: [1, {path: 1}, [() => {}, {}, {}]]}}, {})
),
];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EPLUGINSCONF');
t.is(errors[1].name, 'SemanticReleaseError');
t.is(errors[1].code, 'EPLUGINSCONF');
t.is(errors[2].name, 'SemanticReleaseError');
t.is(errors[2].code, 'EPLUGINSCONF');
});
+200 -44
View File
@@ -1,58 +1,214 @@
import test from 'ava';
import {validateConfig} from '../../lib/plugins/utils';
import {validatePlugin, validateStep, loadPlugin, parseConfig} from '../../lib/plugins/utils';
test('Validate multiple/optional plugin configuration', t => {
test('validatePlugin', t => {
const path = 'plugin-module';
const options = {option1: 'value1', option2: 'value2'};
t.true(validatePlugin(path), 'String definition');
t.true(validatePlugin({publish: () => {}}), 'Object definition');
t.true(validatePlugin([path]), 'Array definition');
t.true(validatePlugin([path, options]), 'Array definition with options');
t.true(validatePlugin([{publish: () => {}}, options]), 'Array definition with options and path as object');
t.true(validatePlugin({path}), 'Object with path definition');
t.true(validatePlugin({path, ...options}), 'Object with path definition with options');
t.true(
validatePlugin({path: {publish: () => {}}, ...options}),
'Object with path definition with options and path as object'
);
t.false(validatePlugin(1), 'String definition, wrong path');
t.false(validatePlugin([]), 'Array definition, missing path');
t.false(validatePlugin([path, options, {}]), 'Array definition, additional parameter');
t.false(validatePlugin([1]), 'Array definition, wrong path');
t.false(validatePlugin([path, 1]), 'Array definition, wrong options');
t.false(validatePlugin({path: 1}), 'Object definition, wrong path');
});
test('validateStep: optional plugin configuration', t => {
const type = {multiple: true, required: false};
t.false(validateConfig(type, {}));
t.false(validateConfig(type, {path: null}));
t.true(validateConfig(type, {path: 'plugin-path.js'}));
t.true(validateConfig(type));
t.true(validateConfig(type, 'plugin-path.js'));
t.true(validateConfig(type, ['plugin-path.js']));
t.true(validateConfig(type, () => {}));
t.true(validateConfig(type, [{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
// Empty config
t.true(validateStep(type));
t.true(validateStep(type, []));
// Single value definition
t.true(validateStep(type, 'plugin-path.js'));
t.true(validateStep(type, () => {}));
t.true(validateStep(type, ['plugin-path.js']));
t.true(validateStep(type, [() => {}]));
t.false(validateStep(type, {}));
t.false(validateStep(type, [{}]));
// Array type definition
t.true(validateStep(type, [['plugin-path.js']]));
t.true(validateStep(type, [['plugin-path.js', {options: 'value'}]]));
t.true(validateStep(type, [[() => {}, {options: 'value'}]]));
t.false(validateStep(type, [['plugin-path.js', 1]]));
// Object type definition
t.true(validateStep(type, {path: 'plugin-path.js'}));
t.true(validateStep(type, {path: 'plugin-path.js', options: 'value'}));
t.true(validateStep(type, {path: () => {}, options: 'value'}));
t.false(validateStep(type, {path: null}));
// Considered as an Array of 2 definitions and not as one Array definition in case of a muliple plugin type
t.false(validateStep(type, [() => {}, {options: 'value'}]));
t.false(validateStep(type, ['plugin-path.js', {options: 'value'}]));
// Multiple definitions
t.true(
validateStep(type, [
'plugin-path.js',
() => {},
['plugin-path.js'],
['plugin-path.js', {options: 'value'}],
[() => {}, {options: 'value'}],
{path: 'plugin-path.js'},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
t.false(
validateStep(type, [
'plugin-path.js',
() => {},
['plugin-path.js'],
['plugin-path.js', 1],
[() => {}, {options: 'value'}],
{path: 'plugin-path.js'},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
t.false(
validateStep(type, [
'plugin-path.js',
{},
['plugin-path.js'],
['plugin-path.js', {options: 'value'}],
[() => {}, {options: 'value'}],
{path: 'plugin-path.js'},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
t.false(
validateStep(type, [
'plugin-path.js',
() => {},
['plugin-path.js'],
['plugin-path.js', {options: 'value'}],
[() => {}, {options: 'value'}],
{path: null},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
});
test('Validate multiple/required plugin configuration', t => {
const type = {multiple: true, required: true};
t.false(validateConfig(type, {}));
t.false(validateConfig(type, {path: null}));
t.false(validateConfig(type));
test('validateStep: required plugin configuration', t => {
const type = {required: true};
t.true(validateConfig(type, {path: 'plugin-path.js'}));
t.true(validateConfig(type, 'plugin-path.js'));
t.true(validateConfig(type, ['plugin-path.js']));
t.true(validateConfig(type, () => {}));
t.true(validateConfig(type, [{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
// Empty config
t.false(validateStep(type));
t.false(validateStep(type, []));
// Single value definition
t.true(validateStep(type, 'plugin-path.js'));
t.true(validateStep(type, () => {}));
t.true(validateStep(type, ['plugin-path.js']));
t.true(validateStep(type, [() => {}]));
t.false(validateStep(type, {}));
t.false(validateStep(type, [{}]));
// Array type definition
t.true(validateStep(type, [['plugin-path.js']]));
t.true(validateStep(type, [['plugin-path.js', {options: 'value'}]]));
t.true(validateStep(type, [[() => {}, {options: 'value'}]]));
t.false(validateStep(type, [['plugin-path.js', 1]]));
// Object type definition
t.true(validateStep(type, {path: 'plugin-path.js'}));
t.true(validateStep(type, {path: 'plugin-path.js', options: 'value'}));
t.true(validateStep(type, {path: () => {}, options: 'value'}));
t.false(validateStep(type, {path: null}));
// Considered as an Array of 2 definitions and not as one Array definition in the case of a muliple plugin type
t.false(validateStep(type, [() => {}, {options: 'value'}]));
t.false(validateStep(type, ['plugin-path.js', {options: 'value'}]));
// Multiple definitions
t.true(
validateStep(type, [
'plugin-path.js',
() => {},
['plugin-path.js'],
['plugin-path.js', {options: 'value'}],
[() => {}, {options: 'value'}],
{path: 'plugin-path.js'},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
t.false(
validateStep(type, [
'plugin-path.js',
() => {},
['plugin-path.js'],
['plugin-path.js', 1],
[() => {}, {options: 'value'}],
{path: 'plugin-path.js'},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
t.false(
validateStep(type, [
'plugin-path.js',
{},
['plugin-path.js'],
['plugin-path.js', {options: 'value'}],
[() => {}, {options: 'value'}],
{path: 'plugin-path.js'},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
t.false(
validateStep(type, [
'plugin-path.js',
() => {},
['plugin-path.js'],
['plugin-path.js', {options: 'value'}],
[() => {}, {options: 'value'}],
{path: null},
{path: 'plugin-path.js', options: 'value'},
{path: () => {}, options: 'value'},
])
);
});
test('Validate single/required plugin configuration', t => {
const type = {multiple: false, required: true};
test('loadPlugin', t => {
const cwd = process.cwd();
const func = () => {};
t.false(validateConfig(type, {}));
t.false(validateConfig(type, {path: null}));
t.false(validateConfig(type, []));
t.false(validateConfig(type));
t.false(validateConfig(type, [{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
t.true(validateConfig(type, {path: 'plugin-path.js'}));
t.true(validateConfig(type, 'plugin-path.js'));
t.true(validateConfig(type, ['plugin-path.js']));
t.true(validateConfig(type, () => {}));
t.is(require('../fixtures/plugin-noop'), loadPlugin({cwd: './test/fixtures'}, './plugin-noop', {}), 'From cwd');
t.is(
require('../fixtures/plugin-noop'),
loadPlugin({cwd}, './plugin-noop', {'./plugin-noop': './test/fixtures'}),
'From a shareable config context'
);
t.is(func, loadPlugin({cwd}, func, {}), 'Defined as a function');
});
test('Validate single/optional plugin configuration', t => {
const type = {multiple: false, required: false};
test('parseConfig', t => {
const path = 'plugin-module';
const options = {option1: 'value1', option2: 'value2'};
t.false(validateConfig(type, {}));
t.false(validateConfig(type, {path: null}));
t.false(validateConfig(type, [{path: 'plugin-path.js'}, 'plugin-path.js', () => {}]));
t.true(validateConfig(type));
t.true(validateConfig(type, []));
t.true(validateConfig(type, {path: 'plugin-path.js'}));
t.true(validateConfig(type, 'plugin-path.js'));
t.true(validateConfig(type, ['plugin-path.js']));
t.true(validateConfig(type, () => {}));
t.deepEqual(parseConfig(path), [path, {}], 'String definition');
t.deepEqual(parseConfig({path}), [path, {}], 'Object definition');
t.deepEqual(parseConfig({path, ...options}), [path, options], 'Object definition with options');
t.deepEqual(parseConfig([path]), [path, {}], 'Array definition');
t.deepEqual(parseConfig([path, options]), [path, options], 'Array definition with options');
});
+20 -6
View File
@@ -7,59 +7,73 @@ test('Throw a AggregateError', async t => {
const {cwd} = await gitRepo();
const options = {};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ENOREPOURL');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
t.is(errors[1].name, 'SemanticReleaseError');
t.is(errors[1].code, 'EINVALIDTAGFORMAT');
t.truthy(errors[1].message);
t.truthy(errors[1].details);
t.is(errors[2].name, 'SemanticReleaseError');
t.is(errors[2].code, 'ETAGNOVERSION');
t.truthy(errors[2].message);
t.truthy(errors[2].details);
});
test('Throw a SemanticReleaseError if does not run on a git repository', async t => {
const cwd = tempy.directory();
const options = {};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ENOGITREPO');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
});
test('Throw a SemanticReleaseError if the "tagFormat" is not valid', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `?\${version}`};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'EINVALIDTAGFORMAT');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
});
test('Throw a SemanticReleaseError if the "tagFormat" does not contains the "version" variable', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const options = {repositoryUrl, tagFormat: 'test'};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ETAGNOVERSION');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
});
test('Throw a SemanticReleaseError if the "tagFormat" contains multiple "version" variables', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `\${version}v\${version}`};
const errors = [...(await t.throws(verify({cwd, options})))];
const errors = [...(await t.throwsAsync(verify({cwd, options})))];
t.is(errors[0].name, 'SemanticReleaseError');
t.is(errors[0].code, 'ETAGNOVERSION');
t.truthy(errors[0].message);
t.truthy(errors[0].details);
});
test('Return "true" if all verification pass', async t => {
const {cwd, repositoryUrl} = await gitRepo(true);
const options = {repositoryUrl, tagFormat: `v\${version}`};
await t.notThrows(verify({cwd, options}));
await t.notThrowsAsync(verify({cwd, options}));
});