From 3dba1d73f6b6a3ac59817b4222f0768dc97e775d Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Mon, 23 Jun 2025 15:48:23 -0300 Subject: [PATCH 1/4] feat: use fang --- go.mod | 9 ++++++--- go.sum | 10 ++++++++-- main.go | 24 +++++++----------------- man_cmd.go | 29 ----------------------------- 4 files changed, 21 insertions(+), 51 deletions(-) delete mode 100644 man_cmd.go diff --git a/go.mod b/go.mod index 97cfc60..b2ce8e5 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/caarlos0/env/v11 v11.3.1 github.com/charmbracelet/bubbles v0.21.0 github.com/charmbracelet/bubbletea v1.3.5 + github.com/charmbracelet/fang v0.2.0 github.com/charmbracelet/glamour v0.10.0 github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 github.com/charmbracelet/log v0.4.2 @@ -19,9 +20,7 @@ require ( github.com/mitchellh/go-homedir v1.1.0 github.com/muesli/gitcha v0.3.0 github.com/muesli/go-app-paths v0.2.2 - github.com/muesli/mango-cobra v1.2.0 github.com/muesli/reflow v0.3.0 - github.com/muesli/roff v0.1.0 github.com/muesli/termenv v0.16.0 github.com/sahilm/fuzzy v0.1.1 github.com/spf13/cobra v1.9.1 @@ -35,9 +34,11 @@ require ( github.com/alecthomas/chroma/v2 v2.14.0 // indirect github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect github.com/aymerick/douceur v0.2.0 // indirect - github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect + github.com/charmbracelet/colorprofile v0.3.0 // indirect + github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.1 // indirect github.com/charmbracelet/x/ansi v0.8.0 // indirect github.com/charmbracelet/x/cellbuf v0.0.13 // indirect + github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 // indirect github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf // indirect github.com/charmbracelet/x/term v0.2.1 // indirect github.com/dlclark/regexp2 v1.11.0 // indirect @@ -53,7 +54,9 @@ require ( github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect github.com/muesli/mango v0.1.0 // indirect + github.com/muesli/mango-cobra v1.2.0 // indirect github.com/muesli/mango-pflag v0.1.0 // indirect + github.com/muesli/roff v0.1.0 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect diff --git a/go.sum b/go.sum index a45e752..1585ca7 100644 --- a/go.sum +++ b/go.sum @@ -18,12 +18,16 @@ github.com/charmbracelet/bubbles v0.21.0 h1:9TdC97SdRVg/1aaXNVWfFH3nnLAwOXr8Fn6u github.com/charmbracelet/bubbles v0.21.0/go.mod h1:HF+v6QUR4HkEpz62dx7ym2xc71/KBHg+zKwJtMw+qtg= github.com/charmbracelet/bubbletea v1.3.5 h1:JAMNLTbqMOhSwoELIr0qyP4VidFq72/6E9j7HHmRKQc= github.com/charmbracelet/bubbletea v1.3.5/go.mod h1:TkCnmH+aBd4LrXhXcqrKiYwRs7qyQx5rBgH5fVY3v54= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs= -github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk= +github.com/charmbracelet/colorprofile v0.3.0 h1:KtLh9uuu1RCt+Hml4s6Hz+kB1PfV3wi++1h5ia65yKQ= +github.com/charmbracelet/colorprofile v0.3.0/go.mod h1:oHJ340RS2nmG1zRGPmhJKJ/jf4FPNNk0P39/wBPA1G0= +github.com/charmbracelet/fang v0.2.0 h1:F2sK2Zjy9kRYz/xUSF1o89DNj2BHKpxVKT7TA21KZi0= +github.com/charmbracelet/fang v0.2.0/go.mod h1:TPpME1GkB6/4uR4wXmPnugTCkqRLgZkWSH+aMds6454= github.com/charmbracelet/glamour v0.10.0 h1:MtZvfwsYCx8jEPFJm3rIBFIMZUfUJ765oX8V6kXldcY= github.com/charmbracelet/glamour v0.10.0/go.mod h1:f+uf+I/ChNmqo087elLnVdCiVgjSKWuXa/l6NU2ndYk= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834 h1:ZR7e0ro+SZZiIZD7msJyA+NjkCNNavuiPBLgerbOziE= github.com/charmbracelet/lipgloss v1.1.1-0.20250404203927-76690c660834/go.mod h1:aKC/t2arECF6rNOnaKaVU6y4t4ZeHQzqfxedE/VkVhA= +github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.1 h1:D9AJJuYTN5pvz6mpIGO1ijLKpfTYSHOtKGgwoTQ4Gog= +github.com/charmbracelet/lipgloss/v2 v2.0.0-beta.1/go.mod h1:tRlx/Hu0lo/j9viunCN2H+Ze6JrmdjQlXUQvvArgaOc= github.com/charmbracelet/log v0.4.2 h1:hYt8Qj6a8yLnvR+h7MwsJv/XvmBJXiueUcI3cIxsyig= github.com/charmbracelet/log v0.4.2/go.mod h1:qifHGX/tc7eluv2R6pWIpyHDDrrb/AG71Pf2ysQu5nw= github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE= @@ -32,6 +36,8 @@ github.com/charmbracelet/x/cellbuf v0.0.13 h1:/KBBKHuVRbq1lYx5BzEHBAFBP8VcQzJejZ github.com/charmbracelet/x/cellbuf v0.0.13/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs= github.com/charmbracelet/x/editor v0.1.0 h1:p69/dpvlwRTs9uYiPeAWruwsHqTFzHhTvQOd/WVSX98= github.com/charmbracelet/x/editor v0.1.0/go.mod h1:oivrEbcP/AYt/Hpvk5pwDXXrQ933gQS6UzL6fxqAGSA= +github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 h1:IJDiTgVE56gkAGfq0lBEloWgkXMk4hl/bmuPoicI4R0= +github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444/go.mod h1:T9jr8CzFpjhFVHjNjKwbAD7KwBNyFnj2pntAO7F2zw0= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ= github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U= github.com/charmbracelet/x/exp/slice v0.0.0-20250327172914-2fdc97757edf h1:rLG0Yb6MQSDKdB52aGX55JT1oi0P0Kuaj7wi1bLUpnI= diff --git a/main.go b/main.go index b0d7a77..44be332 100644 --- a/main.go +++ b/main.go @@ -2,6 +2,7 @@ package main import ( + "context" "errors" "fmt" "io" @@ -14,6 +15,7 @@ import ( "strings" "github.com/caarlos0/env/v11" + "github.com/charmbracelet/fang" "github.com/charmbracelet/glamour" "github.com/charmbracelet/glamour/styles" "github.com/charmbracelet/glow/v2/ui" @@ -44,11 +46,9 @@ var ( mouse bool rootCmd = &cobra.Command{ - Use: "glow [SOURCE|DIR]", - Short: "Render markdown on the CLI, with pizzazz!", - Long: paragraph( - fmt.Sprintf("\nRender markdown on the CLI, %s!", keyword("with pizzazz")), - ), + Use: "glow [SOURCE|DIR]", + Short: "Render markdown on the CLI, with pizzazz!", + Long: fmt.Sprintf("Render markdown on the CLI, %s!", keyword("with pizzazz")), SilenceErrors: false, SilenceUsage: true, TraverseChildren: true, @@ -374,7 +374,7 @@ func main() { fmt.Println(err) os.Exit(1) } - if err := rootCmd.Execute(); err != nil { + if err := fang.Execute(context.Background(), rootCmd); err != nil { _ = closer() os.Exit(1) } @@ -383,16 +383,6 @@ func main() { func init() { tryLoadConfigFromDefaultPlaces() - if len(CommitSHA) >= 7 { - vt := rootCmd.VersionTemplate() - rootCmd.SetVersionTemplate(vt[:len(vt)-1] + " (" + CommitSHA[0:7] + ")\n") - } - if Version == "" { - Version = "unknown (built from source)" - } - rootCmd.Version = Version - rootCmd.InitDefaultCompletionCmd() - // "Glow Classic" cli arguments rootCmd.PersistentFlags().StringVar(&configFile, "config", "", fmt.Sprintf("config file (default %s)", viper.GetViper().ConfigFileUsed())) rootCmd.Flags().BoolVarP(&pager, "pager", "p", false, "display with pager") @@ -420,7 +410,7 @@ func init() { viper.SetDefault("width", 0) viper.SetDefault("all", true) - rootCmd.AddCommand(configCmd, manCmd) + rootCmd.AddCommand(configCmd) } func tryLoadConfigFromDefaultPlaces() { diff --git a/man_cmd.go b/man_cmd.go deleted file mode 100644 index a179ef7..0000000 --- a/man_cmd.go +++ /dev/null @@ -1,29 +0,0 @@ -package main - -import ( - "fmt" - "os" - - mcobra "github.com/muesli/mango-cobra" - "github.com/muesli/roff" - "github.com/spf13/cobra" -) - -var manCmd = &cobra.Command{ - Use: "man", - Short: "Generates manpages", - SilenceUsage: true, - DisableFlagsInUseLine: true, - Hidden: true, - Args: cobra.NoArgs, - RunE: func(*cobra.Command, []string) error { - manPage, err := mcobra.NewManPage(1, rootCmd) - if err != nil { - return fmt.Errorf("unable to instantiate man page: %w", err) - } - if _, err := fmt.Fprint(os.Stdout, manPage.Build(roff.NewDocument())); err != nil { - return fmt.Errorf("unable to build man page: %w", err) - } - return nil - }, -} From 45cacb4b3103240e87428a341377847915d21d74 Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Mon, 30 Jun 2025 08:24:29 -0300 Subject: [PATCH 2/4] fix: use ctx Signed-off-by: Carlos Alexandro Becker --- main.go | 14 ++++++-------- ui/ui.go | 5 +++-- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index 44be332..dd3bb7c 100644 --- a/main.go +++ b/main.go @@ -49,8 +49,6 @@ var ( Use: "glow [SOURCE|DIR]", Short: "Render markdown on the CLI, with pizzazz!", Long: fmt.Sprintf("Render markdown on the CLI, %s!", keyword("with pizzazz")), - SilenceErrors: false, - SilenceUsage: true, TraverseChildren: true, Args: cobra.MaximumNArgs(1), ValidArgsFunction: func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { @@ -233,7 +231,7 @@ func execute(cmd *cobra.Command, args []string) error { switch len(args) { // TUI running on cwd case 0: - return runTUI("", "") + return runTUI(cmd.Context(), "", "") // TUI with possible dir argument case 1: @@ -243,7 +241,7 @@ func execute(cmd *cobra.Command, args []string) error { if err == nil && info.IsDir() { p, err := filepath.Abs(args[0]) if err == nil { - return runTUI(p, "") + return runTUI(cmd.Context(), p, "") } } fallthrough @@ -320,7 +318,7 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error { } pa := strings.Split(pagerCmd, " ") - c := exec.Command(pa[0], pa[1:]...) //nolint:gosec + c := exec.CommandContext(cmd.Context(), pa[0], pa[1:]...) //nolint:gosec c.Stdin = strings.NewReader(out) c.Stdout = os.Stdout if err := c.Run(); err != nil { @@ -332,7 +330,7 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error { if !isURL(src.URL) { path = src.URL } - return runTUI(path, content) + return runTUI(cmd.Context(), path, content) default: if _, err = fmt.Fprint(w, out); err != nil { return fmt.Errorf("unable to write to writer: %w", err) @@ -341,7 +339,7 @@ func executeCLI(cmd *cobra.Command, src *source, w io.Writer) error { } } -func runTUI(path string, content string) error { +func runTUI(ctx context.Context, path string, content string) error { // Read environment to get debugging stuff cfg, err := env.ParseAs[ui.Config]() if err != nil { @@ -361,7 +359,7 @@ func runTUI(path string, content string) error { cfg.PreserveNewLines = preserveNewLines // Run Bubble Tea program - if _, err := ui.NewProgram(cfg, content).Run(); err != nil { + if _, err := ui.NewProgram(ctx, cfg, content).Run(); err != nil { return fmt.Errorf("unable to run tui program: %w", err) } diff --git a/ui/ui.go b/ui/ui.go index 3537d3f..23f3ad8 100644 --- a/ui/ui.go +++ b/ui/ui.go @@ -2,6 +2,7 @@ package ui import ( + "context" "fmt" "os" "path/filepath" @@ -30,7 +31,7 @@ var ( ) // NewProgram returns a new Tea program. -func NewProgram(cfg Config, content string) *tea.Program { +func NewProgram(ctx context.Context, cfg Config, content string) *tea.Program { log.Debug( "Starting glow", "high_perf_pager", @@ -40,7 +41,7 @@ func NewProgram(cfg Config, content string) *tea.Program { ) config = cfg - opts := []tea.ProgramOption{tea.WithAltScreen()} + opts := []tea.ProgramOption{tea.WithAltScreen(), tea.WithContext(ctx)} if cfg.EnableMouse { opts = append(opts, tea.WithMouseCellMotion()) } From 7ec9d79229cb667b20145192b4335572ed0dee26 Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Mon, 30 Jun 2025 08:38:18 -0300 Subject: [PATCH 3/4] fix: use context in http calls --- github.go | 21 ++++++++++++++------- gitlab.go | 21 ++++++++++++++------- main.go | 12 ++++++++---- url.go | 11 ++++++----- url_test.go | 7 +++++-- 5 files changed, 47 insertions(+), 25 deletions(-) diff --git a/github.go b/github.go index fe862e3..7878fdf 100644 --- a/github.go +++ b/github.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "errors" "fmt" @@ -11,7 +12,7 @@ import ( ) // findGitHubREADME tries to find the correct README filename in a repository using GitHub API. -func findGitHubREADME(u *url.URL) (*source, error) { +func findGitHubREADME(ctx context.Context, u *url.URL) (*source, error) { owner, repo, ok := strings.Cut(strings.TrimPrefix(u.Path, "/"), "/") if !ok { return nil, fmt.Errorf("invalid url: %s", u.String()) @@ -23,12 +24,15 @@ func findGitHubREADME(u *url.URL) (*source, error) { apiURL := fmt.Sprintf("https://api.%s/repos/%s/%s/readme", u.Hostname(), owner, repo) - //nolint:bodyclose - // it is closed on the caller - res, err := http.Get(apiURL) //nolint: gosec,noctx + req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, nil) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + res, err := http.DefaultClient.Do(req) if err != nil { return nil, fmt.Errorf("unable to get url: %w", err) } + defer res.Body.Close() //nolint:errcheck body, err := io.ReadAll(res.Body) if err != nil { @@ -41,9 +45,12 @@ func findGitHubREADME(u *url.URL) (*source, error) { } if res.StatusCode == http.StatusOK { - //nolint:bodyclose - // it is closed on the caller - resp, err := http.Get(result.DownloadURL) //nolint: noctx + // consumer of the source is responsible for closing the ReadCloser. + req, err := http.NewRequestWithContext(ctx, http.MethodGet, result.DownloadURL, nil) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + resp, err := http.DefaultClient.Do(req) //nolint:bodyclose if err != nil { return nil, fmt.Errorf("unable to get url: %w", err) } diff --git a/gitlab.go b/gitlab.go index 68256be..d2915ef 100644 --- a/gitlab.go +++ b/gitlab.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "errors" "fmt" @@ -11,7 +12,7 @@ import ( ) // findGitLabREADME tries to find the correct README filename in a repository using GitLab API. -func findGitLabREADME(u *url.URL) (*source, error) { +func findGitLabREADME(ctx context.Context, u *url.URL) (*source, error) { owner, repo, ok := strings.Cut(strings.TrimPrefix(u.Path, "/"), "/") if !ok { return nil, fmt.Errorf("invalid url: %s", u.String()) @@ -25,12 +26,15 @@ func findGitLabREADME(u *url.URL) (*source, error) { apiURL := fmt.Sprintf("https://%s/api/v4/projects/%s", u.Hostname(), projectPath) - //nolint:bodyclose - // it is closed on the caller - res, err := http.Get(apiURL) //nolint: gosec,noctx + req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiURL, nil) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + res, err := http.DefaultClient.Do(req) if err != nil { return nil, fmt.Errorf("unable to get url: %w", err) } + defer res.Body.Close() //nolint:errcheck body, err := io.ReadAll(res.Body) if err != nil { @@ -45,9 +49,12 @@ func findGitLabREADME(u *url.URL) (*source, error) { readmeRawURL := strings.ReplaceAll(result.ReadmeURL, "blob", "raw") if res.StatusCode == http.StatusOK { - //nolint:bodyclose - // it is closed on the caller - resp, err := http.Get(readmeRawURL) //nolint: gosec,noctx + // consumer of the source is responsible for closing the ReadCloser. + req, err := http.NewRequestWithContext(ctx, http.MethodGet, readmeRawURL, nil) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + resp, err := http.DefaultClient.Do(req) //nolint:bodyclose if err != nil { return nil, fmt.Errorf("unable to get url: %w", err) } diff --git a/main.go b/main.go index dd3bb7c..2b4000c 100644 --- a/main.go +++ b/main.go @@ -68,14 +68,14 @@ type source struct { } // sourceFromArg parses an argument and creates a readable source for it. -func sourceFromArg(arg string) (*source, error) { +func sourceFromArg(ctx context.Context, arg string) (*source, error) { // from stdin if arg == "-" { return &source{reader: os.Stdin}, nil } // a GitHub or GitLab URL (even without the protocol): - src, err := readmeURL(arg) + src, err := readmeURL(ctx, arg) if src != nil && err == nil { // if there's an error, try next methods... return src, nil @@ -88,7 +88,11 @@ func sourceFromArg(arg string) (*source, error) { return nil, fmt.Errorf("%s is not a supported protocol", u.Scheme) } // consumer of the source is responsible for closing the ReadCloser. - resp, err := http.Get(u.String()) //nolint: noctx,bodyclose + req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil) + if err != nil { + return nil, fmt.Errorf("unable to create request: %w", err) + } + resp, err := http.DefaultClient.Do(req) //nolint:bodyclose if err != nil { return nil, fmt.Errorf("unable to get url: %w", err) } @@ -260,7 +264,7 @@ func execute(cmd *cobra.Command, args []string) error { func executeArg(cmd *cobra.Command, arg string, w io.Writer) error { // create an io.Reader from the markdown source in cli-args - src, err := sourceFromArg(arg) + src, err := sourceFromArg(cmd.Context(), arg) if err != nil { return err } diff --git a/url.go b/url.go index f716681..d92e70a 100644 --- a/url.go +++ b/url.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "net/url" "strings" @@ -26,16 +27,16 @@ func init() { }) } -func readmeURL(path string) (*source, error) { +func readmeURL(ctx context.Context, path string) (*source, error) { switch { case strings.HasPrefix(path, protoGithub): if u := githubReadmeURL(path); u != nil { - return readmeURL(u.String()) + return readmeURL(ctx, u.String()) } return nil, nil case strings.HasPrefix(path, protoGitlab): if u := gitlabReadmeURL(path); u != nil { - return readmeURL(u.String()) + return readmeURL(ctx, u.String()) } return nil, nil } @@ -50,9 +51,9 @@ func readmeURL(path string) (*source, error) { switch { case u.Hostname() == githubURL.Hostname(): - return findGitHubREADME(u) + return findGitHubREADME(ctx, u) case u.Hostname() == gitlabURL.Hostname(): - return findGitLabREADME(u) + return findGitLabREADME(ctx, u) } return nil, nil diff --git a/url_test.go b/url_test.go index 9683892..a23c1b1 100644 --- a/url_test.go +++ b/url_test.go @@ -1,6 +1,9 @@ package main -import "testing" +import ( + "context" + "testing" +) func TestURLParser(t *testing.T) { for path, url := range map[string]string{ @@ -15,7 +18,7 @@ func TestURLParser(t *testing.T) { } { t.Run(path, func(t *testing.T) { t.Skip("test uses network, sometimes fails for no reason") - got, err := readmeURL(path) + got, err := readmeURL(context.Background(), path) if err != nil { t.Fatalf("expected no error, got %v", err) } From 30efab4f4610b7ed2fbeb8bacf3a22ab1e82d66d Mon Sep 17 00:00:00 2001 From: Carlos Alexandro Becker Date: Tue, 21 Oct 2025 09:56:51 -0300 Subject: [PATCH 4/4] test: update Signed-off-by: Carlos Alexandro Becker --- url_test.go | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/url_test.go b/url_test.go index a23c1b1..8517f65 100644 --- a/url_test.go +++ b/url_test.go @@ -1,9 +1,6 @@ package main -import ( - "context" - "testing" -) +import "testing" func TestURLParser(t *testing.T) { for path, url := range map[string]string{ @@ -18,7 +15,7 @@ func TestURLParser(t *testing.T) { } { t.Run(path, func(t *testing.T) { t.Skip("test uses network, sometimes fails for no reason") - got, err := readmeURL(context.Background(), path) + got, err := readmeURL(t.Context(), path) if err != nil { t.Fatalf("expected no error, got %v", err) }