gh

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 10, 2022 License: MIT Imports: 15 Imported by: 178

README

go-gh beta

This project is in beta! Feedback is welcome.

A Go module for CLI Go applications and gh extensions that want a convenient way to interact with gh, and the GitHub API using gh environment configuration.

go-gh supports multiple ways of getting access to gh functionality:

  • Helpers that automatically read a gh config to authenticate themselves
  • gh.Exec shells out to a gh install on your machine

If you'd like to use go-gh on systems without gh installed and configured, you can provide custom authentication details to the go-gh API helpers.

Installation

go get github.com/cli/go-gh

Usage

package main
import (
	"fmt"
	"github.com/cli/go-gh"
)

func main() {
	// These examples assume `gh` is installed and has been authenticated

	// Execute `gh issue list -R cli/cli`, and print the output.
	args := []string{"issue", "list", "-R", "cli/cli"}
	stdOut, _, err := gh.Exec(args...)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(stdOut.String())
	
	// Use an API helper to grab repository tags
	client, err := gh.RESTClient(nil)
	if err != nil {
		fmt.Println(err)
		return
	}
	response := []struct{ Name string }{}
	err = client.Get("repos/cli/cli/tags", &response)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(response)
}

See examples for more use cases.

Reference Documentation

Full reference docs can be found on pkg.go.dev.

Contributing

If anything feels off, or if you feel that some functionality is missing, please check out the contributing page. There you will find instructions for sharing your feedback, and submitting pull requests to the project.

Documentation

Overview

Package gh is a library for CLI Go applications to help interface with the gh CLI tool, and the GitHub API.

Note that the examples in this package assume gh and git are installed. They do not run in the Go Playground used by pkg.go.dev.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CurrentRepository

func CurrentRepository() (repo.Repository, error)

CurrentRepository uses git remotes to determine the GitHub repository the current directory is tracking.

Example

Get repository for the current directory.

repo, err := CurrentRepository()
if err != nil {
	log.Fatal(err)
}
fmt.Printf("%s/%s/%s\n", repo.Host(), repo.Owner(), repo.Name())
Output:

func Exec

func Exec(args ...string) (stdOut, stdErr bytes.Buffer, err error)

Exec gh command with provided arguments.

Example

Execute 'gh issue list -R cli/cli', and print the output.

args := []string{"issue", "list", "-R", "cli/cli"}
stdOut, stdErr, err := Exec(args...)
if err != nil {
	log.Fatal(err)
}
fmt.Println(stdOut.String())
fmt.Println(stdErr.String())
Output:

func GQLClient

func GQLClient(opts *api.ClientOptions) (api.GQLClient, error)

GQLClient builds a client to send requests to GitHub GraphQL API endpoints. As part of the configuration a hostname, auth token, default set of headers, and unix domain socket are resolved from the gh environment configuration. These behaviors can be overridden using the opts argument.

Example (Advanced)

Query tags from cli/cli repository using GQL API. Enable caching and request timeout.

opts := api.ClientOptions{
	EnableCache: true,
	Timeout:     5 * time.Second,
}
client, err := GQLClient(&opts)
if err != nil {
	log.Fatal(err)
}
var query struct {
	Repository struct {
		Refs struct {
			Nodes []struct {
				Name string
			}
		} `graphql:"refs(refPrefix: $refPrefix, last: $last)"`
	} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]interface{}{
	"refPrefix": graphql.String("refs/tags/"),
	"last":      graphql.Int(30),
	"owner":     graphql.String("cli"),
	"name":      graphql.String("cli"),
}
err = client.Query("RepositoryTags", &query, variables)
if err != nil {
	log.Fatal(err)
}
fmt.Println(query)
Output:

Example (Simple)

Query tags from cli/cli repository using GQL API.

client, err := GQLClient(nil)
if err != nil {
	log.Fatal(err)
}
var query struct {
	Repository struct {
		Refs struct {
			Nodes []struct {
				Name string
			}
		} `graphql:"refs(refPrefix: $refPrefix, last: $last)"`
	} `graphql:"repository(owner: $owner, name: $name)"`
}
variables := map[string]interface{}{
	"refPrefix": graphql.String("refs/tags/"),
	"last":      graphql.Int(30),
	"owner":     graphql.String("cli"),
	"name":      graphql.String("cli"),
}
err = client.Query("RepositoryTags", &query, variables)
if err != nil {
	log.Fatal(err)
}
fmt.Println(query)
Output:

func HTTPClient added in v0.0.2

