All files / src/git manager.ts

94.28% Statements 99/105
80.39% Branches 41/51
100% Functions 10/10
95.09% Lines 97/102

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                                          15x                                           24x 24x 24x 24x                           20x 20x       20x                 20x               20x                   20x                 5x 5x 1x     4x 4x       4x     4x                                 23x   23x                 18x 32x                 5x 5x 1x       4x         4x 4x               4x 4x                   4x 4x     4x   4x   5x                   6x 6x 1x   5x     5x   5x   5x     5x     2x                   6x           3x   3x 3x 3x     3x                       3x   3x                     5x 5x 5x                         23x 23x   23x 23x   23x 141x   41x   18x 18x           18x   41x 100x   41x 41x 59x   18x   18x           23x 23x 23x               23x                 4x 1x     3x       3x 3x   3x 5x     5x 5x 5x     5x 3x     3x   1x 1x   1x 1x   1x 1x         3x       3x      
/**
 * SimpleGit WorktreeManager Adapter
 *
 * Implementation of WorktreeManager port interface using simple-git.
 * This is the ADAPTER for the WorktreeManager PORT.
 *
 * Manages git worktrees for isolated agent workspaces.
 * Each agent gets its own worktree to avoid file conflicts.
 */
 
import path from 'node:path';
import { simpleGit, type SimpleGit } from 'simple-git';
import type { EventBus } from '../events/types.js';
import type {
  WorktreeManager,
  Worktree,
  WorktreeDiff,
  MergeResult,
} from './types.js';
import { createModuleLogger } from '../logger/index.js';
 
const log = createModuleLogger('git');
 
/**
 * SimpleGit-based implementation of the WorktreeManager interface.
 *
 * Wraps simple-git to provide git worktree operations
 * that conform to the WorktreeManager port interface.
 */
export class SimpleGitWorktreeManager implements WorktreeManager {
  private git: SimpleGit;
  private repoPath: string;
  private worktreesDir: string;
  private eventBus?: EventBus;
 
  /**
   * Create a new SimpleGitWorktreeManager.
   *
   * @param repoPath - Absolute path to the git repository
   * @param eventBus - Optional EventBus for emitting git events
   * @param worktreesBaseDir - Optional custom base directory for worktrees (defaults to <repoPath>/.cw-worktrees)
   */
  constructor(repoPath: string, eventBus?: EventBus, worktreesBaseDir?: string) {
    this.repoPath = repoPath;
    this.git = simpleGit(repoPath);
    this.worktreesDir = worktreesBaseDir ?? path.join(repoPath, '.cw-worktrees');
    this.eventBus = eventBus;
  }
 
  /**
   * Create a new worktree for isolated agent work.
   *
   * Creates a new branch and worktree directory.
   * The worktree will be ready for the agent to start working.
   */
  async create(
    id: string,
    branch: string,
    baseBranch: string = 'main'
  ): Promise<Worktree> {
    const worktreePath = path.join(this.worktreesDir, id);
    log.info({ id, branch, baseBranch }, 'creating worktree');
 
    // Create worktree with new branch
    // git worktree add -b <branch> <path> <base-branch>
    await this.git.raw([
      'worktree',
      'add',
      '-b',
      branch,
      worktreePath,
      baseBranch,
    ]);
 
    const worktree: Worktree = {
      id,
      branch,
      path: worktreePath,
      isMainWorktree: false,
    };
 
    // Emit event if eventBus provided
    this.eventBus?.emit({
      type: 'worktree:created',
      timestamp: new Date(),
      payload: {
        worktreeId: id,
        branch,
        path: worktreePath,
      },
    });
 
    return worktree;
  }
 
  /**
   * Remove a worktree and optionally its branch.
   *
   * Cleans up the worktree directory and removes it from git's tracking.
   */
  async remove(id: string): Promise<void> {
    const worktree = await this.get(id);
    if (!worktree) {
      throw new Error(`Worktree not found: ${id}`);
    }
 
    const branch = worktree.branch;
    log.info({ id, branch }, 'removing worktree');
 
    // Remove worktree with force to handle any uncommitted changes
    // git worktree remove <path> --force
    await this.git.raw(['worktree', 'remove', worktree.path, '--force']);
 
    // Emit event if eventBus provided
    this.eventBus?.emit({
      type: 'worktree:removed',
      timestamp: new Date(),
      payload: {
        worktreeId: id,
        branch,
      },
    });
  }
 
  /**
   * List all worktrees in the repository.
   *
   * Returns all worktrees including the main one.
   */
  async list(): Promise<Worktree[]> {
    // git worktree list --porcelain
    const output = await this.git.raw(['worktree', 'list', '--porcelain']);
 
    return this.parseWorktreeList(output);
  }
 
  /**
   * Get a specific worktree by ID.
   *
   * Finds worktree by matching path ending with id.
   */
  async get(id: string): Promise<Worktree | null> {
    const worktrees = await this.list();
    return worktrees.find((wt) => wt.path.endsWith(id)) ?? null;
  }
 
  /**
   * Get the diff/changes in a worktree.
   *
   * Shows what files have changed compared to HEAD.
   */
  async diff(id: string): Promise<WorktreeDiff> {
    const worktree = await this.get(id);
    if (!worktree) {
      throw new Error(`Worktree not found: ${id}`);
    }
 
    // Create git instance for the worktree directory
    const worktreeGit = simpleGit(worktree.path);
 
    // Get name-status diff against HEAD
    // git diff --name-status HEAD
    let diffOutput: string;
    try {
      diffOutput = await worktreeGit.raw(['diff', '--name-status', 'HEAD']);
    } catch {
      // If HEAD doesn't exist or other issues, return empty diff
      diffOutput = '';
    }
 
    // Also get staged changes
    let stagedOutput: string;
    try {
      stagedOutput = await worktreeGit.raw([
        'diff',
        '--name-status',
        '--cached',
      ]);
    } catch {
      stagedOutput = '';
    }
 
    // Combine and parse outputs
    const combined = diffOutput + stagedOutput;
    const files = this.parseDiffNameStatus(combined);
 
    // Get summary
    const fileCount = files.length;
    const summary =
      fileCount === 0 ? 'No changes' : `${fileCount} file(s) changed`;
 
    return { files, summary };
  }
 
