Compare commits

...

35 Commits
v7 ... v8.0.1

Author SHA1 Message Date
Federico Grandi
756d9ea820 release: v8.0.1 2022-01-23 23:49:26 +01:00
allcontributors[bot]
cb4f06fa66 docs: add prince-chrismc as a contributor for doc (#357)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2022-01-23 23:38:50 +01:00
Federico Grandi
3d8fcf9529 docs: add FAQ about PRs
closes #351
2022-01-23 23:35:47 +01:00
allcontributors[bot]
664b419dc5 docs: add secondmanveran as a contributor for doc (#356)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2022-01-23 23:23:14 +01:00
Federico Grandi
7b61ff5331 docs: fix outdated docs about the pull input
closes #354
2022-01-23 23:22:02 +01:00
Federico Grandi
017fbd6dce chore: lint source code 2022-01-23 23:13:35 +01:00
Federico Grandi
2103e93ecc chore: npm audit fix, update build 2022-01-23 23:09:07 +01:00
allcontributors[bot]
1a5e6d925d docs: add mcargille as a contributor for bug, code (#355)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2022-01-23 23:07:03 +01:00
mcargille
bfbc660a1b fix: add check to allow empty commits (#352)
* add check to allow empty commits if arg is set

* fix: target only the desired argument

* fix: add debug message

* fix: fix debug message

Co-authored-by: Federico Grandi <fgrandi30@gmail.com>
2022-01-23 23:05:54 +01:00
Federico Grandi
7ea52730bc docs: update README to new version tag 2022-01-20 15:08:33 +01:00
Federico Grandi
0294aa039d release: v8.0.0 2022-01-20 15:02:45 +01:00
Federico Grandi
b9360951d0 docs: change manifest description 2022-01-20 14:43:11 +01:00
Federico Grandi
ab35b67df6 docs(README): fix contributors link 2022-01-20 13:38:10 +01:00
Federico Grandi
03fca92ff8 docs: improve README 2022-01-20 13:36:33 +01:00
Federico Grandi
0e1feea77e feat: add commit_long_sha output (#349) 2022-01-20 13:18:16 +01:00
allcontributors[bot]
f016b267be docs: add Darylgolden as a contributor for bug (#348)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2022-01-20 12:39:01 +01:00
Federico Grandi
6fdb34ed01 fix!: change behavior related to branches and pulling
I would have opened a pull request, but for some reason GitHub was
preventing me to do so...
Anyway, here's the description:

This PR makes the action run on whatever has been checked out by
previous steps.
This is better because it makes the action faster and solves some issues
that are caused by it pulling from the wrong ref (especially in PRs that
involve a fork).

The previous branch-related inputs have been removed, in favor of a new
input called `new-branch`: this will allow you to create a new branch
from the starting ref. If the branch already exists the action will try
to push anyway, but that can result in the remote rejecting the push
because it's not straightforward. For info on how to handle this
situation, please check out the README.

In conclusion, this PR makes the user responsible for handling branches,
while still keeping an easy-to-use option to create new branches for
those who need it: just make sure that you also consider when the branch
already exists.

Fixes #327
2022-01-20 12:34:22 +01:00
Federico Grandi
bea30d7628 docs(README): improve branch paragraph 2022-01-19 22:31:54 +01:00
Federico Grandi
c989bf31e9 docs: update README 2022-01-19 22:17:57 +01:00
Federico Grandi
a790c74dfe fix: merge existing inputs into new new_branch input 2022-01-19 21:41:48 +01:00
Federico Grandi
90c92e18d6 ci: add CodeQL 2022-01-19 16:26:25 +01:00
dependabot[bot]
b7e58855c4 chore(deps-dev): bump @vercel/ncc from 0.33.0 to 0.33.1 (#344)
Bumps [@vercel/ncc](https://github.com/vercel/ncc) from 0.33.0 to 0.33.1.
- [Release notes](https://github.com/vercel/ncc/releases)
- [Commits](https://github.com/vercel/ncc/compare/0.33.0...0.33.1)

---
updated-dependencies:
- dependency-name: "@vercel/ncc"
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-20 18:12:25 +01:00
dependabot[bot]
4183cd85fa chore(deps-dev): bump typescript from 4.5.3 to 4.5.4 (#343)
Bumps [typescript](https://github.com/Microsoft/TypeScript) from 4.5.3 to 4.5.4.
- [Release notes](https://github.com/Microsoft/TypeScript/releases)
- [Commits](https://github.com/Microsoft/TypeScript/compare/v4.5.3...v4.5.4)

---
updated-dependencies:
- dependency-name: typescript
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-20 18:11:35 +01:00
dependabot[bot]
649affade7 chore(deps-dev): bump typescript from 4.5.2 to 4.5.3 (#338)
Bumps [typescript](https://github.com/Microsoft/TypeScript) from 4.5.2 to 4.5.3.
- [Release notes](https://github.com/Microsoft/TypeScript/releases)
- [Commits](https://github.com/Microsoft/TypeScript/compare/v4.5.2...v4.5.3)

---
updated-dependencies:
- dependency-name: typescript
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-13 19:11:29 +01:00
Federico Grandi
d4d39927bf fix!: don't switch branch unless explicitly told so 2021-12-09 18:35:35 +01:00
Federico Grandi
249b415d1b chore: move io-related code to dedicated file 2021-12-09 18:13:17 +01:00
dependabot[bot]
8e3afcf3c9 chore(deps-dev): bump @vercel/ncc from 0.32.0 to 0.33.0 (#334)
Bumps [@vercel/ncc](https://github.com/vercel/ncc) from 0.32.0 to 0.33.0.
- [Release notes](https://github.com/vercel/ncc/releases)
- [Commits](https://github.com/vercel/ncc/compare/0.32.0...0.33.0)

---
updated-dependencies:
- dependency-name: "@vercel/ncc"
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-06 17:14:06 +01:00
dependabot[bot]
715ee20ac2 chore(deps-dev): bump prettier from 2.5.0 to 2.5.1 (#333)
Bumps [prettier](https://github.com/prettier/prettier) from 2.5.0 to 2.5.1.
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/2.5.0...2.5.1)

---
updated-dependencies:
- dependency-name: prettier
  dependency-type: direct:development
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-12-06 17:13:52 +01:00
Federico Grandi
9b29ba5ec1 [auto] build: update compiled version 2021-12-03 20:45:21 +00:00
Federico Grandi
7d7466136c fix!: remove pull_strategy 2021-12-03 21:44:12 +01:00
Federico Grandi
52d096458a [auto] build: update compiled version 2021-12-03 20:39:27 +00:00
allcontributors[bot]
40463d7b72 docs: add JavierSegoviaCordoba as a contributor for ideas (#332)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-12-03 21:39:16 +01:00
Federico Grandi
7392614f5c feat!: add commit input (#331)
* fix!: remove `signoff` input

* feat: add `commit` input
2021-12-03 21:38:30 +01:00
Federico Grandi
b1323b2f1c docs(README): add FAQ about GitHub PATs
Fixes #318
2021-12-03 20:10:07 +01:00
allcontributors[bot]
15c2ba6606 docs: add drewwells as a contributor for ideas (#330)
* docs: update README.md [skip ci]

* docs: update .all-contributorsrc [skip ci]

Co-authored-by: allcontributors[bot] <46447321+allcontributors[bot]@users.noreply.github.com>
2021-12-03 19:56:05 +01:00
11 changed files with 669 additions and 481 deletions

View File

@@ -287,6 +287,61 @@
"contributions": [
"ideas"
]
},
{
"login": "drewwells",
"name": "Drew Wells",
"avatar_url": "https://avatars.githubusercontent.com/u/239123?v=4",
"profile": "http://blog.madewithdrew.com/",
"contributions": [
"ideas"
]
},
{
"login": "JavierSegoviaCordoba",
"name": "Javier Segovia Córdoba",
"avatar_url": "https://avatars.githubusercontent.com/u/7463564?v=4",
"profile": "https://kotlin.desarrollador-android.com/",
"contributions": [
"ideas"
]
},
{
"login": "Darylgolden",
"name": "Darylgolden",
"avatar_url": "https://avatars.githubusercontent.com/u/9102529?v=4",
"profile": "https://github.com/Darylgolden",
"contributions": [
"bug"
]
},
{
"login": "mcargille",
"name": "mcargille",
"avatar_url": "https://avatars.githubusercontent.com/u/20142895?v=4",
"profile": "https://github.com/mcargille",
"contributions": [
"bug",
"code"
]
},
{
"login": "secondmanveran",
"name": "secondman",
"avatar_url": "https://avatars.githubusercontent.com/u/97000801?v=4",
"profile": "https://github.com/secondmanveran",
"contributions": [
"doc"
]
},
{
"login": "prince-chrismc",
"name": "Chris Mc",
"avatar_url": "https://avatars.githubusercontent.com/u/16867443?v=4",
"profile": "https://github.com/prince-chrismc",
"contributions": [
"doc"
]
}
],
"contributorsPerLine": 7,

70
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@@ -0,0 +1,70 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [ main ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ main ]
schedule:
- cron: '40 12 * * 2'
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v2
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: Autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v1

View File

@@ -7,6 +7,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [8.0.1] - 2022-01-23
### Fixed:
- Fixed a bug that prevented the `--allow-empty` flag from being used for the `commit` input. (#352)
- Fixed README and CHANGELOG docs for the `pull` input, that were still showing the option to use `NO-PULL` to prevent pulling (while now it's the default behavior). (#354)
- Added a paragraph to the FAQs section of the README, that explains how to work with PRs in v8. (#351)
## [8.0.0] - 2022-01-20
### Fixed:
- **[BREAKING]** The action will now work with whatever ref has been checked out, without pulling or switching branches by default. You can still pull using the `pull` input and create a new branch with the newly-added `new_branch` input. For more info, check commit [`6fdb34e`](https://github.com/EndBug/add-and-commit/commit/6fdb34ed01d242c909eeb7e31bf1c4d37db43a54).
### Removed:
- **[BREAKING]** The `signoff` input has been removed, use `commit` instead. (#331)
- **[BREAKING]** The `pull_strategy` input has been removed, use `pull` instead.
- **[BREAKING]** The `branch` and `branch_mode` inputs have been removed, check commit [`6fdb34e`](https://github.com/EndBug/add-and-commit/commit/6fdb34ed01d242c909eeb7e31bf1c4d37db43a54) for more info.
- **[BREAKING]** The `pull` input doesn't support `NO-PULL` anymore: if you don't want the action to pull, simply remove the input, as it's the default behavior now.
### Added:
- Added the `commit` input, that allows you to change the arguments for the `git commit` command. (#331)
- Added the `new_branch` input. ([`6fdb34e`](https://github.com/EndBug/add-and-commit/commit/6fdb34ed01d242c909eeb7e31bf1c4d37db43a54))
- Added the `commit_long_sha` output. (#349)
## [7.5.0] - 2021-12-03
### Added:
@@ -272,7 +299,7 @@ First release
#
[unreleased]: https://github.com/EndBug/add-and-commit/compare/v7.5.0...HEAD
[unreleased]: https://github.com/EndBug/add-and-commit/compare/v8.0.1...HEAD
[1.0.0]: https://github.com/EndBug/add-and-commit/tree/v1.0.0
[2.0.0]: https://github.com/EndBug/add-and-commit/compare/v1.0.0...v2.0.0
[2.1.0]: https://github.com/EndBug/add-and-commit/compare/v2.0.0...v2.1.0
@@ -310,3 +337,5 @@ First release
[7.3.0]: https://github.com/EndBug/add-and-commit/compare/v7.2.1...v7.3.0
[7.4.0]: https://github.com/EndBug/add-and-commit/compare/v7.3.0...v7.4.0
[7.5.0]: https://github.com/EndBug/add-and-commit/compare/v7.4.0...v7.5.0
[8.0.0]: https://github.com/EndBug/add-and-commit/compare/v7.5.0...v8.0.0
[8.0.1]: https://github.com/EndBug/add-and-commit/compare/v8.0.0...v8.0.1

135
README.md
View File

@@ -3,17 +3,22 @@
[![Public workflows that use this action.](https://img.shields.io/endpoint?url=https%3A%2F%2Fapi-endbug.vercel.app%2Fapi%2Fgithub-actions%2Fused-by%3Faction%3DEndBug%2Fadd-and-commit%26badge%3Dtrue)](https://github.com/search?o=desc&q=EndBug+add-and-commit+path%3A.github%2Fworkflows+language%3AYAML&s=&type=Code)
[![All Contributors](https://img.shields.io/github/all-contributors/EndBug/add-and-commit)](#contributors-)
You can use this GitHub Action to commit changes made in your workflow run directly to your repo: for example, you use it to lint your code, update documentation, commit updated builds, etc....
You can use this GitHub Action to commit changes made in your workflow run directly to your repo: for example, you use it to lint your code, update documentation, commit updated builds, etc...
This is **heavily** inspired by [git-auto-commit-action](https://github.com/stefanzweifel/git-auto-commit-action) (by [Stefan Zweifel](https://github.com/stefanzweifel)): that action automatically detects changed files and commits them. While this is useful for most situations, this doesn't commit untracked files and can sometimes commit unintended changes (such as `package-lock.json` or similar, that may have happened during previous steps).
This action lets you choose the path that you want to use when adding & committing changes so that it works as you would normally do using `git` on your machine.
## Table of contents
- [Inputs](#inputs)
- [Outputs](#outputs)
- [FAQs](#faqs)
- [Examples](#examples)
- [Contributors](#contributors-)
## Inputs
Add a step like this to your workflow:
```yaml
- uses: EndBug/add-and-commit@v7 # You can change this to use a specific version.
- uses: EndBug/add-and-commit@v8 # You can change this to use a specific version.
with:
# The arguments for the `git add` command (see the paragraph below for more info)
# Default: '.'
@@ -27,14 +32,6 @@ Add a step like this to your workflow:
# Default: depends on the default_author input
author_email: mail@example.com
# The name of the branch to use, if different from the one that triggered the workflow.
# Default: the branch that triggered the run
branch: some-branch
# How the action should behave when the targeted branch is missing: "create" will create a new one on the remote, "throw" will exit
# Default: throw
branch_mode: create
# The name of the custom committer you want to use, if different from the author of the commit.
# Default: the name of the author (set with either author_name or default_author)
committer_name: Committer Name
@@ -58,6 +55,10 @@ Add a step like this to your workflow:
# Default: 'Commit from GitHub Actions (name of the workflow)'
message: 'Your commit message'
# If this input is set, the action will push the commit to a new branch with this name.
# Default: ''
new_branch: custom-new-branch
# The way the action should handle pathspec errors from the add and remove commands. Three options are available:
# - ignore -> errors will be logged but the step won't fail
# - exitImmediately -> the action will stop right away, and the step will fail
@@ -65,9 +66,9 @@ Add a step like this to your workflow:
# Default: ignore
pathspec_error_handling: ignore
# Arguments for the git pull command. Use NO-PULL to avoid the action pulling at all.
# Default: '--no-rebase'
pull: 'NO-PULL or --rebase --autostash ...'
# Arguments for the git pull command. By default, the action does not pull.
# Default: ''
pull: '--rebase --autostash ...'
# Whether to push the commit and, if any, its tags to the repo. It can also be used to set the git push arguments (see the paragraph below for more info)
# Default: true
@@ -77,10 +78,6 @@ Add a step like this to your workflow:
# Default: ''
remove: './dir/old_file.js'
# Whether to use the --signoff option on `git commit` (only boolean values accepted*)
# Default: false
signoff: true
# Arguments for the git tag command (the tag name always needs to be the first word not preceded by an hyphen)
# Default: ''
tag: 'v1.0.0 --force'
@@ -105,7 +102,7 @@ You can also use JSON or YAML arrays (e.g. `'["first", "second"]'`, `"['first',
### Pushing
By default the action runs the following command: `git push origin ${branch input} --set-upstream`. You can use the `push` input to modify this behavior, here's what you can set it to:
By default the action runs the following command: `git push origin ${new_branch input} --set-upstream`. You can use the `push` input to modify this behavior, here's what you can set it to:
- `true`: this is the default value, it will behave as usual.
- `false`: this prevents the action from pushing at all, no `git push` command is run.
@@ -114,17 +111,74 @@ By default the action runs the following command: `git push origin ${branch inpu
One way to use this is if you want to force push to a branch of your repo: you'll need to set the `push` input to, for example, `origin yourBranch --force`.
### Creating a new branch
If you want the action to commit in a new branch, you can use the `new_branch` input.
Please note that if the branch exists, the action will still try push to it, but it's possible that the push will be rejected by the remote as non-straightforward.
If that's the case, you need to make sure that the branch you want to commit to is already checked out before you run the action.
If you're **really** sure that you want to commit to that branch, you can also force-push by setting the `push` input to something like `origin yourBranchName --set-upstream --force`.
If you want to commit files "across different branches", here are two ways to do it:
1. You can check them out in two different directories, generate your files, move them to your destination and then run `add-and-commit` in the destination directory using the `cwd` input.
2. You can manually commit those files with `git` commands as you would on your machine. There are several ways to do this depending on the scenario. One of them if to stash your changes, checkout the destination branch, and popping the stash. You can then use the `add-and-commit` action as usual. Please note that this is just an example and may not work for you, since your use case may be different.
### Tagging
You can use the `tag` option to enter the arguments for a `git add` command. In order for the action to isolate the tag name from the rest of the arguments, it should be the first word not preceded by an hyphen (e.g. `-a tag-name -m "some other stuff"` is ok).
### Tokens
## Outputs
The action provides these outputs:
- `committed`: whether the action has created a commit (`'true'` or `'false'`)
- `commit_long_sha`: the full SHA of the commit that has just been created
- `commit_sha`: the short 7-character SHA of the commit that has just been created
- `pushed`: whether the action has pushed to the remote (`'true'` or `'false'`)
- `tagged`: whether the action has created a tag (`'true'` or `'false'`)
For more info on how to use outputs, see ["Context and expression syntax"](https://docs.github.com/en/free-pro-team@latest/actions/reference/context-and-expression-syntax-for-github-actions).
## FAQs
### Working with PRs
By default, when you use `actions/checkout` on a PR, it will checkout the head commit in a detached head state.
If you want to make some changes, you have to checkout the branch the PR is coming from in the head repo.
You can set it up like this:
```yaml
- uses: actions/checkout@v2
with:
repository: ${{ github.event.pull_request.head.repo.full_name }}
ref: ${{ github.event.pull_request.head.ref }}
```
You can find the full docs for payloads of `pull_request` events [here](https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads#webhook-payload-example-32).
If you're planning on running this only on "internal" PRs (where head and base are in the same repo) then you can omit the `repository` input.
If you're planning to use this with PRs coming from other forks, please keep in mind that you might not have write access to those repos.
You can try setting up the repo with your PAT, as explained in the ["About tokens" paragraph](#about-tokens) of this section.
Keep in mind that this "custom checkout" is meant only for PRs: if your workflow runs on multiple events (like `push` or `workflow_dispatch`), you could try having this step run only for `pull_request` events, while other ones will trigger the usual checkout.
If you wish to do so, you can use the `step.if` property, [here](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsif)'s the docs.
### About tokens
When pushing, the action uses the token that the local git repository has been configured with: that means that if you want to change it you'll need to do it in the steps that run before this action. For example: if you set up your repo with [`actions/checkout`](https://github.com/actions/checkout/) then you have to add the token there.
Changing the token with which the repo is configured can be useful if you want to run CI checks on the commit pushed by this action; anyway, it has to be set up outside of this action.
The action automatically gets the GitHub token from a `github_token` input: this input should not be modified by the user, since it doesn't affect the commits as it's only used to access the GitHub API to get user info, in case they selected that option for the commit author.
### The commit from the action is not triggering CI!
That's because you're checking out the repo using the built-in [`GITHUB_TOKEN` secret](https://docs.github.com/en/actions/security-guides/automatic-token-authentication): GitHub sees that the push event has been triggered by a commit generated by CI, and doesn't run any further checks to avoid unintentional check loops.
**If you're sure** that you want the commits generated during CI to trigger other workflow runs, you can checkout the repo using a [Personal Access Token (PAT)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token): this will make the resulting commit the same as if you made it yourself.
If you're using `actions/checkout`, check out their [docs](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token) to see how to set your repo token.
### About `actions/checkout`
The token you use when setting up the repo with this action will determine what token `add-and-commit` will use.
@@ -136,19 +190,10 @@ Some users reported that they were getting an error:
If you're getting this error and you're using `actions/checkout@v1`, try upgrading to `actions/checkout@v2`. If you're still having problems after upgrading, feel free to open an issue. Issue ref: [#146](https://github.com/EndBug/add-and-commit/issues/146)
## Outputs
The action provides these outputs:
- `committed`: whether the action has created a commit (`'true'` or `'false'`)
- `commit_sha`: the short 7-digit sha of the commit that has just been created
- `pushed`: whether the action has pushed to the remote (`'true'` or `'false'`)
- `tagged`: whether the action has created a tag (`'true'` or `'false'`)
For more info on how to use outputs, see ["Context and expression syntax"](https://docs.github.com/en/free-pro-team@latest/actions/reference/context-and-expression-syntax-for-github-actions).
## Examples
### Different author/committer configurations
If you don't want to use your GitHub username for the CI commits, you can use the `default_author` option to make it appear as if it was made by "github-actions"
<img src="https://user-images.githubusercontent.com/26386270/115738624-80b51780-a38d-11eb-9bbe-77461654274c.png" height=40/>
@@ -159,7 +204,7 @@ jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: EndBug/add-and-commit@v7
- uses: EndBug/add-and-commit@v8
with:
default_author: github_actions
```
@@ -169,7 +214,7 @@ You can also use the `committer_name` and `committer_email` inputs to make it ap
<img src="https://user-images.githubusercontent.com/26386270/130594168-1d910710-e2d0-4b06-9324-cbe5dde59154.png" height=70/>
```yaml
- uses: EndBug/add-and-commit@v7
- uses: EndBug/add-and-commit@v8
with:
message: Show GitHub Actions logo
committer_name: GitHub Actions
@@ -179,13 +224,15 @@ You can also use the `committer_name` and `committer_email` inputs to make it ap
<img src="https://user-images.githubusercontent.com/26386270/130594443-b881fae7-3064-4020-a4cc-6db37ef0df65.png" height=70/>
```yaml
- uses: EndBug/add-and-commit@v7
- uses: EndBug/add-and-commit@v8
with:
message: Show GitHub logo
committer_name: GitHub Actions
committer_email: 41898282+github-actions[bot]@users.noreply.github.com
```
### Automated linting
Do you want to lint your JavaScript files, located in the `src` folder, with ESLint, so that fixable changes are done without your intervention? You can use a workflow like this:
```yaml
@@ -212,7 +259,7 @@ jobs:
run: eslint "src/**" --fix
- name: Commit changes
uses: EndBug/add-and-commit@v7
uses: EndBug/add-and-commit@v8
with:
author_name: Your Name
author_email: mail@example.com
@@ -220,6 +267,8 @@ jobs:
add: '*.js'
```
### Running the action in a different directory
If you need to run the action on a repository that is not located in [`$GITHUB_WORKSPACE`](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/using-environment-variables#default-environment-variables), you can use the `cwd` option: the action uses a `cd` normal command, so the path should follow bash standards.
```yaml
@@ -241,7 +290,7 @@ jobs:
- run: echo "123" > ./pathToRepo/file.txt
# ...and then use the action as you would normally do, but providing the path to the repo
- uses: EndBug/add-and-commit@v7
- uses: EndBug/add-and-commit@v8
with:
message: 'Add the very useful text file'
add: '*.txt --force'
@@ -295,6 +344,14 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<tr>
<td align="center"><a href="https://orcid.org/0000-0001-6962-4290"><img src="https://avatars.githubusercontent.com/u/1366654?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Oliver Kopp</b></sub></a><br /><a href="#ideas-koppor" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="https://github.com/Glidias"><img src="https://avatars.githubusercontent.com/u/190195?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Glenn Ko</b></sub></a><br /><a href="#ideas-Glidias" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="http://blog.madewithdrew.com/"><img src="https://avatars.githubusercontent.com/u/239123?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Drew Wells</b></sub></a><br /><a href="#ideas-drewwells" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="https://kotlin.desarrollador-android.com/"><img src="https://avatars.githubusercontent.com/u/7463564?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Javier Segovia Córdoba</b></sub></a><br /><a href="#ideas-JavierSegoviaCordoba" title="Ideas, Planning, & Feedback">🤔</a></td>
<td align="center"><a href="https://github.com/Darylgolden"><img src="https://avatars.githubusercontent.com/u/9102529?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Darylgolden</b></sub></a><br /><a href="https://github.com/EndBug/add-and-commit/issues?q=author%3ADarylgolden" title="Bug reports">🐛</a></td>
<td align="center"><a href="https://github.com/mcargille"><img src="https://avatars.githubusercontent.com/u/20142895?v=4?s=100" width="100px;" alt=""/><br /><sub><b>mcargille</b></sub></a><br /><a href="https://github.com/EndBug/add-and-commit/issues?q=author%3Amcargille" title="Bug reports">🐛</a> <a href="https://github.com/EndBug/add-and-commit/commits?author=mcargille" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/secondmanveran"><img src="https://avatars.githubusercontent.com/u/97000801?v=4?s=100" width="100px;" alt=""/><br /><sub><b>secondman</b></sub></a><br /><a href="https://github.com/EndBug/add-and-commit/commits?author=secondmanveran" title="Documentation">📖</a></td>
</tr>
<tr>
<td align="center"><a href="https://github.com/prince-chrismc"><img src="https://avatars.githubusercontent.com/u/16867443?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Chris Mc</b></sub></a><br /><a href="https://github.com/EndBug/add-and-commit/commits?author=prince-chrismc" title="Documentation">📖</a></td>
</tr>
</table>
@@ -305,6 +362,10 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
### Additional credits
This action is inspired by [`git-auto-commit-action`](https://github.com/stefanzweifel/git-auto-commit-action) by [Stefan Zweifel](https://github.com/stefanzweifel).
## License
This action is distributed under the MIT license, check the [license](LICENSE) for more info.

View File

@@ -1,5 +1,5 @@
name: Add & Commit
description: Add & commit files from a path directly from GitHub Actions
description: Automatically commit changes made in your workflow run directly to your repo
inputs:
add:
@@ -12,13 +12,9 @@ inputs:
author_email:
description: The email of the user that will be displayed as the author of the commit
required: false
branch:
description: Name of the branch to use, if different from the one that triggered the workflow
commit:
description: Additional arguments for the git commit command
required: false
branch_mode:
description: How the action should behave when the targeted branch is missing
required: false
default: throw
committer_name:
description: The name of the custom committer you want to use
required: false
@@ -36,19 +32,16 @@ inputs:
message:
description: The message for the commit
required: false
new_branch:
description: The name of the branch to create.
required: false
pathspec_error_handling:
description: The way the action should handle pathspec errors from the add and remove commands.
required: false
default: ignore
pull:
description: Arguments for the git pull command. Use NO-PULL to avoid the action pulling at all.
description: Arguments for the git pull command. By default, the action does not pull.
required: false
# Default value currently set in runtime
# default: '--no-rebase'
pull_strategy:
description: The flag used on the pull strategy. Use NO-PULL to avoid the action pulling at all.
required: false
deprecationMessage: The 'pull_strategy' input is deprecated, please use 'pull'
push:
description: Whether to push the commit and, if any, its tags to the repo. It can also be used to set the git push arguments (more info in the README)
required: false
@@ -56,9 +49,6 @@ inputs:
remove:
description: Arguments for the git rm command
required: false
signoff:
description: Whether to use the --signoff option on git commit
required: false
tag:
description: Arguments for the git tag command (the tag name always needs to be the first word not preceded by a hyphen)
required: false
@@ -72,8 +62,10 @@ inputs:
outputs:
committed:
description: Whether the action has created a commit.
commit_long_sha:
description: The complete SHA of the commit that has been created.
commit_sha:
description: The SHA of the commit that has been created.
description: The short SHA of the commit that has been created.
pushed:
description: Whether the action has pushed to the remote.
tagged:

4
lib/index.js generated

File diff suppressed because one or more lines are too long

111
package-lock.json generated
View File

@@ -1,11 +1,12 @@
{
"name": "add-and-commit",
"version": "7.5.0",
"version": "8.0.1",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"version": "7.5.0",
"name": "add-and-commit",
"version": "8.0.1",
"license": "MIT",
"dependencies": {
"@actions/core": "^1.6.0",
@@ -19,15 +20,15 @@
"@types/node": "^12.12.54",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"@vercel/ncc": "^0.32.0",
"@vercel/ncc": "^0.33.1",
"all-contributors-cli": "^6.20.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"husky": "^7.0.4",
"prettier": "^2.5.0",
"prettier": "^2.5.1",
"ts-node": "^10.4.0",
"typescript": "^4.5.2",
"typescript": "^4.5.4",
"yamljs": "^0.3.0"
}
},
@@ -728,9 +729,9 @@
}
},
"node_modules/@vercel/ncc": {
"version": "0.32.0",
"resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.32.0.tgz",
"integrity": "sha512-S/SxTHHTbBQSOutpgnqEn+LyTfZcq9xMRAnzY05HpGVjxjmfmvg6SWZZkbW/GJIFznMmHGeGOrI1MEBD7efIkA==",
"version": "0.33.1",
"resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.33.1.tgz",
"integrity": "sha512-Mlsps/P0PLZwsCFtSol23FGqT3FhBGb4B1AuGQ52JTAtXhak+b0Fh/4T55r0/SVQPeRiX9pNItOEHwakGPmZYA==",
"dev": true,
"bin": {
"ncc": "dist/ncc/cli.js"
@@ -2267,11 +2268,22 @@
"integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ=="
},
"node_modules/node-fetch": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
"integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw==",
"version": "2.6.7",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
"integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/npm-run-path": {
@@ -2568,9 +2580,9 @@
}
},
"node_modules/prettier": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.0.tgz",
"integrity": "sha512-FM/zAKgWTxj40rH03VxzIPdXmj39SwSjwG0heUcNFwI+EMZJnY93yAiKXM3dObIKAM5TA88werc8T/EwhB45eg==",
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz",
"integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==",
"dev": true,
"bin": {
"prettier": "bin-prettier.js"
@@ -3098,6 +3110,11 @@
"node": ">=8.0"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o="
},
"node_modules/ts-node": {
"version": "10.4.0",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.4.0.tgz",
@@ -3205,9 +3222,9 @@
}
},
"node_modules/typescript": {
"version": "4.5.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.2.tgz",
"integrity": "sha512-5BlMof9H1yGt0P8/WF+wPNw6GfctgGjXp5hkblpyT+8rkASSmkUKMXrxR0Xg8ThVCi/JnHQiKXeBaEwCeQwMFw==",
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz",
"integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
@@ -3240,6 +3257,20 @@
"integrity": "sha512-usZBT3PW+LOjM25wbqIlZwPeJV+3OSz3M1k1Ws8snlW39dZyYL9lOGC5FgPVHfk0jKmjiDV8Z0mIbVQPiwFs7g==",
"dev": true
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -3963,9 +3994,9 @@
}
},
"@vercel/ncc": {
"version": "0.32.0",
"resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.32.0.tgz",
"integrity": "sha512-S/SxTHHTbBQSOutpgnqEn+LyTfZcq9xMRAnzY05HpGVjxjmfmvg6SWZZkbW/GJIFznMmHGeGOrI1MEBD7efIkA==",
"version": "0.33.1",
"resolved": "https://registry.npmjs.org/@vercel/ncc/-/ncc-0.33.1.tgz",
"integrity": "sha512-Mlsps/P0PLZwsCFtSol23FGqT3FhBGb4B1AuGQ52JTAtXhak+b0Fh/4T55r0/SVQPeRiX9pNItOEHwakGPmZYA==",
"dev": true
},
"acorn": {
@@ -5148,9 +5179,12 @@
"integrity": "sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ=="
},
"node-fetch": {
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.1.tgz",
"integrity": "sha512-V4aYg89jEoVRxRb2fJdAg8FHvI7cEyYdVAh94HH0UIK8oJxUfkjlDQN9RbMx+bEjP7+ggMiFRprSti032Oipxw=="
"version": "2.6.7",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz",
"integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==",
"requires": {
"whatwg-url": "^5.0.0"
}
},
"npm-run-path": {
"version": "2.0.2",
@@ -5363,9 +5397,9 @@
"dev": true
},
"prettier": {
"version": "2.5.0",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.0.tgz",
"integrity": "sha512-FM/zAKgWTxj40rH03VxzIPdXmj39SwSjwG0heUcNFwI+EMZJnY93yAiKXM3dObIKAM5TA88werc8T/EwhB45eg==",
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-2.5.1.tgz",
"integrity": "sha512-vBZcPRUR5MZJwoyi3ZoyQlc1rXeEck8KgeC9AwwOn+exuxLxq5toTRDTSaVrXHxelDMHy9zlicw8u66yxoSUFg==",
"dev": true
},
"prettier-linter-helpers": {
@@ -5747,6 +5781,11 @@
"is-number": "^7.0.0"
}
},
"tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o="
},
"ts-node": {
"version": "10.4.0",
"resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.4.0.tgz",
@@ -5811,9 +5850,9 @@
"dev": true
},
"typescript": {
"version": "4.5.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.2.tgz",
"integrity": "sha512-5BlMof9H1yGt0P8/WF+wPNw6GfctgGjXp5hkblpyT+8rkASSmkUKMXrxR0Xg8ThVCi/JnHQiKXeBaEwCeQwMFw==",
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz",
"integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==",
"dev": true
},
"universal-user-agent": {
@@ -5839,6 +5878,20 @@
"integrity": "sha512-usZBT3PW+LOjM25wbqIlZwPeJV+3OSz3M1k1Ws8snlW39dZyYL9lOGC5FgPVHfk0jKmjiDV8Z0mIbVQPiwFs7g==",
"dev": true
},
"webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE="
},
"whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha1-lmRU6HZUYuN2RNNib2dCzotwll0=",
"requires": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "add-and-commit",
"version": "7.5.0",
"version": "8.0.1",
"private": true,
"description": "Add & commit files from a path directly from GitHub Actions",
"main": "lib/index.js",
@@ -42,15 +42,15 @@
"@types/node": "^12.12.54",
"@typescript-eslint/eslint-plugin": "^4.33.0",
"@typescript-eslint/parser": "^4.33.0",
"@vercel/ncc": "^0.32.0",
"@vercel/ncc": "^0.33.1",
"all-contributors-cli": "^6.20.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-prettier": "^4.0.0",
"husky": "^7.0.4",
"prettier": "^2.5.0",
"prettier": "^2.5.1",
"ts-node": "^10.4.0",
"typescript": "^4.5.2",
"typescript": "^4.5.4",
"yamljs": "^0.3.0"
}
}

234
src/io.ts Normal file
View File

@@ -0,0 +1,234 @@
import * as core from '@actions/core'
import { getUserInfo, parseInputArray } from './util'
interface InputTypes {
add: string
author_name: string
author_email: string
commit: string | undefined
committer_name: string
committer_email: string
cwd: string
default_author: 'github_actor' | 'user_info' | 'github_actions'
message: string
new_branch: string | undefined
pathspec_error_handling: 'ignore' | 'exitImmediately' | 'exitAtEnd'
pull: string | undefined
push: string
remove: string | undefined
tag: string | undefined
github_token: string | undefined
}
export type input = keyof InputTypes
interface OutputTypes {
committed: 'true' | 'false'
commit_long_sha: string | undefined
commit_sha: string | undefined
pushed: 'true' | 'false'
tagged: 'true' | 'false'
}
export type output = keyof OutputTypes
export const outputs: OutputTypes = {
committed: 'false',
commit_long_sha: undefined,
commit_sha: undefined,
pushed: 'false',
tagged: 'false'
}
// Setup default output values
Object.entries(outputs).forEach(([name, value]) => core.setOutput(name, value))
export function getInput<T extends input>(name: T, parseAsBool: true): boolean
export function getInput<T extends input>(
name: T,
parseAsBool?: false
): InputTypes[T]
export function getInput<T extends input>(
name: T,
parseAsBool = false
): InputTypes[T] | boolean {
if (parseAsBool) return core.getBooleanInput(name)
// @ts-expect-error
return core.getInput(name)
}
export function setOutput<T extends output>(name: T, value: OutputTypes[T]) {
core.debug(`Setting output: ${name}=${value}`)
outputs[name] = value
core.setOutput(name, value)
}
export function logOutputs() {
core.startGroup('Outputs')
for (const key in outputs) {
core.info(`${key}: ${outputs[key]}`)
}
core.endGroup()
}
export async function checkInputs() {
function setInput(input: input, value: string | undefined) {
if (value) return (process.env[`INPUT_${input.toUpperCase()}`] = value)
else return delete process.env[`INPUT_${input.toUpperCase()}`]
}
function setDefault(input: input, value: string) {
if (!getInput(input)) setInput(input, value)
return getInput(input)
}
// #region add, remove
if (!getInput('add') && !getInput('remove'))
throw new Error(
"Both 'add' and 'remove' are empty, the action has nothing to do."
)
if (getInput('add')) {
const parsed = parseInputArray(getInput('add'))
if (parsed.length == 1)
core.info('Add input parsed as single string, running 1 git add command.')
else if (parsed.length > 1)
core.info(
`Add input parsed as string array, running ${parsed.length} git add commands.`
)
else core.setFailed('Add input: array length < 1')
}
if (getInput('remove')) {
const parsed = parseInputArray(getInput('remove') || '')
if (parsed.length == 1)
core.info(
'Remove input parsed as single string, running 1 git rm command.'
)
else if (parsed.length > 1)
core.info(
`Remove input parsed as string array, running ${parsed.length} git rm commands.`
)
else core.setFailed('Remove input: array length < 1')
}
// #endregion
// #region default_author
const default_author_valid = ['github_actor', 'user_info', 'github_actions']
if (!default_author_valid.includes(getInput('default_author')))
throw new Error(
`'${getInput(
'default_author'
)}' is not a valid value for default_author. Valid values: ${default_author_valid.join(
', '
)}`
)
// #endregion
// #region author_name, author_email
let name, email
switch (getInput('default_author')) {
case 'github_actor': {
name = process.env.GITHUB_ACTOR
email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`
break
}
case 'user_info': {
if (!getInput('author_name') || !getInput('author_email')) {
const res = await getUserInfo(process.env.GITHUB_ACTOR)
if (!res?.name)
core.warning("Couldn't fetch author name, filling with github_actor.")
if (!res?.email)
core.warning(
"Couldn't fetch author email, filling with github_actor."
)
res?.name && (name = res?.name)
res?.email && (email = res.email)
if (name && email) break
}
!name && (name = process.env.GITHUB_ACTOR)
!email && (email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`)
break
}
case 'github_actions': {
name = 'github-actions'
email = '41898282+github-actions[bot]@users.noreply.github.com'
break
}
default:
throw new Error(
'This should not happen, please contact the author of this action. (checkInputs.author)'
)
}
setDefault('author_name', name)
setDefault('author_email', email)
core.info(
`> Using '${getInput('author_name')} <${getInput(
'author_email'
)}>' as author.`
)
// #endregion
// #region committer_name, committer_email
if (getInput('committer_name') || getInput('committer_email'))
core.info(
`> Using custom committer info: ${
getInput('committer_name') ||
getInput('author_name') + ' [from author info]'
} <${
getInput('committer_email') ||
getInput('author_email') + ' [from author info]'
}>`
)
setDefault('committer_name', getInput('author_name'))
setDefault('committer_email', getInput('author_email'))
core.debug(
`Committer: ${getInput('committer_name')} <${getInput('committer_email')}>`
)
// #endregion
// #region message
setDefault(
'message',
`Commit from GitHub Actions (${process.env.GITHUB_WORKFLOW})`
)
core.info(`> Using "${getInput('message')}" as commit message.`)
// #endregion
// #region pathspec_error_handling
const peh_valid = ['ignore', 'exitImmediately', 'exitAtEnd']
if (!peh_valid.includes(getInput('pathspec_error_handling')))
throw new Error(
`"${getInput(
'pathspec_error_handling'
)}" is not a valid value for the 'pathspec_error_handling' input. Valid values are: ${peh_valid.join(
', '
)}`
)
// #endregion
// #region push
if (getInput('push')) {
// It has to be either 'true', 'false', or any other string (use as arguments)
let value: string | boolean
try {
value = getInput('push', true)
} catch {
value = getInput('push')
}
core.debug(`Current push option: '${value}' (parsed as ${typeof value})`)
}
// #endregion
// #region github_token
if (!getInput('github_token'))
core.warning(
'No github_token has been detected, the action may fail if it needs to use the API'
)
// #endregion
}

View File

@@ -1,17 +1,8 @@
import * as core from '@actions/core'
import path from 'path'
import simpleGit, { CommitSummary, Response } from 'simple-git'
import YAML from 'js-yaml'
import {
getInput,
getUserInfo,
input,
log,
matchGitArgs,
outputs,
readJSON,
setOutput
} from './util'
import simpleGit, { Response } from 'simple-git'
import { checkInputs, getInput, logOutputs, setOutput } from './io'
import { log, matchGitArgs, parseInputArray } from './util'
const baseDir = path.join(process.cwd(), getInput('cwd') || '')
const git = simpleGit({ baseDir })
@@ -39,8 +30,17 @@ core.info(`Running in ${baseDir}`)
core.info('> Checking for uncommitted changes in the git working tree...')
const changedFiles = (await git.diffSummary(['--cached'])).files.length
if (changedFiles > 0) {
// continue if there are any changes or if the allow-empty commit argument is included
if (
changedFiles > 0 ||
matchGitArgs(getInput('commit') || '').includes('--allow-empty')
) {
core.info(`> Found ${changedFiles} changed files.`)
core.debug(
`--allow-empty argument detected: ${matchGitArgs(
getInput('commit') || ''
).includes('--allow-empty')}`
)
await git
.addConfig('user.email', getInput('author_email'), undefined, log)
@@ -56,63 +56,43 @@ core.info(`Running in ${baseDir}`)
await git.fetch(['--tags', '--force'], log)
core.info('> Switching/creating branch...')
/** This should store whether the branch already existed, of if a new one was created */
let branchType!: 'existing' | 'new'
await git
.checkout(getInput('branch'))
.then(() => (branchType = 'existing'))
.catch(() => {
if (getInput('branch_mode') == 'create') {
log(
undefined,
`'${getInput('branch')}' branch not found, trying to create one.`
)
branchType = 'new'
return git.checkoutLocalBranch(getInput('branch'), log)
} else throw `'${getInput('branch')}' branch not found.`
})
/*
The current default value is set here: it will not pull when it has
created a new branch, it will use --rebase when the branch already existed
*/
const pull =
getInput('pull') ||
getInput('pull_strategy') ||
(branchType == 'new' ? 'NO-PULL' : '--no-rebase')
if (pull == 'NO-PULL') core.info('> Not pulling from repo.')
else {
core.info('> Pulling from remote...')
core.debug(`Current git pull arguments: ${pull}`)
const targetBranch = getInput('new_branch')
if (targetBranch) {
await git
.fetch(undefined, log)
.pull(undefined, undefined, matchGitArgs(pull), log)
.checkout(targetBranch)
.then(() => {
log(undefined, `'${targetBranch}' branch already existed.`)
})
.catch(() => {
log(undefined, `Creating '${targetBranch}' branch.`)
return git.checkoutLocalBranch(targetBranch, log)
})
}
core.info('> Re-staging files...')
if (getInput('add')) await add('all')
if (getInput('remove')) await remove('all')
const pullOption = getInput('pull')
if (pullOption) {
core.info('> Pulling from remote...')
core.debug(`Current git pull arguments: ${pullOption}`)
await git
.fetch(undefined, log)
.pull(undefined, undefined, matchGitArgs(pullOption), log)
} else core.info('> Not pulling from repo.')
core.info('> Creating commit...')
await git.commit(
getInput('message'),
undefined,
{
...(getInput('signoff')
? {
'--signoff': null
}
: {})
},
(err, data?: CommitSummary) => {
if (data) {
setOutput('committed', 'true')
setOutput('commit_sha', data.commit)
}
return log(err, data)
}
)
const commitData = await git
.commit(getInput('message'), matchGitArgs(getInput('commit') || ''))
.catch((err) => {
log(err)
})
if (commitData) {
log(undefined, commitData)
setOutput('committed', 'true')
setOutput('commit_sha', commitData.commit)
await git
.revparse(commitData.commit)
.then((long_sha) => setOutput('commit_long_sha', long_sha))
.catch((err) => core.warning(`Couldn't parse long SHA:\n${err}`))
}
if (getInput('tag')) {
core.info('> Tagging commit...')
@@ -140,11 +120,13 @@ core.info(`Running in ${baseDir}`)
if (pushOption === true) {
core.debug(
`Running: git push origin ${getInput('branch')} --set-upstream`
`Running: git push origin ${
getInput('new_branch') || ''
} --set-upstream`
)
await git.push(
'origin',
getInput('branch'),
getInput('new_branch'),
{ '--set-upstream': null },
(err, data?) => {
if (data) setOutput('pushed', 'true')
@@ -212,227 +194,6 @@ core.info(`Running in ${baseDir}`)
core.setFailed(e)
})
async function checkInputs() {
function setInput(input: input, value: string | undefined) {
if (value) return (process.env[`INPUT_${input.toUpperCase()}`] = value)
else return delete process.env[`INPUT_${input.toUpperCase()}`]
}
function setDefault(input: input, value: string) {
if (!getInput(input)) setInput(input, value)
return getInput(input)
}
const eventPath = process.env.GITHUB_EVENT_PATH,
event = eventPath && readJSON(eventPath)
const isPR = process.env.GITHUB_EVENT_NAME?.includes('pull_request'),
defaultBranch = isPR
? (event?.pull_request?.head?.ref as string)
: process.env.GITHUB_REF?.substring(11)
// #region add, remove
if (!getInput('add') && !getInput('remove'))
throw new Error(
"Both 'add' and 'remove' are empty, the action has nothing to do."
)
if (getInput('add')) {
const parsed = parseInputArray(getInput('add'))
if (parsed.length == 1)
core.info('Add input parsed as single string, running 1 git add command.')
else if (parsed.length > 1)
core.info(
`Add input parsed as string array, running ${parsed.length} git add commands.`
)
else core.setFailed('Add input: array length < 1')
}
if (getInput('remove')) {
const parsed = parseInputArray(getInput('remove') || '')
if (parsed.length == 1)
core.info(
'Remove input parsed as single string, running 1 git rm command.'
)
else if (parsed.length > 1)
core.info(
`Remove input parsed as string array, running ${parsed.length} git rm commands.`
)
else core.setFailed('Remove input: array length < 1')
}
// #endregion
// #region default_author
const default_author_valid = ['github_actor', 'user_info', 'github_actions']
if (!default_author_valid.includes(getInput('default_author')))
throw new Error(
`'${getInput(
'default_author'
)}' is not a valid value for default_author. Valid values: ${default_author_valid.join(
', '
)}`
)
// #endregion
// #region author_name, author_email
let name, email
switch (getInput('default_author')) {
case 'github_actor': {
name = process.env.GITHUB_ACTOR
email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`
break
}
case 'user_info': {
if (!getInput('author_name') || !getInput('author_email')) {
const res = await getUserInfo(process.env.GITHUB_ACTOR)
if (!res?.name)
core.warning("Couldn't fetch author name, filling with github_actor.")
if (!res?.email)
core.warning(
"Couldn't fetch author email, filling with github_actor."
)
res?.name && (name = res?.name)
res?.email && (email = res.email)
if (name && email) break
}
!name && (name = process.env.GITHUB_ACTOR)
!email && (email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`)
break
}
case 'github_actions': {
name = 'github-actions'
email = '41898282+github-actions[bot]@users.noreply.github.com'
break
}
default:
throw new Error(
'This should not happen, please contact the author of this action. (checkInputs.author)'
)
}
setDefault('author_name', name)
setDefault('author_email', email)
core.info(
`> Using '${getInput('author_name')} <${getInput(
'author_email'
)}>' as author.`
)
// #endregion
// #region committer_name, committer_email
if (getInput('committer_name') || getInput('committer_email'))
core.info(
`> Using custom committer info: ${
getInput('committer_name') ||
getInput('author_name') + ' [from author info]'
} <${
getInput('committer_email') ||
getInput('author_email') + ' [from author info]'
}>`
)
setDefault('committer_name', getInput('author_name'))
setDefault('committer_email', getInput('author_email'))
core.debug(
`Committer: ${getInput('committer_name')} <${getInput('committer_email')}>`
)
// #endregion
// #region message
setDefault(
'message',
`Commit from GitHub Actions (${process.env.GITHUB_WORKFLOW})`
)
core.info(`> Using "${getInput('message')}" as commit message.`)
// #endregion
// #region branch
const branch = setDefault('branch', defaultBranch || '')
if (isPR)
core.info(`> Running for a PR, the action will use '${branch}' as ref.`)
// #endregion
// #region branch_mode
const branch_mode_valid = ['throw', 'create']
if (!branch_mode_valid.includes(getInput('branch_mode')))
throw new Error(
`"${getInput(
'branch_mode'
)}" is not a valid value for the 'branch_mode' input. Valid values are: ${branch_mode_valid.join(
', '
)}`
)
// #endregion
// #region pathspec_error_handling
const peh_valid = ['ignore', 'exitImmediately', 'exitAtEnd']
if (!peh_valid.includes(getInput('pathspec_error_handling')))
throw new Error(
`"${getInput(
'pathspec_error_handling'
)}" is not a valid value for the 'pathspec_error_handling' input. Valid values are: ${peh_valid.join(
', '
)}`
)
// #endregion
// #region pull, pull_strategy [deprecated]
if (getInput('pull') && getInput('pull_strategy'))
throw new Error(
"You can't use both pull and pull_strategy as action inputs. Please remove pull_strategy, which is deprecated."
)
if ([getInput('pull'), getInput('pull_strategy')].includes('NO-PULL'))
core.debug("NO-PULL found: won't pull from remote.")
// #endregion
// #region push
if (getInput('push')) {
// It has to be either 'true', 'false', or any other string (use as arguments)
let value: string | boolean
try {
value = getInput('push', true)
} catch {
value = getInput('push')
}
core.debug(`Current push option: '${value}' (parsed as ${typeof value})`)
}
// #endregion
// #region signoff
if (getInput('signoff')) {
const parsed = getInput('signoff', true)
if (parsed === undefined)
throw new Error(
`"${getInput(
'signoff'
)}" is not a valid value for the 'signoff' input: only "true" and "false" are allowed.`
)
if (!parsed) setInput('signoff', undefined)
core.debug(
`Current signoff option: ${getInput('signoff')} (${typeof getInput(
'signoff'
)})`
)
}
// #endregion
// #region github_token
if (!getInput('github_token'))
core.warning(
'No github_token has been detected, the action may fail if it needs to use the API'
)
// #endregion
}
async function add(
ignoreErrors: 'all' | 'pathspec' | 'none' = 'none'
): Promise<(void | Response<void>)[]> {
@@ -516,44 +277,3 @@ async function remove(
return res
}
/**
* Tries to parse a JSON array, then a YAML array.
* If both fail, it returns an array containing the input value as its only element
*/
function parseInputArray(input: string): string[] {
try {
const json = JSON.parse(input)
if (
json &&
Array.isArray(json) &&
json.every((e) => typeof e == 'string')
) {
core.debug(`Input parsed as JSON array of length ${json.length}`)
return json
}
} catch {}
try {
const yaml = YAML.load(input)
if (
yaml &&
Array.isArray(yaml) &&
yaml.every((e) => typeof e == 'string')
) {
core.debug(`Input parsed as YAML array of length ${yaml.length}`)
return yaml
}
} catch {}
core.debug('Input parsed as single string')
return [input]
}
function logOutputs() {
core.startGroup('Outputs')
for (const key in outputs) {
core.info(`${key}: ${outputs[key]}`)
}
core.endGroup()
}

View File

@@ -1,45 +1,9 @@
import { parseArgsStringToArgv } from 'string-argv'
import * as core from '@actions/core'
import YAML from 'js-yaml'
import { Toolkit } from 'actions-toolkit'
import fs from 'fs'
interface InputTypes {
add: string
author_name: string
author_email: string
branch: string
branch_mode: 'throw' | 'create'
committer_name: string
committer_email: string
cwd: string
default_author: 'github_actor' | 'user_info' | 'github_actions'
message: string
pathspec_error_handling: 'ignore' | 'exitImmediately' | 'exitAtEnd'
pull: string | undefined
pull_strategy: string | undefined
push: string
remove: string | undefined
signoff: undefined
tag: string | undefined
github_token: string | undefined
}
export type input = keyof InputTypes
interface OutputTypes {
committed: 'true' | 'false'
commit_sha: string | undefined
pushed: 'true' | 'false'
tagged: 'true' | 'false'
}
export type output = keyof OutputTypes
export const outputs: OutputTypes = {
committed: 'false',
commit_sha: undefined,
pushed: 'false',
tagged: 'false'
}
import { input, output } from './io'
type RecordOf<T extends string> = Record<T, string | undefined>
export const tools = new Toolkit<RecordOf<input>, RecordOf<output>>({
@@ -51,20 +15,6 @@ export const tools = new Toolkit<RecordOf<input>, RecordOf<output>>({
]
})
export function getInput<T extends input>(name: T, parseAsBool: true): boolean
export function getInput<T extends input>(
name: T,
parseAsBool?: false
): InputTypes[T]
export function getInput<T extends input>(
name: T,
parseAsBool = false
): InputTypes[T] | boolean {
if (parseAsBool) return core.getBooleanInput(name)
// @ts-expect-error
return core.getInput(name)
}
export async function getUserInfo(username?: string) {
if (!username) return undefined
@@ -118,6 +68,39 @@ export function matchGitArgs(string: string) {
return parsed
}
/**
* Tries to parse a JSON array, then a YAML array.
* If both fail, it returns an array containing the input value as its only element
*/
export function parseInputArray(input: string): string[] {
try {
const json = JSON.parse(input)
if (
json &&
Array.isArray(json) &&
json.every((e) => typeof e == 'string')
) {
core.debug(`Input parsed as JSON array of length ${json.length}`)
return json
}
} catch {}
try {
const yaml = YAML.load(input)
if (
yaml &&
Array.isArray(yaml) &&
yaml.every((e) => typeof e == 'string')
) {
core.debug(`Input parsed as YAML array of length ${yaml.length}`)
return yaml
}
} catch {}
core.debug('Input parsed as single string')
return [input]
}
export function readJSON(filePath: string) {
let fileContent: string
try {
@@ -132,12 +115,3 @@ export function readJSON(filePath: string) {
throw `Couldn't parse file to JSON. File path: ${filePath}`
}
}
export function setOutput<T extends output>(name: T, value: OutputTypes[T]) {
core.debug(`Setting output: ${name}=${value}`)
outputs[name] = value
core.setOutput(name, value)
}
// Setup default output values
Object.entries(outputs).forEach(([name, value]) => core.setOutput(name, value))