#!/usr/bin/env node /** * This script is used for cherry-pick commits for web-components repo. * To run this script: * 1.collect committed-PRs marked with target/ labels * 2.cherry-pick the commit to the target branches * 3.label the original commit PR with cherry-picked- * Exception handling: * - works for closed and merged PRs * - Commit PR labelled with {cherry-picked} or {need to pick manually} will be ignored. * - if cherry-pick cannot be done, the original PR will be labelled with need to pick manually */ import https from 'https'; import { exec as execCallback } from 'node:child_process'; import { promisify } from 'node:util'; const exec = promisify(execCallback); const arrPR = []; const arrTitle = []; const arrURL = []; const arrSHA = []; const arrBranch = []; const arrUser = []; const arrMergedBy = []; const arrBody = []; const repo = 'vaadin/web-components'; const token = process.env['GITHUB_TOKEN']; if (!token) { console.log(`GITHUB_TOKEN is not set, skipping PR creation`); process.exit(1); } async function getAllCommits() { const url = `https://api.github.com/repos/${repo}/pulls?state=closed&sort=updated&direction=desc&per_page=100`; try { const res = await fetch(url, { headers: { 'User-Agent': 'Vaadin Cherry Pick', Authorization: `token ${token}`, 'Content-Type': 'application/json', }, }); let data = await res.json(); data = data.filter((da) => da.labels.length > 0 && da.merged_at !== null); if (data.length === 0) { console.log('No commits needs to be picked.'); process.exit(0); } return data; } catch (error) { console.error(`Cannot get the commits. ${error}`); process.exit(1); } } async function getCommit(commitURL) { try { const options = { headers: { 'User-Agent': 'Vaadin Cherry Pick', Authorization: `token ${token}`, 'Content-Type': 'application/json', }, }; return await fetch(commitURL, options).then((res) => res.json()); } catch (error) { console.error(`Cannot get the commit. ${error}`); process.exit(1); } } async function filterCommits(commits) { for (const commit of commits) { for (const label of commit.labels) { let target = false; let picked = false; let branch; let mergedLabel; let manualLabel; if (label.name.includes('target/')) { target = true; branch = /target\/(.*)/u.exec(label.name); mergedLabel = `cherry-picked-${branch[1]}`; manualLabel = `need to pick manually ${branch[1]}`; commit.labels.forEach((la) => { if (la.name === mergedLabel || la.name === manualLabel) { picked = true; } }); } if (target === true && picked === false) { const singleCommit = await getCommit(commit.url); console.log( commit.number, commit.user.login, commit.url, commit.merge_commit_sha, branch[1], singleCommit.merged_by.login, ); arrPR.push(commit.number); arrSHA.push(commit.merge_commit_sha); arrURL.push(commit.url); arrBranch.push(branch[1]); arrTitle.push(`${commit.title} (#${commit.number}) (CP: ${branch[1]})`); arrUser.push(`@${commit.user.login}`); arrMergedBy.push(`@${singleCommit.merged_by.login}`); arrBody.push(singleCommit.body || ''); } } } } async function labelCommit(url, label) { const issueURL = `${url.replace('pulls', 'issues')}/labels`; await fetch(issueURL, { method: 'POST', headers: { 'User-Agent': 'Vaadin Cherry Pick', Authorization: `token ${token}`, }, body: JSON.stringify({ labels: [label] }), }); } async function postComment(url, userName, mergedBy, branch, message) { const issueURL = `${url.replace('pulls', 'issues')}/comments`; await fetch(issueURL, { method: 'POST', headers: { 'User-Agent': 'Vaadin Cherry Pick', Authorization: `token ${token}`, }, body: JSON.stringify({ body: `Hi ${userName} and ${mergedBy}, when i performed cherry-pick to this commit to ${branch}, i have encountered the following issue. Can you take a look and pick it manually?\n Error Message:\n ${message}`, }), }); } function buildCherryPickBody(originalPRNumber, originalBody, targetBranch) { const quotedBody = (originalBody || '_No description provided in the original PR._') .split('\n') .map((line) => `> ${line}`) .join('\n'); return ` This PR cherry-picks changes from the original PR #${originalPRNumber} to branch ${targetBranch}. --- #### Original PR description ${quotedBody} `.trim(); } function createPR(title, head, base, body) { return new Promise((resolve) => { const content = JSON.stringify({ title, head, base, body }, null, 1); const req = https.request( { method: 'POST', hostname: 'api.github.com', path: `/repos/${repo}/pulls`, headers: { Authorization: `token ${token}`, 'User-Agent': 'Vaadin Cherry Pick', 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(content), }, }, (res) => { let responseBody = ''; res.on('data', (data) => { responseBody += data; }); res.on('end', () => { resolve({ status: res.statusCode, body: responseBody }); }); }, ); req.write(content); req.end(); }).then(({ status, body }) => { if (status >= 300) { console.error(`Failed to create PR '${title}' (HTTP ${status}): ${body}`); return; } const resp = JSON.parse(body); console.log(`Created PR '${title}' ${resp.html_url || resp.url}`); }); } async function cherryPickCommits() { for (let i = arrPR.length - 1; i >= 0; i--) { const branchName = `cherry-pick-${arrPR[i]}-to-${arrBranch[i]}-${Date.now()}`; await exec('git checkout main'); await exec('git pull'); await exec(`git checkout ${arrBranch[i]}`); await exec(`git reset --hard origin/${arrBranch[i]}`); try { await exec(`git checkout -b ${branchName}`); } catch (err) { console.error(`Cannot Create Branch, error : ${err}`); process.exit(1); } try { await exec(`git cherry-pick ${arrSHA[i]}`); } catch (err) { console.error(`Cannot Pick the Commit:${arrSHA[i]} to ${arrBranch[i]}, error :${err}`); await labelCommit(arrURL[i], `need to pick manually ${arrBranch[i]}`); await postComment(arrURL[i], arrUser[i], arrMergedBy[i], arrBranch[i], err); await exec(`git cherry-pick --abort`); await exec(`git checkout main`); await exec(`git branch -D ${branchName}`); continue; } await exec(`git push origin HEAD:${branchName}`); try { await createPR(arrTitle[i], branchName, arrBranch[i], buildCherryPickBody(arrPR[i], arrBody[i], arrBranch[i])); } catch (err) { console.error(`Cannot create PR from ${branchName}, error : ${err}`); await labelCommit(arrURL[i], `cannot create PR from ${branchName}`); await postComment(arrURL[i], arrUser[i], arrMergedBy[i], arrBranch[i], err); continue; } await exec(`git checkout main`); await exec(`git branch -D ${branchName}`); await labelCommit(arrURL[i], `cherry-picked-${arrBranch[i]}`); } } async function main() { const allCommits = await getAllCommits(); await filterCommits(allCommits); await cherryPickCommits(); } main();