| 29 | } |
| 30 | |
| 31 | func downloadArtifact(httpClient *http.Client, hostname string, url safeurl.SafeURL, openDestination func() (*safepaths.Root, error)) (downloadErr error) { |
| 32 | // The server rejects this :( |
| 33 | //api.WithHeader("Accept", "application/zip") |
| 34 | // |
| 35 | // The artifact download URL is supplied by the API, so it is absolute and is requested as |
| 36 | // given rather than being resolved against the host's REST endpoint. |
| 37 | // TODO(api-client-rollout) |
| 38 | // This line of code is part of a mechanical roll out of the api client. |
| 39 | // As a follow up, consider whether the api client can be injected to this call site, rather than constructed |
| 40 | resp, err := api.NewClientFromHTTP(httpClient).Request(hostname, http.MethodGet, url.String(), nil) |
| 41 | if err != nil { |
| 42 | return err |
| 43 | } |
| 44 | defer resp.Body.Close() |
| 45 | |
| 46 | tmpfile, err := os.CreateTemp("", "gh-artifact.*.zip") |
| 47 | if err != nil { |
| 48 | return fmt.Errorf("error initializing temporary file: %w", err) |
| 49 | } |
| 50 | defer func() { |
| 51 | _ = tmpfile.Close() |
| 52 | _ = os.Remove(tmpfile.Name()) |
| 53 | }() |
| 54 | |
| 55 | size, err := io.Copy(tmpfile, resp.Body) |
| 56 | if err != nil { |
| 57 | return fmt.Errorf("error writing zip archive: %w", err) |
| 58 | } |
| 59 | |
| 60 | zipfile, err := zip.NewReader(tmpfile, size) |
| 61 | if err != nil { |
| 62 | return fmt.Errorf("error extracting zip archive: %w", err) |
| 63 | } |
| 64 | destDir, err := openDestination() |
| 65 | if err != nil { |
| 66 | return err |
| 67 | } |
| 68 | defer func() { |
| 69 | if err := destDir.Close(); downloadErr == nil && err != nil { |
| 70 | downloadErr = err |
| 71 | } |
| 72 | }() |
| 73 | if err := ghzip.ExtractZip(zipfile, destDir); err != nil { |
| 74 | return fmt.Errorf("error extracting zip archive: %w", err) |
| 75 | } |
| 76 | |
| 77 | return nil |
| 78 | } |