Skip to content

Commit 53de44d

Browse files
authored
feat(internal/fetch,sidekick): add fetch package (#2964)
Move functions related to downloading tarballs and computing checksum to internal/fetch, so that it can be used by code outside of sidekick. For #2966
1 parent 005f697 commit 53de44d

File tree

4 files changed

+330
-98
lines changed

4 files changed

+330
-98
lines changed

internal/fetch/fetch.go

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
// Copyright 2025 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
// Package fetch provides utilities for fetching GitHub repository metadata and computing checksums.
16+
package fetch
17+
18+
import (
19+
"crypto/sha256"
20+
"fmt"
21+
"io"
22+
"net/http"
23+
"strings"
24+
)
25+
26+
// Endpoints defines the endpoints used to access GitHub.
27+
type Endpoints struct {
28+
// API defines the endpoint used to make API calls.
29+
API string
30+
31+
// Download defines the endpoint to download tarballs.
32+
Download string
33+
}
34+
35+
// Repo represents a GitHub repository name.
36+
type Repo struct {
37+
// Org defines the GitHub organization (or user), that owns the repository.
38+
Org string
39+
40+
// Repo is the name of the repository, such as `googleapis` or `google-cloud-rust`.
41+
Repo string
42+
}
43+
44+
// RepoFromTarballLink extracts the gitHub account and repository (such as
45+
// `googleapis/googleapis`, or `googleapis/google-cloud-rust`) from the tarball
46+
// link.
47+
func RepoFromTarballLink(githubDownload, tarballLink string) (*Repo, error) {
48+
urlPath := strings.TrimPrefix(tarballLink, githubDownload)
49+
urlPath = strings.TrimPrefix(urlPath, "/")
50+
components := strings.Split(urlPath, "/")
51+
if len(components) < 2 {
52+
return nil, fmt.Errorf("url path for tarball link is missing components")
53+
}
54+
repo := &Repo{
55+
Org: components[0],
56+
Repo: components[1],
57+
}
58+
return repo, nil
59+
}
60+
61+
// Sha256 downloads the content from the given URL and returns its SHA256
62+
// checksum as a hex string.
63+
func Sha256(query string) (string, error) {
64+
response, err := http.Get(query)
65+
if err != nil {
66+
return "", err
67+
}
68+
if response.StatusCode >= 300 {
69+
return "", fmt.Errorf("http error in download %s", response.Status)
70+
}
71+
defer response.Body.Close()
72+
73+
hasher := sha256.New()
74+
if _, err := io.Copy(hasher, response.Body); err != nil {
75+
return "", err
76+
}
77+
got := fmt.Sprintf("%x", hasher.Sum(nil))
78+
return got, nil
79+
}
80+
81+
// LatestSha fetches the latest commit SHA from the GitHub API for the given
82+
// repository URL.
83+
func LatestSha(query string) (string, error) {
84+
client := &http.Client{}
85+
request, err := http.NewRequest(http.MethodGet, query, nil)
86+
if err != nil {
87+
return "", err
88+
}
89+
request.Header.Set("Accept", "application/vnd.github.VERSION.sha")
90+
response, err := client.Do(request)
91+
if err != nil {
92+
return "", err
93+
}
94+
if response.StatusCode >= 300 {
95+
return "", fmt.Errorf("http error in download %s", response.Status)
96+
}
97+
defer response.Body.Close()
98+
contents, err := io.ReadAll(response.Body)
99+
if err != nil {
100+
return "", err
101+
}
102+
return string(contents), nil
103+
}
104+
105+
// TarballLink constructs a GitHub tarball download URL for the given
106+
// repository and commit SHA.
107+
func TarballLink(githubDownload string, repo *Repo, sha string) string {
108+
return fmt.Sprintf("%s/%s/%s/archive/%s.tar.gz", githubDownload, repo.Org, repo.Repo, sha)
109+
}

internal/fetch/fetch_test.go

Lines changed: 193 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,193 @@
1+
// Copyright 2025 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package fetch
16+
17+
import (
18+
"net/http"
19+
"net/http/httptest"
20+
"testing"
21+
22+
"github.com/google/go-cmp/cmp"
23+
)
24+
25+
const (
26+
testGitHubDn = "https://localhost:12345"
27+
tarballPathTrailer = "/archive/5d5b1bf126485b0e2c972bac41b376438601e266.tar.gz"
28+
)
29+
30+
func TestRepoFromTarballLink(t *testing.T) {
31+
got, err := RepoFromTarballLink(testGitHubDn, testGitHubDn+"/org-name/repo-name"+tarballPathTrailer)
32+
if err != nil {
33+
t.Fatal(err)
34+
}
35+
want := &Repo{
36+
Org: "org-name",
37+
Repo: "repo-name",
38+
}
39+
if diff := cmp.Diff(want, got); diff != "" {
40+
t.Errorf("mismatch (-want +got):\n%s", diff)
41+
}
42+
}
43+
44+
func TestRepoFromTarballLinkErrors(t *testing.T) {
45+
for _, test := range []struct {
46+
tarballLink string
47+
}{
48+
{tarballLink: "too-short"},
49+
} {
50+
if got, err := RepoFromTarballLink(testGitHubDn, test.tarballLink); err == nil {
51+
t.Errorf("expected an error, got=%v", got)
52+
}
53+
}
54+
}
55+
56+
func TestSha256(t *testing.T) {
57+
const (
58+
tarballPath = "/googleapis/googleapis/archive/5d5b1bf126485b0e2c972bac41b376438601e266.tar.gz"
59+
latestShaContents = "The quick brown fox jumps over the lazy dog"
60+
latestShaContentsHash = "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"
61+
)
62+
63+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
64+
if r.URL.Path != tarballPath {
65+
t.Fatalf("unexpected request path %q", r.URL.Path)
66+
}
67+
w.WriteHeader(http.StatusOK)
68+
w.Write([]byte(latestShaContents))
69+
}))
70+
defer server.Close()
71+
72+
got, err := Sha256(server.URL + tarballPath)
73+
if err != nil {
74+
t.Fatal(err)
75+
}
76+
if got != latestShaContentsHash {
77+
t.Errorf("Sha256() = %q, want %q", got, latestShaContentsHash)
78+
}
79+
}
80+
81+
func TestSha256Error(t *testing.T) {
82+
for _, test := range []struct {
83+
name string
84+
url string
85+
}{
86+
{
87+
name: "http status error",
88+
url: func() string {
89+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
90+
w.WriteHeader(http.StatusBadRequest)
91+
w.Write([]byte("ERROR - bad request"))
92+
}))
93+
t.Cleanup(server.Close)
94+
return server.URL + "/test"
95+
}(),
96+
},
97+
{
98+
name: "invalid url",
99+
url: "http://invalid-url-that-does-not-exist-12345.local",
100+
},
101+
} {
102+
t.Run(test.name, func(t *testing.T) {
103+
if _, err := Sha256(test.url); err == nil {
104+
t.Error("expected an error from Sha256()")
105+
}
106+
})
107+
}
108+
}
109+
110+
func TestLatestSha(t *testing.T) {
111+
const (
112+
getLatestShaPath = "/repos/googleapis/googleapis/commits/master"
113+
latestSha = "5d5b1bf126485b0e2c972bac41b376438601e266"
114+
)
115+
116+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
117+
if r.URL.Path != getLatestShaPath {
118+
t.Fatalf("unexpected request path %q", r.URL.Path)
119+
}
120+
got := r.Header.Get("Accept")
121+
want := "application/vnd.github.VERSION.sha"
122+
if got != want {
123+
t.Fatalf("mismatched Accept header for %q, got=%q, want=%s", r.URL.Path, got, want)
124+
}
125+
w.WriteHeader(http.StatusOK)
126+
w.Write([]byte(latestSha))
127+
}))
128+
defer server.Close()
129+
130+
got, err := LatestSha(server.URL + getLatestShaPath)
131+
if err != nil {
132+
t.Fatal(err)
133+
}
134+
if got != latestSha {
135+
t.Errorf("LatestSha() = %q, want %q", got, latestSha)
136+
}
137+
}
138+
139+
func TestLatestShaError(t *testing.T) {
140+
for _, test := range []struct {
141+
name string
142+
url string
143+
}{
144+
{
145+
name: "http status error",
146+
url: func() string {
147+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
148+
w.WriteHeader(http.StatusBadRequest)
149+
w.Write([]byte("ERROR - bad request"))
150+
}))
151+
t.Cleanup(server.Close)
152+
return server.URL + "/test"
153+
}(),
154+
},
155+
{
156+
name: "invalid url",
157+
url: "http://invalid-url-that-does-not-exist-12345.local",
158+
},
159+
} {
160+
t.Run(test.name, func(t *testing.T) {
161+
if _, err := LatestSha(test.url); err == nil {
162+
t.Error("expected an error from LatestSha()")
163+
}
164+
})
165+
}
166+
}
167+
168+
func TestTarballLink(t *testing.T) {
169+
for _, test := range []struct {
170+
githubDownload string
171+
repo *Repo
172+
sha string
173+
want string
174+
}{
175+
{
176+
githubDownload: "https://github.com",
177+
repo: &Repo{Org: "googleapis", Repo: "googleapis"},
178+
sha: "abc123",
179+
want: "https://github.com/googleapis/googleapis/archive/abc123.tar.gz",
180+
},
181+
{
182+
githubDownload: "https://test.example.com",
183+
repo: &Repo{Org: "my-org", Repo: "my-repo"},
184+
sha: "def456",
185+
want: "https://test.example.com/my-org/my-repo/archive/def456.tar.gz",
186+
},
187+
} {
188+
got := TarballLink(test.githubDownload, test.repo, test.sha)
189+
if got != test.want {
190+
t.Errorf("TarballLink() = %q, want %q", got, test.want)
191+
}
192+
}
193+
}

0 commit comments

Comments
 (0)