// Package ghx contains a lib/cli/sink extension for GitHub. package ghx import ( "context" "fmt" "net/http" "github.com/google/go-github/v47/github" "github.com/shurcooL/githubv4" "golang.org/x/oauth2" "edge-infra.dev/pkg/lib/cli/rags" "edge-infra.dev/pkg/lib/cli/sink" ) // TODO: use in-memory caching to take advantage of conditional requests in V3 // client. Requires newer version of go-github to get NewClient().WithToken() type GHX struct { V4 *githubv4.Client V3 *github.Client httpClient *http.Client // Optional indicates that the extension isn't necessary for all invocations // and that we shouldn't error if the token isn't set. Optional bool token string } func (g *GHX) RegisterFlags(rs *rags.RagSet) { rs.Add(&rags.Rag{ Name: "github-token", Value: &rags.String{Var: &g.token}, Usage: "A GitHub personal access token.", Category: "remote file", Required: !g.Optional, }) } func (g *GHX) BeforeRun(ctx context.Context, r sink.Run) (context.Context, sink.Run, error) { switch { case g.token == "" && g.Optional: return ctx, r, nil case g.token == "": // TODO(sink): handle required flags automatically return ctx, r, fmt.Errorf("--github-token is required") } g.httpClient = oauth2.NewClient(ctx, oauth2.StaticTokenSource( &oauth2.Token{AccessToken: g.token}, )) g.V4 = githubv4.NewClient(g.httpClient) g.V3 = github.NewClient(g.httpClient) return ctx, r, nil }