Skip to content

Commit ec90c7c

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 293f9e2 commit ec90c7c

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
@@ -155,8 +155,15 @@ func (g *GitGetter) GetFile(dst string, u *url.URL) error {
155155

156156
// Get the filename, and strip the filename from the URL so we can
157157
// just get the repository directly.
158-
filename := filepath.Base(u.Path)
159-
u.Path = filepath.Dir(u.Path)
158+
var filename string
159+
if u.Host == "github.com" {
160+
tokens := strings.SplitN(u.Path[1:], "/", 3)
161+
u.Path = "/" + tokens[0] + "/" + tokens[1]
162+
filename = tokens[2]
163+
} else {
164+
filename = filepath.Base(u.Path)
165+
u.Path = filepath.Dir(u.Path)
166+
}
160167

161168
// Get the full repository
162169
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
@@ -410,6 +410,49 @@ func TestGitGetter_GetFile(t *testing.T) {
410410
assertContents(t, dst, "hello")
411411
}
412412

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

0 commit comments

Comments
 (0)