createWorktree static method

Future<void> createWorktree(
  1. String gitRoot,
  2. String ref,
  3. String worktreePath
)

Creates a git worktree at the specified path for the given ref Throws GitException if the operation fails

Implementation

static Future<void> createWorktree(String gitRoot, String ref, String worktreePath) async {
  try {
    // First, try to remove existing worktree if it exists
    if (await worktreeExists(gitRoot, worktreePath)) {
      logger.detail('Removing existing worktree at $worktreePath');
      await removeWorktree(gitRoot, worktreePath);
    }

    // Create the worktree
    final result = await Process.run(
      'git',
      ['worktree', 'add', worktreePath, ref],
      workingDirectory: gitRoot,
    );
    if (result.exitCode != 0) {
      throw GitException('Failed to create worktree for ref $ref at $worktreePath: ${result.stderr}');
    }
  } on ProcessException catch (e) {
    throw GitException('Git command not found: ${e.message}');
  } catch (e) {
    if (e is GitException) rethrow;
    throw GitException('Unexpected error: $e');
  }
}