├── .editorconfig ├── .eslintignore ├── .eslintrc.cjs ├── .gitattributes ├── .github ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── Bug_report.md │ ├── Documentation_issue.md │ ├── Feature_request.md │ ├── Security_issue.md │ └── Support_question.md ├── PULL_REQUEST_TEMPLATE.md ├── renovate.json5 ├── settings.yml └── workflows │ ├── auto-close-fixed-issues.yml │ ├── greetings.yml │ ├── semantic-release.yml │ └── test.yml ├── .gitignore ├── .husky ├── .gitignore ├── commit-msg ├── pre-commit └── prepare-commit-msg ├── .lintstagedrc ├── .nvmrc ├── .prettierignore ├── .prettierrc.cjs ├── .releaserc.json ├── .textlintignore ├── .textlintrc ├── .typo-ci.yml ├── .yamllint.yaml ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── UPGRADE.md ├── __tests__ ├── git-version.test.ts ├── ref-helper.test.ts └── retry-helper.test.ts ├── action.yml ├── commitlint.config.cjs ├── dist ├── index.js └── problem-matcher.json ├── jest.config.js ├── package.json ├── src ├── git-auth-helper.ts ├── git-command-manager.ts ├── git-source-provider.ts ├── git-version.ts ├── github-action-cleanup.ts ├── github-action-context.ts ├── github-manager.ts ├── interfaces.ts ├── main.ts ├── misc │ └── generate-docs.ts ├── octokit.ts ├── ref-helper.ts ├── retry-helper.ts ├── settings.ts └── state-helper.ts ├── tsconfig.json ├── types └── octokit__fixtures.d.ts ├── verify-node-version.cjs └── yarn.lock /.editorconfig: -------------------------------------------------------------------------------- 1 | # https://EditorConfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | indent_size = 4 9 | indent_style = space 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | !.eslintrc.js 2 | !**/.eslintrc.js 3 | **/lib 4 | lib 5 | **/dist 6 | dist 7 | **/dist-types 8 | dist-types 9 | node_modules 10 | .out 11 | public 12 | coverage 13 | 14 | .cache 15 | **/.next 16 | lerna.json 17 | .vscode 18 | .yarn/** 19 | 20 | **/temp/** 21 | 22 | pnpm-lock.yaml 23 | .pnpm-store/ 24 | support/root/pnpm-lock.yaml 25 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | extends: ["@anolilab/eslint-config"], 4 | parserOptions: { 5 | project: "./tsconfig.json", 6 | tsconfigRootDir: __dirname, 7 | }, 8 | env: { 9 | // Your environments (which contains several predefined global variables) 10 | browser: false, 11 | node: false, 12 | commonjs: true, 13 | es6: true, 14 | // mocha: true, 15 | jest: true, 16 | "jest/globals": true 17 | // jquery: true 18 | }, 19 | globals: { 20 | // Your global variables (setting to false means it's not allowed to be reassigned) 21 | // 22 | // myGlobal: false 23 | }, 24 | rules: { 25 | // Customize your rules 26 | "import/extensions": "off", 27 | "unicorn/no-array-for-each": "off", 28 | "unicorn/no-null": "off", 29 | "unicorn/no-array-reduce": "off", 30 | 31 | "max-len": ["error", { code: 160 }], 32 | }, 33 | }; 34 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | /.yarn/** linguist-vendored 2 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @prisis -------------------------------------------------------------------------------- /.github/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 community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or 22 | advances of any kind 23 | * Trolling, insulting or derogatory comments, and personal or political attacks 24 | * Public or private harassment 25 | * Publishing others' private information, such as a physical or email 26 | address, without their explicit permission 27 | * Other conduct which could reasonably be considered inappropriate in a 28 | professional setting 29 | 30 | ## Enforcement Responsibilities 31 | 32 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 33 | 34 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 35 | 36 | ## Scope 37 | 38 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 39 | 40 | ## Enforcement 41 | 42 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [d.bannert@anolilab.de](mailto:d.bannert@anolilab.de). All complaints will be reviewed and investigated promptly and fairly. 43 | 44 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 45 | 46 | ## Enforcement Guidelines 47 | 48 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 49 | 50 | ### 1. Correction 51 | 52 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 53 | 54 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 55 | 56 | ### 2. Warning 57 | 58 | **Community Impact**: A violation through a single incident or series of actions. 59 | 60 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 61 | 62 | ### 3. Temporary Ban 63 | 64 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 65 | 66 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 67 | 68 | ### 4. Permanent Ban 69 | 70 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 71 | 72 | **Consequence**: A permanent ban from any sort of public interaction within the community. 73 | 74 | ## Attribution 75 | 76 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 77 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 78 | 79 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 80 | 81 | [homepage]: https://www.contributor-covenant.org 82 | 83 | For answers to common questions about this code of conduct, see the FAQ at 84 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. -------------------------------------------------------------------------------- /.github/CONTRIBUTING.md : -------------------------------------------------------------------------------- 1 | # Contributing to template-sync-action 2 | 3 | ## Contributor Code of Conduct 4 | 5 | Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. 6 | 7 | ## Workflow 8 | 9 | * Fork the project. 10 | * Make your bug fix or feature addition. 11 | * Add tests for it. This is important so we don't break it in a future version unintentionally. 12 | * Send a pull request to the develop branch. 13 | 14 | Please make sure that you have [set up your user name and email address](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup) for use with Git. Strings such as `silly nick name ` look really stupid in the commit history of a project. 15 | 16 | Due to time constraints, you may not always get a quick response. Please do not take delays personal and feel free to remind. 17 | 18 | ## Coding Guidelines 19 | 20 | This project comes with `.prettierrc.json` and `eslintrc.json` configuration files. Please run the following commands to format the code before committing it. 21 | 22 | ```bash 23 | $ npm run format 24 | $ npm run lint 25 | ``` 26 | 27 | ## Using template-sync-action from a Git checkout 28 | 29 | The following commands can be used to perform the initial checkout of template-sync-action: 30 | 31 | ```bash 32 | $ git clone https://github.com/narrowspark/template-sync-action.git 33 | 34 | $ cd template-sync-action 35 | ``` 36 | 37 | Install template-sync-action dependencies using [npm](https://www.npmjs.com/): 38 | 39 | ```bash 40 | $ npm install 41 | ``` 42 | 43 | ## Running the test suite 44 | 45 | After following the steps shown above, The `template-sync-action` tests in the `__tests__` directory can be run using this command: 46 | 47 | ```bash 48 | $ npm test 49 | ``` 50 | 51 | ## Creating a release 52 | 53 | Create a release before you push your changes. 54 | 55 | ```bash 56 | $ npm run all 57 | ``` 58 | 59 | ## Reporting issues 60 | 61 | Please submit the issue using the appropriate template provided for a bug report or a feature request: 62 | 63 | * [Issues](https://github.com/narrowspark/template-sync-action/issues) -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: "prisis" 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🐛 Bug Report 3 | about: If something isn't working as expected. 4 | labels: Type: Bug 5 | 6 | --- 7 | 8 | 11 | 12 | **Version(s) affected**: x.y.z 13 | 14 | **Description** 15 | 16 | 17 | **How to reproduce** 18 | 19 | 20 | **Possible Solution** 21 | 22 | 23 | **Additional context** 24 | 25 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Documentation_issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 📚 Documentation Issue 3 | about: Anything related to documentation 4 | 5 | --- 6 | 7 | 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚀 Feature Request 3 | about: I have a suggestion (and might want to implement myself 🙂)! 4 | 5 | --- 6 | 7 | 10 | 11 | **Is your feature request related to a problem? Please describe.** 12 | 13 | 14 | **Describe the solution you'd like** 15 | 16 | 17 | **Describe alternatives you've considered** 18 | 19 | 20 | **Teachability, Documentation, Adoption, Migration Strategy** 21 | 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Security_issue.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: ㊙️ Security Issue 3 | about: Report security-related errors 4 | 5 | --- 6 | 7 | 10 | 11 | ⚠ PLEASE DON'T DISCLOSE SECURITY-RELATED ISSUES PUBLICLY, SEE BELOW. 12 | 13 | If you have found a security issue in Narrowspark, please send the details to 14 | security [at] narrowspark.com and don't disclose it publicly until we can provide a 15 | fix for it. 16 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/Support_question.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🤗 Support Question 3 | about: If you have a question 💬, please check out our [Discord](https://discord.gg/UBG6r9b) or [StackOverflow](https://stackoverflow.com/)! 4 | labels: Status: Help wanted 5 | 6 | --- 7 | 8 | 11 | 12 | Issues on GitHub are intended to be related to problems with Narrowspark packages itself, so we recommend not using this medium to ask them here 😁. 13 | 14 | For this kind of questions about using Narrowspark or third-party packages, please use 15 | any of the support alternatives. 16 | 17 | Thanks! 18 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | | Q | A 2 | | ------------- | --- 3 | | Branch? | master 4 | | Bug fix? | yes/no 5 | | New feature? | yes/no 6 | | Deprecations? | yes/no 7 | | Tickets | Fix #... 8 | | License | MIT 9 | | Doc PR | yes/no 10 | 11 | -------------------------------------------------------------------------------- /.github/renovate.json5: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:base", 5 | ":timezone(Europe/Berlin)" 6 | ], 7 | "ignoreUnstable": true, 8 | "pinVersions": false, 9 | "rebaseStalePrs": true, 10 | "separateMultipleMajor": true, 11 | "labels": ["dependency", "Changed"], 12 | "composer": { 13 | "enabled": true 14 | }, 15 | "major": { 16 | "semanticCommitType": "chore", 17 | "semanticCommitScope": "deps" 18 | }, 19 | "vulnerabilityAlerts": { 20 | "enabled": true, 21 | "labels": ["Security", "Type: Critical"] 22 | }, 23 | "packageRules": [ 24 | { 25 | "groupName": "renovate-meta", 26 | "automerge": true, 27 | "updateTypes": ["lockFileMaintenance", "minor", "patch", "pin", "digest"], 28 | "labels": ["dependency", "Changed"], 29 | "semanticCommitType": "chore", 30 | "semanticCommitScope": "deps", 31 | "semanticCommits": "enabled", 32 | "datasources": ["npm"] 33 | }, 34 | { 35 | "groupName": "dependencies (major)", 36 | "automerge": false, 37 | "depTypeList": ["require"], 38 | "updateTypes": ["major"], 39 | "semanticCommitType": "deps", 40 | "semanticCommits": "enabled" 41 | }, 42 | { 43 | "groupName": "dependencies (non-major)", 44 | "automerge": true, 45 | "depTypeList": ["dependencies", "require"], 46 | "updateTypes": ["patch", "minor", "pin", "digest"], 47 | "semanticCommitType": "chore", 48 | "semanticCommitScope": "deps", 49 | "semanticCommits": "enabled" 50 | }, 51 | { 52 | "groupName": "devDependencies (major)", 53 | "automerge": true, 54 | "depTypeList": ["devDependencies", "require-dev"], 55 | "updateTypes": ["major"], 56 | "labels": ["dependency", "Changed"], 57 | "semanticCommitType": "chore", 58 | "semanticCommitScope": "deps", 59 | "semanticCommits": "enabled" 60 | }, 61 | { 62 | "groupName": "devDependencies (non-major)", 63 | "automerge": true, 64 | "depTypeList": ["devDependencies", "require-dev"], 65 | "updateTypes": ["patch", "minor", "pin", "digest"], 66 | "labels": ["dependency", "Changed"], 67 | "semanticCommitType": "chore", 68 | "semanticCommitScope": "deps", 69 | "semanticCommits": "enabled" 70 | } 71 | ] 72 | } 73 | -------------------------------------------------------------------------------- /.github/settings.yml: -------------------------------------------------------------------------------- 1 | # https://github.com/probot/settings 2 | 3 | branches: 4 | - name: master 5 | protection: 6 | enforce_admins: false 7 | required_pull_request_reviews: 8 | dismiss_stale_reviews: true 9 | require_code_owner_reviews: true 10 | required_approving_review_count: 1 11 | restrictions: 12 | 13 | # https://developer.github.com/v3/repos/branches/#parameters-1 14 | 15 | # Note: User, app, and team restrictions are only available for organization-owned repositories. 16 | # Set to null to disable when using this configuration for a repository on a personal account. 17 | 18 | apps: 19 | - "dependabot-preview" 20 | teams: [] 21 | 22 | labels: 23 | - name: Added 24 | description: "Changelog Added" 25 | color: 90db3f 26 | 27 | - name: Changed 28 | description: "Changelog Changed" 29 | color: fbca04 30 | 31 | - name: dependency 32 | description: "Pull requests that update a dependency file" 33 | color: e1f788 34 | 35 | - name: Deprecated 36 | description: "Changelog Deprecated" 37 | color: 1d76db 38 | 39 | - name: Duplicate 40 | color: 000000 41 | 42 | - name: Enhancement 43 | color: d7e102 44 | 45 | - name: Fixed 46 | description: "Changelog Fixed" 47 | color: 9ef42e 48 | 49 | - name: Removed 50 | description: "Changelog Removed" 51 | color: e99695 52 | 53 | - name: Security 54 | description: "Changelog Security" 55 | color: ed3e3b 56 | 57 | - name: "Status: Good first issue" 58 | color: d7e102 59 | 60 | - name: "Status: Help wanted" 61 | color: 85d84e 62 | 63 | - name: "Status: Needs Work" 64 | color: fad8c7 65 | 66 | - name: "Status: Waiting for feedback" 67 | color: fef2c0 68 | 69 | - name: "Type: BC Break" 70 | color: b60205 71 | 72 | - name: "Type: Bug" 73 | color: b60205 74 | 75 | - name: "Type: Critical" 76 | color: ff8c00 77 | 78 | - name: "Type: RFC" 79 | color: fbca04 80 | 81 | - name: "Type: Unconfirmed" 82 | color: 444444 83 | 84 | - name: "Type: Wontfix" 85 | color: 000000 86 | 87 | repository: 88 | allow_merge_commit: true 89 | allow_rebase_merge: false 90 | allow_squash_merge: false 91 | archived: false 92 | default_branch: master 93 | delete_branch_on_merge: true 94 | description: ":arrows_counterclockwise: Github action to sync repository with a template repository" 95 | has_downloads: true 96 | has_issues: true 97 | has_pages: false 98 | has_projects: false 99 | has_wiki: false 100 | name: "template-sync-action" 101 | private: false 102 | 103 | # https://developer.github.com/v3/repos/branches/#remove-branch-protection 104 | 105 | topics: "github, github-actions, template, narrowspark, sync" -------------------------------------------------------------------------------- /.github/workflows/auto-close-fixed-issues.yml: -------------------------------------------------------------------------------- 1 | # This action will automatically close issues fixed in 2 | # pull requests that doesn't target the default branch. 3 | 4 | name: Auto Close Fixed Issues 5 | on: 6 | pull_request_target: 7 | types: [closed] 8 | jobs: 9 | run: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: bubkoo/auto-close-fixed-issues@v1 13 | with: 14 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 15 | comment: | 16 | This issue was closed by #{{ pr }}. 17 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | # https://help.github.com/en/categories/automating-your-workflow-with-github-actions 2 | 3 | name: "Greetings" 4 | 5 | on: ["pull_request", "issues"] 6 | 7 | jobs: 8 | greeting: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/first-interaction@v1 12 | with: 13 | repo-token: ${{ secrets.GITHUB_TOKEN }} 14 | issue-message: "Awesome! Thank you for taking the time to create your first issue! Please review the [guidelines](https://narrowspark.com/docs/current/contributing)" 15 | pr-message: "Great! Thank you for taking the time to create your first pull request! Please review the [guidelines](https://narrowspark.com/docs/current/contributing)" 16 | -------------------------------------------------------------------------------- /.github/workflows/semantic-release.yml: -------------------------------------------------------------------------------- 1 | # https://help.github.com/en/categories/automating-your-workflow-with-github-actions 2 | 3 | name: "Semantic Release" 4 | 5 | on: 6 | push: 7 | branches: 8 | - ([0-9])?(.{+([0-9]),x}).x 9 | - main 10 | - next 11 | - next-major 12 | - alpha 13 | - beta 14 | 15 | jobs: 16 | semantic-release: 17 | name: "Semantic Release" 18 | 19 | runs-on: ubuntu-latest 20 | 21 | steps: 22 | - uses: actions/checkout@v2 23 | 24 | - name: "Semantic Release" 25 | uses: cycjimmy/semantic-release-action@v2 26 | with: 27 | semantic_version: 17.0.7 28 | extra_plugins: | 29 | @semantic-release/changelog@^5.0.1 30 | @semantic-release/git@^9.0.0 31 | @google/semantic-release-replace-plugin@^1.0.0 32 | conventional-changelog-conventionalcommits@^4.3.0 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.SEMANTIC_GITHUB_TOKEN }} 35 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # https://help.github.com/en/categories/automating-your-workflow-with-github-actions 2 | 3 | name: "Tests" 4 | 5 | on: [push] 6 | 7 | jobs: 8 | test: 9 | name: "Tests" 10 | 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: 16 | fetch-depth: 0 17 | persist-credentials: false 18 | 19 | - name: Use Node.js 12.x 20 | uses: actions/setup-node@v2 21 | with: 22 | node-version: 12.x 23 | 24 | - name: set git credentials 25 | run: | 26 | git config --local user.email "d.bannert@anolilab.de" 27 | git config --local user.name "Daniel Bannert" 28 | 29 | - name: Get yarn cache directory path 30 | id: yarn-cache-dir-path 31 | run: echo "::set-output name=dir::$(yarn config get cacheFolder)" 32 | 33 | - uses: actions/cache@v2 34 | id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`) 35 | with: 36 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 37 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }} 38 | restore-keys: | 39 | ${{ runner.os }}-yarn- 40 | 41 | - name: install 42 | run: yarn install 43 | 44 | - name: lint 45 | run: yarn run lint 46 | 47 | - name: build 48 | run: yarn run build && yarn run pack 49 | 50 | - name: test 51 | run: yarn run test 52 | 53 | - name: "Send code coverage report to Codecov.io" 54 | uses: codecov/codecov-action@v1 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Dependency directory 2 | node_modules 3 | 4 | # Rest pulled from https://github.com/github/gitignore/blob/master/Node.gitignore 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | yarn-debug.log* 10 | yarn-error.log* 11 | lerna-debug.log* 12 | 13 | # Diagnostic reports (https://nodejs.org/api/report.html) 14 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 15 | 16 | # Runtime data 17 | pids 18 | *.pid 19 | *.seed 20 | *.pid.lock 21 | 22 | # Directory for instrumented libs generated by jscoverage/JSCover 23 | lib-cov 24 | 25 | # Coverage directory used by tools like istanbul 26 | coverage 27 | *.lcov 28 | 29 | # nyc test coverage 30 | .nyc_output 31 | 32 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 33 | .grunt 34 | 35 | # Bower dependency directory (https://bower.io/) 36 | bower_components 37 | 38 | # node-waf configuration 39 | .lock-wscript 40 | 41 | # Compiled binary addons (https://nodejs.org/api/addons.html) 42 | build/Release 43 | 44 | # Dependency directories 45 | jspm_packages/ 46 | 47 | # TypeScript v1 declaration files 48 | typings/ 49 | 50 | # TypeScript cache 51 | *.tsbuildinfo 52 | 53 | # Optional npm cache directory 54 | .npm 55 | 56 | # Optional eslint cache 57 | .eslintcache 58 | 59 | # Optional REPL history 60 | .node_repl_history 61 | 62 | # Output of 'npm pack' 63 | *.tgz 64 | 65 | # Yarn Integrity file 66 | .yarn-integrity 67 | 68 | # dotenv environment variables file 69 | .env 70 | .env.test 71 | 72 | # parcel-bundler cache (https://parceljs.org/) 73 | .cache 74 | 75 | # next.js build output 76 | .next 77 | 78 | # nuxt.js build output 79 | .nuxt 80 | 81 | # vuepress build output 82 | .vuepress/dist 83 | 84 | # Serverless directories 85 | .serverless/ 86 | 87 | # FuseBox cache 88 | .fusebox/ 89 | 90 | # DynamoDB Local files 91 | .dynamodb/ 92 | 93 | # OS metadata 94 | .DS_Store 95 | Thumbs.db 96 | 97 | # Ignore built ts files 98 | __tests__/runner/* 99 | lib/**/* -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # The hook should exit with non-zero status after issuing 4 | # an appropriate message if it wants to stop the commit. 5 | # 6 | # https://rushjs.io/pages/maintainer/git_hooks/ 7 | 8 | echo -------------------------------------------- 9 | echo Starting Git hook: commit-msg 10 | 11 | yarn commitlint --edit $1 || exit $? 12 | 13 | echo Finished Git hook: commit-msg 14 | echo -------------------------------------------- 15 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # The hook should exit with non-zero status after issuing 4 | # an appropriate message if it wants to stop the commit. 5 | # 6 | # https://rushjs.io/pages/maintainer/git_hooks/ 7 | 8 | echo -------------------------------------------- 9 | echo Starting Git hook: pre-commit 10 | 11 | yarn pretty-quick --staged 12 | 13 | yarn sort-package-json 14 | 15 | echo Finished Git hook: pre-commit 16 | echo -------------------------------------------- 17 | -------------------------------------------------------------------------------- /.husky/prepare-commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | echo -------------------------------------------- 4 | echo Starting Git hook: prepare-commit-msg 5 | 6 | exec < /dev/tty && yarn commitizen --hook || true 7 | 8 | echo Finished Git hook: prepare-commit-msg 9 | echo -------------------------------------------- 10 | -------------------------------------------------------------------------------- /.lintstagedrc: -------------------------------------------------------------------------------- 1 | { 2 | "**/*.{js,jsx,tsx,ts}": [ 3 | "prettier --config=.prettierrc.cjs --write", 4 | "cross-env NO_LOGS=true eslint -c ./.eslintrc.cjs --fix" 5 | ], 6 | "*.{json,yml,yaml,less,css,scss,sass}": [ 7 | "prettier --config=.prettierrc.cjs --write" 8 | ], 9 | "*.{md,mdx}": [ 10 | "prettier --config=.prettierrc.cjs --write", 11 | "cross-env NO_LOGS=true eslint -c ./.eslintrc.cjs --fix" 12 | ], 13 | "{packages,support}/**/*.{js,jsx,tsx,ts}": [ 14 | "prettier --config=.prettierrc.cjs --write", 15 | "cross-env NO_LOGS=true eslint -c ./.eslintrc.cjs --fix" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 12.22.6 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .gitkeep 2 | .env* 3 | *.ico 4 | *.lock 5 | db/migrations 6 | dist 7 | CHANGELOG.md 8 | -------------------------------------------------------------------------------- /.prettierrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | printWidth: 160, 3 | tabWidth: 4, 4 | useTabs: false, 5 | semi: true, 6 | singleQuote: false, 7 | quoteProps: "as-needed", 8 | jsxSingleQuote: false, 9 | trailingComma: "all", 10 | bracketSpacing: true, 11 | jsxBracketSameLine: false, 12 | arrowParens: "always", 13 | rangeStart: 0, 14 | rangeEnd: Infinity, 15 | requirePragma: false, 16 | insertPragma: false, 17 | proseWrap: "preserve", 18 | htmlWhitespaceSensitivity: "css", 19 | vueIndentScriptAndStyle: false, 20 | endOfLine: "lf", 21 | embeddedLanguageFormatting: "auto", 22 | }; 23 | -------------------------------------------------------------------------------- /.releaserc.json: -------------------------------------------------------------------------------- 1 | { 2 | "branches": [ 3 | "+([0-9])?(.{+([0-9]),x}).x", 4 | "main", 5 | "next", 6 | "next-major", 7 | { 8 | "name": "beta", 9 | "prerelease": true 10 | }, 11 | { 12 | "name": "alpha", 13 | "prerelease": true 14 | } 15 | ], 16 | "dryRun": false, 17 | "plugins": [ 18 | [ 19 | "@semantic-release/commit-analyzer", 20 | { 21 | "preset": "conventionalcommits" 22 | } 23 | ], 24 | [ 25 | "@google/semantic-release-replace-plugin", 26 | { 27 | "replacements": [ 28 | { 29 | "files": [ 30 | "package.json" 31 | ], 32 | "from": "\"version\": \".*\"", 33 | "to": "\"version\": \"${nextRelease.version}\"", 34 | "results": [ 35 | { 36 | "file": "package.json", 37 | "hasChanged": true, 38 | "numMatches": 1, 39 | "numReplacements": 1 40 | } 41 | ], 42 | "countMatches": true 43 | } 44 | ] 45 | } 46 | ], 47 | [ 48 | "@semantic-release/release-notes-generator", 49 | { 50 | "preset": "conventionalcommits" 51 | } 52 | ], 53 | "@semantic-release/changelog", 54 | "@semantic-release/github", 55 | [ 56 | "@semantic-release/git", 57 | { 58 | "assets": [ 59 | "dist/*", 60 | "package.json", 61 | "package-lock.json", 62 | "UPGRADE.md", 63 | "LICENSE.md", 64 | "README.md", 65 | "CHANGELOG.md", 66 | "action.yml" 67 | ] 68 | } 69 | ] 70 | ] 71 | } 72 | -------------------------------------------------------------------------------- /.textlintignore: -------------------------------------------------------------------------------- 1 | LICENSE.md 2 | -------------------------------------------------------------------------------- /.textlintrc: -------------------------------------------------------------------------------- 1 | { 2 | "filters": { 3 | "comments": true 4 | }, 5 | "rules": { 6 | "en-capitalization": true, 7 | "footnote-order": true, 8 | "no-todo": true, 9 | "no-dead-link": { 10 | "ignore": [ 11 | "bc_data_*", 12 | ] 13 | }, 14 | "no-empty-section": true, 15 | "terminology": true, 16 | "apostrophe": true, 17 | "diacritics": true, 18 | "@textlint-rule/no-invalid-control-character": true, 19 | "@textlint-rule/no-unmatched-pair": true, 20 | "abbr-within-parentheses": true, 21 | "alex": { 22 | "allow": [ 23 | "period", 24 | "european", 25 | "failure", 26 | "fore", 27 | "attack", 28 | "execution", 29 | "executed", 30 | "remain", 31 | "execute" 32 | ] 33 | }, 34 | "@textlint-rule/preset-google": true, 35 | "write-good": { 36 | "passive": false, 37 | "eprime": false, 38 | }, 39 | "common-misspellings": true, 40 | "terminology": { 41 | "defaultTerms": false, 42 | "terms": [ 43 | // Abbreviations 44 | "API", 45 | ["API['’]?s", "APIs"], 46 | "Ajax", 47 | "CLI", 48 | "CSS", 49 | "CORS", 50 | ["^E2E", "E2E"], 51 | "gif", 52 | ["^HTML", "HTML"], 53 | ["^URL(s?)", "URL$1"], 54 | ["^HTTP", "HTTP"], 55 | ["^HTTPS", "HTTPS"], 56 | "SSO", 57 | ["^XHR(s?)", "XHR$1"], 58 | ["^XHR['’]?s", "XHRs"], 59 | "Xvfb", 60 | "YAML", 61 | 62 | // Words and phrases 63 | ["\\(s\\)he", "they"], 64 | ["he or she", "they"], 65 | ["he/she", "they"], 66 | ["crazy", "complex"], 67 | ["crazier", "more complex"], 68 | ["craziest", "most complex"], 69 | ["dumb", "unintended"], 70 | ["insane", "outrageous"], 71 | 72 | // Prefer American spelling 73 | ["behaviour", "behavior"], 74 | ["cancelled", "canceled"], 75 | ["cancelling", "canceling"], 76 | ["centre", "center"], 77 | ["colour", "color"], 78 | ["customise", "customize"], 79 | ["customisation", "customization"], 80 | ["favourite", "favorite"], 81 | ["labelled", "labeled"], 82 | ["licence", "license"], 83 | ["organise", "organize"], 84 | 85 | // Common misspellings 86 | ["gaurantee", "guarantee"], 87 | 88 | // Words we would like to not use altogether 89 | ["simply", ""], 90 | 91 | // Single word 92 | ["change[- ]log(s?)", "changelog$1"], 93 | ["code[- ]base(es?)", "codebase$1"], 94 | ["e[- ]mail(s?)", "email$1"], 95 | ["end[- ]point(s?)", "endpoint$1"], 96 | ["file[- ]name(s?)", "filename$1"], 97 | ["can[- ]not", "cannot$1"], 98 | 99 | // Multiple words 100 | ["back-?end(s?)", "back end$1"], 101 | ["front-?end(s?)", "front end$1"], 102 | ["full-?stack(s?)", "full stack$1"], 103 | ["open-?source(ed?)", "open source$1"], 104 | ["web-?page(s?)", "web page$1"], 105 | 106 | // Hyphenated 107 | ["end ?to ?end", "end-to-end"], 108 | ["retryability", "retry-ability"], 109 | ["retriability", "retry-ability"], 110 | 111 | ["some", ""], 112 | ["filetype", "file type"], 113 | ["stylesheet", "style sheet"], 114 | ["like this", ""], 115 | ["probably", ""], 116 | ["known as", ""], 117 | ["really", ""], 118 | ["just", ""], 119 | ["simple", ""], 120 | ["obvious", ""], 121 | ["straightforward", ""], 122 | ["very", ""], 123 | ["a little", ""], 124 | ["note that", ""], 125 | ["good to note", ""], 126 | ["good to remember", ""], 127 | ["basically", ""], 128 | ["actually", ""], 129 | ["pretty", ""], 130 | ["easy", ""], 131 | ["interesting", ""], 132 | ["way to", ""], 133 | ["In order to", "To"], 134 | ["in order to", "to"], 135 | ["might", ""], 136 | ["us", ""], 137 | ["I'll", ""], 138 | ["I've", ""], 139 | ["they'll", ""], 140 | ["it is", "it's"], 141 | ["It is", "It's"], 142 | ] 143 | } 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /.typo-ci.yml: -------------------------------------------------------------------------------- 1 | # This is a sample .typo-ci.yml file, it's used to configure how Typo CI will behave. 2 | # Add it to the root of your project and push it to github. 3 | --- 4 | 5 | # What language dictionaries should it use? Currently Typo CI supports: 6 | # de 7 | # en 8 | # en_GB 9 | # es 10 | # fr 11 | # it 12 | # pt 13 | # pt_BR 14 | dictionaries: 15 | - en 16 | - en_GB 17 | 18 | # Any files/folders we should ignore? 19 | excluded_files: 20 | - ".dependabot/**/*" 21 | - ".github/workflows/**/*" 22 | - ".github/settings.yml" 23 | - ".editorconfig" 24 | - ".gitattributes" 25 | - ".gitignore" 26 | - ".nvmrc" 27 | - "package.json" 28 | - "package-lock.json" 29 | - "tsconfig.json" 30 | - "jest.config.js" 31 | - ".prettierignore" 32 | - ".prettierrc.json" 33 | - ".eslintignore" 34 | - ".eslintrc.json" 35 | 36 | # Any typos we should ignore? 37 | excluded_words: 38 | - typoci 39 | - anolilab 40 | - bannert 41 | - prisis 42 | - narrowspark 43 | 44 | # Would you like filenames to also be spellchecked? 45 | spellcheck_filenames: true 46 | -------------------------------------------------------------------------------- /.yamllint.yaml: -------------------------------------------------------------------------------- 1 | extends: "default" 2 | 3 | ignore: | 4 | .build/ 5 | .docker/ 6 | vendor/ 7 | node_modules/ 8 | .yarnrc.yml 9 | .yarn/ 10 | 11 | rules: 12 | braces: 13 | max-spaces-inside-empty: 0 14 | max-spaces-inside: 1 15 | min-spaces-inside-empty: 0 16 | min-spaces-inside: 1 17 | brackets: 18 | max-spaces-inside-empty: 0 19 | max-spaces-inside: 0 20 | min-spaces-inside-empty: 0 21 | min-spaces-inside: 0 22 | colons: 23 | max-spaces-after: 1 24 | max-spaces-before: 0 25 | commas: 26 | max-spaces-after: 1 27 | max-spaces-before: 0 28 | min-spaces-after: 1 29 | comments: 30 | ignore-shebangs: true 31 | min-spaces-from-content: 1 32 | require-starting-space: true 33 | comments-indentation: "enable" 34 | document-end: 35 | present: false 36 | document-start: 37 | present: false 38 | indentation: 39 | check-multi-line-strings: false 40 | indent-sequences: true 41 | spaces: 4 42 | empty-lines: 43 | max-end: 0 44 | max-start: 0 45 | max: 1 46 | empty-values: 47 | forbid-in-block-mappings: true 48 | forbid-in-flow-mappings: true 49 | hyphens: 50 | max-spaces-after: 4 51 | key-duplicates: "enable" 52 | key-ordering: "disable" 53 | line-length: "disable" 54 | new-line-at-end-of-file: "enable" 55 | new-lines: 56 | type: "unix" 57 | octal-values: 58 | forbid-implicit-octal: true 59 | quoted-strings: 60 | quote-type: "double" 61 | trailing-spaces: "enable" 62 | truthy: 63 | allowed-values: 64 | - "false" 65 | - "true" 66 | 67 | yaml-files: 68 | - "*.yaml" 69 | - "*.yml" 70 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [1.0.0-alpha.10](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.9...v1.0.0-alpha.10) (2021-09-24) 2 | 3 | 4 | ### Bug Fixes 5 | 6 | * updated all deps ([3647eaa](https://github.com/narrowspark/template-sync-action/commit/3647eaa1700e2f06e94f2dbd8c9736abf792298a)) 7 | 8 | ## [1.0.0-alpha.9](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.8...v1.0.0-alpha.9) (2021-03-01) 9 | 10 | 11 | ### Bug Fixes 12 | 13 | * fixed release flow ([515274b](https://github.com/narrowspark/template-sync-action/commit/515274b1b50d775abdcfabfd6a34f5da1ef84d8b)) 14 | 15 | ## [1.0.0-alpha.8](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.7...v1.0.0-alpha.8) (2021-02-22) 16 | 17 | 18 | ### Features 19 | 20 | * added commitlint ([bb6d375](https://github.com/narrowspark/template-sync-action/commit/bb6d3754507cbb071663c74b52f6d9fa27f8ca1c)) 21 | * added semantic release workflow ([7a40fdf](https://github.com/narrowspark/template-sync-action/commit/7a40fdfaf83bca2130b1390932001607c6b1356e)) 22 | * added text lint ([1de1408](https://github.com/narrowspark/template-sync-action/commit/1de14083b075898d1581778297ef171a1011ab79)) 23 | * merge master (main) into alpha ([ea6eed2](https://github.com/narrowspark/template-sync-action/commit/ea6eed254bfd9393e92fd88bd02277162912fa37)) 24 | * update the dependabot config ([2f438ce](https://github.com/narrowspark/template-sync-action/commit/2f438ceea41759f824122399cc3696a3da7ff5ed)) 25 | * upgraded dependencies ([2ea0d3a](https://github.com/narrowspark/template-sync-action/commit/2ea0d3a0728003537de4b15c2c9ebadc2c4675b4)) 26 | 27 | 28 | ### Bug Fixes 29 | 30 | * changed node version back to 12 ([5ce2fc9](https://github.com/narrowspark/template-sync-action/commit/5ce2fc97c87d7dc0e312843d66f50ee38d271cdf)) 31 | * fixed error handling in github-manager.ts ([1b790ac](https://github.com/narrowspark/template-sync-action/commit/1b790ac37b7c93216fd88c54a3d54344ec73dd26)) 32 | * fixed test pipe ([87f5b05](https://github.com/narrowspark/template-sync-action/commit/87f5b05a45e630416f115f3af8dc986033e86072)) 33 | * fixed wrong type ([90f34c7](https://github.com/narrowspark/template-sync-action/commit/90f34c77a6707467c14c1bc0d949ce4173522423)) 34 | 35 | ## [1.0.0-alpha.7](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.6...v1.0.0-alpha.7) (2020-05-14) 36 | 37 | 38 | ### Bug Fixes 39 | 40 | * fixed error handling in github-manager.ts ([6972d59](https://github.com/narrowspark/template-sync-action/commit/6972d59b0ab409e80094858f20bd80a6584056af)) 41 | 42 | ## [1.0.0-alpha.6](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.5...v1.0.0-alpha.6) (2020-05-14) 43 | 44 | 45 | ### Bug Fixes 46 | 47 | * fixed uuid import ([43eb921](https://github.com/narrowspark/template-sync-action/commit/43eb9216ccdefdec3cdd34ca24f97279244e91b0)) 48 | 49 | ## [1.0.0-alpha.5](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.4...v1.0.0-alpha.5) (2020-05-13) 50 | 51 | 52 | ### Bug Fixes 53 | 54 | * changed node version back to 12 ([b174d93](https://github.com/narrowspark/template-sync-action/commit/b174d9385ddb7f7b80ee5b9e4321cbdf48d4a562)) 55 | 56 | ## [1.0.0-alpha.4](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.3...v1.0.0-alpha.4) (2020-05-13) 57 | 58 | 59 | ### Features 60 | 61 | * added commitlint ([92f9f72](https://github.com/narrowspark/template-sync-action/commit/92f9f72215f79e5010af1da2de8effb68c7acde9)) 62 | 63 | ## [1.0.0-alpha.3](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.2...v1.0.0-alpha.3) (2020-05-13) 64 | 65 | 66 | ### Bug Fixes 67 | 68 | * added missing files to semantic git ([31cdad5](https://github.com/narrowspark/template-sync-action/commit/31cdad5ce851c220a47d8822e1b2bcf14410573f)) 69 | 70 | ## [1.0.0-alpha.2](https://github.com/narrowspark/template-sync-action/compare/v1.0.0-alpha.1...v1.0.0-alpha.2) (2020-05-13) 71 | 72 | 73 | ### Bug Fixes 74 | 75 | * changed .releaserc to release.config.js ([acf953f](https://github.com/narrowspark/template-sync-action/commit/acf953f5b2d8f9ea6fbc0c4c17a54198a36c996f)) 76 | 77 | ## 1.0.0-alpha.1 (2020-05-13) 78 | 79 | 80 | ### Features 81 | 82 | * added semantic release workflow ([15a782f](https://github.com/narrowspark/template-sync-action/commit/15a782f148dfa76b38dd39a1dafa10d4f7396ba7)) 83 | * updated readme with semantic release shield ([56f6e23](https://github.com/narrowspark/template-sync-action/commit/56f6e23039ec2232887d67c3adf183703d6d6b48)) 84 | 85 | 86 | ### Bug Fixes 87 | 88 | * fixed action name ([489c879](https://github.com/narrowspark/template-sync-action/commit/489c8795bf0fb0093cef1eb180d1630a8ca86cc2)) 89 | * fixed example ([e6c5a86](https://github.com/narrowspark/template-sync-action/commit/e6c5a866c5da6c6bf14ceafda87909694ef7cde7)) 90 | * fixed yml syntax of semantic-release.yml ([b4ca974](https://github.com/narrowspark/template-sync-action/commit/b4ca974560c4c89c4ae474691b7bab2d34e14a96)) 91 | * updated github action icon ([8f3c6fa](https://github.com/narrowspark/template-sync-action/commit/8f3c6fadee077a9c52d24b8732ea1d4ba1299cdf)) 92 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Daniel Bannert 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 6 | documentation files (the _Software_), to deal in the Software without restriction, including without limitation the 7 | rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit 8 | persons to whom the Software is furnished to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the 11 | Software. 12 | 13 | THE SOFTWARE IS PROVIDED **AS IS**, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 14 | WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 15 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 16 | OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Narrowspark Template Sync Action

