Attempt to make this work

This commit is contained in:
Mark Wylde
2025-05-30 21:00:03 +01:00
parent 80886e1c8e
commit f2f966c77e
15 changed files with 349 additions and 104 deletions

View File

@@ -34,7 +34,9 @@ export class ClaudeExecutor {
private initializeClient() {
if (this.config.useBedrock || this.config.useVertex) {
throw new Error("Bedrock and Vertex AI not supported in simplified implementation");
throw new Error(
"Bedrock and Vertex AI not supported in simplified implementation",
);
}
if (!this.config.apiKey) {
@@ -63,11 +65,17 @@ export class ClaudeExecutor {
private parseTools(): { allowed: string[]; disallowed: string[] } {
const allowed = this.config.allowedTools
? this.config.allowedTools.split(",").map(t => t.trim()).filter(Boolean)
? this.config.allowedTools
.split(",")
.map((t) => t.trim())
.filter(Boolean)
: [];
const disallowed = this.config.disallowedTools
? this.config.disallowedTools.split(",").map(t => t.trim()).filter(Boolean)
? this.config.disallowedTools
.split(",")
.map((t) => t.trim())
.filter(Boolean)
: [];
return { allowed, disallowed };
@@ -92,7 +100,9 @@ export class ClaudeExecutor {
const prompt = await this.readPrompt();
const tools = this.parseTools();
console.log(`Executing Claude with model: ${this.config.model || "claude-3-7-sonnet-20250219"}`);
console.log(
`Executing Claude with model: ${this.config.model || "claude-3-7-sonnet-20250219"}`,
);
console.log(`Allowed tools: ${tools.allowed.join(", ") || "none"}`);
console.log(`Disallowed tools: ${tools.disallowed.join(", ") || "none"}`);
@@ -122,7 +132,7 @@ export class ClaudeExecutor {
};
} catch (error) {
console.error("Claude execution failed:", error);
const executionFile = this.createExecutionLog(null, String(error));
return {
@@ -134,7 +144,9 @@ export class ClaudeExecutor {
}
}
export async function runClaude(config: ClaudeExecutorConfig): Promise<ClaudeExecutorResult> {
export async function runClaude(
config: ClaudeExecutorConfig,
): Promise<ClaudeExecutorResult> {
const executor = new ClaudeExecutor(config);
return await executor.execute();
}
}

View File

@@ -10,8 +10,12 @@ async function main() {
model: process.env.ANTHROPIC_MODEL || process.env.MODEL,
promptFile: process.env.PROMPT_FILE,
prompt: process.env.PROMPT,
maxTurns: process.env.MAX_TURNS ? parseInt(process.env.MAX_TURNS) : undefined,
timeoutMinutes: process.env.TIMEOUT_MINUTES ? parseInt(process.env.TIMEOUT_MINUTES) : 30,
maxTurns: process.env.MAX_TURNS
? parseInt(process.env.MAX_TURNS)
: undefined,
timeoutMinutes: process.env.TIMEOUT_MINUTES
? parseInt(process.env.TIMEOUT_MINUTES)
: 30,
mcpConfig: process.env.MCP_CONFIG,
allowedTools: process.env.ALLOWED_TOOLS,
disallowedTools: process.env.DISALLOWED_TOOLS,
@@ -43,4 +47,4 @@ main().catch((error) => {
console.error("Unhandled error:", error);
core.setFailed(`Unhandled error: ${error}`);
process.exit(1);
});
});

View File

@@ -133,7 +133,68 @@ async function run() {
}
} catch (error) {
console.error("Error checking for changes in branch:", error);
// Don't fail the entire update if we can't check for changes
// For Gitea compatibility, try alternative approach
try {
console.log(
"Trying alternative branch comparison for Gitea compatibility...",
);
// Get the branch info to see if it exists and has commits
const branchResponse = await octokit.rest.repos.getBranch({
owner,
repo,
branch: claudeBranch,
});
// Get base branch info for comparison
const baseResponse = await octokit.rest.repos.getBranch({
owner,
repo,
branch: baseBranch,
});
const branchSha = branchResponse.data.commit.sha;
const baseSha = baseResponse.data.commit.sha;
// If SHAs are different, assume there are changes and add PR link
if (branchSha !== baseSha) {
console.log(
`Branch ${claudeBranch} appears to have changes (different SHA from base)`,
);
const entityType = context.isPR ? "PR" : "Issue";
const prTitle = encodeURIComponent(
`${entityType} #${context.entityNumber}: Changes from Claude`,
);
const prBody = encodeURIComponent(
`This PR addresses ${entityType.toLowerCase()} #${context.entityNumber}\n\nGenerated with [Claude Code](https://claude.ai/code)`,
);
const prUrl = `${serverUrl}/${owner}/${repo}/compare/${baseBranch}...${claudeBranch}?quick_pull=1&title=${prTitle}&body=${prBody}`;
prLink = `\n[Create a PR](${prUrl})`;
} else {
console.log(
`Branch ${claudeBranch} has same SHA as base, no PR link needed`,
);
}
} catch (fallbackError) {
console.error(
"Fallback branch comparison also failed:",
fallbackError,
);
// If all checks fail, still add PR link to be safe
console.log(
"Adding PR link as fallback since we can't determine branch status",
);
const entityType = context.isPR ? "PR" : "Issue";
const prTitle = encodeURIComponent(
`${entityType} #${context.entityNumber}: Changes from Claude`,
);
const prBody = encodeURIComponent(
`This PR addresses ${entityType.toLowerCase()} #${context.entityNumber}\n\nGenerated with [Claude Code](https://claude.ai/code)`,
);
const prUrl = `${serverUrl}/${owner}/${repo}/compare/${baseBranch}...${claudeBranch}?quick_pull=1&title=${prTitle}&body=${prBody}`;
prLink = `\n[Create a PR](${prUrl})`;
}
}
}
}

View File

@@ -9,7 +9,7 @@ export type Octokits = {
export function createOctokit(token: string): Octokits {
return {
rest: new Octokit({
rest: new Octokit({
auth: token,
baseUrl: GITHUB_API_URL,
}),

View File

@@ -45,7 +45,9 @@ export async function fetchGitHubData({
}
// Check if we're in a Gitea environment (no GraphQL support)
const isGitea = process.env.GITHUB_API_URL && !process.env.GITHUB_API_URL.includes('api.github.com');
const isGitea =
process.env.GITHUB_API_URL &&
!process.env.GITHUB_API_URL.includes("api.github.com");
let contextData: GitHubPullRequest | GitHubIssue | null = null;
let comments: GitHubComment[] = [];
@@ -56,7 +58,9 @@ export async function fetchGitHubData({
if (isGitea) {
// Use REST API for Gitea compatibility
if (isPR) {
console.log(`Fetching PR #${prNumber} data using REST API (Gitea mode)`);
console.log(
`Fetching PR #${prNumber} data using REST API (Gitea mode)`,
);
const prResponse = await octokits.rest.pulls.get({
owner,
repo,
@@ -87,7 +91,7 @@ export async function fetchGitHubData({
repo,
issue_number: parseInt(prNumber),
});
comments = commentsResponse.data.map(comment => ({
comments = commentsResponse.data.map((comment) => ({
id: comment.id.toString(),
databaseId: comment.id.toString(),
body: comment.body || "",
@@ -106,7 +110,7 @@ export async function fetchGitHubData({
repo,
pull_number: parseInt(prNumber),
});
changedFiles = filesResponse.data.map(file => ({
changedFiles = filesResponse.data.map((file) => ({
path: file.filename,
additions: file.additions || 0,
deletions: file.deletions || 0,
@@ -119,7 +123,9 @@ export async function fetchGitHubData({
reviewData = { nodes: [] }; // Simplified for Gitea
} else {
console.log(`Fetching issue #${prNumber} data using REST API (Gitea mode)`);
console.log(
`Fetching issue #${prNumber} data using REST API (Gitea mode)`,
);
const issueResponse = await octokits.rest.issues.get({
owner,
repo,
@@ -142,7 +148,7 @@ export async function fetchGitHubData({
repo,
issue_number: parseInt(prNumber),
});
comments = commentsResponse.data.map(comment => ({
comments = commentsResponse.data.map((comment) => ({
id: comment.id.toString(),
databaseId: comment.id.toString(),
body: comment.body || "",

View File

@@ -34,9 +34,49 @@ export async function checkAndDeleteEmptyBranch(
}
} catch (error) {
console.error("Error checking for commits on Claude branch:", error);
// If we can't check, assume the branch has commits to be safe
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
branchLink = `\n[View branch](${branchUrl})`;
// For Gitea compatibility, try alternative approach using branches endpoint
try {
console.log(
"Trying alternative branch comparison for Gitea compatibility...",
);
// Get the branch info to see if it exists and has commits
const branchResponse = await octokit.rest.repos.getBranch({
owner,
repo,
branch: claudeBranch,
});
// Get base branch info for comparison
const baseResponse = await octokit.rest.repos.getBranch({
owner,
repo,
branch: baseBranch,
});
const branchSha = branchResponse.data.commit.sha;
const baseSha = baseResponse.data.commit.sha;
// If SHAs are different, assume there are commits
if (branchSha !== baseSha) {
console.log(
`Branch ${claudeBranch} appears to have commits (different SHA from base)`,
);
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
branchLink = `\n[View branch](${branchUrl})`;
} else {
console.log(
`Branch ${claudeBranch} has same SHA as base, marking for deletion`,
);
shouldDeleteBranch = true;
}
} catch (fallbackError) {
console.error("Fallback branch comparison also failed:", fallbackError);
// If all checks fail, assume the branch has commits to be safe
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
branchLink = `\n[View branch](${branchUrl})`;
}
}
}
@@ -49,9 +89,18 @@ export async function checkAndDeleteEmptyBranch(
ref: `heads/${claudeBranch}`,
});
console.log(`✅ Deleted empty branch: ${claudeBranch}`);
} catch (deleteError) {
} catch (deleteError: any) {
console.error(`Failed to delete branch ${claudeBranch}:`, deleteError);
// Continue even if deletion fails
console.log(`Delete error status: ${deleteError.status}`);
// For Gitea, branch deletion might not be supported via API
if (deleteError.status === 405 || deleteError.status === 404) {
console.log(
"Branch deletion not supported or branch doesn't exist remotely - this is expected for Gitea",
);
}
// Continue even if deletion fails - this is not critical
}
}

View File

@@ -96,7 +96,7 @@ export async function setupBranch(
// Get the SHA of the source branch
// For Gitea, try using the branches endpoint instead of git/refs
let currentSHA: string;
try {
// First try the GitHub-compatible git.getRef approach
const sourceBranchRef = await octokits.rest.git.getRef({
@@ -107,14 +107,16 @@ export async function setupBranch(
currentSHA = sourceBranchRef.data.object.sha;
} catch (gitRefError: any) {
// If git/refs fails (like in Gitea), use the branches endpoint
console.log(`git/refs failed, trying branches endpoint: ${gitRefError.message}`);
console.log(
`git/refs failed, trying branches endpoint: ${gitRefError.message}`,
);
const branchResponse = await octokits.rest.repos.getBranch({
owner,
repo,
branch: sourceBranch,
});
// Gitea uses commit.id instead of commit.sha
currentSHA = branchResponse.data.commit.sha || branchResponse.data.commit.id;
// GitHub and Gitea both use commit.sha
currentSHA = branchResponse.data.commit.sha;
}
console.log(`Current SHA: ${currentSHA}`);
@@ -127,18 +129,22 @@ export async function setupBranch(
ref: `refs/heads/${newBranch}`,
sha: currentSHA,
});
console.log(`Successfully created branch via API: ${newBranch}`);
} catch (createRefError: any) {
// If git/refs creation fails (like in Gitea), that's expected
// We'll create the branch when we push files later
console.log(`git createRef failed (expected for Gitea): ${createRefError.message}`);
// Log the error details but continue - the branch will be created when we push files
console.log(
`git createRef failed (expected for Gitea): ${createRefError.message}`,
);
console.log(`Error status: ${createRefError.status}`);
console.log(`Branch ${newBranch} will be created when files are pushed`);
// For Gitea, we can still proceed since the MCP server will create the branch on first push
// This is actually the preferred method for Gitea
}
console.log(
`Branch setup completed for: ${newBranch}`,
);
console.log(`Branch setup completed for: ${newBranch}`);
// Set outputs for GitHub Actions
core.setOutput("CLAUDE_BRANCH", newBranch);

View File

@@ -2,9 +2,6 @@
import * as core from "@actions/core";
export async function setupGitHubToken(): Promise<string> {
try {
// Check if GitHub token was provided as override
@@ -18,14 +15,16 @@ export async function setupGitHubToken(): Promise<string> {
// Use the standard GITHUB_TOKEN from the workflow environment
const workflowToken = process.env.GITHUB_TOKEN;
if (workflowToken) {
console.log("Using workflow GITHUB_TOKEN for authentication");
core.setOutput("GITHUB_TOKEN", workflowToken);
return workflowToken;
}
throw new Error("No GitHub token available. Please provide a github_token input or ensure GITHUB_TOKEN is available in the workflow environment.");
throw new Error(
"No GitHub token available. Please provide a github_token input or ensure GITHUB_TOKEN is available in the workflow environment.",
);
} catch (error) {
core.setFailed(
`Failed to setup GitHub token: ${error}.\n\nPlease provide a \`github_token\` in the \`with\` section of the action in your workflow yml file, or ensure the workflow has access to the default GITHUB_TOKEN.`,

View File

@@ -84,67 +84,135 @@ export async function downloadCommentImages(
let bodyHtml: string | undefined;
// Get the HTML version based on comment type
// Try with full+json mediaType first (GitHub), fallback to regular API (Gitea)
switch (comment.type) {
case "issue_comment": {
const response = await octokits.rest.issues.getComment({
owner,
repo,
comment_id: parseInt(comment.id),
mediaType: {
format: "full+json",
},
});
bodyHtml = response.data.body_html;
try {
const response = await octokits.rest.issues.getComment({
owner,
repo,
comment_id: parseInt(comment.id),
mediaType: {
format: "full+json",
},
});
bodyHtml = response.data.body_html;
} catch (error: any) {
console.log(
"Full+json format not supported, trying regular API for issue comment",
);
// Fallback for Gitea - use regular API without mediaType
const response = await octokits.rest.issues.getComment({
owner,
repo,
comment_id: parseInt(comment.id),
});
// Gitea might not have body_html, use body instead
bodyHtml = (response.data as any).body_html || response.data.body;
}
break;
}
case "review_comment": {
const response = await octokits.rest.pulls.getReviewComment({
owner,
repo,
comment_id: parseInt(comment.id),
mediaType: {
format: "full+json",
},
});
bodyHtml = response.data.body_html;
try {
const response = await octokits.rest.pulls.getReviewComment({
owner,
repo,
comment_id: parseInt(comment.id),
mediaType: {
format: "full+json",
},
});
bodyHtml = response.data.body_html;
} catch (error: any) {
console.log(
"Full+json format not supported, trying regular API for review comment",
);
// Fallback for Gitea
const response = await octokits.rest.pulls.getReviewComment({
owner,
repo,
comment_id: parseInt(comment.id),
});
bodyHtml = (response.data as any).body_html || response.data.body;
}
break;
}
case "review_body": {
const response = await octokits.rest.pulls.getReview({
owner,
repo,
pull_number: parseInt(comment.pullNumber),
review_id: parseInt(comment.id),
mediaType: {
format: "full+json",
},
});
bodyHtml = response.data.body_html;
try {
const response = await octokits.rest.pulls.getReview({
owner,
repo,
pull_number: parseInt(comment.pullNumber),
review_id: parseInt(comment.id),
mediaType: {
format: "full+json",
},
});
bodyHtml = response.data.body_html;
} catch (error: any) {
console.log(
"Full+json format not supported, trying regular API for review",
);
// Fallback for Gitea
const response = await octokits.rest.pulls.getReview({
owner,
repo,
pull_number: parseInt(comment.pullNumber),
review_id: parseInt(comment.id),
});
bodyHtml = (response.data as any).body_html || response.data.body;
}
break;
}
case "issue_body": {
const response = await octokits.rest.issues.get({
owner,
repo,
issue_number: parseInt(comment.issueNumber),
mediaType: {
format: "full+json",
},
});
bodyHtml = response.data.body_html;
try {
const response = await octokits.rest.issues.get({
owner,
repo,
issue_number: parseInt(comment.issueNumber),
mediaType: {
format: "full+json",
},
});
bodyHtml = response.data.body_html;
} catch (error: any) {
console.log(
"Full+json format not supported, trying regular API for issue",
);
// Fallback for Gitea
const response = await octokits.rest.issues.get({
owner,
repo,
issue_number: parseInt(comment.issueNumber),
});
bodyHtml = (response.data as any).body_html || response.data.body;
}
break;
}
case "pr_body": {
const response = await octokits.rest.pulls.get({
owner,
repo,
pull_number: parseInt(comment.pullNumber),
mediaType: {
format: "full+json",
},
});
// Type here seems to be wrong
bodyHtml = (response.data as any).body_html;
try {
const response = await octokits.rest.pulls.get({
owner,
repo,
pull_number: parseInt(comment.pullNumber),
mediaType: {
format: "full+json",
},
});
// Type here seems to be wrong
bodyHtml = (response.data as any).body_html;
} catch (error: any) {
console.log(
"Full+json format not supported, trying regular API for PR",
);
// Fallback for Gitea
const response = await octokits.rest.pulls.get({
owner,
repo,
pull_number: parseInt(comment.pullNumber),
});
bodyHtml = (response.data as any).body_html || response.data.body;
}
break;
}
}

View File

@@ -13,10 +13,14 @@ export async function checkHumanActor(
githubContext: ParsedGitHubContext,
) {
// Check if we're in a Gitea environment
const isGitea = process.env.GITHUB_API_URL && !process.env.GITHUB_API_URL.includes('api.github.com');
const isGitea =
process.env.GITHUB_API_URL &&
!process.env.GITHUB_API_URL.includes("api.github.com");
if (isGitea) {
console.log(`Detected Gitea environment, skipping actor type validation for: ${githubContext.actor}`);
console.log(
`Detected Gitea environment, skipping actor type validation for: ${githubContext.actor}`,
);
return;
}
@@ -38,9 +42,14 @@ export async function checkHumanActor(
console.log(`Verified human actor: ${githubContext.actor}`);
} catch (error) {
console.warn(`Failed to check actor type for ${githubContext.actor}:`, error);
console.warn(
`Failed to check actor type for ${githubContext.actor}:`,
error,
);
// For compatibility, assume human actor if API call fails
console.log(`Assuming human actor due to API failure: ${githubContext.actor}`);
console.log(
`Assuming human actor due to API failure: ${githubContext.actor}`,
);
}
}

View File

@@ -15,8 +15,10 @@ export async function checkWritePermissions(
const { repository, actor } = context;
// For Gitea compatibility, check if we're in a non-GitHub environment
const isGitea = process.env.GITHUB_API_URL && !process.env.GITHUB_API_URL.includes('api.github.com');
const isGitea =
process.env.GITHUB_API_URL &&
!process.env.GITHUB_API_URL.includes("api.github.com");
if (isGitea) {
core.info(`Detected Gitea environment, assuming actor has permissions`);
return true;

View File

@@ -15,7 +15,9 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
inputs: { assigneeTrigger, triggerPhrase, directPrompt },
} = context;
console.log(`Checking trigger: event=${context.eventName}, action=${context.eventAction}, phrase='${triggerPhrase}', assignee='${assigneeTrigger}', direct='${directPrompt}'`);
console.log(
`Checking trigger: event=${context.eventName}, action=${context.eventAction}, phrase='${triggerPhrase}', assignee='${assigneeTrigger}', direct='${directPrompt}'`,
);
// If direct prompt is provided, always trigger
if (directPrompt) {
@@ -29,7 +31,9 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
let triggerUser = assigneeTrigger?.replace(/^@/, "") || "";
const assigneeUsername = context.payload.issue.assignee?.login || "";
console.log(`Checking assignee trigger: user='${triggerUser}', assignee='${assigneeUsername}'`);
console.log(
`Checking assignee trigger: user='${triggerUser}', assignee='${assigneeUsername}'`,
);
if (triggerUser && assigneeUsername === triggerUser) {
console.log(`Issue assigned to trigger user '${triggerUser}'`);