All files / src/cli git.ts

76.22% Statements 93/122
51.64% Branches 47/91
83.33% Functions 15/18
79.31% Lines 92/116

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                                  109x 109x   62x 62x               4x             3x             6x                     11x 26x 26x 26x             5x 12x 12x 12x             3x 3x 3x   1x 1x 1x               2x 2x 2x 1x           1x             27x             2x 2x     2x 2x               2x 2x 2x               15x 15x   15x 15x                     15x             2x           2x                                                   6x 6x 3x   3x 6x                             2x   2x       2x   2x 2x   2x 2x   2x 2x   2x                 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x         2x                                               2x 2x     2x   2x 2x     2x 2x   2x 2x 2x         2x                       2x   2x         2x 2x 2x   2x 2x 2x                   2x                                                                             3x 3x 3x    
import { countPatchChunks } from '../types/index.js';
import { execGitNonInteractive } from '../utils/exec.js';
 
export interface GitFileChange {
  filename: string;
  status: 'added' | 'removed' | 'modified' | 'renamed' | 'copied';
  additions: number;
  deletions: number;
  patch?: string;
  chunks?: number;
}
 
/**
 * Execute a git command and return stdout.
 * Uses array-based arguments to avoid shell injection.
 */
function git(args: string[], cwd: string = process.cwd()): string {
  try {
    return execGitNonInteractive(args, { cwd });
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    throw new Error(`Git command failed: git ${args.join(' ')}\n${message}`, { cause: error });
  }
}
 
/**
 * Get the current branch name.
 */
export function getCurrentBranch(cwd: string = process.cwd()): string {
  return git(['rev-parse', '--abbrev-ref', 'HEAD'], cwd);
}
 
/**
 * Get the HEAD commit SHA.
 */
export function getHeadSha(cwd: string = process.cwd()): string {
  return resolveRef('HEAD', cwd);
}
 
/**
 * Resolve a ref (branch name, tag, SHA) to a full commit SHA.
 */
export function resolveRef(ref: string, cwd: string = process.cwd()): string {
  return git(['rev-parse', ref], cwd);
}
 
/**
 * Detect the default branch by checking common branch names locally.
 * Also checks remote tracking refs (origin/*) for shallow clones
 * where local branches may not exist (e.g. GitHub Actions).
 * Does not perform any remote operations to avoid SSH prompts.
 */
export function getDefaultBranch(cwd: string = process.cwd()): string {
  // Check common default branches locally (no remote operations)
  for (const branch of ['main', 'master', 'develop']) {
    try {
      git(['rev-parse', '--verify', branch], cwd);
      return branch;
    } catch {
      // Try next branch
    }
  }
 
  // Check remote tracking refs (common in shallow clones / CI)
  for (const branch of ['main', 'master', 'develop']) {
    try {
      git(['rev-parse', '--verify', `origin/${branch}`], cwd);
      return `origin/${branch}`;
    } catch {
      // Try next branch
    }
  }
 
  // Check remote HEAD symbolic ref (set by clone, no network needed)
  try {
    const remoteHead = git(['symbolic-ref', 'refs/remotes/origin/HEAD'], cwd);
    if (remoteHead) {
      // Returns e.g. "refs/remotes/origin/main" → extract "origin/main"
      const match = remoteHead.match(/refs\/remotes\/(.*)/);
      Eif (match?.[1]) {
        return match[1];
      }
    }
  } catch {
    // No remote HEAD configured
  }
 
  // Check git config for user-configured default branch
  try {
    const configuredDefault = git(['config', 'init.defaultBranch'], cwd);
    if (configuredDefault) {
      return configuredDefault;
    }
  } catch {
    // Config not set
  }
 
  return 'main'; // Default fallback
}
 
/**
 * Get the repository root path.
 */
export function getRepoRoot(cwd: string = process.cwd()): string {
  return git(['rev-parse', '--show-toplevel'], cwd);
}
 