2 |

3 | 4 | 5 | 6 | 7 |

8 | 9 | This [github action](https://github.com/features/actions) gives you the possibility to sync your repository with a [github template repository](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-template-repository). 10 | 11 | --- 12 | 13 |
14 |

15 | 16 | Daniel Bannert's open source work is supported by the community on GitHub Sponsors 17 | 18 |

19 |
20 | 21 | --- 22 | 23 | ## Example Workflow 24 | ```yml 25 | name: 'Template Sync' 26 | 27 | on: 28 | schedule: 29 | - cron: '0 8 * * *' 30 | 31 | jobs: 32 | sync: 33 | 34 | runs-on: ubuntu-latest 35 | 36 | steps: 37 | - uses: actions/checkout@v2 38 | - uses: narrowspark/template-sync-action@v1 39 | with: 40 | github_token: ${{ secrets.GITHUB_TOKEN }} 41 | git_author_name: prisis 42 | git_author_email: d.bannert@anolilab.de 43 | template_repository: narrowspark/php-library-template 44 | ref: refs/heads/master 45 | ``` 46 | 47 | ## Usage 48 | 49 | 50 | ```yaml 51 | - uses: actions/template-sync@v1 52 | with: 53 | # Personal access token (PAT) used to fetch the repository. The PAT is configured 54 | # with the local git config, which enables your scripts to run authenticated git 55 | # commands. The post-job step removes the PAT. We recommend using a service 56 | # account with the least permissions necessary. Also when generating a new PAT, 57 | # select the least scopes necessary. [Learn more about creating and using 58 | # encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) 59 | # Default: ${{ github.token }} 60 | github_token: '' 61 | 62 | # SSH key used to fetch the repository. The SSH key is configured with the local 63 | # git config, which enables your scripts to run authenticated git commands. The 64 | # post-job step removes the SSH key. We recommend using a service account with the 65 | # least permissions necessary. [Learn more about creating and using encrypted 66 | # secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) 67 | ssh-key: '' 68 | 69 | # Known hosts in addition to the user and global host key database. The public SSH 70 | # keys for a host may be obtained using the utility `ssh-keyscan`. For example, 71 | # `ssh-keyscan github.com`. The public key for github.com is always implicitly 72 | # added. 73 | ssh-known-hosts: '' 74 | 75 | # Whether to perform strict host key checking. When true, adds the options 76 | # `StrictHostKeyChecking=yes` and `CheckHostIP=no` to the SSH command line. Use 77 | # the input `ssh-known-hosts` to configure additional hosts. 78 | # Default: true 79 | ssh-strict: '' 80 | 81 | # Whether to configure the token or SSH key with the local git config 82 | # Default: true 83 | persist-credentials: '' 84 | 85 | # Includes your name to the commit 86 | git_author_name: '' 87 | 88 | # Includes your email to the commit 89 | git_author_email: '' 90 | 91 | # Owner of the current repository 92 | owner: '' 93 | 94 | # The current repository name 95 | repo: '' 96 | 97 | # The title of the pull request 98 | pr_title: '' 99 | 100 | # The message in the pull request 101 | pr_message: '' 102 | 103 | # The branch, tag or SHA to checkout. When checking out the repository that 104 | # triggered a workflow, this defaults to the reference or SHA for that event. 105 | # Otherwise, defaults to `master`. 106 | ref: '' 107 | 108 | template_repository: '' 109 | 110 | # The branch, tag or SHA to checkout. When checking out the repository that 111 | # triggered a workflow, this defaults to the reference or SHA for that event. 112 | # Otherwise, defaults to `master`. 113 | template_ref: '' 114 | 115 | # Extend the default list with excluded files that shouldn't be synced. 116 | ignore_list: '' 117 | ``` 118 | 119 | -------------------------------------------------------------------------------- /UPGRADE.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anolilab/template-sync-action/ff5179de3d183c46b0f2fc0e4606241a11d23bf5/UPGRADE.md -------------------------------------------------------------------------------- /__tests__/git-version.test.ts: -------------------------------------------------------------------------------- 1 | import { GitVersion } from "../lib/git-version"; 2 | 3 | describe("git-version tests", () => { 4 | it("basics", async () => { 5 | let version = new GitVersion(""); 6 | expect(version.isValid()).toBeFalsy(); 7 | 8 | version = new GitVersion("asdf"); 9 | expect(version.isValid()).toBeFalsy(); 10 | 11 | version = new GitVersion("1.2"); 12 | expect(version.isValid()).toBeTruthy(); 13 | expect(version.toString()).toBe("1.2"); 14 | 15 | version = new GitVersion("1.2.3"); 16 | expect(version.isValid()).toBeTruthy(); 17 | expect(version.toString()).toBe("1.2.3"); 18 | }); 19 | 20 | it("check minimum", async () => { 21 | let version = new GitVersion("4.5"); 22 | expect(version.checkMinimum(new GitVersion("3.6"))).toBeTruthy(); 23 | expect(version.checkMinimum(new GitVersion("3.6.7"))).toBeTruthy(); 24 | expect(version.checkMinimum(new GitVersion("4.4"))).toBeTruthy(); 25 | expect(version.checkMinimum(new GitVersion("4.5"))).toBeTruthy(); 26 | expect(version.checkMinimum(new GitVersion("4.5.0"))).toBeTruthy(); 27 | expect(version.checkMinimum(new GitVersion("4.6"))).toBeFalsy(); 28 | expect(version.checkMinimum(new GitVersion("4.6.0"))).toBeFalsy(); 29 | expect(version.checkMinimum(new GitVersion("5.1"))).toBeFalsy(); 30 | expect(version.checkMinimum(new GitVersion("5.1.2"))).toBeFalsy(); 31 | 32 | version = new GitVersion("4.5.6"); 33 | expect(version.checkMinimum(new GitVersion("3.6"))).toBeTruthy(); 34 | expect(version.checkMinimum(new GitVersion("3.6.7"))).toBeTruthy(); 35 | expect(version.checkMinimum(new GitVersion("4.4"))).toBeTruthy(); 36 | expect(version.checkMinimum(new GitVersion("4.5"))).toBeTruthy(); 37 | expect(version.checkMinimum(new GitVersion("4.5.5"))).toBeTruthy(); 38 | expect(version.checkMinimum(new GitVersion("4.5.6"))).toBeTruthy(); 39 | expect(version.checkMinimum(new GitVersion("4.5.7"))).toBeFalsy(); 40 | expect(version.checkMinimum(new GitVersion("4.6"))).toBeFalsy(); 41 | expect(version.checkMinimum(new GitVersion("4.6.0"))).toBeFalsy(); 42 | expect(version.checkMinimum(new GitVersion("5.1"))).toBeFalsy(); 43 | expect(version.checkMinimum(new GitVersion("5.1.2"))).toBeFalsy(); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /__tests__/ref-helper.test.ts: -------------------------------------------------------------------------------- 1 | import * as refHelper from "../lib/ref-helper"; 2 | import { IGitCommandManager } from "../lib/interfaces"; 3 | 4 | let git: IGitCommandManager; 5 | 6 | describe("ref-helper tests", () => { 7 | beforeEach(() => { 8 | git = {} as unknown as IGitCommandManager; 9 | }); 10 | 11 | it("getCheckoutInfo requires git", async () => { 12 | const git = null as unknown as IGitCommandManager; 13 | try { 14 | await refHelper.getCheckoutInfo(git, "refs/heads/my/branch"); 15 | throw new Error("Should not reach here"); 16 | } catch (err) { 17 | expect((err as Error).message).toBe("Arg git cannot be empty"); 18 | } 19 | }); 20 | 21 | it("getCheckoutInfo requires ref", async () => { 22 | try { 23 | await refHelper.getCheckoutInfo(git, ""); 24 | throw new Error("Should not reach here"); 25 | } catch (err) { 26 | expect((err as Error).message).toBe("Args ref cannot be empty"); 27 | } 28 | }); 29 | 30 | it("getCheckoutInfo refs/heads/", async () => { 31 | const checkoutInfo = await refHelper.getCheckoutInfo(git, "refs/heads/my/branch"); 32 | expect(checkoutInfo.ref).toBe("my/branch"); 33 | expect(checkoutInfo.startPoint).toBe("refs/remotes/origin/my/branch"); 34 | }); 35 | 36 | it("getCheckoutInfo refs/pull/", async () => { 37 | const checkoutInfo = await refHelper.getCheckoutInfo(git, "refs/pull/123/merge"); 38 | expect(checkoutInfo.ref).toBe("refs/remotes/pull/123/merge"); 39 | expect(checkoutInfo.startPoint).toBeFalsy(); 40 | }); 41 | 42 | it("getCheckoutInfo refs/tags/", async () => { 43 | const checkoutInfo = await refHelper.getCheckoutInfo(git, "refs/tags/my-tag"); 44 | expect(checkoutInfo.ref).toBe("refs/tags/my-tag"); 45 | expect(checkoutInfo.startPoint).toBeFalsy(); 46 | }); 47 | 48 | it("getCheckoutInfo unqualified branch only", async () => { 49 | git.branchExists = jest.fn(async () => { 50 | return true; 51 | }); 52 | 53 | const checkoutInfo = await refHelper.getCheckoutInfo(git, "my/branch"); 54 | 55 | expect(checkoutInfo.ref).toBe("my/branch"); 56 | expect(checkoutInfo.startPoint).toBe("refs/remotes/origin/my/branch"); 57 | }); 58 | 59 | it("getCheckoutInfo unqualified tag only", async () => { 60 | git.branchExists = jest.fn(async () => { 61 | return false; 62 | }); 63 | git.tagExists = jest.fn(async () => { 64 | return true; 65 | }); 66 | 67 | const checkoutInfo = await refHelper.getCheckoutInfo(git, "my-tag"); 68 | 69 | expect(checkoutInfo.ref).toBe("refs/tags/my-tag"); 70 | expect(checkoutInfo.startPoint).toBeFalsy(); 71 | }); 72 | 73 | it("getCheckoutInfo unqualified ref only, not a branch or tag", async () => { 74 | git.branchExists = jest.fn(async () => { 75 | return false; 76 | }); 77 | git.tagExists = jest.fn(async () => { 78 | return false; 79 | }); 80 | 81 | try { 82 | await refHelper.getCheckoutInfo(git, "my-ref"); 83 | throw new Error("Should not reach here"); 84 | } catch (err) { 85 | expect((err as Error).message).toBe("A branch or tag with the name 'my-ref' could not be found"); 86 | } 87 | }); 88 | 89 | it("getRefSpec requires ref or commit", async () => { 90 | try { 91 | refHelper.getRefSpec(""); 92 | throw new Error("Should not reach here"); 93 | } catch (err) { 94 | expect((err as Error).message).toBe("Arg ref cannot be empty"); 95 | } 96 | }); 97 | 98 | it("getRefSpec unqualified ref only", async () => { 99 | const refSpec = refHelper.getRefSpec("my-ref"); 100 | expect(refSpec.length).toBe(2); 101 | expect(refSpec[0]).toBe("+refs/heads/my-ref*:refs/remotes/origin/my-ref*"); 102 | expect(refSpec[1]).toBe("+refs/tags/my-ref*:refs/tags/my-ref*"); 103 | }); 104 | 105 | it("getRefSpec refs/heads/ only", async () => { 106 | const refSpec = refHelper.getRefSpec("refs/heads/my/branch"); 107 | expect(refSpec.length).toBe(1); 108 | expect(refSpec[0]).toBe("+refs/heads/my/branch:refs/remotes/origin/my/branch"); 109 | }); 110 | 111 | it("getRefSpec refs/pull/ only", async () => { 112 | const refSpec = refHelper.getRefSpec("refs/pull/123/merge"); 113 | expect(refSpec.length).toBe(1); 114 | expect(refSpec[0]).toBe("+refs/pull/123/merge:refs/remotes/pull/123/merge"); 115 | }); 116 | 117 | it("getRefSpec refs/tags/ only", async () => { 118 | const refSpec = refHelper.getRefSpec("refs/tags/my-tag"); 119 | expect(refSpec.length).toBe(1); 120 | expect(refSpec[0]).toBe("+refs/tags/my-tag:refs/tags/my-tag"); 121 | }); 122 | }); 123 | -------------------------------------------------------------------------------- /__tests__/retry-helper.test.ts: -------------------------------------------------------------------------------- 1 | import * as core from "@actions/core"; 2 | import { RetryHelper } from "../lib/retry-helper"; 3 | 4 | let info: string[]; 5 | let retryHelper: any; 6 | 7 | describe("retry-helper tests", () => { 8 | beforeAll(() => { 9 | // Mock @actions/core info() 10 | jest.spyOn(core, "info").mockImplementation((message: string) => { 11 | info.push(message); 12 | }); 13 | 14 | retryHelper = new RetryHelper(3, 0, 0); 15 | }); 16 | 17 | beforeEach(() => { 18 | // Reset info 19 | info = []; 20 | }); 21 | 22 | afterAll(() => { 23 | // Restore 24 | jest.restoreAllMocks(); 25 | }); 26 | 27 | it("first attempt succeeds", async () => { 28 | const actual = await retryHelper.execute(async () => { 29 | return "some result"; 30 | }); 31 | expect(actual).toBe("some result"); 32 | expect(info).toHaveLength(0); 33 | }); 34 | 35 | it("second attempt succeeds", async () => { 36 | let attempts = 0; 37 | const actual = await retryHelper.execute(() => { 38 | if (++attempts == 1) { 39 | throw new Error("some error"); 40 | } 41 | 42 | return Promise.resolve("some result"); 43 | }); 44 | expect(attempts).toBe(2); 45 | expect(actual).toBe("some result"); 46 | expect(info).toHaveLength(2); 47 | expect(info[0]).toBe("some error"); 48 | expect(info[1]).toMatch(/Waiting .+ seconds before trying again/); 49 | }); 50 | 51 | it("third attempt succeeds", async () => { 52 | let attempts = 0; 53 | const actual = await retryHelper.execute(() => { 54 | if (++attempts < 3) { 55 | throw new Error(`some error ${attempts}`); 56 | } 57 | 58 | return Promise.resolve("some result"); 59 | }); 60 | expect(attempts).toBe(3); 61 | expect(actual).toBe("some result"); 62 | expect(info).toHaveLength(4); 63 | expect(info[0]).toBe("some error 1"); 64 | expect(info[1]).toMatch(/Waiting .+ seconds before trying again/); 65 | expect(info[2]).toBe("some error 2"); 66 | expect(info[3]).toMatch(/Waiting .+ seconds before trying again/); 67 | }); 68 | 69 | it("all attempts fail succeeds", async () => { 70 | let attempts = 0; 71 | 72 | try { 73 | await retryHelper.execute(() => { 74 | throw new Error(`some error ${++attempts}`); 75 | }); 76 | } catch (err) { 77 | 78 | expect((err as Error).message).toBe("some error 3"); 79 | } 80 | 81 | expect(attempts).toBe(3); 82 | expect(info).toHaveLength(4); 83 | expect(info[0]).toBe("some error 1"); 84 | expect(info[1]).toMatch(/Waiting .+ seconds before trying again/); 85 | expect(info[2]).toBe("some error 2"); 86 | expect(info[3]).toMatch(/Waiting .+ seconds before trying again/); 87 | }); 88 | }); 89 | -------------------------------------------------------------------------------- /action.yml: -------------------------------------------------------------------------------- 1 | name: 'github-template-sync-action' 2 | description: 'Keep your github template fork up to date' 3 | author: 'prisis' 4 | inputs: 5 | github_token: 6 | description: > 7 | Personal access token (PAT) used to fetch the repository. The PAT is configured 8 | with the local git config, which enables your scripts to run authenticated git 9 | commands. The post-job step removes the PAT. 10 | We recommend using a service account with the least permissions necessary. 11 | Also when generating a new PAT, select the least scopes necessary. 12 | [Learn more about creating and using encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) 13 | default: ${{ github.token }} 14 | required: false 15 | 16 | ssh-key: 17 | description: > 18 | SSH key used to fetch the repository. The SSH key is configured with the local 19 | git config, which enables your scripts to run authenticated git commands. 20 | The post-job step removes the SSH key. 21 | We recommend using a service account with the least permissions necessary. 22 | [Learn more about creating and using 23 | encrypted secrets](https://help.github.com/en/actions/automating-your-workflow-with-github-actions/creating-and-using-encrypted-secrets) 24 | required: false 25 | ssh-known-hosts: 26 | description: > 27 | Known hosts in addition to the user and global host key database. The public 28 | SSH keys for a host may be obtained using the utility `ssh-keyscan`. For example, 29 | `ssh-keyscan github.com`. The public key for github.com is always implicitly added. 30 | required: false 31 | ssh-strict: 32 | description: > 33 | Whether to perform strict host key checking. When true, adds the options `StrictHostKeyChecking=yes` 34 | and `CheckHostIP=no` to the SSH command line. Use the input `ssh-known-hosts` to 35 | configure additional hosts. 36 | default: 'true' 37 | required: false 38 | persist-credentials: 39 | description: 'Whether to configure the token or SSH key with the local git config' 40 | default: 'true' 41 | required: false 42 | 43 | git_author_name: 44 | description: 'Includes your name to the commit' 45 | required: true 46 | git_author_email: 47 | description: 'Includes your email to the commit' 48 | required: true 49 | 50 | owner: 51 | description: 'Owner of the current repository' 52 | required: false 53 | repo: 54 | description: 'The current repository name' 55 | required: false 56 | 57 | pr_title: 58 | description: 'The title of the pull request' 59 | required: false 60 | pr_message: 61 | description: 'The message in the pull request' 62 | required: false 63 | 64 | ref: 65 | description: > 66 | The branch, tag or SHA to checkout. When checking out the repository that 67 | triggered a workflow, this defaults to the reference or SHA for that 68 | event. Otherwise, defaults to `master`. 69 | required: true 70 | 71 | template_repository: 72 | description: '' 73 | required: true 74 | template_ref: 75 | description: > 76 | The branch, tag or SHA to checkout. When checking out the repository that 77 | triggered a workflow, this defaults to the reference or SHA for that 78 | event. Otherwise, defaults to `master`. 79 | required: false 80 | 81 | ignore_list: 82 | description: > 83 | Extend the default list with excluded files that shouldn't be synced. 84 | required: false 85 | 86 | branding: 87 | icon: "refresh-ccw" 88 | color: yellow 89 | 90 | runs: 91 | using: 'node12' 92 | main: 'dist/index.js' 93 | post: dist/index.js 94 | -------------------------------------------------------------------------------- /commitlint.config.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ["@commitlint/config-conventional"], 3 | }; 4 | 5 | -------------------------------------------------------------------------------- /dist/problem-matcher.json: -------------------------------------------------------------------------------- 1 | { 2 | "problemMatcher": [ 3 | { 4 | "owner": "template-sync", 5 | "pattern": [ 6 | { 7 | "regexp": "^(fatal|error): (.*)$", 8 | "message": 2 9 | } 10 | ] 11 | } 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | clearMocks: true, 3 | moduleFileExtensions: ['js', 'ts'], 4 | testEnvironment: 'node', 5 | testMatch: ['**/*.test.ts'], 6 | testRunner: 'jest-circus/runner', 7 | transform: { 8 | '^.+\\.ts$': 'ts-jest' 9 | }, 10 | roots: ['/__tests__'], 11 | verbose: true, 12 | collectCoverage: true 13 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "template-sync-action", 3 | "version": "1.0.0-alpha.10", 4 | "private": true, 5 | "description": "Keep your github template fork up to date.", 6 | "keywords": [ 7 | "actions", 8 | "node", 9 | "setup", 10 | "fork", 11 | "automation", 12 | "sync", 13 | "github-template", 14 | "github-templates" 15 | ], 16 | "repository": { 17 | "type": "git", 18 | "url": "git+https://github.com/narrowspark/template-sync-action.git" 19 | }, 20 | "license": "MIT", 21 | "author": "prisis", 22 | "main": "lib/main.js", 23 | "scripts": { 24 | "postinstall": "husky install", 25 | "build": "tsc && tsc src/misc/generate-docs.ts --outDir ./lib/misc", 26 | "lint": "yarn run lint:eslint && yarn run lint:text", 27 | "lint:staged": "lint-staged", 28 | "lint:text": "textlint ./.build/ISSUE_TEMPLATE/** ./src/** ./docs/** ./README.md ./UPGRADE.md --dry-run", 29 | "lint:text:fix": "textlint ./.build/ISSUE_TEMPLATE/** ./src/** ./docs/** ./README.md ./UPGRADE.md --fix", 30 | "fix:lint:eslint": "yarn run lint --fix", 31 | "lint:eslint": "cross-env NO_LOGS=true eslint -c ./.eslintrc.cjs --ext .js,.ts,.tsx ./src", 32 | "pack": "ncc build", 33 | "test": "jest", 34 | "all": "yarn run lint && yarn run build && yarn run pack && yarn test && node lib/misc/generate-docs.js" 35 | }, 36 | "commitlint": { 37 | "extends": [ 38 | "@commitlint/config-conventional" 39 | ] 40 | }, 41 | "lint-staged": { 42 | "*.{js,jsx,less,md,json}": [ 43 | "prettier --write" 44 | ] 45 | }, 46 | "config": { 47 | "commitizen": { 48 | "path": "./node_modules/cz-conventional-changelog" 49 | } 50 | }, 51 | "dependencies": { 52 | "@actions/core": "1.5.0", 53 | "@actions/exec": "1.1.0", 54 | "@actions/io": "1.1.1", 55 | "@actions/tool-cache": "1.7.1", 56 | "@octokit/action": "3.17.0", 57 | "@octokit/plugin-retry": "3.0.9", 58 | "filehound": "1.17.5", 59 | "fs-extra": "10.0.0", 60 | "uuid": "8.3.2" 61 | }, 62 | "devDependencies": { 63 | "@anolilab/eslint-config": "2.2.0", 64 | "@anolilab/textlint-config": "2.0.9", 65 | "@anolilab/prettier-config": "2.0.5", 66 | "@octokit/fixtures": "22.0.2", 67 | "@octokit/types": "6.34.0", 68 | "@types/bluebird": "3.5.36", 69 | "@types/fs-extra": "9.0.13", 70 | "@types/jest": "27.4.0", 71 | "@types/js-yaml": "4.0.5", 72 | "@types/node": "16.11.18", 73 | "@types/promise-retry": "1.1.3", 74 | "@types/uuid": "8.3.3", 75 | "@typescript-eslint/eslint-plugin": "4.33.0", 76 | "@typescript-eslint/parser": "4.33.0", 77 | "@zeit/ncc": "0.22.3", 78 | "eslint": "7.32.0", 79 | "eslint-plugin-jest": "24.7.0", 80 | "husky": "7.0.4", 81 | "jest": "27.4.5", 82 | "jest-circus": "27.4.5", 83 | "js-yaml": "4.1.0", 84 | "prettier": "2.5.1", 85 | "ts-jest": "27.1.2", 86 | "typescript": "4.5.4", 87 | "cross-env": "^7.0.3" 88 | }, 89 | "engines": { 90 | "node": ">=12" 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/git-auth-helper.ts: -------------------------------------------------------------------------------- 1 | import * as assert from "assert"; 2 | import * as core from "@actions/core"; 3 | import * as coreCommand from "@actions/core/lib/command"; 4 | import * as exec from "@actions/exec"; 5 | import * as fs from "fs"; 6 | import * as io from "@actions/io"; 7 | import * as os from "os"; 8 | import * as path from "path"; 9 | import { v4 as uuidv4 } from "uuid"; 10 | import { URL } from "url"; 11 | import { IGitCommandManager, ISettings } from "./interfaces"; 12 | import * as stateHelper from "./state-helper"; 13 | 14 | const IS_WINDOWS = process.platform === "win32"; 15 | const SSH_COMMAND_KEY = "core.sshCommand"; 16 | 17 | export class GitAuthHelper { 18 | private readonly git: IGitCommandManager; 19 | private readonly settings: ISettings; 20 | private readonly tokenConfigKey: string; 21 | private readonly tokenConfigValue: string; 22 | private readonly tokenPlaceholderConfigValue: string; 23 | // @ts-ignore 24 | private readonly insteadOfKey: string; 25 | // @ts-ignore 26 | private readonly insteadOfValue: string; 27 | private sshCommand = ""; 28 | private sshKeyPath = ""; 29 | private sshKnownHostsPath = ""; 30 | 31 | constructor(git: IGitCommandManager, settings: ISettings) { 32 | this.git = git; 33 | this.settings = settings; 34 | 35 | // Token auth header 36 | const serverUrl = new URL(process.env["GITHUB_URL"] || "https://github.com"); 37 | 38 | this.tokenConfigKey = `http.${serverUrl.origin}/.extraheader`; // "origin" is SCHEME://HOSTNAME[:PORT] 39 | 40 | const basicCredential = Buffer.from(`x-access-token:${this.settings.authToken}`, "utf8").toString("base64"); 41 | 42 | core.setSecret(basicCredential); 43 | 44 | this.tokenPlaceholderConfigValue = `AUTHORIZATION: basic ***`; 45 | this.tokenConfigValue = `AUTHORIZATION: basic ${basicCredential}`; 46 | 47 | // Instead of SSH URL 48 | this.insteadOfKey = `url.${serverUrl.origin}/.insteadOf`; // "origin" is SCHEME://HOSTNAME[:PORT] 49 | this.insteadOfValue = `git@${serverUrl.hostname}:`; 50 | } 51 | 52 | async configureAuth(): Promise { 53 | // Remove possible previous values 54 | await this.removeAuth(); 55 | 56 | // Configure new values 57 | await this.configureSsh(); 58 | await this.configureToken(); 59 | } 60 | 61 | async removeAuth(): Promise { 62 | await this.removeSsh(); 63 | await this.removeToken(); 64 | } 65 | 66 | private async configureSsh(): Promise { 67 | if (!this.settings.sshKey) { 68 | return; 69 | } 70 | 71 | // Write key 72 | const runnerTemp = process.env["RUNNER_TEMP"] || ""; 73 | assert.ok(runnerTemp, "RUNNER_TEMP is not defined"); 74 | 75 | const uniqueId = uuidv4(); 76 | 77 | stateHelper.setSshKeyPath(path.join(runnerTemp, uniqueId)); 78 | 79 | coreCommand.issueCommand("save-state", { name: "sshKeyPath" }, this.sshKeyPath); 80 | 81 | await fs.promises.mkdir(runnerTemp, { recursive: true }); 82 | await fs.promises.writeFile(this.sshKeyPath, `${this.settings.sshKey.trim()}\n`, { mode: 0o600 }); 83 | 84 | // Remove inherited permissions on Windows 85 | if (IS_WINDOWS) { 86 | const icacls = await io.which("icacls.exe"); 87 | 88 | await exec.exec(`"${icacls}" "${this.sshKeyPath}" /grant:r "${process.env["USERDOMAIN"]}\\${process.env["USERNAME"]}:F"`); 89 | await exec.exec(`"${icacls}" "${this.sshKeyPath}" /inheritance:r`); 90 | } 91 | 92 | // Write known hosts 93 | const userKnownHostsPath = path.join(os.homedir(), ".ssh", "known_hosts"); 94 | let userKnownHosts = ""; 95 | 96 | try { 97 | userKnownHosts = (await fs.promises.readFile(userKnownHostsPath)).toString(); 98 | } catch (err) { 99 | if ((err as Error & { code: string }).code !== "ENOENT") { 100 | throw err; 101 | } 102 | } 103 | 104 | let knownHosts = ""; 105 | 106 | if (userKnownHosts) { 107 | knownHosts += `# Begin from ${userKnownHostsPath}\n${userKnownHosts}\n# End from ${userKnownHostsPath}\n`; 108 | } 109 | 110 | if (this.settings.sshKnownHosts) { 111 | knownHosts += `# Begin from input known hosts\n${this.settings.sshKnownHosts}\n# end from input known hosts\n`; 112 | } 113 | 114 | knownHosts += `# Begin implicitly added github.com\ngithub.com ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==\n# End implicitly added github.com\n`; 115 | 116 | this.sshKnownHostsPath = path.join(runnerTemp, `${uniqueId}_known_hosts`); 117 | 118 | stateHelper.setSshKnownHostsPath(this.sshKnownHostsPath); 119 | 120 | coreCommand.issueCommand("save-state", { name: "sshKnownHostsPath" }, this.sshKnownHostsPath); 121 | 122 | await fs.promises.writeFile(this.sshKnownHostsPath, knownHosts); 123 | 124 | // Configure GIT_SSH_COMMAND 125 | const sshPath = await io.which("ssh", true); 126 | 127 | this.sshCommand = `"${sshPath}" -i "$RUNNER_TEMP/${path.basename(this.sshKeyPath)}"`; 128 | 129 | if (this.settings.sshStrict) { 130 | this.sshCommand += " -o StrictHostKeyChecking=yes -o CheckHostIP=no"; 131 | } 132 | 133 | this.sshCommand += ` -o "UserKnownHostsFile=$RUNNER_TEMP/${path.basename(this.sshKnownHostsPath)}"`; 134 | 135 | core.info(`Temporarily overriding GIT_SSH_COMMAND=${this.sshCommand}`); 136 | 137 | this.git.setEnvironmentVariable("GIT_SSH_COMMAND", this.sshCommand); 138 | 139 | // Configure core.sshCommand 140 | if (this.settings.persistCredentials) { 141 | await this.git.config(SSH_COMMAND_KEY, this.sshCommand); 142 | } 143 | } 144 | 145 | private async configureToken(configPath?: string, globalConfig?: boolean): Promise { 146 | // Validate args 147 | assert.ok((configPath && globalConfig) || (!configPath && !globalConfig), "Unexpected configureToken parameter combinations"); 148 | 149 | // Default config path 150 | if (!configPath && !globalConfig) { 151 | configPath = path.join(this.git.getWorkingDirectory(), ".git", "config"); 152 | } 153 | 154 | // Configure a placeholder value. This approach avoids the credential being captured 155 | // by process creation audit events, which are commonly logged. For more information, 156 | // refer to https://docs.microsoft.com/en-us/windows-server/identity/ad-ds/manage/component-updates/command-line-process-auditing 157 | await this.git.config(this.tokenConfigKey, this.tokenPlaceholderConfigValue, globalConfig); 158 | 159 | // Replace the placeholder 160 | await this.replaceTokenPlaceholder(configPath || ""); 161 | } 162 | 163 | private async replaceTokenPlaceholder(configPath: string): Promise { 164 | assert.ok(configPath, "configPath is not defined"); 165 | 166 | let content = (await fs.promises.readFile(configPath)).toString(); 167 | const placeholderIndex = content.indexOf(this.tokenPlaceholderConfigValue); 168 | 169 | if (placeholderIndex < 0 || placeholderIndex !== content.lastIndexOf(this.tokenPlaceholderConfigValue)) { 170 | throw new Error(`Unable to replace auth placeholder in ${configPath}`); 171 | } 172 | 173 | assert.ok(this.tokenConfigValue, "tokenConfigValue is not defined"); 174 | 175 | content = content.replace(this.tokenPlaceholderConfigValue, this.tokenConfigValue); 176 | 177 | await fs.promises.writeFile(configPath, content); 178 | } 179 | 180 | private async removeSsh(): Promise { 181 | // SSH key 182 | const keyPath = this.sshKeyPath || stateHelper.SshKeyPath; 183 | if (keyPath) { 184 | try { 185 | await io.rmRF(keyPath); 186 | } catch (err) { 187 | core.debug((err as Error).message); 188 | core.warning(`Failed to remove SSH key '${keyPath}'`); 189 | } 190 | } 191 | 192 | // SSH known hosts 193 | const knownHostsPath = this.sshKnownHostsPath || stateHelper.SshKnownHostsPath; 194 | if (knownHostsPath) { 195 | try { 196 | await io.rmRF(knownHostsPath); 197 | } catch { 198 | // Intentionally empty 199 | } 200 | } 201 | 202 | // SSH command 203 | await this.removeGitConfig(SSH_COMMAND_KEY); 204 | } 205 | 206 | private async removeToken(): Promise { 207 | // HTTP extra header 208 | await this.removeGitConfig(this.tokenConfigKey); 209 | } 210 | 211 | private async removeGitConfig(configKey: string, submoduleOnly = false): Promise { 212 | if (!submoduleOnly) { 213 | if ((await this.git.configExists(configKey)) && !(await this.git.tryConfigUnset(configKey))) { 214 | // Load the config contents 215 | core.warning(`Failed to remove '${configKey}' from the git config`); 216 | } 217 | } 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /src/git-command-manager.ts: -------------------------------------------------------------------------------- 1 | import { GitVersion } from "./git-version"; 2 | import * as core from "@actions/core"; 3 | import * as exec from "@actions/exec"; 4 | import * as io from "@actions/io"; 5 | import fs from "fs-extra"; 6 | import path from "path"; 7 | import { RetryHelper } from "./retry-helper"; 8 | import { IGitCommandManager } from "./interfaces"; 9 | 10 | const retryHelper = new RetryHelper(); 11 | 12 | // Auth header not supported before 2.9 13 | // Wire protocol v2 not supported before 2.18 14 | export const MinimumGitVersion = new GitVersion("2.18"); 15 | 16 | export async function createCommandManager(workingDirectory: string): Promise { 17 | return await GitCommandManager.createCommandManager(workingDirectory); 18 | } 19 | 20 | export class GitCommandManager implements IGitCommandManager { 21 | private gitEnv: { [key: string]: string } = { 22 | GIT_TERMINAL_PROMPT: "0", // Disable git prompt 23 | GCM_INTERACTIVE: "Never", // Disable prompting for git credential manager 24 | }; 25 | 26 | private workingDirectory = ""; 27 | 28 | private gitPath = ""; 29 | 30 | private gitVersion?: GitVersion = undefined; 31 | 32 | private constructor() {} 33 | 34 | static async createCommandManager(workingDirectory: string): Promise { 35 | const result = new GitCommandManager(); 36 | 37 | await result.initializeCommandManager(workingDirectory); 38 | 39 | return result; 40 | } 41 | 42 | private async initializeCommandManager(workingDirectory: string): Promise { 43 | this.workingDirectory = workingDirectory; 44 | this.gitPath = await io.which("git", true); 45 | 46 | // Git version 47 | core.debug("Getting git version"); 48 | 49 | this.gitVersion = new GitVersion(); 50 | const gitOutput = await this.execGit(["version"]); 51 | const stdout = gitOutput.stdout.trim(); 52 | 53 | if (!stdout.includes("\n")) { 54 | const match = stdout.match(/\d+\.\d+(\.\d+)?/); 55 | 56 | if (match) { 57 | this.gitVersion = new GitVersion(match[0]); 58 | } 59 | } 60 | 61 | if (!this.gitVersion.isValid()) { 62 | throw new Error("Unable to determine git version"); 63 | } 64 | 65 | // Set the user agent 66 | const gitHttpUserAgent = `git/${this.gitVersion} (github-actions-checkout)`; 67 | 68 | core.debug(`Set git useragent to: ${gitHttpUserAgent}`); 69 | 70 | this.gitEnv["GIT_HTTP_USER_AGENT"] = gitHttpUserAgent; 71 | } 72 | 73 | checkGitVersion(): void { 74 | if (this.gitVersion === undefined) { 75 | throw new Error("Init the git command manager"); 76 | } 77 | 78 | if (!this.gitVersion.checkMinimum(MinimumGitVersion)) { 79 | throw new Error(`Minimum required git version is ${MinimumGitVersion}. Your git ('${this.gitPath}') is ${this.gitVersion}`); 80 | } 81 | } 82 | 83 | getWorkingDirectory(): string { 84 | return this.workingDirectory; 85 | } 86 | 87 | async init(): Promise { 88 | await this.execGit(["init", this.workingDirectory]); 89 | } 90 | 91 | async fetch(fetchDepth: number, refSpec: string[]): Promise { 92 | const args = ["-c", "protocol.version=2", "fetch", "--no-tags", "--prune", "--progress", "--no-recurse-submodules"]; 93 | 94 | if (fetchDepth > 0) { 95 | args.push(`--depth=${fetchDepth}`); 96 | } else if (fs.existsSync(path.join(this.workingDirectory, ".git", "shallow"))) { 97 | args.push("--unshallow"); 98 | } 99 | 100 | args.push("origin"); 101 | 102 | for (const arg of refSpec) { 103 | args.push(arg); 104 | } 105 | 106 | const that = this; 107 | 108 | await retryHelper.execute(async () => { 109 | await that.execGit(args); 110 | }); 111 | } 112 | 113 | async checkout(ref: string, startPoint: string): Promise { 114 | const args = ["checkout", "--progress", "--force"]; 115 | if (startPoint) { 116 | args.push("-B", ref, startPoint); 117 | } else { 118 | args.push(ref); 119 | } 120 | 121 | await this.execGit(args); 122 | } 123 | 124 | async sha(type: string): Promise { 125 | const output = await this.execGit(["rev-parse", "--verify", type]); 126 | 127 | return output.stdout.trim(); 128 | } 129 | 130 | async status(args: string[] = []): Promise { 131 | const output = await this.execGit(["status"].concat(args)); 132 | 133 | return output.stdout.trim(); 134 | } 135 | 136 | async log1(): Promise { 137 | await this.execGit(["log", "-1"]); 138 | } 139 | 140 | async config(configKey: string, configValue: string, globalConfig?: boolean): Promise { 141 | await this.execGit(["config", globalConfig ? "--global" : "--local", configKey, configValue]); 142 | } 143 | 144 | async configExists(configKey: string, globalConfig?: boolean): Promise { 145 | const pattern = configKey.replace(/[^a-zA-Z0-9_]/g, (x) => { 146 | return `\\${x}`; 147 | }); 148 | const output = await this.execGit(["config", globalConfig ? "--global" : "--local", "--name-only", "--get-regexp", pattern], true); 149 | 150 | return output.exitCode === 0; 151 | } 152 | 153 | async tryConfigUnset(configKey: string, globalConfig?: boolean): Promise { 154 | const output = await this.execGit(["config", globalConfig ? "--global" : "--local", "--unset-all", configKey], true); 155 | 156 | return output.exitCode === 0; 157 | } 158 | 159 | removeEnvironmentVariable(name: string): void { 160 | delete this.gitEnv[name]; 161 | } 162 | 163 | setEnvironmentVariable(name: string, value: string): void { 164 | this.gitEnv[name] = value; 165 | } 166 | 167 | async tryDisableAutomaticGarbageCollection(): Promise { 168 | const output = await this.execGit(["config", "--local", "gc.auto", "0"], true); 169 | 170 | return output.exitCode === 0; 171 | } 172 | 173 | async remoteAdd(remoteName: string, remoteUrl: string): Promise { 174 | await this.execGit(["remote", "add", remoteName, remoteUrl]); 175 | } 176 | 177 | async branchExists(remote: boolean, pattern: string): Promise { 178 | const args = ["branch", "--list"]; 179 | 180 | if (remote) { 181 | args.push("--remote"); 182 | } 183 | 184 | args.push(pattern); 185 | 186 | const output = await this.execGit(args); 187 | 188 | return !!output.stdout.trim(); 189 | } 190 | 191 | async tagExists(pattern: string): Promise { 192 | const output = await this.execGit(["tag", "--list", pattern]); 193 | 194 | return !!output.stdout.trim(); 195 | } 196 | 197 | async addAll(): Promise { 198 | const output = await this.execGit(["add", "--all"]); 199 | 200 | return Boolean(output.exitCode); 201 | } 202 | 203 | async commit(message: string): Promise { 204 | const output = await this.execGit(["commit", "-m", `"${message}"`]); 205 | 206 | return Boolean(output.exitCode); 207 | } 208 | 209 | async push(ref: string): Promise { 210 | const output = await this.execGit(["push", "-u", "origin", ref]); 211 | 212 | return Boolean(output.exitCode); 213 | } 214 | 215 | private async execGit(args: string[], allowAllExitCodes = false): Promise { 216 | fs.existsSync(this.workingDirectory); 217 | 218 | const result = new GitOutput(); 219 | 220 | const env: { [key: string]: string } = {}; 221 | 222 | for (const key of Object.keys(process.env)) { 223 | env[key] = process.env[key] as string; 224 | } 225 | for (const key of Object.keys(this.gitEnv)) { 226 | env[key] = this.gitEnv[key]; 227 | } 228 | 229 | const stdout: string[] = []; 230 | 231 | const options = { 232 | cwd: this.workingDirectory, 233 | env, 234 | ignoreReturnCode: allowAllExitCodes, 235 | listeners: { 236 | stdout: (data: Buffer) => { 237 | stdout.push(data.toString()); 238 | }, 239 | }, 240 | }; 241 | 242 | result.exitCode = await exec.exec(`"${this.gitPath}"`, args, options); 243 | result.stdout = stdout.join(""); 244 | 245 | return result; 246 | } 247 | } 248 | 249 | class GitOutput { 250 | stdout = ""; 251 | exitCode = 0; 252 | } 253 | -------------------------------------------------------------------------------- /src/git-source-provider.ts: -------------------------------------------------------------------------------- 1 | import * as core from "@actions/core"; 2 | import * as io from "@actions/io"; 3 | import * as path from "path"; 4 | import fs from "fs-extra"; 5 | import { IGitCommandManager, IGithubManager, ISettings } from "./interfaces"; 6 | import { createCommandManager, MinimumGitVersion } from "./git-command-manager"; 7 | import { GitAuthHelper } from "./git-auth-helper"; 8 | import * as refHelper from "./ref-helper"; 9 | import * as stateHelper from "./state-helper"; 10 | 11 | export async function getSource( 12 | githubManager: IGithubManager, 13 | settings: ISettings, 14 | repositoryUrl: string, 15 | repositoryPath: string, 16 | ref: string, // ref 17 | fetchDepth = 0, 18 | ): Promise { 19 | // Repository URL 20 | core.info(`Cloning repository: ${repositoryUrl}`); 21 | 22 | // Remove conflicting file path 23 | if (fs.existsSync(repositoryPath)) { 24 | await io.rmRF(repositoryPath); 25 | } 26 | 27 | // Create directory 28 | let isExisting = true; 29 | 30 | if (!fs.existsSync(repositoryPath)) { 31 | isExisting = false; 32 | 33 | await io.mkdirP(repositoryPath); 34 | } 35 | 36 | // Git command manager 37 | core.startGroup("Getting Git version info"); 38 | const git = await gitCommandManager(repositoryPath); 39 | core.endGroup(); 40 | 41 | // Prepare existing directory, otherwise recreate 42 | if (isExisting) { 43 | core.info(`Deleting the contents of '${repositoryPath}'`); 44 | 45 | for (const file of await fs.promises.readdir(repositoryPath)) { 46 | await io.rmRF(path.join(repositoryPath, file)); 47 | } 48 | } 49 | 50 | if (!git) { 51 | // Downloading using REST API 52 | core.info(`The repository will be downloaded using the GitHub REST API`); 53 | core.info(`To create a local Git repository instead, add Git ${MinimumGitVersion} or higher to the PATH`); 54 | 55 | if (settings.sshKey) { 56 | throw new Error( 57 | `Input 'ssh-key' not supported when falling back to download using the GitHub REST API. To create a local Git repository instead, add Git ${MinimumGitVersion} or higher to the PATH.`, 58 | ); 59 | } 60 | 61 | const [templateRepositoryOwner, templateRepositoryName] = repositoryPath.split("/"); 62 | 63 | await githubManager.repos.downloadRepository(templateRepositoryOwner, templateRepositoryName, ref); 64 | return; 65 | } 66 | 67 | // Save state for POST action 68 | stateHelper.setTemplateRepositoryPath(repositoryPath); 69 | 70 | // Initialize the repository 71 | if (!fs.existsSync(path.join(repositoryPath, ".git"))) { 72 | core.startGroup("Initializing the repository"); 73 | await git.init(); 74 | 75 | await git.remoteAdd("origin", repositoryUrl); 76 | core.endGroup(); 77 | } 78 | 79 | // Disable automatic garbage collection 80 | core.startGroup("Disabling automatic garbage collection"); 81 | if (!(await git.tryDisableAutomaticGarbageCollection())) { 82 | core.warning(`Unable to turn off git automatic garbage collection. The git fetch operation may trigger garbage collection and cause a delay.`); 83 | } 84 | core.endGroup(); 85 | 86 | const authHelper = new GitAuthHelper(git, settings); 87 | 88 | try { 89 | // Configure auth 90 | core.startGroup("Setting up auth"); 91 | await authHelper.configureAuth(); 92 | core.endGroup(); 93 | 94 | // Fetch 95 | core.startGroup("Fetching the repository"); 96 | const refSpec = refHelper.getRefSpec(ref); 97 | await git.fetch(fetchDepth, refSpec); 98 | core.endGroup(); 99 | 100 | // Checkout info 101 | core.startGroup("Determining the checkout info"); 102 | const checkoutInfo = await refHelper.getCheckoutInfo(git, ref); 103 | core.endGroup(); 104 | 105 | // Checkout 106 | core.startGroup("Checking out the ref"); 107 | await git.checkout(checkoutInfo.ref, checkoutInfo.startPoint); 108 | core.endGroup(); 109 | 110 | // Dump some info about the checked out commit 111 | await git.log1(); 112 | } finally { 113 | // Remove auth 114 | if (!settings.persistCredentials) { 115 | core.startGroup("Removing auth"); 116 | await authHelper.removeAuth(); 117 | core.endGroup(); 118 | } 119 | } 120 | } 121 | 122 | async function gitCommandManager(repositoryPath: string): Promise { 123 | core.info(`Working directory is '${repositoryPath}'`); 124 | 125 | try { 126 | const manager = await createCommandManager(repositoryPath); 127 | 128 | manager.checkGitVersion(); 129 | 130 | return manager; 131 | } catch (err) { 132 | // Otherwise fallback to REST API 133 | return undefined; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/git-version.ts: -------------------------------------------------------------------------------- 1 | export class GitVersion { 2 | private readonly major: number = NaN; 3 | private readonly minor: number = NaN; 4 | private readonly patch: number = NaN; 5 | 6 | /** 7 | * Used for comparing the version of git and git-lfs against the minimum required version. 8 | * 9 | * @param {undefined|string} version - The version string, e.g. 1.2 or 1.2.3. 10 | */ 11 | constructor(version?: string) { 12 | if (version) { 13 | const match = version.match(/^(\d+)\.(\d+)(\.(\d+))?$/); 14 | if (match) { 15 | this.major = Number(match[1]); 16 | this.minor = Number(match[2]); 17 | 18 | if (match[4]) { 19 | this.patch = Number(match[4]); 20 | } 21 | } 22 | } 23 | } 24 | 25 | /** 26 | * Compares the instance against a minimum required version. 27 | * 28 | * @param {GitVersion} minimum - Minimum version. 29 | * 30 | * @returns {boolean} Compares the instance against a minimum required version. 31 | */ 32 | checkMinimum(minimum: GitVersion): boolean { 33 | if (!minimum.isValid()) { 34 | throw new Error("Arg minimum is not a valid version"); 35 | } 36 | 37 | // Major is insufficient 38 | if (this.major < minimum.major) { 39 | return false; 40 | } 41 | 42 | // Major is equal 43 | if (this.major === minimum.major) { 44 | // Minor is insufficient 45 | if (this.minor < minimum.minor) { 46 | return false; 47 | } 48 | 49 | // Minor is equal 50 | if (this.minor === minimum.minor) { 51 | // Patch is insufficient 52 | if (this.patch && this.patch < (minimum.patch || 0)) { 53 | return false; 54 | } 55 | } 56 | } 57 | 58 | return true; 59 | } 60 | 61 | /** 62 | * Indicates whether the instance was constructed from a valid version string. 63 | * 64 | * @returns {boolean} Indicates whether the instance was constructed from a valid version string. 65 | */ 66 | isValid(): boolean { 67 | return !isNaN(this.major); 68 | } 69 | 70 | /** 71 | * Returns the version as a string, e.g. 1.2 or 1.2.3. 72 | * 73 | * @returns {string} Returns the version as a string, e.g. 1.2 or 1.2.3. 74 | */ 75 | toString(): string { 76 | let result = ""; 77 | 78 | if (this.isValid()) { 79 | result = `${this.major}.${this.minor}`; 80 | 81 | if (!isNaN(this.patch)) { 82 | result += `.${this.patch}`; 83 | } 84 | } 85 | 86 | return result; 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/github-action-cleanup.ts: -------------------------------------------------------------------------------- 1 | import fs from "fs-extra"; 2 | import path from "path"; 3 | import * as core from "@actions/core"; 4 | import * as io from "@actions/io"; 5 | import { createCommandManager } from "./git-command-manager"; 6 | import { IGitCommandManager, ISettings } from "./interfaces"; 7 | import { GitAuthHelper } from "./git-auth-helper"; 8 | import { GithubActionContext } from "./github-action-context"; 9 | import { Settings } from "./settings"; 10 | 11 | export async function cleanup(repositoryPath: string): Promise { 12 | if (!repositoryPath || !fs.existsSync(path.join(repositoryPath, ".git", "config"))) { 13 | return; 14 | } 15 | 16 | let git: IGitCommandManager; 17 | try { 18 | git = await createCommandManager(repositoryPath); 19 | } catch { 20 | return; 21 | } 22 | 23 | try { 24 | const context = new GithubActionContext(); 25 | let settings: ISettings = new Settings(context); 26 | // Remove auth 27 | const authHelper = new GitAuthHelper(git, settings); 28 | await authHelper.removeAuth(); 29 | 30 | await io.rmRF(repositoryPath); 31 | } catch (error) { 32 | core.setFailed((error as Error).message); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/github-action-context.ts: -------------------------------------------------------------------------------- 1 | import { readFileSync, existsSync } from "fs"; 2 | import { IWebhookPayload } from "./interfaces"; 3 | import { EOL } from "os"; 4 | 5 | export class GithubActionContext { 6 | payload: IWebhookPayload; 7 | 8 | constructor() { 9 | this.payload = {}; 10 | 11 | if (process.env.GITHUB_EVENT_PATH) { 12 | if (existsSync(process.env.GITHUB_EVENT_PATH)) { 13 | this.payload = JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, { encoding: "utf8" })); 14 | } else { 15 | const path = process.env.GITHUB_EVENT_PATH; 16 | 17 | process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${EOL}`); 18 | } 19 | } 20 | } 21 | 22 | get repo(): { owner: string; repo: string } { 23 | if (process.env.GITHUB_REPOSITORY) { 24 | const [owner, repo] = process.env.GITHUB_REPOSITORY.split("/"); 25 | return { owner, repo }; 26 | } 27 | 28 | if (this.payload.repository) { 29 | return { 30 | owner: this.payload.repository.owner.login, 31 | repo: this.payload.repository.name, 32 | }; 33 | } 34 | 35 | throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/github-manager.ts: -------------------------------------------------------------------------------- 1 | import { Octokit } from "@octokit/core"; 2 | import * as core from "@actions/core"; 3 | import { inspect } from "util"; 4 | import { v4 as uuidv4 } from "uuid"; 5 | import path from "path"; 6 | import fs from "fs"; 7 | import * as io from "@actions/io"; 8 | import * as toolCache from "@actions/tool-cache"; 9 | import assert from "assert"; 10 | import { IGithubManager, IGithubManagerBranch, IGithubManagerPulls, IGithubManagerRepos, OctokitHttpError } from "./interfaces"; 11 | 12 | const IS_WINDOWS = process.platform === "win32"; 13 | 14 | export class GithubManager implements IGithubManager { 15 | octokit: Octokit; 16 | 17 | constructor(octokit: Octokit) { 18 | this.octokit = octokit; 19 | } 20 | 21 | get branch(): IGithubManagerBranch { 22 | return { 23 | create: async (owner: string, repo: string, sha: string, syncBranch: string) => { 24 | try { 25 | core.debug(`Creating branch ${syncBranch}`); 26 | 27 | await this.octokit.git.createRef({ 28 | ref: `refs/heads/${syncBranch}`, 29 | sha, 30 | owner, 31 | repo, 32 | }); 33 | } catch (error) { 34 | throw new Error(`Failed to create branch ${syncBranch}; ${inspect(error)}`); 35 | } 36 | }, 37 | delete: async (owner: string, repo: string, branch: string) => { 38 | try { 39 | core.debug(`Delete branch ${branch}`); 40 | 41 | await this.octokit.git.deleteRef({ 42 | owner, 43 | repo, 44 | ref: `refs/heads/${branch}`, 45 | }); 46 | } catch (error) { 47 | throw new Error(`Failed to delete branch ${branch}; ${inspect(error)}`); 48 | } 49 | }, 50 | get: async (owner: string, repo: string, branch: string) => { 51 | try { 52 | return await this.octokit.git.getRef({ 53 | owner, 54 | repo, 55 | ref: `heads/${branch}`, 56 | }); 57 | } catch (error) { 58 | throw new Error(`Failed to get branch ${branch}; ${inspect(error)}`); 59 | } 60 | }, 61 | has: async (owner: string, repo: string, branch: string) => { 62 | try { 63 | await this.octokit.repos.getBranch({ 64 | owner, 65 | repo, 66 | branch, 67 | }); 68 | 69 | return true; 70 | } catch (error) { 71 | const err: OctokitHttpError = error as OctokitHttpError; 72 | 73 | if (err.name === "HttpError" && err.status === 404) { 74 | return false; 75 | } 76 | 77 | throw new Error(`Failed to check if branch ${branch} exist; ${inspect(err)}`); 78 | } 79 | }, 80 | }; 81 | } 82 | 83 | get pulls(): IGithubManagerPulls { 84 | return { 85 | create: async (owner: string, repo: string, head: string, base: string, title: string, body: string): Promise => { 86 | try { 87 | await this.octokit.pulls.create({ 88 | owner, 89 | repo, 90 | title, 91 | head, 92 | base, 93 | body, 94 | }); 95 | } catch (error) { 96 | const err: OctokitHttpError = error as OctokitHttpError; 97 | 98 | core.debug(inspect(err)); 99 | 100 | if (err.name === "HttpError" && (err.message.includes("No commits between") || err.message.includes("A pull request already exists for"))) { 101 | core.info(err.message); 102 | 103 | process.exit(0); // there is currently no neutral exit code 104 | } else { 105 | throw new Error(`Failed to create a pull request; ${inspect(error)}`); 106 | } 107 | } 108 | }, 109 | }; 110 | } 111 | 112 | get repos(): IGithubManagerRepos { 113 | const getArchiveLink = async (owner: string, repo: string, ref: string): Promise => { 114 | const response = await this.octokit.repos.getArchiveLink({ 115 | owner, 116 | repo, 117 | archive_format: IS_WINDOWS ? "zipball" : "tarball", // eslint-disable-line @typescript-eslint/camelcase 118 | ref, 119 | }); 120 | 121 | if (response.status !== 200) { 122 | throw new Error(`Unexpected response from GitHub API. Status: ${response.status}, Data: ${response.data}`); 123 | } 124 | 125 | return Buffer.from(response.data); // response.data is ArrayBuffer 126 | }; 127 | 128 | return { 129 | get: async ( 130 | owner: string, 131 | repo: string, 132 | // @ts-ignore 133 | ): Promise => { 134 | try { 135 | return await this.octokit.repos.get({ 136 | owner, 137 | repo, 138 | }); 139 | } catch (error) { 140 | throw new Error(`Failed to get repository; ${inspect(error)}`); 141 | } 142 | }, 143 | getArchiveLink, 144 | downloadRepository: async (owner: string, repo: string, ref: string): Promise => { 145 | const repositoryPath = `${owner}_${repo}`; 146 | 147 | // Download the archive 148 | core.info("Downloading the archive"); 149 | let archiveData = await getArchiveLink(owner, repo, ref); 150 | 151 | // Write archive to disk 152 | core.info("Writing archive to disk"); 153 | 154 | const uniqueId = uuidv4(); 155 | const archivePath = path.join(repositoryPath, `${uniqueId}.tar.gz`); 156 | 157 | await fs.promises.writeFile(archivePath, archiveData); 158 | archiveData = Buffer.from(""); // Free memory 159 | 160 | // Extract archive 161 | core.info("Extracting the archive"); 162 | 163 | const extractPath = path.join(repositoryPath, uniqueId); 164 | 165 | await io.mkdirP(extractPath); 166 | 167 | if (IS_WINDOWS) { 168 | await toolCache.extractZip(archivePath, extractPath); 169 | } else { 170 | await toolCache.extractTar(archivePath, extractPath); 171 | } 172 | 173 | io.rmRF(archivePath); 174 | 175 | // Determine the path of the repository content. The archive contains 176 | // a top-level folder and the repository content is inside. 177 | const archiveFileNames = await fs.promises.readdir(extractPath); 178 | 179 | assert.ok(archiveFileNames.length === 1, "Expected exactly one directory inside archive"); 180 | 181 | const archiveVersion = archiveFileNames[0]; // The top-level folder name includes the short SHA 182 | 183 | core.info(`Resolved version ${archiveVersion}`); 184 | 185 | const tempRepositoryPath = path.join(extractPath, archiveVersion); 186 | 187 | // Move the files 188 | for (const fileName of await fs.promises.readdir(tempRepositoryPath)) { 189 | const sourcePath = path.join(tempRepositoryPath, fileName); 190 | const targetPath = path.join(repositoryPath, fileName); 191 | 192 | if (IS_WINDOWS) { 193 | await io.cp(sourcePath, targetPath, { recursive: true }); // Copy on Windows (Windows Defender may have a lock) 194 | } else { 195 | await io.mv(sourcePath, targetPath); 196 | } 197 | } 198 | 199 | io.rmRF(extractPath); 200 | }, 201 | }; 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /src/interfaces.ts: -------------------------------------------------------------------------------- 1 | import { URL } from "url"; 2 | import { RequestOptions, ResponseHeaders } from "@octokit/types"; 3 | 4 | export interface IPayloadRepository { 5 | full_name?: string; 6 | name: string; 7 | owner: { 8 | login: string; 9 | name?: string; 10 | }; 11 | } 12 | 13 | export interface IWebhookPayload { 14 | repository?: IPayloadRepository; 15 | } 16 | 17 | export interface IGitCommandManager { 18 | init(): Promise; 19 | checkGitVersion(): void; 20 | fetch(fetchDepth: number, refSpec: string[]): Promise; 21 | checkout(ref: string, startPoint: string): Promise; 22 | sha(type: string): Promise; 23 | addAll(): Promise; 24 | commit(message: string): Promise; 25 | push(ref: string): Promise; 26 | status(args: string[]): Promise; 27 | log1(): Promise; 28 | config(configKey: string, configValue: string, globalConfig?: boolean): Promise; 29 | configExists(configKey: string, globalConfig?: boolean): Promise; 30 | tryConfigUnset(configKey: string, globalConfig?: boolean): Promise; 31 | getWorkingDirectory(): string; 32 | setEnvironmentVariable(name: string, value: string): void; 33 | removeEnvironmentVariable(name: string): void; 34 | tryDisableAutomaticGarbageCollection(): Promise; 35 | remoteAdd(remoteName: string, remoteUrl: string): Promise; 36 | branchExists(remote: boolean, pattern: string): Promise; 37 | tagExists(pattern: string): Promise; 38 | } 39 | 40 | export interface IGithubManagerBranch { 41 | create: (owner: string, repo: string, sha: string, syncBranch: string) => Promise; 42 | delete: (owner: string, repo: string, branch: string) => Promise; 43 | get: ( 44 | owner: string, 45 | repo: string, 46 | branch: string, 47 | ) => Promise<{ 48 | data: { 49 | ref: string; 50 | node_id: string; 51 | url: string; 52 | object: { 53 | type: string; 54 | sha: string; 55 | url: string; 56 | }; 57 | }; 58 | }>; 59 | has: (owner: string, repo: string, branch: string) => Promise; 60 | } 61 | 62 | export interface IGithubManagerPulls { 63 | create: (owner: string, repo: string, head: string, base: string, title: string, body: string) => Promise; 64 | } 65 | 66 | export interface IGithubManagerRepos { 67 | get: ( 68 | owner: string, 69 | repo: string, 70 | // @ts-ignore 71 | ) => Promise<{ 72 | data: { 73 | template_repository?: { 74 | full_name: string; 75 | }; 76 | }; 77 | }>; 78 | getArchiveLink: (owner: string, repo: string, ref: string) => Promise; 79 | downloadRepository: (owner: string, repo: string, ref: string) => Promise; 80 | } 81 | 82 | export interface IGithubManager { 83 | branch: IGithubManagerBranch; 84 | pulls: IGithubManagerPulls; 85 | repos: IGithubManagerRepos; 86 | } 87 | 88 | export interface ISettings { 89 | /** 90 | * The auth token to use when fetching the repository. 91 | */ 92 | authToken: string; 93 | 94 | /** 95 | * The github api url. 96 | */ 97 | apiUrl: string; 98 | 99 | /** 100 | * The github url. 101 | */ 102 | serverUrl: URL; 103 | 104 | /** 105 | * The SSH key to configure. 106 | */ 107 | sshKey: string; 108 | 109 | /** 110 | * Additional SSH known hosts. 111 | */ 112 | sshKnownHosts: string; 113 | 114 | /** 115 | * Indicates whether the server must be a known host. 116 | */ 117 | sshStrict: boolean; 118 | 119 | /** 120 | * Indicates whether to persist the credentials on disk to enable scripting authenticated git commands. 121 | */ 122 | persistCredentials: boolean; 123 | 124 | /** 125 | * The author name and email for the commit message. 126 | */ 127 | authorName: string; 128 | authorEmail: string; 129 | 130 | /** 131 | * Owner of the current repository. 132 | */ 133 | repositoryOwner: string; 134 | 135 | /** 136 | * The current repository name. 137 | */ 138 | repositoryName: string; 139 | 140 | repositoryPath: string; 141 | 142 | /** 143 | * GitHub workspace. 144 | */ 145 | githubWorkspacePath: string; 146 | 147 | /** 148 | * The pr message. 149 | */ 150 | messageHead: string; 151 | 152 | /** 153 | * The pr message. 154 | */ 155 | messageBody: string; 156 | 157 | /** 158 | * The name of the ref you want the changes pulled into. This should be an existing ref on the current repository. 159 | * You cannot submit a pull request to one repository that requests a merge to a base of another repository. 160 | */ 161 | ref: string; 162 | 163 | /** 164 | * The ref name for the merge request. 165 | */ 166 | syncBranchName: string; 167 | 168 | /** 169 | * The template ref name, i most cases "master". 170 | */ 171 | templateRepositoryRef: string; 172 | 173 | /** 174 | * The template repository path {owner}/{repo}. 175 | */ 176 | templateRepository: string; 177 | 178 | /** 179 | * The full url tp the template repository. 180 | */ 181 | templateRepositoryUrl: string; 182 | 183 | /** 184 | * Path to the template repository folder. 185 | */ 186 | templateRepositoryPath: string; 187 | 188 | /** 189 | * List of ignored files and directories that that should be excluded from the template sync. 190 | */ 191 | ignoreList: string[]; 192 | 193 | clean: boolean; 194 | } 195 | 196 | export interface OctokitHttpError extends Error { 197 | name: string; 198 | /** 199 | * http status code 200 | */ 201 | status: number; 202 | /** 203 | * http status code 204 | * 205 | * @deprecated `error.code` is deprecated in favor of `error.status` 206 | */ 207 | code: number; 208 | /** 209 | * error response headers 210 | */ 211 | headers: ResponseHeaders; 212 | /** 213 | * Request options that lead to the error. 214 | */ 215 | request: RequestOptions; 216 | } 217 | 218 | export interface OctokitHttpError extends Error { 219 | name: string; 220 | /** 221 | * http status code 222 | */ 223 | status: number; 224 | /** 225 | * http status code 226 | * 227 | * @deprecated `error.code` is deprecated in favor of `error.status` 228 | */ 229 | code: number; 230 | /** 231 | * error response headers 232 | */ 233 | headers: ResponseHeaders; 234 | /** 235 | * Request options that lead to the error. 236 | */ 237 | request: RequestOptions; 238 | } 239 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import path from "path"; 2 | import fs from "fs-extra"; 3 | import * as core from "@actions/core"; 4 | import * as coreCommand from "@actions/core/lib/command"; 5 | import * as io from "@actions/io"; 6 | import { inspect } from "util"; 7 | import FileHound from "filehound"; 8 | import { Settings } from "./settings"; 9 | import { GithubActionContext } from "./github-action-context"; 10 | import * as gitSourceProvider from "./git-source-provider"; 11 | import { GithubManager } from "./github-manager"; 12 | import { createCommandManager } from "./git-command-manager"; 13 | import { octokit } from "./octokit"; 14 | import * as stateHelper from "./state-helper"; 15 | import * as refHelper from "./ref-helper"; 16 | import { ISettings } from "./interfaces"; 17 | import { cleanup } from "./github-action-cleanup"; 18 | 19 | const USER_EMAIL = "user.email"; 20 | const USER_NAME = "user.name"; 21 | 22 | const filehound = FileHound.create(); 23 | 24 | async function run(): Promise { 25 | try { 26 | const context = new GithubActionContext(); 27 | let settings: ISettings = new Settings(context); 28 | const githubManager = new GithubManager(octokit(settings)); 29 | 30 | settings = await prepareTemplateSettings(settings, githubManager); 31 | 32 | core.debug(`Used settings: ${inspect(settings)}`); 33 | 34 | try { 35 | // Register problem matcher 36 | coreCommand.issueCommand("add-matcher", {}, path.join(__dirname, "problem-matcher.json")); 37 | 38 | if (!(await githubManager.branch.has(settings.repositoryOwner, settings.repositoryName, settings.syncBranchName))) { 39 | const baseBranch = await githubManager.branch.get( 40 | settings.repositoryOwner, 41 | settings.repositoryName, 42 | settings.ref.replace(/^refs\/heads\//, ""), 43 | ); 44 | 45 | await githubManager.branch.create(settings.repositoryOwner, settings.repositoryName, baseBranch.data.object.sha, settings.syncBranchName); 46 | } 47 | 48 | const mainGitCommandManager = await createCommandManager(settings.repositoryPath); 49 | const ref = `refs/heads/${settings.syncBranchName}`; 50 | 51 | await mainGitCommandManager.fetch(0, refHelper.getRefSpec(ref)); 52 | 53 | const checkoutInfo = await refHelper.getCheckoutInfo(mainGitCommandManager, ref); 54 | 55 | await mainGitCommandManager.checkout(checkoutInfo.ref, checkoutInfo.startPoint); 56 | 57 | // download the template repo 58 | await gitSourceProvider.getSource( 59 | githubManager, 60 | settings, 61 | settings.templateRepositoryUrl, 62 | settings.templateRepositoryPath, 63 | settings.templateRepositoryRef, 64 | ); 65 | 66 | // find all files 67 | const files: string[] = filehound.path(settings.templateRepositoryPath).discard(settings.ignoreList).findSync(); 68 | 69 | core.debug(`List of found files ${inspect(files)}`); 70 | 71 | for (const file of files) { 72 | fs.copySync(file, path.join(settings.githubWorkspacePath, file.replace(settings.templateRepositoryPath, "")), { 73 | overwrite: true, 74 | }); 75 | } 76 | 77 | await io.rmRF(settings.templateRepositoryPath); 78 | 79 | try { 80 | core.startGroup("Setting up git user and email"); 81 | await mainGitCommandManager.config(USER_EMAIL, settings.authorEmail, true); 82 | await mainGitCommandManager.config(USER_NAME, settings.authorName, true); 83 | core.endGroup(); 84 | 85 | core.startGroup("Adding all changed files to main repository"); 86 | await mainGitCommandManager.addAll(); 87 | core.endGroup(); 88 | 89 | core.startGroup("Checking if changes exist that needs to applied"); 90 | if ((await mainGitCommandManager.status(["--porcelain"])) === "") { 91 | core.setOutput("Git status", `No changes found for ${settings.templateRepositoryUrl}`); 92 | process.exit(0); // there is currently no neutral exit code 93 | } 94 | core.endGroup(); 95 | 96 | core.startGroup("Creating a commit"); 97 | await mainGitCommandManager.commit(settings.messageHead); 98 | core.endGroup(); 99 | 100 | core.startGroup("Pushing new commit"); 101 | await mainGitCommandManager.push(settings.syncBranchName); 102 | core.endGroup(); 103 | 104 | // Dump some info about the checked out commit 105 | await mainGitCommandManager.log1(); 106 | } finally { 107 | await mainGitCommandManager.tryConfigUnset(USER_EMAIL, true); 108 | await mainGitCommandManager.tryConfigUnset(USER_NAME, true); 109 | } 110 | 111 | core.startGroup("Creating Pull request"); 112 | await githubManager.pulls.create( 113 | settings.repositoryOwner, 114 | settings.repositoryName, 115 | settings.syncBranchName, 116 | settings.ref, 117 | settings.messageHead, 118 | settings.messageBody, 119 | ); 120 | core.endGroup(); 121 | } finally { 122 | // Unregister problem matcher 123 | coreCommand.issueCommand("remove-matcher", { owner: "checkout-git" }, ""); 124 | } 125 | } catch (error) { 126 | core.setFailed((error as Error).message); 127 | } 128 | } 129 | 130 | async function prepareTemplateSettings(settings: ISettings, githubManager: GithubManager): Promise { 131 | let template = core.getInput("template_repository", { required: false }); 132 | 133 | if (!template) { 134 | const repoData = await githubManager.repos.get(settings.repositoryOwner, settings.repositoryName); 135 | 136 | if (repoData.data.template_repository !== undefined) { 137 | template = repoData.data.template_repository.full_name; 138 | } else { 139 | core.setFailed('Template repository not found, please provide "template_repository" key, that you want to check'); 140 | 141 | process.exit(1); // there is currently no neutral exit code 142 | } 143 | } else { 144 | const [templateRepositoryOwner, templateRepositoryName] = template.split("/"); 145 | const repoData = await githubManager.repos.get(templateRepositoryOwner, templateRepositoryName); 146 | 147 | if (repoData.data.template_repository === undefined) { 148 | core.setFailed('You need to provide a github template repository for "template_repository"'); 149 | 150 | process.exit(1); // there is currently no neutral exit code 151 | } 152 | } 153 | 154 | settings.templateRepository = template; 155 | 156 | const [templateRepositoryOwner, templateRepositoryName] = template.split("/"); 157 | 158 | settings.templateRepositoryPath = path.resolve( 159 | settings.githubWorkspacePath, 160 | `${encodeURIComponent(templateRepositoryOwner)}/${encodeURIComponent(templateRepositoryName)}`, 161 | ); 162 | 163 | if (!(settings.templateRepositoryPath + path.sep).startsWith(settings.githubWorkspacePath + path.sep)) { 164 | throw new Error(`Repository path '${settings.templateRepositoryPath}' is not under '${settings.githubWorkspacePath}'`); 165 | } 166 | 167 | if (settings.sshKey) { 168 | settings.templateRepositoryUrl = `git@${settings.serverUrl.hostname}:${settings.templateRepository}.git`; 169 | } else { 170 | // "origin" is SCHEME://HOSTNAME[:PORT] 171 | settings.templateRepositoryUrl = `${settings.serverUrl.origin}/${settings.templateRepository}`; 172 | } 173 | 174 | return settings; 175 | } 176 | 177 | if (!stateHelper.IsPost) { 178 | run(); 179 | } else { 180 | cleanup(stateHelper.TemplateRepositoryPath); 181 | } 182 | -------------------------------------------------------------------------------- /src/misc/generate-docs.ts: -------------------------------------------------------------------------------- 1 | import * as fs from "fs"; 2 | import * as os from "os"; 3 | import * as path from "path"; 4 | import * as yaml from "js-yaml"; 5 | 6 | // 7 | // SUMMARY 8 | // 9 | // This script rebuilds the usage section in the README.md to be consistent with the action.yml 10 | 11 | function updateUsage( 12 | actionReference: string, 13 | actionYamlPath: string = "action.yml", 14 | readmePath: string = "README.md", 15 | startToken: string = "", 16 | endToken: string = "", 17 | ): void { 18 | if (!actionReference) { 19 | throw new Error("Parameter actionReference must not be empty"); 20 | } 21 | 22 | // Load the action.yml 23 | const actionYaml = yaml.load(fs.readFileSync(actionYamlPath, "utf8").toString(), { filename: actionYamlPath }); 24 | 25 | // Load the README 26 | const originalReadme = fs.readFileSync(readmePath, "utf8").toString(); 27 | 28 | // Find the start token 29 | const startTokenIndex = originalReadme.indexOf(startToken); 30 | if (startTokenIndex < 0) { 31 | throw new Error(`Start token '${startToken}' not found`); 32 | } 33 | 34 | // Find the end token 35 | const endTokenIndex = originalReadme.indexOf(endToken); 36 | if (endTokenIndex < 0) { 37 | throw new Error(`End token '${endToken}' not found`); 38 | } else if (endTokenIndex < startTokenIndex) { 39 | throw new Error("Start token must appear before end token"); 40 | } 41 | 42 | // Build the new README 43 | const newReadme: string[] = []; 44 | 45 | // Append the beginning 46 | newReadme.push(originalReadme.substr(0, startTokenIndex + startToken.length)); 47 | 48 | // Build the new usage section 49 | newReadme.push("```yaml", `- uses: ${actionReference}`, " with:"); 50 | 51 | // @ts-ignore 52 | const inputs = actionYaml.inputs; 53 | 54 | let firstInput = true; 55 | 56 | for (const key of Object.keys(inputs)) { 57 | const input = inputs[key]; 58 | 59 | // Line break between inputs 60 | if (!firstInput) { 61 | newReadme.push(""); 62 | } 63 | 64 | // Constrain the width of the description 65 | const width = 80; 66 | let description = (input.description as string) 67 | .trimRight() 68 | .replace(/\r\n/g, "\n") // Convert CR to LF 69 | .replace(/ +/g, " ") // Squash consecutive spaces 70 | .replace(/ \n/g, "\n"); // Squash space followed by newline 71 | while (description) { 72 | // Longer than width? Find a space to break apart 73 | let segment: string = description; 74 | if (description.length > width) { 75 | segment = description.substr(0, width + 1); 76 | while (!segment.endsWith(" ") && !segment.endsWith("\n") && segment) { 77 | segment = segment.substr(0, segment.length - 1); 78 | } 79 | 80 | // Trimmed too much? 81 | if (segment.length < width * 0.67) { 82 | segment = description; 83 | } 84 | } else { 85 | segment = description; 86 | } 87 | 88 | // Check for newline 89 | const newlineIndex = segment.indexOf("\n"); 90 | if (newlineIndex >= 0) { 91 | segment = segment.substr(0, newlineIndex + 1); 92 | } 93 | 94 | // Append segment 95 | newReadme.push(` # ${segment}`.trimRight()); 96 | 97 | // Remaining 98 | description = description.substr(segment.length); 99 | } 100 | 101 | if (input.default !== undefined) { 102 | // Append blank line if description had paragraphs 103 | if ((input.description as string).trimRight().match(/\n[ ]*\r?\n/)) { 104 | newReadme.push(` #`); 105 | } 106 | 107 | // Default 108 | newReadme.push(` # Default: ${input.default}`); 109 | } 110 | 111 | // Input name 112 | newReadme.push(` ${key}: ''`); 113 | 114 | firstInput = false; 115 | } 116 | 117 | newReadme.push("```"); 118 | 119 | // Append the end 120 | newReadme.push(originalReadme.substr(endTokenIndex)); 121 | 122 | // Write the new README 123 | fs.writeFileSync(readmePath, newReadme.join(os.EOL)); 124 | } 125 | 126 | updateUsage("actions/template-sync@v1", path.join(__dirname, "..", "..", "action.yml"), path.join(__dirname, "..", "..", "README.md")); 127 | -------------------------------------------------------------------------------- /src/octokit.ts: -------------------------------------------------------------------------------- 1 | import { Octokit } from "@octokit/action"; 2 | import { Octokit as Core } from "@octokit/core"; 3 | import { retry } from "@octokit/plugin-retry"; 4 | import { ISettings } from "./interfaces"; 5 | 6 | // plugins for octokit 7 | const MyOctokit = Octokit.plugin(retry); 8 | 9 | export function octokit(setting: ISettings): Core { 10 | return new MyOctokit({ 11 | auth: setting.authToken, 12 | baseUrl: setting.apiUrl, 13 | previews: [ 14 | "baptiste", // templateRepositoryPath 15 | "lydian", // update pull request 16 | ], 17 | }); 18 | } 19 | -------------------------------------------------------------------------------- /src/ref-helper.ts: -------------------------------------------------------------------------------- 1 | import { IGitCommandManager } from "./interfaces"; 2 | 3 | export interface ICheckoutInfo { 4 | ref: string; 5 | startPoint: string; 6 | } 7 | 8 | export async function getCheckoutInfo(git: IGitCommandManager, ref: string): Promise { 9 | if (!git) { 10 | throw new Error("Arg git cannot be empty"); 11 | } 12 | 13 | if (!ref) { 14 | throw new Error("Args ref cannot be empty"); 15 | } 16 | 17 | const result = {} as unknown as ICheckoutInfo; 18 | const upperRef = (ref || "").toUpperCase(); 19 | 20 | // refs/heads/ 21 | if (upperRef.startsWith("REFS/HEADS/")) { 22 | const branch = ref.substring("refs/heads/".length); 23 | result.ref = branch; 24 | result.startPoint = `refs/remotes/origin/${branch}`; 25 | } 26 | // refs/pull/ 27 | else if (upperRef.startsWith("REFS/PULL/")) { 28 | const branch = ref.substring("refs/pull/".length); 29 | result.ref = `refs/remotes/pull/${branch}`; 30 | } 31 | // refs/tags/ 32 | else if (upperRef.startsWith("REFS/")) { 33 | result.ref = ref; 34 | } 35 | // Unqualified ref, check for a matching ref or tag 36 | else { 37 | if (await git.branchExists(true, `origin/${ref}`)) { 38 | result.ref = ref; 39 | result.startPoint = `refs/remotes/origin/${ref}`; 40 | } else if (await git.tagExists(`${ref}`)) { 41 | result.ref = `refs/tags/${ref}`; 42 | } else { 43 | throw new Error(`A branch or tag with the name '${ref}' could not be found`); 44 | } 45 | } 46 | 47 | return result; 48 | } 49 | 50 | export function getRefSpec(ref: string): string[] { 51 | if (!ref) { 52 | throw new Error("Arg ref cannot be empty"); 53 | } 54 | 55 | const upperRef = (ref || "").toUpperCase(); 56 | 57 | // Unqualified ref, check for a matching ref or tag 58 | if (!upperRef.startsWith("REFS/")) { 59 | return [`+refs/heads/${ref}*:refs/remotes/origin/${ref}*`, `+refs/tags/${ref}*:refs/tags/${ref}*`]; 60 | } 61 | // refs/heads/ 62 | else if (upperRef.startsWith("REFS/HEADS/")) { 63 | const branch = ref.substring("refs/heads/".length); 64 | return [`+${ref}:refs/remotes/origin/${branch}`]; 65 | } 66 | // refs/pull/ 67 | else if (upperRef.startsWith("REFS/PULL/")) { 68 | const branch = ref.substring("refs/pull/".length); 69 | return [`+${ref}:refs/remotes/pull/${branch}`]; 70 | } 71 | // refs/tags/ 72 | else { 73 | return [`+${ref}:${ref}`]; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/retry-helper.ts: -------------------------------------------------------------------------------- 1 | import * as core from "@actions/core"; 2 | 3 | const defaultMaxAttempts = 3; 4 | const defaultMinSeconds = 10; 5 | const defaultMaxSeconds = 20; 6 | 7 | export class RetryHelper { 8 | private maxAttempts: number; 9 | private minSeconds: number; 10 | private maxSeconds: number; 11 | 12 | constructor(maxAttempts: number = defaultMaxAttempts, minSeconds: number = defaultMinSeconds, maxSeconds: number = defaultMaxSeconds) { 13 | this.maxAttempts = maxAttempts; 14 | this.minSeconds = Math.floor(minSeconds); 15 | this.maxSeconds = Math.floor(maxSeconds); 16 | 17 | if (this.minSeconds > this.maxSeconds) { 18 | throw new Error("min seconds should be less than or equal to max seconds"); 19 | } 20 | } 21 | 22 | async execute(action: () => Promise): Promise { 23 | let attempt = 1; 24 | 25 | while (attempt < this.maxAttempts) { 26 | // Try 27 | try { 28 | return await action(); 29 | } catch (err) { 30 | core.info((err as Error).message); 31 | } 32 | 33 | // Sleep 34 | const seconds = this.getSleepAmount(); 35 | core.info(`Waiting ${seconds} seconds before trying again`); 36 | await this.sleep(seconds); 37 | attempt++; 38 | } 39 | 40 | // Last attempt 41 | return await action(); 42 | } 43 | 44 | private getSleepAmount(): number { 45 | return Math.floor(Math.random() * (this.maxSeconds - this.minSeconds + 1)) + this.minSeconds; 46 | } 47 | 48 | private async sleep(seconds: number): Promise { 49 | return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/settings.ts: -------------------------------------------------------------------------------- 1 | import * as core from "@actions/core"; 2 | import { URL } from "url"; 3 | import { GithubActionContext } from "./github-action-context"; 4 | import { ISettings } from "./interfaces"; 5 | import path from "path"; 6 | 7 | export class Settings implements ISettings { 8 | settings: ISettings; 9 | 10 | constructor(context: GithubActionContext) { 11 | const message = 12 | "This pull request has been created by the [template sync action](https://github.com/narrowspark/template-sync-action) action.\n\nThis PR synchronizes with {0}\n\n---\n\n You can set a custom pull request title, body, ref and commit messages, see [Usage](https://github.com/narrowspark/template-sync-action#Usage)."; 13 | 14 | let githubWorkspacePath = process.env["GITHUB_WORKSPACE"]; 15 | 16 | if (!githubWorkspacePath) { 17 | throw new Error("GITHUB_WORKSPACE not defined"); 18 | } 19 | 20 | githubWorkspacePath = path.resolve(githubWorkspacePath); 21 | 22 | core.debug(`GITHUB_WORKSPACE = '${githubWorkspacePath}'`); 23 | 24 | this.settings = { 25 | authToken: core.getInput("github_token", { required: true }), 26 | apiUrl: process.env["GITHUB_API_URL"] || "https://api.github.com", 27 | serverUrl: new URL(process.env["GITHUB_URL"] || "https://github.com"), 28 | 29 | sshKey: core.getInput("ssh_key"), 30 | sshKnownHosts: core.getInput("ssh_known_hosts"), 31 | sshStrict: (core.getInput("ssh_strict") || "true").toUpperCase() === "TRUE", 32 | persistCredentials: (core.getInput("persist_credentials") || "false").toUpperCase() === "TRUE", 33 | 34 | authorName: core.getInput("git_author_name", { required: true }), 35 | authorEmail: core.getInput("git_author_email", { required: true }), 36 | 37 | repositoryOwner: core.getInput("owner") || context.repo.owner, 38 | repositoryName: core.getInput("repo") || context.repo.repo, 39 | githubWorkspacePath, 40 | repositoryPath: githubWorkspacePath, 41 | 42 | messageHead: core.getInput("pr_title") || 'Enhancement: Synchronize with "{0}"', 43 | messageBody: core.getInput("pr_message") || message, 44 | 45 | ref: core.getInput("ref", { required: true }), 46 | syncBranchName: "feature/template/sync/{0}", 47 | 48 | templateRepositoryRef: core.getInput("template_ref") || "refs/heads/master", 49 | templateRepository: "", 50 | templateRepositoryUrl: "", 51 | templateRepositoryPath: (process.env["STATE_template_repository_path"] as string) || "", 52 | 53 | ignoreList: [".git$", ".changelog", ".editorconfig", ".gitignore", "CHANGELOG.md", "LICENSE.md", "README.md", "UPGRADE.md"].concat( 54 | core.getInput("ignore_list", { required: false }) || [], 55 | ), 56 | clean: (core.getInput("clean") || "true").toUpperCase() === "TRUE", 57 | }; 58 | } 59 | 60 | get authToken(): string { 61 | return this.settings.authToken; 62 | } 63 | 64 | get apiUrl(): string { 65 | return this.settings.apiUrl; 66 | } 67 | 68 | get serverUrl(): URL { 69 | return this.settings.serverUrl; 70 | } 71 | 72 | get repositoryOwner(): string { 73 | return this.settings.repositoryOwner; 74 | } 75 | 76 | get repositoryName(): string { 77 | return this.settings.repositoryName; 78 | } 79 | 80 | get repositoryPath(): string { 81 | return this.settings.repositoryPath; 82 | } 83 | 84 | get githubWorkspacePath(): string { 85 | return this.settings.githubWorkspacePath; 86 | } 87 | 88 | get authorEmail(): string { 89 | return this.settings.authorEmail; 90 | } 91 | 92 | get authorName(): string { 93 | return this.settings.authorName; 94 | } 95 | 96 | get messageHead(): string { 97 | return this.settings.messageHead.replace("{0}", this.settings.templateRepository); 98 | } 99 | 100 | get messageBody(): string { 101 | return this.settings.messageBody.replace("{0}", this.settings.templateRepository); 102 | } 103 | 104 | get ref(): string { 105 | return this.settings.ref; 106 | } 107 | 108 | get syncBranchName(): string { 109 | return this.settings.syncBranchName.replace("{0}", this.settings.templateRepository); 110 | } 111 | 112 | get templateRepositoryRef(): string { 113 | return this.settings.templateRepositoryRef; 114 | } 115 | 116 | set templateRepository(templateRepository: string) { 117 | this.settings.templateRepository = templateRepository; 118 | } 119 | 120 | get templateRepository(): string { 121 | return this.settings.templateRepository; 122 | } 123 | 124 | set templateRepositoryUrl(templateUrl: string) { 125 | this.settings.templateRepositoryUrl = templateUrl; 126 | } 127 | 128 | get templateRepositoryUrl(): string { 129 | return this.settings.templateRepositoryUrl; 130 | } 131 | 132 | set templateRepositoryPath(templateRepository: string) { 133 | this.settings.templateRepositoryPath = templateRepository; 134 | } 135 | 136 | get templateRepositoryPath(): string { 137 | return this.settings.templateRepositoryPath; 138 | } 139 | 140 | get sshKey(): string { 141 | return this.settings.sshKey; 142 | } 143 | 144 | get sshKnownHosts(): string { 145 | return this.settings.sshKey; 146 | } 147 | 148 | get sshStrict(): boolean { 149 | return this.settings.sshStrict; 150 | } 151 | 152 | get persistCredentials(): boolean { 153 | return this.settings.persistCredentials; 154 | } 155 | 156 | get ignoreList(): string[] { 157 | return this.settings.ignoreList; 158 | } 159 | 160 | get clean(): boolean { 161 | return this.settings.clean; 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/state-helper.ts: -------------------------------------------------------------------------------- 1 | import * as coreCommand from "@actions/core/lib/command"; 2 | 3 | /** 4 | * Indicates whether the POST action is running. 5 | */ 6 | export const IsPost = !!process.env["STATE_isPost"]; 7 | 8 | /** 9 | * The template repository path for the POST action. The value is empty during the MAIN action. 10 | */ 11 | export const TemplateRepositoryPath = (process.env["STATE_template_repository_path"] as string) || ""; 12 | 13 | /** 14 | * The repository path for the POST action. The value is empty during the MAIN action. 15 | */ 16 | export const RepositoryPath = (process.env["STATE_repositoryPath"] as string) || ""; 17 | 18 | /** 19 | * The SSH key path for the POST action. The value is empty during the MAIN action. 20 | */ 21 | export const SshKeyPath = (process.env["STATE_template_ssh_key_path"] as string) || ""; 22 | 23 | /** 24 | * The SSH known hosts path for the POST action. The value is empty during the MAIN action. 25 | */ 26 | export const SshKnownHostsPath = (process.env["STATE_template_ssh_known_hosts_path"] as string) || ""; 27 | 28 | /** 29 | * Save the repository path so the POST action can retrieve the value. 30 | * 31 | * @param {string} repositoryPath - Path to repository. 32 | */ 33 | export function setTemplateRepositoryPath(repositoryPath: string): void { 34 | coreCommand.issueCommand("save-state", { name: "template_repository_path" }, repositoryPath); 35 | } 36 | 37 | /** 38 | * Save the SSH key path so the POST action can retrieve the value. 39 | * 40 | * @param {string} sshKeyPath - The ssh key path. 41 | */ 42 | export function setSshKeyPath(sshKeyPath: string): void { 43 | coreCommand.issueCommand("save-state", { name: "template_ssh_key_path" }, sshKeyPath); 44 | } 45 | 46 | /** 47 | * Save the SSH known hosts path so the POST action can retrieve the value. 48 | * 49 | * @param {string} sshKnownHostsPath - The ssh known hosts path. 50 | */ 51 | export function setSshKnownHostsPath(sshKnownHostsPath: string): void { 52 | coreCommand.issueCommand("save-state", { name: "template_ssh_known_hosts_path" }, sshKnownHostsPath); 53 | } 54 | 55 | // Publish a variable so that when the POST action runs, it can determine it should run the cleanup logic. 56 | // This is necessary since we don't have a separate entry point. 57 | if (!IsPost) { 58 | coreCommand.issueCommand("save-state", { name: "isPost" }, "true"); 59 | } 60 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/tsconfig", 3 | "display": "React + Node 12", 4 | "compilerOptions": { 5 | "module": "ESNext", 6 | "target": "es5", 7 | "lib": ["dom", "es2019", "es2020.promise", "es2020.bigint", "es2020.string"], 8 | 9 | "noEmit": true, 10 | "jsx": "react-jsx", 11 | "strict": true, 12 | "declaration": true, 13 | "allowJs": true, 14 | 15 | /* Additional Checks */ 16 | "noUnusedLocals": true, 17 | "noUnusedParameters": true, 18 | "noImplicitReturns": true, 19 | "noFallthroughCasesInSwitch": true, 20 | 21 | /* Module Resolution Options */ 22 | "moduleResolution": "node", 23 | "isolatedModules": true, 24 | // "importsNotUsedAsValues": "error", 25 | "resolveJsonModule": true, 26 | "esModuleInterop": true, 27 | "skipLibCheck": true, 28 | "forceConsistentCasingInFileNames": true 29 | }, 30 | "exclude": [ 31 | "node_modules", 32 | "build", 33 | "scripts", 34 | "acceptance-tests", 35 | "jest", 36 | "stories", 37 | "__tests__", 38 | "babel.config.cjs" 39 | ] 40 | } 41 | -------------------------------------------------------------------------------- /types/octokit__fixtures.d.ts: -------------------------------------------------------------------------------- 1 | declare module '@octokit/fixtures' 2 | -------------------------------------------------------------------------------- /verify-node-version.cjs: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-console */ 2 | /* eslint-disable unicorn/no-process-exit */ 3 | let requiredVersion = require("fs").readFileSync(".nvmrc", { encoding: "utf8" }).trim(); 4 | 5 | if (!requiredVersion.includes("v")) { 6 | requiredVersion = `v${requiredVersion}`; 7 | } 8 | 9 | if (process.env.SKIP_CHECK !== undefined) { 10 | process.exit(0); 11 | } 12 | 13 | if (process.version.split(".")[0] !== requiredVersion.split(".")[0]) { 14 | console.error(`[!] This project requires Node.js ${requiredVersion}, current version is ${process.version}`); 15 | 16 | process.exit(1); 17 | } 18 | --------------------------------------------------------------------------------