github.com/cli/cli@v1.14.1-0.20210902173923-1af6a669e342/pkg/cmd/repo/view/http.go (about)

     1  package view
     2  
     3  import (
     4  	"encoding/base64"
     5  	"errors"
     6  	"fmt"
     7  	"net/http"
     8  
     9  	"github.com/cli/cli/api"
    10  	"github.com/cli/cli/internal/ghrepo"
    11  )
    12  
    13  var NotFoundError = errors.New("not found")
    14  
    15  func fetchRepository(apiClient *api.Client, repo ghrepo.Interface, fields []string) (*api.Repository, error) {
    16  	query := fmt.Sprintf(`query RepositoryInfo($owner: String!, $name: String!) {
    17  		repository(owner: $owner, name: $name) {%s}
    18  	}`, api.RepositoryGraphQL(fields))
    19  
    20  	variables := map[string]interface{}{
    21  		"owner": repo.RepoOwner(),
    22  		"name":  repo.RepoName(),
    23  	}
    24  
    25  	var result struct {
    26  		Repository api.Repository
    27  	}
    28  	if err := apiClient.GraphQL(repo.RepoHost(), query, variables, &result); err != nil {
    29  		return nil, err
    30  	}
    31  	return api.InitRepoHostname(&result.Repository, repo.RepoHost()), nil
    32  }
    33  
    34  type RepoReadme struct {
    35  	Filename string
    36  	Content  string
    37  	BaseURL  string
    38  }
    39  
    40  func RepositoryReadme(client *http.Client, repo ghrepo.Interface, branch string) (*RepoReadme, error) {
    41  	apiClient := api.NewClientFromHTTP(client)
    42  	var response struct {
    43  		Name    string
    44  		Content string
    45  		HTMLURL string `json:"html_url"`
    46  	}
    47  
    48  	err := apiClient.REST(repo.RepoHost(), "GET", getReadmePath(repo, branch), nil, &response)
    49  	if err != nil {
    50  		var httpError api.HTTPError
    51  		if errors.As(err, &httpError) && httpError.StatusCode == 404 {
    52  			return nil, NotFoundError
    53  		}
    54  		return nil, err
    55  	}
    56  
    57  	decoded, err := base64.StdEncoding.DecodeString(response.Content)
    58  	if err != nil {
    59  		return nil, fmt.Errorf("failed to decode readme: %w", err)
    60  	}
    61  
    62  	return &RepoReadme{
    63  		Filename: response.Name,
    64  		Content:  string(decoded),
    65  		BaseURL:  response.HTMLURL,
    66  	}, nil
    67  }
    68  
    69  func getReadmePath(repo ghrepo.Interface, branch string) string {
    70  	path := fmt.Sprintf("repos/%s/readme", ghrepo.FullName(repo))
    71  	if branch != "" {
    72  		path = fmt.Sprintf("%s?ref=%s", path, branch)
    73  	}
    74  	return path
    75  }