createWorktreeForSession method

Future<WorktreeSession> createWorktreeForSession(
  1. String sessionId,
  2. String slug, {
  3. String? tmuxSessionName,
  4. WorktreeCreateOptions? options,
})

Creates a worktree for a session. Hook-based creation takes precedence.

Implementation

Future<WorktreeSession> createWorktreeForSession(
  String sessionId,
  String slug, {
  String? tmuxSessionName,
  WorktreeCreateOptions? options,
}) async {
  validateWorktreeSlug(slug);
  final originalCwd = _getCwd();

  if (_hasWorktreeCreateHook() && onExecuteWorktreeCreateHook != null) {
    final hookResult = await onExecuteWorktreeCreateHook!(slug);
    _logForDebugging(
      'Created hook-based worktree at: ${hookResult.worktreePath}',
    );

    final session = WorktreeSession(
      originalCwd: originalCwd,
      worktreePath: hookResult.worktreePath,
      worktreeName: slug,
      sessionId: sessionId,
      tmuxSessionName: tmuxSessionName,
      hookBased: true,
    );
    currentSession.value = session;
  } else {
    final gitRoot = _findGitRoot(_getCwd());
    if (gitRoot == null) {
      throw StateError(
        'Cannot create a worktree: not in a git repository and no '
        'WorktreeCreate hooks are configured.',
      );
    }

    final originalBranch = await _getBranch();
    final createStart = DateTime.now().millisecondsSinceEpoch;
    final result = await _getOrCreateWorktree(
      gitRoot,
      slug,
      options: options,
    );

    int? creationDurationMs;
    if (result is WorktreeCreated) {
      _logForDebugging(
        'Created worktree at: ${result.worktreePath} on branch: ${result.worktreeBranch}',
      );
      await _performPostCreationSetup(gitRoot, result.worktreePath);
      creationDurationMs =
          DateTime.now().millisecondsSinceEpoch - createStart;
    } else {
      _logForDebugging(
        'Resuming existing worktree at: ${result.worktreePath}',
      );
    }

    final session = WorktreeSession(
      originalCwd: originalCwd,
      worktreePath: result.worktreePath,
      worktreeName: slug,
      worktreeBranch: result.worktreeBranch,
      originalBranch: originalBranch,
      originalHeadCommit: result.headCommit,
      sessionId: sessionId,
      tmuxSessionName: tmuxSessionName,
      creationDurationMs: creationDurationMs,
    );
    currentSession.value = session;
  }

  onSaveProjectConfig?.call(currentSession.value);
  return currentSession.value!;
}