lgtm-processor.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /**
  2. * LGTM Command Processor
  3. *
  4. * Processes /lgtm comments on pull requests. Checks if the commenter has the
  5. * required reviewer role(s) based on CODEOWNERS.md, then adds the lgtm label
  6. * and posts a confirmation comment.
  7. *
  8. * @param {object} params
  9. * @param {object} params.core - @actions/core
  10. * @param {object} params.github - @actions/github Octokit instance
  11. * @param {object} params.context - GitHub Actions context
  12. * @param {object} params.fs - Node.js fs module
  13. */
  14. export default async function run({ core, github, context, fs }) {
  15. const organization = 'external-secrets';
  16. const lgtmLabelName = 'lgtm';
  17. const owner = context.repo.owner;
  18. const repo = context.repo.repo;
  19. // Fail fast if the LGTM label does not exist in the repository
  20. const repoLabels = await github.paginate(github.rest.issues.listLabelsForRepo, {
  21. owner, repo, per_page: 100
  22. });
  23. if (!repoLabels.some(l => l.name === lgtmLabelName)) {
  24. core.setFailed(`LGTM label "${lgtmLabelName}" does not exist in the repository. Please create it before using the LGTM workflow.`);
  25. return;
  26. }
  27. const commenter = context.payload.comment.user.login;
  28. const prNumber = context.payload.issue.number;
  29. // Parse CODEOWNERS.md file
  30. let codeownersContent;
  31. try {
  32. codeownersContent = fs.readFileSync('CODEOWNERS.md', 'utf8');
  33. } catch (error) {
  34. return;
  35. }
  36. // Extract role mappings from CODEOWNERS.md (including * pattern)
  37. const codeownerMappings = [];
  38. let wildcardRoles = [];
  39. codeownersContent.split('\n').forEach(line => {
  40. const trimmed = line.trim();
  41. if (!trimmed || trimmed.startsWith('#')) return;
  42. const match = trimmed.match(/^(\S+)\s+(.+)$/);
  43. if (match) {
  44. const [, pattern, roles] = match;
  45. const rolesList = roles.split(/\s+/).filter(r => r.startsWith('@'));
  46. if (pattern === '*') {
  47. wildcardRoles = rolesList;
  48. } else {
  49. codeownerMappings.push({
  50. pattern,
  51. roles: rolesList
  52. });
  53. }
  54. }
  55. });
  56. // Extract maintainer roles from wildcardRoles
  57. const maintainerRoles = wildcardRoles.map(role => role.replace(`@${organization}/`, ''));
  58. // Early check: if user is a maintainer, approve immediately
  59. let isMaintainer = false;
  60. for (const role of maintainerRoles) {
  61. try {
  62. const response = await github.rest.teams.getMembershipForUserInOrg({
  63. org: organization,
  64. team_slug: role,
  65. username: commenter
  66. });
  67. if (response.data.state === 'active') {
  68. isMaintainer = true;
  69. break;
  70. }
  71. } catch (error) {
  72. // User not in this team, continue checking others
  73. }
  74. }
  75. if (isMaintainer) {
  76. // Check if LGTM label already exists
  77. const labels = await github.rest.issues.listLabelsOnIssue({
  78. owner, repo, issue_number: prNumber
  79. });
  80. if (!labels.data.some(l => l.name === lgtmLabelName)) {
  81. await github.rest.issues.addLabels({
  82. owner, repo, issue_number: prNumber, labels: [lgtmLabelName]
  83. });
  84. }
  85. // Simple confirmation for maintainers (no role mentions)
  86. await github.rest.issues.createComment({
  87. owner, repo, issue_number: prNumber,
  88. body: `✅ LGTM by @${commenter} (maintainer)`
  89. });
  90. return;
  91. }
  92. // Get changed files in PR
  93. const filesResponse = await github.rest.pulls.listFiles({
  94. owner, repo, pull_number: prNumber
  95. });
  96. const changedFiles = filesResponse.data.map(f => f.filename);
  97. // Find all required reviewer roles for the changed files
  98. // This includes hierarchical matching (e.g., pkg/provider/ matches pkg/provider/aws/file.go)
  99. const requiredReviewerRoles = new Set();
  100. let hasFilesWithoutSpecificOwners = false;
  101. changedFiles.forEach(file => {
  102. let hasSpecificOwner = false;
  103. codeownerMappings.forEach(mapping => {
  104. const { pattern, roles } = mapping;
  105. // Match pattern (handle both exact matches and directory patterns)
  106. // This handles hierarchical matching where broader patterns can cover more specific paths
  107. if (file === pattern ||
  108. file.startsWith(pattern.endsWith('/') ? pattern : pattern + '/')) {
  109. roles.forEach(role => requiredReviewerRoles.add(role));
  110. hasSpecificOwner = true;
  111. }
  112. });
  113. if (!hasSpecificOwner) {
  114. hasFilesWithoutSpecificOwners = true;
  115. }
  116. });
  117. // For files that only match the wildcard pattern, add wildcard roles
  118. if (hasFilesWithoutSpecificOwners) {
  119. wildcardRoles.forEach(role => {
  120. requiredReviewerRoles.add(role);
  121. });
  122. }
  123. // Find commenter's matching reviewer roles
  124. const commenterReviewerRoles = new Set();
  125. for (const role of requiredReviewerRoles) {
  126. const roleSlug = role.replace(`@${organization}/`, '');
  127. try {
  128. const response = await github.rest.teams.getMembershipForUserInOrg({
  129. org: organization,
  130. team_slug: roleSlug,
  131. username: commenter
  132. });
  133. if (response.data.state === 'active') {
  134. commenterReviewerRoles.add(role);
  135. }
  136. } catch (error) {
  137. // User not in this role, continue checking others
  138. }
  139. }
  140. // Check if user has any required reviewer role
  141. if (commenterReviewerRoles.size === 0) {
  142. const rolesList = Array.from(requiredReviewerRoles).map(role => role.replace(`@${organization}/`, '')).join(', ');
  143. await github.rest.issues.createComment({
  144. owner, repo, issue_number: prNumber,
  145. body: `@${commenter} You must be a member of one of the required reviewer roles to use /lgtm.\n\nRequired roles for this PR: ${rolesList}`
  146. });
  147. return;
  148. }
  149. // Check if LGTM label already exists
  150. const labels = await github.rest.issues.listLabelsOnIssue({
  151. owner, repo, issue_number: prNumber
  152. });
  153. if (!labels.data.some(l => l.name === lgtmLabelName)) {
  154. await github.rest.issues.addLabels({
  155. owner, repo, issue_number: prNumber, labels: [lgtmLabelName]
  156. });
  157. // Added LGTM label
  158. }
  159. // Build confirmation message with role coverage info
  160. const mentionRoles = wildcardRoles.join(' ');
  161. let confirmationMessage = `${mentionRoles}\n\n✅ LGTM by @${commenter}`;
  162. // Check for truly uncovered roles using pattern hierarchy
  163. const uncoveredRoles = [];
  164. for (const requiredRole of requiredReviewerRoles) {
  165. let isCovered = commenterReviewerRoles.has(requiredRole);
  166. // If not directly covered, check if any commenter role has a pattern that covers this required role's pattern
  167. if (!isCovered) {
  168. // Find the patterns for this required role
  169. const requiredRolePatterns = codeownerMappings
  170. .filter(mapping => mapping.roles.includes(requiredRole))
  171. .map(mapping => mapping.pattern);
  172. // Check if any commenter role has a pattern that is a parent of any required role pattern
  173. for (const commenterRole of commenterReviewerRoles) {
  174. const commenterRolePatterns = codeownerMappings
  175. .filter(mapping => mapping.roles.includes(commenterRole))
  176. .map(mapping => mapping.pattern);
  177. // Check if any commenter pattern is a parent of any required pattern
  178. for (const commenterPattern of commenterRolePatterns) {
  179. for (const requiredPattern of requiredRolePatterns) {
  180. const commenterPath = commenterPattern.endsWith('/') ? commenterPattern : commenterPattern + '/';
  181. const requiredPath = requiredPattern.endsWith('/') ? requiredPattern : requiredPattern + '/';
  182. // If required pattern starts with commenter pattern, it's hierarchically covered
  183. if (requiredPath.startsWith(commenterPath) && commenterPath !== requiredPath) {
  184. isCovered = true;
  185. break;
  186. }
  187. }
  188. if (isCovered) break;
  189. }
  190. if (isCovered) break;
  191. }
  192. }
  193. if (!isCovered) {
  194. uncoveredRoles.push(requiredRole);
  195. }
  196. }
  197. // Show role coverage analysis
  198. confirmationMessage += `\n\n**Review Coverage:**`;
  199. if (uncoveredRoles.length > 0) {
  200. confirmationMessage += `\n- Commenter has roles:`;
  201. Array.from(commenterReviewerRoles).forEach(role => {
  202. const roleName = role.replace(`@${organization}/`, '');
  203. confirmationMessage += `\n - ${roleName}`;
  204. });
  205. confirmationMessage += `\n- Required roles:`;
  206. Array.from(requiredReviewerRoles).forEach(role => {
  207. const roleName = role.replace(`@${organization}/`, '');
  208. confirmationMessage += `\n - ${roleName}`;
  209. });
  210. confirmationMessage += `\n- ❌ Additional review may be needed by:`;
  211. uncoveredRoles.forEach(role => {
  212. const roleName = role.replace(`@${organization}/`, '');
  213. confirmationMessage += `\n - ${roleName}`;
  214. });
  215. } else {
  216. confirmationMessage += `\n- ✅ All required roles covered`;
  217. }
  218. await github.rest.issues.createComment({
  219. owner, repo, issue_number: prNumber,
  220. body: confirmationMessage
  221. });
  222. }