cli/pkg/cmd/run/download/http.go
Babak K. Shandiz 0f32f2ac46
refactor(run download): extract zip extraction func into a separate package
Signed-off-by: Babak K. Shandiz <babakks@github.com>

Co-authored-by: Kynan Ware <bagtoad@github.com>
Co-authored-by: Devraj Mehta <devm33@github.com>
2026-01-19 10:38:21 +00:00

71 lines
1.6 KiB
Go

package download
import (
"archive/zip"
"fmt"
"io"
"net/http"
"os"
"github.com/cli/cli/v2/api"
"github.com/cli/cli/v2/internal/ghrepo"
"github.com/cli/cli/v2/internal/safepaths"
ghzip "github.com/cli/cli/v2/internal/zip"
"github.com/cli/cli/v2/pkg/cmd/run/shared"
)
type apiPlatform struct {
client *http.Client
repo ghrepo.Interface
}
func (p *apiPlatform) List(runID string) ([]shared.Artifact, error) {
return shared.ListArtifacts(p.client, p.repo, runID)
}
func (p *apiPlatform) Download(url string, dir safepaths.Absolute) error {
return downloadArtifact(p.client, url, dir)
}
func downloadArtifact(httpClient *http.Client, url string, destDir safepaths.Absolute) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
// The server rejects this :(
//req.Header.Set("Accept", "application/zip")
resp, err := httpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return api.HandleHTTPError(resp)
}
tmpfile, err := os.CreateTemp("", "gh-artifact.*.zip")
if err != nil {
return fmt.Errorf("error initializing temporary file: %w", err)
}
defer func() {
_ = tmpfile.Close()
_ = os.Remove(tmpfile.Name())
}()
size, err := io.Copy(tmpfile, resp.Body)
if err != nil {
return fmt.Errorf("error writing zip archive: %w", err)
}
zipfile, err := zip.NewReader(tmpfile, size)
if err != nil {
return fmt.Errorf("error extracting zip archive: %w", err)
}
if err := ghzip.ExtractZip(zipfile, destDir); err != nil {
return fmt.Errorf("error extracting zip archive: %w", err)
}
return nil
}