github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/pkg/cmd/run/download/http.go (about)

     1  package download
     2  
     3  import (
     4  	"archive/zip"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"os"
     9  
    10  	"github.com/ungtb10d/cli/v2/api"
    11  	"github.com/ungtb10d/cli/v2/internal/ghrepo"
    12  	"github.com/ungtb10d/cli/v2/pkg/cmd/run/shared"
    13  )
    14  
    15  type apiPlatform struct {
    16  	client *http.Client
    17  	repo   ghrepo.Interface
    18  }
    19  
    20  func (p *apiPlatform) List(runID string) ([]shared.Artifact, error) {
    21  	return shared.ListArtifacts(p.client, p.repo, runID)
    22  }
    23  
    24  func (p *apiPlatform) Download(url string, dir string) error {
    25  	return downloadArtifact(p.client, url, dir)
    26  }
    27  
    28  func downloadArtifact(httpClient *http.Client, url, destDir string) error {
    29  	req, err := http.NewRequest("GET", url, nil)
    30  	if err != nil {
    31  		return err
    32  	}
    33  	// The server rejects this :(
    34  	//req.Header.Set("Accept", "application/zip")
    35  
    36  	resp, err := httpClient.Do(req)
    37  	if err != nil {
    38  		return err
    39  	}
    40  	defer resp.Body.Close()
    41  
    42  	if resp.StatusCode > 299 {
    43  		return api.HandleHTTPError(resp)
    44  	}
    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  	if err := extractZip(zipfile, destDir); err != nil {
    65  		return fmt.Errorf("error extracting zip archive: %w", err)
    66  	}
    67  
    68  	return nil
    69  }