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

Fix issues #26

Merged
merged 10 commits into from
Jan 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fix-resolve-ref-2024-0-29-18-16-6.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chronus/chronus": patch
---

Fix various issues(Missing depedencies on globby), resolving correct upstream branch
5 changes: 5 additions & 0 deletions .changeset/fix-resolve-ref-2024-0-29-19-30-13.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@chronus/github-pr-commenter": patch
---

Allow to run this not in github actions(Azure pipelines or custom ci system)
3 changes: 3 additions & 0 deletions .github/workflows/changes.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ on:
pull_request:
branches: ["main"]

permissions:
pull-requests: write

jobs:
changes:
if: ${{ github.actor != 'dependabot[bot]' }}
Expand Down
2 changes: 1 addition & 1 deletion packages/chronus/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"@changesets/apply-release-plan": "^7.0.0",
"@changesets/parse": "^0.4.0",
"@changesets/write": "^0.3.0",
"globby": "^14.0.0",
"js-yaml": "^4.1.0",
"micromatch": "^4.0.5",
"picocolors": "^1.0.0",
Expand All @@ -60,7 +61,6 @@
"@typescript-eslint/parser": "^6.10.0",
"cross-spawn": "^7.0.3",
"eslint": "^8.56.0",
"globby": "^14.0.0",
"rimraf": "^5.0.5",
"typescript": "^5.3.3"
}
Expand Down
5 changes: 4 additions & 1 deletion packages/chronus/src/source-control/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,10 +158,13 @@ export function createGitSourceControl(repositoryPath: string): GitRepository {
}

async function listChangedFilesFromBase(baseBranch: string) {
let remoteBase: string;
let remoteBase: string | undefined;
try {
remoteBase = await findRemoteForBranch(baseBranch);
} catch {
// ignore
}
if (remoteBase === undefined) {
remoteBase = `refs/remotes/origin/${baseBranch}`;
}
return await listChangedFilesSince(remoteBase);
Expand Down
117 changes: 98 additions & 19 deletions packages/github-pr-commenter/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,55 +5,136 @@ try {
} catch {
// package only present in dev.
}
import { context, getOctokit } from "@actions/github";
import { getOctokit, context as githubActionContext } from "@actions/github";
import type { ChangeStatus, PackageStatus } from "@chronus/chronus";
import { getWorkspaceStatus } from "@chronus/chronus";

interface Context {
repoName: string;
repoOwner: string;
prNumber: number;
headRef: string;
prTitle?: string;
}

function getGithubContext(): Context | undefined {
// eslint-disable-next-line no-console
console.log("Github context", githubActionContext);

if (githubActionContext === undefined) {
return undefined;
}
if (githubActionContext.payload.pull_request === undefined) {
throw new Error("Cannot run outside of a pull request");
}
return {
repoName: githubActionContext.repo.repo,
repoOwner: githubActionContext.repo.owner,
prNumber: githubActionContext.issue.number,
headRef: githubActionContext.payload.pull_request.head.ref,
prTitle: githubActionContext.payload.pull_request.title,
};
}

function getAzureDevopsContext(): Context | undefined {
const repo = process.env["BUILD_REPOSITORY_NAME"];
if (repo === undefined) {
return undefined;
}
const [repoOwner, repoName] = repo.split("/", 2);
const values = {
prNumber: process.env["SYSTEM_PULLREQUEST_PULLREQUESTNUMBER"],
repoName,
repoOwner,
headRef: process.env["SYSTEM_PULLREQUEST_SOURCEBRANCH"],
};

return values.prNumber && values.repoName && values.repoOwner && values.headRef ? (values as any) : undefined;
}

function getGenericContext(): Context | undefined {
const values = {
prNumber: process.env["GH_PR_NUMBER"],
repoName: process.env["GH_REPO_OWNER"],
repoOwner: process.env["GH_REPO_REPO"],
headRef: process.env["GH_PR_HEAD_REF"],
prTitle: process.env["GH_PR_TITLE"],
};

return values.prNumber && values.repoName && values.repoOwner && values.headRef ? (values as any) : undefined;
}

const magicString = "<!--chronus-github-change-commenter-->";
async function main() {
const token = process.env.GITHUB_TOKEN;
if (!token) {
throw new Error("GITHUB_TOKEN environment variable is not set");
}
const context = getGithubContext() ?? getAzureDevopsContext() ?? getGenericContext();
// eslint-disable-next-line no-console
console.log("Resolved context", context);
if (!context?.prNumber) {
throw new Error("PR number not found. Set $GH_PR_NUMBER");
}

if (context?.repoOwner === undefined) {
throw new Error("PR number not found. Set $GH_REPO_OWNER");
}
if (!context?.repoName) {
throw new Error("PR number not found. Set $GH_REPO_REPO");
}
if (!context?.headRef) {
throw new Error("PR number not found. Set $GH_PR_HEAD_REF");
}

const github = getOctokit(token);

const pr = await github.rest.pulls.get({
pull_number: context.prNumber,
owner: context.repoOwner,
repo: context.repoName,
});
const status = await getWorkspaceStatus(process.cwd());

const content = resolveComment(status);
if (!context.prTitle) {
context.prTitle = pr.data.title;
}

const content = resolveComment(status, pr.data, context as any);

const comments = await github.rest.issues.listComments({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.prNumber,
owner: context.repoOwner,
repo: context.repoName,
});
const existingComment = comments.data.find((x) => x.body?.includes(magicString));

if (existingComment) {
github.rest.issues.updateComment({
comment_id: existingComment.id,
owner: context.repo.owner,
repo: context.repo.repo,
owner: context.repoOwner,
repo: context.repoName,
body: content,
});
} else {
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.prNumber,
owner: context.repoOwner,
repo: context.repoName,
body: content,
});
}
}

