1
1
package getter
2
2
3
3
import (
4
+ "bytes"
4
5
"context"
5
6
"encoding/base64"
6
7
"fmt"
@@ -9,6 +10,7 @@ import (
9
10
"os"
10
11
"os/exec"
11
12
"path/filepath"
13
+ "regexp"
12
14
"runtime"
13
15
"strconv"
14
16
"strings"
@@ -24,6 +26,8 @@ type GitGetter struct {
24
26
getter
25
27
}
26
28
29
+ var defaultBranchRegexp = regexp .MustCompile (`\s->\sorigin/(.*)` )
30
+
27
31
func (g * GitGetter ) ClientMode (_ * url.URL ) (ClientMode , error ) {
28
32
return ClientModeDir , nil
29
33
}
@@ -182,10 +186,10 @@ func (g *GitGetter) update(ctx context.Context, dst, sshKeyFile, ref string, dep
182
186
cmd .Dir = dst
183
187
184
188
if getRunCommand (cmd ) != nil {
185
- // Not a branch, switch to master . This will also catch non-existent
186
- // branches, in which case we want to switch to master and then
187
- // checkout the proper branch later.
188
- ref = "master"
189
+ // Not a branch, switch to default branch . This will also catch
190
+ // non-existent branches, in which case we want to switch to default
191
+ // and then checkout the proper branch later.
192
+ ref = findDefaultBranch ( dst )
189
193
}
190
194
191
195
// We have to be on a branch to pull
@@ -216,6 +220,22 @@ func (g *GitGetter) fetchSubmodules(ctx context.Context, dst, sshKeyFile string,
216
220
return getRunCommand (cmd )
217
221
}
218
222
223
+ // findDefaultBranch checks the repo's origin remote for its default branch
224
+ // (generally "master"). "master" is returned if an origin default branch
225
+ // can't be determined.
226
+ func findDefaultBranch (dst string ) string {
227
+ var stdoutbuf bytes.Buffer
228
+ cmd := exec .Command ("git" , "branch" , "-r" , "--points-at" , "refs/remotes/origin/HEAD" )
229
+ cmd .Dir = dst
230
+ cmd .Stdout = & stdoutbuf
231
+ err := cmd .Run ()
232
+ matches := defaultBranchRegexp .FindStringSubmatch (stdoutbuf .String ())
233
+ if err != nil || matches == nil {
234
+ return "master"
235
+ }
236
+ return matches [len (matches )- 1 ]
237
+ }
238
+
219
239
// setupGitEnv sets up the environment for the given command. This is used to
220
240
// pass configuration data to git and ssh and enables advanced cloning methods.
221
241
func setupGitEnv (cmd * exec.Cmd , sshKeyFile string ) {
0 commit comments