func HTTPClient(opts *api.ClientOptions) (*http.Client, error)

HTTPClient builds a client that can be passed to another library. As part of the configuration a hostname, auth token, default set of headers, and unix domain socket are resolved from the gh environment configuration. These behaviors can be overridden using the opts argument. In this instance providing opts.Host will not change the destination of your request as it is the responsibility of the consumer to configure this. However, if opts.Host does not match the request host, the auth token will not be added to the headers. This is to protect against the case where tokens could be sent to an arbitrary host.

func RESTClient

func RESTClient(opts *api.ClientOptions) (api.RESTClient, error)

RESTClient builds a client to send requests to GitHub REST API endpoints. As part of the configuration a hostname, auth token, default set of headers, and unix domain socket are resolved from the gh environment configuration. These behaviors can be overridden using the opts argument.

Example (Advanced)

Get tags from cli/cli repository using REST API. Specifying host, auth token, headers and logging to stdout.

opts := api.ClientOptions{
	Host:      "github.com",
	AuthToken: "xxxxxxxxxx", // Replace with valid auth token.
	Headers:   map[string]string{"Time-Zone": "America/Los_Angeles"},
	Log:       os.Stdout,
}
client, err := RESTClient(&opts)
if err != nil {
	log.Fatal(err)
}
response := []struct{ Name string }{}
err = client.Get("repos/cli/cli/tags", &response)
if err != nil {
	log.Fatal(err)
}
fmt.Println(response)
Output:

Example (Request)

Get release asset from cli/cli repository using REST API.

opts := api.ClientOptions{
	Headers: map[string]string{"Accept": "application/octet-stream"},
}
client, err := RESTClient(&opts)
if err != nil {
	log.Fatal(err)
}

// URL to cli/cli release v2.14.2 checksums.txt
assetURL := "repos/cli/cli/releases/assets/71589494"
resp, err := client.Request("GET", assetURL, nil)
if err != nil {
	log.Fatal(err)
}
defer resp.Body.Close()

if resp.StatusCode > 299 {
	log.Fatal("server error")
}

f, err := os.CreateTemp("", "*_checksums.txt")
if err != nil {
	log.Fatal(err)
}
defer f.Close()

_, err = io.Copy(f, resp.Body)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Asset downloaded to %s\n", f.Name())
Output:

Example (Simple)

Get tags from cli/cli repository using REST API.

client, err := RESTClient(nil)
if err != nil {
	log.Fatal(err)
}
response := []struct{ Name string }{}
err = client.Get("repos/cli/cli/tags", &response)
if err != nil {
	log.Fatal(err)
}
fmt.Println(response)
Output:

Types

This section is empty.

Directories

Path Synopsis
internal
api
git
set
yamlmap
Package yamlmap is a wrapper of gopkg.in/yaml.v3 for interacting with yaml data as if it were a map.
Package yamlmap is a wrapper of gopkg.in/yaml.v3 for interacting with yaml data as if it were a map.
pkg
api
Package api is a set of types for interacting with the GitHub API.
Package api is a set of types for interacting with the GitHub API.
auth
Package auth is a set of functions for retrieving authentication tokens and authenticated hosts.
Package auth is a set of functions for retrieving authentication tokens and authenticated hosts.
browser
Package browser facilitates opening of URLs in a web browser.
Package browser facilitates opening of URLs in a web browser.
config
Package config is a set of types for interacting with the gh configuration files.
Package config is a set of types for interacting with the gh configuration files.
jsonpretty
Package jsonpretty implements a terminal pretty-printer for JSON.
Package jsonpretty implements a terminal pretty-printer for JSON.
repository
Package repository is a set of types and functions for modeling and interacting with GitHub repositories.
Package repository is a set of types and functions for modeling and interacting with GitHub repositories.
ssh
Package ssh is a set of types and functions for parsing and applying a user's SSH hostname aliases.
Package ssh is a set of types and functions for parsing and applying a user's SSH hostname aliases.
tableprinter
Package tableprinter facilitates rendering column-formatted data to a terminal and TSV-formatted data to a script or a file.
Package tableprinter facilitates rendering column-formatted data to a terminal and TSV-formatted data to a script or a file.
term
Package term provides information about the terminal that the current process is connected to (if any), for example measuring the dimensions of the terminal and inspecting whether it's safe to output color.
Package term provides information about the terminal that the current process is connected to (if any), for example measuring the dimensions of the terminal and inspecting whether it's safe to output color.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL