### Template Funcs Example Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/template Illustrates the output when custom functions are applied within a template. ```text Output: * 1 apple * 2 oranges ``` -------------------------------- ### PrompterMock Basic Usage Example Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Demonstrates how to use PrompterMock with a ConfirmPrompter interface and test function. ```go type ConfirmPrompter interface { Confirm(string, bool) (bool, error) } func PlayGame(prompter ConfirmPrompter) (int, error) { confirm, err := prompter.Confirm("Shall we play a game", true) if err != nil { return 0, err } if confirm { return 1, nil } return 2, nil } func TestPlayGame(t *testing.T) { expectedOutcome := 1 mock := NewMock(t) mock.RegisterConfirm("Shall we play a game", func(prompt string, defaultValue bool) (bool, error) { return true, nil }) outcome, err := PlayGame(mock) if err != nil { t.Fatalf("unexpected error: %v", err) } if outcome != expectedOutcome { t.Errorf("expected %q, got %q", expectedOutcome, outcome) } } ``` -------------------------------- ### Execute gh Command and Get Output Source: https://pkg.go.dev/github.com/cli/go-gh/v2 Shells out to a `gh` command (e.g., `issue list`) and captures its standard output. Assumes `gh` is installed and authenticated. Handles potential errors during command execution. ```go package main import ( "fmt" "log" "github.com/cli/go-gh/v2" "github.com/cli/go-gh/v2/pkg/api" ) func main() { // These examples assume `gh` is installed and has been authenticated. // Shell out to a gh command and read its output. issueList, _, err := gh.Exec("issue", "list", "--repo", "cli/cli", "--limit", "5") if err != nil { log.Fatal(err) } fmt.Println(issueList.String()) // Use an API client to retrieve repository tags. client, err := api.DefaultRESTClient() 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) } ``` -------------------------------- ### Template Example Usage Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/template Demonstrates the output format of a processed template, including headers, lists, and footers. ```text Output: HEADER 1 One 2 Two FOOTER ``` -------------------------------- ### Create New StringSet Source: https://pkg.go.dev/github.com/cli/go-gh/v2/internal/set Initializes and returns a new, empty stringSet. Use this to start managing unique strings. ```go func NewStringSet() *stringSet ``` -------------------------------- ### Get Default Host and Source Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Retrieves the default authenticated host and its source (environment variable or config file). Returns "github.com", "default" if no viable host is found. ```go func DefaultHost() (string, string) ``` -------------------------------- ### Get Terminal Theme Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/term Theme returns the terminal's theme by analyzing its background color. ```go func (t Term) Theme() string ``` -------------------------------- ### Perform REST GET Request Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Issues a GET request to the specified path. The response is populated into the provided response argument. ```go func (c *RESTClient) Get(path string, resp interface{}) error ``` -------------------------------- ### Get Configuration Directory Path Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Returns the path to the configuration directory. Precedence is given to GH_CONFIG_DIR, then XDG_CONFIG_HOME, then AppData (Windows), then HOME. ```go func ConfigDir() string ``` -------------------------------- ### Get Token from Environment or Config Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Retrieves an authentication token from environment variables or the config file as a fallback. This function does not support reading tokens from the system keyring. Most consumers should use TokenForHost. ```go func TokenFromEnvOrConfig(host string) (string, string) ``` -------------------------------- ### Get State Directory Path Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Returns the path to the state directory. Precedence is given to XDG_STATE_HOME, then LocalAppData (Windows), then HOME. ```go func StateDir() string ``` -------------------------------- ### Get Data Directory Path Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Returns the path to the data directory. Precedence is given to XDG_DATA_HOME, then LocalAppData (Windows), then HOME. ```go func DataDir() string ``` -------------------------------- ### Get Keys from YAML Map Source: https://pkg.go.dev/github.com/cli/go-gh/v2/internal/yamlmap Returns a slice of all keys present in the map. ```go func (m *Map) Keys() []string ``` -------------------------------- ### RESTClient.Get Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Issues a GET request to the specified path. The response is populated into the response argument. ```APIDOC ## GET /path ### Description Issues a GET request to the specified path. ### Method GET ### Endpoint /path ### Parameters #### Path Parameters - **path** (string) - Required - The API path to send the request to. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **resp** (interface{}) - Populated with the response body. #### Error Response - **error** (error) - An error if the request fails. ``` -------------------------------- ### Get Default HTTP Client Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Retrieves the default HTTP client configured for GitHub API interactions. ```go func DefaultHTTPClient() (*http.Client, error) ``` -------------------------------- ### Get Standard Output Writer Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/term The Out method returns the writer associated with standard output for the Term. ```go func (t Term) Out() io.Writer ``` -------------------------------- ### Get All Remotes Source: https://pkg.go.dev/github.com/cli/go-gh/v2/internal/git Retrieves all configured git remotes for the current repository. Returns a RemoteSet and an error if any issues occur during retrieval. ```go func Remotes() (RemoteSet, error) ``` -------------------------------- ### Execute gh issue list command Source: https://pkg.go.dev/github.com/cli/go-gh/v2 Executes the 'gh issue list -R cli/cli' command and captures its standard output and error streams. Assumes gh and git are installed. ```go stdout, stderr, err := gh.Exec("issue", "list", "-R", "cli/cli") if err != nil { fmt.Println(string(stderr.Bytes())) return } fmt.Println(string(stdout.Bytes())) ``` -------------------------------- ### Get Default REST Client Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Returns a RESTClient configured with default settings, including authentication and host, resolved from the gh environment configuration. ```go func DefaultRESTClient() (*RESTClient, error) ``` -------------------------------- ### Get Standard Input Reader Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/term The In method returns the reader associated with standard input for the Term. ```go func (t Term) In() io.Reader ``` -------------------------------- ### Get Cache Directory Path Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Returns the path to the cache directory. Precedence is given to XDG_CACHE_HOME, then LocalAppData (Windows), then HOME, and finally a legacy gh-cli-cache. ```go func CacheDir() string ``` -------------------------------- ### Get Token for Host Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Retrieves an authentication token and its source for a specified host. Supports environment variables, configuration files, and system keyring (via 'gh auth token'). Returns "", "default" if no token is found. ```go func TokenForHost(host string) (string, string) ``` -------------------------------- ### Config.Get Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Gets a string value from a Config. The keys argument is a sequence of key values to retrieve nested entries. Returns an empty string and KeyNotFoundError if any keys cannot be found. ```APIDOC ## func (*Config) Get ### Description Get a string value from a Config. The keys argument is a sequence of key values so that nested entries can be retrieved. A undefined string will be returned if trying to retrieve a key that corresponds to a map value. Returns "", KeyNotFoundError if any of the keys can not be found. ### Signature ```go func (c *Config) Get(keys []string) (string, error) ``` ``` -------------------------------- ### RESTClient Methods Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Provides methods for interacting with the GitHub REST API, including GET, POST, PUT, PATCH, DELETE, and general Do requests. ```APIDOC ## RESTClient Operations ### Description Methods for interacting with the GitHub REST API. ### Methods - **DefaultRESTClient()** (*RESTClient, error): Returns a REST client with default configurations. - **NewRESTClient**(opts ClientOptions) (*RESTClient, error): Creates a REST client with custom options. - **Delete**(path string, resp interface{}) error: Sends a DELETE request to the specified path. - **Do**(method string, path string, body io.Reader, response interface{}) error: Sends a generic HTTP request. - **DoWithContext**(ctx context.Context, method string, path string, body io.Reader, ...) error: Sends a generic HTTP request with context. - **Get**(path string, resp interface{}) error: Sends a GET request to the specified path. - **Patch**(path string, body io.Reader, resp interface{}) error: Sends a PATCH request to the specified path. - **Post**(path string, body io.Reader, resp interface{}) error: Sends a POST request to the specified path. - **Put**(path string, body io.Reader, resp interface{}) error: Sends a PUT request to the specified path. - **Request**(method string, path string, body io.Reader) (*http.Response, error): Performs an HTTP request and returns the raw response. - **RequestWithContext**(ctx context.Context, method string, path string, body io.Reader) (*http.Response, error): Performs an HTTP request with context and returns the raw response. ``` -------------------------------- ### Get String Value from Config Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Retrieves a string value from the Config using a sequence of keys for nested access. Returns an error if keys are not found or if a key corresponds to a map. ```go func (c *Config) Get(keys []string) (string, error) ``` -------------------------------- ### Get Accessible Style Configuration Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/x/markdown Returns an ansi.StyleConfig for accessible markdown rendering based on the provided theme. Use this function to configure styling for markdown content to ensure accessibility. ```go func AccessibleStyleConfig(theme string) ansi.StyleConfig ``` -------------------------------- ### Initialize New Template Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/template Initializes a new Template instance with a writer, width, and color enablement. ```go func New(w io.Writer, width int, colorEnabled bool) *Template ``` -------------------------------- ### Create GraphQL Client with Options Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Builds a client for GitHub GraphQL API endpoints using provided `ClientOptions`. This allows customization of hostname, authentication, headers, and more. ```go func NewGraphQLClient(opts ClientOptions) (*GraphQLClient, error) ``` -------------------------------- ### New Browser Constructor Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/browser Initializes a new Browser instance. If no launcher is specified, it determines one based on environment variables (GH_BROWSER, BROWSER) or configuration. Requires stdout and stderr writers for potential output. ```go func New(launcher string, stdout, stderr io.Writer) *Browser ``` -------------------------------- ### New Browser Initialization Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/browser Initializes a new Browser instance. If no launcher is provided, it attempts to determine one based on environment variables or configuration. ```APIDOC ## func New ### Description New initializes a Browser. If a launcher is not specified one is determined based on environment variables or from the configuration file. The order of precedence for determining a launcher is: - Specified launcher; - GH_BROWSER environment variable; - browser option from configuration file; - BROWSER environment variable. ### Signature ``` func New(launcher string, stdout, stderr io.Writer) *Browser ``` ### Parameters * **launcher** (string) - The command to use to launch the browser. If empty, an attempt is made to auto-detect. * **stdout** (io.Writer) - The standard output writer. * **stderr** (io.Writer) - The standard error writer. ### Returns * (*Browser) - A pointer to the initialized Browser object. ``` -------------------------------- ### Create Default GraphQL Client Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Creates a GraphQL client using default configurations derived from the gh environment. Returns the client and an error if creation fails. ```go func DefaultGraphQLClient() (*GraphQLClient, error) ``` -------------------------------- ### Browse URL Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/browser Opens the configured web browser and navigates to the provided URL. Returns an error if the URL cannot be opened. ```go func (b *Browser) Browse(url string) error ``` -------------------------------- ### Get Standard Error Writer Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/term The ErrOut method returns the writer associated with standard error for the Term. ```go func (t Term) ErrOut() io.Writer ``` -------------------------------- ### Initialize Term from Environment Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/term Use FromEnv to initialize a Term struct using os.Stdout and relevant environment variables like GH_FORCE_TTY, NO_COLOR, CLICOLOR, CLICOLOR_FORCE, TERM, and COLORTERM. ```go func FromEnv() Term ``` -------------------------------- ### Template.New Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/template Initializes a new Template object with a specified writer, column width, and color enablement. ```APIDOC ## func New ### Description Initializes a Template. ### Signature ```go func New(w io.Writer, width int, colorEnabled bool) *Template ``` ``` -------------------------------- ### New Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/tableprinter Initializes a new TablePrinter. It takes an io.Writer for output, a boolean indicating if the output is a TTY, and the maximum width for the terminal. ```APIDOC ## func New ### Description Initializes a table printer with terminal mode and terminal width. When terminal mode is enabled, the output will be human-readable, column-formatted to fit available width, and rendered with color support. In non-terminal mode, the output is tab-separated and all truncation of values is disabled. ### Signature ``` func New(w io.Writer, isTTY bool, maxWidth int) TablePrinter ``` ### Parameters * **w** (io.Writer) - The writer to output the table to. * **isTTY** (bool) - A boolean indicating if the output is a terminal (TTY). * **maxWidth** (int) - The maximum width of the terminal. ### Returns * **TablePrinter** - An initialized TablePrinter interface. ``` -------------------------------- ### Get Terminal Size Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/term Size returns the width and height of the terminal. It returns -1 for numeric values in case of errors. ```go func (t Term) Size() (int, int, error) ``` -------------------------------- ### Parse Repository String Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/repository Extracts repository information from various string formats like 'OWNER/REPO', 'HOST/OWNER/REPO', or a full URL. Uses configuration to determine the host if not specified. ```go func Parse(s string) (Repository, error) ``` -------------------------------- ### Create New REST Client Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Builds a client to send requests to GitHub REST API endpoints. Configuration can be overridden using the opts argument. ```go func NewRESTClient(opts ClientOptions) (*RESTClient, error) ``` -------------------------------- ### Perform Raw REST Request (No Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Issues a request with the specified method and path, using context.Background. Returns the raw HTTP response and an error. ```go func (c *RESTClient) Request(method string, path string, body io.Reader) (*http.Response, error) ``` -------------------------------- ### New Prompter Constructor Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Instantiates a new Prompter with specified reader and writer interfaces. ```go func New(stdin FileReader, stdout FileWriter, stderr FileWriter) *Prompter ``` -------------------------------- ### Perform Raw REST Request (With Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Issues a request with the specified method, path, and body, using the provided context. Returns the raw HTTP response and an error. ```go func (c *RESTClient) RequestWithContext(ctx context.Context, method string, path string, body io.Reader) (*http.Response, error) ``` -------------------------------- ### Execute Template Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/template Applies the parsed template to input data and writes the result to the initialized writer. ```go func (t *Template) Execute(input io.Reader) error ``` -------------------------------- ### Create New HTTP Client Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Builds an HTTP client for API requests, resolving configuration from the gh environment. Overrides can be provided via ClientOptions. ```go func NewHTTPClient(opts ClientOptions) (*http.Client, error) ``` -------------------------------- ### Get Current Repository Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/repository Determines the GitHub repository the current directory is tracking using git remotes. Returns the Repository struct and an error if any. ```go func Current() (Repository, error) ``` -------------------------------- ### Read Configuration from String Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Parses a YAML string and returns a Config object. ```go func ReadFromString(str string) *Config ``` -------------------------------- ### Perform Generic REST Request (No Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Issues a request with the specified method and path, using context.Background. The response is populated into the response argument. ```go func (c *RESTClient) Do(method string, path string, body io.Reader, response interface{}) error ``` -------------------------------- ### Prompter Select Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Prompts the user to select a single option from a list. ```go func (p *Prompter) Select(prompt, defaultValue string, options []string) (int, error) ``` -------------------------------- ### DefaultHost Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Retrieves an authenticated host and its source (environment variable or configuration file). Returns 'github.com', 'default' if no host is found. ```APIDOC ## DefaultHost ### Description Retrieves an authenticated host and the source of host. The source can be either an environment variable or from the configuration file. Returns "github.com", "default" if no viable host is found. ### Signature ```go func DefaultHost() (string, string) ``` ``` -------------------------------- ### TokenFromEnvOrConfig Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Retrieves an authentication token from environment variables or config file, excluding system keyring. Most consumers should use TokenForHost. ```APIDOC ## TokenFromEnvOrConfig ### Description TokenFromEnvOrConfig retrieves an authentication token from environment variables or the config file as fallback, but does not support reading the token from system keyring. Most consumers should use TokenForHost. ### Signature ```go func TokenFromEnvOrConfig(host string) (string, string) ``` ``` -------------------------------- ### Prompter Input Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Prompts the user to input a single-line string with a default value. ```go func (p *Prompter) Input(prompt, defaultValue string) (string, error) ``` -------------------------------- ### Template.Execute Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/template Applies the parsed template to the input data and writes the resulting output to the initialized writer. ```APIDOC ## func (*Template) Execute ### Description Applies the parsed template to the input and writes result to the writer the template was initialized with. ### Signature ```go func (t *Template) Execute(input io.Reader) error ``` ``` -------------------------------- ### Term.FromEnv Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/term Initializes a Term object based on environment variables and standard output. ```APIDOC ## func Term.FromEnv ### Description FromEnv initializes a Term from os.Stdout and environment variables. ### Signature ```go func FromEnv() Term ``` ### Environment Variables - GH_FORCE_TTY - NO_COLOR - CLICOLOR - CLICOLOR_FORCE - TERM - COLORTERM ``` -------------------------------- ### Perform Generic REST Request (With Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Issues a request with the specified method, path, and body, using the provided context. The response is populated into the response argument. ```go func (c *RESTClient) DoWithContext(ctx context.Context, method string, path string, body io.Reader, response interface{}) error ``` -------------------------------- ### Parse Repository String with Host Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/repository Extracts repository information from various string formats, using a provided host if the format does not specify one. Supports 'OWNER/REPO', 'HOST/OWNER/REPO', and full URLs. ```go func ParseWithHost(s, host string) (Repository, error) ``` -------------------------------- ### Execute Git Command Source: https://pkg.go.dev/github.com/cli/go-gh/v2/internal/git Executes a git command with the given arguments and returns its standard output, standard error, and an error if one occurred. ```go func Exec(args ...string) (stdOut, stdErr bytes.Buffer, err error) ``` -------------------------------- ### Execute GraphQL Mutation (Background Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Executes a GraphQL mutation using the client's background context. The mutation string is derived from the `name` argument, and the response is populated into the `m` argument. ```go func (c *GraphQLClient) Mutate(name string, m interface{}, variables map[string]interface{}) error ``` -------------------------------- ### ClientOptions Struct Definition Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Defines the available options for configuring API clients, such as authentication tokens, caching, headers, and timeouts. Use these options to customize client behavior. ```go type ClientOptions struct { // AuthToken is the authorization token that will be used // to authenticate against API endpoints. AuthToken string // CacheDir is the directory to use for cached API requests. // Default is the same directory that gh uses for caching. CacheDir string // CacheTTL is the time that cached API requests are valid for. // Default is 24 hours. CacheTTL time.Duration // EnableCache specifies if API requests will be cached or not. // Default is no caching. EnableCache bool // Headers are the headers that will be sent with every API request. // Default headers set are Accept, Content-Type, Time-Zone, and User-Agent. // Default headers will be overridden by keys specified in Headers. Headers map[string]string // Host is the default host that API requests will be sent to. Host string // Log specifies a writer to write API request logs to. Default is to respect the GH_DEBUG environment // variable, and no logging otherwise. Log io.Writer // LogIgnoreEnv disables respecting the GH_DEBUG environment variable. This can be useful in test mode // or when the extension already offers its own controls for logging to the user. LogIgnoreEnv bool // LogColorize enables colorized logging to Log for display in a terminal. // Default is no coloring. LogColorize bool // LogVerboseHTTP enables logging HTTP headers and bodies to Log. // Default is only logging request URLs and response statuses. LogVerboseHTTP bool // SkipDefaultHeaders disables setting of the default headers. SkipDefaultHeaders bool // Timeout specifies a time limit for each API request. // Default is no timeout. Timeout time.Duration // Transport specifies the mechanism by which individual API requests are made. // If both Transport and UnixDomainSocket are specified then Transport takes // precedence. Due to this behavior any value set for Transport needs to manually // handle routing to UnixDomainSocket if necessary. Generally, setting Transport // should be reserved for testing purposes. // Default is http.DefaultTransport. Transport http.RoundTripper // UnixDomainSocket specifies the Unix domain socket address by which individual // API requests will be routed. If specifed, this will form the base of the API // request transport chain. // Default is no socket address. UnixDomainSocket string } ``` -------------------------------- ### Parse Template String Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/template Parses the given template string, preparing it for execution. ```go func (t *Template) Parse(tmpl string) error ``` -------------------------------- ### New TablePrinter Initialization Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/tableprinter Initializes a new table printer. It requires an io.Writer for output, a boolean indicating if the output is a TTY (for terminal-specific formatting), and the maximum width for the terminal. In TTY mode, output is human-readable and colorized; otherwise, it's tab-separated with no truncation. ```go func New(w io.Writer, isTTY bool, maxWidth int) TablePrinter ``` -------------------------------- ### Execute GraphQL Mutation (With Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Executes a GraphQL mutation request with a specified context. The mutation string is derived from the `name` argument, and the response is populated into the `m` argument. The `m` argument should be a pointer to a struct matching the GraphQL schema. ```go func (c *GraphQLClient) MutateWithContext(ctx context.Context, name string, m interface{}, variables map[string]interface{}) error ``` -------------------------------- ### NewMock PrompterMock Constructor Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Instantiates a new PrompterMock for testing purposes. ```go func NewMock(t *testing.T) *PrompterMock ``` -------------------------------- ### DataDir Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Returns the path to the data directory. The precedence for data path is XDG_DATA_HOME, LocalAppData (Windows only), and HOME. ```APIDOC ## func DataDir ### Description DataDir returns the path to the data directory. Data path precedence: XDG_DATA_HOME, LocalAppData (windows only), HOME. ### Signature ```go func DataDir() string ``` ``` -------------------------------- ### Indent Each Line of a String Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/text Returns a copy of the string with the specified indent prefixed to each line. ```go func Indent(s, indent string) string ``` -------------------------------- ### ConfigDir Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Returns the path to the configuration directory. The precedence for config path is GH_CONFIG_DIR, XDG_CONFIG_HOME, AppData (Windows only), and HOME. ```APIDOC ## func ConfigDir ### Description ConfigDir returns the path to the configuration directory. Config path precedence: GH_CONFIG_DIR, XDG_CONFIG_HOME, AppData (windows only), HOME. ### Signature ```go func ConfigDir() string ``` ``` -------------------------------- ### Normalize Hostname Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Ensures the provided hostname matches the standard format used throughout the codebase, specifically for 'github', 'localhost', and 'tenancyHost'. ```go func NormalizeHostname(host string) string ``` -------------------------------- ### ReadFromString Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Takes a YAML string and returns a Config object. ```APIDOC ## func ReadFromString ### Description ReadFromString takes a yaml string and returns a Config. ### Signature ```go func ReadFromString(str string) *Config ``` ``` -------------------------------- ### Prompter MultiSelect Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Prompts the user to select multiple options from a list. ```go func (p *Prompter) MultiSelect(prompt string, defaultValues, options []string) ([]int, error) ``` -------------------------------- ### Browse URL Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/browser Opens a web browser window navigated to the specified URL. ```APIDOC ## func (*Browser) Browse ### Description Browse opens the launcher and navigates to the specified URL. ### Signature ``` func (b *Browser) Browse(url string) error ``` ### Parameters * **url** (string) - The URL to navigate to. ### Returns * (error) - An error if the URL could not be opened, otherwise nil. ``` -------------------------------- ### PrompterMock RegisterInput Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Records a stub for the Input prompt to be called on PrompterMock. ```go func (m *PrompterMock) RegisterInput(prompt string, stub func(_, _ string) (string, error)) ``` -------------------------------- ### GraphQLClient Methods Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Provides methods for interacting with the GitHub GraphQL API, including querying and mutating data. ```APIDOC ## GraphQLClient Operations ### Description Methods for interacting with the GitHub GraphQL API. ### Methods - **DefaultGraphQLClient()** (*GraphQLClient, error): Returns a GraphQL client with default configurations. - **NewGraphQLClient**(opts ClientOptions) (*GraphQLClient, error): Creates a GraphQL client with custom options. - **Do**(query string, variables map[string]interface{}, response interface{}) error: Executes a GraphQL query or mutation. - **DoWithContext**(ctx context.Context, query string, variables map[string]interface{}, ...) error: Executes a GraphQL query or mutation with context. - **Mutate**(name string, m interface{}, variables map[string]interface{}) error: Executes a GraphQL mutation. - **MutateWithContext**(ctx context.Context, name string, m interface{}, ...) error: Executes a GraphQL mutation with context. - **Query**(name string, q interface{}, variables map[string]interface{}) error: Executes a GraphQL query. - **QueryWithContext**(ctx context.Context, name string, q interface{}, ...) error: Executes a GraphQL query with context. ``` -------------------------------- ### Fetch GraphQL Query Definition (Background Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Wraps `QueryWithContext` to execute a GraphQL query using `context.Background`. The query string is derived from the `q` argument, and the response is populated into it. ```go func (c *GraphQLClient) Query(name string, q interface{}, variables map[string]interface{}) error ``` -------------------------------- ### StubConfig Function Signature Source: https://pkg.go.dev/github.com/cli/go-gh/v2/internal/testutils Replaces the config.Read function with a custom one for testing. It sets up a cleanup function to restore the original config.Read. ```go func StubConfig(t *testing.T, cfgStr string) ``` -------------------------------- ### NewGraphQLClient Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Constructs a new GraphQL client with specified options. It configures the client to interact with GitHub GraphQL API endpoints, resolving hostnames, authentication tokens, headers, and Unix domain sockets from the gh environment configuration, with overrides possible via opts. ```APIDOC ## NewGraphQLClient ### Description Builds a client to send requests to GitHub GraphQL API endpoints. Configuration details like hostname, auth token, default headers, and Unix domain socket are resolved from the gh environment configuration and can be overridden using the `opts` argument. ### Method `NewGraphQLClient(opts ClientOptions) (*GraphQLClient, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage: // opts := api.ClientOptions{... // client, err := api.NewGraphQLClient(opts) // ... ``` ### Response #### Success Response (200) - `*GraphQLClient` (pointer to GraphQLClient) - A configured GraphQL client. - `error` - An error if the client could not be created. #### Response Example None explicitly defined in source. ``` -------------------------------- ### GraphQLClient.Do Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Executes a GraphQL query using the client. It wraps `DoWithContext` and uses `context.Background()` for the context. The response is populated into the provided response interface. ```APIDOC ## GraphQLClient.Do ### Description Wraps the `DoWithContext` method, utilizing `context.Background()` for the execution context. This method executes a GraphQL query request, populating the results into the provided `response` argument. ### Method `Do(query string, variables map[string]interface{}, response interface{}) error` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage: // var result MyResponseType // err := client.Do("query { ... }", map[string]interface{}{"key": "value"}, &result) // ... ``` ### Response #### Success Response (200) - `error` - Returns nil on success. The `response` interface will be populated with the query results. #### Response Example None explicitly defined in source. ``` -------------------------------- ### Exec Source: https://pkg.go.dev/github.com/cli/go-gh/v2/internal/git Exec executes a git command with the given arguments and returns its standard output, standard error, and an error if any occurred. ```APIDOC ## func Exec ### Description Exec executes a git command with the given arguments and returns its standard output, standard error, and an error if any occurred. ### Signature ```go func Exec(args ...string) (stdOut, stdErr bytes.Buffer, err error) ``` ``` -------------------------------- ### Set String Value in Config Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Sets a string value in the Config using a sequence of keys for nested access. Creates keys if they do not exist. An empty string value is written as null. ```go func (c *Config) Set(keys []string, value string) ``` ```go var c *Config c.Set([]string{"key"}, "") Write(c) // writes `key: ` not `key: ""` ``` -------------------------------- ### Prompter Confirm Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Prompts the user to confirm a yes/no question with a default value. ```go func (p *Prompter) Confirm(prompt string, defaultValue bool) (bool, error) ``` -------------------------------- ### Repository.Parse Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/repository Extracts repository information from various string formats including "OWNER/REPO", "HOST/OWNER/REPO", and full URLs. It uses the configuration to determine the host if not specified. ```APIDOC ## Parse ### Description Extracts the repository information from the following string formats: "OWNER/REPO", "HOST/OWNER/REPO", and a full URL. If the format does not specify a host, use the config to determine a host. ### Signature ```go func Parse(s string) (Repository, error) ``` ``` -------------------------------- ### TokenForHost Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Retrieves an authentication token and its source for a specified host. Supports environment variables, configuration files, and system keyring (via 'gh auth token'). Returns '', 'default' if no token is found. ```APIDOC ## TokenForHost ### Description TokenForHost retrieves an authentication token and the source of that token for the specified host. The source can be either an environment variable, configuration file, or the system keyring. In the latter case, this shells out to "gh auth token" to obtain the token. Returns "", "default" if no applicable token is found. ### Signature ```go func TokenForHost(host string) (string, string) ``` ``` -------------------------------- ### DefaultHTTPClient Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api DefaultHTTPClient creates an HTTP client with default GitHub API configurations. ```APIDOC ## DefaultHTTPClient ### Description Creates an HTTP client with default GitHub API configurations. ### Method GET ### Endpoint N/A ### Returns - *http.Client: The default HTTP client. - error: An error if the client could not be created. ``` -------------------------------- ### Fetch GraphQL Query Definition (With Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Executes a GraphQL query request with a specified context. The query string is derived from the `q` argument, and the response is populated into it. The `q` argument should be a pointer to a struct matching the GitHub GraphQL schema. ```go func (c *GraphQLClient) QueryWithContext(ctx context.Context, name string, q interface{}, variables map[string]interface{}) error ``` -------------------------------- ### KeyNotFoundError Type Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Represents an error when a configuration key cannot be found. ```go type KeyNotFoundError struct { Key string } ``` -------------------------------- ### Execute GraphQL Query (Background Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Executes a GraphQL query using the client's background context. The query string is derived from the `query` argument, and results are populated into the `response` struct. ```go func (c *GraphQLClient) Do(query string, variables map[string]interface{}, response interface{}) error ``` -------------------------------- ### Term.Size Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/term Retrieves the width and height of the terminal. ```APIDOC ## func (Term) Size ### Description Size returns the width and height of the terminal that the current process is attached to. In case of errors, the numeric values returned are -1. ### Signature ```go func (t Term) Size() (int, int, error) ``` ### Returns - **width** (int) - The width of the terminal. - **height** (int) - The height of the terminal. - **error** - An error if the size could not be determined. ``` -------------------------------- ### StateDir Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Returns the path to the state directory. The precedence for state path is XDG_STATE_HOME, LocalAppData (Windows only), and HOME. ```APIDOC ## func StateDir ### Description StateDir returns the path to the state directory. State path precedence: XDG_STATE_HOME, LocalAppData (windows only), HOME. ### Signature ```go func StateDir() string ``` ``` -------------------------------- ### NewHTTPClient Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api NewHTTPClient builds a client that can be passed to another library, resolving configuration from the gh environment. ```APIDOC ## NewHTTPClient ### Description Builds an HTTP client that can be passed to another library. Configuration such as hostname, auth token, and default headers are resolved from the gh environment configuration. These can be overridden using the `opts` argument. Providing `opts.Host` will not change the request destination but will affect auth token addition if it doesn't match the request host. ### Method N/A ### Endpoint N/A ### Parameters #### Request Body - **opts** (ClientOptions) - Required - Options to configure the HTTP client. ### Returns - *http.Client: The configured HTTP client. - error: An error if the client could not be created. ``` -------------------------------- ### RemoteSet Less Than Source: https://pkg.go.dev/github.com/cli/go-gh/v2/internal/git Compares two remotes in a RemoteSet to determine their order, used for sorting. ```go func (r RemoteSet) Less(i, j int) bool ``` -------------------------------- ### Repository.ParseWithHost Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/repository Extracts repository information from various string formats including "OWNER/REPO", "HOST/OWNER/REPO", and full URLs. It uses the provided host if the format does not specify one. ```APIDOC ## ParseWithHost ### Description Extracts the repository information from the following string formats: "OWNER/REPO", "HOST/OWNER/REPO", and a full URL. If the format does not specify a host, use the host provided. ### Signature ```go func ParseWithHost(s, host string) (Repository, error) ``` ``` -------------------------------- ### List Known Authenticated Hosts Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Retrieves a list of hosts that have corresponding authentication tokens from environment variables or configuration files. Returns an empty slice if no hosts are found. ```go func KnownHosts() []string ``` -------------------------------- ### NewTranslator Initialization Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/ssh Initializes and returns a new instance of the Translator. Use this to create a Translator object before applying translations. ```go func NewTranslator() *Translator ``` -------------------------------- ### Set Rendering Theme Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/markdown A rendering option to apply a specific theme to the markdown output. Respects the GLAMOUR_STYLE environment variable if set. ```go func WithTheme(theme string) glamour.TermRendererOption ``` -------------------------------- ### Execute GraphQL Query (With Context) Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Executes a GraphQL query request with a specified context. This is useful for managing request lifecycles, timeouts, and cancellations. The response is populated into the `response` argument. ```go func (c *GraphQLClient) DoWithContext(ctx context.Context, query string, variables map[string]interface{}, response interface{}) error ``` -------------------------------- ### Prompter Password Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Prompts the user to input a single-line string without echoing the input. ```go func (p *Prompter) Password(prompt string) (string, error) ``` -------------------------------- ### Format Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/jsonpretty Format reads JSON from r and writes a prettified version of it to w. ```APIDOC ## func Format ### Description Format reads JSON from r and writes a prettified version of it to w. ### Signature ```go func Format(w io.Writer, r io.Reader, indent string, colorize bool) error ``` ### Parameters * `w` (io.Writer) - The writer to which the prettified JSON will be written. * `r` (io.Reader) - The reader from which to read the JSON input. * `indent` (string) - The string to use for indentation (e.g., " " or "\t"). * `colorize` (bool) - A boolean indicating whether to colorize the output. ### Returns * `error` - An error if the JSON is invalid or if writing fails. ``` -------------------------------- ### KnownHosts Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/auth Retrieves a list of hosts with corresponding authentication tokens from environment variables or configuration files. Returns an empty slice if no hosts are found. ```APIDOC ## KnownHosts ### Description KnownHosts retrieves a list of hosts that have corresponding authentication tokens, either from environment variables or from the configuration file. Returns an empty string slice if no hosts are found. ### Signature ```go func KnownHosts() []string ``` ``` -------------------------------- ### Constants for Accessible Colors Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/x/color Defines environment variable and configuration setting names for enabling accessible color features. ```go const ( // AccessibleColorsEnv is the name of the environment variable to enable accessibile color features. AccessibleColorsEnv = "GH_ACCESSIBLE_COLORS" // AccessibleColorsSetting is the name of the `gh config` setting to enable accessibile color features. AccessibleColorsSetting = "accessible_colors" ) ``` -------------------------------- ### GraphQLClient.Query Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Executes a GraphQL query request. It wraps `QueryWithContext` using `context.Background()`. The query string and variables are provided, and the response is populated into the query argument. ```APIDOC ## GraphQLClient.Query ### Description Wraps the `QueryWithContext` method, utilizing `context.Background()` for the execution context. This method executes a GraphQL query request. The query string is derived from the `name` argument, and the response is populated into the `q` argument. The `q` argument should be a pointer to a struct that corresponds to the GitHub GraphQL schema. ### Method `Query(name string, q interface{}, variables map[string]interface{}) error` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```go // Example usage: // type MyQueryResponse struct { ... } // var queryResponse MyQueryResponse // err := client.Query("GetUser", &queryResponse, map[string]interface{}{"username": "octocat"}) // ... ``` ### Response #### Success Response (200) - `error` - Returns nil on success. The `q` interface will be populated with the query results. #### Response Example None explicitly defined in source. ``` -------------------------------- ### Enumerate Keys in Config Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Enumerates the keys within a Config, supporting nested map values. Returns an error if any specified keys are not found. ```go func (c *Config) Keys(keys []string) ([]string, error) ``` -------------------------------- ### Perform REST POST Request Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/api Issues a POST request to the specified path with the provided body. The response is populated into the response argument. ```go func (c *RESTClient) Post(path string, body io.Reader, resp interface{}) error ``` -------------------------------- ### Render Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/markdown Renders a markdown string to the terminal. Supports various options for customization like base URL, theme, wrapping, and indentation. ```APIDOC ## Render ### Description Renders the markdown string according to the specified rendering options. By default, emoji are rendered and new lines are preserved. ### Function Signature ```go func Render(text string, opts ...glamour.TermRendererOption) (string, error) ``` ### Options - **WithBaseURL(u string)**: Sets the base URL to use when rendering relative URLs. - **WithTheme(theme string)**: Sets the theme to use while rendering the markdown. If the environment variable `GLAMOUR_STYLE` is set, it will take precedence. - **WithWrap(w int)**: Sets the character limit for soft wrapping the markdown rendering. - **WithoutIndentation()**: Removes indentation from the markdown rendering. ``` -------------------------------- ### PrompterMock RegisterConfirm Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Records a stub for the Confirm prompt to be called on PrompterMock. ```go func (m *PrompterMock) RegisterConfirm(prompt string, stub func(_ string, _ bool) (bool, error)) ``` -------------------------------- ### Config.Set Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Sets a string value in a Config. The keys argument is a sequence of key values to set nested entries. If any keys do not exist, they will be created. An empty string value will be represented as null when written. ```APIDOC ## func (*Config) Set ### Description Set a string value in a Config. The keys argument is a sequence of key values so that nested entries can be set. If any of the keys do not exist they will be created. If the string value to be set is empty it will be represented as null not an empty string when written. ### Example ```go var c *Config c.Set([]string{"key"}, "") Write(c) // writes `key: ` not `key: ""` ``` ### Signature ```go func (c *Config) Set(keys []string, value string) ``` ``` -------------------------------- ### Indent Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/text Returns a copy of the string with indent prefixed to each line. ```APIDOC ## Indent ### Description Indent returns a copy of the string s with indent prefixed to it, will apply indent to each line of the string. ### Signature ``` func Indent(s, indent string) string ``` ``` -------------------------------- ### Read Configuration Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Reads gh configuration files from the local file system. It supports fallback configurations and returns an empty configuration if no files or fallback are found. ```APIDOC ## func Read ### Description Reads gh configuration files from the local file system and returns a Config object. A copy of the fallback configuration will be returned when there are no configuration files to load. If there are no configuration files and no fallback configuration an empty configuration will be returned. ### Signature ```go func Read(fallback *Config) (*Config, error) ``` ``` -------------------------------- ### ExecInteractive Source: https://pkg.go.dev/github.com/cli/go-gh/v2 ExecInteractive invokes a gh command in a subprocess, connecting its stdin, stdout, and stderr to the parent process. This is ideal for commands that require user interaction. ```APIDOC ## func ExecInteractive ### Description ExecInteractive invokes a gh command in a subprocess with its stdin, stdout, and stderr streams connected to those of the parent process. This is suitable for running gh commands with interactive prompts. ### Signature ```go func ExecInteractive(ctx context.Context, args ...string) error ``` ### Parameters * `ctx` (context.Context) - The context for the operation. * `args` (...string) - The arguments to pass to the gh command. ``` -------------------------------- ### Prompter Methods Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Methods available on the Prompter struct for user interaction. ```APIDOC ## New ### Description Instantiates a new Prompter. ### Signature ```go func New(stdin FileReader, stdout FileWriter, stderr FileWriter) *Prompter ``` ## Confirm ### Description Prompts the user to confirm a yes/no question. ### Signature ```go func (p *Prompter) Confirm(prompt string, defaultValue bool) (bool, error) ``` ## Input ### Description Prompts the user to input a single-line string. ### Signature ```go func (p *Prompter) Input(prompt, defaultValue string) (string, error) ``` ## MultiSelect ### Description Prompts the user to select multiple options from a list of options. ### Signature ```go func (p *Prompter) MultiSelect(prompt string, defaultValues, options []string) ([]int, error) ``` ## Password ### Description Prompts the user to input a single-line string without echoing the input. ### Signature ```go func (p *Prompter) Password(prompt string) (string, error) ``` ## Select ### Description Prompts the user to select an option from a list of options. ### Signature ```go func (p *Prompter) Select(prompt, defaultValue string, options []string) (int, error) ``` ``` -------------------------------- ### Pad String to Maximum Width Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/text Pads a string on the right with whitespace to ensure it fits a maximum display width. Added in v2.5.0. ```go func PadRight(maxWidth int, s string) string ``` -------------------------------- ### Set Soft Wrapping Limit Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/markdown A rendering option to control the maximum line width for soft wrapping markdown text. ```go func WithWrap(w int) glamour.TermRendererOption ``` -------------------------------- ### Path Source: https://pkg.go.dev/github.com/cli/go-gh/v2 Path searches the system's PATH environment variable for the gh executable and returns its absolute path if found. ```APIDOC ## func Path ### Description Path searches for an executable named "gh" in the directories named by the PATH environment variable. If the executable is found the result is an absolute path. ### Signature ```go func Path() (string, error) ``` ### Returns * `string` - The absolute path to the gh executable. * `error` - An error if the gh executable is not found or another issue occurs. ``` -------------------------------- ### InvalidConfigFileError Error Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/config Implements the error interface for InvalidConfigFileError. ```go func (e *InvalidConfigFileError) Error() string ``` -------------------------------- ### Create String YAML Map Value Source: https://pkg.go.dev/github.com/cli/go-gh/v2/internal/yamlmap Creates a Map value from a given string. ```go func StringValue(value string) *Map ``` -------------------------------- ### PrompterMock RegisterSelect Method Source: https://pkg.go.dev/github.com/cli/go-gh/v2/pkg/prompter Records a stub for the Select prompt to be called on PrompterMock. ```go func (m *PrompterMock) RegisterSelect(prompt string, opts []string, stub func(_, _ string, _ []string) (int, error)) ```