removeWorktree static method
Removes a git worktree Throws GitException if the operation fails
Implementation
static Future<void> removeWorktree(String gitRoot, String worktreePath) async {
try {
// Use --force to handle cases where worktree has uncommitted changes or is locked
final result = await Process.run(
'git',
['worktree', 'remove', '--force', worktreePath],
workingDirectory: gitRoot,
);
if (result.exitCode != 0) {
// If worktree remove fails, try to remove the directory manually
final dir = Directory(worktreePath);
if (dir.existsSync()) {
logger.detail('Git worktree remove failed, attempting manual cleanup of $worktreePath');
try {
dir.deleteSync(recursive: true);
} catch (e) {
throw GitException(
'Failed to remove worktree at $worktreePath: ${result.stderr}. Manual cleanup also failed: $e');
}
} else {
// Directory doesn't exist, consider it cleaned up
logger.detail('Worktree directory $worktreePath does not exist, considering it cleaned up');
}
}
} on ProcessException catch (e) {
throw GitException('Git command not found: ${e.message}');
} catch (e) {
if (e is GitException) rethrow;
throw GitException('Unexpected error: $e');
}
}