android-merge.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // SPDX-FileCopyrightText: 2023 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. // Note: This is a GitHub Actions script
  4. // It is not meant to be executed directly on your machine without modifications
  5. const fs = require("fs");
  6. // which label to check for changes
  7. const CHANGE_LABEL = 'android-merge';
  8. // how far back in time should we consider the changes are "recent"? (default: 24 hours)
  9. const DETECTION_TIME_FRAME = (parseInt(process.env.DETECTION_TIME_FRAME)) || (24 * 3600 * 1000);
  10. async function checkBaseChanges(github, context) {
  11. // query the commit date of the latest commit on this branch
  12. const query = `query($owner:String!, $name:String!, $ref:String!) {
  13. repository(name:$name, owner:$owner) {
  14. ref(qualifiedName:$ref) {
  15. target {
  16. ... on Commit { id pushedDate oid }
  17. }
  18. }
  19. }
  20. }`;
  21. const variables = {
  22. owner: context.repo.owner,
  23. name: context.repo.repo,
  24. ref: 'refs/heads/master',
  25. };
  26. const result = await github.graphql(query, variables);
  27. const pushedAt = result.repository.ref.target.pushedDate;
  28. console.log(`Last commit pushed at ${pushedAt}.`);
  29. const delta = new Date() - new Date(pushedAt);
  30. if (delta <= DETECTION_TIME_FRAME) {
  31. console.info('New changes detected, triggering a new build.');
  32. return true;
  33. }
  34. console.info('No new changes detected.');
  35. return false;
  36. }
  37. async function checkAndroidChanges(github, context) {
  38. if (checkBaseChanges(github, context)) return true;
  39. const query = `query($owner:String!, $name:String!, $label:String!) {
  40. repository(name:$name, owner:$owner) {
  41. pullRequests(labels: [$label], states: OPEN, first: 100) {
  42. nodes { number headRepository { pushedAt } }
  43. }
  44. }
  45. }`;
  46. const variables = {
  47. owner: context.repo.owner,
  48. name: context.repo.repo,
  49. label: CHANGE_LABEL,
  50. };
  51. const result = await github.graphql(query, variables);
  52. const pulls = result.repository.pullRequests.nodes;
  53. for (let i = 0; i < pulls.length; i++) {
  54. let pull = pulls[i];
  55. if (new Date() - new Date(pull.headRepository.pushedAt) <= DETECTION_TIME_FRAME) {
  56. console.info(`${pull.number} updated at ${pull.headRepository.pushedAt}`);
  57. return true;
  58. }
  59. }
  60. console.info("No changes detected in any tagged pull requests.");
  61. return false;
  62. }
  63. async function tagAndPush(github, owner, repo, execa, commit=false) {
  64. let altToken = process.env.ALT_GITHUB_TOKEN;
  65. if (!altToken) {
  66. throw `Please set ALT_GITHUB_TOKEN environment variable. This token should have write access to ${owner}/${repo}.`;
  67. }
  68. const query = `query ($owner:String!, $name:String!) {
  69. repository(name:$name, owner:$owner) {
  70. refs(refPrefix: "refs/tags/", orderBy: {field: TAG_COMMIT_DATE, direction: DESC}, first: 10) {
  71. nodes { name }
  72. }
  73. }
  74. }`;
  75. const variables = {
  76. owner: owner,
  77. name: repo,
  78. };
  79. const tags = await github.graphql(query, variables);
  80. const tagList = tags.repository.refs.nodes;
  81. const lastTag = tagList[0] ? tagList[0].name : 'dummy-0';
  82. const tagNumber = /\w+-(\d+)/.exec(lastTag)[1] | 0;
  83. const channel = repo.split('-')[1];
  84. const newTag = `${channel}-${tagNumber + 1}`;
  85. console.log(`New tag: ${newTag}`);
  86. if (commit) {
  87. let channelName = channel[0].toUpperCase() + channel.slice(1);
  88. console.info(`Committing pending commit as ${channelName} #${tagNumber + 1}`);
  89. await execa("git", ['commit', '-m', `${channelName} #${tagNumber + 1}`]);
  90. }
  91. console.info('Pushing tags to GitHub ...');
  92. await execa("git", ['tag', newTag]);
  93. await execa("git", ['remote', 'add', 'target', `https://${altToken}@github.com/${owner}/${repo}.git`]);
  94. await execa("git", ['push', 'target', 'master', '-f']);
  95. await execa("git", ['push', 'target', 'master', '--tags']);
  96. console.info('Successfully pushed new changes.');
  97. }
  98. async function generateReadme(pulls, context, mergeResults, execa) {
  99. let baseUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/`;
  100. let output =
  101. "| Pull Request | Commit | Title | Author | Merged? |\n|----|----|----|----|----|\n";
  102. for (let pull of pulls) {
  103. let pr = pull.number;
  104. let result = mergeResults[pr];
  105. output += `| [${pr}](${baseUrl}/pull/${pr}) | [\`${result.rev || "N/A"}\`](${baseUrl}/pull/${pr}/files) | ${pull.title} | [${pull.author.login}](https://github.com/${pull.author.login}/) | ${result.success ? "Yes" : "No"} |\n`;
  106. }
  107. output +=
  108. "\n\nEnd of merge log. You can find the original README.md below the break.\n\n-----\n\n";
  109. output += fs.readFileSync("./README.md");
  110. fs.writeFileSync("./README.md", output);
  111. await execa("git", ["add", "README.md"]);
  112. }
  113. async function fetchPullRequests(pulls, repoUrl, execa) {
  114. console.log("::group::Fetch pull requests");
  115. for (let pull of pulls) {
  116. let pr = pull.number;
  117. console.info(`Fetching PR ${pr} ...`);
  118. await execa("git", [
  119. "fetch",
  120. "-f",
  121. "--no-recurse-submodules",
  122. repoUrl,
  123. `pull/${pr}/head:pr-${pr}`,
  124. ]);
  125. }
  126. console.log("::endgroup::");
  127. }
  128. async function mergePullRequests(pulls, execa) {
  129. let mergeResults = {};
  130. console.log("::group::Merge pull requests");
  131. await execa("git", ["config", "--global", "user.name", "yuzubot"]);
  132. await execa("git", [
  133. "config",
  134. "--global",
  135. "user.email",
  136. "yuzu\x40yuzu-emu\x2eorg", // prevent email harvesters from scraping the address
  137. ]);
  138. let hasFailed = false;
  139. for (let pull of pulls) {
  140. let pr = pull.number;
  141. console.info(`Merging PR ${pr} ...`);
  142. try {
  143. const process1 = execa("git", [
  144. "merge",
  145. "--squash",
  146. "--no-edit",
  147. `pr-${pr}`,
  148. ]);
  149. process1.stdout.pipe(process.stdout);
  150. await process1;
  151. const process2 = execa("git", ["commit", "-m", `Merge PR ${pr}`]);
  152. process2.stdout.pipe(process.stdout);
  153. await process2;
  154. const process3 = await execa("git", ["rev-parse", "--short", `pr-${pr}`]);
  155. mergeResults[pr] = {
  156. success: true,
  157. rev: process3.stdout,
  158. };
  159. } catch (err) {
  160. console.log(
  161. `::error title=#${pr} not merged::Failed to merge pull request: ${pr}: ${err}`
  162. );
  163. mergeResults[pr] = { success: false };
  164. hasFailed = true;
  165. await execa("git", ["reset", "--hard"]);
  166. }
  167. }
  168. console.log("::endgroup::");
  169. if (hasFailed) {
  170. throw 'There are merge failures. Aborting!';
  171. }
  172. return mergeResults;
  173. }
  174. async function mergebot(github, context, execa) {
  175. const query = `query ($owner:String!, $name:String!, $label:String!) {
  176. repository(name:$name, owner:$owner) {
  177. pullRequests(labels: [$label], states: OPEN, first: 100) {
  178. nodes {
  179. number title author { login }
  180. }
  181. }
  182. }
  183. }`;
  184. const variables = {
  185. owner: context.repo.owner,
  186. name: context.repo.repo,
  187. label: CHANGE_LABEL,
  188. };
  189. const result = await github.graphql(query, variables);
  190. const pulls = result.repository.pullRequests.nodes;
  191. let displayList = [];
  192. for (let i = 0; i < pulls.length; i++) {
  193. let pull = pulls[i];
  194. displayList.push({ PR: pull.number, Title: pull.title });
  195. }
  196. console.info("The following pull requests will be merged:");
  197. console.table(displayList);
  198. await fetchPullRequests(pulls, "https://github.com/yuzu-emu/yuzu", execa);
  199. const mergeResults = await mergePullRequests(pulls, execa);
  200. await generateReadme(pulls, context, mergeResults, execa);
  201. await tagAndPush(github, context.repo.owner, `${context.repo.repo}-android`, execa, true);
  202. }
  203. module.exports.mergebot = mergebot;
  204. module.exports.checkAndroidChanges = checkAndroidChanges;
  205. module.exports.tagAndPush = tagAndPush;
  206. module.exports.checkBaseChanges = checkBaseChanges;