All files / packages/sds-release-manager/src/services gitcore-service.ts

94.44% Statements 153/162
90.32% Branches 112/124
100% Functions 33/33
94.37% Lines 151/160

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550                                                                                                                                                                                              10x                       49x 49x 49x         47x       45x           2x 2x     2x 2x 1x   1x   1x           7x   27x   7x 7x 7x 1x     6x     7x                 9x   27x   9x     9x 9x           3x     6x 6x           6x               2x     4x 4x 1x   3x 3x 1x     2x                     3x 3x 3x 1x   2x         1x 1x                   1x 1x           1x 1x   1x 1x 2x         1x 1x 1x   1x         3x 3x 3x 3x 1x   2x   1x 1x               2x 2x 2x 2x     3x   1x   2x   1x             4x 4x 4x     4x 4x         1x   3x   1x 1x                       3x 3x 3x     3x               3x 3x 1x   2x   1x 1x               3x 3x 3x     3x 3x 1x   2x   1x 1x               4x 4x 4x 2x 1x   1x   3x 1x   2x           1x             1x             3x 3x 3x                                   3x 3x     3x 1x   2x 2x             1x   1x   1x     2x 1x     1x 1x               3x 3x                           3x 2x   3x 2x   3x 3x         1x             1x 1x 1x                 1x 1x 1x 1x                 1x 1x 1x   1x                           34x       3x     3x     3x    
import { execa } from 'execa';
import type { Logger } from '../utils/logger.js';
import {
  applyPinToCatalogFile,
  applyPinToVersionFile,
  GITCORE_PIN_CATALOG_PATH,
  GITCORE_PIN_VERSION_PATH,
  parsePinBlock,
  previewPinDiff,
  type ApplyPinUpdateInput,
  type PinBlock,
} from '../utils/pin-files.js';
import { DEFAULT_GITCORE_HOST } from '../config.js';
 
export type GitcoreFile = {
  path: string;
  content: string;
  sha: string;
};
 
export type GitcoreFileBuffer = {
  path: string;
  content: Buffer;
  sha: string;
  apiSize: number;
  blobSize: number;
};
 
export type CommitFilesInput = {
  repo: string;
  baseBranch: string;
  newBranch: string;
  message: string;
  files: Array<{ path: string; content: string }>;
};
 
export type CreatePullRequestInput = {
  repo: string;
  base: string;
  head: string;
  title: string;
  body: string;
  assignees?: string[];
  labels?: string[];
};
 
export type OpenPullRequest = {
  url: string;
  assignees: string[];
  labels: string[];
  title: string;
};
 
export type PreparedPinUpdate = {
  oldPin: PinBlock;
  versionPath: string;
  catalogPath: string;
  versionOld: string;
  versionNew: string;
  catalogOld: string;
  catalogNew: string;
  diff: string;
};
 
export interface IGitCoreService {
  getAuthenticatedLogin(): Promise<string>;
  getFile(repo: string, path: string, ref: string): Promise<GitcoreFile>;
  getFileBuffer(repo: string, path: string, ref: string): Promise<GitcoreFileBuffer>;
  getRefSha(repo: string, branch: string): Promise<string>;
  createBranch(repo: string, newBranch: string, fromSha: string): Promise<void>;
  commitFiles(input: CommitFilesInput): Promise<string>;
  getCommitTreeSha(repo: string, commitSha: string): Promise<string>;
  getCommitParents(repo: string, commitSha: string): Promise<string[]>;
  createBlobBase64(repo: string, content: Buffer): Promise<string>;
  createTree(
    repo: string,
    baseTreeSha: string,
    entries: Array<{ path: string; sha: string }>,
  ): Promise<string>;
  createCommit(repo: string, message: string, treeSha: string, parentSha: string): Promise<string>;
  getBranchHeadSha(repo: string, branch: string): Promise<string | null>;
  createRef(repo: string, branch: string, commitSha: string): Promise<void>;
  updateRef(repo: string, branch: string, commitSha: string): Promise<void>;
  findOpenPullRequest(repo: string, base: string, head: string): Promise<OpenPullRequest | null>;
  createPullRequest(input: CreatePullRequestInput): Promise<string>;
  addPullRequestComment(repo: string, prUrl: string, body: string): Promise<void>;
  readSldsScsPin(repo: string, targetBranch: string): Promise<PinBlock>;
  preparePinUpdate(
    repo: string,
    targetBranch: string,
    update: Pick<ApplyPinUpdateInput, 'newVersion' | 'newSha256' | 'newSha1'>,
  ): Promise<PreparedPinUpdate>;
}
 
