From 9dff05bf205a7554d83310731cd8e65beb423777 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Mon, 22 Feb 2021 16:13:24 +0100 Subject: [PATCH] Add `api --cache` flag Cache API responses on disk for a specified duration. --- pkg/cmd/api/api.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/pkg/cmd/api/api.go b/pkg/cmd/api/api.go index 8ebdd3bc7..025225825 100644 --- a/pkg/cmd/api/api.go +++ b/pkg/cmd/api/api.go @@ -14,8 +14,10 @@ import ( "strconv" "strings" "syscall" + "time" "github.com/MakeNowJust/heredoc" + "github.com/cli/cli/api" "github.com/cli/cli/internal/ghinstance" "github.com/cli/cli/internal/ghrepo" "github.com/cli/cli/pkg/cmdutil" @@ -38,6 +40,7 @@ type ApiOptions struct { ShowResponseHeaders bool Paginate bool Silent bool + CacheTTL time.Duration HttpClient func() (*http.Client, error) BaseRepo func() (ghrepo.Interface, error) @@ -52,6 +55,8 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command Branch: f.Branch, } + var cacheDuration string + cmd := &cobra.Command{ Use: "api ", Short: "Make an authenticated GitHub API request", @@ -160,6 +165,14 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command return &cmdutil.FlagError{Err: errors.New(`the '--paginate' option is not supported with '--input'`)} } + if cacheDuration != "" { + cacheTTL, err := time.ParseDuration(cacheDuration) + if err != nil { + return fmt.Errorf("error parsing `--cache` value: %w", err) + } + opts.CacheTTL = cacheTTL + } + if runF != nil { return runF(&opts) } @@ -176,6 +189,7 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*ApiOptions) error) *cobra.Command cmd.Flags().BoolVar(&opts.Paginate, "paginate", false, "Make additional HTTP requests to fetch all pages of results") cmd.Flags().StringVar(&opts.RequestInputFile, "input", "", "The `file` to use as body for the HTTP request") cmd.Flags().BoolVar(&opts.Silent, "silent", false, "Do not print the response body") + cmd.Flags().StringVar(&cacheDuration, "cache", "", "Cache the response for the specified duration") return cmd } @@ -219,6 +233,9 @@ func apiRun(opts *ApiOptions) error { if err != nil { return err } + if opts.CacheTTL > 0 { + httpClient = api.NewCachedClient(httpClient, opts.CacheTTL) + } headersOutputStream := opts.IO.Out if opts.Silent {