Skip to content
Myr

command.go

This file

Path

spin/command.go

82 lines · 2.3 KiB · Go

Last changed by

chore: prepare v2 (#1116)Drew Smirnoffbefore adoption02d6f06

History of this file

Take it

1package spin23import (4	"fmt"5	"os"67	"charm.land/bubbles/v2/spinner"8	tea "charm.land/bubbletea/v2"9	"charm.land/gum/v2/internal/exit"10	"charm.land/gum/v2/internal/timeout"11	"charm.land/gum/v2/style"12	"github.com/charmbracelet/x/term"13)1415// Run provides a shell script interface for the spinner bubble.16// https://github.com/charmbracelet/bubbles/spinner17func (o Options) Run() error {18	isOutTTY := term.IsTerminal(os.Stdout.Fd())19	isErrTTY := term.IsTerminal(os.Stderr.Fd())2021	s := spinner.New()22	s.Style = o.SpinnerStyle.ToLipgloss()23	s.Spinner = spinnerMap[o.Spinner]24	top, right, bottom, left := style.ParsePadding(o.Padding)25	m := model{26		spinner:    s,27		title:      o.TitleStyle.ToLipgloss().Render(o.Title),28		command:    o.Command,29		align:      o.Align,30		showStdout: (o.ShowOutput || o.ShowStdout) && isOutTTY,31		showStderr: (o.ShowOutput || o.ShowStderr) && isErrTTY,32		showError:  o.ShowError,33		isTTY:      isErrTTY,34		padding:    []int{top, right, bottom, left},35	}3637	ctx, cancel := timeout.Context(o.Timeout)38	defer cancel()3940	tm, err := tea.NewProgram(41		m,42		tea.WithOutput(os.Stderr),43		tea.WithContext(ctx),44		tea.WithInput(nil),45	).Run()46	if err != nil {47		return fmt.Errorf("unable to run action: %w", err)48	}4950	m = tm.(model)51	// If the command succeeds, and we are printing output and we are in a TTY then push the STDOUT we got to the actual52	// STDOUT for piping or other things.53	//nolint:nestif54	if m.err != nil {55		if _, err := fmt.Fprintf(os.Stderr, "%s\n", m.err.Error()); err != nil {56			return fmt.Errorf("failed to write to stdout: %w", err)57		}58		return exit.ErrExit(1)59	} else if m.status == 0 {60		var output string61		if o.ShowOutput || (o.ShowStdout && o.ShowStderr) {62			output = m.output63		} else if o.ShowStdout {64			output = m.stdout65		} else if o.ShowStderr {66			output = m.stderr67		}68		if output != "" {69			if _, err := os.Stdout.WriteString(output); err != nil {70				return fmt.Errorf("failed to write to stdout: %w", err)71			}72		}73	} else if o.ShowError {74		// Otherwise if we are showing errors and the command did not exit with a 0 status code then push all of the command75		// output to the terminal. This way failed commands can be debugged.76		if _, err := os.Stdout.WriteString(m.output); err != nil {77			return fmt.Errorf("failed to write to stdout: %w", err)78		}79	}8081	return exit.ErrExit(m.status)82}