...

Source file src/github.com/cli/go-gh/v2/gh.go

Documentation: github.com/cli/go-gh/v2

     1  // Package gh is a library for CLI Go applications to help interface with the gh CLI tool,
     2  // and the GitHub API.
     3  //
     4  // Note that the examples in this package assume gh and git are installed. They do not run in
     5  // the Go Playground used by pkg.go.dev.
     6  package gh
     7  
     8  import (
     9  	"bytes"
    10  	"context"
    11  	"fmt"
    12  	"io"
    13  	"os"
    14  	"os/exec"
    15  
    16  	"github.com/cli/safeexec"
    17  )
    18  
    19  // Exec invokes a gh command in a subprocess and captures the output and error streams.
    20  func Exec(args ...string) (stdout, stderr bytes.Buffer, err error) {
    21  	ghExe, err := Path()
    22  	if err != nil {
    23  		return
    24  	}
    25  	err = run(context.Background(), ghExe, nil, nil, &stdout, &stderr, args)
    26  	return
    27  }
    28  
    29  // ExecContext invokes a gh command in a subprocess and captures the output and error streams.
    30  func ExecContext(ctx context.Context, args ...string) (stdout, stderr bytes.Buffer, err error) {
    31  	ghExe, err := Path()
    32  	if err != nil {
    33  		return
    34  	}
    35  	err = run(ctx, ghExe, nil, nil, &stdout, &stderr, args)
    36  	return
    37  }
    38  
    39  // Exec invokes a gh command in a subprocess with its stdin, stdout, and stderr streams connected to
    40  // those of the parent process. This is suitable for running gh commands with interactive prompts.
    41  func ExecInteractive(ctx context.Context, args ...string) error {
    42  	ghExe, err := Path()
    43  	if err != nil {
    44  		return err
    45  	}
    46  	return run(ctx, ghExe, nil, os.Stdin, os.Stdout, os.Stderr, args)
    47  }
    48  
    49  // Path searches for an executable named "gh" in the directories named by the PATH environment variable.
    50  // If the executable is found the result is an absolute path.
    51  func Path() (string, error) {
    52  	if ghExe := os.Getenv("GH_PATH"); ghExe != "" {
    53  		return ghExe, nil
    54  	}
    55  	return safeexec.LookPath("gh")
    56  }
    57  
    58  func run(ctx context.Context, ghExe string, env []string, stdin io.Reader, stdout, stderr io.Writer, args []string) error {
    59  	cmd := exec.CommandContext(ctx, ghExe, args...)
    60  	cmd.Stdin = stdin
    61  	cmd.Stdout = stdout
    62  	cmd.Stderr = stderr
    63  	if env != nil {
    64  		cmd.Env = env
    65  	}
    66  	if err := cmd.Run(); err != nil {
    67  		return fmt.Errorf("gh execution failed: %w", err)
    68  	}
    69  	return nil
    70  }
    71  

View as plain text