diff --git a/lib/setup/clone.dart b/lib/setup/clone.dart index 644fa745..3aff41b1 100644 --- a/lib/setup/clone.dart +++ b/lib/setup/clone.dart @@ -50,6 +50,17 @@ Future> cloneRemote({ if (r.isFailure) { return fail(r); } + + var branchR = await gitDefaultBranchViaExecutable( + repoPath: repoPath, + privateKey: sshPrivateKey, + privateKeyPassword: sshPassword, + remoteName: remoteName, + ); + if (r.isFailure) { + return fail(r); + } + remoteBranchName = branchR.getOrThrow(); } Log.i("Using remote branch: $remoteBranchName"); diff --git a/lib/utils/git_desktop.dart b/lib/utils/git_desktop.dart index c41c3535..a49f64d2 100644 --- a/lib/utils/git_desktop.dart +++ b/lib/utils/git_desktop.dart @@ -1,6 +1,7 @@ // GIT_SSH_COMMAND='ssh -i private_key_file -o IdentitiesOnly=yes' git clone user@host:repo.git -import 'dart:io' show Directory, File, Process, ProcessStartMode; +import 'dart:convert'; +import 'dart:io'; import 'package:dart_git/utils/result.dart'; @@ -72,3 +73,57 @@ Future> _gitCommandViaExecutable({ return Result(null); } + +// Default branch - git remote show origin | grep 'HEAD branch' +Future> gitDefaultBranchViaExecutable({ + required String repoPath, + required String privateKey, + required String privateKeyPassword, + required String remoteName, +}) async { + assert(repoPath.startsWith('/')); + if (privateKeyPassword.isNotEmpty) { + var ex = Exception("SSH Keys with passwords are not supported"); + return Result.fail(ex); + } + + var dir = Directory.systemTemp.createTempSync(); + var temp = File("${dir.path}/key"); + temp.writeAsString(privateKey); + + var process = await Process.start( + 'git', + [ + 'remote', + 'show', + remoteName, + ], + workingDirectory: repoPath, + environment: { + 'GIT_SSH_COMMAND': 'ssh -i ${temp.path} -o IdentitiesOnly=yes', + }, + ); + + var exitCode = await process.exitCode; + await dir.delete(recursive: true); + + if (exitCode != 0) { + var ex = Exception("Failed to fetch, exitCode: $exitCode"); + return Result.fail(ex); + } + + var stdoutB = []; + await for (var d in process.stdout) { + stdoutB.addAll(d); + } + var stdout = utf8.decode(stdoutB); + for (var line in LineSplitter.split(stdout)) { + if (line.contains('HEAD branch:')) { + var branch = line.split(':')[1].trim(); + return Result(branch); + } + } + + var ex = Exception('Default Branch not found'); + return Result.fail(ex); +}