Skip to content

Commit c9d6108

Browse files
mtillerwillnorris
authored andcommitted
This adds an additional method to RepositoriesService to download a file
1 parent af9f30e commit c9d6108

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

‎github/repos_contents.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,10 @@ import (
1313
"encoding/json"
1414
"errors"
1515
"fmt"
16+
"io"
1617
"net/http"
1718
"net/url"
19+
"path"
1820
)
1921

2022
// RepositoryContent represents a file or directory in a github repository.
@@ -91,6 +93,32 @@ func (s *RepositoriesService) GetReadme(owner, repo string, opt *RepositoryConte
9193
return readme, resp, err
9294
}
9395

96+
// DownloadContents returns an io.ReadCloser that reads the contents of the
97+
// specified file. This function will work with files of any size, as opposed
98+
// to GetContents which is limited to 1 Mb files. It is the caller's
99+
// responsibility to close the ReadCloser.
100+
func (s *RepositoriesService) DownloadContents(owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error) {
101+
dir := path.Dir(filepath)
102+
filename := path.Base(filepath)
103+
_, dirContents, _, err := s.GetContents(owner, repo, dir, opt)
104+
if err != nil {
105+
return nil, err
106+
}
107+
for _, contents := range dirContents {
108+
if *contents.Name == filename {
109+
if contents.DownloadURL == nil || *contents.DownloadURL == "" {
110+
return nil, fmt.Errorf("No download link found for %s", filepath)
111+
}
112+
resp, err := s.client.client.Get(*contents.DownloadURL)
113+
if err != nil {
114+
return nil, err
115+
}
116+
return resp.Body, nil
117+
}
118+
}
119+
return nil, fmt.Errorf("No file named %s found in %s", filename, dir)
120+
}
121+
94122
// GetContents can return either the metadata and content of a single file
95123
// (when path references a file) or the metadata of all the files and/or
96124
// subdirectories of a directory (when path references a directory). To make it

0 commit comments

Comments
 (0)