File size: 6,226 Bytes
fd2c364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env node

import { existsSync, readFileSync, realpathSync } from "node:fs";
import { dirname, isAbsolute, relative, resolve } from "node:path";

const DEFAULT_MARKER = "<!-- agent-canvas-live-e2e-report -->";
const API_ROOT = process.env.GITHUB_API_URL ?? "https://api.github.com";

function parseArgs(argv) {
  const args = {};
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index];
    if (!arg.startsWith("--")) {
      continue;
    }

    const [rawKey, inlineValue] = arg.slice(2).split("=", 2);
    const key = rawKey.replaceAll("-", "_");
    if (inlineValue !== undefined) {
      args[key] = inlineValue;
      continue;
    }

    const next = argv[index + 1];
    if (next && !next.startsWith("--")) {
      args[key] = next;
      index += 1;
    } else {
      args[key] = "";
    }
  }
  return args;
}

function requireValue(name, value) {
  if (!value) {
    throw new Error(`Missing required value: ${name}`);
  }
  return value;
}

function assertWithinCwd(label, path) {
  const relativePath = relative(realpathSync(resolve(".")), path);
  if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
    throw new Error(`${label} must be within the current working directory.`);
  }
}

function nearestExistingPath(path) {
  let currentPath = path;
  while (!existsSync(currentPath)) {
    const parentPath = dirname(currentPath);
    if (parentPath === currentPath) {
      throw new Error(`No existing parent found for ${path}`);
    }
    currentPath = parentPath;
  }
  return currentPath;
}

function resolveWithinCwd(label, filePath, options = {}) {
  const resolvedPath = resolve(filePath);
  if (existsSync(resolvedPath)) {
    assertWithinCwd(label, realpathSync(resolvedPath));
    return resolvedPath;
  }

  if (options.mustExist) {
    throw new Error(`${label} does not exist: ${resolvedPath}`);
  }

  const existingParent = nearestExistingPath(dirname(resolvedPath));
  const checkedPath = resolve(
    realpathSync(existingParent),
    relative(existingParent, resolvedPath),
  );
  assertWithinCwd(label, checkedPath);
  return resolvedPath;
}

function validateRepo(repo) {
  if (
    !/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?\/[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/.test(
      repo,
    )
  ) {
    throw new Error(`Invalid repo format: ${repo}`);
  }
  return repo;
}

function validateIssueNumber(issueNumber) {
  if (!/^\d+$/.test(String(issueNumber))) {
    throw new Error(`Invalid issue number: ${issueNumber}`);
  }
  return String(issueNumber);
}

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
}

function retryDelayMs(attempt, response) {
  const retryAfter = response.headers.get("retry-after");
  if (retryAfter && /^\d+$/.test(retryAfter)) {
    return Number(retryAfter) * 1000;
  }
  return 1000 * 2 ** attempt;
}

function parseGitHubPayload(method, path, status, text) {
  if (!text) {
    return null;
  }
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error(
      `GitHub API ${method} ${path} returned invalid JSON with status ${status}: ${text.slice(
        0,
        500,
      )}`,
    );
  }
}

async function githubRequest(method, path, token, body) {
  const retryableStatuses = new Set([429, 502, 503, 504]);

  for (let attempt = 0; attempt < 5; attempt += 1) {
    const response = await fetch(`${API_ROOT}${path}`, {
      method,
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28",
        ...(body === undefined ? {} : { "Content-Type": "application/json" }),
      },
      body: body === undefined ? undefined : JSON.stringify(body),
    });

    const text = await response.text();
    if (!response.ok && retryableStatuses.has(response.status) && attempt < 4) {
      await sleep(retryDelayMs(attempt, response));
      continue;
    }

    const payload = parseGitHubPayload(method, path, response.status, text);
    if (!response.ok) {
      throw new Error(
        `GitHub API ${method} ${path} failed with ${response.status}: ${text}`,
      );
    }
    return payload;
  }

  throw new Error(`GitHub API ${method} ${path} failed after retries.`);
}

async function listIssueComments(repo, issueNumber, token) {
  const comments = [];
  for (let page = 1; page <= 10; page += 1) {
    const batch = await githubRequest(
      "GET",
      `/repos/${repo}/issues/${issueNumber}/comments?per_page=100&page=${page}`,
      token,
    );
    comments.push(...batch);
    if (batch.length < 100) {
      break;
    }
  }
  return comments;
}

async function main() {
  const args = parseArgs(process.argv.slice(2));
  const issueNumber =
    args.issue_number ??
    process.env.PR_NUMBER ??
    process.env.ISSUE_NUMBER ??
    "";

  if (!issueNumber) {
    console.log("Skipping PR comment because no PR number was provided.");
    return;
  }

  const repo = validateRepo(
    requireValue("repo", args.repo ?? process.env.GITHUB_REPOSITORY),
  );
  const validatedIssueNumber = validateIssueNumber(issueNumber);
  const token = requireValue(
    "token",
    args.token ?? process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN,
  );
  const marker = args.marker ?? DEFAULT_MARKER;
  const bodyFile = resolveWithinCwd(
    "body-file",
    requireValue("body-file", args.body_file),
    { mustExist: true },
  );
  let body = readFileSync(bodyFile, "utf8");

  if (!body.includes(marker)) {
    body = `${marker}\n${body}`;
  }

  const comments = await listIssueComments(repo, validatedIssueNumber, token);
  const existing = comments.find((comment) => comment.body?.includes(marker));

  if (existing) {
    await githubRequest(
      "PATCH",
      `/repos/${repo}/issues/comments/${existing.id}`,
      token,
      { body },
    );
    console.log(`Updated PR comment ${existing.id}.`);
    return;
  }

  const created = await githubRequest(
    "POST",
    `/repos/${repo}/issues/${validatedIssueNumber}/comments`,
    token,
    { body },
  );
  console.log(`Created PR comment ${created.id}.`);
}

main().catch((error) => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exit(1);
});