├── .nowignore ├── .gitignore ├── assets └── preview.png ├── .travis.yml ├── now-lambda.ts ├── test ├── fixtures │ ├── content_file.json │ └── pullrequests.opened.json ├── test-helper.ts └── index.test.ts ├── manifest.yml ├── jest.config.js ├── .env.example ├── src ├── index.ts ├── config.ts └── update.ts ├── now.json ├── .github └── dependabot.yml ├── tsconfig.json ├── package.json ├── CONTRIBUTING.md ├── CODE_OF_CONDUCT.md ├── README.md ├── app.yml └── LICENSE /.nowignore: -------------------------------------------------------------------------------- 1 | assets 2 | node_modules 3 | *.md 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | lib 3 | .env 4 | npm-debug.log 5 | /coverage -------------------------------------------------------------------------------- /assets/preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/s4heid/branch-switcher/HEAD/assets/preview.png -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - "13.7" 5 | notifications: 6 | disabled: true 7 | -------------------------------------------------------------------------------- /now-lambda.ts: -------------------------------------------------------------------------------- 1 | import { toLambda } from 'probot-serverless-now' 2 | import main from './src/index' 3 | 4 | export default toLambda(main as any) 5 | -------------------------------------------------------------------------------- /test/fixtures/content_file.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "file", 3 | "encoding": "base64", 4 | "name": "", 5 | "path": "", 6 | "content": "" 7 | } 8 | -------------------------------------------------------------------------------- /manifest.yml: -------------------------------------------------------------------------------- 1 | --- 2 | applications: 3 | - name: branch-switcher 4 | memory: 128M 5 | instances: 1 6 | random-route: true 7 | buildpack: nodejs_buildpack 8 | command: npm run-script start 9 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | roots: ['/src/', '/test/'], 3 | transform: { 4 | '^.+\\.tsx?$': 'ts-jest' 5 | }, 6 | testRegex: '(/__tests__/.*|\\.(test|spec))\\.[tj]sx?$', 7 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'] 8 | } 9 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # The ID of your GitHub App 2 | APP_ID= 3 | WEBHOOK_SECRET=development 4 | 5 | # Use `trace` to get verbose logging or `info` to show less 6 | LOG_LEVEL=debug 7 | 8 | # Go to https://smee.io/new set this to the URL that you are redirected to. 9 | WEBHOOK_PROXY_URL= 10 | -------------------------------------------------------------------------------- /test/fixtures/pullrequests.opened.json: -------------------------------------------------------------------------------- 1 | { 2 | "action": "reopened", 3 | "pull_request": { 4 | "number": 1, 5 | "user": { 6 | "login": "dpb587" 7 | }, 8 | "labels": [] 9 | }, 10 | "repository": { 11 | "name": "branch-switcher", 12 | "owner": { 13 | "login": "s4heid" 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Probot } from 'probot' 2 | import { update } from './update' 3 | 4 | export = (app: Probot) => { 5 | app.log.info('Branch Switcher is listening for events...') 6 | app.on([ 7 | 'pull_request.opened', 8 | 'pull_request.reopened', 9 | 'pull_request.edited', 10 | 'pull_request.labeled', 11 | 'pull_request.unlabeled' 12 | ], update) 13 | } 14 | -------------------------------------------------------------------------------- /now.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "branch-switcher", 3 | "version": 2, 4 | "alias": "branch-switcher.now.sh", 5 | "public": true, 6 | "env": { 7 | "APP_ID": "@app-id", 8 | "WEBHOOK_SECRET": "@webhook-secret", 9 | "PRIVATE_KEY": "@private-key-base64-encoded" 10 | }, 11 | "builds": [ 12 | { 13 | "src": "now-lambda.ts", 14 | "use": "@now/node" 15 | } 16 | ], 17 | "routes": [ 18 | { 19 | "src": "/.*", 20 | "dest": "now-lambda.ts" 21 | } 22 | ] 23 | } 24 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: npm 4 | directory: "/" 5 | schedule: 6 | interval: monthly 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | reviewers: 10 | - s4heid 11 | ignore: 12 | - dependency-name: probot 13 | versions: 14 | - 11.0.1 15 | - 11.0.5 16 | - dependency-name: "@typescript-eslint/parser" 17 | versions: 18 | - 4.11.1 19 | - 4.14.1 20 | - dependency-name: nock 21 | versions: 22 | - 13.0.5 23 | - 13.0.7 24 | - dependency-name: "@types/node" 25 | versions: 26 | - 14.14.17 27 | - 14.14.22 28 | - dependency-name: "@types/jest" 29 | versions: 30 | - 26.0.19 31 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": false, 4 | "lib": [ 5 | "es2015", 6 | "es2017" 7 | ], 8 | "module": "commonjs", 9 | "moduleResolution": "node", 10 | "target": "es5", 11 | "noImplicitReturns": true, 12 | "noFallthroughCasesInSwitch": true, 13 | "noUnusedLocals": false, 14 | "pretty": true, 15 | "strict": true, 16 | "sourceMap": true, 17 | "outDir": "./lib", 18 | "skipLibCheck": true, 19 | "noImplicitAny": true, 20 | "esModuleInterop": true, 21 | "declaration": true, 22 | "resolveJsonModule": true 23 | }, 24 | "include": [ 25 | "index.d.ts", 26 | "src/**/*" 27 | ], 28 | "compileOnSave": false 29 | } 30 | -------------------------------------------------------------------------------- /test/test-helper.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock' 2 | 3 | export const endpoint = 'https://api.github.com' 4 | 5 | export function nockEmptyConfig () { 6 | nock(endpoint) 7 | .persist() 8 | .get('/repos/s4heid/branch-switcher/contents/.github%2Fbranch-switcher.yml') 9 | .reply(404) 10 | .get('/repos/s4heid/.github/contents/.github%2Fbranch-switcher.yml') 11 | .reply(404) 12 | .get('/repos/s4heid/branch-switcher/contents/.github%2Fbranch-switcher.yaml') 13 | .reply(404) 14 | .get('/repos/s4heid/.github/contents/.github%2Fbranch-switcher.yml') 15 | .reply(404) 16 | } 17 | 18 | export function nockUserConfig (config: string) { 19 | nock('https://api.github.com') 20 | .get('/repos/s4heid/branch-switcher/contents/.github%2Fbranch-switcher.yml') 21 | .reply(404) 22 | .get('/repos/s4heid/.github/contents/.github%2Fbranch-switcher.yml') 23 | .reply(200, config) 24 | } 25 | -------------------------------------------------------------------------------- /src/config.ts: -------------------------------------------------------------------------------- 1 | import { Context } from 'probot' 2 | 3 | interface ExcludeConfig { 4 | branch: string 5 | label: string 6 | } 7 | 8 | interface Config { 9 | preferredBranch: string 10 | exclude: Array 11 | switchComment: string 12 | } 13 | 14 | const defaultConfig: Config = { 15 | preferredBranch: 'develop', 16 | exclude: [], 17 | switchComment: 'Hello @{{author}}. The base branch of this pull request has been updated to the `{{preferredBranch}}` branch. Please revisit the changes and make sure that there are no conflicts with the new base branch. Thank you for your contributions.' 18 | } 19 | const configFilename: string = 'branch-switcher.yml' 20 | const configPath: string = `.github/${configFilename}` 21 | 22 | class ConfigNotFoundError extends Error { 23 | constructor ( 24 | public readonly filePath: string 25 | ) { 26 | super(`Config file '${filePath}' not found`) 27 | Object.setPrototypeOf(this, new.target.prototype) 28 | } 29 | } 30 | 31 | export async function loadConfig (context: Context) { 32 | const config = await context.config('branch-switcher.yml', defaultConfig) 33 | if (!config) { 34 | context.log.error('Failed to load configuration configuration') 35 | throw new ConfigNotFoundError(configPath) 36 | } 37 | context.log.debug(config, `Loaded config ${JSON.stringify(config)} from ${configPath}`) 38 | return config as Config 39 | } 40 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "branch-switcher", 3 | "version": "1.0.0", 4 | "contributors": [ 5 | "Danny Berger", 6 | "Sebastian Heid" 7 | ], 8 | "description": "A branch switcher app.", 9 | "license": "Apache-2.0", 10 | "repository": "https://github.com/s4heid/branch-switcher.git", 11 | "homepage": "https://github.com/s4heid/branch-switcher", 12 | "bugs": "https://github.com/s4heid/branch-switcher/issues", 13 | "keywords": [ 14 | "probot", 15 | "github", 16 | "probot-app" 17 | ], 18 | "scripts": { 19 | "build": "tsc -p tsconfig.json", 20 | "dev": "nodemon --exec \"npm start\"", 21 | "start": "probot run ./lib/index.js", 22 | "lint": "standard **/*.ts --fix", 23 | "test": "jest && standard **/*.ts", 24 | "test:watch": "jest --watch --notify --notifyMode=change --coverage" 25 | }, 26 | "dependencies": { 27 | "probot": "^11.4.1", 28 | "probot-serverless-now": "^2.1.2" 29 | }, 30 | "devDependencies": { 31 | "@types/jest": "^26.0.19", 32 | "@types/nock": "^11.1.0", 33 | "@types/node": "^18.11.10", 34 | "@typescript-eslint/parser": "^4.32.0", 35 | "@vercel/ncc": "^0.24", 36 | "acorn": "^8.6.0", 37 | "eslint-plugin-typescript": "^0.14.0", 38 | "jest": "^26.6.3", 39 | "nock": "^13.1.0", 40 | "nodemon": "^2.0.13", 41 | "smee-client": "^1.2.2", 42 | "standard": "^16.0.4", 43 | "ts-jest": "^26.4.4", 44 | "typescript": "^4.3.5" 45 | }, 46 | "engines": { 47 | "node": ">= 10.13.0" 48 | }, 49 | "standard": { 50 | "parser": "@typescript-eslint/parser", 51 | "env": [ 52 | "jest" 53 | ], 54 | "plugins": [ 55 | "typescript" 56 | ] 57 | }, 58 | "jest": { 59 | "testEnvironment": "node" 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/update.ts: -------------------------------------------------------------------------------- 1 | import { loadConfig } from './config' 2 | 3 | export async function update (context: import('probot').Context) { 4 | const cfg = await loadConfig(context) 5 | const preferredBranch = cfg.preferredBranch 6 | const messageText = cfg.switchComment 7 | const exclude = cfg.exclude 8 | const actualBranch = context.payload.pull_request.base.ref 9 | const actualLabels = context.payload.pull_request.labels.map((c: { name: string }) => c.name) 10 | 11 | const excludeBranches = (exclude || []).filter(c => c.branch).map(c => c.branch) 12 | const excludeLabels = (exclude || []).filter(c => c.label).map(c => c.label) 13 | 14 | if (actualBranch === preferredBranch) { 15 | context.log(`skipping (branch ${actualBranch} is already preferred)`) 16 | return 17 | } 18 | 19 | if (excludeBranches.some((rule) => new RegExp(`^${rule.split('*').join('.*')}$`).test(actualBranch))) { 20 | context.log(`skipping (branch ${actualBranch} is excluded)`) 21 | return 22 | } 23 | 24 | const excludedLabels = actualLabels.filter((value: string) => excludeLabels.includes(value)) 25 | if (excludedLabels.length > 0) { 26 | context.log(`skipping (labels ${excludedLabels} are excluded)`) 27 | return 28 | } 29 | 30 | context.log(`changing branch (to ${preferredBranch}; from ${actualBranch})`) 31 | const updateBranch = context.repo({ 32 | pull_number: context.payload.pull_request.number, 33 | base: preferredBranch 34 | }) 35 | await context.octokit.pulls.update(updateBranch) 36 | 37 | const interpolatedMsg = messageText.replace( 38 | /{{(?:author)}}/, 39 | context.payload.pull_request.user.login 40 | ).replace( 41 | /{{(?:preferredBranch)}}/, 42 | preferredBranch 43 | ) 44 | context.log(`adding comment (${interpolatedMsg})`) 45 | 46 | const pullComment = context.repo({ 47 | issue_number: context.payload.pull_request.number, 48 | body: interpolatedMsg 49 | }) 50 | 51 | try { 52 | await context.octokit.issues.createComment(pullComment) 53 | } catch (err) { 54 | err.message = `There was an issue commenting on PR #${pullComment.issue_number} \n\n${err.message}` 55 | context.log.error(err) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 sebastian.heid@sap.com. 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # branch-switcher 2 | 3 | [![Build Status](https://travis-ci.org/s4heid/branch-switcher.svg?branch=master)](https://travis-ci.org/s4heid/branch-switcher) 4 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 5 | [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com) 6 | 7 | A GitHub App built with [Probot](https://github.com/probot/probot) that automatically 8 | updates the base ref of a pull request if it has been opened against a non-preferred 9 | branch. 10 | 11 | 12 | ## How it works 13 | 14 | In projects where the default branch is not master, pull requests are often opened against a wrong branch. Typically, maintainers of the project need to reach out to the authors and ask them to change the base branch as most bigger projects have automated tests configured against the default branch. 15 | 16 | The intent of this GitHub app is to support maintainers by automatically changing the base branch of pull requests to the default branch if applicable. The app listens to a set of [webhooks](https://developer.github.com/v3/activity/events/types/#pullrequestevent): 17 | 18 | - `pull_request.opened`, 19 | - `pull_request.reopened`, 20 | - `pull_request.edited`, 21 | - `pull_request.labeled`, 22 | - `pull_request.unlabeled`, 23 | 24 | which triggers 25 | 26 | - a check whether the base branch of the pull request matches the preferred branch and changes it if applicable, 27 | - comments on the pull request and informs the author about the changes being made. 28 | 29 | ![](assets/preview.png) 30 | 31 | 32 | ## Installation 33 | 34 | 1. [Install the GitHub App](https://github.com/apps/branch-switcher) for the intended repositories. 35 | 1. Create a `.github/branch-switcher.yml` file in the root of the intended repositories where 36 | branch-switcher has been installed. This configuration file is optional and overrides any of the default 37 | settings. 38 | 39 | 40 | ## Configuration 41 | 42 | The following properties are currently supported: 43 | 44 | * `preferredBranch` *(string)* - name of the preferred branch against which the 45 | pull request should be opened. Default: develop. 46 | * `switchComment` *(string)* - content of the message indicating that the base 47 | has been updated to the preferred branch. `{{author}}` can be used as a placeholder 48 | which interpolates to the pull request author and `{{preferredBranch}}` analogously. 49 | * `exclude` *(Array)* - list of all branches and labels that should be ignored. 50 | By default, all branches are considered and no labels are excluded. 51 | - `branch` *(string)* - name of the branch that should be ignored. 52 | - `label` *(string)* - name of the label that should be ignored. 53 | 54 | **Example** `.github/branch-switcher.yml`: 55 | 56 | ```yaml 57 | exclude: 58 | - branch: do-nothing 59 | - branch: dont-touch-* 60 | - label: ignore-me 61 | switchComment: > 62 | Hey @{{author}}, the base branch of your pull request has been changed 63 | to {{preferredBranch}}. Have a nice day! :wave: 64 | ``` 65 | 66 | Above config does not touch the base branch if there is a label `ignore-me` attached 67 | on the pull request and it also does not switch if the base branch is either called 68 | `do-nothing` or every branch matching the wildcard `dont-touch-*`. 69 | 70 | 71 | ## Development 72 | 73 | 1. Follow the [docs for deployment](https://probot.github.io/docs/deployment) and 74 | set the following **Permissions & events** for the GitHub App: 75 | - Pull requests - **Read & Write** 76 | - [x] Check the box for **Pull request review comment** events 77 | - Repository metadata - **Read-only** 78 | - Single File - **Read-only** 79 | - Path: `.github/branch-switcher.yml` 80 | 2. Clone the repo: 81 | ```sh 82 | git clone git@github.com:s4heid/branch-switcher.git 83 | ``` 84 | 3. Copy [.env.example](.env.example) to `.env` and set the right environment variables as described in the official [probot docs](https://probot.github.io/docs/configuration) 85 | 4. Install app dependencies and run the app: 86 | ```sh 87 | # Install dependencies 88 | npm install 89 | 90 | # Run typescript and run the bot 91 | npm run build && npm start 92 | ``` 93 | 94 | 95 | ## Contributing 96 | 97 | If you have suggestions for how branch-switcher could be improved, or want to report a bug, open an issue! We'd love all and any contributions. 98 | 99 | For more, check out the [Contributing Guide](CONTRIBUTING.md). 100 | 101 | 102 | ## License 103 | 104 | [Apache 2.0](LICENSE) 105 | -------------------------------------------------------------------------------- /app.yml: -------------------------------------------------------------------------------- 1 | # This is a GitHub App Manifest. These settings will be used by default when 2 | # initially configuring your GitHub App. 3 | # 4 | # NOTE: changing this file will not update your GitHub App settings. 5 | # You must visit github.com/settings/apps/your-app-name to edit them. 6 | # 7 | # Read more about configuring your GitHub App: 8 | # https://probot.github.io/docs/development/#configuring-a-github-app 9 | # 10 | # Read more about GitHub App Manifests: 11 | # https://developer.github.com/apps/building-github-apps/creating-github-apps-from-a-manifest/ 12 | 13 | # The list of events the GitHub App subscribes to. 14 | # Uncomment the event names below to enable them. 15 | default_events: 16 | # - check_run 17 | # - check_suite 18 | # - commit_comment 19 | # - create 20 | # - delete 21 | # - deployment 22 | # - deployment_status 23 | # - fork 24 | # - gollum 25 | # - issue_comment 26 | # - issues 27 | # - label 28 | # - milestone 29 | # - member 30 | # - membership 31 | # - org_block 32 | # - organization 33 | # - page_build 34 | # - project 35 | # - project_card 36 | # - project_column 37 | # - public 38 | - pull_request 39 | # - pull_request_review 40 | # - pull_request_review_comment 41 | # - push 42 | # - release 43 | # - repository 44 | # - repository_import 45 | # - status 46 | # - team 47 | # - team_add 48 | # - watch 49 | 50 | # The set of permissions needed by the GitHub App. The format of the object uses 51 | # the permission name for the key (for example, issues) and the access type for 52 | # the value (for example, write). 53 | # Valid values are `read`, `write`, and `none` 54 | default_permissions: 55 | # Repository creation, deletion, settings, teams, and collaborators. 56 | # https://developer.github.com/v3/apps/permissions/#permission-on-administration 57 | # administration: read 58 | 59 | # Checks on code. 60 | # https://developer.github.com/v3/apps/permissions/#permission-on-checks 61 | # checks: read 62 | 63 | # Repository contents, commits, branches, downloads, releases, and merges. 64 | # https://developer.github.com/v3/apps/permissions/#permission-on-contents 65 | # contents: read 66 | 67 | # Deployments and deployment statuses. 68 | # https://developer.github.com/v3/apps/permissions/#permission-on-deployments 69 | # deployments: read 70 | 71 | # Issues and related comments, assignees, labels, and milestones. 72 | # https://developer.github.com/v3/apps/permissions/#permission-on-issues 73 | # issues: write 74 | 75 | # Search repositories, list collaborators, and access repository metadata. 76 | # https://developer.github.com/v3/apps/permissions/#metadata-permissions 77 | metadata: read 78 | 79 | # Retrieve Pages statuses, configuration, and builds, as well as create new builds. 80 | # https://developer.github.com/v3/apps/permissions/#permission-on-pages 81 | # pages: read 82 | 83 | # Pull requests and related comments, assignees, labels, milestones, and merges. 84 | # https://developer.github.com/v3/apps/permissions/#permission-on-pull-requests 85 | pull_requests: write 86 | 87 | # Manage the post-receive hooks for a repository. 88 | # https://developer.github.com/v3/apps/permissions/#permission-on-repository-hooks 89 | # repository_hooks: read 90 | 91 | # Manage repository projects, columns, and cards. 92 | # https://developer.github.com/v3/apps/permissions/#permission-on-repository-projects 93 | # repository_projects: read 94 | 95 | # Retrieve security vulnerability alerts. 96 | # https://developer.github.com/v4/object/repositoryvulnerabilityalert/ 97 | # vulnerability_alerts: read 98 | 99 | # Commit statuses. 100 | # https://developer.github.com/v3/apps/permissions/#permission-on-statuses 101 | # statuses: read 102 | 103 | # Organization members and teams. 104 | # https://developer.github.com/v3/apps/permissions/#permission-on-members 105 | # members: read 106 | 107 | # View and manage users blocked by the organization. 108 | # https://developer.github.com/v3/apps/permissions/#permission-on-organization-user-blocking 109 | # organization_user_blocking: read 110 | 111 | # Manage organization projects, columns, and cards. 112 | # https://developer.github.com/v3/apps/permissions/#permission-on-organization-projects 113 | # organization_projects: read 114 | 115 | # Manage team discussions and related comments. 116 | # https://developer.github.com/v3/apps/permissions/#permission-on-team-discussions 117 | # team_discussions: read 118 | 119 | # Manage the post-receive hooks for an organization. 120 | # https://developer.github.com/v3/apps/permissions/#permission-on-organization-hooks 121 | # organization_hooks: read 122 | 123 | # Get notified of, and update, content references. 124 | # https://developer.github.com/v3/apps/permissions/ 125 | # organization_administration: read 126 | 127 | 128 | # The name of the GitHub App. Defaults to the name specified in package.json 129 | name: branch-switcher 130 | 131 | # The homepage of your GitHub App. 132 | url: https://github.com/apps/branch-switcher 133 | 134 | # A description of the GitHub App. 135 | +description: a GitHub bot that switches the base branch of pull requests to the preferred branch 136 | 137 | # Set to true when your GitHub App is available to the public or false when it is only accessible to the owner of the app. 138 | # Default: true 139 | # public: false 140 | -------------------------------------------------------------------------------- /test/index.test.ts: -------------------------------------------------------------------------------- 1 | import nock from 'nock' 2 | import { Probot, ProbotOctokit } from 'probot' 3 | import branchSwitcher from '../src' 4 | import * as helper from './test-helper' 5 | import defaultPayload from './fixtures/pullrequests.opened.json' 6 | import contentFile from './fixtures/content_file.json' 7 | 8 | const defaultComment = { body: 'Hello @dpb587. The base branch of this pull request has been updated to the `develop` branch. Please revisit the changes and make sure that there are no conflicts with the new base branch. Thank you for your contributions.' } 9 | 10 | describe('Branch switcher', () => { 11 | let probot: any 12 | let payload: any 13 | 14 | beforeEach(() => { 15 | nock.disableNetConnect() 16 | probot = new Probot({ 17 | appId: 123, 18 | githubToken: 'test-token', 19 | Octokit: ProbotOctokit.defaults({ 20 | retry: { enabled: false }, 21 | throttle: { enabled: false } 22 | }) 23 | }) 24 | probot.load(branchSwitcher) 25 | }) 26 | 27 | describe('opened against non-preferred branch', () => { 28 | beforeEach(() => { 29 | payload = defaultPayload 30 | payload.pull_request.base = { ref: 'master' } 31 | }) 32 | 33 | it('can comment on open pull requests', async (done) => { 34 | nock(helper.endpoint) 35 | .patch('/repos/s4heid/branch-switcher/pulls/1') 36 | .reply(200) 37 | .post('/repos/s4heid/branch-switcher/issues/1/comments', (body: any) => { 38 | done(expect(body).toMatchObject(defaultComment)) 39 | return true 40 | }) 41 | .reply(200) 42 | 43 | helper.nockEmptyConfig() 44 | 45 | await probot.receive({ name: 'pull_request', payload }) 46 | }) 47 | 48 | it('can switch the base to the preferred branch', async (done) => { 49 | helper.nockEmptyConfig() 50 | 51 | nock(helper.endpoint) 52 | .patch('/repos/s4heid/branch-switcher/pulls/1', (body: any) => { 53 | expect(body).toMatchObject({ base: 'develop' }) 54 | return true 55 | }) 56 | .reply(200) 57 | 58 | nock(helper.endpoint) 59 | .post('/repos/s4heid/branch-switcher/issues/1/comments', (body: any) => { 60 | done(expect(body.body).toEqual(expect.stringContaining('The base'))) 61 | return true 62 | }) 63 | .reply(200) 64 | 65 | await probot.receive({ name: 'pull_request', payload }) 66 | }) 67 | 68 | describe('when custom config exists', () => { 69 | beforeEach(() => { 70 | contentFile.name = 'branch-switcher.yml' 71 | contentFile.path = '.github/branch-switcher.yml' 72 | }) 73 | 74 | it('can customize message of the comment', async (done) => { 75 | helper.nockUserConfig('switchComment: something') 76 | 77 | nock(helper.endpoint) 78 | .patch('/repos/s4heid/branch-switcher/pulls/1', (body: any) => { 79 | expect(body).toMatchObject({ base: 'develop' }) 80 | return true 81 | }) 82 | .reply(200) 83 | 84 | .post('/repos/s4heid/branch-switcher/issues/1/comments', (body: any) => { 85 | done(expect(body.body).toEqual(expect.stringContaining('something'))) 86 | return true 87 | }) 88 | .reply(200) 89 | 90 | await probot.receive({ name: 'pull_request', payload }) 91 | }) 92 | 93 | it('can interpolate variables from custom config into the comment', async (done) => { 94 | payload.pull_request.user.login = 'johndoe' 95 | 96 | helper.nockUserConfig(`preferredBranch: my-branch 97 | switchComment: "@{{author}}, base branch is now {{preferredBranch}}" 98 | `) 99 | 100 | nock(helper.endpoint) 101 | .patch('/repos/s4heid/branch-switcher/pulls/1', (body: any) => { 102 | expect(body).toMatchObject({ base: 'my-branch' }) 103 | return true 104 | }) 105 | .reply(200) 106 | 107 | .post('/repos/s4heid/branch-switcher/issues/1/comments', (body: any) => { 108 | done(expect(body.body).toEqual(expect.stringContaining('@johndoe, base branch is now my-branch'))) 109 | return true 110 | }) 111 | .reply(200) 112 | 113 | await probot.receive({ name: 'pull_request', payload }) 114 | }) 115 | 116 | it('respects exclude properties', async () => { 117 | payload.pull_request.base = { ref: 'dont-switch' } 118 | 119 | helper.nockUserConfig('exclude: [branch: dont-*, branch: really-dont-switch]') 120 | 121 | await probot.receive({ name: 'pull_request', payload }) 122 | }) 123 | 124 | it('respects exclude label properties', async () => { 125 | payload.pull_request.labels = [{ name: 'ignore' }] 126 | 127 | helper.nockUserConfig('exclude: [label: ignore]') 128 | 129 | await probot.receive({ name: 'pull_request', payload }) 130 | }) 131 | }) 132 | }) 133 | 134 | describe('opened against the preferred branch', () => { 135 | beforeEach(() => { 136 | payload = defaultPayload 137 | payload.pull_request.base = { ref: 'develop' } 138 | }) 139 | 140 | it('does not comment', async () => { 141 | helper.nockEmptyConfig() 142 | 143 | await probot.receive({ name: 'pull_request', payload }) 144 | }) 145 | }) 146 | 147 | afterEach(() => { 148 | nock.cleanAll() 149 | nock.enableNetConnect() 150 | }) 151 | }) 152 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "{}" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2019 Sebastian Heid 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------