Skip to content

Commit 7db7326

Browse files
committed
Fix GetFile support for GitHub getter
This change fixes support for getting single files from GitHub. While this worked fine for other Git repositories, it did not work for GitHub, because the getter tried to clone a wrong URL. For example, if a GitHub URL of "https://github.com/owner/repo/subdir/file.txt" would be given to "GetFile", it would clone "https://github.com/owner/repo/subdir" instead of cloning "https://github.com/owner/repo" and extracting "subdir/file.txt".
1 parent 4553965 commit 7db7326

File tree

2 files changed

+52
-2
lines changed

2 files changed

+52
-2
lines changed

get_git.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,15 @@ func (g *GitGetter) GetFile(dst string, u *url.URL) error {
143143

144144
// Get the filename, and strip the filename from the URL so we can
145145
// just get the repository directly.
146-
filename := filepath.Base(u.Path)
147-
u.Path = filepath.Dir(u.Path)
146+
var filename string
147+
if u.Host == "github.com" {
148+
tokens := strings.SplitN(u.Path[1:], "/", 3)
149+
u.Path = "/" + tokens[0] + "/" + tokens[1]
150+
filename = tokens[2]
151+
} else {
152+
filename = filepath.Base(u.Path)
153+
u.Path = filepath.Dir(u.Path)
154+
}
148155

149156
// Get the full repository
150157
if err := g.Get(td, u); err != nil {

get_git_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,49 @@ func TestGitGetter_GetFile(t *testing.T) {
407407
assertContents(t, dst, "hello")
408408
}
409409

410+
func TestGitGetter_githubGetWithFileMode(t *testing.T) {
411+
if !testHasGit {
412+
t.Skip("git not found, skipping")
413+
}
414+
415+
dst := tempTestFile(t)
416+
defer os.RemoveAll(filepath.Dir(dst))
417+
418+
c := Client{
419+
Src: "git::https://github.com/arikkfir/go-getter/testdata/basic/foo/main.tf?ref=master",
420+
Dst: dst,
421+
Mode: ClientModeFile,
422+
}
423+
if err := c.Get(); err != nil {
424+
t.Fatalf("err: %s", err)
425+
}
426+
427+
// Verify the main file exists
428+
if _, err := os.Stat(dst); err != nil {
429+
t.Fatalf("err: %s", err)
430+
}
431+
assertContents(t, dst, "# Hello\n")
432+
}
433+
434+
func TestGitGetter_githubGetFile(t *testing.T) {
435+
if !testHasGit {
436+
t.Skip("git not found, skipping")
437+
}
438+
439+
dst := tempTestFile(t)
440+
defer os.RemoveAll(filepath.Dir(dst))
441+
442+
if err := GetFile(dst, "git::https://github.com/arikkfir/go-getter/testdata/basic/foo/main.tf?ref=master"); err != nil {
443+
t.Fatalf("err: %s", err)
444+
}
445+
446+
// Verify the main file exists
447+
if _, err := os.Stat(dst); err != nil {
448+
t.Fatalf("err: %s", err)
449+
}
450+
assertContents(t, dst, "# Hello\n")
451+
}
452+
410453
func TestGitGetter_gitVersion(t *testing.T) {
411454
if !testHasGit {
412455
t.Skip("git not found, skipping")

0 commit comments

Comments
 (0)