  /**
   * Merge worktree changes into target branch.
   *
   * Attempts to merge the worktree's branch into the target branch.
   * Returns conflict information if merge cannot be completed cleanly.
   */
  async merge(id: string, targetBranch: string): Promise<MergeResult> {
    const worktree = await this.get(id);
    if (!worktree) {
      throw new Error(`Worktree not found: ${id}`);
    }
    log.info({ id, targetBranch }, 'merging worktree');
 
    // Store current branch to restore later
    const currentBranch = await this.git.revparse(['--abbrev-ref', 'HEAD']);
 
    try {
      // Checkout target branch in main repo
      await this.git.checkout(targetBranch);
 
      // Attempt merge with no-edit (no interactive editor)
      await this.git.merge([worktree.branch, '--no-edit']);
 
      // Emit success event
      this.eventBus?.emit({
        type: 'worktree:merged',
        timestamp: new Date(),
        payload: {
          worktreeId: id,
          sourceBranch: worktree.branch,
          targetBranch,
        },
      });
 
      return {
        success: true,
        message: 'Merged successfully',
      };
    } catch (error) {
      // Check if it's a merge conflict
      const status = await this.git.status();
 
      Eif (status.conflicted.length > 0) {
        const conflicts = status.conflicted;
        log.warn({ id, targetBranch, conflictCount: conflicts.length }, 'merge conflicts detected');
 
        // Emit conflict event
        this.eventBus?.emit({
          type: 'worktree:conflict',
          timestamp: new Date(),
          payload: {
            worktreeId: id,
            sourceBranch: worktree.branch,
            targetBranch,
            conflictingFiles: conflicts,
          },
        });
 
        // Abort merge to clean up
        await this.git.merge(['--abort']);
 
        return {
          success: false,
          conflicts,
          message: 'Merge conflicts detected',
        };
      }
 
      // Some other error occurred, rethrow
      throw error;
    } finally {
      // Restore original branch if different from target
      try {
        const nowBranch = await this.git.revparse(['--abbrev-ref', 'HEAD']);
        Iif (nowBranch.trim() !== currentBranch.trim()) {
          await this.git.checkout(currentBranch.trim());
        }
      } catch {
        // Ignore errors restoring branch
      }
    }
  }
 
  /**
   * Parse the porcelain output of git worktree list.
   */
  private parseWorktreeList(output: string): Worktree[] {
    const worktrees: Worktree[] = [];
    const lines = output.trim().split('\n');
 
    let currentWorktree: Partial<Worktree> = {};
    let isFirst = true;
 
    for (const line of lines) {
      if (line.startsWith('worktree ')) {
        // Start of a new worktree entry
        if (currentWorktree.path) {
          // Derive ID from path
          const id = isFirst ? 'main' : path.basename(currentWorktree.path);
          worktrees.push({
            id,
            branch: currentWorktree.branch || '',
            path: currentWorktree.path,
            isMainWorktree: isFirst,
          });
          isFirst = false;
        }
        currentWorktree = { path: line.substring('worktree '.length) };
      } else if (line.startsWith('branch ')) {
        // Branch reference (e.g., "branch refs/heads/main")
        const branchRef = line.substring('branch '.length);
        currentWorktree.branch = branchRef.replace('refs/heads/', '');
      } else if (line.startsWith('HEAD ')) {
        // Detached HEAD, skip
      I} else if (line === 'bare') {
        // Bare worktree, skip
      E} else if (line === '') {
        // Empty line between worktrees
      }
    }
 
    // Don't forget the last worktree
    Eif (currentWorktree.path) {
      const id = isFirst ? 'main' : path.basename(currentWorktree.path);
      worktrees.push({
        id,
        branch: currentWorktree.branch || '',
        path: currentWorktree.path,
        isMainWorktree: isFirst,
      });
    }
 
    return worktrees;
  }
 
  /**
   * Parse the output of git diff --name-status.
   */
  private parseDiffNameStatus(
    output: string
  ): Array<{ path: string; status: 'added' | 'modified' | 'deleted' }> {
    if (!output.trim()) {
      return [];
    }
 
    const lines = output.trim().split('\n');
    const files: Array<{
      path: string;
      status: 'added' | 'modified' | 'deleted';
    }> = [];
    const seen = new Set<string>();
 
    for (const line of lines) {
      Iif (!line.trim()) continue;
 
      // Format: "M\tpath/to/file" or "A\tpath/to/file" or "D\tpath/to/file"
      const match = line.match(/^([AMD])\t(.+)$/);
      Eif (match) {
        const [, statusLetter, filePath] = match;
 
        // Skip duplicates (can happen when combining diff + cached)
        if (seen.has(filePath)) continue;
        seen.add(filePath);
 
        let status: 'added' | 'modified' | 'deleted';
        switch (statusLetter) {
          case 'A':
            status = 'added';
            break;
          case 'M':
            status = 'modified';
            break;
          case 'D':
            status = 'deleted';
            break;
          default:
            continue;
        }
 
        files.push({ path: filePath, status });
      }
    }
 
    return files;
  }
}