function resolveComment(status: ChangeStatus): string {
function resolveComment(status: ChangeStatus, pr: any, context: Required<Context>): string {
const undocummentedPackages = [...status.packages.values()].filter((x) => x.changed && !x.documented);
const documentedPackages = [...status.packages.values()].filter((x) => x.changed && x.documented);

const content = [magicString];

if (undocummentedPackages.length > 0) {
content.push(
`:x: There is undocummented changes. Run \`chronus add\` to add a changeset or [click here](${addChangeSetUrl(undocummentedPackages)}).`,
`:x: There is undocummented changes. Run \`chronus add\` to add a changeset or [click here](${addChangeSetUrl(undocummentedPackages, pr, context)}).`,
);
content.push("");
content.push(`**The following packages have changes but are not documented.**`);
Expand All @@ -76,14 +157,12 @@ function resolveComment(status: ChangeStatus): string {
return content.join("\n");
}

function addChangeSetUrl(undocummentedPackages: PackageStatus[]): string {
if (context.payload.pull_request === undefined) throw new Error("Not a pull request");
const repoUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}`;
function addChangeSetUrl(undocummentedPackages: PackageStatus[], pr: any, context: Required<Context>): string {
const repoUrl = pr.head.repo.html_url;

const ref = context.payload.pull_request.head.ref;
const date = new Date();
const id = [
ref.replace(/\//g, "-"),
context.headRef.replace(/\//g, "-"),
date.getFullYear(),
date.getMonth(),
date.getDate(),
Expand All @@ -92,8 +171,8 @@ function addChangeSetUrl(undocummentedPackages: PackageStatus[]): string {
date.getSeconds(),
].join("-");
const filename = `.changeset/${id}.md`;
const content = renderChangesetTemplate(undocummentedPackages, context.payload.pull_request.title);
return `${repoUrl}/new/${ref}?filename=${filename}&value=${encodeURIComponent(content)}`;
const content = renderChangesetTemplate(undocummentedPackages, context.prTitle);
return `${repoUrl}/new/${context.headRef}?filename=${filename}&value=${encodeURIComponent(content)}`;
}

function renderChangesetTemplate(undocummentedPackages: PackageStatus[], title: string): string {
Expand Down
16 changes: 8 additions & 8 deletions pnpm-lock.yaml

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

Loading