github.com/ungtb10d/cli/v2@v2.0.0-20221110210412-98537dd9d6a1/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/ungtb10d/cli/v2/api"
    10  	"github.com/ungtb10d/cli/v2/internal/ghrepo"
    11  )
    12  
    13  var NotFoundError = errors.New("not found")
    14  
    15  type RepoReadme struct {
    16  	Filename string
    17  	Content  string
    18  	BaseURL  string
    19  }
    20  
    21  func RepositoryReadme(client *http.Client, repo ghrepo.Interface, branch string) (*RepoReadme, error) {
    22  	apiClient := api.NewClientFromHTTP(client)
    23  	var response struct {
    24  		Name    string
    25  		Content string
    26  		HTMLURL string `json:"html_url"`
    27  	}
    28  
    29  	err := apiClient.REST(repo.RepoHost(), "GET", getReadmePath(repo, branch), nil, &response)
    30  	if err != nil {
    31  		var httpError api.HTTPError
    32  		if errors.As(err, &httpError) && httpError.StatusCode == 404 {
    33  			return nil, NotFoundError
    34  		}
    35  		return nil, err
    36  	}
    37  
    38  	decoded, err := base64.StdEncoding.DecodeString(response.Content)
    39  	if err != nil {
    40  		return nil, fmt.Errorf("failed to decode readme: %w", err)
    41  	}
    42  
    43  	return &RepoReadme{
    44  		Filename: response.Name,
    45  		Content:  string(decoded),
    46  		BaseURL:  response.HTMLURL,
    47  	}, nil
    48  }
    49  
    50  func getReadmePath(repo ghrepo.Interface, branch string) string {
    51  	path := fmt.Sprintf("repos/%s/readme", ghrepo.FullName(repo))
    52  	if branch != "" {
    53  		path = fmt.Sprintf("%s?ref=%s", path, branch)
    54  	}
    55  	return path
    56  }