2
0

github-comment.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. const fetch = require('node-fetch');
  2. const REPO = process.env.ACCESS_REPO;
  3. const TOKEN = process.env.ACCESS_TOKEN;
  4. const PR = process.env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER;
  5. const argv = process.argv;
  6. const tag = argv[argv.length - 2];
  7. const comment = argv[argv.length - 1];
  8. const REPLACE_MARK = `<!-- AZURE_UPDATE_COMMENT_${tag} -->`;
  9. const wrappedComment = `
  10. ${REPLACE_MARK}
  11. ${comment}
  12. `.trim();
  13. async function withGithub(url, json, method) {
  14. const res = await fetch(url, {
  15. method: method || (json ? 'POST' : 'GET'),
  16. headers: {
  17. Accept: 'application/json',
  18. 'Content-Type': 'application/json',
  19. Authorization: `Basic ${Buffer.from(TOKEN).toString('base64')}`,
  20. },
  21. body: json ? JSON.stringify(json) : undefined,
  22. });
  23. return res.json();
  24. }
  25. (async function run() {
  26. if (PR == null) {
  27. console.log('未获取到PR,忽略处理')
  28. return;
  29. }
  30. const comments = await withGithub(`https://api.github.com/repos/${REPO}/issues/${PR}/comments`);
  31. // Find my comment
  32. const updateComment = comments.find(({ body }) => body.includes(REPLACE_MARK));
  33. // eslint-disable-next-line no-console
  34. console.log('Origin comment:', updateComment);
  35. // Update
  36. let res;
  37. if (!updateComment) {
  38. res = await withGithub(`https://api.github.com/repos/${REPO}/issues/${PR}/comments`, {
  39. body: wrappedComment,
  40. });
  41. } else {
  42. res = await withGithub(
  43. `https://api.github.com/repos/${REPO}/issues/comments/${updateComment.id}`,
  44. {
  45. body: wrappedComment,
  46. },
  47. 'PATCH',
  48. );
  49. }
  50. // eslint-disable-next-line no-console
  51. console.log(res);
  52. })();