/**
 * Get the repository name from the git remote or directory name.
 */
export function getRepoName(cwd: string = process.cwd()): { owner: string; name: string } {
  try {
    const remoteUrl = git(['config', '--get', 'remote.origin.url'], cwd);
    // Handle SSH: git@github.com:owner/repo.git
    // Handle HTTPS: https://github.com/owner/repo.git
    const match = remoteUrl.match(/[/:]([\w.-]+)\/([\w.-]+?)(?:\.git)?$/);
    Iif (match && match[1] && match[2]) {
      return { owner: match[1], name: match[2] };
    }
  } catch {
    // No remote configured
  }
 
  // Fall back to directory name
  const repoRoot = getRepoRoot(cwd);
  const dirName = repoRoot.split('/').pop() ?? 'unknown';
  return { owner: 'local', name: dirName };
}
 
/**
 * Get the GitHub repository URL if the remote is on GitHub.
 * Returns null if the remote is not GitHub or not configured.
 */
export function getGitHubRepoUrl(cwd: string = process.cwd()): string | null {
  try {
    const remoteUrl = git(['config', '--get', 'remote.origin.url'], cwd);
    // Handle SSH: git@github.com:owner/repo.git
    const sshMatch = remoteUrl.match(/git@github\.com:([\w.-]+)\/([\w.-]+?)(?:\.git)?$/);
    Iif (sshMatch && sshMatch[1] && sshMatch[2]) {
      return `https://github.com/${sshMatch[1]}/${sshMatch[2]}`;
    }
    // Handle HTTPS: https://github.com/owner/repo.git
    const httpsMatch = remoteUrl.match(/https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?$/);
    if (httpsMatch && httpsMatch[1] && httpsMatch[2]) {
      return `https://github.com/${httpsMatch[1]}/${httpsMatch[2]}`;
    }
  } catch {
    // No remote configured
  }
  return null;
}
 
/**
 * Map git status letter to FileChange status.
 */
function mapStatus(status: string): GitFileChange['status'] {
  switch (status[0]) {
    case 'A':
      return 'added';
    case 'D':
      return 'removed';
    case 'M':
      return 'modified';
    case 'R':
      return 'renamed';
    case 'C':
      return 'copied';
    default:
      return 'modified';
  }
}
 
export interface DiffOptions {
  /** Use --cached to diff only staged changes against HEAD */
  staged?: boolean;
}
 
/**
 * Build the git diff arguments for a given base/head/staged configuration.
 * Extra flags (e.g. '--name-status') are placed before the ref, matching
 * the documented git-diff synopsis: git diff [<options>] [<commit>] ...
 */
function buildDiffArgs(
  base: string,
  head: string | undefined,
  options?: DiffOptions,
  extraFlags?: string[]
): string[] {
  const flags = extraFlags ?? [];
  if (options?.staged) {
    return ['diff', ...flags, '--cached'];
  }
  const diffRef = head ? `${base}...${head}` : base;
  return ['diff', ...flags, diffRef];
}
 
/**
 * Get list of changed files between two refs.
 * If head is undefined, compares against the working tree.
 * If options.staged is true, compares only staged changes against HEAD.
 */
export function getChangedFiles(
  base: string,
  head?: string,
  cwd: string = process.cwd(),
  options?: DiffOptions
): GitFileChange[] {
  // Get file statuses
  const nameStatusOutput = git(buildDiffArgs(base, head, options, ['--name-status']), cwd);
 
  Iif (!nameStatusOutput) {
    return [];
  }
 
  const files: GitFileChange[] = [];
 
  for (const line of nameStatusOutput.split('\n')) {
    Iif (!line.trim()) continue;
 
    const parts = line.split('\t');
    const status = parts[0] ?? '';
    // For renames, format is "R100\told-name\tnew-name"
    const filename = parts.length > 2 ? (parts[2] ?? '') : (parts[1] ?? '');
    Iif (!filename) continue;
 
    files.push({
      filename,
      status: mapStatus(status),
      additions: 0,
      deletions: 0,
    });
  }
 
  // Get numstat for additions/deletions
  const numstatOutput = git(buildDiffArgs(base, head, options, ['--numstat']), cwd);
  Eif (numstatOutput) {
    for (const line of numstatOutput.split('\n')) {
      Iif (!line.trim()) continue;
      const parts = line.split('\t');
      const additions = parts[0] ?? '0';
      const deletions = parts[1] ?? '0';
      const filename = parts[2] ?? '';
      const file = files.find((f) => f.filename === filename);
      Eif (file) {
        file.additions = additions === '-' ? 0 : parseInt(additions, 10);
        file.deletions = deletions === '-' ? 0 : parseInt(deletions, 10);
      }
    }
  }
 
  return files;
}
 
