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

Conversation

developerjhp
Copy link
Member

@developerjhp developerjhp commented Jan 13, 2025

Changes

This PR introduces a GitHub Actions workflow (auto_assign.yaml) to automatically assign the PR creator as the assignee when a pull request is opened. It uses the actions/github-script to interact with GitHub's REST API.

Visuals

No visuals are included, as this is a backend configuration update.

Checklist

  • Have you written the functional specifications?
  • Have you written the test code?

Additional Discussion Points

  • Are there any additional edge cases we should test for?
  • Error handling and permission optimization could be reviewed for further improvement.

Summary by CodeRabbit

  • New Features
    • 풀 리퀘스트 생성 시 자동으로 작성자를 담당자로 지정하는 GitHub Actions 워크플로우를 추가했습니다.
    • auto_assign.js 파일에서 PR 작성자를 자동으로 할당하는 기능을 구현했습니다.
  • Chores
    • auto-assign 프로젝트를 위한 package.json 파일을 추가했습니다.
    • VSCode 추천 확장 목록에 "github.vscode-github-actions"를 추가했습니다.

Copy link

changeset-bot bot commented Jan 13, 2025

⚠️ No Changeset found

Latest commit: b095755

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

coderabbitai bot commented Jan 13, 2025

"""

워크스루

새로운 GitHub Actions 워크플로우 파일 auto_assign.yaml이 추가되었습니다. 이 워크플로우는 풀 리퀘스트가 열릴 때 트리거되며, 풀 리퀘스트와 이슈에 대한 쓰기 권한을 가집니다. Ubuntu 환경에서 실행되며, GitHub API를 사용하여 풀 리퀘스트 생성자를 자동으로 담당자로 할당합니다. 스크립트는 오류 처리 기능을 포함하여 할당 실패 시 메시지를 로그로 남기고 작업을 실패로 설정합니다.

변경 사항

파일 변경 요약
.github/workflows/auto_assign.yaml 새로운 GitHub Actions 워크플로우 추가. 풀 리퀘스트 생성자를 자동으로 담당자로 지정
.github/workflows/auto-assign/auto_assign.js 풀 리퀘스트 생성자를 담당자로 지정하는 스크립트 추가. 오류 처리 및 Octokit 클라이언트 초기화 포함
.github/workflows/auto-assign/package.json auto-assign 프로젝트를 위한 새로운 package.json 파일 추가. 메타데이터 및 종속성 정의
.vscode/extensions.json 새로운 추천 확장 프로그램 "github.vscode-github-actions" 추가

시퀀스 다이어그램

sequenceDiagram
    participant PR Creator
    participant GitHub Actions
    participant GitHub API
    
    PR Creator->>GitHub Actions: Pull Request 생성
    GitHub Actions->>GitHub API: PR 정보 조회
    GitHub API-->>GitHub Actions: PR 정보 반환
    GitHub Actions->>GitHub API: PR 생성자를 담당자로 지정
Loading

토끼의 시

🐰 풀 리퀘스트, 자동 배정
코드의 여정 간편하게
깃헙 액션즈의 마법
개발자의 손길 덜어내
효율성의 토끼 점프! 🚀
"""


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ae404ac and b095755.

