@computesdk/cli 2.5.3 → 2.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -67,6 +67,7 @@ function getProviderStatus() {
67
67
  // src/actions.ts
68
68
  import pc2 from "picocolors";
69
69
  import { mkdirSync, readFileSync, writeFileSync } from "fs";
70
+ import { spawnSync } from "child_process";
70
71
 
71
72
  // src/settings.ts
72
73
  import pc from "picocolors";
@@ -183,6 +184,15 @@ var ActionsClient = class {
183
184
  });
184
185
  return this.parse(res);
185
186
  }
187
+ /** POST a raw text body (e.g. a unified diff to `/api/v1/actions/patches`). */
188
+ async postText(path, body, contentType) {
189
+ const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {
190
+ method: "POST",
191
+ headers: { ...this.headers(), "content-type": contentType },
192
+ body
193
+ });
194
+ return this.parse(res);
195
+ }
186
196
  async put(path, body = {}) {
187
197
  const res = await this.fetchImpl(`${this.auth.baseUrl}${path}`, {
188
198
  method: "PUT",
@@ -1046,9 +1056,69 @@ function dispatchBody(workflow, opts) {
1046
1056
  provider: opts.provider,
1047
1057
  ...opts.providerRegion !== void 0 && { providerRegion: opts.providerRegion }
1048
1058
  },
1049
- ...maxPrice !== void 0 && maxPrice
1059
+ ...maxPrice !== void 0 && maxPrice,
1060
+ ...opts.patchId !== void 0 && { patchId: opts.patchId }
1050
1061
  };
1051
1062
  }
1063
+ var runGit = (args) => {
1064
+ const r = spawnSync("git", args, { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
1065
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "" };
1066
+ };
1067
+ function remoteNamesRepo(remote, repo) {
1068
+ const normalized = remote.trim().replace(/\.git$/, "").replace(/\/+$/, "");
1069
+ return normalized.toLowerCase().endsWith(`/${repo.toLowerCase()}`) || normalized.toLowerCase().endsWith(`:${repo.toLowerCase()}`);
1070
+ }
1071
+ function currentBranch(git = runGit) {
1072
+ const r = git(["rev-parse", "--abbrev-ref", "HEAD"]);
1073
+ if (r.status !== 0) return null;
1074
+ const name = r.stdout.trim();
1075
+ return name === "" || name === "HEAD" ? null : name;
1076
+ }
1077
+ function hasLocalChanges(git = runGit) {
1078
+ const r = git(["status", "--porcelain", "--untracked-files=all"]);
1079
+ return r.status === 0 && r.stdout.trim() !== "";
1080
+ }
1081
+ function localChangesPatch(ref, git = runGit, repo) {
1082
+ const branch = ref.replace(/^refs\/heads\//, "");
1083
+ const base = `origin/${branch}`;
1084
+ if (repo !== void 0) {
1085
+ const remote = git(["remote", "get-url", "origin"]).stdout.trim();
1086
+ if (!remoteNamesRepo(remote, repo)) {
1087
+ throw new ActionsCliError(
1088
+ "invalid_argument",
1089
+ `--with-changes sends this checkout's changes, but its origin (${remote || "none"}) is not ${repo}. Run it from a checkout of ${repo}.`
1090
+ );
1091
+ }
1092
+ }
1093
+ const fetched = git(["fetch", "--quiet", "origin", branch]);
1094
+ if (fetched.status !== 0) {
1095
+ throw new ActionsCliError("invalid_argument", `git fetch origin ${branch} failed: ${fetched.stderr.trim() || "is the branch pushed?"}`);
1096
+ }
1097
+ if (git(["rev-parse", "--verify", "--quiet", `${base}^{commit}`]).status !== 0) {
1098
+ throw new ActionsCliError(
1099
+ "invalid_argument",
1100
+ `--with-changes diffs against ${base}, which does not exist locally. Push the branch (or run \`git fetch origin ${branch}\`), or pass --ref <branch that exists on origin>.`
1101
+ );
1102
+ }
1103
+ const tracked = git(["diff", "--no-color", "--no-ext-diff", "--src-prefix=a/", "--dst-prefix=b/", base, "--"]);
1104
+ if (tracked.status !== 0) {
1105
+ throw new ActionsCliError("invalid_argument", `git diff against ${base} failed: ${tracked.stderr.trim()}`);
1106
+ }
1107
+ const parts = [tracked.stdout];
1108
+ const topLevel = git(["rev-parse", "--show-toplevel"]).stdout.replace(/\r?\n$/, "");
1109
+ const untracked = git(["-C", topLevel, "ls-files", "--others", "--exclude-standard", "-z"]);
1110
+ for (const file of untracked.stdout.split("\0").filter((f) => f !== "")) {
1111
+ const d = git(["-C", topLevel, "diff", "--no-color", "--no-ext-diff", "--no-index", "--src-prefix=a/", "--dst-prefix=b/", "--", "/dev/null", file]);
1112
+ if (d.stdout !== "") parts.push(d.stdout);
1113
+ }
1114
+ const patch = parts.filter((p2) => p2 !== "").join("");
1115
+ if (patch.trim() === "") return null;
1116
+ if (patch.includes("\0") || /^Binary files .* differ$/m.test(patch)) {
1117
+ throw new ActionsCliError("invalid_argument", "Local changes include a binary file; --with-changes sends text diffs only.");
1118
+ }
1119
+ const files = patch.match(/^\+\+\+ /gm)?.length ?? 0;
1120
+ return { patch, files, base };
1121
+ }
1052
1122
  function maxPriceFields(maxBid, maxBidPer) {
1053
1123
  if (maxBidPer !== void 0 && maxBid === void 0) {
1054
1124
  throw new ActionsCliError("invalid_argument", "--max-bid-per requires --max-bid.");
@@ -1138,7 +1208,7 @@ function registerActionsCommands(program2) {
1138
1208
  const actions = program2.command("actions").alias("ci").description("Drive the benchmarks-platform Actions API").configureOutput({ outputError: usageErrorOutput });
1139
1209
  const common = (cmd) => cmd.option("--api-key <key>", "API key (default: $COMPUTE_API_KEY)").option("--base-url <url>", "API base URL (default: https://platform.computesdk.com)").option("--org <slug>", "organization slug for this command (or $COMPUTE_ORG)").option("--allow-untrusted-host", "send an explicit --api-key/env key to a non-computesdk, non-localhost --base-url (stored login credentials are never sent)").option("--json", "print machine-readable JSON");
1140
1210
  common(
1141
- actions.command("dispatch").description("Dispatch a workflow_dispatch run (or any workflow with --manual)").argument("<repo>", "repository in owner/repo format").requiredOption("--workflow <path|name>", "workflow path or name").option("--ref <ref>", "git ref to run (default: the workflow's first watched ref)").option("--inputs <pairs...>", "workflow inputs as key=value (workflow_dispatch inputs only)").option("--manual", "run a workflow even if it does not declare workflow_dispatch (such runs take no --inputs)").option("--provider <id>", "place the run on one provider (e.g. namespace, vercel:sfo1) instead of the org provider order").option("--provider-region <region>", "region for --provider (same as --provider <id>:<region>)").option("--max-bid <usd>", "max price per vCPU for a market fill (e.g. 0.12); unfilled jobs fall through to the next provider").option("--max-bid-per <unit>", "time unit --max-bid is priced in: second, minute, or hour (default: second)")
1211
+ actions.command("dispatch").description("Dispatch a workflow_dispatch run (or any workflow with --manual)").argument("<repo>", "repository in owner/repo format").requiredOption("--workflow <path|name>", "workflow path or name").option("--ref <ref>", "git ref to run (default: the workflow's first watched ref)").option("--inputs <pairs...>", "workflow inputs as key=value (workflow_dispatch inputs only)").option("--manual", "run a workflow even if it does not declare workflow_dispatch (such runs take no --inputs)").option("--provider <id>", "place the run on one provider (e.g. namespace, vercel:sfo1) instead of the org provider order").option("--provider-region <region>", "region for --provider (same as --provider <id>:<region>)").option("--max-bid <usd>", "max price per vCPU for a market fill (e.g. 0.12); unfilled jobs fall through to the next provider").option("--max-bid-per <unit>", "time unit --max-bid is priced in: second, minute, or hour (default: second)").option("--with-changes", "run your local changes: everything the working tree has beyond origin/<ref> is sent as a diff and applied after checkout (default --ref: the current branch)")
1142
1212
  ).action(async (repo, opts) => {
1143
1213
  try {
1144
1214
  const c = await client(opts);
@@ -1154,16 +1224,35 @@ function registerActionsCommands(program2) {
1154
1224
  `No workflow "${opts.workflow}" in ${repo}. Available: ${choices}`
1155
1225
  );
1156
1226
  }
1157
- const body = dispatchBody(workflow, opts);
1227
+ let patch;
1228
+ let ref = opts.ref;
1229
+ if (opts.withChanges) {
1230
+ ref ?? (ref = currentBranch() ?? void 0);
1231
+ if (!ref) throw new ActionsCliError("invalid_argument", "--with-changes needs a branch: check one out or pass --ref.");
1232
+ const local = localChangesPatch(ref, void 0, repo);
1233
+ if (local) {
1234
+ const uploaded = await c.postText(
1235
+ "/api/v1/actions/patches",
1236
+ local.patch,
1237
+ "text/x-patch; charset=utf-8"
1238
+ );
1239
+ patch = { patchId: uploaded.patchId, files: uploaded.files, bytes: uploaded.bytes };
1240
+ } else if (!opts.json) {
1241
+ console.error(pc2.dim(`no local changes beyond origin/${ref.replace(/^refs\/heads\//, "")}; running the ref as is`));
1242
+ }
1243
+ } else if (!opts.json && hasLocalChanges()) {
1244
+ console.error(pc2.dim("You have uncommitted changes. Add --with-changes to run them."));
1245
+ }
1246
+ const body = dispatchBody(workflow, { ...opts, ref, patchId: patch?.patchId });
1158
1247
  const result = await c.post(
1159
1248
  "/api/v1/actions/dispatch",
1160
1249
  body
1161
1250
  );
1162
1251
  const org2 = await c.org();
1163
1252
  const url = `${c.baseUrl}/${org2.slug}/actions/runs/${result.runId}`;
1164
- output(opts, { ...result, url }, (r) => {
1253
+ output(opts, { ...result, url, ...patch && { patch } }, (r) => {
1165
1254
  console.log(`${r.created ? "dispatched" : "already running"} ${pc2.cyan(r.runId)}`);
1166
- console.log(`sha: ${r.headSha}`);
1255
+ console.log(`sha: ${r.headSha}${r.patch ? ` + ${r.patch.files} changed file${r.patch.files === 1 ? "" : "s"} (uncommitted)` : ""}`);
1167
1256
  console.log(`url: ${r.url}`);
1168
1257
  });
1169
1258
  } catch (e) {