githubgithub-apipull-requestoctokit

Find a string in a GitHub Pull Request


I'd like to build a bot to let you know if a certain string, like DONT_MERGE_ME appears in a GitHub Pull Request, so I can block the commit with a failed check and add a helpful comment for the developer.

Let's say you had committed code like the follow, that you don't want to accidentally merge with your PR (e.g. you're hacking around).

const bar = 'some-hack-value'; // DONT_MERGE_ME

Given the PR id, I'd like to figure out if the PR still has the string DONT_MERGE_ME in it. However,

Given the above limitations, it looks like the only way to figure this out, for a given PR id and commit, would be to find all commits in the PR up to this commit, download the diffs, and sum them up.

Is there a simpler way to do this with the GitHub API?


Solution

  • The approach I would recommend is subscribe to the pull_request event. If payload.action is either opened or synchronize, load the diff of the pull request and look for the string in all lines that have been changed.

    You can preview the diff response for a pull request by adding .diff to any pull request URL, e.g. https://patch-diff.githubusercontent.com/raw/gr2m/sandbox/pull/194.diff

    Find the lines starting with a + and look for your string in them

    If you use the JavaScript octokit package, you can load a pull request like this

    const { data: diff } = octokit.rest.pulls.get({ owner, repo, pull_number, mediaType: { format: "diff }})
    

    Also check out the TODO GitHub App, its source is Open Source, too