Compare commits

..
41 Commits
Author SHA1 Message Date
github-actions[bot] 746c25e23c v1.5.0 2025-05-05 08:17:03 +00:00
github-actions[bot] 5f15b43b42 Version Packages (#463)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-05-05 10:16:36 +02:00
Sam LanningandMateusz Burzyński 207dc3da2d Introduce an option to use the GitHub API to commit changes, for GPG (#391)
* Create tags on GitHub using API

To allow for signed tags to be created,
rather than use the git CLI to push tags,
manually push each tag using the GitHub API,
which will sign the tag using the built-in GitHub GPG key.

* Use ghcommit to push changes

To allow for all commits to be signed,
use the GitHub API to push changes.

* Add changeset version

* Allow tag publish to fail, assume it was manually published

* Add to changeset

* Update @s0/ghcommit

* Update ghcommit to fix missing ref bug

* Make using GitHub API Optional

Change this to a minor version bump,
with a new feature that allows for using the
GitHub API to create tags and commits.

* Use a strategy pattern for GitHub API vs CLI usage

* refactor git interactions

* fix mock thing

* usechangesets pkg

* switch to `commitMode`

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2025-05-02 15:32:14 +02:00
Changwan bd5d1d2a62 Remove unused variable (#460)
* unused variable

* double negative var

* Revert "double negative var"

This reverts commit 13cd17e381.
2025-04-22 07:22:46 +02:00
github-actions[bot] ff7179cf12 Version Packages (#449)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2025-03-10 11:53:19 +01:00
Bjorn Lu 8b16070fe3 Use full git email for github-actions bot (#448)
* Use full git email for github-actions bot

* Create fluffy-clocks-knock.md
2025-03-10 11:42:00 +01:00
Zachary Cowan 07dc948a9f Add Dependabot config file (#432) 2024-12-14 14:40:37 +01:00
github-actions[bot]andgithub-actions[bot] 31ff97e8ac Version Packages (#416)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-10-14 19:12:43 +02:00
Ben McCann 57ab80c611 Improve error message when attempting to publish without publish script defined (#415)
* Improve error message when attempting to publish without publish script defined

* Update src/index.ts

* Update src/index.ts
2024-10-14 18:44:02 +02:00
github-actions[bot]andgithub-actions[bot] 50750fa876 Version Packages (#394)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-08-26 19:01:26 +02:00
48ab0d2f2e Switch to pull request list API instead of search (#393)
* Switch to pull request list API instead of search

To reduce the amount of rate-limit that we use,
switch to a cheaper API for determining whether
an existing PR exists for a given branch.

* Ensure PR remains open when updating description

* Update .changeset/clean-bees-count.md

Co-authored-by: willo-icon <161356817+willo-icon@users.noreply.github.com>

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
Co-authored-by: willo-icon <161356817+willo-icon@users.noreply.github.com>
2024-08-26 18:38:29 +02:00
Thomas Beer 89b41e6c69 Fix typos in README.md (#384) 2024-07-30 15:02:29 +02:00
Trivikram Kamat c62ef9792f Use latest versions of checkout and setup-node actions (#359) 2024-03-26 21:11:40 +01:00
github-actions[bot]andgithub-actions[bot] 63ffd93140 Version Packages (#357)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-03-19 12:11:08 +10:00
Ernesto García f2660aa7e7 Feature: Allow custom branch (#255) 2024-03-19 08:57:05 +10:00
github-actions[bot]andgithub-actions[bot] e245972e63 Version Packages (#351)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-02-16 11:37:28 +01:00
m-shakaandMateusz Burzyński 9385be9e75 Bump node.js to 20 on the CI (#350)
* chore: bump nodejs from 16 to 20

* Create kind-sheep-grab.md

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2024-02-16 11:35:19 +01:00
Mateusz Burzyński 2bb9bcbd6b Update semver package (#307) 2023-06-23 13:19:12 +02:00
github-actions[bot]andgithub-actions[bot] cbef32198f Version Packages (#305)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-06-23 12:57:14 +02:00
Mark OmarovandMateusz Burzyński eb19e25e77 Updated a few dependencies to patch the security vulnerabilities that were reported for their older versions (#282)
* fix: patch vulnerabilities

* chore: add changeset

* fix: dependabot reported vulnerabilities

* Cleanup resolutions

* tweak changeset

* Update .changeset/wicked-apes-watch.md

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2023-06-23 12:55:59 +02:00
Mateusz Burzyński 49f9bd750b Upgrade @octokit/plugin-throttling and fix type errors (#294) 2023-05-14 16:56:41 +02:00
github-actions[bot]andgithub-actions[bot] 28271921f0 Version Packages (#292)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-05-10 07:26:55 +02:00
Mateusz Burzyński ba5ea93f34 Replace Parcel with ncc 2023-05-09 17:44:11 +02:00
Mateusz Burzyński 4e64830a00 Update Jest 2023-05-09 17:32:35 +02:00
Viktor VarlandandMateusz Burzyński db8a1099bc Wire up @octokit/plugin-throttling with all GitHub Octokit instances (#291)
* fix: use throttling-wired octokit everywhere

* test: fix run.test.ts

* Update .changeset/new-worms-knock.md

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2023-05-09 17:21:08 +02:00
github-actions[bot]andgithub-actions[bot] 4cb1c2fbde Version Packages (#290)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2023-05-09 06:47:54 +02:00
Viktor VarlandandMateusz Burzyński 8b2818674d Use logging provided by @actions/core (#289)
* chore: migrate to logging from @actions/core

* Update src/index.ts

* Update .changeset/blue-hornets-marry.md

---------

Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2023-05-08 23:42:00 +02: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
20 changed files with 3613 additions and 8403 deletions
+11
View File
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "npm" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
+4 -4
View File
@@ -10,12 +10,12 @@ jobs:
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@v2 uses: actions/checkout@v4
- name: Use Node.js 14 - name: Use Node.js 20
uses: actions/setup-node@v1 uses: actions/setup-node@v4
with: with:
node-version: 14.x node-version: 20.x
- name: Install Dependencies - name: Install Dependencies
run: yarn --frozen-lockfile run: yarn --frozen-lockfile
+4 -4
View File
@@ -12,12 +12,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@v2 uses: actions/checkout@v4
- name: Use Node.js 14 - name: Use Node.js 20
uses: actions/setup-node@v1 uses: actions/setup-node@v4
with: with:
node-version: 14.x node-version: 20.x
- name: Install Dependencies - name: Install Dependencies
run: yarn --frozen-lockfile run: yarn --frozen-lockfile
+87
View File
@@ -1,5 +1,92 @@
# @changesets/action # @changesets/action
## 1.5.0
### Minor Changes
- [#391](https://github.com/changesets/action/pull/391) [`207dc3d`](https://github.com/changesets/action/commit/207dc3da2d1907cae0454ce123935401332be72b) Thanks [@s0](https://github.com/s0)! - Introduce a new input `commitMode` that allows using the GitHub API for pushing tags and commits instead of the Git CLI.
When used with `"github-api"` value all tags and commits will be attributed to the user whose GITHUB_TOKEN is used, and also signed using GitHub's internal GPG key.
## 1.4.10
### Patch Changes
- [#448](https://github.com/changesets/action/pull/448) [`8b16070`](https://github.com/changesets/action/commit/8b16070fe386eed3456c83eeed9460160432cf26) Thanks [@bluwy](https://github.com/bluwy)! - Use full git email (`41898282+github-actions[bot]@users.noreply.github.com`) for github-actions bot when making commits
## 1.4.9
### Patch Changes
- [#415](https://github.com/changesets/action/pull/415) [`57ab80c`](https://github.com/changesets/action/commit/57ab80c61104c270bebc125910ae32da3a5aca46) Thanks [@benmccann](https://github.com/benmccann)! - Improve error message when attempting to publish without publish script defined
## 1.4.8
### Patch Changes
- [#393](https://github.com/changesets/action/pull/393) [`48ab0d2`](https://github.com/changesets/action/commit/48ab0d2f2e77ae169182d022591ef5c18c931ff2) Thanks [@s0](https://github.com/s0)! - Ensure the PR remains open when updated
- [#393](https://github.com/changesets/action/pull/393) [`48ab0d2`](https://github.com/changesets/action/commit/48ab0d2f2e77ae169182d022591ef5c18c931ff2) Thanks [@s0](https://github.com/s0)! - Switch to cheaper API for querying existing PRs
## 1.4.7
### Patch Changes
- [#255](https://github.com/changesets/action/pull/255) [`f2660aa`](https://github.com/changesets/action/commit/f2660aa7e78365f53dbeb4cfa774c1499ec6483a) Thanks [@ernestognw](https://github.com/ernestognw)! - Allow customize PR `branch` field
## 1.4.6
### Patch Changes
- [#350](https://github.com/changesets/action/pull/350) [`9385be9`](https://github.com/changesets/action/commit/9385be9e757839189ea5ee63ec4e3caa8a6ca71b) Thanks [@m-shaka](https://github.com/m-shaka)! - Bump the used node.js from 16 to 20
## 1.4.5
### Patch Changes
- [#282](https://github.com/changesets/action/pull/282) [`eb19e25`](https://github.com/changesets/action/commit/eb19e25e7797cf33dc2de4caa071e85a8057a0f0) Thanks [@mark-omarov](https://github.com/mark-omarov)! - Updated a few dependencies to patch the security vulnerabilities that were reported for their older versions.
## 1.4.4
### Patch Changes
- [#291](https://github.com/changesets/action/pull/291) [`db8a109`](https://github.com/changesets/action/commit/db8a1099bc0ba1dd6f46a5b9df4212e4f69e78c9) Thanks [@varl](https://github.com/varl)! - Wire up [`@octokit/plugin-throttling`](https://github.com/octokit/plugin-throttling.js) with all GitHub Octokit instances
## 1.4.3
### Patch Changes
- [#289](https://github.com/changesets/action/pull/289) [`8b28186`](https://github.com/changesets/action/commit/8b2818674de86a7fc69aebb9ed6b486ee32eb96e) Thanks [@varl](https://github.com/varl)! - Use logging provided by `@actions/core`
## 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 ## 1.3.0
### Minor Changes ### Minor Changes
+25 -24
View File
@@ -1,6 +1,6 @@
# Changesets Release Action # Changesets Release Action
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. This action for [Changesets](https://github.com/changesets/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.
## Usage ## Usage
@@ -11,11 +11,13 @@ This action for [Changesets](https://github.com/atlassian/changesets) creates a
- 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` - 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`
- commitMode - Specifies the commit mode. Use `"git-cli"` to push changes using the Git CLI, or `"github-api"` to push changes via the GitHub API. When using `"github-api"`, all commits and tags are GPG-signed and attributed to the user or app who owns the `GITHUB_TOKEN`. Default to `git-cli`.
- cwd - Changes node's `process.cwd()` if the project is not located on the root. Default to `process.cwd()` - cwd - Changes node's `process.cwd()` if the project is not located on the root. Default to `process.cwd()`
### Outputs ### Outputs
- published - A boolean value to indicate whether a publishing is happened or not - published - A boolean value to indicate whether a publishing has happened or not
- publishedPackages - 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"}]` - publishedPackages - 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"}]`
### Example workflow: ### Example workflow:
@@ -30,7 +32,7 @@ name: Release
on: on:
push: push:
branches: branches:
- master - main
concurrency: ${{ github.workflow }}-${{ github.ref }} concurrency: ${{ github.workflow }}-${{ github.ref }}
@@ -40,12 +42,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@v2 uses: actions/checkout@v3
- name: Setup Node.js 12.x - name: Setup Node.js 20
uses: actions/setup-node@v2 uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 20
- name: Install Dependencies - name: Install Dependencies
run: yarn run: yarn
@@ -66,7 +68,7 @@ name: Release
on: on:
push: push:
branches: branches:
- master - main
concurrency: ${{ github.workflow }}-${{ github.ref }} concurrency: ${{ github.workflow }}-${{ github.ref }}
@@ -76,12 +78,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@v2 uses: actions/checkout@v3
- name: Setup Node.js 12.x - name: Setup Node.js 20.x
uses: actions/setup-node@v2 uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 20.x
- name: Install Dependencies - name: Install Dependencies
run: yarn run: yarn
@@ -115,7 +117,6 @@ 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:
@@ -124,7 +125,7 @@ For example, you can add a step before running the Changesets GitHub Action:
#### Custom Publishing #### Custom Publishing
If you want to hook into when publishing should occur but have your own publishing functionality you can utilize the `hasChangesets` output. 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. 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.
@@ -134,7 +135,7 @@ name: Release
on: on:
push: push:
branches: branches:
- master - main
jobs: jobs:
release: release:
@@ -142,12 +143,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@v2 uses: actions/checkout@v3
- name: Setup Node.js 12.x - name: Setup Node.js 20.x
uses: actions/setup-node@v2 uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 20.x
- name: Install Dependencies - name: Install Dependencies
run: yarn run: yarn
@@ -176,7 +177,7 @@ name: Release
on: on:
push: push:
branches: branches:
- master - main
concurrency: ${{ github.workflow }}-${{ github.ref }} concurrency: ${{ github.workflow }}-${{ github.ref }}
@@ -186,12 +187,12 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout Repo - name: Checkout Repo
uses: actions/checkout@v2 uses: actions/checkout@v3
- name: Setup Node.js 12.x - name: Setup Node.js 20.x
uses: actions/setup-node@v2 uses: actions/setup-node@v3
with: with:
node-version: 12.x node-version: 20.x
- name: Install Dependencies - name: Install Dependencies
run: yarn run: yarn
+12 -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: "node20"
main: "dist/index.js" main: "dist/index.js"
inputs: inputs:
publish: publish:
@@ -28,6 +28,17 @@ inputs:
description: "A boolean value to indicate whether to create Github releases after `publish` or not" description: "A boolean value to indicate whether to create Github releases after `publish` or not"
required: false required: false
default: true default: true
commitMode:
description: >
An enum to specify the commit mode. Use "git-cli" to push changes using the Git CLI,
or "github-api" to push changes via the GitHub API. When using "github-api",
all commits and tags are signed using GitHub's GPG key and attributed to the user
or app who owns the GITHUB_TOKEN.
required: false
default: "git-cli"
branch:
description: Sets the branch in which the action will run. Default to `github.ref_name` if not provided
required: false
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
+67 -921
View File
File diff suppressed because one or more lines are too long
+30 -19
View File
@@ -1,52 +1,63 @@
{ {
"name": "@changesets/action", "name": "@changesets/action",
"version": "1.3.0", "version": "1.5.0",
"main": "dist/index.js", "main": "dist/index.js",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@babel/core": "^7.13.10",
"@babel/preset-env": "^7.13.10",
"@babel/preset-typescript": "^7.13.0",
"@changesets/changelog-github": "^0.4.2", "@changesets/changelog-github": "^0.4.2",
"@changesets/cli": "^2.20.0", "@changesets/cli": "^2.20.0",
"@changesets/write": "^0.1.6", "@changesets/write": "^0.1.6",
"@types/fs-extra": "^8.0.0",
"@types/jest": "^29.5.1",
"@types/node": "^20.11.17",
"@types/semver": "^7.5.0",
"@vercel/ncc": "^0.36.1",
"babel-jest": "^29.5.0",
"fixturez": "^1.1.0", "fixturez": "^1.1.0",
"parcel": "^1.12.3", "husky": "^3.0.3",
"jest": "^29.5.0",
"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": "ncc build src/index.ts -o dist --transpile-only --minify",
"test": "jest", "test": "jest",
"test:watch": "yarn test --watch", "test:watch": "yarn test --watch",
"changeset": "changeset", "changeset": "changeset",
"bump": "node ./scripts/bump.js", "bump": "node ./scripts/bump.js",
"release": "node ./scripts/release.js" "release": "node ./scripts/release.js"
}, },
"engines": {
"node": ">= 20"
},
"dependencies": { "dependencies": {
"@actions/core": "^1.3.0", "@actions/core": "^1.10.0",
"@actions/exec": "^1.1.0", "@actions/exec": "^1.1.1",
"@actions/github": "^4.0.0", "@actions/github": "^5.1.1",
"@babel/core": "^7.13.10", "@changesets/ghcommit": "1.3.0",
"@babel/preset-env": "^7.13.10",
"@babel/preset-typescript": "^7.13.0",
"@changesets/pre": "^1.0.9", "@changesets/pre": "^1.0.9",
"@changesets/read": "^0.5.3", "@changesets/read": "^0.5.3",
"@manypkg/get-packages": "^1.1.3", "@manypkg/get-packages": "^1.1.3",
"@types/fs-extra": "^8.0.0", "@octokit/plugin-throttling": "^5.2.1",
"@types/jest": "^24.0.18",
"@types/node": "^12.7.1",
"@types/semver": "^6.0.2",
"babel-jest": "^24.9.0",
"fs-extra": "^8.1.0", "fs-extra": "^8.1.0",
"husky": "^3.0.3",
"jest": "^24.9.0",
"mdast-util-to-string": "^1.0.6", "mdast-util-to-string": "^1.0.6",
"remark-parse": "^7.0.1", "remark-parse": "^7.0.1",
"remark-stringify": "^7.0.3", "remark-stringify": "^7.0.3",
"resolve-from": "^5.0.0", "resolve-from": "^5.0.0",
"semver": "^6.3.0", "semver": "^7.5.3",
"unified": "^8.3.2" "unified": "^8.3.2"
}, },
"husky": { "husky": {
"hooks": {} "hooks": {}
}, },
"prettier": {} "prettier": {},
"resolutions": {
"**/@octokit/core": "4.2.0",
"trim": "^0.0.3",
"y18n": "^4.0.1"
},
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
} }
+10 -10
View File
@@ -1,8 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`version creates simple PR 1`] = ` exports[`version creates simple PR 1`] = `
Array [ [
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.
@@ -34,8 +34,8 @@ Array [
`; `;
exports[`version does not include any release information if a message with simplified release info exceeds size limit 1`] = ` exports[`version does not include any release information if a message with simplified release info exceeds size limit 1`] = `
Array [ [
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.
@@ -52,8 +52,8 @@ Array [
`; `;
exports[`version does not include changelog entries if full message exceeds size limit 1`] = ` exports[`version does not include changelog entries if full message exceeds size limit 1`] = `
Array [ [
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.
@@ -74,8 +74,8 @@ Array [
`; `;
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 [ [
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.
@@ -96,8 +96,8 @@ Array [
`; `;
exports[`version only includes bumped packages in the PR body 1`] = ` exports[`version only includes bumped packages in the PR body 1`] = `
Array [ [
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.
+4 -4
View File
@@ -1,18 +1,18 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`it sorts the things right 1`] = ` exports[`it sorts the things right 1`] = `
Array [ [
Object { {
"highestLevel": 3, "highestLevel": 3,
"name": "c", "name": "c",
"private": false, "private": false,
}, },
Object { {
"highestLevel": 1, "highestLevel": 1,
"name": "b", "name": "b",
"private": false, "private": false,
}, },
Object { {
"highestLevel": 3, "highestLevel": 3,
"name": "a", "name": "a",
"private": true, "private": true,
+106
View File
@@ -0,0 +1,106 @@
import * as core from "@actions/core";
import { exec, getExecOutput } from "@actions/exec";
import * as github from "@actions/github";
import { commitChangesFromRepo } from "@changesets/ghcommit/git";
import { Octokit } from "./octokit";
const push = async (branch: string, { force }: { force?: boolean } = {}) => {
await exec(
"git",
["push", "origin", `HEAD:${branch}`, force && "--force"].filter<string>(
Boolean as any
)
);
};
const switchToMaybeExistingBranch = async (branch: string) => {
let { stderr } = await getExecOutput("git", ["checkout", branch], {
ignoreReturnCode: true,
});
let isCreatingBranch = !stderr
.toString()
.includes(`Switched to a new branch '${branch}'`);
if (isCreatingBranch) {
await exec("git", ["checkout", "-b", branch]);
}
};
const reset = async (
pathSpec: string,
mode: "hard" | "soft" | "mixed" = "hard"
) => {
await exec("git", ["reset", `--${mode}`, pathSpec]);
};
const commitAll = async (message: string) => {
await exec("git", ["add", "."]);
await exec("git", ["commit", "-m", message]);
};
const checkIfClean = async (): Promise<boolean> => {
const { stdout } = await getExecOutput("git", ["status", "--porcelain"]);
return !stdout.length;
};
export class Git {
octokit;
constructor(octokit?: Octokit) {
this.octokit = octokit;
}
async setupUser() {
if (this.octokit) {
return;
}
await exec("git", ["config", "user.name", `"github-actions[bot]"`]);
await exec("git", [
"config",
"user.email",
`"41898282+github-actions[bot]@users.noreply.github.com"`,
]);
}
async pushTag(tag: string) {
if (this.octokit) {
return this.octokit.rest.git
.createRef({
...github.context.repo,
ref: `refs/tags/${tag}`,
sha: github.context.sha,
})
.catch((err) => {
// Assuming tag was manually pushed in custom publish script
core.warning(`Failed to create tag ${tag}: ${err.message}`);
});
}
await exec("git", ["push", "origin", tag]);
}
async prepareBranch(branch: string) {
if (this.octokit) {
// Preparing a new local branch is not necessary when using the API
return;
}
await switchToMaybeExistingBranch(branch);
await reset(github.context.sha);
}
async pushChanges({ branch, message }: { branch: string; message: string }) {
if (this.octokit) {
return commitChangesFromRepo({
octokit: this.octokit,
...github.context.repo,
branch,
message,
base: {
commit: github.context.sha,
},
force: true,
});
}
if (!(await checkIfClean())) {
await commitAll(message);
}
await push(branch, { force: true });
}
}
-64
View File
@@ -1,64 +0,0 @@
import { exec } from "@actions/exec";
import { execWithOutput } from "./utils";
export const setupUser = async () => {
await exec("git", [
"config",
"user.name",
`"github-actions[bot]"`,
]);
await exec("git", [
"config",
"user.email",
`"github-actions[bot]@users.noreply.github.com"`,
]);
};
export const pullBranch = async (branch: string) => {
await exec("git", ["pull", "origin", branch]);
};
export const push = async (
branch: string,
{ force }: { force?: boolean } = {}
) => {
await exec(
"git",
["push", "origin", `HEAD:${branch}`, force && "--force"].filter<string>(
Boolean as any
)
);
};
export const pushTags = async () => {
await exec("git", ["push", "origin", "--tags"]);
};
export const switchToMaybeExistingBranch = async (branch: string) => {
let { stderr } = await execWithOutput("git", ["checkout", branch], {
ignoreReturnCode: true,
});
let isCreatingBranch = !stderr
.toString()
.includes(`Switched to a new branch '${branch}'`);
if (isCreatingBranch) {
await exec("git", ["checkout", "-b", branch]);
}
};
export const reset = async (
pathSpec: string,
mode: "hard" | "soft" | "mixed" = "hard"
) => {
await exec("git", ["reset", `--${mode}`, pathSpec]);
};
export const commitAll = async (message: string) => {
await exec("git", ["add", "."]);
await exec("git", ["commit", "-m", message]);
};
export const checkIfClean = async (): Promise<boolean> => {
const { stdout } = await execWithOutput("git", ["status", "--porcelain"]);
return !stdout.length;
};
+39 -17
View File
@@ -1,8 +1,9 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import fs from "fs-extra"; import fs from "fs-extra";
import * as gitUtils from "./gitUtils"; import { Git } from "./git";
import { runPublish, runVersion } from "./run"; import { setupOctokit } from "./octokit";
import readChangesetState from "./readChangesetState"; import readChangesetState from "./readChangesetState";
import { runPublish, runVersion } from "./run";
const getOptionalInput = (name: string) => core.getInput(name) || undefined; const getOptionalInput = (name: string) => core.getInput(name) || undefined;
@@ -16,18 +17,26 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
const inputCwd = core.getInput("cwd"); const inputCwd = core.getInput("cwd");
if (inputCwd) { if (inputCwd) {
console.log("changing directory to the one given as the input"); core.info("changing directory to the one given as the input");
process.chdir(inputCwd); process.chdir(inputCwd);
} }
const octokit = setupOctokit(githubToken);
const commitMode = getOptionalInput("commitMode") ?? "git-cli";
if (commitMode !== "git-cli" && commitMode !== "github-api") {
core.setFailed(`Invalid commit mode: ${commitMode}`);
return;
}
const git = new Git(commitMode === "github-api" ? octokit : undefined);
let setupGitUser = core.getBooleanInput("setupGitUser"); let setupGitUser = core.getBooleanInput("setupGitUser");
if (setupGitUser) { if (setupGitUser) {
console.log("setting git user"); core.info("setting git user");
await gitUtils.setupUser(); await git.setupUser();
} }
console.log("setting GitHub credentials"); core.info("setting GitHub credentials");
await fs.writeFile( await fs.writeFile(
`${process.env.HOME}/.netrc`, `${process.env.HOME}/.netrc`,
`machine github.com\nlogin github-actions[bot]\npassword ${githubToken}` `machine github.com\nlogin github-actions[bot]\npassword ${githubToken}`
@@ -37,6 +46,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");
@@ -45,27 +57,29 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
switch (true) { switch (true) {
case !hasChangesets && !hasPublishScript: case !hasChangesets && !hasPublishScript:
console.log("No changesets found"); core.info(
"No changesets present or were removed by merging release PR. Not publishing because no publish script found."
);
return; return;
case !hasChangesets && hasPublishScript: { case !hasChangesets && hasPublishScript: {
console.log( core.info(
"No changesets found, attempting to publish any unpublished packages to npm" "No changesets found. Attempting to publish any unpublished packages to npm"
); );
let userNpmrcPath = `${process.env.HOME}/.npmrc`; let userNpmrcPath = `${process.env.HOME}/.npmrc`;
if (fs.existsSync(userNpmrcPath)) { if (fs.existsSync(userNpmrcPath)) {
console.log("Found existing user .npmrc file"); core.info("Found existing user .npmrc file");
const userNpmrcContent = await fs.readFile(userNpmrcPath, "utf8"); const userNpmrcContent = await fs.readFile(userNpmrcPath, "utf8");
const authLine = userNpmrcContent.split("\n").find((line) => { const authLine = userNpmrcContent.split("\n").find((line) => {
// check based on https://github.com/npm/cli/blob/8f8f71e4dd5ee66b3b17888faad5a7bf6c657eed/test/lib/adduser.js#L103-L105 // check based on https://github.com/npm/cli/blob/8f8f71e4dd5ee66b3b17888faad5a7bf6c657eed/test/lib/adduser.js#L103-L105
return /^\s*\/\/registry\.npmjs\.org\/:[_-]authToken=/i.test(line); return /^\s*\/\/registry\.npmjs\.org\/:[_-]authToken=/i.test(line);
}); });
if (authLine) { if (authLine) {
console.log( core.info(
"Found existing auth token for the npm registry in the user .npmrc file" "Found existing auth token for the npm registry in the user .npmrc file"
); );
} else { } else {
console.log( core.info(
"Didn't find existing auth token for the npm registry in the user .npmrc file, creating one" "Didn't find existing auth token for the npm registry in the user .npmrc file, creating one"
); );
fs.appendFileSync( fs.appendFileSync(
@@ -74,7 +88,7 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
); );
} }
} else { } else {
console.log("No user .npmrc file found, creating one"); core.info("No user .npmrc file found, creating one");
fs.writeFileSync( fs.writeFileSync(
userNpmrcPath, userNpmrcPath,
`//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n` `//registry.npmjs.org/:_authToken=${process.env.NPM_TOKEN}\n`
@@ -83,7 +97,8 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
const result = await runPublish({ const result = await runPublish({
script: publishScript, script: publishScript,
githubToken, git,
octokit,
createGithubReleases: core.getBooleanInput("createGithubReleases"), createGithubReleases: core.getBooleanInput("createGithubReleases"),
}); });
@@ -96,20 +111,27 @@ const getOptionalInput = (name: string) => core.getInput(name) || undefined;
} }
return; return;
} }
case hasChangesets: case hasChangesets && !hasNonEmptyChangesets:
core.info("All changesets are empty; not creating PR");
return;
case hasChangesets: {
const octokit = setupOctokit(githubToken);
const { pullRequestNumber } = await runVersion({ const { pullRequestNumber } = await runVersion({
script: getOptionalInput("version"), script: getOptionalInput("version"),
githubToken, git,
octokit,
prTitle: getOptionalInput("title"), prTitle: getOptionalInput("title"),
commitMessage: getOptionalInput("commit"), commitMessage: getOptionalInput("commit"),
hasPublishScript, hasPublishScript,
branch: getOptionalInput("branch"),
}); });
core.setOutput("pullRequestNumber", String(pullRequestNumber)); core.setOutput("pullRequestNumber", String(pullRequestNumber));
return; return;
}
} }
})().catch((err) => { })().catch((err) => {
console.error(err); core.error(err);
core.setFailed(err.message); core.setFailed(err.message);
}); });
+39
View File
@@ -0,0 +1,39 @@
import * as core from "@actions/core";
import { GitHub, getOctokitOptions } from "@actions/github/lib/utils";
import { throttling } from "@octokit/plugin-throttling";
export const setupOctokit = (githubToken: string) => {
return new (GitHub.plugin(throttling))(
getOctokitOptions(githubToken, {
throttle: {
onRateLimit: (retryAfter, options: any, octokit, retryCount) => {
core.warning(
`Request quota exhausted for request ${options.method} ${options.url}`
);
if (retryCount <= 2) {
core.info(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
onSecondaryRateLimit: (
retryAfter,
options: any,
octokit,
retryCount
) => {
core.warning(
`SecondaryRateLimit detected for request ${options.method} ${options.url}`
);
if (retryCount <= 2) {
core.info(`Retrying after ${retryAfter} seconds!`);
return true;
}
},
},
})
);
};
export type Octokit = ReturnType<typeof setupOctokit>;
+7 -5
View File
@@ -11,17 +11,19 @@ export default async function readChangesetState(
cwd: string = process.cwd() cwd: string = process.cwd()
): Promise<ChangesetState> { ): Promise<ChangesetState> {
let preState = await readPreState(cwd); let preState = await readPreState(cwd);
let isInPreMode = preState !== undefined && preState.mode === "pre";
let changesets = await readChangesets(cwd); let changesets = await readChangesets(cwd);
if (isInPreMode) { if (preState !== undefined && preState.mode === "pre") {
let changesetsToFilter = new Set(preState.changesets); let changesetsToFilter = new Set(preState.changesets);
changesets = changesets.filter((x) => !changesetsToFilter.has(x.id));
return {
preState,
changesets: changesets.filter((x) => !changesetsToFilter.has(x.id)),
};
} }
return { return {
preState: isInPreMode ? preState : undefined, preState: undefined,
changesets, changesets,
}; };
} }
+35 -29
View File
@@ -1,9 +1,10 @@
import { Changeset } from "@changesets/types";
import writeChangeset from "@changesets/write";
import fixturez from "fixturez"; import fixturez from "fixturez";
import * as github from "@actions/github";
import fs from "fs-extra"; import fs from "fs-extra";
import path from "path"; import path from "path";
import writeChangeset from "@changesets/write"; import { Git } from "./git";
import { Changeset } from "@changesets/types"; import { setupOctokit } from "./octokit";
import { runVersion } from "./run"; import { runVersion } from "./run";
jest.mock("@actions/github", () => ({ jest.mock("@actions/github", () => ({
@@ -15,22 +16,32 @@ jest.mock("@actions/github", () => ({
ref: "refs/heads/some-branch", ref: "refs/heads/some-branch",
sha: "xeac7", sha: "xeac7",
}, },
getOctokit: jest.fn(),
})); }));
jest.mock("./gitUtils"); jest.mock("@actions/github/lib/utils", () => ({
GitHub: {
plugin: () => {
// function necessary to be used as constructor
return function () {
return {
rest: mockedGithubMethods,
};
};
},
},
getOctokitOptions: jest.fn(),
}));
jest.mock("./git");
jest.mock("@changesets/ghcommit/git");
let mockedGithubMethods = { let mockedGithubMethods = {
search: {
issuesAndPullRequests: jest.fn(),
},
pulls: { pulls: {
create: jest.fn(), create: jest.fn(),
list: jest.fn(),
}, },
repos: { repos: {
createRelease: jest.fn(), createRelease: jest.fn(),
}, },
}; };
(github.getOctokit as any).mockImplementation(() => mockedGithubMethods);
let f = fixturez(__dirname); let f = fixturez(__dirname);
@@ -53,9 +64,7 @@ describe("version", () => {
let cwd = f.copy("simple-project"); let cwd = f.copy("simple-project");
linkNodeModules(cwd); linkNodeModules(cwd);
mockedGithubMethods.search.issuesAndPullRequests.mockImplementationOnce( mockedGithubMethods.pulls.list.mockImplementationOnce(() => ({ data: [] }));
() => ({ data: { items: [] } })
);
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({ mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 }, data: { number: 123 },
@@ -81,7 +90,8 @@ describe("version", () => {
); );
await runVersion({ await runVersion({
githubToken: "@@GITHUB_TOKEN", octokit: setupOctokit("@@GITHUB_TOKEN"),
git: new Git(),
cwd, cwd,
}); });
@@ -92,9 +102,7 @@ describe("version", () => {
let cwd = f.copy("simple-project"); let cwd = f.copy("simple-project");
linkNodeModules(cwd); linkNodeModules(cwd);
mockedGithubMethods.search.issuesAndPullRequests.mockImplementationOnce( mockedGithubMethods.pulls.list.mockImplementationOnce(() => ({ data: [] }));
() => ({ data: { items: [] } })
);
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({ mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 }, data: { number: 123 },
@@ -116,7 +124,8 @@ describe("version", () => {
); );
await runVersion({ await runVersion({
githubToken: "@@GITHUB_TOKEN", octokit: setupOctokit("@@GITHUB_TOKEN"),
git: new Git(),
cwd, cwd,
}); });
@@ -127,9 +136,7 @@ describe("version", () => {
let cwd = f.copy("ignored-package"); let cwd = f.copy("ignored-package");
linkNodeModules(cwd); linkNodeModules(cwd);
mockedGithubMethods.search.issuesAndPullRequests.mockImplementationOnce( mockedGithubMethods.pulls.list.mockImplementationOnce(() => ({ data: [] }));
() => ({ data: { items: [] } })
);
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({ mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 }, data: { number: 123 },
@@ -151,7 +158,8 @@ describe("version", () => {
); );
await runVersion({ await runVersion({
githubToken: "@@GITHUB_TOKEN", octokit: setupOctokit("@@GITHUB_TOKEN"),
git: new Git(),
cwd, cwd,
}); });
@@ -162,9 +170,7 @@ describe("version", () => {
let cwd = f.copy("simple-project"); let cwd = f.copy("simple-project");
linkNodeModules(cwd); linkNodeModules(cwd);
mockedGithubMethods.search.issuesAndPullRequests.mockImplementationOnce( mockedGithubMethods.pulls.list.mockImplementationOnce(() => ({ data: [] }));
() => ({ data: { items: [] } })
);
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({ mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 }, data: { number: 123 },
@@ -206,7 +212,8 @@ fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
); );
await runVersion({ await runVersion({
githubToken: "@@GITHUB_TOKEN", octokit: setupOctokit("@@GITHUB_TOKEN"),
git: new Git(),
cwd, cwd,
prBodyMaxCharacters: 1000, prBodyMaxCharacters: 1000,
}); });
@@ -221,9 +228,7 @@ fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
let cwd = f.copy("simple-project"); let cwd = f.copy("simple-project");
linkNodeModules(cwd); linkNodeModules(cwd);
mockedGithubMethods.search.issuesAndPullRequests.mockImplementationOnce( mockedGithubMethods.pulls.list.mockImplementationOnce(() => ({ data: [] }));
() => ({ data: { items: [] } })
);
mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({ mockedGithubMethods.pulls.create.mockImplementationOnce(() => ({
data: { number: 123 }, data: { number: 123 },
@@ -265,7 +270,8 @@ fluminis divesque vulnere aquis parce lapsis rabie si visa fulmineis.
); );
await runVersion({ await runVersion({
githubToken: "@@GITHUB_TOKEN", octokit: setupOctokit("@@GITHUB_TOKEN"),
git: new Git(),
cwd, cwd,
prBodyMaxCharacters: 500, prBodyMaxCharacters: 500,
}); });
+70 -63
View File
@@ -1,20 +1,21 @@
import { exec } from "@actions/exec"; import * as core from "@actions/core";
import { exec, getExecOutput } from "@actions/exec";
import * as github from "@actions/github"; import * as github from "@actions/github";
import fs from "fs-extra";
import { getPackages, Package } from "@manypkg/get-packages";
import path from "path";
import * as semver from "semver";
import { PreState } from "@changesets/types"; import { PreState } from "@changesets/types";
import { import { Package, getPackages } from "@manypkg/get-packages";
getChangelogEntry, import fs from "fs-extra";
execWithOutput, import path from "path";
getChangedPackages,
sortTheThings,
getVersionsByDirectory,
} from "./utils";
import * as gitUtils from "./gitUtils";
import readChangesetState from "./readChangesetState";
import resolveFrom from "resolve-from"; import resolveFrom from "resolve-from";
import * as semver from "semver";
import { Git } from "./git";
import { Octokit } from "./octokit";
import readChangesetState from "./readChangesetState";
import {
getChangedPackages,
getChangelogEntry,
getVersionsByDirectory,
sortTheThings,
} from "./utils";
// GitHub Issues/PRs messages have a max size limit on the // GitHub Issues/PRs messages have a max size limit on the
// message body payload. // message body payload.
@@ -23,7 +24,7 @@ import resolveFrom from "resolve-from";
const MAX_CHARACTERS_PER_MESSAGE = 60000; const MAX_CHARACTERS_PER_MESSAGE = 60000;
const createRelease = async ( const createRelease = async (
octokit: ReturnType<typeof github.getOctokit>, octokit: Octokit,
{ pkg, tagName }: { pkg: Package; tagName: string } { pkg, tagName }: { pkg: Package; tagName: string }
) => { ) => {
try { try {
@@ -40,16 +41,21 @@ 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,
prerelease: pkg.packageJson.version.includes("-"), prerelease: pkg.packageJson.version.includes("-"),
...github.context.repo, ...github.context.repo,
}); });
} catch (err: any) { } catch (err) {
// if we can't find a changelog, the user has probably disabled changelogs // if we can't find a changelog, the user has probably disabled changelogs
if (err.code !== "ENOENT") { if (
err &&
typeof err === "object" &&
"code" in err &&
err.code !== "ENOENT"
) {
throw err; throw err;
} }
} }
@@ -57,8 +63,9 @@ const createRelease = async (
type PublishOptions = { type PublishOptions = {
script: string; script: string;
githubToken: string; octokit: Octokit;
createGithubReleases: boolean; createGithubReleases: boolean;
git: Git;
cwd?: string; cwd?: string;
}; };
@@ -75,21 +82,19 @@ type PublishResult =
export async function runPublish({ export async function runPublish({
script, script,
githubToken, git,
octokit,
createGithubReleases, createGithubReleases,
cwd = process.cwd(), cwd = process.cwd(),
}: PublishOptions): Promise<PublishResult> { }: PublishOptions): Promise<PublishResult> {
let octokit = github.getOctokit(githubToken);
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 }
); );
await gitUtils.pushTags();
let { packages, tool } = await getPackages(cwd); let { packages, tool } = await getPackages(cwd);
let releasedPackages: Package[] = []; let releasedPackages: Package[] = [];
@@ -115,12 +120,11 @@ export async function runPublish({
if (createGithubReleases) { if (createGithubReleases) {
await Promise.all( await Promise.all(
releasedPackages.map((pkg) => releasedPackages.map(async (pkg) => {
createRelease(octokit, { const tagName = `${pkg.packageJson.name}@${pkg.packageJson.version}`;
pkg, await git.pushTag(tagName);
tagName: `${pkg.packageJson.name}@${pkg.packageJson.version}`, await createRelease(octokit, { pkg, tagName });
}) })
)
); );
} }
} else { } else {
@@ -139,10 +143,9 @@ export async function runPublish({
if (match) { if (match) {
releasedPackages.push(pkg); releasedPackages.push(pkg);
if (createGithubReleases) { if (createGithubReleases) {
await createRelease(octokit, { const tagName = `v${pkg.packageJson.version}`;
pkg, await git.pushTag(tagName);
tagName: `v${pkg.packageJson.version}`, await createRelease(octokit, { pkg, tagName });
});
} }
break; break;
} }
@@ -165,8 +168,13 @@ export async function runPublish({
const requireChangesetsCliPkgJson = (cwd: string) => { const requireChangesetsCliPkgJson = (cwd: string) => {
try { try {
return require(resolveFrom(cwd, "@changesets/cli/package.json")); return require(resolveFrom(cwd, "@changesets/cli/package.json"));
} catch (err: any) { } catch (err) {
if (err && err.code === "MODULE_NOT_FOUND") { if (
err &&
typeof err === "object" &&
"code" in err &&
err.code === "MODULE_NOT_FOUND"
) {
throw new Error( throw new Error(
`Have you forgotten to install \`@changesets/cli\` in "${cwd}"?` `Have you forgotten to install \`@changesets/cli\` in "${cwd}"?`
); );
@@ -246,12 +254,14 @@ export async function getVersionPrBody({
type VersionOptions = { type VersionOptions = {
script?: string; script?: string;
githubToken: string; git: Git;
octokit: Octokit;
cwd?: string; cwd?: string;
prTitle?: string; prTitle?: string;
commitMessage?: string; commitMessage?: string;
hasPublishScript?: boolean; hasPublishScript?: boolean;
prBodyMaxCharacters?: number; prBodyMaxCharacters?: number;
branch?: string;
}; };
type RunVersionResult = { type RunVersionResult = {
@@ -260,21 +270,20 @@ type RunVersionResult = {
export async function runVersion({ export async function runVersion({
script, script,
githubToken, git,
octokit,
cwd = process.cwd(), cwd = process.cwd(),
prTitle = "Version Packages", prTitle = "Version Packages",
commitMessage = "Version Packages", commitMessage = "Version Packages",
hasPublishScript = false, hasPublishScript = false,
prBodyMaxCharacters = MAX_CHARACTERS_PER_MESSAGE, prBodyMaxCharacters = MAX_CHARACTERS_PER_MESSAGE,
branch = github.context.ref.replace("refs/heads/", ""),
}: VersionOptions): Promise<RunVersionResult> { }: VersionOptions): Promise<RunVersionResult> {
let repo = `${github.context.repo.owner}/${github.context.repo.repo}`;
let branch = github.context.ref.replace("refs/heads/", "");
let versionBranch = `changeset-release/${branch}`; let versionBranch = `changeset-release/${branch}`;
let octokit = github.getOctokit(githubToken);
let { preState } = await readChangesetState(cwd); let { preState } = await readChangesetState(cwd);
await gitUtils.switchToMaybeExistingBranch(versionBranch); await git.prepareBranch(versionBranch);
await gitUtils.reset(github.context.sha);
let versionsByDirectory = await getVersionsByDirectory(cwd); let versionsByDirectory = await getVersionsByDirectory(cwd);
@@ -291,9 +300,11 @@ export async function runVersion({
}); });
} }
let searchQuery = `repo:${repo}+state:open+head:${versionBranch}+base:${branch}`; const existingPullRequestsPromise = octokit.rest.pulls.list({
let searchResultPromise = octokit.search.issuesAndPullRequests({ ...github.context.repo,
q: searchQuery, state: "open",
head: `${github.context.repo.owner}:${versionBranch}`,
base: branch,
}); });
let changedPackages = await getChangedPackages(cwd, versionsByDirectory); let changedPackages = await getChangedPackages(cwd, versionsByDirectory);
let changedPackagesInfoPromises = Promise.all( let changedPackagesInfoPromises = Promise.all(
@@ -314,19 +325,14 @@ export async function runVersion({
); );
const finalPrTitle = `${prTitle}${!!preState ? ` (${preState.tag})` : ""}`; const finalPrTitle = `${prTitle}${!!preState ? ` (${preState.tag})` : ""}`;
const finalCommitMessage = `${commitMessage}${
!!preState ? ` (${preState.tag})` : ""
}`;
// project with `commit: true` setting could have already committed files await git.pushChanges({ branch: versionBranch, message: finalCommitMessage });
if (!(await gitUtils.checkIfClean())) {
const finalCommitMessage = `${commitMessage}${
!!preState ? ` (${preState.tag})` : ""
}`;
await gitUtils.commitAll(finalCommitMessage);
}
await gitUtils.push(versionBranch, { force: true }); let existingPullRequests = await existingPullRequestsPromise;
core.info(JSON.stringify(existingPullRequests.data, null, 2));
let searchResult = await searchResultPromise;
console.log(JSON.stringify(searchResult.data, null, 2));
const changedPackagesInfo = (await changedPackagesInfoPromises) const changedPackagesInfo = (await changedPackagesInfoPromises)
.filter((x) => x) .filter((x) => x)
@@ -340,9 +346,9 @@ export async function runVersion({
prBodyMaxCharacters, prBodyMaxCharacters,
}); });
if (searchResult.data.items.length === 0) { if (existingPullRequests.data.length === 0) {
console.log("creating pull request"); core.info("creating pull request");
const { data: newPullRequest } = await octokit.pulls.create({ const { data: newPullRequest } = await octokit.rest.pulls.create({
base: branch, base: branch,
head: versionBranch, head: versionBranch,
title: finalPrTitle, title: finalPrTitle,
@@ -354,14 +360,15 @@ export async function runVersion({
pullRequestNumber: newPullRequest.number, pullRequestNumber: newPullRequest.number,
}; };
} else { } else {
const [pullRequest] = searchResult.data.items; const [pullRequest] = existingPullRequests.data;
console.log(`updating found pull request #${pullRequest.number}`); core.info(`updating found pull request #${pullRequest.number}`);
await octokit.pulls.update({ await octokit.rest.pulls.update({
pull_number: pullRequest.number, pull_number: pullRequest.number,
title: finalPrTitle, title: finalPrTitle,
body: prBody, body: prBody,
...github.context.repo, ...github.context.repo,
state: "open",
}); });
return { return {
-27
View File
@@ -3,7 +3,6 @@ import remarkParse from "remark-parse";
import remarkStringify from "remark-stringify"; import remarkStringify from "remark-stringify";
// @ts-ignore // @ts-ignore
import mdastToString from "mdast-util-to-string"; import mdastToString from "mdast-util-to-string";
import { exec } from "@actions/exec";
import { getPackages, Package } from "@manypkg/get-packages"; import { getPackages, Package } from "@manypkg/get-packages";
export const BumpLevels = { export const BumpLevels = {
@@ -87,32 +86,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 }
+1 -1
View File
@@ -39,7 +39,7 @@
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */ /* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ "moduleResolution": "nodenext", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
+3062 -7210
View File
File diff suppressed because it is too large Load Diff