Skip to content

Commit

Permalink
[fix] Fix action on comment (again)
Browse files Browse the repository at this point in the history
  • Loading branch information
baseballyama committed Nov 5, 2023
1 parent 226a5c9 commit 1e80cf2
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 40 deletions.
9 changes: 5 additions & 4 deletions packages/ai-craftsman/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,11 @@ const main = async () => {
const rules = await readCodingRules();
const promises: (() => Promise<void>)[] = [];
let commented = false;
const targetBranch = isIncremental
? await git.getLatestCommitIdByTheApp()
: await git.getBaseRef();
for (const { diff, path } of git.getDiff(targetBranch)) {
let { base, head } = await git.getRef();
if (isIncremental) {
base = await git.getLatestCommitIdByTheApp();
}
for (const { diff, path } of git.getDiff(base, head)) {
if (excludePatterns.some((pattern) => pattern.test(path))) {
console.log(`SKIP REVIEW: ${path}`);
continue;
Expand Down
74 changes: 38 additions & 36 deletions packages/ai-craftsman/src/utils/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import github from "@actions/github";
import * as fs from "node:fs";
import { execSync } from "node:child_process";
import { Octokit } from "@octokit/rest";
import { env } from "../config.js";

const githubToken = process.env["GITHUB_TOKEN"] ?? "";

Expand All @@ -18,22 +19,33 @@ const getOwnerAndRepo = () => {
return { owner: owner?.login ?? "", repo: name ?? "" };
};

const getPullNumberAndCommitId = async () => {
const githubEvent = JSON.parse(await fs.promises.readFile(eventPath, "utf8"));
const pullNumber = github.context.payload.pull_request?.number ?? 0;
const commitId = githubEvent.pull_request.head.sha ?? "";
return { pullNumber, commitId };
const getPullNumber = () => {
let number = github.context.payload.pull_request?.number;
if (number) return number;
number = github.context.issue?.number;
if (number) return number;
throw new Error("Cannot get pull request number.");
};

export const getCommitId = async (): Promise<string> => {
const octokit = getOctokit();
const { owner, repo } = getOwnerAndRepo();
const { data } = await octokit.rest.pulls.get({
owner,
repo,
pull_number: getPullNumber(),
});
return data.head.sha;
};

export const isPrDraft = async (): Promise<boolean> => {
try {
const octokit = getOctokit();
const { owner, repo } = getOwnerAndRepo();
const { pullNumber } = await getPullNumberAndCommitId();
const { data } = await octokit.rest.pulls.get({
owner,
repo,
pull_number: pullNumber,
pull_number: getPullNumber(),
});
return data.draft === true || data.title.startsWith("[WIP]");
} catch (error) {
Expand All @@ -46,16 +58,15 @@ export const getCommentsOrderByCreatedAtDesc = async () => {
try {
const octokit = getOctokit();
const { owner, repo } = getOwnerAndRepo();
const { pullNumber } = await getPullNumberAndCommitId();
const { data: reviews } = await octokit.rest.pulls.listReviewComments({
owner,
repo,
pull_number: pullNumber,
pull_number: getPullNumber(),
});
const { data: comments } = await octokit.rest.issues.listComments({
owner,
repo,
issue_number: pullNumber,
issue_number: getPullNumber(),
});

return [...reviews, ...comments].sort((a, b) => {
Expand Down Expand Up @@ -88,12 +99,11 @@ export const postComment = async (body: string) => {
try {
const octokit = getOctokit();
const { owner, repo } = getOwnerAndRepo();
const { pullNumber, commitId } = await getPullNumberAndCommitId();
await octokit.rest.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body: appendCommitId(body, commitId),
issue_number: getPullNumber(),
body: appendCommitId(body, await getCommitId()),
});
} catch (error) {
console.error(error);
Expand All @@ -109,11 +119,11 @@ export const postReviewComment = async (
try {
const octokit = getOctokit();
const { owner, repo } = getOwnerAndRepo();
const { pullNumber, commitId } = await getPullNumberAndCommitId();
const commitId = await getCommitId();
await octokit.rest.pulls.createReviewComment({
owner,
repo,
pull_number: pullNumber,
pull_number: getPullNumber(),
commit_id: commitId,
path,
start_line: startLine,
Expand All @@ -126,39 +136,31 @@ export const postReviewComment = async (
}
};

export const getBaseRef = async () => {
const ref = github.context.payload.pull_request?.["base"]?.ref;
if (ref) return ref;
export const getRef = async () => {
const base = github.context.payload.pull_request?.["base"]?.sha;
const head = github.context.payload.pull_request?.["head"]?.sha;
if (base && head) return { base, head };
const { owner, repo } = getOwnerAndRepo();
const pullNumber = github.context.payload.issue?.["pull_request"]?.number;
const octokit = getOctokit();
const { data: pullRequest } = await octokit.pulls.get({
owner,
repo,
pull_number: pullNumber,
pull_number: getPullNumber(),
});

return pullRequest.base.ref;
return { base: pullRequest.base.sha, head: pullRequest.head.sha };
};

export interface Diff {
path: string;
diff: string;
}

export const getDiff = (targetBranch: string): Diff[] => {
const currentBranch = execSync("git rev-parse --abbrev-ref HEAD")
.toString()
.trim();

const branch =
currentBranch === targetBranch
? `HEAD~1..HEAD`
: `origin/${targetBranch}..${currentBranch}`;

const filePaths = execSync(
`git --no-pager diff --minimal --name-only ${branch}`
)
export const getDiff = (base: string, head: string): Diff[] => {
const command = `git --no-pager diff --minimal --name-only ${base}..${head}`;
if (env.debug) {
console.debug(`Execute command: ${command}`);
}
const filePaths = execSync(command)
.toString()
.split("\n")
.map((ln) => ln.trim())
Expand All @@ -169,7 +171,7 @@ export const getDiff = (targetBranch: string): Diff[] => {
if (!fs.existsSync(path)) {
continue;
}
const diff = execSync(`git --no-pager diff ${branch} ${path}`)
const diff = execSync(`git --no-pager diff ${base}..${head} ${path}`)
.toString()
.trim();
diffs.push({ path, diff });
Expand Down

0 comments on commit 1e80cf2

Please sign in to comment.