function coreRepo(releaseId: string): string {
  return `core-2206/core-${releaseId}-public`;
}
 
export { coreRepo };
 
/**
 * Gitcore access for release commands: file, ref, and commit reads; Git Data API writes;
 * and pull requests through the `gh` CLI with GH_HOST. No Workspace checkout is needed.
 */
// Read / write gitcore repos via `gh api` (no Workspace checkout).
export class GitCoreService implements IGitCoreService {
  constructor(
    private readonly logger: Logger,
    private readonly gitcoreHost = DEFAULT_GITCORE_HOST,
    private readonly execaFn: typeof execa = execa,
  ) {}
 
  // Run gitcore API requests with the configured host and optional request body.
  private async ghApi(args: string[], options: { input?: string } = {}): Promise<string> {
    const { stdout } = await this.execaFn('gh', ['api', ...args], {
      env: { ...process.env, GH_HOST: this.gitcoreHost },
      input: options.input,
    });
    return stdout;
  }
 
  // Reads: identify the signed-in user for release pull request metadata.
  async getAuthenticatedLogin(): Promise<string> {
    // Use fixed errors rather than passing through CLI output that may contain tokens or response bodies.
    try {
      const { stdout } = await this.execaFn('gh', ['api', 'user', '--jq', '.login'], {
        env: { ...process.env, GH_HOST: this.gitcoreHost },
      });
      const login = stdout.trim();
      if (!login) {
        throw new Error('Could not resolve authenticated gitcore user');
      }
      return login;
    } catch {
      throw new Error('Could not resolve authenticated gitcore user');
    }
  }
 
  // Reads: fetch a text file at a chosen ref for pin inspection and updates.
  async getFile(repo: string, path: string, ref: string): Promise<GitcoreFile> {
    const encodedPath = path
      .split('/')
      .map((p) => encodeURIComponent(p))
      .join('/');
    const raw = await this.ghApi([`repos/${repo}/contents/${encodedPath}?ref=${encodeURIComponent(ref)}`]);
    const json = JSON.parse(raw) as { content?: string; encoding?: string; sha?: string; path?: string };
    if (!json.content || !json.sha) {
      throw new Error(`Unexpected contents response for ${repo}:${path}@${ref}`);
    }
    const content =
      json.encoding === 'base64'
        ? Buffer.from(json.content.replace(/\n/g, ''), 'base64').toString('utf8')
        : json.content;
    return { path: json.path ?? path, content, sha: json.sha };
  }
 
