Skip to content

Commit cb021ed

Browse files
committed
GitInput: Determine default branch for repository
Up until now when no branch was defined the Git Plugin hardcoded the master branch. Now we try resolving the default branch with git ls-remote and allow a configurable fallback branch, that can be master or anything else.
1 parent cd235f7 commit cb021ed

1 file changed

Lines changed: 29 additions & 2 deletions

File tree

subprojects/hydra/lib/Hydra/Plugin/GitInput.pm

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,6 @@ sub _parseValue {
2828
my ($value) = @_;
2929
my @parts = split ' ', $value;
3030
(my $uri, my $branch, my $deepClone) = @parts;
31-
$branch = defined $branch ? $branch : "master";
3231
my $options = {};
3332
my $start_options = 3;
3433
# if deepClone has "=" then is considered an option
@@ -44,6 +43,24 @@ sub _parseValue {
4443
return ($uri, $branch, $deepClone, $options);
4544
}
4645

46+
sub _getDefaultBranch {
47+
my ($uri) = @_;
48+
49+
my $res = runCommand(
50+
cmd => ["git", "ls-remote", "--symref", $uri, "HEAD"],
51+
);
52+
53+
return undef if $res->{status};
54+
55+
for my $line (split /\n/, ($res->{stdout} // '')) {
56+
if ($line =~ /^ref:\s+refs\/heads\/(\S+)/) {
57+
return $1;
58+
}
59+
}
60+
61+
return undef;
62+
}
63+
4764
sub _printIfDebug {
4865
my ($msg) = @_;
4966
print STDERR "GitInput: $msg" if $ENV{'HYDRA_DEBUG'};
@@ -55,7 +72,8 @@ Read the configuration from the main hydra config file.
5572
5673
The configuration is loaded from the "git-input" block.
5774
58-
Currently only the "timeout" variable is been looked up in the file.
75+
Currently the "fallback_branch" and a "timeout" variable are looked up in the
76+
file.
5977
6078
The variables defined directly in the input value will override
6179
the ones on the configuration file, to define the variables
@@ -67,6 +85,9 @@ Expected configuration format in the hydra config file:
6785
# general timeout
6886
timeout = 400
6987
88+
# branch, if no default branch can be determined and none is specified
89+
fallback_branch = main
90+
7091
<project:jobset:input-name>
7192
# specific timeout for a particular input
7293
timeout = 400
@@ -79,6 +100,7 @@ sub _pluginConfig {
79100
my $cfg = $main_config->{$CONFIG_SECTION};
80101
# default values
81102
my $values = {
103+
fallback_branch => "master",
82104
timeout => 600,
83105
};
84106
my $input_block = "$project_name:$jobset_name:$input_name";
@@ -126,6 +148,11 @@ sub fetchInput {
126148
_printIfDebug "'$name': override '$opt_name' with input value: $opt_value\n";
127149
}
128150

151+
# Determine a branch to check out, if none is explicitly defined
152+
if (!defined $branch) {
153+
$branch = _getDefaultBranch($uri) // $cfg->{fallback_branch} // "master";
154+
}
155+
129156
# Clone or update a branch of the repository into our SCM cache.
130157
my $cacheDir = getSCMCacheDir . "/git";
131158
mkpath($cacheDir);

0 commit comments

Comments
 (0)