├── .husky ├── .gitignore └── pre-commit ├── .gitignore ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── config.yml │ ├── blank-issue.md │ ├── question.md │ └── bug_report.md ├── workflows │ ├── stale.yml │ ├── versioning.yml │ ├── label-sync.yml │ ├── codesee-arch-diagram.yml │ ├── test.yml │ ├── export-labels.yml │ └── codeql-analysis.yml ├── FUNDING.yml ├── dependabot.yml └── labels.yml ├── .prettierrc ├── CONTRIBUTING.md ├── .eslintrc.js ├── .devcontainer └── devcontainer.json ├── LICENSE ├── package.json ├── action.yml ├── src ├── util.ts ├── io.ts └── main.ts ├── tsconfig.json ├── CODE_OF_CONDUCT.md ├── .all-contributorsrc └── README.md /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | build 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | lib/* linguist-generated 3 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | npm run build 5 | git add lib 6 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "tabWidth": 2, 5 | "useTabs": false, 6 | "trailingComma": "none" 7 | } 8 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/blank-issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Blank issue 3 | about: Just a blank template 4 | title: '' 5 | labels: 'status: pending' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Ask a question on how to use the action 4 | title: '' 5 | labels: 'type: question' 6 | assignees: '' 7 | 8 | --- 9 | 10 | 11 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: 'Handle stale issues and PR' 2 | on: 3 | schedule: 4 | - cron: '00 5,17 * * *' 5 | workflow_dispatch: 6 | 7 | jobs: 8 | stale: 9 | uses: EndBug/workflows/.github/workflows/stale.yml@main 10 | -------------------------------------------------------------------------------- /.github/workflows/versioning.yml: -------------------------------------------------------------------------------- 1 | name: Update tags 2 | 3 | on: 4 | release: 5 | types: [published, edited] 6 | 7 | jobs: 8 | actions-tagger: 9 | runs-on: windows-2022 10 | steps: 11 | - uses: Actions-R-Us/actions-tagger@v2 12 | with: 13 | publish_latest_tag: true 14 | -------------------------------------------------------------------------------- /.github/workflows/label-sync.yml: -------------------------------------------------------------------------------- 1 | name: Sync labels 2 | on: 3 | push: 4 | branches: 5 | - main 6 | paths: 7 | - '.github/labels.yml' 8 | workflow_dispatch: 9 | 10 | jobs: 11 | sync: 12 | name: Run EndBug/label-sync 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v4 16 | - uses: EndBug/label-sync@v2 17 | with: 18 | config-file: '.github/labels.yml' 19 | -------------------------------------------------------------------------------- /.github/workflows/codesee-arch-diagram.yml: -------------------------------------------------------------------------------- 1 | # This workflow was added by CodeSee. Learn more at https://codesee.io/ 2 | # This is v2.0 of this workflow file 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request_target: 8 | types: [opened, synchronize, reopened] 9 | 10 | name: CodeSee 11 | 12 | permissions: read-all 13 | 14 | jobs: 15 | codesee: 16 | runs-on: ubuntu-latest 17 | continue-on-error: true 18 | name: Analyze the repo with CodeSee 19 | steps: 20 | - uses: Codesee-io/codesee-action@v2 21 | with: 22 | codesee-token: ${{ secrets.CODESEE_ARCH_DIAG_API_TOKEN }} 23 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | on: 3 | push: 4 | pull_request: 5 | workflow_dispatch: 6 | 7 | jobs: 8 | build: 9 | name: Build 10 | runs-on: ubuntu-20.04 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: actions/setup-node@v3 14 | with: 15 | cache: npm 16 | - run: npm ci 17 | - run: npm run build 18 | 19 | lint: 20 | name: Lint 21 | runs-on: ubuntu-20.04 22 | steps: 23 | - uses: actions/checkout@v4 24 | - uses: actions/setup-node@v3 25 | with: 26 | cache: npm 27 | - run: npm ci 28 | - run: npm run lint 29 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [endbug] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | If you want to contribute to this project, check out this steps! 4 | 5 | 1. Check out existing features to make sure your case is not already covered. Also, try [searching open or closed issues](https://github.com/EndBug/add-and-commit/issues) that may cover the same topic. 6 | 2. Either [open a new issue](https://github.com/EndBug/add-and-commit/issues/new/choose) or comment on an existing one to let everyone know what you're working on. 7 | 3. Edit the source files to implement your feature or fix. 8 | 4. Build the action and test it in a test repo. 9 | 5. Update the [action manifest](./action.yml) AND the [README](./README.md) with your changes. 10 | 6. [Open a PR](https://github.com/EndBug/add-and-commit/compare). 11 | 12 | Thanks! 💖 13 | 14 | -------------------------------------------------------------------------------- /.github/workflows/export-labels.yml: -------------------------------------------------------------------------------- 1 | name: Export label config 2 | on: 3 | # You can run this with every event, but it's better to run it only when you actually need it. 4 | workflow_dispatch: 5 | 6 | jobs: 7 | labels: 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - uses: EndBug/export-label-config@main 12 | with: 13 | # This is needed if you're dealing with private repos. 14 | token: ${{ secrets.GITHUB_TOKEN }} 15 | 16 | # Set this to `true` if you want to get the raw API reponse. Defaults to `false`. 17 | raw-result: false 18 | 19 | # By default every label entry will have an `aliases` property set to an empty array. 20 | # It's for EndBug/label-sync, if you don't want it you cans set this to `false` 21 | add-aliases: true 22 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | commonjs: true, 4 | es6: true, 5 | node: true 6 | }, 7 | extends: ['eslint:recommended', 'plugin:prettier/recommended'], 8 | globals: {}, 9 | parser: '@typescript-eslint/parser', 10 | parserOptions: { 11 | ecmaVersion: 6, 12 | sourceType: 'module' 13 | }, 14 | plugins: ['@typescript-eslint'], 15 | ignorePatterns: ['lib/*'], 16 | rules: { 17 | 'prettier/prettier': 'warn', 18 | 'no-cond-assign': [2, 'except-parens'], 19 | 'no-unused-vars': 0, 20 | 'no-redeclare': 0, 21 | '@typescript-eslint/no-unused-vars': 1, 22 | 'no-empty': [ 23 | 'error', 24 | { 25 | allowEmptyCatch: true 26 | } 27 | ], 28 | 'prefer-const': [ 29 | 'warn', 30 | { 31 | destructuring: 'all' 32 | } 33 | ], 34 | 'spaced-comment': 'warn' 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: 'npm' # See documentation for possible values 9 | directory: '/' # Location of package manifests 10 | schedule: 11 | interval: 'weekly' 12 | commit-message: 13 | prefix: 'chore' 14 | include: 'scope' 15 | labels: 16 | - 'type: chore' 17 | - package-ecosystem: github-actions 18 | directory: / 19 | schedule: 20 | interval: weekly 21 | open-pull-requests-limit: 10 22 | commit-message: 23 | include: scope 24 | prefix: ci 25 | labels: 26 | - 'type: chore' 27 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Report an issue with the action 4 | title: '' 5 | labels: 'status: pending' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. If a particular error is shown 12 | 13 | **Workflow used** 14 | Provide a snippet of the workflow and/or a link to it (use the commit sha as the ref when you link it, so that it's not influenced by other changes). If you only share a section of the workflow, make sure it includes the step that uses the action! 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Logs** 20 | Either provide a link to the action run or (if your repo is private) paste here the logs from the step that uses it. If you paste the logs, please use this template, and remember to paste the logs from all the different sections. 21 |
22 | Logs 23 |
Your logs here.
24 |
25 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/ubuntu 3 | { 4 | "name": "Ubuntu", 5 | // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile 6 | "image": "mcr.microsoft.com/devcontainers/base:jammy", 7 | "features": { 8 | "ghcr.io/devcontainers/features/github-cli:1": {}, 9 | "ghcr.io/devcontainers/features/node:1": {} 10 | } 11 | // Features to add to the dev container. More info: https://containers.dev/features. 12 | // "features": {}, 13 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 14 | // "forwardPorts": [], 15 | // Use 'postCreateCommand' to run commands after the container is created. 16 | // "postCreateCommand": "uname -a", 17 | // Configure tool-specific properties. 18 | // "customizations": {}, 19 | // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. 20 | // "remoteUser": "root" 21 | } 22 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Federico Grandi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "add-and-commit", 3 | "version": "9.1.3", 4 | "private": true, 5 | "description": "Add & commit files from a path directly from GitHub Actions", 6 | "main": "lib/index.js", 7 | "scripts": { 8 | "build": "ncc build src/main.ts --minify --out lib", 9 | "watch": "ncc build src/main.ts --watch --out lib", 10 | "lint": "eslint --ext .ts src", 11 | "lint:fix": "eslint --ext .ts --fix src", 12 | "prepare": "husky install", 13 | "test": "echo \"Error: no test specified\" && exit 1" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "git+https://github.com/EndBug/add-and-commit.git" 18 | }, 19 | "keywords": [ 20 | "github", 21 | "action", 22 | "version", 23 | "npm", 24 | "node" 25 | ], 26 | "author": "Federico Grandi ", 27 | "license": "MIT", 28 | "bugs": { 29 | "url": "https://github.com/EndBug/add-and-commit/issues" 30 | }, 31 | "homepage": "https://github.com/EndBug/add-and-commit#readme", 32 | "dependencies": { 33 | "@actions/core": "^1.10.1", 34 | "actions-toolkit": "github:EndBug/actions-toolkit#core-actions", 35 | "js-yaml": "^4.1.0", 36 | "simple-git": "^3.18.0", 37 | "string-argv": "^0.3.2" 38 | }, 39 | "devDependencies": { 40 | "@types/js-yaml": "^4.0.6", 41 | "@types/node": "^12.12.54", 42 | "@typescript-eslint/eslint-plugin": "^6.7.0", 43 | "@typescript-eslint/parser": "^6.7.2", 44 | "@vercel/ncc": "^0.38.0", 45 | "all-contributors-cli": "^6.26.1", 46 | "eslint": "^8.48.0", 47 | "eslint-config-prettier": "^9.0.0", 48 | "eslint-plugin-prettier": "^5.0.0", 49 | "husky": "^8.0.3", 50 | "prettier": "^3.0.3", 51 | "typescript": "^5.2.2" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /.github/labels.yml: -------------------------------------------------------------------------------- 1 | - name: 'good first issue' 2 | color: '5319e7' 3 | description: 'Good for newcomers' 4 | aliases: [] 5 | 6 | - name: 'help wanted' 7 | color: '008672' 8 | description: 'Extra attention is needed' 9 | aliases: [] 10 | 11 | - name: 'status: pending' 12 | color: c5def5 13 | description: 'More info is needed before deciding what to do' 14 | aliases: [] 15 | 16 | - name: 'status: pinned' 17 | color: 0052cc 18 | description: 'Should not be labeled as stale' 19 | aliases: [] 20 | 21 | - name: 'status: stale' 22 | color: fbca04 23 | description: 'Inactive issues and PRs' 24 | aliases: ['stale'] 25 | 26 | - name: 'status: wontfix' 27 | color: cfd3d7 28 | description: 'This will not be worked on' 29 | aliases: ['wontfix'] 30 | 31 | - name: 'type: bug' 32 | color: d73a4a 33 | description: 'Verified problems that need to be worked on' 34 | aliases: ['bug'] 35 | 36 | - name: 'type: chore' 37 | color: C5DEF5 38 | description: 'Code changes that neither fix bugs nor add features (refactoring, dependency chnages, ...)' 39 | aliases: ['dependencies', 'type: dependencies', 'automation', 'type: automation'] 40 | 41 | - name: 'type: docs' 42 | color: C5DEF5 43 | description: "Documentation changes" 44 | aliases: ['documentation', 'maintenance', 'type: maintenance'] 45 | 46 | - name: 'type: duplicate' 47 | color: cfd3d7 48 | description: 'This issue or pull request already exists' 49 | aliases: ['duplicate'] 50 | 51 | - name: 'type: feature' 52 | color: 0E8A16 53 | description: 'New feature or feature request' 54 | aliases: ['enhancement', 'type: enhancement'] 55 | 56 | - name: 'type: fix' 57 | color: 1D76DB 58 | description: 'Updates to existing functionalities' 59 | aliases: ['fix'] 60 | 61 | - name: 'type: invalid' 62 | color: e4e669 63 | description: "This doesn't seem right" 64 | aliases: ['invalid'] 65 | 66 | - name: 'type: not a bug' 67 | color: 0e8a16 68 | description: 'Reports that happen not be our fault' 69 | aliases: ['not a bug'] 70 | 71 | - name: 'type: question' 72 | color: d876e3 73 | description: 'Further information is requested' 74 | aliases: ['question'] 75 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ main ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ main ] 20 | schedule: 21 | - cron: '40 12 * * 2' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | steps: 33 | - name: Checkout repository 34 | uses: actions/checkout@v4 35 | 36 | # Initializes the CodeQL tools for scanning. 37 | - name: Initialize CodeQL 38 | uses: github/codeql-action/init@v2 39 | # Override language selection by uncommenting this and choosing your languages 40 | # with: 41 | # languages: go, javascript, csharp, python, cpp, java 42 | 43 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 44 | # If this step fails, then you should remove it and run the build manually (see below). 45 | - name: Autobuild 46 | uses: github/codeql-action/autobuild@v2 47 | 48 | # ℹ️ Command-line programs to run using the OS shell. 49 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 50 | 51 | # ✏️ If the Autobuild fails above, remove it and uncomment the following 52 | # three lines and modify them (or add more) to build your code if your 53 | # project uses a compiled language 54 | 55 | #- run: | 56 | # make bootstrap 57 | # make release 58 | 59 | - name: Perform CodeQL Analysis 60 | uses: github/codeql-action/analyze@v2 61 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | name: Add & Commit 2 | description: Automatically commit changes made in your workflow run directly to your repo 3 | 4 | inputs: 5 | add: 6 | description: Arguments for the git add command 7 | required: false 8 | default: '.' 9 | author_name: 10 | description: The name of the user that will be displayed as the author of the commit 11 | required: false 12 | author_email: 13 | description: The email of the user that will be displayed as the author of the commit 14 | required: false 15 | commit: 16 | description: Additional arguments for the git commit command 17 | required: false 18 | committer_name: 19 | description: The name of the custom committer you want to use 20 | required: false 21 | committer_email: 22 | description: The email of the custom committer you want to use 23 | required: false 24 | cwd: 25 | description: The directory where your repository is located. You should use actions/checkout first to set it up 26 | required: false 27 | default: '.' 28 | default_author: 29 | description: How the action should fill missing author name or email. 30 | required: false 31 | default: 'github_actor' 32 | fetch: 33 | description: Arguments for the git fetch command (if 'false', the action won't fetch the repo) 34 | required: false 35 | default: --tags --force 36 | message: 37 | description: The message for the commit 38 | required: false 39 | new_branch: 40 | description: The name of the branch to create. 41 | required: false 42 | pathspec_error_handling: 43 | description: The way the action should handle pathspec errors from the add and remove commands. 44 | required: false 45 | default: ignore 46 | pull: 47 | description: Arguments for the git pull command. By default, the action does not pull. 48 | required: false 49 | push: 50 | 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) 51 | required: false 52 | default: 'true' 53 | remove: 54 | description: Arguments for the git rm command 55 | required: false 56 | tag: 57 | description: Arguments for the git tag command (the tag name always needs to be the first word not preceded by a hyphen) 58 | required: false 59 | tag_push: 60 | description: Arguments for the git push --tags command (any additional argument will be added after --tags) 61 | required: false 62 | 63 | # Input not required from the user 64 | github_token: 65 | description: The token used to make requests to the GitHub API. It's NOT used to make commits and should not be changed. 66 | required: false 67 | default: ${{ github.token }} 68 | 69 | outputs: 70 | committed: 71 | description: Whether the action has created a commit. 72 | commit_long_sha: 73 | description: The complete SHA of the commit that has been created. 74 | commit_sha: 75 | description: The short SHA of the commit that has been created. 76 | pushed: 77 | description: Whether the action has pushed to the remote. 78 | tagged: 79 | description: Whether the action has created a tag. 80 | tag_pushed: 81 | description: Whether the action has pushed a tag. 82 | 83 | runs: 84 | using: node16 85 | main: lib/index.js 86 | 87 | branding: 88 | icon: git-commit 89 | color: gray-dark 90 | -------------------------------------------------------------------------------- /src/util.ts: -------------------------------------------------------------------------------- 1 | import { parseArgsStringToArgv } from 'string-argv' 2 | import * as core from '@actions/core' 3 | import YAML from 'js-yaml' 4 | import { Toolkit } from 'actions-toolkit' 5 | import fs from 'fs' 6 | import { input, output } from './io' 7 | 8 | type RecordOf = Record 9 | export const tools = new Toolkit, RecordOf>({ 10 | secrets: [ 11 | 'GITHUB_EVENT_PATH', 12 | 'GITHUB_EVENT_NAME', 13 | 'GITHUB_REF', 14 | 'GITHUB_ACTOR' 15 | ] 16 | }) 17 | 18 | export async function getUserInfo(username?: string) { 19 | if (!username) return undefined 20 | 21 | const res = await tools.github.users.getByUsername({ username }) 22 | 23 | core.debug( 24 | `Fetched github actor from the API: ${JSON.stringify(res?.data, null, 2)}` 25 | ) 26 | 27 | return { 28 | name: res?.data?.name, 29 | email: res?.data?.email 30 | } 31 | } 32 | 33 | export function log(err: any | Error, data?: any) { 34 | if (data) console.log(data) 35 | if (err) core.error(err) 36 | } 37 | 38 | /** 39 | * Matches the given string to an array of arguments. 40 | * The parsing is made by `string-argv`: if your way of using argument is not supported, the issue is theirs! 41 | * {@link https://www.npm.im/string-argv} 42 | * @example 43 | * ```js 44 | * matchGitArgs(` 45 | -s 46 | --longOption 'This uses the "other" quotes' 47 | --foo 1234 48 | --file=message.txt 49 | --file2="Application 'Support'/\"message\".txt" 50 | `) => [ 51 | '-s', 52 | '--longOption', 53 | 'This uses the "other" quotes', 54 | '--foo', 55 | '1234', 56 | '--file=message.txt', 57 | `--file2="Application 'Support'/\\"message\\".txt"` 58 | ] 59 | * matchGitArgs(' ') => [ ] 60 | * ``` 61 | * @returns An array, if there's no match it'll be empty 62 | */ 63 | export function matchGitArgs(string: string) { 64 | const parsed = parseArgsStringToArgv(string) 65 | core.debug(`Git args parsed: 66 | - Original: ${string} 67 | - Parsed: ${JSON.stringify(parsed)}`) 68 | return parsed 69 | } 70 | 71 | /** 72 | * Tries to parse a JSON array, then a YAML array. 73 | * If both fail, it returns an array containing the input value as its only element 74 | */ 75 | export function parseInputArray(input: string): string[] { 76 | try { 77 | const json = JSON.parse(input) 78 | if ( 79 | json && 80 | Array.isArray(json) && 81 | json.every((e) => typeof e == 'string') 82 | ) { 83 | core.debug(`Input parsed as JSON array of length ${json.length}`) 84 | return json 85 | } 86 | } catch {} 87 | 88 | try { 89 | const yaml = YAML.load(input) 90 | if ( 91 | yaml && 92 | Array.isArray(yaml) && 93 | yaml.every((e) => typeof e == 'string') 94 | ) { 95 | core.debug(`Input parsed as YAML array of length ${yaml.length}`) 96 | return yaml 97 | } 98 | } catch {} 99 | 100 | core.debug('Input parsed as single string') 101 | return [input] 102 | } 103 | 104 | export function readJSON(filePath: string) { 105 | let fileContent: string 106 | try { 107 | fileContent = fs.readFileSync(filePath, { encoding: 'utf8' }) 108 | } catch { 109 | throw `Couldn't read file. File path: ${filePath}` 110 | } 111 | 112 | try { 113 | return JSON.parse(fileContent) 114 | } catch { 115 | throw `Couldn't parse file to JSON. File path: ${filePath}` 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Basic Options */ 4 | // "incremental": true, /* Enable incremental compilation */ 5 | "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ 6 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ 7 | // "allowJs": true, /* Allow javascript files to be compiled. */ 8 | // "checkJs": true, /* Report errors in .js files. */ 9 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 10 | // "declaration": true, /* Generates corresponding '.d.ts' file. */ 11 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 12 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 13 | // "outFile": "./", /* Concatenate and emit output to single file. */ 14 | "outDir": "./build", /* Redirect output structure to the directory. */ 15 | "rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 16 | // "composite": true, /* Enable project compilation */ 17 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 18 | // "removeComments": true, /* Do not emit comments to output. */ 19 | // "noEmit": true, /* Do not emit outputs. */ 20 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 21 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 22 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 23 | /* Strict Type-Checking Options */ 24 | "strict": true, /* Enable all strict type-checking options. */ 25 | "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ 26 | // "strictNullChecks": true, /* Enable strict null checks. */ 27 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 28 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 29 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 30 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 31 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 32 | /* Additional Checks */ 33 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 34 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 35 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 36 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 37 | /* Module Resolution Options */ 38 | "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 39 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 40 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 41 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 42 | // "typeRoots": [], /* List of folders to include type definitions from. */ 43 | // "types": [], /* Type declaration files to be included in compilation. */ 44 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 45 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 46 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 47 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 48 | /* Source Map Options */ 49 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 50 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 51 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 52 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 53 | /* Experimental Options */ 54 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 55 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 56 | }, 57 | "exclude": [ 58 | "node_modules", 59 | "**/*.test.ts", 60 | "scripts" 61 | ] 62 | } 63 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | fgrandi30@gmail.com. 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | 121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct 122 | enforcement ladder](https://github.com/mozilla/diversity). 123 | 124 | [homepage]: https://www.contributor-covenant.org 125 | 126 | For answers to common questions about this code of conduct, see the FAQ at 127 | https://www.contributor-covenant.org/faq. Translations are available at 128 | https://www.contributor-covenant.org/translations. 129 | -------------------------------------------------------------------------------- /src/io.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import { getUserInfo, parseInputArray } from './util' 3 | 4 | interface InputTypes { 5 | add: string 6 | author_name: string 7 | author_email: string 8 | commit: string | undefined 9 | committer_name: string 10 | committer_email: string 11 | cwd: string 12 | default_author: 'github_actor' | 'user_info' | 'github_actions' 13 | fetch: string 14 | message: string 15 | new_branch: string | undefined 16 | pathspec_error_handling: 'ignore' | 'exitImmediately' | 'exitAtEnd' 17 | pull: string | undefined 18 | push: string 19 | remove: string | undefined 20 | tag: string | undefined 21 | tag_push: string | undefined 22 | 23 | github_token: string | undefined 24 | } 25 | export type input = keyof InputTypes 26 | 27 | interface OutputTypes { 28 | committed: 'true' | 'false' 29 | commit_long_sha: string | undefined 30 | commit_sha: string | undefined 31 | pushed: 'true' | 'false' 32 | tagged: 'true' | 'false' 33 | tag_pushed: 'true' | 'false' 34 | } 35 | export type output = keyof OutputTypes 36 | 37 | export const outputs: OutputTypes = { 38 | committed: 'false', 39 | commit_long_sha: undefined, 40 | commit_sha: undefined, 41 | pushed: 'false', 42 | tagged: 'false', 43 | tag_pushed: 'false' 44 | } 45 | // Setup default output values 46 | Object.entries(outputs).forEach(([name, value]) => core.setOutput(name, value)) 47 | 48 | export function getInput(name: T, parseAsBool: true): boolean 49 | export function getInput( 50 | name: T, 51 | parseAsBool?: false 52 | ): InputTypes[T] 53 | export function getInput( 54 | name: T, 55 | parseAsBool = false 56 | ): InputTypes[T] | boolean { 57 | if (parseAsBool) return core.getBooleanInput(name) 58 | // @ts-expect-error 59 | return core.getInput(name) 60 | } 61 | 62 | export function setOutput(name: T, value: OutputTypes[T]) { 63 | core.debug(`Setting output: ${name}=${value}`) 64 | outputs[name] = value 65 | core.setOutput(name, value) 66 | } 67 | 68 | export function logOutputs() { 69 | core.startGroup('Outputs') 70 | for (const key in outputs) { 71 | core.info(`${key}: ${outputs[key]}`) 72 | } 73 | core.endGroup() 74 | } 75 | 76 | export async function checkInputs() { 77 | function setInput(input: input, value: string | undefined) { 78 | if (value) return (process.env[`INPUT_${input.toUpperCase()}`] = value) 79 | else return delete process.env[`INPUT_${input.toUpperCase()}`] 80 | } 81 | function setDefault(input: input, value: string) { 82 | if (!getInput(input)) setInput(input, value) 83 | return getInput(input) 84 | } 85 | 86 | // #region add, remove 87 | if (!getInput('add') && !getInput('remove')) 88 | throw new Error( 89 | "Both 'add' and 'remove' are empty, the action has nothing to do." 90 | ) 91 | 92 | if (getInput('add')) { 93 | const parsed = parseInputArray(getInput('add')) 94 | if (parsed.length == 1) 95 | core.info('Add input parsed as single string, running 1 git add command.') 96 | else if (parsed.length > 1) 97 | core.info( 98 | `Add input parsed as string array, running ${parsed.length} git add commands.` 99 | ) 100 | else core.setFailed('Add input: array length < 1') 101 | } 102 | if (getInput('remove')) { 103 | const parsed = parseInputArray(getInput('remove') || '') 104 | if (parsed.length == 1) 105 | core.info( 106 | 'Remove input parsed as single string, running 1 git rm command.' 107 | ) 108 | else if (parsed.length > 1) 109 | core.info( 110 | `Remove input parsed as string array, running ${parsed.length} git rm commands.` 111 | ) 112 | else core.setFailed('Remove input: array length < 1') 113 | } 114 | // #endregion 115 | 116 | // #region default_author 117 | const default_author_valid = ['github_actor', 'user_info', 'github_actions'] 118 | if (!default_author_valid.includes(getInput('default_author'))) 119 | throw new Error( 120 | `'${getInput( 121 | 'default_author' 122 | )}' is not a valid value for default_author. Valid values: ${default_author_valid.join( 123 | ', ' 124 | )}` 125 | ) 126 | // #endregion 127 | 128 | // #region fetch 129 | if (getInput('fetch')) { 130 | let value: string | boolean 131 | 132 | try { 133 | value = getInput('fetch', true) 134 | } catch { 135 | value = getInput('fetch') 136 | } 137 | 138 | core.debug(`Current fetch option: '${value}' (parsed as ${typeof value})`) 139 | } 140 | // #endregion 141 | 142 | // #region author_name, author_email 143 | let name, email 144 | switch (getInput('default_author')) { 145 | case 'github_actor': { 146 | name = process.env.GITHUB_ACTOR 147 | email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com` 148 | break 149 | } 150 | 151 | case 'user_info': { 152 | if (!getInput('author_name') || !getInput('author_email')) { 153 | const res = await getUserInfo(process.env.GITHUB_ACTOR) 154 | if (!res?.name) 155 | core.warning("Couldn't fetch author name, filling with github_actor.") 156 | if (!res?.email) 157 | core.warning( 158 | "Couldn't fetch author email, filling with github_actor." 159 | ) 160 | 161 | res?.name && (name = res?.name) 162 | res?.email && (email = res.email) 163 | if (name && email) break 164 | } 165 | 166 | !name && (name = process.env.GITHUB_ACTOR) 167 | !email && (email = `${process.env.GITHUB_ACTOR}@users.noreply.github.com`) 168 | break 169 | } 170 | 171 | case 'github_actions': { 172 | name = 'github-actions' 173 | email = '41898282+github-actions[bot]@users.noreply.github.com' 174 | break 175 | } 176 | 177 | default: 178 | throw new Error( 179 | 'This should not happen, please contact the author of this action. (checkInputs.author)' 180 | ) 181 | } 182 | 183 | setDefault('author_name', name) 184 | setDefault('author_email', email) 185 | core.info( 186 | `> Using '${getInput('author_name')} <${getInput( 187 | 'author_email' 188 | )}>' as author.` 189 | ) 190 | // #endregion 191 | 192 | // #region committer_name, committer_email 193 | if (getInput('committer_name') || getInput('committer_email')) 194 | core.info( 195 | `> Using custom committer info: ${ 196 | getInput('committer_name') || 197 | getInput('author_name') + ' [from author info]' 198 | } <${ 199 | getInput('committer_email') || 200 | getInput('author_email') + ' [from author info]' 201 | }>` 202 | ) 203 | 204 | setDefault('committer_name', getInput('author_name')) 205 | setDefault('committer_email', getInput('author_email')) 206 | core.debug( 207 | `Committer: ${getInput('committer_name')} <${getInput('committer_email')}>` 208 | ) 209 | // #endregion 210 | 211 | // #region message 212 | setDefault( 213 | 'message', 214 | `Commit from GitHub Actions (${process.env.GITHUB_WORKFLOW})` 215 | ) 216 | core.info(`> Using "${getInput('message')}" as commit message.`) 217 | // #endregion 218 | 219 | // #region pathspec_error_handling 220 | const peh_valid = ['ignore', 'exitImmediately', 'exitAtEnd'] 221 | if (!peh_valid.includes(getInput('pathspec_error_handling'))) 222 | throw new Error( 223 | `"${getInput( 224 | 'pathspec_error_handling' 225 | )}" is not a valid value for the 'pathspec_error_handling' input. Valid values are: ${peh_valid.join( 226 | ', ' 227 | )}` 228 | ) 229 | // #endregion 230 | 231 | // #region pull 232 | if (getInput('pull') == 'NO-PULL') 233 | core.warning( 234 | "`NO-PULL` is a legacy option for the `pull` input. If you don't want the action to pull the repo, simply remove this input." 235 | ) 236 | // #endregion 237 | 238 | // #region push 239 | if (getInput('push')) { 240 | // It has to be either 'true', 'false', or any other string (use as arguments) 241 | let value: string | boolean 242 | 243 | try { 244 | value = getInput('push', true) 245 | } catch { 246 | value = getInput('push') 247 | } 248 | 249 | core.debug(`Current push option: '${value}' (parsed as ${typeof value})`) 250 | } 251 | // #endregion 252 | 253 | // #region github_token 254 | if (!getInput('github_token')) 255 | core.warning( 256 | 'No github_token has been detected, the action may fail if it needs to use the API' 257 | ) 258 | // #endregion 259 | } 260 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import * as core from '@actions/core' 2 | import path from 'path' 3 | import simpleGit, { Response } from 'simple-git' 4 | import { checkInputs, getInput, logOutputs, setOutput } from './io' 5 | import { log, matchGitArgs, parseInputArray } from './util' 6 | 7 | const baseDir = path.join(process.cwd(), getInput('cwd') || '') 8 | const git = simpleGit({ baseDir }) 9 | 10 | const exitErrors: Error[] = [] 11 | 12 | core.info(`Running in ${baseDir}`) 13 | ;(async () => { 14 | await checkInputs() 15 | 16 | core.startGroup('Internal logs') 17 | core.info('> Staging files...') 18 | 19 | const ignoreErrors = 20 | getInput('pathspec_error_handling') == 'ignore' ? 'pathspec' : 'none' 21 | 22 | if (getInput('add')) { 23 | core.info('> Adding files...') 24 | await add(ignoreErrors) 25 | } else core.info('> No files to add.') 26 | 27 | if (getInput('remove')) { 28 | core.info('> Removing files...') 29 | await remove(ignoreErrors) 30 | } else core.info('> No files to remove.') 31 | 32 | core.info('> Checking for uncommitted changes in the git working tree...') 33 | const changedFiles = (await git.diffSummary(['--cached'])).files.length 34 | // continue if there are any changes or if the allow-empty commit argument is included 35 | if ( 36 | changedFiles > 0 || 37 | matchGitArgs(getInput('commit') || '').includes('--allow-empty') 38 | ) { 39 | core.info(`> Found ${changedFiles} changed files.`) 40 | core.debug( 41 | `--allow-empty argument detected: ${matchGitArgs( 42 | getInput('commit') || '' 43 | ).includes('--allow-empty')}` 44 | ) 45 | 46 | await git 47 | .addConfig('user.email', getInput('author_email'), undefined, log) 48 | .addConfig('user.name', getInput('author_name'), undefined, log) 49 | .addConfig('author.email', getInput('author_email'), undefined, log) 50 | .addConfig('author.name', getInput('author_name'), undefined, log) 51 | .addConfig('committer.email', getInput('committer_email'), undefined, log) 52 | .addConfig('committer.name', getInput('committer_name'), undefined, log) 53 | core.debug( 54 | '> Current git config\n' + 55 | JSON.stringify((await git.listConfig()).all, null, 2) 56 | ) 57 | 58 | let fetchOption: string | boolean 59 | try { 60 | fetchOption = getInput('fetch', true) 61 | } catch { 62 | fetchOption = getInput('fetch') 63 | } 64 | if (fetchOption) { 65 | core.info('> Fetching repo...') 66 | await git.fetch( 67 | matchGitArgs(fetchOption === true ? '' : fetchOption), 68 | log 69 | ) 70 | } else core.info('> Not fetching repo.') 71 | 72 | const targetBranch = getInput('new_branch') 73 | if (targetBranch) { 74 | core.info('> Checking-out branch...') 75 | 76 | if (!fetchOption) 77 | core.warning( 78 | 'Creating a new branch without fetching the repo first could result in an error when pushing to GitHub. Refer to the action README for more info about this topic.' 79 | ) 80 | 81 | await git 82 | .checkout(targetBranch) 83 | .then(() => { 84 | log(undefined, `'${targetBranch}' branch already existed.`) 85 | }) 86 | .catch(() => { 87 | log(undefined, `Creating '${targetBranch}' branch.`) 88 | return git.checkoutLocalBranch(targetBranch, log) 89 | }) 90 | } 91 | 92 | const pullOption = getInput('pull') 93 | if (pullOption) { 94 | core.info('> Pulling from remote...') 95 | core.debug(`Current git pull arguments: ${pullOption}`) 96 | await git 97 | .fetch(undefined, log) 98 | .pull(undefined, undefined, matchGitArgs(pullOption), log) 99 | 100 | core.info('> Checking for conflicts...') 101 | const status = await git.status(undefined, log) 102 | 103 | if (!status.conflicted.length) { 104 | core.info('> No conflicts found.') 105 | core.info('> Re-staging files...') 106 | if (getInput('add')) await add(ignoreErrors) 107 | if (getInput('remove')) await remove(ignoreErrors) 108 | } else 109 | throw new Error( 110 | `There are ${ 111 | status.conflicted.length 112 | } conflicting files: ${status.conflicted.join(', ')}` 113 | ) 114 | } else core.info('> Not pulling from repo.') 115 | 116 | core.info('> Creating commit...') 117 | await git 118 | .commit(getInput('message'), matchGitArgs(getInput('commit') || '')) 119 | .then(async (data) => { 120 | log(undefined, data) 121 | setOutput('committed', 'true') 122 | setOutput('commit_long_sha', data.commit) 123 | setOutput('commit_sha', data.commit.substring(0, 7)) 124 | }) 125 | .catch((err) => core.setFailed(err)) 126 | 127 | if (getInput('tag')) { 128 | core.info('> Tagging commit...') 129 | 130 | if (!fetchOption) 131 | core.warning( 132 | 'Creating a tag without fetching the repo first could result in an error when pushing to GitHub. Refer to the action README for more info about this topic.' 133 | ) 134 | 135 | await git 136 | .tag(matchGitArgs(getInput('tag') || ''), (err, data?) => { 137 | if (data) setOutput('tagged', 'true') 138 | return log(err, data) 139 | }) 140 | .then((data) => { 141 | setOutput('tagged', 'true') 142 | return log(null, data) 143 | }) 144 | .catch((err) => core.setFailed(err)) 145 | } else core.info('> No tag info provided.') 146 | 147 | let pushOption: string | boolean 148 | try { 149 | pushOption = getInput('push', true) 150 | } catch { 151 | pushOption = getInput('push') 152 | } 153 | if (pushOption) { 154 | // If the options is `true | string`... 155 | core.info('> Pushing commit to repo...') 156 | 157 | if (pushOption === true) { 158 | core.debug( 159 | `Running: git push origin ${ 160 | getInput('new_branch') || '' 161 | } --set-upstream` 162 | ) 163 | await git.push( 164 | 'origin', 165 | getInput('new_branch'), 166 | { '--set-upstream': null }, 167 | (err, data?) => { 168 | if (data) setOutput('pushed', 'true') 169 | return log(err, data) 170 | } 171 | ) 172 | } else { 173 | core.debug(`Running: git push ${pushOption}`) 174 | await git.push( 175 | undefined, 176 | undefined, 177 | matchGitArgs(pushOption), 178 | (err, data?) => { 179 | if (data) setOutput('pushed', 'true') 180 | return log(err, data) 181 | } 182 | ) 183 | } 184 | 185 | if (getInput('tag')) { 186 | core.info('> Pushing tags to repo...') 187 | 188 | await git 189 | .pushTags('origin', matchGitArgs(getInput('tag_push') || '')) 190 | .then((data) => { 191 | setOutput('tag_pushed', 'true') 192 | return log(null, data) 193 | }) 194 | .catch((err) => core.setFailed(err)) 195 | } else core.info('> No tags to push.') 196 | } else core.info('> Not pushing anything.') 197 | 198 | core.endGroup() 199 | core.info('> Task completed.') 200 | } else { 201 | core.endGroup() 202 | core.info('> Working tree clean. Nothing to commit.') 203 | } 204 | })() 205 | .then(() => { 206 | // Check for exit errors 207 | if (exitErrors.length == 1) throw exitErrors[0] 208 | else if (exitErrors.length > 1) { 209 | exitErrors.forEach((e) => core.error(e)) 210 | throw 'There have been multiple runtime errors.' 211 | } 212 | }) 213 | .then(logOutputs) 214 | .catch((e) => { 215 | core.endGroup() 216 | logOutputs() 217 | core.setFailed(e) 218 | }) 219 | 220 | async function add(ignoreErrors: 'all' | 'pathspec' | 'none' = 'none') { 221 | const input = getInput('add') 222 | if (!input) return [] 223 | 224 | const parsed = parseInputArray(input) 225 | const res: (string | void)[] = [] 226 | 227 | for (const args of parsed) { 228 | res.push( 229 | // Push the result of every git command (which are executed in order) to the array 230 | // If any of them fails, the whole function will return a Promise rejection 231 | await git 232 | .add(matchGitArgs(args), (err: any, data?: any) => 233 | log(ignoreErrors == 'all' ? null : err, data) 234 | ) 235 | .catch((e: Error) => { 236 | // if I should ignore every error, return 237 | if (ignoreErrors == 'all') return 238 | 239 | // if it's a pathspec error... 240 | if ( 241 | e.message.includes('fatal: pathspec') && 242 | e.message.includes('did not match any files') 243 | ) { 244 | if (ignoreErrors == 'pathspec') return 245 | 246 | const peh = getInput('pathspec_error_handling'), 247 | err = new Error( 248 | `Add command did not match any file: git add ${args}` 249 | ) 250 | if (peh == 'exitImmediately') throw err 251 | if (peh == 'exitAtEnd') exitErrors.push(err) 252 | } else throw e 253 | }) 254 | ) 255 | } 256 | 257 | return res 258 | } 259 | 260 | async function remove( 261 | ignoreErrors: 'all' | 'pathspec' | 'none' = 'none' 262 | ): Promise<(void | Response)[]> { 263 | const input = getInput('remove') 264 | if (!input) return [] 265 | 266 | const parsed = parseInputArray(input) 267 | const res: (void | Response)[] = [] 268 | 269 | for (const args of parsed) { 270 | res.push( 271 | // Push the result of every git command (which are executed in order) to the array 272 | // If any of them fails, the whole function will return a Promise rejection 273 | await git 274 | .rm(matchGitArgs(args), (e: any, d?: any) => 275 | log(ignoreErrors == 'all' ? null : e, d) 276 | ) 277 | .catch((e: Error) => { 278 | // if I should ignore every error, return 279 | if (ignoreErrors == 'all') return 280 | 281 | // if it's a pathspec error... 282 | if ( 283 | e.message.includes('fatal: pathspec') && 284 | e.message.includes('did not match any files') 285 | ) { 286 | if (ignoreErrors == 'pathspec') return 287 | 288 | const peh = getInput('pathspec_error_handling'), 289 | err = new Error( 290 | `Remove command did not match any file:\n git rm ${args}` 291 | ) 292 | if (peh == 'exitImmediately') throw err 293 | if (peh == 'exitAtEnd') exitErrors.push(err) 294 | } else throw e 295 | }) 296 | ) 297 | } 298 | 299 | return res 300 | } 301 | -------------------------------------------------------------------------------- /.all-contributorsrc: -------------------------------------------------------------------------------- 1 | { 2 | "projectName": "add-and-commit", 3 | "projectOwner": "EndBug", 4 | "repoType": "github", 5 | "repoHost": "https://github.com", 6 | "files": [ 7 | "README.md" 8 | ], 9 | "imageSize": 100, 10 | "commit": true, 11 | "commitConvention": "angular", 12 | "contributors": [ 13 | { 14 | "login": "EndBug", 15 | "name": "Federico Grandi", 16 | "avatar_url": "https://avatars1.githubusercontent.com/u/26386270?v=4", 17 | "profile": "https://github.com/EndBug", 18 | "contributions": [ 19 | "code", 20 | "doc" 21 | ] 22 | }, 23 | { 24 | "login": "jactor-rises", 25 | "name": "Tor Egil Jacobsen", 26 | "avatar_url": "https://avatars3.githubusercontent.com/u/14565088?v=4", 27 | "profile": "https://github.com/jactor-rises", 28 | "contributions": [ 29 | "code" 30 | ] 31 | }, 32 | { 33 | "login": "yelizariev", 34 | "name": "Ivan Yelizariev", 35 | "avatar_url": "https://avatars0.githubusercontent.com/u/186131?v=4", 36 | "profile": "https://twitter.com/yelizariev", 37 | "contributions": [ 38 | "ideas" 39 | ] 40 | }, 41 | { 42 | "login": "jhhughes", 43 | "name": "jhhughes", 44 | "avatar_url": "https://avatars2.githubusercontent.com/u/13724293?v=4", 45 | "profile": "https://github.com/jhhughes", 46 | "contributions": [ 47 | "bug" 48 | ] 49 | }, 50 | { 51 | "login": "DmitrijOkeanij", 52 | "name": "Дмитрий Океаний", 53 | "avatar_url": "https://avatars3.githubusercontent.com/u/10674646?v=4", 54 | "profile": "https://sunengine.site", 55 | "contributions": [ 56 | "ideas" 57 | ] 58 | }, 59 | { 60 | "login": "brahma-dev", 61 | "name": "Brahma Dev", 62 | "avatar_url": "https://avatars3.githubusercontent.com/u/1793295?v=4", 63 | "profile": "https://github.com/brahma-dev", 64 | "contributions": [ 65 | "bug" 66 | ] 67 | }, 68 | { 69 | "login": "felixlapalma", 70 | "name": "Felix Rojo Lapalma", 71 | "avatar_url": "https://avatars2.githubusercontent.com/u/38389683?v=4", 72 | "profile": "https://github.com/felixlapalma", 73 | "contributions": [ 74 | "bug" 75 | ] 76 | }, 77 | { 78 | "login": "RobinWijnant", 79 | "name": "Robin Wijnant", 80 | "avatar_url": "https://avatars3.githubusercontent.com/u/33033209?v=4", 81 | "profile": "http://robinwijnant.me", 82 | "contributions": [ 83 | "bug", 84 | "code" 85 | ] 86 | }, 87 | { 88 | "login": "onilton", 89 | "name": "Onilton Maciel", 90 | "avatar_url": "https://avatars2.githubusercontent.com/u/725676?v=4", 91 | "profile": "https://github.com/onilton", 92 | "contributions": [ 93 | "ideas" 94 | ] 95 | }, 96 | { 97 | "login": "jsoref", 98 | "name": "Josh Soref", 99 | "avatar_url": "https://avatars0.githubusercontent.com/u/2119212?v=4", 100 | "profile": "https://github.com/jsoref", 101 | "contributions": [ 102 | "doc" 103 | ] 104 | }, 105 | { 106 | "login": "ToMe25", 107 | "name": "ToMe25", 108 | "avatar_url": "https://avatars1.githubusercontent.com/u/38815969?v=4", 109 | "profile": "https://github.com/ToMe25", 110 | "contributions": [ 111 | "code", 112 | "ideas" 113 | ] 114 | }, 115 | { 116 | "login": "JonasJacobsUserspace", 117 | "name": "JonasJacobsUserspace", 118 | "avatar_url": "https://avatars0.githubusercontent.com/u/59708720?v=4", 119 | "profile": "https://github.com/JonasJacobsUserspace", 120 | "contributions": [ 121 | "bug" 122 | ] 123 | }, 124 | { 125 | "login": "pvogt09", 126 | "name": "pvogt09", 127 | "avatar_url": "https://avatars3.githubusercontent.com/u/50047961?v=4", 128 | "profile": "https://github.com/pvogt09", 129 | "contributions": [ 130 | "code" 131 | ] 132 | }, 133 | { 134 | "login": "connorjclark", 135 | "name": "Connor Clark", 136 | "avatar_url": "https://avatars1.githubusercontent.com/u/4071474?v=4", 137 | "profile": "http://hoten.cc", 138 | "contributions": [ 139 | "ideas" 140 | ] 141 | }, 142 | { 143 | "login": "Cyberbeni", 144 | "name": "Benedek Kozma", 145 | "avatar_url": "https://avatars1.githubusercontent.com/u/8356175?v=4", 146 | "profile": "https://github.com/Cyberbeni", 147 | "contributions": [ 148 | "ideas", 149 | "code" 150 | ] 151 | }, 152 | { 153 | "login": "coffeegoddd", 154 | "name": "Dustin Brown", 155 | "avatar_url": "https://avatars3.githubusercontent.com/u/43383835?v=4", 156 | "profile": "https://github.com/coffeegoddd", 157 | "contributions": [ 158 | "bug" 159 | ] 160 | }, 161 | { 162 | "login": "Chocrates", 163 | "name": "Chris McIntosh", 164 | "avatar_url": "https://avatars1.githubusercontent.com/u/1758164?v=4", 165 | "profile": "https://github.com/Chocrates", 166 | "contributions": [ 167 | "bug" 168 | ] 169 | }, 170 | { 171 | "login": "kbsali", 172 | "name": "Kevin Saliou", 173 | "avatar_url": "https://avatars0.githubusercontent.com/u/53676?v=4", 174 | "profile": "https://github.com/kbsali", 175 | "contributions": [ 176 | "ideas" 177 | ] 178 | }, 179 | { 180 | "login": "ewjoachim", 181 | "name": "Joachim Jablon", 182 | "avatar_url": "https://avatars0.githubusercontent.com/u/1457576?v=4", 183 | "profile": "https://github.com/ewjoachim", 184 | "contributions": [ 185 | "ideas" 186 | ] 187 | }, 188 | { 189 | "login": "trallnag", 190 | "name": "Tim Schwenke", 191 | "avatar_url": "https://avatars3.githubusercontent.com/u/24834206?v=4", 192 | "profile": "https://github.com/trallnag", 193 | "contributions": [ 194 | "ideas" 195 | ] 196 | }, 197 | { 198 | "login": "PssbleTrngle", 199 | "name": "Possible Triangle", 200 | "avatar_url": "https://avatars1.githubusercontent.com/u/12880806?v=4", 201 | "profile": "https://www.somethingcatchy.net", 202 | "contributions": [ 203 | "ideas" 204 | ] 205 | }, 206 | { 207 | "login": "ocean90", 208 | "name": "Dominik Schilling", 209 | "avatar_url": "https://avatars2.githubusercontent.com/u/617637?v=4", 210 | "profile": "https://dominikschilling.de", 211 | "contributions": [ 212 | "ideas", 213 | "doc", 214 | "code" 215 | ] 216 | }, 217 | { 218 | "login": "rugk", 219 | "name": "rugk", 220 | "avatar_url": "https://avatars.githubusercontent.com/u/11966684?v=4", 221 | "profile": "https://chaos.social/@rugk", 222 | "contributions": [ 223 | "doc" 224 | ] 225 | }, 226 | { 227 | "login": "xenoterracide", 228 | "name": "Caleb Cushing", 229 | "avatar_url": "https://avatars.githubusercontent.com/u/5517?v=4", 230 | "profile": "https://xenoterracide.com", 231 | "contributions": [ 232 | "bug" 233 | ] 234 | }, 235 | { 236 | "login": "ruohola", 237 | "name": "Eero Ruohola", 238 | "avatar_url": "https://avatars.githubusercontent.com/u/33625218?v=4", 239 | "profile": "https://ruohola.dev", 240 | "contributions": [ 241 | "bug", 242 | "ideas" 243 | ] 244 | }, 245 | { 246 | "login": "vincentchu12", 247 | "name": "Vincent Chu", 248 | "avatar_url": "https://avatars.githubusercontent.com/u/23532586?v=4", 249 | "profile": "https://github.com/vincentchu12", 250 | "contributions": [ 251 | "bug" 252 | ] 253 | }, 254 | { 255 | "login": "CWSites", 256 | "name": "Matt H", 257 | "avatar_url": "https://avatars.githubusercontent.com/u/1242102?v=4", 258 | "profile": "https://www.linkedin.com/in/cwsites", 259 | "contributions": [ 260 | "doc", 261 | "ideas" 262 | ] 263 | }, 264 | { 265 | "login": "danielwerg", 266 | "name": "danielwerg", 267 | "avatar_url": "https://avatars.githubusercontent.com/u/35052399?v=4", 268 | "profile": "https://github.com/danielwerg", 269 | "contributions": [ 270 | "doc" 271 | ] 272 | }, 273 | { 274 | "login": "koppor", 275 | "name": "Oliver Kopp", 276 | "avatar_url": "https://avatars.githubusercontent.com/u/1366654?v=4", 277 | "profile": "https://orcid.org/0000-0001-6962-4290", 278 | "contributions": [ 279 | "ideas" 280 | ] 281 | }, 282 | { 283 | "login": "Glidias", 284 | "name": "Glenn Ko", 285 | "avatar_url": "https://avatars.githubusercontent.com/u/190195?v=4", 286 | "profile": "https://github.com/Glidias", 287 | "contributions": [ 288 | "ideas" 289 | ] 290 | }, 291 | { 292 | "login": "drewwells", 293 | "name": "Drew Wells", 294 | "avatar_url": "https://avatars.githubusercontent.com/u/239123?v=4", 295 | "profile": "http://blog.madewithdrew.com/", 296 | "contributions": [ 297 | "ideas" 298 | ] 299 | }, 300 | { 301 | "login": "JavierSegoviaCordoba", 302 | "name": "Javier Segovia Córdoba", 303 | "avatar_url": "https://avatars.githubusercontent.com/u/7463564?v=4", 304 | "profile": "https://kotlin.desarrollador-android.com/", 305 | "contributions": [ 306 | "ideas" 307 | ] 308 | }, 309 | { 310 | "login": "Darylgolden", 311 | "name": "Darylgolden", 312 | "avatar_url": "https://avatars.githubusercontent.com/u/9102529?v=4", 313 | "profile": "https://github.com/Darylgolden", 314 | "contributions": [ 315 | "bug" 316 | ] 317 | }, 318 | { 319 | "login": "mcargille", 320 | "name": "mcargille", 321 | "avatar_url": "https://avatars.githubusercontent.com/u/20142895?v=4", 322 | "profile": "https://github.com/mcargille", 323 | "contributions": [ 324 | "bug", 325 | "code" 326 | ] 327 | }, 328 | { 329 | "login": "secondmanveran", 330 | "name": "secondman", 331 | "avatar_url": "https://avatars.githubusercontent.com/u/97000801?v=4", 332 | "profile": "https://github.com/secondmanveran", 333 | "contributions": [ 334 | "doc" 335 | ] 336 | }, 337 | { 338 | "login": "prince-chrismc", 339 | "name": "Chris Mc", 340 | "avatar_url": "https://avatars.githubusercontent.com/u/16867443?v=4", 341 | "profile": "https://github.com/prince-chrismc", 342 | "contributions": [ 343 | "doc" 344 | ] 345 | }, 346 | { 347 | "login": "Namyalg", 348 | "name": "Namya LG", 349 | "avatar_url": "https://avatars.githubusercontent.com/u/53875297?v=4", 350 | "profile": "https://linkedin.com/in/namyalg", 351 | "contributions": [ 352 | "doc" 353 | ] 354 | }, 355 | { 356 | "login": "sconix", 357 | "name": "Janne Julkunen", 358 | "avatar_url": "https://avatars.githubusercontent.com/u/921515?v=4", 359 | "profile": "https://github.com/sconix", 360 | "contributions": [ 361 | "ideas" 362 | ] 363 | }, 364 | { 365 | "login": "Josh-Cena", 366 | "name": "Joshua Chen", 367 | "avatar_url": "https://avatars.githubusercontent.com/u/55398995?v=4", 368 | "profile": "https://joshcena.com", 369 | "contributions": [ 370 | "bug" 371 | ] 372 | }, 373 | { 374 | "login": "Akimon658", 375 | "name": "Akimo", 376 | "avatar_url": "https://avatars.githubusercontent.com/u/81888693?v=4", 377 | "profile": "http://akimon658.github.io", 378 | "contributions": [ 379 | "doc" 380 | ] 381 | }, 382 | { 383 | "login": "revolunet", 384 | "name": "Julien Bouquillon", 385 | "avatar_url": "https://avatars.githubusercontent.com/u/124937?v=4", 386 | "profile": "https://revolunet.com", 387 | "contributions": [ 388 | "doc" 389 | ] 390 | }, 391 | { 392 | "login": "AvivPeledTalon", 393 | "name": "Aviv Peled", 394 | "avatar_url": "https://avatars.githubusercontent.com/u/92471076?v=4", 395 | "profile": "https://github.com/AvivPeledTalon", 396 | "contributions": [ 397 | "bug" 398 | ] 399 | }, 400 | { 401 | "login": "onedr0p", 402 | "name": "Devin Buhl", 403 | "avatar_url": "https://avatars.githubusercontent.com/u/213795?v=4", 404 | "profile": "https://github.com/onedr0p", 405 | "contributions": [ 406 | "bug" 407 | ] 408 | }, 409 | { 410 | "login": "melink14", 411 | "name": "Erek Speed", 412 | "avatar_url": "https://avatars.githubusercontent.com/u/1176550?v=4", 413 | "profile": "https://erekspeed.com", 414 | "contributions": [ 415 | "bug" 416 | ] 417 | }, 418 | { 419 | "login": "kachkaev", 420 | "name": "Alexander Kachkaev", 421 | "avatar_url": "https://avatars.githubusercontent.com/u/608862?v=4", 422 | "profile": "https://kachkaev.uk", 423 | "contributions": [ 424 | "bug" 425 | ] 426 | }, 427 | { 428 | "login": "ManuelRauber", 429 | "name": "Manuel Rauber", 430 | "avatar_url": "https://avatars.githubusercontent.com/u/740791?v=4", 431 | "profile": "https://manuel-rauber.com", 432 | "contributions": [ 433 | "code" 434 | ] 435 | }, 436 | { 437 | "login": "ggreif", 438 | "name": "Gabor Greif", 439 | "avatar_url": "https://avatars.githubusercontent.com/u/1312006?v=4", 440 | "profile": "http://heisenbug.blogspot.com", 441 | "contributions": [ 442 | "maintenance", 443 | "doc" 444 | ] 445 | }, 446 | { 447 | "login": "keithrfung", 448 | "name": "Keith Fung", 449 | "avatar_url": "https://avatars.githubusercontent.com/u/10125297?v=4", 450 | "profile": "http://keithrfung.dev", 451 | "contributions": [ 452 | "doc" 453 | ] 454 | }, 455 | { 456 | "login": "DenverCoder1", 457 | "name": "Jonah Lawrence", 458 | "avatar_url": "https://avatars.githubusercontent.com/u/20955511?v=4", 459 | "profile": "https://freshidea.com/jonah", 460 | "contributions": [ 461 | "bug", 462 | "code" 463 | ] 464 | }, 465 | { 466 | "login": "azeemba", 467 | "name": "Azeem Bande-Ali", 468 | "avatar_url": "https://avatars.githubusercontent.com/u/2160795?v=4", 469 | "profile": "https://azeemba.com/", 470 | "contributions": [ 471 | "doc" 472 | ] 473 | }, 474 | { 475 | "login": "ViacheslavKudinov", 476 | "name": "Viacheslav Kudinov", 477 | "avatar_url": "https://avatars.githubusercontent.com/u/56436734?v=4", 478 | "profile": "https://github.com/ViacheslavKudinov", 479 | "contributions": [ 480 | "security" 481 | ] 482 | }, 483 | { 484 | "login": "justanotheranonymoususer", 485 | "name": "justanotheranonymoususer", 486 | "avatar_url": "https://avatars.githubusercontent.com/u/5781692?v=4", 487 | "profile": "https://github.com/justanotheranonymoususer", 488 | "contributions": [ 489 | "bug" 490 | ] 491 | } 492 | ], 493 | "contributorsPerLine": 7, 494 | "skipCi": true, 495 | "commitType": "docs" 496 | } 497 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Add & Commit 2 | 3 | [![All Contributors](https://img.shields.io/github/all-contributors/EndBug/add-and-commit)](#contributors-) 4 | 5 | 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... 6 | 7 | ## Table of contents 8 | 9 | - [Inputs](#inputs) 10 | - [Outputs](#outputs) 11 | - [FAQs](#faqs) 12 | - [Examples](#examples) 13 | - [Contributors](#contributors-) 14 | - [Articles](#articles) 15 | 16 | ## Inputs 17 | 18 | Add a step like this to your workflow: 19 | 20 | ```yaml 21 | - uses: EndBug/add-and-commit@v9 # You can change this to use a specific version. 22 | with: 23 | # The arguments for the `git add` command (see the paragraph below for more info) 24 | # Default: '.' 25 | add: 'src' 26 | 27 | # The name of the user that will be displayed as the author of the commit. 28 | # Default: depends on the default_author input 29 | author_name: Author Name 30 | 31 | # The email of the user that will be displayed as the author of the commit. 32 | # Default: depends on the default_author input 33 | author_email: mail@example.com 34 | 35 | # Additional arguments for the git commit command. The --message argument is already set by the message input. 36 | # Default: '' 37 | commit: --signoff 38 | 39 | # The name of the custom committer you want to use, if different from the author of the commit. 40 | # Default: the name of the author (set with either author_name or default_author) 41 | committer_name: Committer Name 42 | 43 | # The email of the custom committer you want to use, if different from the author of the commit. 44 | # Default: the email of the author (set with either author_email or default_author) 45 | committer_email: mail@example.com 46 | 47 | # The local path to the directory where your repository is located. You should use actions/checkout first to set it up. 48 | # Default: '.' 49 | cwd: './path/to/the/repo' 50 | 51 | # Determines the way the action fills missing author name and email. Three options are available: 52 | # - github_actor -> UserName 53 | # - user_info -> Your Display Name 54 | # - github_actions -> github-actions 55 | # Default: github_actor 56 | default_author: github_actor 57 | 58 | # Arguments for the git fetch command. If set to false, the action won't fetch the repo. 59 | # For more info as to why fetching is usually recommended, please see the "Performance on large repos" FAQ. 60 | # Default: --tags --force 61 | fetch: false 62 | 63 | # The message for the commit. 64 | # Default: 'Commit from GitHub Actions (name of the workflow)' 65 | message: 'Your commit message' 66 | 67 | # If this input is set, the action will push the commit to a new branch with this name. 68 | # Default: '' 69 | new_branch: custom-new-branch 70 | 71 | # The way the action should handle pathspec errors from the add and remove commands. Three options are available: 72 | # - ignore -> errors will be logged but the step won't fail 73 | # - exitImmediately -> the action will stop right away, and the step will fail 74 | # - exitAtEnd -> the action will go on, every pathspec error will be logged at the end, the step will fail. 75 | # Default: ignore 76 | pathspec_error_handling: ignore 77 | 78 | # Arguments for the git pull command. By default, the action does not pull. 79 | # Default: '' 80 | pull: '--rebase --autostash ...' 81 | 82 | # 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) 83 | # Default: true 84 | push: false 85 | 86 | # The arguments for the `git rm` command (see the paragraph below for more info) 87 | # Default: '' 88 | remove: './dir/old_file.js' 89 | 90 | # Arguments for the git tag command (the tag name always needs to be the first word not preceded by an hyphen) 91 | # Default: '' 92 | tag: 'v1.0.0 --force' 93 | 94 | # Arguments for the git push --tags command (any additional argument will be added after --tags) 95 | # Default: '' 96 | tag_push: '--force' 97 | ``` 98 | 99 | ### Git arguments 100 | 101 | Multiple options let you provide the `git` arguments that you want the action to use. It's important to note that these arguments **are not actually used with a CLI command**, but they are parsed by a package called [`string-argv`](https://npm.im/string-argv), and then used with [`simple-git`](https://npm.im/simple-git). 102 | What does this mean for you? It means that strings that contain a lot of nested quotes may be parsed incorrectly, and that specific ways of declaring arguments may not be supported by these libraries. If you're having issues with your argument strings you can check whether they're being parsed correctly either by [enabling debug logging](https://docs.github.com/en/actions/managing-workflow-runs/enabling-debug-logging) for your workflow runs or by testing it directly with `string-argv` ([RunKit demo](https://npm.runkit.com/string-argv)): if each argument and option is parsed correctly you'll see an array where every string is an option or value. 103 | 104 | ### Adding files 105 | 106 | The action adds files using a regular `git add` command, so you can put every kind of argument in the `add` option. For example, if you want to force-add a file: `./path/to/file.txt --force`. 107 | The script will not stop if one of the git commands doesn't match any file. E.g.: if your command shows a "fatal: pathspec 'yourFile' did not match any files" error the action will go on. 108 | You can also use JSON or YAML arrays (e.g. `'["first", "second"]'`, `"['first', 'second']"`) to make the action run multiple `git add` commands: the action will log how your input has been parsed. Please mind that your input still needs to be a string because of how GitHub Actions works with inputs: just write your array inside the string, the action will parse it later. 109 | 110 | ### Deleting files 111 | 112 | The `remove` option can be used if a predetermined list of files needs to be removed. It runs the `git rm` command, so you can pass every kind of argument with it. As if with the [`add` input](#adding-files), you can also use JSON or YAML arrays to make the action run multiple `git rm` commands. 113 | 114 | If you want deleted files to be auto-detected and committed, you can use the [`--no-ignore-removal`/`-A`](https://git-scm.com/docs/git-add#Documentation/git-add.txt--A) git arguments. 115 | 116 | ### Pushing 117 | 118 | 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: 119 | 120 | - `true`: this is the default value, it will behave as usual. 121 | - `false`: this prevents the action from pushing at all, no `git push` command is run. 122 | - any other string: 123 | The action will use your string as the arguments for the `git push` command. Please note that nothing is used other than your arguments, and the command will result in `git push ${push input}` (no remote, no branch, no `--set-upstream`, you have to include them yourself). 124 | 125 | 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`. 126 | 127 | ### Creating a new branch 128 | 129 | If you want the action to commit in a new branch, you can use the `new_branch` input. 130 | 131 | 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. 132 | 133 | 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. 134 | 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`. 135 | 136 | If you want to commit files "across different branches", here are two ways to do it: 137 | 138 | 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. 139 | 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. 140 | 141 | ### Tagging 142 | 143 | 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). 144 | You can also change the arguments of the push command for tags: every argument in the `tag_push` input will be appended to the `git push --tags` command. 145 | For more info on how git arguments are parsed, see [the "Git arguments" section](#git-arguments). 146 | 147 | ## Outputs 148 | 149 | The action provides these outputs: 150 | 151 | - `committed`: whether the action has created a commit (`'true'` or `'false'`) 152 | - `commit_long_sha`: the full SHA of the commit that has just been created 153 | - `commit_sha`: the short 7-character SHA of the commit that has just been created 154 | - `pushed`: whether the action has pushed to the remote (`'true'` or `'false'`) 155 | - `tagged`: whether the action has created a tag (`'true'` or `'false'`) 156 | - `tag_pushed`: whether the action has pushed a tag (`'true'` or `'false'`) 157 | 158 | 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). 159 | 160 | ## FAQs 161 | 162 | ### Working with PRs 163 | 164 | By default, when you use `actions/checkout` on a PR, it will checkout the head commit in a detached head state. 165 | If you want to make some changes, you have to checkout the branch the PR is coming from in the head repo. 166 | You can set it up like this: 167 | 168 | ```yaml 169 | - uses: actions/checkout@v3 170 | with: 171 | repository: ${{ github.event.pull_request.head.repo.full_name }} 172 | ref: ${{ github.event.pull_request.head.ref }} 173 | ``` 174 | 175 | 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). 176 | 177 | 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. 178 | 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. 179 | You can try setting up the repo with your PAT, as explained in the ["About tokens" paragraph](#about-tokens) of this section. 180 | 181 | 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. 182 | 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. 183 | 184 | ### About tokens 185 | 186 | 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. 187 | 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. 188 | 189 | 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. 190 | 191 | ### The commit from the action is not triggering CI! 192 | 193 | 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. 194 | 195 | **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. 196 | 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. 197 | 198 | ### About `actions/checkout` 199 | 200 | The token you use when setting up the repo with this action will determine what token `add-and-commit` will use. 201 | Some users reported that they were getting an error: 202 | 203 | ``` 204 | > fatal: could not read Username for 'https://github.com': No such device or address 205 | ``` 206 | 207 | 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) 208 | 209 | ### Performance on large repos 210 | 211 | By default, the action will fetch the repository before starting to work on it: this ensures that it can see the already existing refs. 212 | 213 | When working with a repository that has a lot of branches and tags, fetching it can take a long time. If the fetch step is taking too much time, you can decide to skip it by setting the `fetch` input to `false`: this will prevent the action from running `git fetch` altogether. 214 | 215 | Please note that you have to set up your workflow accordingly: not fetching the repo can impact branch and tag creation within the action, and for this reason it's recommended to disable it only if necessary. Issue ref: [#386](https://github.com/EndBug/add-and-commit/issues/386) 216 | 217 | ## Examples 218 | 219 | ### Different author/committer configurations 220 | 221 | If you don't want to use your GitHub username for the CI commits, you can use the `default_author` input to make it appear as if it was made by "GitHub Actions", by setting its value to `github_actions`. 222 | 223 | 224 | 225 | ```yaml 226 | on: push 227 | jobs: 228 | build: 229 | runs-on: ubuntu-latest 230 | steps: 231 | - uses: EndBug/add-and-commit@v9 232 | with: 233 | default_author: github_actions 234 | ``` 235 | 236 | You can also use the `committer_name` and `committer_email` inputs to make it appear as if GitHub Actions is the committer, here are a couple of example steps: 237 | 238 | 239 | 240 | ```yaml 241 | - uses: EndBug/add-and-commit@v9 242 | with: 243 | message: Show GitHub Actions logo 244 | committer_name: GitHub Actions 245 | committer_email: actions@github.com 246 | ``` 247 | 248 | 249 | 250 | ```yaml 251 | - uses: EndBug/add-and-commit@v9 252 | with: 253 | message: Show GitHub logo 254 | committer_name: GitHub Actions 255 | committer_email: 41898282+github-actions[bot]@users.noreply.github.com 256 | ``` 257 | 258 | ### Automated linting 259 | 260 | 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: 261 | 262 | ```yaml 263 | name: Lint source code 264 | on: push 265 | 266 | jobs: 267 | run: 268 | name: Lint with ESLint 269 | runs-on: ubuntu-latest 270 | steps: 271 | - name: Checkout repo 272 | uses: actions/checkout@v3 273 | 274 | - name: Set up Node.js 275 | uses: actions/setup-node@v3 276 | 277 | - name: Install dependencies 278 | run: npm install 279 | 280 | - name: Update source code 281 | run: eslint "src/**" --fix 282 | 283 | - name: Commit changes 284 | uses: EndBug/add-and-commit@v9 285 | with: 286 | author_name: Your Name 287 | author_email: mail@example.com 288 | message: 'Your commit message' 289 | add: '*.js' 290 | ``` 291 | 292 | ### Running the action in a different directory 293 | 294 | 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. 295 | 296 | ```yaml 297 | name: Use a different repository directory 298 | on: push 299 | 300 | jobs: 301 | run: 302 | name: Add a text file 303 | runs-on: ubuntu-latest 304 | 305 | steps: 306 | # If you need to, you can check out your repo to a different location 307 | - uses: actions/checkout@v3 308 | with: 309 | path: './pathToRepo/' 310 | 311 | # You can make whatever type of change to the repo... 312 | - run: echo "123" > ./pathToRepo/file.txt 313 | 314 | # ...and then use the action as you would normally do, but providing the path to the repo 315 | - uses: EndBug/add-and-commit@v9 316 | with: 317 | message: 'Add the very useful text file' 318 | add: '*.txt --force' 319 | cwd: './pathToRepo/' 320 | ``` 321 | 322 | ## Articles 323 | 324 | - [Console by CodeSee #156](https://console.substack.com/p/console-156) 325 | - [MichealHeap.com](https://michaelheap.com/add-and-commit-action/) 326 | 327 | ## Contributors ✨ 328 | 329 | Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): 330 | 331 | 332 | 333 | 334 | 335 | 336 | 337 | 338 | 339 | 340 | 341 | 342 | 343 | 344 | 345 | 346 | 347 | 348 | 349 | 350 | 351 | 352 | 353 | 354 | 355 | 356 | 357 | 358 | 359 | 360 | 361 | 362 | 363 | 364 | 365 | 366 | 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | 383 | 384 | 385 | 386 | 387 | 388 | 389 | 390 | 391 | 392 | 393 | 394 | 395 | 396 | 397 | 398 | 399 | 400 | 401 | 402 | 403 | 404 | 405 |
Federico Grandi
Federico Grandi

💻 📖
Tor Egil Jacobsen
Tor Egil Jacobsen

💻
Ivan Yelizariev
Ivan Yelizariev

🤔
jhhughes
jhhughes

🐛
Дмитрий Океаний
Дмитрий Океаний

🤔
Brahma Dev
Brahma Dev

🐛
Felix Rojo Lapalma
Felix Rojo Lapalma

🐛
Robin Wijnant
Robin Wijnant

🐛 💻
Onilton Maciel
Onilton Maciel

🤔
Josh Soref
Josh Soref

📖
ToMe25
ToMe25

💻 🤔
JonasJacobsUserspace
JonasJacobsUserspace

🐛
pvogt09
pvogt09

💻
Connor Clark
Connor Clark

🤔
Benedek Kozma
Benedek Kozma

🤔 💻
Dustin Brown
Dustin Brown

🐛
Chris McIntosh
Chris McIntosh

🐛
Kevin Saliou
Kevin Saliou

🤔
Joachim Jablon
Joachim Jablon

🤔
Tim Schwenke
Tim Schwenke

🤔
Possible Triangle
Possible Triangle

🤔
Dominik Schilling
Dominik Schilling

🤔 📖 💻
rugk
rugk

📖
Caleb Cushing
Caleb Cushing

🐛
Eero Ruohola
Eero Ruohola

🐛 🤔
Vincent Chu
Vincent Chu

🐛
Matt H
Matt H

📖 🤔
danielwerg
danielwerg

📖
Oliver Kopp
Oliver Kopp

🤔
Glenn Ko
Glenn Ko

🤔
Drew Wells
Drew Wells

🤔
Javier Segovia Córdoba
Javier Segovia Córdoba

🤔
Darylgolden
Darylgolden

🐛
mcargille
mcargille

🐛 💻
secondman
secondman

📖
Chris Mc
Chris Mc

📖
Namya LG
Namya LG

📖
Janne Julkunen
Janne Julkunen

🤔
Joshua Chen
Joshua Chen

🐛
Akimo
Akimo

📖
Julien Bouquillon
Julien Bouquillon

📖
Aviv Peled
Aviv Peled

🐛
Devin Buhl
Devin Buhl

🐛
Erek Speed
Erek Speed

🐛
Alexander Kachkaev
Alexander Kachkaev

🐛
Manuel Rauber
Manuel Rauber

💻
Gabor Greif
Gabor Greif

🚧 📖
Keith Fung
Keith Fung

📖
Jonah Lawrence
Jonah Lawrence

🐛 💻
Azeem Bande-Ali
Azeem Bande-Ali

📖
Viacheslav Kudinov
Viacheslav Kudinov

🛡️
justanotheranonymoususer
justanotheranonymoususer

🐛
406 | 407 | 408 | 409 | 410 | 411 | 412 | This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! 413 | 414 | ### Additional credits 415 | 416 | This action is inspired by [`git-auto-commit-action`](https://github.com/stefanzweifel/git-auto-commit-action) by [Stefan Zweifel](https://github.com/stefanzweifel). 417 | 418 | ## License 419 | 420 | This action is distributed under the MIT license, check the [license](LICENSE) for more info. 421 | --------------------------------------------------------------------------------