github.com/andrewhsu/cli/v2@v2.0.1-0.20210910131313-d4b4061f5b89/pkg/cmd/run/shared/artifacts.go (about)

     1  package shared
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  
     8  	"github.com/andrewhsu/cli/v2/api"
     9  	"github.com/andrewhsu/cli/v2/internal/ghinstance"
    10  	"github.com/andrewhsu/cli/v2/internal/ghrepo"
    11  )
    12  
    13  type Artifact struct {
    14  	Name        string `json:"name"`
    15  	Size        uint64 `json:"size_in_bytes"`
    16  	DownloadURL string `json:"archive_download_url"`
    17  	Expired     bool   `json:"expired"`
    18  }
    19  
    20  func ListArtifacts(httpClient *http.Client, repo ghrepo.Interface, runID string) ([]Artifact, error) {
    21  	perPage := 100
    22  	path := fmt.Sprintf("repos/%s/%s/actions/artifacts?per_page=%d", repo.RepoOwner(), repo.RepoName(), perPage)
    23  	if runID != "" {
    24  		path = fmt.Sprintf("repos/%s/%s/actions/runs/%s/artifacts?per_page=%d", repo.RepoOwner(), repo.RepoName(), runID, perPage)
    25  	}
    26  
    27  	req, err := http.NewRequest("GET", ghinstance.RESTPrefix(repo.RepoHost())+path, nil)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	resp, err := httpClient.Do(req)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	defer resp.Body.Close()
    37  
    38  	if resp.StatusCode > 299 {
    39  		return nil, api.HandleHTTPError(resp)
    40  	}
    41  
    42  	var response struct {
    43  		TotalCount uint16 `json:"total_count"`
    44  		Artifacts  []Artifact
    45  	}
    46  
    47  	dec := json.NewDecoder(resp.Body)
    48  	if err := dec.Decode(&response); err != nil {
    49  		return response.Artifacts, fmt.Errorf("error parsing JSON: %w", err)
    50  	}
    51  
    52  	return response.Artifacts, nil
    53  }