  /**
   * Reads: fetch Contents metadata, then the Git blob to preserve exact bytes.
   * apiSize is the hydrated file size; blobSize is the stored blob size, which can
   * be the pointer size for a large file stored elsewhere.
   */
  async getFileBuffer(repo: string, path: string, ref: string): Promise<GitcoreFileBuffer> {
    const encodedPath = path
      .split('/')
      .map((part) => encodeURIComponent(part))
      .join('/');
    const metadataRaw = await this.ghApi([
      `repos/${repo}/contents/${encodedPath}?ref=${encodeURIComponent(ref)}`,
    ]);
    const metadata = JSON.parse(metadataRaw) as { path?: string; sha?: string; size?: number };
    if (
      typeof metadata.sha !== 'string' ||
      (metadata.path !== undefined && typeof metadata.path !== 'string') ||
      !Number.isSafeInteger(metadata.size) ||
      (metadata.size ?? -1) < 0
    ) {
      throw new Error(`Unexpected contents response for ${repo}:${path}@${ref}`);
    }
 
    const blobRaw = await this.ghApi([`repos/${repo}/git/blobs/${encodeURIComponent(metadata.sha)}`]);
    const blob = JSON.parse(blobRaw) as {
      content?: string;
      encoding?: string;
      sha?: string;
      size?: number;
    };
    if (
      typeof blob.content !== 'string' ||
      blob.encoding !== 'base64' ||
      typeof blob.sha !== 'string' ||
      blob.sha !== metadata.sha ||
      !Number.isSafeInteger(blob.size) ||
      (blob.size ?? -1) < 0
    ) {
      throw new Error(`Unexpected blob response for ${repo}:${path}@${ref}`);
    }
 
    const encodedContent = blob.content.replace(/\n/g, '');
    if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encodedContent)) {
      throw new Error(`Unexpected blob response for ${repo}:${path}@${ref}`);
    }
    const content = Buffer.from(encodedContent, 'base64');
    if (content.length !== blob.size) {
      throw new Error(`Git blob size mismatch for ${repo}:${path}@${ref}`);
    }
 
    return {
      path: metadata.path ?? path,
      sha: blob.sha,
      apiSize: metadata.size as number,
      blobSize: blob.size as number,
      content,
    };
  }
 
  // Reads: resolve the base branch commit before building a release commit.
  async getRefSha(repo: string, branch: string): Promise<string> {
    const raw = await this.ghApi([`repos/${repo}/git/ref/heads/${branch}`]);
    const json = JSON.parse(raw) as { object?: { sha?: string } };
    if (!json.object?.sha) {
      throw new Error(`Could not resolve ref heads/${branch} on ${repo}`);
    }
    return json.object.sha;
  }
 
  // Git Data writes: start the pin-update branch at the chosen base commit.
  async createBranch(repo: string, newBranch: string, fromSha: string): Promise<void> {
    this.logger.step(`Create branch ${newBranch} on ${repo}`);
    await this.ghApi([`--method`, `POST`, `repos/${repo}/git/refs`, `--input`, `-`], {
      input: JSON.stringify({
        ref: `refs/heads/${newBranch}`,
        sha: fromSha,
      }),
    });
  }
 
  // Pin update: keep the bump-bazel-pin branch and its file changes in one call.
  async commitFiles(input: CommitFilesInput): Promise<string> {
    const { repo, baseBranch, newBranch, message, files } = input;
    this.logger.step(`Commit ${files.length} file(s) on ${newBranch}`);
 
    // Compose the shared Git Data API primitives: resolve the base, create the
    // branch at it, build blobs + tree + commit, then move the branch ref to the
    // new commit. Blobs are byte-exact (base64); for UTF-8 text this yields the
    // same blob SHA as a utf-8 blob.
    const baseSha = await this.getRefSha(repo, baseBranch);
    await this.createBranch(repo, newBranch, baseSha);
 
    const baseTreeSha = await this.getCommitTreeSha(repo, baseSha);
    const entries = await Promise.all(
      files.map(async (file) => ({
        path: file.path,
        sha: await this.createBlobBase64(repo, Buffer.from(file.content, 'utf8')),
      })),
    );
    const treeSha = await this.createTree(repo, baseTreeSha, entries);
    const newCommitSha = await this.createCommit(repo, message, treeSha, baseSha);
    await this.updateRef(repo, newBranch, newCommitSha);
 
    return newCommitSha;
  }
 
  // Reads: find the base tree so new files can be committed without replacing the rest.
  async getCommitTreeSha(repo: string, commitSha: string): Promise<string> {
    const message = `Could not resolve commit ${commitSha} on ${repo}`;
    try {
      const json: unknown = JSON.parse(await this.ghApi([`repos/${repo}/git/commits/${commitSha}`]));
      if (!isRecord(json) || !isRecord(json.tree) || typeof json.tree.sha !== 'string') {
        throw new Error(message);
      }
      return json.tree.sha;
    } catch (error) {
      Eif (error instanceof Error && error.message === message) {
        throw error;
      }
      throw new Error(message);
    }
  }
 
  // Reads: inspect parent commits when checking an existing release commit.
  async getCommitParents(repo: string, commitSha: string): Promise<string[]> {
    const message = `Could not resolve commit parents for ${commitSha} on ${repo}`;
    try {
      const json: unknown = JSON.parse(await this.ghApi([`repos/${repo}/git/commits/${commitSha}`]));
      if (
        !isRecord(json) ||
        !Array.isArray(json.parents) ||
        !json.parents.every((parent) => isRecord(parent) && typeof parent.sha === 'string')
      ) {
        throw new Error(message);
      }
      return json.parents.map((parent) => parent.sha as string);
    } catch (error) {
      Eif (error instanceof Error && error.message === message) throw error;
      throw new Error(message);
    }
  }
 
  // Git Data writes: encode bytes as base64 so uploaded blobs are byte-exact, not UTF-8 text.
  async createBlobBase64(repo: string, content: Buffer): Promise<string> {
    const message = `Unexpected blob response on ${repo}`;
    try {
      const raw = await this.ghApi([`--method`, `POST`, `repos/${repo}/git/blobs`, `--input`, `-`], {
        input: JSON.stringify({ content: content.toString('base64'), encoding: 'base64' }),
      });
      const json: unknown = JSON.parse(raw);
      if (
        !isRecord(json) ||
        typeof json.sha !== 'string' ||
        !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(json.sha)
      ) {
        throw new Error(message);
      }
      return json.sha;
    } catch (error) {
      Eif (error instanceof Error && error.message === message) {
        throw error;
      }
      throw new Error(message);
    }
  }
 
  // Git Data writes: preserve the base tree and add ordinary 100644 file entries.
  async createTree(
    repo: string,
    baseTreeSha: string,
    entries: Array<{ path: string; sha: string }>,
  ): Promise<string> {
    const message = `Unexpected tree response on ${repo}`;
    try {
      const raw = await this.ghApi([`--method`, `POST`, `repos/${repo}/git/trees`, `--input`, `-`], {
        input: JSON.stringify({
          base_tree: baseTreeSha,
          tree: entries.map((entry) => ({
            path: entry.path,
            mode: '100644',
            type: 'blob',
            sha: entry.sha,
          })),
        }),
      });
      const json: unknown = JSON.parse(raw);
      if (!isRecord(json) || typeof json.sha !== 'string') {
        throw new Error(message);
      }
      return json.sha;
    } catch (error) {
      Eif (error instanceof Error && error.message === message) {
        throw error;
      }
      throw new Error(message);
    }
  }
 
  // Git Data writes: create one commit with a single parent on the chosen base.
  async createCommit(repo: string, message: string, treeSha: string, parentSha: string): Promise<string> {
    const errorMessage = `Unexpected commit response on ${repo}`;
    try {
      const raw = await this.ghApi([`--method`, `POST`, `repos/${repo}/git/commits`, `--input`, `-`], {
        input: JSON.stringify({ message, tree: treeSha, parents: [parentSha] }),
      });
      const json: unknown = JSON.parse(raw);
      if (!isRecord(json) || typeof json.sha !== 'string') {
        throw new Error(errorMessage);
      }
      return json.sha;
    } catch (error) {
      Eif (error instanceof Error && error.message === errorMessage) {
        throw error;
      }
      throw new Error(errorMessage);
    }
  }
 
  // Reads: check the current branch head; a missing ref (404) returns null.
  async getBranchHeadSha(repo: string, branch: string): Promise<string | null> {
    const message = `Could not read ref heads/${branch} on ${repo}`;
    try {
      const json: unknown = JSON.parse(await this.ghApi([`repos/${repo}/git/ref/heads/${branch}`]));
      if (!isRecord(json) || !isRecord(json.object) || typeof json.object.sha !== 'string') {
        throw new Error(message);
      }
      return json.object.sha;
    } catch (error) {
      if (isNotFoundError(error)) {
        return null;
      }
      throw new Error(message);
    }
  }
 
  // Git Data writes: POST a new branch ref after its commit is ready.
  async createRef(repo: string, branch: string, commitSha: string): Promise<void> {
    await this.ghApi([`--method`, `POST`, `repos/${repo}/git/refs`, `--input`, `-`], {
      input: JSON.stringify({ ref: `refs/heads/${branch}`, sha: commitSha }),
    });
  }
 
  // Git Data writes: PATCH an existing branch ref to move it to the new commit.
  async updateRef(repo: string, branch: string, commitSha: string): Promise<void> {
    await this.ghApi([`--method`, `PATCH`, `repos/${repo}/git/refs/heads/${branch}`, `--input`, `-`], {
      input: JSON.stringify({ sha: commitSha, force: false }),
    });
  }
 
  // Pull requests: find an open match before creating a duplicate release PR.
  async findOpenPullRequest(repo: string, base: string, head: string): Promise<OpenPullRequest | null> {
    const message = `Unexpected pull request response on ${repo}`;
    try {
      const { stdout } = await this.execaFn(
        'gh',
        [
          'pr',
          'list',
          '--repo',
          repo,
          '--base',
          base,
          '--head',
          head,
          '--state',
          'open',
          '--json',
          'url,title,labels,assignees',
        ],
        { env: { ...process.env, GH_HOST: this.gitcoreHost } },
      );
      const json: unknown = JSON.parse(stdout);
      Iif (!Array.isArray(json)) {
        throw new Error(message);
      }
      if (json.length === 0) {
        return null;
      }
      const pullRequest = json[0];
      if (
        !isRecord(pullRequest) ||
        typeof pullRequest.url !== 'string' ||
        typeof pullRequest.title !== 'string' ||
        !Array.isArray(pullRequest.labels) ||
        !Array.isArray(pullRequest.assignees) ||
        !pullRequest.labels.every((label) => isRecord(label) && typeof label.name === 'string') ||
        !pullRequest.assignees.every((assignee) => isRecord(assignee) && typeof assignee.login === 'string')
      ) {
        throw new Error(message);
      }
      return {
        url: pullRequest.url,
        title: pullRequest.title,
        labels: pullRequest.labels.map((label) => label.name as string),
        assignees: pullRequest.assignees.map((assignee) => assignee.login as string),
      };
    } catch (error) {
      Eif (error instanceof Error && error.message === message) {
        throw error;
      }
      throw new Error(message);
    }
  }
 
  // Pull requests: open the release PR with any requested assignees and labels.
  async createPullRequest(input: CreatePullRequestInput): Promise<string> {
    this.logger.step(`Create PR ${input.head} → ${input.base} on ${input.repo}`);
    const args = [
      'pr',
      'create',
      '--repo',
      input.repo,
      '--base',
      input.base,
      '--head',
      input.head,
      '--title',
      input.title,
      '--body',
      input.body,
    ];
    for (const assignee of input.assignees ?? []) {
      args.push('--assignee', assignee);
    }
    for (const label of input.labels ?? []) {
      args.push('--label', label);
    }
    const { stdout } = await this.execaFn('gh', args, { env: { ...process.env, GH_HOST: this.gitcoreHost } });
    return stdout.trim();
  }
 
  // Pull requests: attach the validation summary to the release PR.
  async addPullRequestComment(repo: string, prUrl: string, body: string): Promise<void> {
    await this.execaFn('gh', ['pr', 'comment', prUrl, '--repo', repo, '--body', body], {
      env: { ...process.env, GH_HOST: this.gitcoreHost },
    });
  }
 
  // Pin helpers: read the version and checksum files together for the slds-scs Bazel pin.
  async readSldsScsPin(repo: string, targetBranch: string): Promise<PinBlock> {
    const versionFile = await this.getFile(repo, GITCORE_PIN_VERSION_PATH, targetBranch);
    const catalogFile = await this.getFile(repo, GITCORE_PIN_CATALOG_PATH, targetBranch);
    return parsePinBlock(versionFile.content, catalogFile.content);
  }
 
  // Pin helpers: prepare both Bazel pin edits and a preview without writing to gitcore.
  async preparePinUpdate(
    repo: string,
    targetBranch: string,
    update: Pick<ApplyPinUpdateInput, 'newVersion' | 'newSha256' | 'newSha1'>,
  ): Promise<PreparedPinUpdate> {
    const versionFile = await this.getFile(repo, GITCORE_PIN_VERSION_PATH, targetBranch);
    const catalogFile = await this.getFile(repo, GITCORE_PIN_CATALOG_PATH, targetBranch);
    const oldPin = parsePinBlock(versionFile.content, catalogFile.content);
    const input: ApplyPinUpdateInput = {
      oldVersion: oldPin.version,
      newVersion: update.newVersion,
      oldSha256: oldPin.sha256,
      newSha256: update.newSha256,
      oldSha1: oldPin.sha1,
      newSha1: update.newSha1,
    };
 
    const versionNew = applyPinToVersionFile(versionFile.content, input);
    const catalogNew = applyPinToCatalogFile(catalogFile.content, input);
    const diff = previewPinDiff(versionFile.content, versionNew, catalogFile.content, catalogNew);
 
    return {
      oldPin,
      versionPath: GITCORE_PIN_VERSION_PATH,
      catalogPath: GITCORE_PIN_CATALOG_PATH,
      versionOld: versionFile.content,
      versionNew,
      catalogOld: catalogFile.content,
      catalogNew,
      diff,
    };
  }
}
 
function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value);
}
 
function isNotFoundError(error: unknown): boolean {
  Iif (!isRecord(error)) {
    return false;
  }
  Iif (error.statusCode === 404) {
    return true;
  }
  return typeof error.stderr === 'string' && /\b404\b/.test(error.stderr);
}