Updating PRs when deployed

I wanted to add a comment, on all the PRs in a changeset, e.g. when deployed to a specific environment.

Assuming you have a commit range, it’s relatively straightforward to get the list of commits between them:

const res = await octokit.request({
        method: 'GET',
        url: '/repos/{owner}/{repo}/compare/{basehead}',
        owner: 'foo',
        repo: 'bar',
        basehead: `${process.env.GIT_PREVIOUS_SUCCESSFUL_COMMIT}...${process.env.GIT_COMMIT}`
    });

Then, for each commit, you can search for a PR containing it:

    const commits = res.data.commits.map(c => c.sha);
    const results = await Promise.all(commits.map(q => {
        return octokit.request({
            method: 'GET',
            url: '/search/issues',
            owner: 'foo',
            repo: 'bar',
            q,
        })
    }));

Assuming you only want one comment per PR, you can use a Set to get a distinct list of numbers:

    const prs = new Set();
    results.forEach(r => {
        if (r.data.items.length) {
            prs.add(r.data.items[0].number);
        }
    });
    const prList = Array.from(prs.keys());

And finally add a comment on each PR:

 await Promise.all(prList.map(pr => {
        return octokit.request({
            method: 'POST',
            url: '/repos/{owner}/{repo}/issues/{issue_number}/comments',
            owner: 'foo',
            repo: 'bar',
            issue_number: pr,
            body: `something something: ${process.env.BUILD_URL}`
        });
    }));

Or, if you’re feeling really brave, you can do the whole thing in one line of bash!

curl -s -u "$GH_USER:$GH_TOKEN" -H "Accept: application/vnd.github.v3+json" "https://api.github.com/repos/foo/bar/compare/$BASE_COMMIT...$HEAD_COMMIT" \
    | jq '.commits[] | .sha' \
    | xargs -I '{}' sh -c 'curl -s -u "$GH_USER:$GH_TOKEN" -H "Accept: application/vnd.github.v3+json" "https://api.github.com/search/issues?q={}" \
    | jq '\''.items[0] | .number'\''' \
    | sort \
    | uniq \
    | xargs -I '{}' sh -c 'curl -s -u "$GH_USER:$GH_TOKEN" -H "Accept: application/vnd.github.v3+json" "https://api.github.com/repos/foo/bar/issues/{}/comments" -d "{\"body\":\"something something: $BUILD_URL\"}" > /dev/null'