├── .eslintrc.cjs ├── .github ├── dependabot.yml └── workflows │ ├── dependabot-approve-merge.yml │ ├── lint-eslint.yml │ └── node-test.yml ├── .gitignore ├── .vscode └── launch.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── COPYING ├── README.md ├── docker-compose.yml ├── logo.png ├── package-lock.json ├── package.json ├── src ├── appUtils.ts ├── backport.ts ├── constants.ts ├── gitUtils.ts ├── githubUtils.ts ├── index.ts ├── logUtils.ts ├── nextcloudUtils.spec.ts ├── nextcloudUtils.ts ├── payloadUtils.spec.ts ├── payloadUtils.ts └── queue.ts ├── tsconfig.json └── vitest.config.ts /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | /* eslint-env node */ 2 | module.exports = { 3 | extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended'], 4 | parser: '@typescript-eslint/parser', 5 | plugins: ['@typescript-eslint'], 6 | root: true, 7 | } 8 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | day: saturday 8 | time: '03:00' 9 | timezone: Europe/Paris 10 | open-pull-requests-limit: 10 11 | labels: 12 | - 3. to review 13 | - dependencies 14 | 15 | - package-ecosystem: github-actions 16 | directory: / 17 | schedule: 18 | interval: weekly 19 | day: saturday 20 | time: '03:00' 21 | timezone: Europe/Paris 22 | open-pull-requests-limit: 10 23 | labels: 24 | - 3. to review 25 | - dependencies 26 | -------------------------------------------------------------------------------- /.github/workflows/dependabot-approve-merge.yml: -------------------------------------------------------------------------------- 1 | # This workflow is provided via the organization template repository 2 | # 3 | # https://github.com/nextcloud/.github 4 | # https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization 5 | # 6 | # SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors 7 | # SPDX-License-Identifier: MIT 8 | 9 | name: Dependabot 10 | 11 | on: 12 | pull_request_target: 13 | branches: 14 | - main 15 | - master 16 | - stable* 17 | 18 | permissions: 19 | contents: read 20 | 21 | concurrency: 22 | group: dependabot-approve-merge-${{ github.head_ref || github.run_id }} 23 | cancel-in-progress: true 24 | 25 | jobs: 26 | auto-approve-merge: 27 | if: github.actor == 'dependabot[bot]' || github.actor == 'renovate[bot]' 28 | runs-on: ubuntu-latest-low 29 | permissions: 30 | # for hmarr/auto-approve-action to approve PRs 31 | pull-requests: write 32 | 33 | steps: 34 | - name: Disabled on forks 35 | if: ${{ github.event.pull_request.head.repo.full_name != github.repository }} 36 | run: | 37 | echo 'Can not approve PRs from forks' 38 | exit 1 39 | 40 | # GitHub actions bot approve 41 | - uses: hmarr/auto-approve-action@b40d6c9ed2fa10c9a2749eca7eb004418a705501 # v2 42 | with: 43 | github-token: ${{ secrets.GITHUB_TOKEN }} 44 | 45 | # Nextcloud bot approve and merge request 46 | - uses: ahmadnassri/action-dependabot-auto-merge@45fc124d949b19b6b8bf6645b6c9d55f4f9ac61a # v2 47 | with: 48 | target: minor 49 | github-token: ${{ secrets.DEPENDABOT_AUTOMERGE_TOKEN }} 50 | -------------------------------------------------------------------------------- /.github/workflows/lint-eslint.yml: -------------------------------------------------------------------------------- 1 | # This workflow is provided via the organization template repository 2 | # 3 | # https://github.com/nextcloud/.github 4 | # https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization 5 | # 6 | # SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors 7 | # SPDX-License-Identifier: MIT 8 | 9 | name: Lint eslint 10 | 11 | on: pull_request 12 | 13 | permissions: 14 | contents: read 15 | 16 | concurrency: 17 | group: lint-eslint-${{ github.head_ref || github.run_id }} 18 | cancel-in-progress: true 19 | 20 | jobs: 21 | changes: 22 | runs-on: ubuntu-latest-low 23 | permissions: 24 | contents: read 25 | pull-requests: read 26 | 27 | outputs: 28 | src: ${{ steps.changes.outputs.src}} 29 | 30 | steps: 31 | - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 32 | id: changes 33 | continue-on-error: true 34 | with: 35 | filters: | 36 | src: 37 | - '.github/workflows/**' 38 | - 'src/**' 39 | - 'appinfo/info.xml' 40 | - 'package.json' 41 | - 'package-lock.json' 42 | - 'tsconfig.json' 43 | - '.eslintrc.*' 44 | - '.eslintignore' 45 | - '**.js' 46 | - '**.ts' 47 | - '**.vue' 48 | 49 | lint: 50 | runs-on: ubuntu-latest 51 | 52 | needs: changes 53 | if: needs.changes.outputs.src != 'false' 54 | 55 | name: NPM lint 56 | 57 | steps: 58 | - name: Checkout 59 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 60 | 61 | - name: Read package.json node and npm engines version 62 | uses: skjnldsv/read-package-engines-version-actions@06d6baf7d8f41934ab630e97d9e6c0bc9c9ac5e4 # v3 63 | id: versions 64 | with: 65 | fallbackNode: '^20' 66 | fallbackNpm: '^10' 67 | 68 | - name: Set up node ${{ steps.versions.outputs.nodeVersion }} 69 | uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 70 | with: 71 | node-version: ${{ steps.versions.outputs.nodeVersion }} 72 | 73 | - name: Set up npm ${{ steps.versions.outputs.npmVersion }} 74 | run: npm i -g 'npm@${{ steps.versions.outputs.npmVersion }}' 75 | 76 | - name: Install dependencies 77 | env: 78 | CYPRESS_INSTALL_BINARY: 0 79 | PUPPETEER_SKIP_DOWNLOAD: true 80 | run: npm ci 81 | 82 | - name: Lint 83 | run: npm run lint 84 | 85 | summary: 86 | permissions: 87 | contents: none 88 | runs-on: ubuntu-latest-low 89 | needs: [changes, lint] 90 | 91 | if: always() 92 | 93 | # This is the summary, we just avoid to rename it so that branch protection rules still match 94 | name: eslint 95 | 96 | steps: 97 | - name: Summary status 98 | run: if ${{ needs.changes.outputs.src != 'false' && needs.lint.result != 'success' }}; then exit 1; fi 99 | -------------------------------------------------------------------------------- /.github/workflows/node-test.yml: -------------------------------------------------------------------------------- 1 | # This workflow is provided via the organization template repository 2 | # 3 | # https://github.com/nextcloud/.github 4 | # https://docs.github.com/en/actions/learn-github-actions/sharing-workflows-with-your-organization 5 | # 6 | # SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors 7 | # SPDX-License-Identifier: MIT 8 | 9 | name: Node tests 10 | 11 | on: 12 | pull_request: 13 | push: 14 | branches: 15 | - main 16 | - master 17 | - stable* 18 | 19 | permissions: 20 | contents: read 21 | 22 | concurrency: 23 | group: node-tests-${{ github.head_ref || github.run_id }} 24 | cancel-in-progress: true 25 | 26 | jobs: 27 | changes: 28 | runs-on: ubuntu-latest-low 29 | permissions: 30 | contents: read 31 | pull-requests: read 32 | 33 | outputs: 34 | src: ${{ steps.changes.outputs.src}} 35 | 36 | steps: 37 | - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2 38 | id: changes 39 | continue-on-error: true 40 | with: 41 | filters: | 42 | src: 43 | - '.github/workflows/**' 44 | - '__tests__/**' 45 | - '__mocks__/**' 46 | - 'src/**' 47 | - 'appinfo/info.xml' 48 | - 'package.json' 49 | - 'package-lock.json' 50 | - 'tsconfig.json' 51 | - '**.js' 52 | - '**.ts' 53 | - '**.vue' 54 | 55 | test: 56 | runs-on: ubuntu-latest 57 | 58 | needs: changes 59 | if: needs.changes.outputs.src != 'false' 60 | 61 | steps: 62 | - name: Checkout 63 | uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 64 | 65 | - name: Read package.json node and npm engines version 66 | uses: skjnldsv/read-package-engines-version-actions@06d6baf7d8f41934ab630e97d9e6c0bc9c9ac5e4 # v3 67 | id: versions 68 | with: 69 | fallbackNode: '^20' 70 | fallbackNpm: '^10' 71 | 72 | - name: Set up node ${{ steps.versions.outputs.nodeVersion }} 73 | uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 74 | with: 75 | node-version: ${{ steps.versions.outputs.nodeVersion }} 76 | 77 | - name: Set up npm ${{ steps.versions.outputs.npmVersion }} 78 | run: npm i -g 'npm@${{ steps.versions.outputs.npmVersion }}' 79 | 80 | - name: Install dependencies & build 81 | env: 82 | CYPRESS_INSTALL_BINARY: 0 83 | run: | 84 | npm ci 85 | npm run build --if-present 86 | 87 | - name: Test 88 | run: npm run test --if-present 89 | 90 | - name: Test and process coverage 91 | run: npm run test:coverage --if-present 92 | 93 | - name: Collect coverage 94 | uses: codecov/codecov-action@18283e04ce6e62d37312384ff67231eb8fd56d24 # v5.4.3 95 | with: 96 | files: ./coverage/lcov.info 97 | 98 | summary: 99 | permissions: 100 | contents: none 101 | runs-on: ubuntu-latest-low 102 | needs: [changes, test] 103 | 104 | if: always() 105 | 106 | name: test-summary 107 | 108 | steps: 109 | - name: Summary status 110 | run: if ${{ needs.changes.outputs.src != 'false' && needs.test.result != 'success' }}; then exit 1; fi 111 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | cache 132 | work 133 | private-key.pem 134 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "1.0.0", 6 | "configurations": [ 7 | { 8 | "name": "TSX Debug", 9 | "type": "node", 10 | "request": "launch", 11 | "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/tsx", 12 | "program": "src/index.ts", 13 | "cwd": "${workspaceRoot}", 14 | "internalConsoleOptions": "openOnSessionStart", 15 | "skipFiles": ["/**", "node_modules/**"] 16 | } 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | education, socio-economic status, nationality, personal appearance, race, 10 | religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at roeland@famdouma.nl. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | [fork]: /fork 4 | [pr]: /compare 5 | [style]: https://standardjs.com/ 6 | [code-of-conduct]: CODE_OF_CONDUCT.md 7 | 8 | Hi there! We're thrilled that you'd like to contribute to this project. Your help is essential for keeping it great. 9 | 10 | Please note that this project is released with a [Contributor Code of Conduct][code-of-conduct]. By participating in this project you agree to abide by its terms. 11 | 12 | ## Issues and PRs 13 | 14 | If you have suggestions for how this project could be improved, or want to report a bug, open an issue! We'd love all and any contributions. If you have questions, too, we'd love to hear them. 15 | 16 | We'd also love PRs. If you're thinking of a large PR, we advise opening up an issue first to talk about it, though! Look at the links below if you're not sure how to open a PR. 17 | 18 | ## Submitting a pull request 19 | 20 | 1. [Fork][fork] and clone the repository. 21 | 1. Configure and install the dependencies: `npm install`. 22 | 1. Make sure the tests pass on your machine: `npm test`, note: these tests also apply the linter, so there's no need to lint separately. 23 | 1. Create a new branch: `git checkout -b my-branch-name`. 24 | 1. Make your change, add tests, and make sure the tests still pass. 25 | 1. Push to your fork and [submit a pull request][pr]. 26 | 1. Pat your self on the back and wait for your pull request to be reviewed and merged. 27 | 28 | Here are a few things you can do that will increase the likelihood of your pull request being accepted: 29 | 30 | - Follow the [style guide][style] which is using standard. Any linting errors should be shown when running `npm test`. 31 | - Write and update tests. 32 | - Keep your changes as focused as possible. If there are multiple changes you would like to make that are not dependent upon each other, consider submitting them as separate pull requests. 33 | - Write a [good commit message](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). 34 | 35 | Work in Progress pull requests are also welcome to get feedback early on, or if there is something blocked you. 36 | 37 | ## Resources 38 | 39 | - [How to Contribute to Open Source](https://opensource.guide/how-to-contribute/) 40 | - [Using Pull Requests](https://help.github.com/articles/about-pull-requests/) 41 | - [GitHub Help](https://help.github.com) 42 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Backportbot 2 | 3 | The Backportbot is a GitHub bot designed to streamline the process of backporting pull requests or specific commits to older branches in the Nextcloud repository. 4 | This bot aims to make it easier for contributors to maintain and support multiple versions of the software by automating the backporting process. 5 | 6 | ## Usage 7 | 8 | The Backportbot responds to specific commands in GitHub comments. Here are the allowed commands: 9 | 10 | - `/backport to `: Backport all of the pull request's commits to the specified branch. 11 | - `/backport to `: Backport the specified commit to the specified branch. 12 | - `/backport to `: Backport multiple commits to the specified branch. 13 | - `/backport! to `: Trigger the backport request instantly without waiting for the pull request to be merged. 14 | 15 | ### Examples: 16 | 17 | 1. `/backport to stable28`: Backport all of the PR's commits to the stable28 branch. 18 | 2. `/backport abc456def to stable28`: Backport the commit with hash abc456def to the stable28 branch. 19 | 3. `/backport abc456def 123ghi789 to stable28`: Backport both commit abc456def and 123ghi789 to the stable28 branch. 20 | 4. `/backport! to stable28`: Trigger the backport request instantly without waiting for PR to be merged. 21 | 22 | ## How it Works 23 | 24 | The Backportbot monitors GitHub comments for the specified commands. When triggered and approved, it will wait for the PR to be merged and automatically create backport requests to the specified branches. In case of duplicates branches in the commands, the most recent one will always be used and the other dropped. 25 | 26 | ### Reactions and their meanings 27 | 28 | - 👀 The command is valid and the bot is waiting for the PR to be merged 29 | - 😕 The command is not valid 30 | - 👍 The bot started processing that comment/request 31 | - 👎 The bot failed to execute tha backport. A comment with steps and additional informations on the failure will also be added. 32 | 33 | ## Contribution 34 | 35 | Feel free to contribute to the development of the Backportbot. If you encounter issues or have ideas for improvement, please open an issue or submit a pull request. 36 | 37 | Let's make maintaining Nextcloud across different branches more efficient with the help of the Backportbot! -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.7" 2 | 3 | services: 4 | app: 5 | image: node:lts 6 | working_dir: "/app" 7 | command: sh -c "npm i && npm run serve" 8 | 9 | ports: 10 | - "3000:3000" 11 | 12 | environment: 13 | APP_ID: 12345 14 | WEBHOOK_SECRET: 123456789abcdefghijklmnop 15 | PRIVATE_KEY_PATH: /private-key.pem 16 | 17 | volumes: 18 | - ./backportbot:/app 19 | - ./private-key.pem:/private-key.pem:ro 20 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nextcloud/backportbot/5416d07b5ab889216e8bd15d43a96e79c6103308/logo.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "backportbot", 3 | "version": "2.0.0", 4 | "description": "A bot that backport commits to other branches", 5 | "main": "index.ts", 6 | "type": "module", 7 | "scripts": { 8 | "serve": "tsx src/index.ts", 9 | "test": "vitest run", 10 | "test:coverage": "vitest run --coverage", 11 | "test:watch": "vitest watch", 12 | "lint": "eslint src/**/*.ts", 13 | "lint:fix": "eslint src/**/*.ts --fix" 14 | }, 15 | "repository": { 16 | "type": "git", 17 | "url": "git+https://github.com/skjnldsv/backportbot.git" 18 | }, 19 | "keywords": [ 20 | "backport", 21 | "bot", 22 | "github", 23 | "git", 24 | "commit" 25 | ], 26 | "author": "skjnldsv", 27 | "license": "AGPL-3.0-or-later", 28 | "bugs": { 29 | "url": "https://github.com/skjnldsv/backportbot/issues" 30 | }, 31 | "homepage": "https://github.com/skjnldsv/backportbot#readme", 32 | "dependencies": { 33 | "@octokit/app": "^14.1.0", 34 | "@octokit/rest": "^21.1.1", 35 | "@octokit/webhooks": "^13.9.0", 36 | "p-queue": "^8.1.0", 37 | "simple-git": "^3.27.0", 38 | "tsx": "^4.19.4" 39 | }, 40 | "devDependencies": { 41 | "@tsconfig/recommended": "^1.0.8", 42 | "@types/node": "^20.14.12", 43 | "@typescript-eslint/eslint-plugin": "^7.0.0", 44 | "@typescript-eslint/parser": "^6.21.0", 45 | "@vitest/coverage-istanbul": "^2.1.8", 46 | "eslint": "^8.57.1", 47 | "typescript": "^5.8.3", 48 | "vitest": "^2.0.5" 49 | }, 50 | "engines": { 51 | "node": "^20.0.0", 52 | "npm": "^10.0.0" 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/appUtils.ts: -------------------------------------------------------------------------------- 1 | import { App } from '@octokit/app' 2 | import { readFileSync } from 'node:fs' 3 | 4 | import { APP_ID, PRIVATE_KEY_PATH, WEBHOOK_SECRET } from './constants' 5 | 6 | const initApp = (): App => { 7 | const privateKey = readFileSync(PRIVATE_KEY_PATH, 'utf-8').toString() 8 | return new App({ 9 | appId: APP_ID, 10 | privateKey, 11 | webhooks: { 12 | secret: WEBHOOK_SECRET, 13 | }, 14 | }) 15 | } 16 | 17 | let app: App | null = null 18 | export const getApp = (): App => { 19 | if (!app) { 20 | app = initApp() 21 | } 22 | return app 23 | } 24 | -------------------------------------------------------------------------------- /src/backport.ts: -------------------------------------------------------------------------------- 1 | import { existsSync, rmSync } from 'node:fs' 2 | import { Octokit } from '@octokit/rest' 3 | 4 | import { cherryPickCommits, cloneAndCacheRepo, getCommitTitle, hasDiff, hasEmptyCommits, hasSkipCiCommits, pushBranch } from './gitUtils.js' 5 | import { CherryPickResult, Task } from './constants.js' 6 | import { debug, error, info, warn } from './logUtils.js' 7 | import { Reaction, addReaction, getAuthToken, getAvailableLabels, getLabelsFromPR, getAvailableMilestones, requestReviewers, getReviewers, createBackportPullRequest, setPRLabels, setPRMilestone, getChangesFromPR, updatePRBody, commentOnPR, assignToPR } from './githubUtils.js' 8 | import { getBackportBody, getFailureCommentBody, getLabelsForPR, getMilestoneFromBase } from './nextcloudUtils.js' 9 | 10 | export async function backport(task: Task): Promise { 11 | const token = await getAuthToken(task.installationId) 12 | const octokit = new Octokit({ auth: token }) 13 | 14 | let tmpDir: string = '' 15 | let prNumber: number = 0 16 | let conflicts: CherryPickResult|null = null 17 | const backportBranch = `backport/${task.prNumber}/${task.branch}` 18 | 19 | info(task, `Starting backport request`) 20 | 21 | // Add a reaction to the comment to indicate that we're processing it 22 | try { 23 | await addReaction(octokit, task, Reaction.THUMBS_UP) 24 | } catch (e) { 25 | error(task, `Failed to add reaction to PR: ${e.message}`) 26 | // continue, this is not a fatal error 27 | } 28 | 29 | try { 30 | // Clone and cache the repo 31 | try { 32 | tmpDir = await cloneAndCacheRepo(task, backportBranch) 33 | info(task, `Cloned to ${tmpDir}`) 34 | } catch (e) { 35 | throw new Error(`Failed to clone repository: ${e.message}`) 36 | } 37 | 38 | // Cherry pick the commits 39 | try { 40 | conflicts = await cherryPickCommits(task, tmpDir) 41 | if (conflicts === CherryPickResult.CONFLICTS) { 42 | warn(task, `Cherry picking commits resulted in conflicts`) 43 | } else { 44 | info(task, `Cherry picking commits successful`) 45 | } 46 | } catch (e) { 47 | throw new Error(`Failed to cherry pick commits: ${e.message}`) 48 | } 49 | 50 | try { 51 | // Check if there are any changes to backport 52 | const hasChanges = await hasDiff(tmpDir, `origin/${task.branch}`, backportBranch, task) 53 | if (!hasChanges) { 54 | throw new Error(`No changes found in backport branch`) 55 | } 56 | } catch (e) { 57 | throw new Error(`Failed to check for changes with origin/${task.branch}: ${e.message}`) 58 | } 59 | 60 | // Push the branch 61 | try { 62 | await pushBranch(task, tmpDir, token, backportBranch) 63 | info(task, `Pushed branch ${backportBranch}`) 64 | } catch (e) { 65 | throw new Error(`Failed to push branch ${backportBranch}: ${e.message}`) 66 | } 67 | 68 | // If only one commit, we use it as the PR title 69 | if (!task.isFullRequest && task.commits.length === 1) { 70 | const oldTitle = task.prTitle 71 | task.prTitle = await getCommitTitle(tmpDir, task.commits[0]) || task.prTitle 72 | if (oldTitle !== task.prTitle) { 73 | info(task, `Using commit title as PR title: ${task.prTitle}`) 74 | } else { 75 | error(task, `Failed to get commit title`) 76 | } 77 | } 78 | 79 | // Create the pull request 80 | try { 81 | const reviewers = await getReviewers(octokit, task) 82 | const prCreationResult = await createBackportPullRequest(octokit, task, backportBranch, conflicts === CherryPickResult.CONFLICTS) 83 | prNumber = prCreationResult.data.number 84 | info(task, `Opened Pull Request #${prNumber} on ${prCreationResult.data.html_url}`) 85 | 86 | try { 87 | // Ask for reviews from all reviewers of the original PR 88 | if (reviewers.length !== 0) { 89 | await requestReviewers(octokit, task, prNumber, reviewers) 90 | } 91 | 92 | // Also ask the author of the original PR for a review 93 | await requestReviewers(octokit, task, prNumber, [task.author]) 94 | info(task, `Requested reviews from ${[...reviewers, task.author].join(', ')}`) 95 | } catch (e) { 96 | error(task, `Failed to request reviews: ${e.message}`) 97 | } 98 | } catch (e) { 99 | throw new Error(`Failed to create pull request: ${e.message}`) 100 | } 101 | 102 | // Get labels from original PR and set them on the new PR 103 | try { 104 | const availableLabels = await getAvailableLabels(octokit, task) 105 | const prLabels = await getLabelsFromPR(octokit, task) 106 | const labels = getLabelsForPR(prLabels, availableLabels) 107 | await setPRLabels(octokit, task, prNumber, labels) 108 | info(task, `Set labels: ${labels.join(', ')}`) 109 | } catch (e) { 110 | error(task, `Failed to get and set labels: ${e.message}`) 111 | // continue, this is not a fatal error 112 | } 113 | 114 | // Find new appropriate Milestone and set it on the new PR 115 | try { 116 | const availableMilestone = await getAvailableMilestones(octokit, task) 117 | const milestone = await getMilestoneFromBase(task.branch, availableMilestone) 118 | await setPRMilestone(octokit, task, prNumber, milestone) 119 | info(task, `Set milestone: ${milestone.title}`) 120 | } catch (e) { 121 | error(task, `Failed to find appropriate milestone: ${e.message}`) 122 | // continue, this is not a fatal error 123 | } 124 | 125 | // Assign the PR to the author of the original PR 126 | try { 127 | await assignToPR(octokit, task, prNumber, [task.author]) 128 | info(task, `Assigned original author: ${task.author}`) 129 | } catch (e) { 130 | error(task, `Failed to assign PR: ${e.message}`) 131 | // continue, this is not a fatal error 132 | } 133 | 134 | // Compare the original PR with the new PR 135 | try { 136 | const oldChanges = await getChangesFromPR(octokit, task, task.prNumber) 137 | const newChanges = await getChangesFromPR(octokit, task, prNumber) 138 | const diffChanges = oldChanges.additions !== newChanges.additions 139 | || oldChanges.deletions !== newChanges.deletions 140 | || oldChanges.changedFiles !== newChanges.changedFiles 141 | const skipCi = await hasSkipCiCommits(tmpDir, task.commits.length) 142 | const emptyCommits = await hasEmptyCommits(tmpDir, task.commits.length, task) 143 | const hasConflicts = conflicts === CherryPickResult.CONFLICTS 144 | 145 | debug(task, `hasConflicts: ${hasConflicts}, diffChanges: ${diffChanges}, emptyCommits: ${emptyCommits}, skipCi: ${skipCi}`) 146 | try { 147 | if (hasConflicts || diffChanges || emptyCommits || skipCi) { 148 | const newBody = await getBackportBody(task.prNumber, hasConflicts, diffChanges, emptyCommits, skipCi, task.isFullRequest) 149 | await updatePRBody(octokit, task, prNumber, newBody) 150 | } 151 | } catch (e) { 152 | error(task, `Failed to update PR body: ${e.message}`) 153 | // continue, this is not a fatal error 154 | } 155 | } catch (e) { 156 | error(task, `Failed to compare changes: ${e.message}`) 157 | // continue, this is not a fatal error 158 | } 159 | 160 | // Success! We're done here 161 | addReaction(octokit, task, Reaction.HOORAY) 162 | } catch (e) { 163 | // Add a thumbs down reaction to the comment to indicate that we failed 164 | try { 165 | addReaction(octokit, task, Reaction.THUMBS_DOWN) 166 | const failureComment = getFailureCommentBody(task, backportBranch, e?.message) 167 | await commentOnPR(octokit, task, failureComment) 168 | error(task, `Something went wrong during the backport process: ${e?.message}`) 169 | console.trace() 170 | } catch (e) { 171 | error(task, `Failed to comment failure on PR: ${e.message}`) 172 | // continue, this is not a fatal error 173 | } 174 | 175 | throw new Error(`Failed to backport: ${e.message}`) 176 | } finally { 177 | // Remove the temp dir if it exists 178 | if (tmpDir !== '' && existsSync(tmpDir)) { 179 | try { 180 | rmSync(tmpDir, { recursive: true }) 181 | info(task, `Removed ${tmpDir}`) 182 | } catch (e) { 183 | error(task, `Failed to remove ${tmpDir}: ${e.message}`) 184 | } 185 | } 186 | } 187 | } 188 | -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- 1 | import { dirname, join, resolve } from 'node:path' 2 | import { fileURLToPath } from 'node:url'; 3 | 4 | const __filename = fileURLToPath(import.meta.url) 5 | const __dirname = dirname(__filename) 6 | 7 | 8 | // Runtime variables 9 | export const SERVE_PORT = process.env.SERVE_PORT || 3000 10 | export const SERVE_HOST = process.env.SERVE_HOST || '0.0.0.0' 11 | 12 | // Path variables 13 | export const ROOT_DIR = resolve(__dirname + '/../') 14 | export const CACHE_DIRNAME = 'cache' // relative to the root dir 15 | export const WORK_DIRNAME = 'work' // relative to the root dir 16 | 17 | // Nextcloud variables 18 | export const ALLOWED_ORGS = ['nextcloud', 'nextcloud-libraries', 'skjnldsv'] 19 | 20 | // App variables 21 | export const APP_ID = process.env.APP_ID || 0 22 | export const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET || '' 23 | export const PRIVATE_KEY_FILENAME = 'private-key.pem' 24 | export const PRIVATE_KEY_PATH = process.env.PRIVATE_KEY_PATH || join(ROOT_DIR, PRIVATE_KEY_FILENAME) 25 | export const LOG_FILE = 'backport.log' 26 | 27 | // Command variables 28 | export const COMMAND_PREFIX = '/backport' 29 | export const TO_SEPARATOR = ' to ' 30 | export const COMMIT_REGEX = /^\b[0-9a-f]{7,40}$\b/i 31 | export const BRANCH_REGEX = /^\b[a-z0-9-_./]{1,100}\b$/i 32 | 33 | // Pull requests variables 34 | export const LABEL_BACKPORT = 'backport-request' 35 | export const LABEL_TO_REVIEW = '3. to review' 36 | 37 | export const STEP_REVIEW_CONFLICTS = 'Review and resolve any conflicts' 38 | export const STEP_REMOVE_EMPTY_COMMITS = 'Remove all the empty commits' 39 | export const STEP_AMEND_SKIP_CI = 'Amend HEAD commit to remove the line stating to skip CI' 40 | 41 | export const WARN_CONFLICTS = 'This backport had conflicts that were resolved with the `ours` merge strategy and is likely incomplete ⚠️' 42 | export const WARN_DIFF = 'This backport\'s changes differ from the original and might be incomplete ⚠️' 43 | 44 | export const LEARN_MORE = `\n\n---\n\nLearn more about backports at https://docs.nextcloud.com/server/stable/go.php?to=developer-backports.` 45 | 46 | // -------------------------------------------------- 47 | // Various shared types and enums 48 | export type Task = { 49 | installationId: number 50 | owner: string 51 | repo: string 52 | branch: string 53 | commits: string[] 54 | prNumber: number 55 | prTitle: string 56 | commentId: number 57 | author: string 58 | isFullRequest: boolean 59 | } 60 | 61 | export enum CherryPickResult { 62 | OK, 63 | CONFLICTS, 64 | } 65 | 66 | export type AuthResponse = { 67 | type: 'token', 68 | tokenType: 'installation', 69 | token: string, 70 | installationId: number, 71 | permissions: { 72 | contents: string, 73 | issues: string, 74 | metadata: string, 75 | pull_requests: string, 76 | }, 77 | createdAt: Date, 78 | expiresAt: Date, 79 | repositorySelection: string, 80 | } 81 | 82 | export type LogLevel = 'info' | 'warn' | 'error' | 'debug' 83 | 84 | export type PRChanges = { 85 | additions: number, 86 | deletions: number, 87 | changedFiles: number, 88 | } 89 | -------------------------------------------------------------------------------- /src/gitUtils.ts: -------------------------------------------------------------------------------- 1 | import { existsSync, mkdirSync} from 'node:fs' 2 | import { join } from 'node:path' 3 | import { CleanOptions, simpleGit } from 'simple-git' 4 | 5 | import { CACHE_DIRNAME, CherryPickResult, ROOT_DIR, Task, WORK_DIRNAME } from './constants.js' 6 | import { debug, error, info } from './logUtils.js' 7 | import { randomBytes } from 'node:crypto' 8 | 9 | export const setGlobalGitConfig = async (user: string): Promise => { 10 | const git = simpleGit() 11 | await git.addConfig('user.email', `${user}[bot]@users.noreply.github.com`, false, 'global') 12 | await git.addConfig('user.name', `${user}[bot]`, false, 'global') 13 | await git.addConfig('commit.gpgsign', 'false', false, 'global') 14 | await git.addConfig('format.signoff', 'true', false, 'global') 15 | } 16 | 17 | /** 18 | * Clones the repo into the cache dir and then copies it to the work dir. 19 | * @param owner The owner of the repo. 20 | * @param repo The name of the repo. 21 | * @param branch The branch to backport from. 22 | * @param backportBranch The branch to backport to. 23 | * @returns The path to the temp repo. 24 | */ 25 | export const cloneAndCacheRepo = async (task: Task, backportBranch: string): Promise => { 26 | const { owner, repo, branch } = task 27 | 28 | // Clone the repo into the cache dir or make sure it already exists 29 | const cachedRepoRoot = join(ROOT_DIR, CACHE_DIRNAME, owner, repo) 30 | try { 31 | // Create repo path if needed 32 | if (!existsSync(cachedRepoRoot)) { 33 | mkdirSync(cachedRepoRoot, { recursive: true }) 34 | } 35 | 36 | const git = simpleGit(cachedRepoRoot) 37 | if (!existsSync(cachedRepoRoot + '/.git')) { 38 | // Is not a repository, so clone 39 | await git.clone(`https://github.com/${owner}/${repo}`, '.') 40 | } else { 41 | // Is already a repository so make sure it is clean and follows the default branch 42 | await git.clean(CleanOptions.FORCE + CleanOptions.IGNORED_ONLY + CleanOptions.RECURSIVE) 43 | debug(task, `Repo already cached at ${cachedRepoRoot}`) 44 | } 45 | } catch (e) { 46 | throw new Error(`Failed to clone and cache repo: ${e.message}`) 47 | } 48 | 49 | // Init a new temp repo in the work dir 50 | const tmpDirName = randomBytes(7).toString('hex') 51 | const tmpRepoRoot = join(ROOT_DIR, WORK_DIRNAME, tmpDirName) 52 | try { 53 | // Copy the cached repo to the temp repo 54 | mkdirSync(join(ROOT_DIR, WORK_DIRNAME), { recursive: true }) 55 | 56 | // create worktree 57 | const git = simpleGit(cachedRepoRoot) 58 | 59 | // make sure we are on the default branch 60 | const defaultBranch = (await git.raw(['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'])).split('origin/').pop() || 'master' 61 | await git.raw(['checkout', defaultBranch.slice(0, defaultBranch.indexOf("\n")).trim()]) 62 | 63 | // fetch upstream version of the branch - well we need to fetch all because we do not know where the commits are located we need to cherry-pick 64 | await git.fetch(['-p', '--all']) 65 | 66 | // make sure the branch doesn't already exist 67 | try { 68 | await git.raw(['worktree', 'prune']); 69 | await git.deleteLocalBranches([backportBranch], true) 70 | info(task, `Removed existing worktree for branch ${backportBranch}`) 71 | } catch (e) { 72 | error(task, `Failed to remove existing worktree for branch ${backportBranch}: ${e.message}`) 73 | } 74 | // create work tree with up-to-date content of that branch 75 | await git.raw(['worktree', 'add', '-b', backportBranch, tmpRepoRoot, `origin/${branch}`]) 76 | } catch (e) { 77 | throw new Error(`Failed to create working tree: ${e.message}`) 78 | } 79 | 80 | return tmpRepoRoot 81 | } 82 | 83 | export const cherryPickCommits = async (task: Task, repoRoot: string): Promise => { 84 | const git = simpleGit(repoRoot) 85 | let conflicts = false 86 | let lastValidCommit = '' 87 | 88 | // Cherry pick all the commits 89 | for (const commit of task.commits) { 90 | // Cherry picking commit 91 | try { 92 | await git.raw(['cherry-pick', commit]) 93 | debug(task, `Cherry picked commit ${commit.slice(0, 8)}`) 94 | lastValidCommit = commit 95 | continue 96 | } catch (e) { 97 | conflicts = true 98 | await git.raw(['cherry-pick', '--abort']) 99 | error(task, `Could not cherry pick commit ${commit.slice(0, 8)}: ${e.message}`) 100 | } 101 | 102 | // Cherry picking commit while discarding conflicts 103 | try { 104 | await git.raw([ 105 | 'cherry-pick', 106 | commit, 107 | '--strategy-option', 108 | 'ours', 109 | '--keep-redundant-commits' 110 | ]) 111 | debug(task, `Cherry picked commit ${commit.slice(0, 8)} with conflicts`) 112 | lastValidCommit = commit 113 | } catch (e) { 114 | // This can fail if the commit is empty because all of its 115 | // files are conflicting. In that case, we can just skip it. 116 | error(task, `Could not cherry pick commit ${commit.slice(0, 8)} with ours strategy: ${e.message}`) 117 | await git.raw(['cherry-pick', '--abort']) 118 | } 119 | } 120 | 121 | // If there are conflicts, we need to amend the last commit message 122 | // to add a skip-ci tag so that CI doesn't run on the PR. 123 | if (conflicts && lastValidCommit !== '') { 124 | let originalCommitMessage: string|null = null 125 | try { 126 | const commitLog = await git.log({ 127 | from: lastValidCommit, 128 | to: `${lastValidCommit}~1`, 129 | multiLine: true, 130 | }) 131 | originalCommitMessage = commitLog?.latest?.body || null 132 | 133 | if (originalCommitMessage !== null) { 134 | originalCommitMessage += '\n\n[skip ci]' 135 | // One line per -m flag 136 | const splitLines = originalCommitMessage.split('\n').map(line => ['-m', line.trim()]) 137 | await git.raw(['commit', '--amend', ...splitLines.flat()]) 138 | debug(task, `Amended commit ${lastValidCommit.slice(0, 8)} message with [skip ci] tag`) 139 | } 140 | } catch (e) { 141 | error(task, `Could not get commit ${lastValidCommit.slice(0, 8)} message from git log`) 142 | } 143 | } 144 | 145 | return conflicts ? CherryPickResult.CONFLICTS : CherryPickResult.OK 146 | } 147 | 148 | export const pushBranch = async (task: Task, repoRoot: string, token: string, backportBranch: string): Promise => { 149 | const git = simpleGit(repoRoot) 150 | git.remote(['set-url', 'origin', `https://x-access-token:${token}@github.com/${task.owner}/${task.repo}.git`]) 151 | await git.raw(['push', 'origin', '--force', backportBranch]) 152 | } 153 | 154 | export const hasSkipCiCommits = async (repoRoot: string, commits: number): Promise => { 155 | const git = simpleGit(repoRoot) 156 | const log = await git.log({ 157 | from: `HEAD~${commits}`, 158 | to: 'HEAD', 159 | multiLine: true, 160 | }) 161 | const commitMessages = log.all.map(commit => commit.body) 162 | return commitMessages.some(message => message.includes('[skip ci]')) 163 | } 164 | 165 | export const hasDiff = async (repoRoot: string, base: string, head: string, task: Task): Promise => { 166 | const git = simpleGit(repoRoot) 167 | const diff = await git.raw(['diff', '--stat', base, head]) 168 | debug(task, `Diff between ${base} and ${head}: ${diff}`) 169 | return diff !== '' 170 | } 171 | 172 | export const hasEmptyCommits = async (repoRoot: string, commits: number, task: Task): Promise => { 173 | let hasEmptyCommits = false 174 | for (let count = 0; count < commits; count++) { 175 | if (!await hasDiff(repoRoot, `HEAD~${count}`, `HEAD~${count + 1}`, task)) { 176 | hasEmptyCommits = true 177 | break 178 | } 179 | } 180 | return hasEmptyCommits 181 | } 182 | 183 | export const getCommitTitle = async (repoRoot: string, commit: string): Promise => { 184 | const git = simpleGit(repoRoot) 185 | const log = await git.log({ 186 | from: commit, 187 | to: `${commit}~1`, 188 | multiLine: true, 189 | }) 190 | return log.latest?.message || null 191 | } 192 | -------------------------------------------------------------------------------- /src/githubUtils.ts: -------------------------------------------------------------------------------- 1 | import { Octokit } from '@octokit/rest' 2 | import { getApp } from './appUtils' 3 | import { AuthResponse, COMMAND_PREFIX, PRChanges, Task } from './constants' 4 | import { IssueComment, Milestone } from '@octokit/webhooks-types' 5 | 6 | export enum Reaction { 7 | THUMBS_UP = '+1', 8 | THUMBS_DOWN = '-1', 9 | LAUGH = 'laugh', 10 | CONFUSED = 'confused', 11 | HEART = 'heart', 12 | HOORAY = 'hooray', 13 | ROCKET = 'rocket', 14 | EYES = 'eyes', 15 | } 16 | 17 | export const getAuthToken = async (installationId: number): Promise => { 18 | const app = getApp() 19 | const { token } = await app.octokit.auth({ type: 'installation', installationId }) as AuthResponse 20 | return token 21 | } 22 | 23 | export const getCommitsForPR = async (octokit: Octokit, owner: string, repo: string, pr: number): Promise => { 24 | const { data: commits } = await octokit.rest.pulls.listCommits({ 25 | owner, 26 | repo, 27 | pull_number: pr, 28 | }) 29 | return commits 30 | // Filter out merge commits 31 | .filter(commit => (commit.parents || []).length <= 1) 32 | .map(commit => commit.sha) 33 | } 34 | 35 | export const addReaction = async (octokit: Octokit, task: Task, reaction: Reaction): Promise => { 36 | const { owner, repo, commentId } = task 37 | await octokit.rest.reactions.createForIssueComment({ 38 | owner, 39 | repo, 40 | comment_id: commentId, 41 | content: reaction, 42 | }) 43 | } 44 | 45 | export const getReviewers = async function (octokit: Octokit, task: Task): Promise { 46 | const { owner, repo, prNumber } = task 47 | const reviews = await octokit.pulls.listReviews({ 48 | owner, 49 | repo, 50 | pull_number: prNumber 51 | }) 52 | 53 | // Filter non collaborators and non approved reviews 54 | // Then map to usernames and remove invalid values 55 | const reviewers = reviews.data 56 | .filter(review => review.state === 'APPROVED') 57 | .filter(reviewer => reviewer.author_association !== 'NONE') 58 | .map(reviewer => reviewer?.user?.login) 59 | .filter(Boolean) as string[] 60 | 61 | // Remove duplicates 62 | return [...new Set(reviewers)] 63 | } 64 | 65 | export const requestReviewers = async function (octokit: Octokit, task: Task, prNumber: number, reviewers: string[]) { 66 | const { owner, repo } = task 67 | return octokit.pulls.requestReviewers({ 68 | owner, 69 | repo, 70 | pull_number: prNumber, 71 | reviewers 72 | }) 73 | } 74 | 75 | export const createBackportPullRequest = async (octokit: Octokit, task: Task, head: string, conflicts = false) => { 76 | const { owner, repo, branch, prNumber, prTitle } = task 77 | 78 | return await octokit.rest.pulls.create({ 79 | owner, 80 | repo, 81 | head, 82 | base: branch, 83 | body: `Backport of PR #${prNumber}`, 84 | title: `[${branch}] ${prTitle}`, 85 | draft: conflicts, 86 | maintainer_can_modify: true, 87 | }) 88 | } 89 | 90 | export const updatePRBody = async (octokit: Octokit, task: Task, prNumber: number, body: string) => { 91 | const { owner, repo } = task 92 | return octokit.rest.pulls.update({ 93 | owner, 94 | repo, 95 | pull_number: prNumber, 96 | body, 97 | }) 98 | } 99 | 100 | export const getAvailableMilestones = async (octokit: Octokit, task: Task): Promise => { 101 | const { owner, repo } = task 102 | const { data } = await octokit.rest.issues.listMilestones({ 103 | owner, 104 | repo, 105 | state: 'open', 106 | }) 107 | 108 | return data as Milestone[] 109 | } 110 | 111 | export const getAvailableLabels = async (octokit: Octokit, task: Task): Promise => { 112 | const { owner, repo } = task 113 | const labels = await octokit.rest.issues.listLabelsForRepo({ 114 | owner, 115 | repo, 116 | }) 117 | 118 | return labels.data.map(label => label.name) 119 | } 120 | 121 | export const getLabelsFromPR = async (octokit: Octokit, task: Task): Promise => { 122 | const { owner, repo, prNumber } = task 123 | const labels = await octokit.rest.issues.listLabelsOnIssue({ 124 | owner, 125 | repo, 126 | issue_number: prNumber, 127 | }) 128 | 129 | return labels.data.map(label => label.name) 130 | } 131 | 132 | export const setPRLabels = async (octokit: Octokit, task: Task, prNumber: number, labels: string[]) => { 133 | const { owner, repo } = task 134 | return octokit.issues.update({ 135 | owner, 136 | repo, 137 | issue_number: prNumber, 138 | labels 139 | }) 140 | } 141 | 142 | export const addPRLabel = async (octokit: Octokit, task: Task, prNumber: number, label: string) => { 143 | const { owner, repo } = task 144 | return octokit.issues.addLabels({ 145 | owner, 146 | repo, 147 | issue_number: prNumber, 148 | labels: [label] 149 | }) 150 | } 151 | 152 | export const removePRLabel = async (octokit: Octokit, task: Task, prNumber: number, label: string) => { 153 | const { owner, repo } = task 154 | return octokit.issues.removeLabel({ 155 | owner, 156 | repo, 157 | issue_number: prNumber, 158 | name: label 159 | }) 160 | } 161 | 162 | export const assignToPR = async (octokit: Octokit, task: Task, prNumber: number, assignees: string[]) => { 163 | const { owner, repo } = task 164 | return octokit.issues.addAssignees({ 165 | owner, 166 | repo, 167 | issue_number: prNumber, 168 | assignees 169 | }) 170 | } 171 | 172 | export const setPRMilestone = async (octokit: Octokit, task: Task, prNumber: number, milestone: Milestone) => { 173 | const { owner, repo } = task 174 | return octokit.issues.update({ 175 | owner, 176 | repo, 177 | issue_number: prNumber, 178 | milestone: milestone.number 179 | }) 180 | } 181 | 182 | export const getChangesFromPR = async (octokit: Octokit, task: Task, prNumber: number): Promise => { 183 | const { owner, repo } = task 184 | 185 | const { data } = await octokit.rest.pulls.get({ 186 | owner, 187 | repo, 188 | pull_number: prNumber, 189 | }) 190 | 191 | return { 192 | additions: data.additions, 193 | deletions: data.deletions, 194 | changedFiles: data.changed_files, 195 | } as PRChanges 196 | } 197 | 198 | export const commentOnPR = async (octokit: Octokit, task: Task, body: string) => { 199 | const { owner, repo, prNumber } = task 200 | return octokit.rest.issues.createComment({ 201 | owner, 202 | repo, 203 | issue_number: prNumber, 204 | body, 205 | }) 206 | } 207 | 208 | export const getBackportRequestsFromPR = async (octokit: Octokit, task: Task): Promise => { 209 | const { owner, repo, prNumber } = task 210 | const { data } = await octokit.rest.issues.listComments({ 211 | owner, 212 | repo, 213 | issue_number: prNumber, 214 | }) 215 | 216 | return data 217 | // Filter out invalid comments 218 | .filter(comment => comment?.body?.trim().startsWith(COMMAND_PREFIX)) 219 | // Filter out forced requests 220 | .filter(comment => !comment?.body?.trim().startsWith(COMMAND_PREFIX + '!')) 221 | // Filter out comments from non-collaborators 222 | .filter(comment => comment?.author_association !== 'NONE') 223 | // Filter out comments that got rejected by the bot. 224 | // This is a safety measure, we will check the command again 225 | .filter(comment => comment.reactions?.confused === 0) as IssueComment[] 226 | } 227 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { createNodeMiddleware } from '@octokit/webhooks' 2 | import { createServer } from 'http' 3 | import { info, error, warn } from 'node:console' 4 | import { Octokit } from '@octokit/rest' 5 | 6 | import { addToQueue } from './queue.js' 7 | import { ALLOWED_ORGS, CACHE_DIRNAME, COMMAND_PREFIX, LABEL_BACKPORT, PRIVATE_KEY_PATH, ROOT_DIR, SERVE_HOST, SERVE_PORT, TO_SEPARATOR, Task, WEBHOOK_SECRET, WORK_DIRNAME } from './constants.js' 8 | import { extractBranchFromPayload, extractCommitsFromPayload, isFriendly } from './payloadUtils.js' 9 | import { getApp } from './appUtils.js' 10 | import { Reaction, addPRLabel, addReaction, getAuthToken, getBackportRequestsFromPR, getCommitsForPR, removePRLabel } from './githubUtils.js' 11 | import { setGlobalGitConfig } from './gitUtils.js' 12 | 13 | const app = getApp() 14 | 15 | app.webhooks.onError((err) => { 16 | error(`Error occurred in ${err.event.name}: ${err.message}`) 17 | }) 18 | 19 | app.webhooks.on(['pull_request.closed'], async ({ payload }) => { 20 | const installationId = payload?.installation?.id as number 21 | const owner = payload.repository.owner.login 22 | const repo = payload.repository.name 23 | const htmlUrl = payload.pull_request.html_url 24 | 25 | if (ALLOWED_ORGS.includes(owner) === false) { 26 | info(`Ignoring ${htmlUrl} from ${owner}`) 27 | return 28 | } 29 | 30 | const authOctokit = new Octokit({ auth: await getAuthToken(installationId) }) 31 | 32 | const author = payload.pull_request?.user?.login || '' 33 | const prNumber = payload.pull_request?.number 34 | const prTitle = payload.pull_request?.title || `Backport of PR #${prNumber}` 35 | 36 | // Check if valid PR 37 | const isMerged = payload?.pull_request?.merged === true 38 | if (!isMerged) { 39 | info(`Ignoring closed but unmerged PR ${htmlUrl}`) 40 | return 41 | } 42 | 43 | // Check if PR has backport requests 44 | const comments = await (await getBackportRequestsFromPR(authOctokit, { owner, repo, prNumber: payload.number } as Task)).reverse() 45 | if (comments.length === 0) { 46 | info(`Closed PR ${htmlUrl} have no backport requests, skipping`) 47 | return 48 | } 49 | 50 | info(`\nReceived merged PR ${htmlUrl}`) 51 | info(`├ Repo: ${owner}/${repo}`) 52 | info(`├ Author: ${author}`) 53 | 54 | // We will ignore duplicate requests to the same branch 55 | const processedBranches = new Set() 56 | const tasksToProcess: Task[] = [] 57 | 58 | // Process each comment 59 | for(const { id, body } of comments) { 60 | try { 61 | let branch: string 62 | let commits: string[] = [] 63 | 64 | // Extract the commits and branch from the payload 65 | try { 66 | commits = extractCommitsFromPayload(body) 67 | branch = extractBranchFromPayload(body) 68 | } catch (e) { 69 | // Add a confused reaction to the comment to indicate that we failed to understand it 70 | addReaction(authOctokit, { owner, repo, commentId: id } as Task, Reaction.CONFUSED) 71 | error(`├ Failed to extract commits and branch from payload: \`${body}\``) 72 | continue 73 | } 74 | 75 | if (processedBranches.has(branch)) { 76 | info(`├ Skipping duplicate backport request to \`${branch}\``) 77 | continue 78 | } 79 | 80 | const isFullRequest = body.trim().startsWith(COMMAND_PREFIX + TO_SEPARATOR) 81 | if (isFullRequest) { 82 | commits = await getCommitsForPR(authOctokit, owner, repo, prNumber) 83 | info(`├ Full backport request to \`${branch}\` with ${commits.length} commits`) 84 | } else { 85 | info(`├ Partial backport request to \`${branch}\` with ${commits.length} commits`) 86 | } 87 | 88 | const task = { 89 | owner, 90 | repo, 91 | branch, 92 | commits, 93 | prNumber, 94 | prTitle, 95 | commentId: id, 96 | installationId, 97 | author, 98 | isFullRequest, 99 | } as Task 100 | 101 | processedBranches.add(branch) 102 | tasksToProcess.push(task) 103 | } catch (e) { 104 | error(`├ Failed to handle \`${body}\` request: ${e.message}`) 105 | } 106 | } 107 | 108 | // Process the tasks 109 | const tasks = tasksToProcess.map(task => addToQueue(task)) 110 | Promise.allSettled(tasks).then(async results => { 111 | const hasFailedTasks = results.some(result => result.status === 'rejected') 112 | 113 | // Remove the backport label from the PR if all succeeded 114 | if (!hasFailedTasks) { 115 | try { 116 | await removePRLabel(authOctokit, { owner, repo } as Task, prNumber, LABEL_BACKPORT) 117 | } catch (e) { 118 | error(`\nFailed to remove backport label from PR ${htmlUrl}: ${e.message}`) 119 | } 120 | } 121 | }) 122 | 123 | info(`├ Total backport requests: ${comments.length}`) 124 | info(`└ Handled backport requests: ${processedBranches.size}\n`) 125 | }) 126 | 127 | app.webhooks.on(['issue_comment.created'], async ({ payload }) => { 128 | const installationId = payload?.installation?.id as number 129 | const owner = payload.repository.owner.login 130 | const repo = payload.repository.name 131 | const htmlUrl = payload.issue.html_url 132 | 133 | if (ALLOWED_ORGS.includes(owner) === false) { 134 | info(`Ignoring ${htmlUrl} from ${owner}`) 135 | return 136 | } 137 | 138 | const commentId = payload?.comment?.id as number 139 | const body = payload?.comment?.body || '' 140 | const actor = payload?.comment?.user?.login || '' 141 | 142 | const author = payload.issue?.user?.login || '' 143 | const prNumber = payload.issue?.number 144 | const prTitle = payload.issue?.title || `Backport of PR #${prNumber}` 145 | 146 | const authOctokit = new Octokit({ auth: await getAuthToken(installationId) }) 147 | 148 | // Ignoring comments on issues that are not PRs 149 | if (!payload?.issue?.pull_request) { 150 | return 151 | } 152 | 153 | // Check if the comment is a backport request 154 | if (body.trim().startsWith(COMMAND_PREFIX)) { 155 | // Check if the author is at least a collaborator 156 | const commentAuthor = payload?.comment?.user.login 157 | const authorAssociation = payload?.comment?.author_association 158 | if (!authorAssociation || authorAssociation === 'NONE') { 159 | info(`Ignoring comment from non-collaborator: ${commentAuthor}}`) 160 | return 161 | } 162 | 163 | let branch: string 164 | let commits: string[] = [] 165 | 166 | const isForcedRequest = body.trim().startsWith(COMMAND_PREFIX + '!') 167 | const isFullRequest = body.trim().startsWith(isForcedRequest ? COMMAND_PREFIX + '!' + TO_SEPARATOR : COMMAND_PREFIX + TO_SEPARATOR) 168 | const isClosed = payload.issue?.state === 'closed' 169 | const isMerged = typeof payload.issue?.pull_request?.merged_at === 'string' 170 | 171 | if (isClosed && !isMerged) { 172 | try { 173 | addReaction(authOctokit, { owner, repo, commentId } as Task, Reaction.THUMBS_DOWN) 174 | } catch (e) { 175 | // Safely ignore 176 | warn(`Failed to add reaction to comment: ${e.message}`) 177 | } 178 | error(`Ignoring comment on closed but unmerged PR ${htmlUrl}`) 179 | return 180 | } 181 | 182 | // Extract the commits and branch from the payload 183 | try { 184 | commits = extractCommitsFromPayload(body) 185 | branch = extractBranchFromPayload(body) 186 | } catch (e) { 187 | // Add a confused reaction to the comment to indicate that we failed to understand it 188 | addReaction(authOctokit, { owner, repo, commentId } as Task, Reaction.CONFUSED) 189 | error(`Failed to extract commits and branch from payload: \`${body}\` on ${htmlUrl}`) 190 | return 191 | } 192 | try { 193 | if (isFriendly(body)) { 194 | addReaction(authOctokit, { owner, repo, commentId } as Task, Reaction.HEART) 195 | } 196 | } catch (e) { 197 | warn(`Could not process friendliness: ` + e.message) 198 | } 199 | 200 | // Start processing the request 201 | try { 202 | // If we have no commits, and the request did specify some commits 203 | // then something went wrong. 204 | // /backport `5e83e97 to stable28` means we backport 5e83e97 to stable28 205 | // /backport to stable28 means we backport all commits from this PR to stable28 206 | if (commits.length === 0 && !isFullRequest) { 207 | throw new Error('No commits found in payload') 208 | } 209 | 210 | if (isFullRequest) { 211 | info(`\nReceived full backport request to \`${branch}\``) 212 | info(`├ Fetching commits from PR ${htmlUrl}...`) 213 | commits = await getCommitsForPR(authOctokit, owner, repo, prNumber) 214 | } else { 215 | info(`\nReceived partial backport request to \`${branch}\``) 216 | } 217 | 218 | // PR info 219 | if (isMerged) { 220 | info(`├ PR is merged, starting backport right away`) 221 | } else if (isForcedRequest) { 222 | info(`├ PR is not merged, but force flag is present, starting backport right away`) 223 | } else { 224 | info(`├ PR is not merged yet, waiting for merge`) 225 | addReaction(authOctokit, { owner, repo, commentId } as Task, Reaction.EYES) 226 | } 227 | 228 | info(`├ Repo: ${owner}/${repo}`) 229 | info(`├ Author: ${author}`) 230 | info(`├ Actor: ${actor}`) 231 | info(`└ Commits: ${commits.map(commit => commit.slice(0, 8)).join(' ')}\n`) 232 | 233 | const task = { 234 | owner, 235 | repo, 236 | branch, 237 | commits, 238 | prNumber, 239 | prTitle, 240 | commentId, 241 | installationId, 242 | author, 243 | isFullRequest 244 | } as Task 245 | 246 | // Add the backport label to the PR 247 | try { 248 | await addPRLabel(authOctokit, task, prNumber, LABEL_BACKPORT) 249 | } catch (e) { 250 | error(`Failed to set labels on PR: ${e.message}`) 251 | } 252 | 253 | // If the PR is already merged, we can start the backport right away 254 | if (isMerged || isForcedRequest) { 255 | try { 256 | await addToQueue(task) 257 | // Remove the backport label from the PR on success 258 | try { 259 | await removePRLabel(authOctokit, task, prNumber, LABEL_BACKPORT) 260 | } catch (e) { 261 | error(`\nFailed to remove backport label from PR ${htmlUrl}: ${e.message}`) 262 | } 263 | } catch (e) { 264 | // Safely ignore 265 | } 266 | } 267 | } catch (e) { 268 | // This should really not happen, but if it does, we want to know about it 269 | if (e instanceof Error) { 270 | try { 271 | addReaction(authOctokit, { owner, repo, commentId } as Task, Reaction.THUMBS_DOWN) 272 | } catch (e) { 273 | // Safely ignore 274 | warn(`Failed to add reaction to comment: ${e.message}`) 275 | } 276 | error(`Failed to handle backport request: ${e.message}`) 277 | return 278 | } 279 | error('Failed to handle backport request, unknown error') 280 | } 281 | } 282 | }) 283 | 284 | app.octokit.request('/app').then(async ({data}) => { 285 | if (!data.events.includes('pull_request') || !data.events.includes('issue_comment')) { 286 | error(`The app is not subscribed to the required events. 287 | You need to subscribe to \`pull_request\` AND \`issue_comment\` events. 288 | Subscribed events: ${data.events}`) 289 | process.exit(1) 290 | } 291 | 292 | // Set the global git config 293 | await setGlobalGitConfig(data.name) 294 | 295 | const obfuscatedWebhookSecret = WEBHOOK_SECRET.slice(0, 8) + '*'.repeat(WEBHOOK_SECRET.length - 8) 296 | info(`Listening on ${SERVE_HOST}:${SERVE_PORT}`) 297 | info(`├ Authenticated as ${data.name}`) 298 | info(`├ Monitoring events ${data.events.join(', ')}`) 299 | info(`├ Command prefix: ${COMMAND_PREFIX}`) 300 | info(`├──────────────────────────────`) 301 | info(`├ Root directory: ${ROOT_DIR}`) 302 | info(`├ Cache directory: ${ROOT_DIR}/${CACHE_DIRNAME}`) 303 | info(`├ Work directory: ${ROOT_DIR}/${WORK_DIRNAME}`) 304 | info(`├──────────────────────────────`) 305 | info(`├ Allowed orgs: ${ALLOWED_ORGS.join(', ')}`) 306 | info(`├ Private key in ${PRIVATE_KEY_PATH}`) 307 | info(`└ Webhook secret is ${obfuscatedWebhookSecret}`) 308 | 309 | // Create server 310 | const middleware = createNodeMiddleware(app.webhooks) 311 | createServer(async (req, res) => { 312 | // `middleware` returns `false` when `req` is unhandled (beyond `/api/github`) 313 | if (await middleware(req, res)) return; 314 | 315 | // Add health check 316 | if (req.url === '/health') { 317 | res.writeHead(200, { 'Content-Type': 'text/plain' }) 318 | res.end('OK') 319 | } 320 | }).listen(SERVE_PORT, SERVE_HOST) 321 | }) 322 | -------------------------------------------------------------------------------- /src/logUtils.ts: -------------------------------------------------------------------------------- 1 | import { createWriteStream } from 'fs' 2 | import { join } from 'node:path' 3 | 4 | import { LOG_FILE, LogLevel, ROOT_DIR, Task } from './constants' 5 | 6 | // Open the log file for appending 7 | const logFile = createWriteStream(join(ROOT_DIR, LOG_FILE), { flags : 'a' }) 8 | 9 | // Log a message to the log file 10 | const log = (task: Task, message: string, level: LogLevel): void => { 11 | logFile.write(JSON.stringify({ 12 | level, 13 | task, 14 | message, 15 | time: new Date().toISOString(), 16 | }) + '\n') 17 | } 18 | 19 | export const error = (task: Task, message: string): void => { 20 | log(task, message, 'error') 21 | } 22 | 23 | export const warn = (task: Task, message: string): void => { 24 | log(task, message, 'warn') 25 | } 26 | 27 | export const info = (task: Task, message: string): void => { 28 | log(task, message, 'info') 29 | } 30 | 31 | export const debug = (task: Task, message: string): void => { 32 | log(task, message, 'debug') 33 | } 34 | -------------------------------------------------------------------------------- /src/nextcloudUtils.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, test } from 'vitest' 2 | import { Milestone } from '@octokit/webhooks-types' 3 | import { getMilestoneFromBase } from './nextcloudUtils' 4 | 5 | describe('Match branch branch to milestone', () => { 6 | const branches = [ 7 | 'stable28', 8 | 'stable26', 9 | 'stable21', 10 | 'stable1', 11 | 'stable-3.11', 12 | 'stable-4.0.0', 13 | ] 14 | 15 | const milestones = [ 16 | 'Nextcloud 21.1.0', 17 | 'Nextcloud 21.0.1', 18 | 'Nextcloud 26.0.10', 19 | 'Nextcloud 26.0.9', 20 | 'Nextcloud 21.1.0', 21 | 'Nextcloud 1.0.0', 22 | 'Nextcloud 1.1.1', 23 | '💞 Next Major (29)', 24 | '💙 Next Patch (28)', 25 | '💔 Backlog', 26 | '3.11.1', 27 | '3.10.4', 28 | ].map(title => ({ title })) as Milestone[] 29 | 30 | const expectedMilestones = [ 31 | '💙 Next Patch (28)', 32 | 'Nextcloud 26.0.9', 33 | 'Nextcloud 21.0.1', 34 | 'Nextcloud 1.0.0', 35 | '3.11.1', 36 | undefined, 37 | ] 38 | 39 | branches.forEach((branch, index) => { 40 | test(`Branch '${branch}' should return milestone '${expectedMilestones[index]}'`, () => { 41 | expect(getMilestoneFromBase(branch, milestones)?.title).toEqual(expectedMilestones[index]) 42 | }) 43 | }) 44 | }) 45 | 46 | describe('Throws error for invalid branch', () => { 47 | const branches = [ 48 | 'stable', 49 | '', 50 | ] 51 | const milestones = [ 52 | 'Nextcloud 21.1.0', 53 | 'Nextcloud 21.0.1', 54 | 'Nextcloud 1.0.0', 55 | 'Nextcloud 1.1.1', 56 | '💞 Next Major (29)', 57 | '💙 Next Patch (28)', 58 | '💔 Backlog', 59 | '3.11.1', 60 | '3.10.4', 61 | ].map(title => ({ title })) as Milestone[] 62 | 63 | branches.forEach(branch => { 64 | test(`Branch '${branch}'`, () => { 65 | expect(() => getMilestoneFromBase(branch, milestones)) 66 | .toThrow(`Could not extract version from branch \`${branch}\``) 67 | }) 68 | }) 69 | }) 70 | -------------------------------------------------------------------------------- /src/nextcloudUtils.ts: -------------------------------------------------------------------------------- 1 | import { Milestone } from '@octokit/webhooks-types' 2 | import { LABEL_BACKPORT, LABEL_TO_REVIEW, LEARN_MORE, STEP_AMEND_SKIP_CI, STEP_REMOVE_EMPTY_COMMITS, STEP_REVIEW_CONFLICTS, Task, WARN_CONFLICTS, WARN_DIFF } from './constants' 3 | 4 | const compareSemanticVersions = (a: string, b: string) => { 5 | // 1. Split the strings into their parts. 6 | const a1 = a.split('.') 7 | const b1 = b.split('.') 8 | 9 | // 2. Contingency in case there's a 4th or 5th version 10 | const len = Math.min(a1.length, b1.length) 11 | 12 | // 3. Look through each version number and compare. 13 | for (let i = 0; i < len; i++) { 14 | const a2 = +a1[ i ] || 0 15 | const b2 = +b1[ i ] || 0 16 | 17 | if (a2 !== b2) { 18 | return a2 > b2 ? 1 : -1 19 | } 20 | } 21 | 22 | // 4. We hit this if the all checked versions so far are equal 23 | return b1.length - a1.length 24 | } 25 | 26 | export const getMilestoneFromBase = (branch: string, milestones: Milestone[]): Milestone => { 27 | // Extract the version from the branch name, e.g. stable21 28 | const version = branch.match(/^\D+([\d.]+)/i)?.[1] 29 | if (!version) { 30 | throw new Error(`Could not extract version from branch \`${branch}\``) 31 | } 32 | const selection = milestones 33 | .filter(milestone => milestone.title.includes(version)) 34 | .sort((a, b) => compareSemanticVersions(a.title, b.title)) 35 | return selection[0] 36 | } 37 | 38 | export const getLabelsForPR = (labels: string[], repoLabels: string[]): string[] => { 39 | const results: string[] = [] 40 | 41 | // If the repo have the to-review kanban label, add it to the PR 42 | if (repoLabels.includes(LABEL_TO_REVIEW)) { 43 | results.push(LABEL_TO_REVIEW) 44 | } 45 | 46 | results.push( 47 | ...labels 48 | // Filter out the backport label 49 | .filter(label => label !== LABEL_BACKPORT) 50 | // Filter out kanban labels 51 | .filter(label => label.match(/^\d\./) === null) 52 | ) 53 | 54 | return [...new Set(results)] // Remove duplicates 55 | } 56 | 57 | export const getBackportBody = (prNumber: number, hasConflicts: boolean, hasDiff: boolean, hasEmptyCommits: boolean, hasSkipCiCommits: boolean, isFullRequest = false) => { 58 | const steps: string[] = [] 59 | let warning: string = '' 60 | 61 | if (hasConflicts) { 62 | steps.push(STEP_REVIEW_CONFLICTS) 63 | warning = WARN_CONFLICTS 64 | } 65 | 66 | // Check if we have a PR diff only if it's a full request 67 | if (hasDiff && isFullRequest) { 68 | steps.push(STEP_REVIEW_CONFLICTS) 69 | warning = WARN_DIFF 70 | } 71 | 72 | if (hasEmptyCommits) { 73 | steps.push(STEP_REMOVE_EMPTY_COMMITS) 74 | } 75 | 76 | if (hasSkipCiCommits) { 77 | steps.push(STEP_AMEND_SKIP_CI) 78 | } 79 | 80 | let body = `Backport of #${prNumber}` 81 | 82 | if (warning !== '') { 83 | body += `\n\n Warning, ${warning}` 84 | } 85 | 86 | if (steps.length > 0) { 87 | body += `\n\n## Todo \n` 88 | body += [...new Set(steps)].map(step => `- [ ] ${step}`).join('\n') 89 | } 90 | 91 | body += LEARN_MORE 92 | 93 | return body 94 | } 95 | 96 | export const getFailureCommentBody = (task: Task, target: string, error: string = 'Unknown error') => { 97 | const { branch, commits } = task 98 | 99 | return `The backport to \`${branch}\` failed. Please do this backport manually. 100 | 101 | \`\`\`bash 102 | # Switch to the target branch and update it 103 | git checkout ${branch} 104 | git pull origin ${branch} 105 | 106 | # Create the new backport branch 107 | git checkout -b ${target} 108 | 109 | # Cherry pick the change from the commit sha1 of the change against the default branch 110 | # This might cause conflicts, resolve them 111 | git cherry-pick ${commits.map(commit => commit.slice(0, 8)).join(' ')} 112 | 113 | # Push the cherry pick commit to the remote repository and open a pull request 114 | git push origin ${target} 115 | \`\`\` 116 | 117 | Error: ${error} 118 | 119 | ${LEARN_MORE}` 120 | } 121 | -------------------------------------------------------------------------------- /src/payloadUtils.spec.ts: -------------------------------------------------------------------------------- 1 | import { describe, expect, test } from 'vitest' 2 | import { extractBranchFromPayload, extractCommitsFromPayload } from './payloadUtils' 3 | 4 | describe('Extracts valid commits from payload', () => { 5 | const payloads = [ 6 | '/backport to stable28', 7 | '/backport! to stable28', 8 | '/backport 123456789 123456789 to stable28', 9 | '/backport! 123456789 123456789 to stable28', 10 | '/backport 0182735b7bb0ee7904f0622943afe689cdaf50d5 to stable28', 11 | '/backport! 0182735b7bb0ee7904f0622943afe689cdaf50d5 to stable28', 12 | '/backport to stable28 please', 13 | '/backport 0182735b7bb0ee7904f0622943afe689cdaf50d5 to stable28', 14 | ] 15 | 16 | const expectedCommits = [ 17 | [], 18 | [], 19 | ['123456789', '123456789'], 20 | ['123456789', '123456789'], 21 | ['0182735b7bb0ee7904f0622943afe689cdaf50d5'], 22 | ['0182735b7bb0ee7904f0622943afe689cdaf50d5'], 23 | [], 24 | ['0182735b7bb0ee7904f0622943afe689cdaf50d5'], 25 | ] 26 | 27 | payloads.forEach((payload, index) => { 28 | test(payload, () => { 29 | expect(extractCommitsFromPayload(payload)).toEqual(expectedCommits[index]) 30 | }) 31 | }) 32 | }) 33 | 34 | describe('Throws error for invalid commits in payload', () => { 35 | const payloads = [ 36 | '/backport 123 to stable28', 37 | '/backport! 123 to stable28', 38 | '/backport 123456789 123 to stable28', 39 | '/backport! 123456789 123 to stable28', 40 | '/backport 0182735b7bb0ee7904f0622943afe689cdaf50d5123465456 to stable28', 41 | '/backport! 0182735b7bb0ee7904f0622943afe689cdaf50d5123465456 to stable28', 42 | '/wrongcommand 123456789 123456789 to stable28', 43 | ] 44 | 45 | payloads.forEach(payload => { 46 | test(payload, () => { 47 | expect(() => extractCommitsFromPayload(payload)) 48 | .toThrow(`Failed to extract commits from payload: \`${payload}\``) 49 | }) 50 | }) 51 | }) 52 | 53 | describe('Extracts valid branch from payload', () => { 54 | const payloads = [ 55 | '/backport 123456789 to stable28', 56 | '/backport 123456789 to fix/123456/fix-something', 57 | '/backport 123456789 to fix-123456-fix-something', 58 | '/backport to stable28 please', 59 | '/backport 123456789 to stable28 please', 60 | ] 61 | 62 | const expectedBranches = [ 63 | 'stable28', 64 | 'fix/123456/fix-something', 65 | 'fix-123456-fix-something', 66 | 'stable28', 67 | 'stable28', 68 | ] 69 | 70 | payloads.forEach((payload, index) => { 71 | test(payload, () => { 72 | expect(extractBranchFromPayload(payload)).toEqual(expectedBranches[index]) 73 | }) 74 | }) 75 | }) 76 | 77 | describe('Throws error for invalid branch in payload', () => { 78 | const payloads = [ 79 | '/backport 123456789 to 123 456', 80 | '/backport 123456789 to', 81 | ] 82 | 83 | const expectedErrors = [ 84 | 'Branch name `123 456` is invalid', 85 | 'Branch name `` is invalid', 86 | ] 87 | 88 | payloads.forEach((payload, index) => { 89 | test(payload, () => { 90 | expect(() => extractBranchFromPayload(payload)) 91 | .toThrow(expectedErrors[index]) 92 | }) 93 | }) 94 | }) 95 | -------------------------------------------------------------------------------- /src/payloadUtils.ts: -------------------------------------------------------------------------------- 1 | import { BRANCH_REGEX, COMMAND_PREFIX, COMMIT_REGEX, TO_SEPARATOR } from './constants' 2 | 3 | /** 4 | * Extracts the commits from the payload. 5 | * @param payload The payload from the webhook. e.g. `/backport 5e83e97 to stable28` 6 | * @returns The list of commits. 7 | */ 8 | export const extractCommitsFromPayload = (payload: string): string[] => { 9 | try { 10 | const commitsChain = payload.split(TO_SEPARATOR)[0].slice(COMMAND_PREFIX.length).trim() 11 | 12 | // Split and remove the force flag if present 13 | const commits = commitsChain.split(' ').filter(str => !str.startsWith('!')) 14 | if (commitsChain !== '' && commits.some(commit => !COMMIT_REGEX.test(commit))) { 15 | throw new Error(`Invalid commit(s) found in payload: ${commitsChain}`) 16 | } 17 | 18 | return commits.filter(commit => COMMIT_REGEX.test(commit)) 19 | } catch (e) { 20 | throw new Error(`Failed to extract commits from payload: \`${payload}\``) 21 | } 22 | } 23 | 24 | export const extractBranchFromPayload = (payload: string): string => { 25 | const firstLine = payload.split('\n')[0] 26 | 27 | // Split the first line by the TO_SEPARATOR 28 | let branch = firstLine.split(TO_SEPARATOR)[1]?.trim?.() ?? '' 29 | 30 | // Ignore polite requests 31 | branch = branch.replace('please', '').trim() 32 | 33 | // Check if the branch matches the regex 34 | if (!BRANCH_REGEX.test(branch)) { 35 | throw new Error(`Branch name \`${branch}\` is invalid`) 36 | } 37 | return branch 38 | } 39 | 40 | export const isFriendly = (payload: string): boolean => { 41 | return payload.endsWith('please') 42 | } 43 | -------------------------------------------------------------------------------- /src/queue.ts: -------------------------------------------------------------------------------- 1 | import PQueue from 'p-queue' 2 | import { Task } from './constants.js' 3 | import { backport } from './backport.js' 4 | import { error } from './logUtils.js' 5 | 6 | let queue: PQueue 7 | 8 | export async function addToQueue(task: Task): Promise { 9 | if (!queue) { 10 | queue = new PQueue({ concurrency: 1 }) 11 | } 12 | 13 | try { 14 | await queue.add(async () => { 15 | await backport(task) 16 | }) 17 | } catch(e) { 18 | error(task, e) 19 | throw e 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@tsconfig/recommended", 3 | "include": ["src/**/*.ts"], 4 | "exclude": ["node_modules"], 5 | "compilerOptions": { 6 | "lib": ["ES2023"], 7 | "allowJs": true, 8 | "moduleResolution": "Node16", 9 | "module": "Node16", 10 | "target": "ES2022" 11 | }, 12 | } 13 | -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vitest/config' 2 | 3 | const exclude = ['cache/**', 'dist/**', 'node_modules/**', 'work/**'] 4 | 5 | export default defineConfig({ 6 | test: { 7 | globals: true, 8 | exclude, 9 | coverage: { 10 | include: ['src/**'], 11 | exclude, 12 | provider: 'istanbul', 13 | reporter: ['lcov', 'text'], 14 | }, 15 | }, 16 | }) 17 | --------------------------------------------------------------------------------