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

100% Statements 52/52
100% Branches 12/12
100% Functions 11/11
100% Lines 52/52

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                                                                                                                            7x               11x 11x       17x       17x       7x   27x   7x 7x 7x 1x     6x     7x       3x 3x 3x 1x   2x       1x 1x                 1x 1x   1x 1x   1x 1x 1x   1x 1x 2x     2x 2x               1x           1x   1x             1x   1x       1x       1x 1x                                   1x       1x 1x 1x               1x 1x 1x 1x                 1x 1x 1x   1x                        
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 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;
};
 
export type PreparedPinUpdate = {
  oldPin: PinBlock;
  versionPath: string;
  catalogPath: string;
  versionOld: string;
  versionNew: string;
  catalogOld: string;
  catalogNew: string;
  diff: string;
};
 
export interface IGitCoreService {
  getFile(repo: string, path: string, ref: string): Promise<GitcoreFile>;
  getRefSha(repo: string, branch: string): Promise<string>;
  createBranch(repo: string, newBranch: string, fromSha: string): Promise<void>;
  commitFiles(input: CommitFilesInput): Promise<string>;
  createPullRequest(input: CreatePullRequestInput): Promise<string>;
  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 };
 
// 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 async ghApi(args: string[], options: { input?: string } = {}): Promise<string> {
    const { stdout } = await execa('gh', ['api', ...args], {
      env: { ...process.env, GH_HOST: this.gitcoreHost },
      input: options.input,
    });
    return stdout;
  }
 
  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 };
  }
 
  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;
  }
 
  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,
      }),
    });
  }
 
  async commitFiles(input: CommitFilesInput): Promise<string> {
    const { repo, baseBranch, newBranch, message, files } = input;
    this.logger.step(`Commit ${files.length} file(s) on ${newBranch}`);
 
    const baseSha = await this.getRefSha(repo, baseBranch);
    await this.createBranch(repo, newBranch, baseSha);
 
    const commitRaw = await this.ghApi([`repos/${repo}/git/commits/${baseSha}`]);
    const baseCommit = JSON.parse(commitRaw) as { tree: { sha: string } };
    const baseTreeSha = baseCommit.tree.sha;
 
    const treeItems: Array<{ path: string; mode: string; type: string; sha: string }> = [];
    for (const file of files) {
      const blobRaw = await this.ghApi([`--method`, `POST`, `repos/${repo}/git/blobs`, `--input`, `-`], {
        input: JSON.stringify({ content: file.content, encoding: 'utf-8' }),
      });
      const blob = JSON.parse(blobRaw) as { sha: string };
      treeItems.push({
        path: file.path,
        mode: '100644',
        type: 'blob',
        sha: blob.sha,
      });
    }
 
    const treeRaw = await this.ghApi([`--method`, `POST`, `repos/${repo}/git/trees`, `--input`, `-`], {
      input: JSON.stringify({
        base_tree: baseTreeSha,
        tree: treeItems,
      }),
    });
    const tree = JSON.parse(treeRaw) as { sha: string };
 
    const newCommitRaw = await this.ghApi([`--method`, `POST`, `repos/${repo}/git/commits`, `--input`, `-`], {
      input: JSON.stringify({
        message,
        tree: tree.sha,
        parents: [baseSha],
      }),
    });
    const newCommit = JSON.parse(newCommitRaw) as { sha: string };
 
    await this.ghApi([`--method`, `PATCH`, `repos/${repo}/git/refs/heads/${newBranch}`, `--input`, `-`], {
      input: JSON.stringify({ sha: newCommit.sha, force: false }),
    });
 
    return newCommit.sha;
  }
 
  async createPullRequest(input: CreatePullRequestInput): Promise<string> {
    this.logger.step(`Create PR ${input.head} → ${input.base} on ${input.repo}`);
    const { stdout } = await execa(
      'gh',
      [
        'pr',
        'create',
        '--repo',
        input.repo,
        '--base',
        input.base,
        '--head',
        input.head,
        '--title',
        input.title,
        '--body',
        input.body,
      ],
      { env: { ...process.env, GH_HOST: this.gitcoreHost } },
    );
    return stdout.trim();
  }
 
  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);
  }
 
  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,
    };
  }
}