|
| 1 | +package github |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "net/http" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/databricks/cli/libs/log" |
| 13 | +) |
| 14 | + |
| 15 | +const gitHubAPI = "https://api.github.com" |
| 16 | +const gitHubUserContent = "https://raw.githubusercontent.com" |
| 17 | + |
| 18 | +// Placeholders to use as unique keys in context.Context. |
| 19 | +var apiOverride int |
| 20 | +var userContentOverride int |
| 21 | + |
| 22 | +func WithApiOverride(ctx context.Context, override string) context.Context { |
| 23 | + return context.WithValue(ctx, &apiOverride, override) |
| 24 | +} |
| 25 | + |
| 26 | +func WithUserContentOverride(ctx context.Context, override string) context.Context { |
| 27 | + return context.WithValue(ctx, &userContentOverride, override) |
| 28 | +} |
| 29 | + |
| 30 | +var ErrNotFound = errors.New("not found") |
| 31 | + |
| 32 | +func getBytes(ctx context.Context, method, url string, body io.Reader) ([]byte, error) { |
| 33 | + ao, ok := ctx.Value(&apiOverride).(string) |
| 34 | + if ok { |
| 35 | + url = strings.Replace(url, gitHubAPI, ao, 1) |
| 36 | + } |
| 37 | + uco, ok := ctx.Value(&userContentOverride).(string) |
| 38 | + if ok { |
| 39 | + url = strings.Replace(url, gitHubUserContent, uco, 1) |
| 40 | + } |
| 41 | + log.Tracef(ctx, "%s %s", method, url) |
| 42 | + req, err := http.NewRequestWithContext(ctx, "GET", url, body) |
| 43 | + if err != nil { |
| 44 | + return nil, err |
| 45 | + } |
| 46 | + res, err := http.DefaultClient.Do(req) |
| 47 | + if err != nil { |
| 48 | + return nil, err |
| 49 | + } |
| 50 | + if res.StatusCode == 404 { |
| 51 | + return nil, ErrNotFound |
| 52 | + } |
| 53 | + if res.StatusCode >= 400 { |
| 54 | + return nil, fmt.Errorf("github request failed: %s", res.Status) |
| 55 | + } |
| 56 | + defer res.Body.Close() |
| 57 | + return io.ReadAll(res.Body) |
| 58 | +} |
| 59 | + |
| 60 | +func httpGetAndUnmarshall(ctx context.Context, url string, response any) error { |
| 61 | + raw, err := getBytes(ctx, "GET", url, nil) |
| 62 | + if err != nil { |
| 63 | + return err |
| 64 | + } |
| 65 | + return json.Unmarshal(raw, response) |
| 66 | +} |
0 commit comments