{"size": 1614, "ext": "js", "max_stars_repo_path": "src/backport.js", "max_stars_repo_name": "mapbox/github-release-tools", "max_stars_repo_stars_event_min_datetime": "2018-06-14T19:57:42.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-20T19:54:40.000Z", "max_issues_repo_path": "src/backport.js", "max_issues_repo_name": "matterport/github-release-tools", "max_issues_repo_issues_event_min_datetime": "2018-05-09T02:26:46.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-25T20:29:25.000Z", "max_forks_repo_path": "src/backport.js", "max_forks_repo_name": "matterport/github-release-tools", "max_forks_repo_forks_event_min_datetime": "2018-09-13T02:35:48.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-04T20:28:04.000Z"}
{"max_stars_count": 16, "max_issues_count": 23, "max_forks_count": 5, "avg_line_length": 36.6818181818, "max_line_length": 135, "alphanum_fraction": 0.6177199504}
const parse = require('parse-github-url');
const octokit = require('@octokit/rest')();
const {execSync} = require('child_process');

module.exports = async function ({change, branch}) {
    octokit.authenticate({
        type: 'token',
        token: process.env.GITHUB_TOKEN
    });

    const {owner, name: repo, filepath: number} = parse(change);

    const prData = (await octokit.pullRequests.get({owner, repo, number})).data;
    const prReviews = (await octokit.pullRequests.getReviews({owner, repo, number})).data;
    const prPatch = (await octokit.pullRequests.get({owner, repo, number, headers: {accept: 'application/vnd.github.v3.patch'}})).data;
    const prSlug = branch.replace(/^release-/, '');
    const prBranch = `backport-${prSlug}-${number}-${prData.head.ref}`;

    execSync(`git branch --no-track ${prBranch} origin/${branch}`);
    execSync(`git checkout ${prBranch}`);
    execSync(`git am`, {input: prPatch});
    execSync(`git push origin --set-upstream ${prBranch}`);

    const result = (await octokit.pullRequests.create({
        owner,
        repo,
        title: `${prSlug} backport: ${prData.title}`,
        head: prBranch,
        base: branch,
        body: `Backports #${number} to [\`${branch}\`](https://github.com/${owner}/${repo}/tree/${branch})\n\n---\n\n${prData.body}`
    })).data;

    await octokit.pullRequests.createReviewRequest({
        owner,
        repo,
        number: result.number,
        reviewers: prReviews
            .filter(({state}) => state === 'APPROVED')
            .map(({user}) => user.login)
    });

    console.log(result.html_url);
};