/**
 * Get the patch for a specific file.
 */
export function getFilePatch(
  base: string,
  head: string | undefined,
  filename: string,
  cwd: string = process.cwd(),
  options?: DiffOptions
): string | undefined {
  try {
    return git([...buildDiffArgs(base, head, options), '--', filename], cwd);
  } catch {
    return undefined;
  }
}
 
/**
 * Parse a combined diff output into individual file patches.
 */
function parseCombinedDiff(diffOutput: string): Map<string, string> {
  const patches = new Map<string, string>();
  Iif (!diffOutput) return patches;
 
  // Split by "diff --git" but keep the delimiter
  const parts = diffOutput.split(/(?=^diff --git )/m);
 
  for (const part of parts) {
    Iif (!part.trim()) continue;
 
    // Extract filename from "diff --git a/path b/path" line
    const match = part.match(/^diff --git a\/(.+?) b\/(.+?)\n/);
    Eif (match) {
      // Use the "b" path (destination) as the filename
      const filename = match[2];
      Eif (filename) {
        patches.set(filename, part);
      }
    }
  }
 
  return patches;
}
 
/**
 * Get patches for all changed files in a single git command.
 */
export function getChangedFilesWithPatches(
  base: string,
  head?: string,
  cwd: string = process.cwd(),
  options?: DiffOptions
): GitFileChange[] {
  const files = getChangedFiles(base, head, cwd, options);
 
  Iif (files.length === 0) {
    return files;
  }
 
  // Get all patches in a single git diff command
  try {
    const combinedDiff = git(buildDiffArgs(base, head, options), cwd);
    const patches = parseCombinedDiff(combinedDiff);
 
    for (const file of files) {
      file.patch = patches.get(file.filename);
      file.chunks = countPatchChunks(file.patch);
    }
  } catch {
    // Fall back to per-file patches if combined diff fails
    for (const file of files) {
      file.patch = getFilePatch(base, head, file.filename, cwd, options);
      file.chunks = countPatchChunks(file.patch);
    }
  }
 
  return files;
}
 
/**
 * Check if there are uncommitted changes in the working tree.
 */
export function hasUncommittedChanges(cwd: string = process.cwd()): boolean {
  const status = git(['status', '--porcelain'], cwd);
  return status.length > 0;
}
 
/**
 * Check if a ref exists.
 */
export function refExists(ref: string, cwd: string = process.cwd()): boolean {
  try {
    git(['rev-parse', '--verify', ref], cwd);
    return true;
  } catch {
    return false;
  }
}
 
/**
 * Commit message with subject and body separated.
 */
export interface CommitMessage {
  /** First line of the commit message */
  subject: string;
  /** Remaining lines after the subject (may be empty) */
  body: string;
}
 
/**
 * Get the commit message for a specific ref.
 * Returns subject (first line) and body (remaining lines) separately.
 */
export function getCommitMessage(ref: string, cwd: string = process.cwd()): CommitMessage {
  // %s = subject, %b = body
  const subject = git(['log', '-1', `--format=%s`, ref], cwd);
  const body = git(['log', '-1', `--format=%b`, ref], cwd);
  return { subject, body };
}