📒 Files selected for processing (1)
  • .vscode/extensions.json (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: chromatic
🔇 Additional comments (1)
.vscode/extensions.json (1)

2-6: 권장 확장 프로그램 추가가 적절합니다!

GitHub Actions 워크플로우를 구현하는 PR의 목적에 맞게 github.vscode-github-actions 확장 프로그램을 추가한 것이 적절합니다. 이는 팀원들이 GitHub Actions 워크플로우를 더 쉽게 관리하고 디버깅할 수 있도록 도와줄 것입니다.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@developerjhp developerjhp changed the title feat(auto_assign): add GitHub Actions workflow for auto-assigning PR … feat(auto_assign): Add GitHub Actions workflow for auto-assigning PR creators Jan 13, 2025
Copy link

codecov bot commented Jan 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
.github/workflows/auto_assign.yaml (1)

1-6: PR이 다시 열릴 때도 자동 할당이 필요합니다

워크플로우가 PR이 처음 열릴 때만 트리거되도록 설정되어 있습니다. PR이 다시 열리는 경우도 처리하도록 개선하는 것이 좋겠습니다.

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

 on:
   pull_request:
-    types: [opened]
+    types: [opened, reopened]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9ac17a9 and 35db31e.

📒 Files selected for processing (1)
  • .github/workflows/auto_assign.yaml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: chromatic
🔇 Additional comments (1)
.github/workflows/auto_assign.yaml (1)

11-14: 작업 구성이 적절합니다

작업 이름이 명확하고 실행 환경이 적절하게 설정되어 있습니다.

Comment on lines 7 to 10
permissions:
pull-requests: write
issues: write

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

불필요한 권한을 제거하세요

PR 담당자 지정을 위해서는 pull-requests 권한만 필요합니다. 최소 권한의 원칙에 따라 불필요한 issues 권한은 제거하는 것이 좋습니다.

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

 permissions:
   pull-requests: write
-  issues: write
📝 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
permissions:
pull-requests: write
issues: write
permissions:
pull-requests: write

Comment on lines 15 to 25
- uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
const repository = context.payload.repository;
await github.rest.issues.addAssignees({
owner: repository.owner.login,
repo: repository.name,
issue_number: pr.number,
assignees: [pr.user.login]
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

에러 처리 로직을 추가하세요

GitHub API 호출 시 발생할 수 있는 오류(예: API 제한, 네트워크 문제 등)에 대한 처리가 없습니다. 워크플로우의 안정성을 위해 에러 처리를 추가하는 것이 좋겠습니다.

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

       - uses: actions/github-script@v7
         with:
           script: |
             const pr = context.payload.pull_request;
             const repository = context.payload.repository;
-            await github.rest.issues.addAssignees({
-              owner: repository.owner.login,
-              repo: repository.name,
-              issue_number: pr.number,
-              assignees: [pr.user.login]
-            });
+            try {
+              await github.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);
+              core.setFailed(error.message);
+            }
📝 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
- uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
const repository = context.payload.repository;
await github.rest.issues.addAssignees({
owner: repository.owner.login,
repo: repository.name,
issue_number: pr.number,
assignees: [pr.user.login]
});
- uses: actions/github-script@v7
with:
script: |
const pr = context.payload.pull_request;
const repository = context.payload.repository;
try {
await github.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);
core.setFailed(error.message);
}

…PR creators

- Removed unnecessary permissions for issues.
- Added try-catch block to handle errors when assigning PR creators, with logging for success and failure cases.
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.

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (1)
.github/workflows/auto-assign/auto_assign.js (1)

5-34: 🛠️ Refactor suggestion

에러 처리를 개선해야 합니다

현재 에러 처리가 너무 단순합니다. GitHub API 호출 시 발생할 수 있는 구체적인 에러 케이스(예: API 제한, 권한 부족 등)에 대한 처리가 필요합니다.

다음과 같이 개선하는 것을 제안합니다:

 const octokit = github.getOctokit(token);
+const { retry } = require('@octokit/plugin-retry');
+const RetryOctokit = github.getOctokit(token).plugin(retry);

-    await octokit.rest.issues.addAssignees({
+    try {
+      await RetryOctokit.rest.issues.addAssignees({
         owner: repository.owner.login,
         repo: repository.name,
         issue_number: pr.number,
         assignees: [pr.user.login],
-    });
+      });
+    } catch (error) {
+      if (error.status === 403) {
+        throw new Error('권한이 부족합니다. GitHub 토큰의 권한을 확인해주세요.');
+      } else if (error.status === 429) {
+        throw new Error('GitHub API 호출 제한에 도달했습니다. 잠시 후 다시 시도해주세요.');
+      }
+      throw error;
+    }
🧹 Nitpick comments (2)
.github/workflows/auto-assign/auto_assign.js (1)

1-4: ESLint 설정 개선이 필요합니다

TypeScript 프로젝트에서 JavaScript 파일을 사용하고 있습니다. 코드베이스의 일관성을 위해 TypeScript로 마이그레이션하는 것이 좋습니다.

다음과 같이 변경하는 것을 제안합니다:

  1. 파일 확장자를 .ts로 변경
  2. 타입 정의 추가:
import * as github from '@actions/github'
import * as core from '@actions/core'

interface Repository {
  owner: {
    login: string
  }
  name: string
}

interface PullRequest {
  number: number
  user: {
    login: string
  }
}
.github/workflows/auto_assign.yaml (1)

28-32: 의존성 설치 단계 최적화가 필요합니다

npm ci 명령어를 실행하기 전에 package-lock.json 파일의 존재 여부를 확인하지 않고 있습니다.

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

       - name: Install dependencies for auto-assign
         run: |
           cd .github/workflows/auto-assign
+          if [ ! -f package-lock.json ]; then
+            echo "Error: package-lock.json not found"
+            exit 1
+          fi
           npm ci
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b53e40f and 70b8ec0.

⛔ Files ignored due to path filters (1)
  • .github/workflows/auto-assign/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • .github/workflows/auto-assign/auto_assign.js (1 hunks)
  • .github/workflows/auto-assign/package.json (1 hunks)
  • .github/workflows/auto_assign.yaml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .github/workflows/auto-assign/package.json
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/auto_assign.yaml

16-16: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

🔇 Additional comments (2)
.github/workflows/auto_assign.yaml (2)

7-10: 권한 설정이 최적화되어 있습니다

이전 리뷰 의견을 반영하여 필요한 최소한의 권한만 설정된 것을 확인했습니다.


1-37: JavaScript 액션으로의 마이그레이션을 고려해보세요

이전 리뷰 의견에서 제안된 것처럼, 이 워크플로우를 JavaScript 액션으로 변환하면 재사용성과 유지보수성이 향상될 것 같습니다.

JavaScript 액션으로 변환하는 작업을 도와드릴까요?

🧰 Tools
🪛 actionlint (1.7.4)

16-16: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

}
}

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);
});

runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

액션 버전 업데이트가 필요합니다

actions/checkout 액션의 버전이 너무 오래되었습니다.

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

-        uses: actions/checkout@v3
+        uses: actions/checkout@v4
📝 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
uses: actions/checkout@v3
uses: actions/checkout@v4
🧰 Tools
🪛 actionlint (1.7.4)

16-16: the runner of "actions/checkout@v3" action is too old to run on GitHub Actions. update the action's version to fix this issue

(action)

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Node.js 버전 선택을 재고해야 합니다

Node.js 22 버전은 아직 안정화되지 않은 버전입니다. 프로덕션 환경에서는 LTS 버전을 사용하는 것이 좋습니다.

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

-          node-version: "22"
+          node-version: "20"
📝 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
node-version: "22"
node-version: "20"

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
.github/workflows/auto-assign/auto_assign.js (1)

5-9: 토큰 검증 로직 개선이 필요합니다.

토큰 유효성 검사를 더 강화하고 오류 메시지를 더 상세하게 제공하면 좋을 것 같습니다.

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

 async function getOctokitAndContext() {
   const token = process.env.GITHUB_TOKEN;
-  if (!token) throw new Error('GITHUB_TOKEN is not provided');
+  if (!token) throw new Error('GitHub 토큰이 환경 변수에 설정되지 않았습니다. workflow 파일에서 permissions 설정을 확인해주세요.');
+  if (typeof token !== 'string' || token.trim() === '') {
+    throw new Error('GitHub 토큰이 유효하지 않습니다.');
+  }
   return { octokit: github.getOctokit(token), context: github.context };
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 70b8ec0 and 63b175f.

📒 Files selected for processing (1)
  • .github/workflows/auto-assign/auto_assign.js (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: chromatic
🔇 Additional comments (2)
.github/workflows/auto-assign/auto_assign.js (2)

1-3: ESLint 설정과 임포트가 적절합니다!

GitHub Actions 스크립트에 필요한 ESLint 규칙 비활성화와 라이브러리 임포트가 올바르게 구성되어 있습니다.


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

이전 리뷰에서 지적된 것처럼, 비동기 함수의 실행 결과와 에러를 제대로 처리하지 않고 있습니다.

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

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

Comment on lines +11 to +30
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);
}
}
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);
}
}


- name: Setup Node.js
uses: actions/setup-node@v4
with:
Copy link
Contributor

Choose a reason for hiding this comment

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

이거 indent가 잘못들어간거 같은데?

가끔 이런 syntax에러는 나같은 경우는

익스텐션 설치해서 사용하는데, 알아보긴하는데 .vscode extensions.json에 추가하는게 좋을까 ?

Copy link
Member Author

Choose a reason for hiding this comment

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

extension recommendations에 github-action 추가했어!! 고마워~!!

/* 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.

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

- name: Install dependencies for auto-assign
run: |
cd .github/workflows/auto-assign
npm ci
Copy link
Contributor

Choose a reason for hiding this comment

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

pnpm ci 로 해야하는거 아닌가 ~ ?

pnpm install --frozen-lockfile

Copy link
Member Author

Choose a reason for hiding this comment

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

요것도 추가했어!! 고마웡~!!!

Copy link
Contributor

@froggy1014 froggy1014 left a comment

Choose a reason for hiding this comment

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

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants