Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(auto_assign): Add GitHub Actions workflow for auto-assigning PR creators #102

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
32 changes: 32 additions & 0 deletions .github/workflows/auto-assign/auto_assign.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/* eslint-disable no-undef */
/* eslint-disable @typescript-eslint/no-require-imports */
const github = require('@actions/github');

async function getOctokitAndContext() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이런식으로 만들어서 쓰는거 처음알아따..

const token = process.env.GITHUB_TOKEN;
if (!token) throw new Error('GITHUB_TOKEN is not provided');
return { octokit: github.getOctokit(token), context: github.context };
}

async function run() {
try {
const { octokit, context } = await getOctokitAndContext();
const { pull_request: pr, repository } = context.payload;

if (!pr) throw new Error('This action only runs on pull request events.');

await octokit.rest.issues.addAssignees({
owner: repository.owner.login,
repo: repository.name,
issue_number: pr.number,
assignees: [pr.user.login],
});

console.log(`Successfully assigned ${pr.user.login} to PR #${pr.number}`);
} catch (error) {
console.error('Failed to assign PR creator:', error.message);
process.exit(1);
}
}
Comment on lines +11 to +30
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

에러 처리와 API 제한 처리가 필요합니다.

  1. API 호출 실패에 대한 구체적인 에러 처리
  2. GitHub API 레이트 리밋 처리
  3. 네트워크 타임아웃 처리가 필요합니다.

다음과 같이 수정하는 것을 제안합니다:

 async function run() {
   try {
     const { octokit, context } = await getOctokitAndContext();
     const { pull_request: pr, repository } = context.payload;

     if (!pr) throw new Error('This action only runs on pull request events.');

+    // API 레이트 리밋 확인
+    const { data: rateLimit } = await octokit.rest.rateLimit.get();
+    if (rateLimit.remaining === 0) {
+      throw new Error(`API 레이트 리밋에 도달했습니다. ${new Date(rateLimit.reset * 1000)} 이후에 다시 시도해주세요.`);
+    }

+    // 타임아웃 설정과 함께 API 호출
+    const timeoutPromise = new Promise((_, reject) =>
+      setTimeout(() => reject(new Error('API 요청 타임아웃')), 10000)
+    );

+    await Promise.race([
       octokit.rest.issues.addAssignees({
         owner: repository.owner.login,
         repo: repository.name,
         issue_number: pr.number,
         assignees: [pr.user.login],
-      });
+      }),
+      timeoutPromise
+    ]);

     console.log(`Successfully assigned ${pr.user.login} to PR #${pr.number}`);
   } catch (error) {
-    console.error('Failed to assign PR creator:', error.message);
+    if (error.status === 403) {
+      console.error('권한이 없습니다. workflow 파일의 permissions 설정을 확인해주세요.');
+    } else if (error.status === 404) {
+      console.error('PR 또는 저장소를 찾을 수 없습니다.');
+    } else {
+      console.error('PR 생성자 할당 실패:', error.message);
+    }
     process.exit(1);
   }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function run() {
try {
const { octokit, context } = await getOctokitAndContext();
const { pull_request: pr, repository } = context.payload;
if (!pr) throw new Error('This action only runs on pull request events.');
await octokit.rest.issues.addAssignees({
owner: repository.owner.login,
repo: repository.name,
issue_number: pr.number,
assignees: [pr.user.login],
});
console.log(`Successfully assigned ${pr.user.login} to PR #${pr.number}`);
} catch (error) {
console.error('Failed to assign PR creator:', error.message);
process.exit(1);
}
}
async function run() {
try {
const { octokit, context } = await getOctokitAndContext();
const { pull_request: pr, repository } = context.payload;
if (!pr) throw new Error('This action only runs on pull request events.');
// API 레이트 리밋 확인
const { data: rateLimit } = await octokit.rest.rateLimit.get();
if (rateLimit.remaining === 0) {
throw new Error(`API 레이트 리밋에 도달했습니다. ${new Date(rateLimit.reset * 1000)} 이후에 다시 시도해주세요.`);
}
// 타임아웃 설정과 함께 API 호출
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error('API 요청 타임아웃')), 10000)
);
await Promise.race([
octokit.rest.issues.addAssignees({
owner: repository.owner.login,
repo: repository.name,
issue_number: pr.number,
assignees: [pr.user.login],
}),
timeoutPromise
]);
console.log(`Successfully assigned ${pr.user.login} to PR #${pr.number}`);
} catch (error) {
if (error.status === 403) {
console.error('권한이 없습니다. workflow 파일의 permissions 설정을 확인해주세요.');
} else if (error.status === 404) {
console.error('PR 또는 저장소를 찾을 수 없습니다.');
} else {
console.error('PR 생성자 할당 실패:', error.message);
}
process.exit(1);
}
}


run();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

비동기 함수 실행 방식 개선이 필요합니다

비동기 함수의 실행 결과와 에러를 제대로 처리하지 않고 있습니다.

다음과 같이 수정하는 것을 제안합니다:

-run();
+run().catch(error => {
+  console.error('치명적인 오류 발생:', error);
+  process.exit(1);
+});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
run();
run().catch(error => {
console.error('치명적인 오류 발생:', error);
process.exit(1);
});

235 changes: 235 additions & 0 deletions .github/workflows/auto-assign/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions .github/workflows/auto-assign/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "auto-assign",
"version": "1.0.0",
"description": "",
"main": "auto_assign.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@actions/github": "^6.0.0"
}
}
37 changes: 37 additions & 0 deletions .github/workflows/auto_assign.yaml
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

액션의 유지보수성을 높이기 위해 JavaScript action으로 만들어서 관리하면 어떨까? ㅎㅎ

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오 좋은생각인 것 같아!!
한번 시도해볼게!!

Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Auto Assign PR Creator

on:
pull_request:
types: [opened]

permissions:
pull-requests: write
contents: read

jobs:
auto-assign:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
repository: ${{ github.event.pull_request.head.repo.full_name }}
ref: ${{ github.event.pull_request.head.ref }}
fetch-depth: 0

- name: Setup Node.js
uses: actions/setup-node@v4
with:
cache: pnpm
node-version-file: .nvmrc

- name: Install dependencies for auto-assign
run: |
cd .github/workflows/auto-assign
pnpm install --frozen-lockfile

- name: Run Auto Assign Script
run: node auto_assign.js
working-directory: .github/workflows/auto-assign
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
6 changes: 5 additions & 1 deletion .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
{
"recommendations": ["biomejs.biome", "dbaeumer.vscode-eslint"]
"recommendations": [
"biomejs.biome",
"dbaeumer.vscode-eslint",
"github.vscode-github-actions"
]
}
Loading