Compare commits

..
40 Commits
Author SHA1 Message Date
github-actions[bot] 62a9eee638 v1.4.2 2023-05-06 09:21:28 +00:00
github-actions[bot]andgithub-actions[bot] ab485bff43 Version Packages (#288)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-05-06 11:20:22 +02:00
Viktor VarlandandMateusz Burzyński 225a1e8cbc Add a throttling plugin to the used Octokit instance to retry requests after hitting secondary rate limits (#286)
* fix: prevent hitting github secondary rate limits

Adds the octokit plugin for throttling / rate-limiting to fix the
problem where action runs get blocked with a 403 error[1].

The `github.getOctokit`[2] function accepts a list of plugins, so this
passes in the `throttling` plugin[3] to be hooked into the octokit
instance.

It also needs some configuration to setup the `throttle` mechanisms,
passed in to the `getOctokit` function.

[1]: https://github.com/changesets/action/issues/192
[2]: https://github.com/actions/toolkit/blob/main/packages/github/src/github.ts#LL18C40-L18C40
[3]: https://github.com/octokit/plugin-throttling.js

* refactor: change rate limit callback signatures

Based on additional docs, the callbacks seem to have changes to their
signatures[1]. This change aligns this implementation with the docs[2].

[1]: https://octokit.github.io/rest.js/v19#throttling
[2]: https://github.com/octokit/plugin-throttling.js/blob/v5.1.1/src/index.ts#L90-L91

* chore: add changeset

* wire up typed throttle options

* Upgrade TS

* refactor: use console based logging

* Update .changeset/rotten-carrots-pump.md

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2023-05-06 10:52:18 +02:00
Mateusz Burzyński 595655c3ea Update more examples with references to the latest versions of core actions 2022-12-05 14:55:10 +01:00
allbetter-max da3a687419 Update examples in the docs to use new versions of other core actions like checkout and setup-node (#237) 2022-12-05 14:53:04 +01:00
github-actions[bot]andgithub-actions[bot] c831d73dde Version Packages (#232)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-11-08 10:30:21 +01:00
Mateusz Burzyński b78f480998 Upgrade @actions/* dependencies (#123)
* Upgrade `@actions/*` dependencies

* bumps deps again

* add changeset
2022-11-08 10:26:23 +01:00
github-actions[bot]andgithub-actions[bot] ca3c2e0bbf Version Packages (#208)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-11-02 10:27:24 +01:00
Ian SandersandMateusz Burzyński bff53cc50c Add is:pull-request to search query when looking for existing PR (#228)
* Add `is:pull-request` to search query when looking for existing PR

* Create sharp-pens-matter.md

* Update .changeset/sharp-pens-matter.md

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-11-02 10:23:46 +01:00
David GlasserandMateusz Burzyński 8ec7804f3e Create changeset for #216 (#223)
* Create changeset for #216

* Tweak changeset

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-11-02 10:18:49 +01:00
Quinn J NeumiillerandMateusz Burzyński 398d7edfb1 Use node16 (#216)
* Use node16 in actions

* fixup! Use node16 in actions

* remove `engines.npm`

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-09-15 10:36:58 +02:00
David GlasserandMateusz Burzyński 8c3f5f5637 Skip creating a PR when all existing changesets are empty (#206)
* Don't create a PR if all changesets are empty

Fixes #205.

Note that this maintains the previous behavior that if there are any
changesets (even empty ones), the action does not publish packages.

* Create three-needles-protect.md

* Update .changeset/three-needles-protect.md

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-08-18 23:10:27 +02:00
Brian Espinosa 6a46d2c283 Update README to reference baseBranch, use "main" as default in examples (#180)
* chore(docs): Update README to reference baseBranch

- Adds reference to the `baseBranch` config in the Changesets docs
- Updates all references in examples to `main` instead of `master`
  - `main` is now the default branch in new GitHub projects
  - This change aligns with the comment in the `baseBranch` section of Changesets docs

* remove commit sha from docs URL
2022-06-11 10:00:48 +02:00
Patrick McElhaney fa2875d617 Remove unnecessary email config from README (#186)
The `email=my@email.com` line isn't necessary. It doesn't seem to be a real configuration option and as far as I can tell npm ignores it. 

fixes #185
2022-05-24 13:39:08 +02:00
John Undersander 5252f6fe5d Document createGithubReleases input (#165) 2022-05-16 15:34:21 +10:00
github-actions[bot]andgithub-actions[bot] 3914e56b03 Version Packages (#169)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-05-10 11:11:10 +02:00
Nicola MolinariandMateusz Burzyński 521c27bf86 Automatically adjust GitHub PR message if it exceeds a size limit of 60k characters by omitting some of the changelog information (#157)
* fix: body max length

* docs: improve logs

* docs: changeset

* refactor: changeset message to omit some info if message exceeds size limit

* refactor: minor adjustments based on feedback

* Apply nits from code review

* Fixed tests

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-05-10 11:06:04 +02:00
Mateusz Burzyński 2ccdaef0d0 Change trigger's event type to pull_request in the CI action (#181) 2022-05-10 10:39:50 +02:00
Royston Shufflebotham 26d7bf0c4b Remove suggestions of using fetch-depth: 0 (#177)
Changesets automatically deepens a shallow clone as necessary,
so we don't need to recommend a complete deep clone in order
for changsets to work.

Fixes: #97
2022-04-29 12:53:40 +02:00
David RegisterandMateusz Burzyński 993a0a090d Added pullRequestNumber to the action's outputs (#167)
* feat: set pullRequesstNumber as action output

* chore: add changeset

* fix: feedback from pr review

* Update .changeset/long-mayflies-yell.md

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-04-07 19:10:26 +02:00
github-actions[bot] c7c59f0c6f Version Packages (#163) 2022-03-15 15:11:12 +01:00
Russell Bicknell 52c9ce75d9 Change directory to cwd before running git user setup. (#161) 2022-03-15 15:07:12 +01:00
Will WeaverandMateusz Burzyński b0aaf6aed5 Document hasChangesets output (#136)
* Add shouldPublish output

* Update README.md

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>

* Remove changeset

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-03-14 15:27:53 +01:00
Mateusz Burzyński 5766bae8d9 Add concurrency to the local Changesets workflow 2022-03-04 10:27:57 +01:00
github-actions[bot]andgithub-actions[bot] 69dae4d9ca Version Packages (#145)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-03-04 08:30:04 +01:00
Mateusz Burzyński 56bd5e54f8 Add concurrency option to the exampels in the README (#156) 2022-03-04 07:27:33 +01:00
Mateusz Burzyński 898d125cee Updated all Changesets dependencies (#144) 2022-01-27 07:36:21 +01:00
github-actions[bot]andgithub-actions[bot] e8ffc2d207 Version Packages (#140)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-01-23 14:27:10 +01:00
David RegisterandMateusz Burzyński 1ed9bc24b7 Added cwd input option (#134)
* feat: add cwd for projects that not in the root directory

* docs: add cwd to README

* reword the added log

* tweak changeset

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-01-23 14:25:45 +01:00
An PhiandMateusz Burzyński 5c0997b25e Added createGithubReleases input option (defaults to true) to control whether to create Github releases during publish or not (#130)
* allow skipping creation of Github releases

* fixes for PR review

* minor improvements

* add changeset

* nits

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2022-01-23 11:07:42 +01:00
github-actions[bot]andgithub-actions[bot] f4afbea27e Version Packages (#129)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2022-01-07 16:41:51 +01:00
Jack LeslieandMitchell Hamilton d3db9eceaf Added setupGitUser option to enable or disable setting up a default git user (#131)
* custom git user option

* Create two-dolls-promise.md

* Update two-dolls-promise.md

* change input name and update default

* Update .changeset/two-dolls-promise.md

Co-authored-by: Mitchell Hamilton <mitchell@hamil.town>
2022-01-07 15:27:29 +01:00
Mateusz Burzyński e0c51a52b8 Fix changeset author attribution 2021-12-23 11:31:32 +01:00
Mateusz BurzyńskiandDhruvdutt Jadhav 19373036c4 Setup the git user in the local config instead of the global one (#128)
* Update gitUtils.ts

* add changeset

Co-authored-by: Dhruvdutt Jadhav <dhruvdutt.jadhav@razorpay.com>
2021-12-23 11:21:40 +01:00
Mateusz Burzyński 37c2edd85b Fixed the checkout repo step in ci.yml 2021-11-26 14:18:16 +01:00
Mitchell Hamilton 5556dd0a57 Reference specific versions of other actions (#122) 2021-11-26 10:23:11 +01:00
2eadeb0ff8 Version Packages (#119)
* Version Packages

* Fixup version bump

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2021-11-25 18:07:53 +01:00
Mateusz Burzyński 3ea945d945 Rename version script to bump 2021-11-25 18:02:16 +01:00
Mateusz Burzyński 77633d0426 Fixed how local action is referenced from the workflow file 2021-11-25 17:53:46 +01:00
Mateusz BurzyńskiandNicola Molinari 05c863d3f9 Switch to Changesets-based release process (#118)
* Switch to Changesets-based release process

* Bump version

* drop unused variable

* Update .github/workflows/version-or-publish.yml

Co-authored-by: Nicola Molinari <nicola.molinari@commercetools.com>

* Push also to a release line branch when releasing

* Change node version used in the version-or-publish workflow

* Switch to using the local action

Co-authored-by: Nicola Molinari <nicola.molinari@commercetools.com>

* build the action before trying to use it the workflow

* Add changeset and actually setup Changesets, lol

Co-authored-by: Nicola Molinari <nicola.molinari@commercetools.com>
2021-11-25 17:51:48 +01:00
19 changed files with 1598 additions and 1172 deletions
+8
View File
@@ -0,0 +1,8 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
+13
View File
@@ -0,0 +1,13 @@
{
"$schema": "https://unpkg.com/@changesets/config@1.6.2/schema.json",
"changelog": [
"@changesets/changelog-github",
{ "repo": "changesets/action" }
],
"commit": false,
"linked": [],
"access": "restricted",
"baseBranch": "main",
"updateInternalDependencies": "patch",
"ignore": []
}
+7 -6
View File
@@ -1,6 +1,6 @@
name: Node CI name: Node CI
on: [push] on: [pull_request]
jobs: jobs:
build: build:
@@ -9,15 +9,16 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v2 - name: Checkout Repo
uses: actions/checkout@v2
- name: Use Node.js 12 - name: Use Node.js 16
uses: actions/setup-node@v1 uses: actions/setup-node@v1
with: with:
node-version: 12.x node-version: 16.x
- name: Install dependencies - name: Install Dependencies
run: yarn run: yarn --frozen-lockfile
- name: Test - name: Test
run: yarn test run: yarn test
+35
View File
@@ -0,0 +1,35 @@
name: Version or Publish
on:
push:
branches:
- main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs:
changesets:
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v2
- name: Use Node.js 16
uses: actions/setup-node@v1
with:
node-version: 16.x
- name: Install Dependencies
run: yarn --frozen-lockfile
- name: Build
run: yarn build
- name: Create Release Pull Request or Publish
id: changesets
uses: ./
with:
version: yarn bump
publish: yarn release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+2
View File
@@ -2,3 +2,5 @@ node_modules
.parcel-cache .parcel-cache
.cache .cache
*.log *.log
dist/
+74
View File
@@ -0,0 +1,74 @@
# @changesets/action
## 1.4.2
### Patch Changes
- [#286](https://github.com/changesets/action/pull/286) [`225a1e8`](https://github.com/changesets/action/commit/225a1e8cbcabb7b585174ba0ad806549db40d4cd) Thanks [@varl](https://github.com/varl)! - This patch implements the [`@octokit/plugin-throttling`](https://github.com/octokit/plugin-throttling.js) plugin and [wires
it up with the internal GitHub Octokit instance](https://github.com/actions/toolkit/tree/457303960f03375db6f033e214b9f90d79c3fe5c/packages/github#extending-the-octokit-instance).
This plugin is recommended by [the Octokit docs](://octokit.github.io/rest.js/v19#throttling) as it implements all the GitHub [best practices for integrators](https://docs.github.com/en/rest/guides/best-practices-for-integrators?apiVersion=2022-11-28).
This should help with `changesets/action` gitting spurious secondary rate limits and failing CI jobs, for which the only known workaround is to simply re-run the job.
## 1.4.1
### Patch Changes
- [#123](https://github.com/changesets/action/pull/123) [`b78f480`](https://github.com/changesets/action/commit/b78f48099899f0a853c5d9cd3feb21a5440babbd) Thanks [@Andarist](https://github.com/Andarist)! - Updated `@actions/*` dependencies to avoid using deprecated features of the runner.
## 1.4.0
### Minor Changes
- [#216](https://github.com/changesets/action/pull/216) [`398d7ed`](https://github.com/changesets/action/commit/398d7ed) Thanks [@quinnjn](https://github.com/quinnjn)! - Execute action with node16 instead of node12.
### Patch Changes
- [#228](https://github.com/changesets/action/pull/228) [`bff53cc`](https://github.com/changesets/action/commit/bff53cc50c1ebb33f8f558f9de2e0eb9a99230c6) Thanks [@iansan5653](https://github.com/iansan5653)! - Add `is:pull-request` to search query when looking for existing PR. This fixes an issue with user-owned PATs.
* [#206](https://github.com/changesets/action/pull/206) [`8c3f5f5`](https://github.com/changesets/action/commit/8c3f5f5637a95a2327e78d5dabcf357978aedcbb) Thanks [@glasser](https://github.com/glasser)! - Skip creating a PR when all existing changesets are empty.
## 1.3.0
### Minor Changes
- [#167](https://github.com/changesets/action/pull/167) [`993a0a0`](https://github.com/changesets/action/commit/993a0a090df78cee07481d3886dcd8b29deb9567) Thanks [@dmregister](https://github.com/dmregister)! - Added `pullRequestNumber` to the action's outputs
### Patch Changes
- [#157](https://github.com/changesets/action/pull/157) [`521c27b`](https://github.com/changesets/action/commit/521c27bf86ec53547d6a350d208fbbbc9d576fbc) Thanks [@emmenko](https://github.com/emmenko)! - Automatically adjust GitHub PR message if it exceeds a size limit of 60k characters by omitting some of the changelog information.
## 1.2.2
### Patch Changes
- [#161](https://github.com/changesets/action/pull/161) [`52c9ce7`](https://github.com/changesets/action/commit/52c9ce75d9d8a14ea2d75e4157b0c15b7a4ac313) Thanks [@bicknellr](https://github.com/bicknellr)! - Change directory to `cwd` before running git user setup. This fixes an issue when the action starts its execution not in a git repository.
## 1.2.1
### Patch Changes
- [#144](https://github.com/changesets/action/pull/144) [`898d125`](https://github.com/changesets/action/commit/898d125cee6ba00c6a11b6cadca512752c6c910c) Thanks [@Andarist](https://github.com/Andarist)! - Updated all Changesets dependencies. This should fix parsing issues for completely empty summaries that has been fixed in `@changesets/parse@0.3.11`.
## 1.2.0
### Minor Changes
- [#130](https://github.com/changesets/action/pull/130) [`5c0997b`](https://github.com/changesets/action/commit/5c0997b25e175ecf5e1723ba07210bbcea5d92fb) Thanks [@akphi](https://github.com/akphi)! - Added `createGithubReleases` input option (defaults to `true`) to control whether to create Github releases during publish or not.
* [#134](https://github.com/changesets/action/pull/134) [`1ed9bc2`](https://github.com/changesets/action/commit/1ed9bc24b7a56462c183eb815c8f4bdf0e2e5785) Thanks [@dmregister](https://github.com/dmregister)! - Added `cwd` input option that can be used in projects that are not in the root directory.
## 1.1.0
### Minor Changes
- [#128](https://github.com/changesets/action/pull/128) [`1937303`](https://github.com/changesets/action/commit/19373036c4bad4b0183344b6f2623a3b0e42da6c) Thanks [@dhruvdutt](https://github.com/dhruvdutt)! - Setup the git user in the local config instead of the global one.
* [#131](https://github.com/changesets/action/pull/131) [`d3db9ec`](https://github.com/changesets/action/commit/d3db9eceaf41d42c56d5370d504c86851627188f) Thanks [@jacklesliewise](https://github.com/jacklesliewise)! - Added `setupGitUser` option to enable or disable setting up a default git user
## 1.0.0
### Major Changes
- [#118](https://github.com/changesets/action/pull/118) [`05c863d`](https://github.com/changesets/action/commit/05c863d3f980125585016a593b5cb45b27d19c2c) Thanks [@Andarist](https://github.com/Andarist)! - From now on this action will be released using the Changesets-based workflow (using itself). Thanks to that we'll have a good release history. The users will be able to find specific versions of the action and will be able to track changes over time. It also improves the security as the build artifact will always get built in the CI environment, using a frozen lockfile.
+71 -31
View File
@@ -1,8 +1,6 @@
# Changesets Release Action # Changesets Release Action
> ⚠️ This branch has been frozen and deprecated. Please update your workflow to either use `@v1` or a specific commit SHA that is tagged. This action for [Changesets](https://github.com/atlassian/changesets) creates a pull request with all of the package versions updated and changelogs updated and when there are new changesets on [your configured `baseBranch`](https://github.com/changesets/changesets/blob/main/docs/config-file-options.md#basebranch-git-branch-name), the PR will be updated. When you're ready, you can merge the pull request and you can either publish the packages to npm manually or setup the action to do it for you.
This action for [Changesets](https://github.com/atlassian/changesets) creates a pull request with all of the package versions updated and changelogs updated and when there are new changesets on master, the PR will be updated. When you're ready, you can merge the pull request and you can either publish the packages to npm manually or setup the action to do it for you.
## Usage ## Usage
@@ -12,6 +10,9 @@ This action for [Changesets](https://github.com/atlassian/changesets) creates a
- version - The command to update version, edit CHANGELOG, read and delete changesets. Default to `changeset version` if not provided - version - The command to update version, edit CHANGELOG, read and delete changesets. Default to `changeset version` if not provided
- commit - The commit message to use. Default to `Version Packages` - commit - The commit message to use. Default to `Version Packages`
- title - The pull request title. Default to `Version Packages` - title - The pull request title. Default to `Version Packages`
- setupGitUser - Sets up the git user for commits as `"github-actions[bot]"`. Default to `true`
- createGithubReleases - A boolean value to indicate whether to create Github releases after `publish` or not. Default to `true`
- cwd - Changes node's `process.cwd()` if the project is not located on the root. Default to `process.cwd()`
### Outputs ### Outputs
@@ -30,7 +31,9 @@ name: Release
on: on:
push: push:
branches: branches:
- master - main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs: jobs:
release: release:
@@ -38,21 +41,18 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@master uses: actions/checkout@v3
with:
# This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
fetch-depth: 0
- name: Setup Node.js 12.x - name: Setup Node.js 16
uses: actions/setup-node@master uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 16
- name: Install Dependencies - name: Install Dependencies
run: yarn run: yarn
- name: Create Release Pull Request - name: Create Release Pull Request
uses: changesets/action@master uses: changesets/action@v1
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
``` ```
@@ -67,7 +67,9 @@ name: Release
on: on:
push: push:
branches: branches:
- master - main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs: jobs:
release: release:
@@ -75,22 +77,19 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@master uses: actions/checkout@v3
with:
# This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
fetch-depth: 0
- name: Setup Node.js 12.x - name: Setup Node.js 16.x
uses: actions/setup-node@master uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 16.x
- name: Install Dependencies - name: Install Dependencies
run: yarn run: yarn
- name: Create Release Pull Request or Publish to npm - name: Create Release Pull Request or Publish to npm
id: changesets id: changesets
uses: changesets/action@master uses: changesets/action@v1
with: with:
# This expects you to have a script called release which does a build for your packages and calls changeset publish # This expects you to have a script called release which does a build for your packages and calls changeset publish
publish: yarn release publish: yarn release
@@ -117,13 +116,54 @@ For example, you can add a step before running the Changesets GitHub Action:
- name: Creating .npmrc - name: Creating .npmrc
run: | run: |
cat << EOF > "$HOME/.npmrc" cat << EOF > "$HOME/.npmrc"
email=my@email.com
//registry.npmjs.org/:_authToken=$NPM_TOKEN //registry.npmjs.org/:_authToken=$NPM_TOKEN
EOF EOF
env: env:
NPM_TOKEN: ${{ secrets.NPM_TOKEN }} NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
``` ```
#### Custom Publishing
If you want to hook into when publishing should occur but have your own publishing functionality you can utilize the `hasChangesets` output.
Note that you might need to account for things already being published in your script because a commit without any new changesets can always land on your base branch after a successful publish. In such a case you need to figure out on your own how to skip over the actual publishing logic or handle errors gracefully as most package registries won't allow you to publish over already published version.
```yml
name: Release
on:
push:
branches:
- main
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v3
- name: Setup Node.js 16.x
uses: actions/setup-node@v3
with:
node-version: 16.x
- name: Install Dependencies
run: yarn
- name: Create Release Pull Request or Publish to npm
id: changesets
uses: changesets/action@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Publish
if: steps.changesets.outputs.hasChangesets == 'false'
# You can do something when a publish should happen.
run: yarn publish
```
#### With version script #### With version script
If you need to add additional logic to the version command, you can do so by using a version script. If you need to add additional logic to the version command, you can do so by using a version script.
@@ -136,7 +176,9 @@ name: Release
on: on:
push: push:
branches: branches:
- master - main
concurrency: ${{ github.workflow }}-${{ github.ref }}
jobs: jobs:
release: release:
@@ -144,20 +186,18 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@master uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Node.js 12.x - name: Setup Node.js 16.x
uses: actions/setup-node@master uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 16.x
- name: Install Dependencies - name: Install Dependencies
run: yarn run: yarn
- name: Create Release Pull Request - name: Create Release Pull Request
uses: changesets/action@master uses: changesets/action@v1
with: with:
# this expects you to have a npm script called version that runs some logic and then calls `changeset version`. # this expects you to have a npm script called version that runs some logic and then calls `changeset version`.
version: yarn version version: yarn version
@@ -170,7 +210,7 @@ jobs:
If you are using [Yarn Plug'n'Play](https://yarnpkg.com/features/pnp), you should use a custom `version` command so that the action can resolve the `changeset` CLI: If you are using [Yarn Plug'n'Play](https://yarnpkg.com/features/pnp), you should use a custom `version` command so that the action can resolve the `changeset` CLI:
```yaml ```yaml
- uses: changesets/action@master - uses: changesets/action@v1
with: with:
version: yarn changeset version version: yarn changeset version
... ...
+16 -1
View File
@@ -1,7 +1,7 @@
name: Changesets name: Changesets
description: A GitHub action to automate releases with Changesets description: A GitHub action to automate releases with Changesets
runs: runs:
using: "node12" using: "node16"
main: "dist/index.js" main: "dist/index.js"
inputs: inputs:
publish: publish:
@@ -10,6 +10,9 @@ inputs:
version: version:
description: "The command to update version, edit CHANGELOG, read and delete changesets. Default to `changeset version` if not provided" description: "The command to update version, edit CHANGELOG, read and delete changesets. Default to `changeset version` if not provided"
required: false required: false
cwd:
description: Sets the cwd for the node process. Default to `process.cwd()`
required: false
commit: commit:
description: | description: |
The commit message. Default to `Version Packages` The commit message. Default to `Version Packages`
@@ -17,12 +20,24 @@ inputs:
title: title:
description: The pull request title. Default to `Version Packages` description: The pull request title. Default to `Version Packages`
required: false required: false
setupGitUser:
description: Sets up the git user for commits as `"github-actions[bot]"`. Default to `true`
required: false
default: true
createGithubReleases:
description: "A boolean value to indicate whether to create Github releases after `publish` or not"
required: false
default: true
outputs: outputs:
published: published:
description: A boolean value to indicate whether a publishing is happened or not description: A boolean value to indicate whether a publishing is happened or not
publishedPackages: publishedPackages:
description: > description: >
A JSON array to present the published packages. The format is `[{"name": "@xx/xx", "version": "1.2.0"}, {"name": "@xx/xy", "version": "0.8.9"}]` A JSON array to present the published packages. The format is `[{"name": "@xx/xx", "version": "1.2.0"}, {"name": "@xx/xy", "version": "0.8.9"}]`
hasChangesets:
description: A boolean about whether there were changesets. Useful if you want to create your own publishing functionality.
pullRequestNumber:
description: The pull request number that was created or updated
branding: branding:
icon: "package" icon: "package"
color: "blue" color: "blue"
+437 -531
View File
File diff suppressed because one or more lines are too long
+24 -15
View File
@@ -1,31 +1,39 @@
{ {
"name": "@changesets/action", "name": "@changesets/action",
"version": "0.1.0", "version": "1.4.2",
"main": "dist/index.js", "main": "dist/index.js",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@changesets/cli": "^2.9.1", "@changesets/changelog-github": "^0.4.2",
"@changesets/write": "^0.1.3", "@changesets/cli": "^2.20.0",
"@changesets/write": "^0.1.6",
"fixturez": "^1.1.0", "fixturez": "^1.1.0",
"parcel": "^1.12.3", "parcel": "^1.12.3",
"prettier": "^2.0.5", "prettier": "^2.0.5",
"typescript": "^3.5.3" "typescript": "^5.0.4"
}, },
"scripts": { "scripts": {
"build": "parcel build ./src/index.ts --no-source-maps --target=node --bundle-node-modules", "build": "parcel build ./src/index.ts --no-source-maps --target=node --bundle-node-modules",
"test": "jest", "test": "jest",
"test:watch": "yarn test --watch" "test:watch": "yarn test --watch",
"changeset": "changeset",
"bump": "node ./scripts/bump.js",
"release": "node ./scripts/release.js"
},
"engines": {
"node": ">= 16"
}, },
"dependencies": { "dependencies": {
"@actions/core": "^1.6.0", "@actions/core": "^1.10.0",
"@actions/exec": "^1.0.4", "@actions/exec": "^1.1.1",
"@actions/github": "^4.0.0", "@actions/github": "^5.1.1",
"@babel/core": "^7.13.10", "@babel/core": "^7.13.10",
"@babel/preset-env": "^7.13.10", "@babel/preset-env": "^7.13.10",
"@babel/preset-typescript": "^7.13.0", "@babel/preset-typescript": "^7.13.0",
"@changesets/pre": "^1.0.4", "@changesets/pre": "^1.0.9",
"@changesets/read": "^0.4.6", "@changesets/read": "^0.5.3",
"@manypkg/get-packages": "^1.1.1", "@manypkg/get-packages": "^1.1.3",
"@octokit/plugin-throttling": "5.1.1",
"@types/fs-extra": "^8.0.0", "@types/fs-extra": "^8.0.0",
"@types/jest": "^24.0.18", "@types/jest": "^24.0.18",
"@types/node": "^12.7.1", "@types/node": "^12.7.1",
@@ -42,9 +50,10 @@
"unified": "^8.3.2" "unified": "^8.3.2"
}, },
"husky": { "husky": {
"hooks": { "hooks": {}
"pre-commit": "yarn build && git add dist/index.js"
}
}, },
"prettier": {} "prettier": {},
"resolutions": {
"**/@octokit/core": "4.2.0"
}
} }
+19
View File
@@ -0,0 +1,19 @@
const fs = require("fs");
const path = require("path");
const { exec } = require("@actions/exec");
process.chdir(path.join(__dirname, ".."));
(async () => {
await exec("changeset", ["version"]);
const releaseLine = `v${require("../package.json").version.split(".")[0]}`;
const readmePath = path.join(__dirname, "..", "README.md");
const content = fs.readFileSync(readmePath, "utf8");
const updatedContent = content.replace(
/changesets\/action@[^\s]+/g,
`changesets/action@${releaseLine}`
);
fs.writeFileSync(readmePath, updatedContent);
})();
+41
View File
@@ -0,0 +1,41 @@
const path = require("path");
const { exec, getExecOutput } = require("@actions/exec");
const { version } = require("../package.json");
const tag = `v${version}`;
const releaseLine = `v${version.split(".")[0]}`;
process.chdir(path.join(__dirname, ".."));
(async () => {
const { exitCode, stderr } = await getExecOutput(
`git`,
["ls-remote", "--exit-code", "origin", "--tags", `refs/tags/${tag}`],
{
ignoreReturnCode: true,
}
);
if (exitCode === 0) {
console.log(
`Action is not being published because version ${tag} is already published`
);
return;
}
if (exitCode !== 2) {
throw new Error(`git ls-remote exited with ${exitCode}:\n${stderr}`);
}
await exec("git", ["checkout", "--detach"]);
await exec("git", ["add", "--force", "dist"]);
await exec("git", ["commit", "-m", tag]);
await exec("changeset", ["tag"]);
await exec("git", [
"push",
"--force",
"--follow-tags",
"origin",
`HEAD:refs/heads/${releaseLine}`,
]);
})();
+45 -2
View File
@@ -6,6 +6,7 @@ Array [
"base": "some-branch", "base": "some-branch",
"body": "This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to some-branch, this PR will be updated. "body": "This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to some-branch, this PR will be updated.
# Releases # Releases
## simple-project-pkg-a@1.1.0 ## simple-project-pkg-a@1.1.0
@@ -15,10 +16,10 @@ Array [
### Patch Changes ### Patch Changes
- Updated dependencies [undefined] - Updated dependencies
- simple-project-pkg-b@1.1.0 - simple-project-pkg-b@1.1.0
## simple-project-pkg-b@1.1.0 ## simple-project-pkg-b@1.1.0
### Minor Changes ### Minor Changes
@@ -32,12 +33,53 @@ Array [
] ]
`; `;
exports[`version does not include any release information if a message with simplified release info exceeds size limit 1`] = `
Array [
Object {
"base": "some-branch",
"body": "This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to some-branch, this PR will be updated.
# Releases
> All release information have been omitted from this message, as the content exceeds the size limit.",
"head": "changeset-release/some-branch",
"owner": "changesets",
"repo": "action",
"title": "Version Packages",
},
]
`;
exports[`version does not include changelog entries if full message exceeds size limit 1`] = `
Array [
Object {
"base": "some-branch",
"body": "This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to some-branch, this PR will be updated.
# Releases
> The changelog information of each package has been omitted from this message, as the content exceeds the size limit.
## simple-project-pkg-a@1.1.0
",
"head": "changeset-release/some-branch",
"owner": "changesets",
"repo": "action",
"title": "Version Packages",
},
]
`;
exports[`version doesn't include ignored package that got a dependency update in the PR body 1`] = ` exports[`version doesn't include ignored package that got a dependency update in the PR body 1`] = `
Array [ Array [
Object { Object {
"base": "some-branch", "base": "some-branch",
"body": "This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to some-branch, this PR will be updated. "body": "This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to some-branch, this PR will be updated.
# Releases # Releases
## ignored-package-pkg-b@1.1.0 ## ignored-package-pkg-b@1.1.0
@@ -59,6 +101,7 @@ Array [
"base": "some-branch", "base": "some-branch",
"body": "This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to some-branch, this PR will be updated. "body": "This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing). If you're not ready to do a release yet, that's fine, whenever you add more changesets to some-branch, this PR will be updated.
# Releases # Releases
## simple-project-pkg-a@1.1.0 ## simple-project-pkg-a@1.1.0
+3 -6
View File
@@ -1,16 +1,13 @@
import { exec } from "@actions/exec"; import { exec, getExecOutput } from "@actions/exec";
import { execWithOutput } from "./utils";
export const setupUser = async () => { export const setupUser = async () => {
await exec("git", [ await exec("git", [
"config", "config",
"--global",
"user.name", "user.name",
`"github-actions[bot]"`, `"github-actions[bot]"`,
]); ]);
await exec("git", [ await exec("git", [
"config", "config",
"--global",
"user.email", "user.email",
`"github-actions[bot]@users.noreply.github.com"`, `"github-actions[bot]@users.noreply.github.com"`,
]); ]);
@@ -37,7 +34,7 @@ export const pushTags = async () => {
}; };
export const switchToMaybeExistingBranch = async (branch: string) => { export const switchToMaybeExistingBranch = async (branch: string) => {
let { stderr } = await execWithOutput("git", ["checkout", branch], { let { stderr } = await getExecOutput("git", ["checkout", branch], {
ignoreReturnCode: true, ignoreReturnCode: true,
}); });
let isCreatingBranch = !stderr let isCreatingBranch = !stderr
@@ -61,6 +58,6 @@ export const commitAll = async (message: string) => {
}; };
export const checkIfClean = async (): Promise<boolean> => { export const checkIfClean = async (): Promise<boolean> => {
const { stdout } = await execWithOutput("git", ["status", "--porcelain"]); const { stdout } = await getExecOutput("git", ["status", "--porcelain"]);
return !stdout.length; return !stdout.length;
}; };
+23 -7
View File
@@ -4,10 +4,6 @@ import * as gitUtils from "./gitUtils";
import { runPublish, runVersion } from "./run"; import { runPublish, runVersion } from "./run";
import readChangesetState from "./readChangesetState"; import readChangesetState from "./readChangesetState";
core.warning(
"The workflow file using `changesets/action` is currently using `@master` as the version. This branch has been frozen and deprecated. Please update your workflow to either use `@v1` or a specific commit SHA that is tagged."
);
const getOptionalInput = (name: string) => core.getInput(name) || undefined; const getOptionalInput = (name: string) => core.getInput(name) || undefined;
(async () => { (async () => {
@@ -18,8 +14,18 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
return; return;
} }
console.log("setting git user"); const inputCwd = core.getInput("cwd");
await gitUtils.setupUser(); if (inputCwd) {
console.log("changing directory to the one given as the input");
process.chdir(inputCwd);
}
let setupGitUser = core.getBooleanInput("setupGitUser");
if (setupGitUser) {
console.log("setting git user");
await gitUtils.setupUser();
}
console.log("setting GitHub credentials"); console.log("setting GitHub credentials");
await fs.writeFile( await fs.writeFile(
@@ -31,6 +37,9 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
let publishScript = core.getInput("publish"); let publishScript = core.getInput("publish");
let hasChangesets = changesets.length !== 0; let hasChangesets = changesets.length !== 0;
const hasNonEmptyChangesets = changesets.some(
(changeset) => changeset.releases.length > 0
);
let hasPublishScript = !!publishScript; let hasPublishScript = !!publishScript;
core.setOutput("published", "false"); core.setOutput("published", "false");
@@ -78,6 +87,7 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
const result = await runPublish({ const result = await runPublish({
script: publishScript, script: publishScript,
githubToken, githubToken,
createGithubReleases: core.getBooleanInput("createGithubReleases"),
}); });
if (result.published) { if (result.published) {
@@ -89,14 +99,20 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
} }
return; return;
} }
case hasChangesets && !hasNonEmptyChangesets:
console.log("All changesets are empty; not creating PR");
return;
case hasChangesets: case hasChangesets:
await runVersion({ const { pullRequestNumber } = await runVersion({
script: getOptionalInput("version"), script: getOptionalInput("version"),
githubToken, githubToken,
prTitle: getOptionalInput("title"), prTitle: getOptionalInput("title"),
commitMessage: getOptionalInput("commit"), commitMessage: getOptionalInput("commit"),
hasPublishScript, hasPublishScript,
}); });
core.setOutput("pullRequestNumber", String(pullRequestNumber));
return; return;
} }
})().catch((err) => { })().catch((err) => {
+133 -1
View File
@@ -30,7 +30,9 @@ let mockedGithubMethods = {
createRelease: jest.fn(), createRelease: jest.fn(),
}, },
}; };
(github.getOctokit as any).mockImplementation(() => mockedGithubMethods); (github.getOctokit as any).mockImplementation(() => ({
rest: mockedGithubMethods,
}));
let f = fixturez(__dirname); let f = fixturez(__dirname);
@@ -57,6 +59,10 @@ describe("version", () => {
() => ({ data: { items: [] } }) () => ({ data: { items: [] } })
); );
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 },
}));
await writeChangesets( await writeChangesets(
[ [
{ {
@@ -92,6 +98,10 @@ describe("version", () => {
() => ({ data: { items: [] } }) () => ({ data: { items: [] } })
); );
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 },
}));
await writeChangesets( await writeChangesets(
[ [
{ {
@@ -123,6 +133,10 @@ describe("version", () => {
() => ({ data: { items: [] } }) () => ({ data: { items: [] } })
); );
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 },
}));
await writeChangesets( await writeChangesets(
[ [
{ {
@@ -145,4 +159,122 @@ describe("version", () => {
expect(mockedGithubMethods.pulls.create.mock.calls[0]).toMatchSnapshot(); expect(mockedGithubMethods.pulls.create.mock.calls[0]).toMatchSnapshot();
}); });
it("does not include changelog entries if full message exceeds size limit", async () => {
let cwd = f.copy("simple-project");
linkNodeModules(cwd);
mockedGithubMethods.search.issuesAndPullRequests.mockImplementationOnce(
() => ({ data: { items: [] } })
);
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 },
}));
await writeChangesets(
[
{
releases: [
{
name: "simple-project-pkg-a",
type: "minor",
},
],
summary: `# Non manus superum
## Nec cornibus aequa numinis multo onerosior adde
Lorem markdownum undas consumpserat malas, nec est lupus; memorant gentisque ab
limine auctore. Eatque et promptu deficit, quam videtur aequa est **faciat**,
locus. Potentia deus habebat pia quam qui coniuge frater, tibi habent fertque
viribus. E et cognoscere arcus, lacus aut sic pro crimina fuit tum **auxilium**
dictis, qua, in.
In modo. Nomen illa membra.
> Corpora gratissima parens montibus tum coeperat qua remulus caelum Helenamque?
> Non poenae modulatur Amathunta in concita superi, procerum pariter rapto cornu
> munera. Perrhaebum parvo manus contingere, morari, spes per totiens ut
> dividite proculcat facit, visa.
Adspicit sequitur diffamatamque superi Phoebo qua quin lammina utque: per? Exit
decus aut hac inpia, seducta mirantia extremo. Vidi pedes vetus. Saturnius
fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
`,
},
],
cwd
);
await runVersion({
githubToken: "@@GITHUB_TOKEN",
cwd,
prBodyMaxCharacters: 1000,
});
expect(mockedGithubMethods.pulls.create.mock.calls[0]).toMatchSnapshot();
expect(mockedGithubMethods.pulls.create.mock.calls[0][0].body).toMatch(
/The changelog information of each package has been omitted from this message/
);
});
it("does not include any release information if a message with simplified release info exceeds size limit", async () => {
let cwd = f.copy("simple-project");
linkNodeModules(cwd);
mockedGithubMethods.search.issuesAndPullRequests.mockImplementationOnce(
() => ({ data: { items: [] } })
);
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 },
}));
await writeChangesets(
[
{
releases: [
{
name: "simple-project-pkg-a",
type: "minor",
},
],
summary: `# Non manus superum
## Nec cornibus aequa numinis multo onerosior adde
Lorem markdownum undas consumpserat malas, nec est lupus; memorant gentisque ab
limine auctore. Eatque et promptu deficit, quam videtur aequa est **faciat**,
locus. Potentia deus habebat pia quam qui coniuge frater, tibi habent fertque
viribus. E et cognoscere arcus, lacus aut sic pro crimina fuit tum **auxilium**
dictis, qua, in.
In modo. Nomen illa membra.
> Corpora gratissima parens montibus tum coeperat qua remulus caelum Helenamque?
> Non poenae modulatur Amathunta in concita superi, procerum pariter rapto cornu
> munera. Perrhaebum parvo manus contingere, morari, spes per totiens ut
> dividite proculcat facit, visa.
Adspicit sequitur diffamatamque superi Phoebo qua quin lammina utque: per? Exit
decus aut hac inpia, seducta mirantia extremo. Vidi pedes vetus. Saturnius
fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
`,
},
],
cwd
);
await runVersion({
githubToken: "@@GITHUB_TOKEN",
cwd,
prBodyMaxCharacters: 500,
});
expect(mockedGithubMethods.pulls.create.mock.calls[0]).toMatchSnapshot();
expect(mockedGithubMethods.pulls.create.mock.calls[0][0].body).toMatch(
/All release information have been omitted from this message, as the content exceeds the size limit/
);
});
}); });
+186 -74
View File
@@ -1,12 +1,13 @@
import { exec } from "@actions/exec"; import { exec, getExecOutput } from "@actions/exec";
import { GitHub, getOctokitOptions } from "@actions/github/lib/utils";
import * as github from "@actions/github"; import * as github from "@actions/github";
import fs from "fs-extra"; import fs from "fs-extra";
import { getPackages, Package } from "@manypkg/get-packages"; import { getPackages, Package } from "@manypkg/get-packages";
import path from "path"; import path from "path";
import * as semver from "semver"; import * as semver from "semver";
import { PreState } from "@changesets/types";
import { import {
getChangelogEntry, getChangelogEntry,
execWithOutput,
getChangedPackages, getChangedPackages,
sortTheThings, sortTheThings,
getVersionsByDirectory, getVersionsByDirectory,
@@ -14,6 +15,15 @@ import {
import * as gitUtils from "./gitUtils"; import * as gitUtils from "./gitUtils";
import readChangesetState from "./readChangesetState"; import readChangesetState from "./readChangesetState";
import resolveFrom from "resolve-from"; import resolveFrom from "resolve-from";
import { throttling } from "@octokit/plugin-throttling";
// temporary workaround for https://github.com/octokit/plugin-throttling.js/pull/590
import type {} from "@octokit/plugin-throttling/dist-types/types.d";
// GitHub Issues/PRs messages have a max size limit on the
// message body payload.
// `body is too long (maximum is 65536 characters)`.
// To avoid that, we ensure to cap the message to 60k chars.
const MAX_CHARACTERS_PER_MESSAGE = 60000;
const createRelease = async ( const createRelease = async (
octokit: ReturnType<typeof github.getOctokit>, octokit: ReturnType<typeof github.getOctokit>,
@@ -33,7 +43,7 @@ const createRelease = async (
); );
} }
await octokit.repos.createRelease({ await octokit.rest.repos.createRelease({
name: tagName, name: tagName,
tag_name: tagName, tag_name: tagName,
body: changelogEntry.content, body: changelogEntry.content,
@@ -51,6 +61,7 @@ const createRelease = async (
type PublishOptions = { type PublishOptions = {
script: string; script: string;
githubToken: string; githubToken: string;
createGithubReleases: boolean;
cwd?: string; cwd?: string;
}; };
@@ -68,12 +79,44 @@ type PublishResult =
export async function runPublish({ export async function runPublish({
script, script,
githubToken, githubToken,
createGithubReleases,
cwd = process.cwd(), cwd = process.cwd(),
}: PublishOptions): Promise<PublishResult> { }: PublishOptions): Promise<PublishResult> {
let octokit = github.getOctokit(githubToken); const octokit = new (GitHub.plugin(throttling))(
getOctokitOptions(githubToken, {
throttle: {
onRateLimit: (retryAfter, options: any, octokit, retryCount) => {
console.log(
`Request quota exhausted for request ${options.method} ${options.url}`
);
if (retryCount <= 2) {
console.log(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
onSecondaryRateLimit: (
retryAfter,
options: any,
octokit,
retryCount
) => {
console.log(
`SecondaryRateLimit detected for request ${options.method} ${options.url}`
);
if (retryCount <= 2) {
console.log(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
},
})
);
let [publishCommand, ...publishArgs] = script.split(/\s+/); let [publishCommand, ...publishArgs] = script.split(/\s+/);
let changesetPublishOutput = await execWithOutput( let changesetPublishOutput = await getExecOutput(
publishCommand, publishCommand,
publishArgs, publishArgs,
{ cwd } { cwd }
@@ -104,14 +147,16 @@ export async function runPublish({
releasedPackages.push(pkg); releasedPackages.push(pkg);
} }
await Promise.all( if (createGithubReleases) {
releasedPackages.map((pkg) => await Promise.all(
createRelease(octokit, { releasedPackages.map((pkg) =>
pkg, createRelease(octokit, {
tagName: `${pkg.packageJson.name}@${pkg.packageJson.version}`, pkg,
}) tagName: `${pkg.packageJson.name}@${pkg.packageJson.version}`,
) })
); )
);
}
} else { } else {
if (packages.length === 0) { if (packages.length === 0) {
throw new Error( throw new Error(
@@ -127,10 +172,12 @@ export async function runPublish({
if (match) { if (match) {
releasedPackages.push(pkg); releasedPackages.push(pkg);
await createRelease(octokit, { if (createGithubReleases) {
pkg, await createRelease(octokit, {
tagName: `v${pkg.packageJson.version}`, pkg,
}); tagName: `v${pkg.packageJson.version}`,
});
}
break; break;
} }
} }
@@ -162,6 +209,75 @@ const requireChangesetsCliPkgJson = (cwd: string) => {
} }
}; };
type GetMessageOptions = {
hasPublishScript: boolean;
branch: string;
changedPackagesInfo: {
highestLevel: number;
private: boolean;
content: string;
header: string;
}[];
prBodyMaxCharacters: number;
preState?: PreState;
};
export async function getVersionPrBody({
hasPublishScript,
preState,
changedPackagesInfo,
prBodyMaxCharacters,
branch,
}: GetMessageOptions) {
let messageHeader = `This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and ${
hasPublishScript
? `the packages will be published to npm automatically`
: `publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing)`
}. If you're not ready to do a release yet, that's fine, whenever you add more changesets to ${branch}, this PR will be updated.
`;
let messagePrestate = !!preState
? `⚠️⚠️⚠️⚠️⚠️⚠️
\`${branch}\` is currently in **pre mode** so this branch has prereleases rather than normal releases. If you want to exit prereleases, run \`changeset pre exit\` on \`${branch}\`.
⚠️⚠️⚠️⚠️⚠️⚠️
`
: "";
let messageReleasesHeading = `# Releases`;
let fullMessage = [
messageHeader,
messagePrestate,
messageReleasesHeading,
...changedPackagesInfo.map((info) => `${info.header}\n\n${info.content}`),
].join("\n");
// Check that the message does not exceed the size limit.
// If not, omit the changelog entries of each package.
if (fullMessage.length > prBodyMaxCharacters) {
fullMessage = [
messageHeader,
messagePrestate,
messageReleasesHeading,
`\n> The changelog information of each package has been omitted from this message, as the content exceeds the size limit.\n`,
...changedPackagesInfo.map((info) => `${info.header}\n\n`),
].join("\n");
}
// Check (again) that the message is within the size limit.
// If not, omit all release content this time.
if (fullMessage.length > prBodyMaxCharacters) {
fullMessage = [
messageHeader,
messagePrestate,
messageReleasesHeading,
`\n> All release information have been omitted from this message, as the content exceeds the size limit.`,
].join("\n");
}
return fullMessage;
}
type VersionOptions = { type VersionOptions = {
script?: string; script?: string;
githubToken: string; githubToken: string;
@@ -169,6 +285,11 @@ type VersionOptions = {
prTitle?: string; prTitle?: string;
commitMessage?: string; commitMessage?: string;
hasPublishScript?: boolean; hasPublishScript?: boolean;
prBodyMaxCharacters?: number;
};
type RunVersionResult = {
pullRequestNumber: number;
}; };
export async function runVersion({ export async function runVersion({
@@ -178,7 +299,8 @@ export async function runVersion({
prTitle = "Version Packages", prTitle = "Version Packages",
commitMessage = "Version Packages", commitMessage = "Version Packages",
hasPublishScript = false, hasPublishScript = false,
}: VersionOptions) { prBodyMaxCharacters = MAX_CHARACTERS_PER_MESSAGE,
}: VersionOptions): Promise<RunVersionResult> {
let repo = `${github.context.repo.owner}/${github.context.repo.repo}`; let repo = `${github.context.repo.owner}/${github.context.repo.repo}`;
let branch = github.context.ref.replace("refs/heads/", ""); let branch = github.context.ref.replace("refs/heads/", "");
let versionBranch = `changeset-release/${branch}`; let versionBranch = `changeset-release/${branch}`;
@@ -203,60 +325,27 @@ export async function runVersion({
}); });
} }
let searchQuery = `repo:${repo}+state:open+head:${versionBranch}+base:${branch}`; let searchQuery = `repo:${repo}+state:open+head:${versionBranch}+base:${branch}+is:pull-request`;
let searchResultPromise = octokit.search.issuesAndPullRequests({ let searchResultPromise = octokit.rest.search.issuesAndPullRequests({
q: searchQuery, q: searchQuery,
}); });
let changedPackages = await getChangedPackages(cwd, versionsByDirectory); let changedPackages = await getChangedPackages(cwd, versionsByDirectory);
let changedPackagesInfoPromises = Promise.all(
changedPackages.map(async (pkg) => {
let changelogContents = await fs.readFile(
path.join(pkg.dir, "CHANGELOG.md"),
"utf8"
);
let prBodyPromise = (async () => { let entry = getChangelogEntry(changelogContents, pkg.packageJson.version);
return ( return {
`This PR was opened by the [Changesets release](https://github.com/changesets/action) GitHub action. When you're ready to do a release, you can merge this and ${ highestLevel: entry.highestLevel,
hasPublishScript private: !!pkg.packageJson.private,
? `the packages will be published to npm automatically` content: entry.content,
: `publish to npm yourself or [setup this action to publish automatically](https://github.com/changesets/action#with-publishing)` header: `## ${pkg.packageJson.name}@${pkg.packageJson.version}`,
}. If you're not ready to do a release yet, that's fine, whenever you add more changesets to ${branch}, this PR will be updated. };
${ })
!!preState );
? `
⚠️⚠️⚠️⚠️⚠️⚠️
\`${branch}\` is currently in **pre mode** so this branch has prereleases rather than normal releases. If you want to exit prereleases, run \`changeset pre exit\` on \`${branch}\`.
⚠️⚠️⚠️⚠️⚠️⚠️
`
: ""
}
# Releases
` +
(
await Promise.all(
changedPackages.map(async (pkg) => {
let changelogContents = await fs.readFile(
path.join(pkg.dir, "CHANGELOG.md"),
"utf8"
);
let entry = getChangelogEntry(
changelogContents,
pkg.packageJson.version
);
return {
highestLevel: entry.highestLevel,
private: !!pkg.packageJson.private,
content:
`## ${pkg.packageJson.name}@${pkg.packageJson.version}\n\n` +
entry.content,
};
})
)
)
.filter((x) => x)
.sort(sortTheThings)
.map((x) => x.content)
.join("\n ")
);
})();
const finalPrTitle = `${prTitle}${!!preState ? ` (${preState.tag})` : ""}`; const finalPrTitle = `${prTitle}${!!preState ? ` (${preState.tag})` : ""}`;
@@ -272,22 +361,45 @@ ${
let searchResult = await searchResultPromise; let searchResult = await searchResultPromise;
console.log(JSON.stringify(searchResult.data, null, 2)); console.log(JSON.stringify(searchResult.data, null, 2));
const changedPackagesInfo = (await changedPackagesInfoPromises)
.filter((x) => x)
.sort(sortTheThings);
let prBody = await getVersionPrBody({
hasPublishScript,
preState,
branch,
changedPackagesInfo,
prBodyMaxCharacters,
});
if (searchResult.data.items.length === 0) { if (searchResult.data.items.length === 0) {
console.log("creating pull request"); console.log("creating pull request");
await octokit.pulls.create({ const { data: newPullRequest } = await octokit.rest.pulls.create({
base: branch, base: branch,
head: versionBranch, head: versionBranch,
title: finalPrTitle, title: finalPrTitle,
body: await prBodyPromise, body: prBody,
...github.context.repo, ...github.context.repo,
}); });
return {
pullRequestNumber: newPullRequest.number,
};
} else { } else {
octokit.pulls.update({ const [pullRequest] = searchResult.data.items;
pull_number: searchResult.data.items[0].number,
console.log(`updating found pull request #${pullRequest.number}`);
await octokit.rest.pulls.update({
pull_number: pullRequest.number,
title: finalPrTitle, title: finalPrTitle,
body: await prBodyPromise, body: prBody,
...github.context.repo, ...github.context.repo,
}); });
console.log("pull request found");
return {
pullRequestNumber: pullRequest.number,
};
} }
} }
-26
View File
@@ -87,32 +87,6 @@ export function getChangelogEntry(changelog: string, version: string) {
}; };
} }
export async function execWithOutput(
command: string,
args?: string[],
options?: { ignoreReturnCode?: boolean; cwd?: string }
) {
let myOutput = "";
let myError = "";
return {
code: await exec(command, args, {
listeners: {
stdout: (data: Buffer) => {
myOutput += data.toString();
},
stderr: (data: Buffer) => {
myError += data.toString();
},
},
...options,
}),
stdout: myOutput,
stderr: myError,
};
}
export function sortTheThings( export function sortTheThings(
a: { private: boolean; highestLevel: number }, a: { private: boolean; highestLevel: number },
b: { private: boolean; highestLevel: number } b: { private: boolean; highestLevel: number }
+460 -471
View File
File diff suppressed because it is too large Load Diff