getUniqueForkName function
Generate a unique fork name by checking for collisions with existing session names. If "baseName (Branch)" already exists, tries "baseName (Branch 2)", "baseName (Branch 3)", etc.
Implementation
Future<String> getUniqueForkName(String projectDir, String baseName) async {
final candidateName = '$baseName (Branch)';
// Check if this exact name already exists
final existingWithExactName = await searchSessionsByCustomTitle(
projectDir,
candidateName,
exact: true,
);
if (existingWithExactName.isEmpty) {
return candidateName;
}
// Name collision — find a unique numbered suffix.
// Search for all sessions that start with the base pattern.
final existingForks = await searchSessionsByCustomTitle(
projectDir,
'$baseName (Branch',
);
// Extract existing fork numbers to find the next available.
final usedNumbers = <int>{1}; // Consider " (Branch)" as number 1
final escapedBase = RegExp.escape(baseName);
final forkNumberPattern = RegExp('^$escapedBase \\(Branch(?: (\\d+))?\\)\$');
for (final session in existingForks) {
final title = session['customTitle'];
if (title == null) continue;
final match = forkNumberPattern.firstMatch(title);
if (match != null) {
final numberStr = match.group(1);
if (numberStr != null) {
usedNumbers.add(int.parse(numberStr));
} else {
usedNumbers.add(1); // " (Branch)" without number is treated as 1
}
}
}
// Find the next available number.
var nextNumber = 2;
while (usedNumbers.contains(nextNumber)) {
nextNumber++;
}
return '$baseName (Branch $nextNumber)';
}