Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(rexctl): add prompts, progress steps and styled help

Hampus57016d392679
diff --git a/fluxer_rexctl/internal/ui/help.go b/fluxer_rexctl/internal/ui/help.go
new file mode 100644
index 000000000..386951085
--- /dev/null
+++ b/fluxer_rexctl/internal/ui/help.go
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ui
+
+import (
+ "bytes"
+ "io"
+ "os"
+ "regexp"
+ "strings"
+
+ "github.com/charmbracelet/x/ansi"
+ "golang.org/x/term"
+)
+
+type HelpWriter struct {
+ f *os.File
+ titles map[string]string
+}
+
+func NewHelpWriter(f *os.File, titles ...string) *HelpWriter {
+ w := &HelpWriter{f: f, titles: map[string]string{}}
+ for _, t := range append([]string{"Usage", "Examples", "Commands", "Flags"}, titles...) {
+ w.titles[strings.ToUpper(t)] = t
+ }
+ return w
+}
+
+func (w *HelpWriter) Fd() uintptr { return w.f.Fd() }
+func (w *HelpWriter) Read(p []byte) (int, error) { return w.f.Read(p) }
+func (w *HelpWriter) Close() error { return w.f.Close() }
+func (w *HelpWriter) WriteString(s string) (int, error) { return w.Write([]byte(s)) }
+
+var trailingSpace = regexp.MustCompile(`[ \t]+(\x1b\[[0-9;]*m)*(\r?\n|$)`)
+
+func (w *HelpWriter) trim(p []byte) []byte {
+ if isTerminal(w.f) && colourAllowed() {
+ return p
+ }
+ if !colourAllowed() {
+ p = []byte(ansi.Strip(string(p)))
+ }
+ return trailingSpace.ReplaceAll(p, []byte("$1$2"))
+}
+
+var helpItem = regexp.MustCompile(`^( {2,}\S.*?\S?)( {2,})\S`)
+
+func (w *HelpWriter) width() int {
+ if !isTerminal(w.f) {
+ return 0
+ }
+ cols, _, err := term.GetSize(int(w.f.Fd()))
+ if err != nil {
+ return 0
+ }
+ return min(cols, 120)
+}
+
+func (w *HelpWriter) wrap(p []byte) []byte {
+ limit := w.width()
+ line, ok := strings.CutSuffix(string(p), "\n")
+ if limit == 0 || !ok || strings.Contains(line, "\n") || ansi.StringWidth(line) <= limit {
+ return p
+ }
+ m := helpItem.FindStringSubmatchIndex(ansi.Strip(line))
+ if m == nil {
+ return p
+ }
+ plain := ansi.Strip(line)
+ key := ansi.StringWidth(plain[:m[3]])
+ col := ansi.StringWidth(plain[:m[5]])
+ total := ansi.StringWidth(line)
+ head := ansi.Cut(line, 0, key)
+ help := ansi.Cut(line, col, total)
+ if limit-col < 24 {
+ indent := strings.Repeat(" ", 6)
+ body := ansi.Wordwrap(help, limit-len(indent), "")
+ return []byte(head + "\n" + indent + strings.ReplaceAll(body, "\n", "\n"+indent) + "\n")
+ }
+ indent := strings.Repeat(" ", col)
+ body := ansi.Wordwrap(help, limit-col, "")
+ return []byte(ansi.Cut(line, 0, col) + strings.ReplaceAll(body, "\n", "\n"+indent) + "\n")
+}
+
+func (w *HelpWriter) Write(p []byte) (int, error) {
+ shout := strings.TrimSpace(ansi.Strip(string(p)))
+ title, ok := w.titles[shout]
+ if !ok {
+ if _, err := w.f.Write(w.trim(w.wrap(p))); err != nil {
+ return 0, err
+ }
+ return len(p), nil
+ }
+ if _, err := w.f.Write(w.trim(bytes.Replace(p, []byte(shout), []byte(title), 1))); err != nil {
+ return 0, err
+ }
+ return len(p), nil
+}
+
+var _ io.ReadWriteCloser = (*HelpWriter)(nil)
diff --git a/fluxer_rexctl/internal/ui/prompt.go b/fluxer_rexctl/internal/ui/prompt.go
new file mode 100644
index 000000000..03e8416d8
--- /dev/null
+++ b/fluxer_rexctl/internal/ui/prompt.go
@@ -0,0 +1,321 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ui
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+ "sync/atomic"
+
+ "charm.land/huh/v2"
+ "github.com/spf13/cobra"
+)
+
+type Option struct {
+ Label string
+ Value string
+}
+
+type Field struct {
+ Flag string
+ Title string
+ Value *string
+ Options []Option
+ Secret bool
+ Default string
+ Optional bool
+ Validate func(string) error
+}
+
+var errNoValue = errors.New("prompt field has no value pointer")
+
+type promptError string
+
+func (e promptError) Error() string { return string(e) }
+
+func (u *UI) Ask(cmd *cobra.Command, fields ...Field) error {
+ for _, f := range fields {
+ if f.Value == nil {
+ return errNoValue
+ }
+ if f.Default == "" {
+ f.Default = flagDefault(cmd, f.Flag)
+ }
+ if flagPassed(cmd, f.Flag) {
+ if err := f.check(*f.Value); err != nil {
+ return Usage(sentence(err.Error()))
+ }
+ continue
+ }
+ if !u.interactive {
+ if *f.Value == "" {
+ *f.Value = f.Default
+ }
+ if *f.Value == "" {
+ if f.Optional {
+ continue
+ }
+ return f.missing()
+ }
+ if err := f.check(*f.Value); err != nil {
+ return Usage(sentence(err.Error()))
+ }
+ continue
+ }
+ if *f.Value == "" {
+ *f.Value = f.Default
+ }
+ if err := u.runForm(u.fieldGroup(f)); err != nil {
+ return err
+ }
+ u.echo(f.Title, f.answer(*f.Value))
+ }
+ return nil
+}
+
+func (f Field) answer(v string) string {
+ if f.Secret {
+ return strings.Repeat("•", min(len([]rune(v)), 12))
+ }
+ for _, o := range f.Options {
+ if o.Value == v {
+ return o.Label
+ }
+ }
+ return v
+}
+
+func (u *UI) echo(question, answer string) {
+ if u.accessible {
+ return
+ }
+ th := u.themed()
+ u.emit(th.Heading.Render(question) + "\n" + th.Accent.Render(">") + " " + answer + "\n\n")
+}
+
+func flagPassed(cmd *cobra.Command, name string) bool {
+ if cmd == nil || name == "" {
+ return false
+ }
+ fl := cmd.Flags().Lookup(name)
+ return fl != nil && fl.Changed
+}
+
+func flagDefault(cmd *cobra.Command, name string) string {
+ if cmd == nil || name == "" {
+ return ""
+ }
+ fl := cmd.Flags().Lookup(name)
+ if fl == nil {
+ return ""
+ }
+ switch fl.DefValue {
+ case "", "false", "[]":
+ return ""
+ }
+ return fl.DefValue
+}
+
+func (f Field) check(v string) error {
+ if len(f.Options) > 0 {
+ ok := false
+ for _, o := range f.Options {
+ if o.Value == v {
+ ok = true
+ break
+ }
+ }
+ if !ok {
+ return fmt.Errorf("%s isn't one of %s", quoteValue(v), optionList(f.Options))
+ }
+ }
+ if f.Validate != nil {
+ return f.Validate(v)
+ }
+ return nil
+}
+
+func (f Field) missing() error {
+ if f.Flag == "" {
+ return Usage(fmt.Sprintf("%s needs an answer.", f.Title))
+ }
+ return MissingFlag(f.Flag)
+}
+
+func quoteValue(v string) string {
+ if v == "" {
+ return "An empty value"
+ }
+ return `"` + v + `"`
+}
+
+func optionList(opts []Option) string {
+ s := ""
+ for i, o := range opts {
+ switch {
+ case i == 0:
+ case i == len(opts)-1:
+ s += " or "
+ default:
+ s += ", "
+ }
+ s += o.Value
+ }
+ return s
+}
+
+func (u *UI) fieldGroup(f Field) *huh.Group {
+ if len(f.Options) > 0 {
+ opts := make([]huh.Option[string], len(f.Options))
+ for i, o := range f.Options {
+ opts[i] = huh.NewOption(o.Label, o.Value)
+ }
+ sel := huh.NewSelect[string]().Title(f.Title).Options(opts...).Value(f.Value)
+ if f.Validate != nil {
+ sel = sel.Validate(f.Validate)
+ }
+ return huh.NewGroup(sel)
+ }
+ in := huh.NewInput().Title(f.Title).Value(f.Value)
+ if f.Secret {
+ in = in.EchoMode(huh.EchoModePassword)
+ }
+ validate := f.Validate
+ in = in.Validate(func(v string) error {
+ if v == "" && f.Optional {
+ return nil
+ }
+ if v == "" && f.Default == "" {
+ return promptError("Type an answer.")
+ }
+ if validate != nil {
+ return validate(v)
+ }
+ return nil
+ })
+ return huh.NewGroup(in)
+}
+
+type eofReader struct {
+ r io.Reader
+ eof atomic.Bool
+}
+
+func (e *eofReader) Read(p []byte) (int, error) {
+ n, err := e.r.Read(p)
+ if err != nil {
+ e.eof.Store(true)
+ }
+ return n, err
+}
+
+type fdEOFReader struct {
+ *eofReader
+ fd uintptr
+}
+
+func (f fdEOFReader) Fd() uintptr { return f.fd }
+
+func (u *UI) runForm(groups ...*huh.Group) error {
+ ctx := u.opts.Context
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ u.themed()
+ dark := u.dark
+ in := &eofReader{r: u.opts.Stdin}
+ input := u.opts.Stdin
+ if u.accessible {
+ input = in
+ if f, ok := u.opts.Stdin.(interface{ Fd() uintptr }); ok {
+ input = fdEOFReader{eofReader: in, fd: f.Fd()}
+ }
+ }
+ form := huh.NewForm(groups...).
+ WithTheme(huh.ThemeFunc(func(bool) *huh.Styles { return HuhTheme(dark) })).
+ WithAccessible(u.accessible).
+ WithShowHelp(false).
+ WithInput(input).
+ WithOutput(u.opts.Stderr)
+ u.mu.Lock()
+ if u.spin != nil {
+ u.spin.clear()
+ }
+ u.mu.Unlock()
+ var err error
+ if u.accessible {
+ done := make(chan error, 1)
+ go func() { done <- form.RunWithContext(ctx) }()
+ select {
+ case err = <-done:
+ case <-ctx.Done():
+ return &ExitError{Code: ExitInterrupted}
+ }
+ } else {
+ err = form.RunWithContext(ctx)
+ }
+ if errors.Is(err, huh.ErrUserAborted) || ctx.Err() != nil || (u.accessible && in.eof.Load()) {
+ return &ExitError{Code: ExitInterrupted}
+ }
+ return err
+}
+
+func (u *UI) Confirm(question string, def bool) (bool, error) {
+ if u.opts.Yes {
+ return true, nil
+ }
+ if !u.interactive {
+ return false, MissingFlag("yes")
+ }
+ v := def
+ c := huh.NewConfirm().Title(question).Affirmative("Yes").Negative("No").Value(&v)
+ if err := u.runForm(huh.NewGroup(c)); err != nil {
+ return false, err
+ }
+ answer := "No"
+ if v {
+ answer = "Yes"
+ }
+ u.echo(question, answer)
+ return v, nil
+}
+
+func (u *UI) ConfirmDestructive(what, domain, confirm string) error {
+ if strings.TrimSpace(domain) == "" {
+ return Refused("rexctl can't read your instance's domain to ask you to confirm.", "Run rexctl doctor to see what's wrong.")
+ }
+ if confirm != "" {
+ if confirm == domain {
+ return nil
+ }
+ return Refused(fmt.Sprintf("%s doesn't match %s.", confirm, domain), fmt.Sprintf("Pass --confirm %s.", domain))
+ }
+ if !u.interactive {
+ return &ExitError{Code: ExitUsage, Msg: what, Fix: fmt.Sprintf("Pass --confirm %s to go ahead.", domain)}
+ }
+ if u.accessible {
+ u.emit(what + "\n")
+ }
+ var typed string
+ in := huh.NewInput().
+ Title(fmt.Sprintf("Type %s to confirm.", domain)).
+ Description(what).
+ Value(&typed).
+ Validate(func(v string) error {
+ if v != domain {
+ return promptError(fmt.Sprintf("Type %s exactly as shown.", domain))
+ }
+ return nil
+ })
+ if err := u.runForm(huh.NewGroup(in)); err != nil {
+ return err
+ }
+ if strings.TrimSpace(typed) != domain {
+ return Refused("Stopped without changing anything.", "")
+ }
+ u.echo(fmt.Sprintf("Type %s to confirm.", domain), typed)
+ return nil
+}
diff --git a/fluxer_rexctl/internal/ui/rex.go b/fluxer_rexctl/internal/ui/rex.go
new file mode 100644
index 000000000..3727d127a
--- /dev/null
+++ b/fluxer_rexctl/internal/ui/rex.go
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ui
+
+import (
+ "image/color"
+ "strings"
+
+ "charm.land/lipgloss/v2"
+)
+
+const (
+ Greeting = "Hi, I'm Rex."
+ WelcomeLine = "Let's get your Fluxer instance running."
+ FinishLine = "All set. Your instance is ready."
+ AllGreenLine = "Everything looks good."
+ rexWidth = 16
+)
+
+var rexPalette = map[byte]color.Color{
+ 'a': lipgloss.Color("#6f6bf2"),
+ 'b': Indigo,
+ 'c': lipgloss.Color("#2b2794"),
+ 'e': lipgloss.Color("#1c1a4a"),
+}
+
+var rexSprite = []string{
+ ".........aaaaaa.",
+ "........aaeaaaaa",
+ "........aaaaaaaa",
+ "........aaacc...",
+ "........aaaaaa..",
+ "........aaaa....",
+ "a......aaaaab...",
+ "aa....aaaaaab...",
+ ".aaaaaaaaaaa....",
+ "..aaaaaaaaa.....",
+ "......aa.aa.....",
+ "......bb.bb.....",
+}
+
+func rexPixel(x, y int) byte {
+ if y >= len(rexSprite) || x >= len(rexSprite[y]) {
+ return '.'
+ }
+ return rexSprite[y][x]
+}
+
+func rexCell(top, bottom byte) string {
+ switch {
+ case top == '.' && bottom == '.':
+ return " "
+ case top == '.':
+ return lipgloss.NewStyle().Foreground(rexPalette[bottom]).Render("▄")
+ case bottom == '.':
+ return lipgloss.NewStyle().Foreground(rexPalette[top]).Render("▀")
+ default:
+ return lipgloss.NewStyle().Foreground(rexPalette[top]).Background(rexPalette[bottom]).Render("▀")
+ }
+}
+
+func rexArt() []string {
+ var rows []string
+ for y := 0; y < len(rexSprite); y += 2 {
+ var b strings.Builder
+ for x := 0; x < rexWidth; x++ {
+ b.WriteString(rexCell(rexPixel(x, y), rexPixel(x, y+1)))
+ }
+ rows = append(rows, b.String())
+ }
+ return rows
+}
+
+func (u *UI) Rex(lines ...string) {
+ if !u.ShowsRex() {
+ return
+ }
+ art := rexArt()
+ first := (len(art) - len(lines)) / 2
+ var b strings.Builder
+ b.WriteString("\n")
+ for i, row := range art {
+ if i >= first && i-first < len(lines) {
+ row += " " + lines[i-first]
+ }
+ b.WriteString(row + "\n")
+ }
+ b.WriteString("\n")
+ u.emit(b.String())
+}
+
+func (u *UI) Welcome() {
+ u.Rex(Greeting, WelcomeLine)
+}
+
+func (u *UI) Finish(url string) {
+ if u.ShowsRex() {
+ u.Rex(FinishLine)
+ } else {
+ u.Info("Your instance is ready.")
+ }
+ if url != "" {
+ u.Highlight(url)
+ }
+}
+
+func (u *UI) AllGreen() {
+ u.Rex(AllGreenLine)
+}
diff --git a/fluxer_rexctl/internal/ui/step.go b/fluxer_rexctl/internal/ui/step.go
new file mode 100644
index 000000000..c8e2b5c0b
--- /dev/null
+++ b/fluxer_rexctl/internal/ui/step.go
@@ -0,0 +1,246 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package ui
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "sync"
+ "time"
+
+ "charm.land/lipgloss/v2"
+ "github.com/charmbracelet/x/ansi"
+ "golang.org/x/term"
+)
+
+var spinnerFrames = []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
+
+const spinnerInterval = 80 * time.Millisecond
+
+type Step struct {
+ ui *UI
+ mu sync.Mutex
+ title string
+ done string
+ logs []string
+ cur int64
+ total int64
+ waitFor string
+ since time.Time
+ announce bool
+ announced string
+}
+
+func (s *Step) Title(title string) {
+ s.mu.Lock()
+ s.title = title
+ s.waitFor = ""
+ s.mu.Unlock()
+}
+
+func (s *Step) Waiting(title, waitFor string) {
+ s.mu.Lock()
+ if s.since.IsZero() {
+ s.since = time.Now()
+ }
+ changed := waitFor != s.announced
+ s.title, s.waitFor, s.announced = title, waitFor, waitFor
+ line := s.titleLocked()
+ s.mu.Unlock()
+ if changed && s.announce {
+ s.ui.emit(line + "\n")
+ }
+}
+
+func (s *Step) titleLocked() string {
+ if s.waitFor == "" {
+ return s.title
+ }
+ return s.title + ", waiting for " + s.waitFor + " (" + Elapsed(time.Since(s.since)) + ")"
+}
+
+func Elapsed(d time.Duration) string {
+ d = d.Round(time.Second)
+ switch {
+ case d >= time.Hour:
+ return fmt.Sprintf("%dh %dm", int(d.Hours()), int(d.Minutes())%60)
+ case d >= time.Minute:
+ return fmt.Sprintf("%dm %ds", int(d.Minutes()), int(d.Seconds())%60)
+ }
+ return fmt.Sprintf("%ds", int(d.Seconds()))
+}
+
+func (s *Step) Done(format string, args ...any) {
+ s.mu.Lock()
+ s.done = fmt.Sprintf(format, args...)
+ s.mu.Unlock()
+}
+
+func (s *Step) Log(line string) {
+ s.mu.Lock()
+ s.logs = append(s.logs, line)
+ s.mu.Unlock()
+ s.ui.Detail("%s", line)
+}
+
+func (s *Step) Progress(current, total int64) {
+ s.mu.Lock()
+ s.cur, s.total = current, total
+ s.mu.Unlock()
+}
+
+func (s *Step) Logs() []string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return append([]string(nil), s.logs...)
+}
+
+func (s *Step) status() (string, string) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ title := s.titleLocked()
+ if s.total <= 0 && s.cur <= 0 {
+ return title, ""
+ }
+ if s.total <= 0 {
+ return title, Bytes(s.cur)
+ }
+ return title, Bytes(s.cur) + " of " + Bytes(s.total)
+}
+
+func (s *Step) doneText() string {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return s.done
+}
+
+type spinner struct {
+ u *UI
+ step *Step
+ accent lipgloss.Style
+ frame int
+ width int
+ drawn bool
+ stop chan struct{}
+ wg sync.WaitGroup
+}
+
+func (sp *spinner) clear() {
+ if sp.drawn {
+ fmt.Fprint(sp.u.errw, "\r"+ansi.EraseEntireLine)
+ sp.drawn = false
+ }
+}
+
+func (sp *spinner) draw() {
+ title, progress := sp.step.status()
+ text := title
+ if progress != "" {
+ text += " " + progress
+ }
+ if sp.width > 3 {
+ text = ansi.Truncate(text, sp.width-3, "")
+ }
+ frame := sp.accent.Render(spinnerFrames[sp.frame%len(spinnerFrames)])
+ fmt.Fprint(sp.u.errw, "\r"+ansi.EraseEntireLine+frame+" "+text)
+ sp.drawn = true
+}
+
+func (sp *spinner) run() {
+ defer sp.wg.Done()
+ t := time.NewTicker(spinnerInterval)
+ defer t.Stop()
+ for {
+ select {
+ case <-sp.stop:
+ return
+ case <-t.C:
+ sp.u.mu.Lock()
+ sp.frame++
+ sp.draw()
+ sp.u.mu.Unlock()
+ }
+ }
+}
+
+func (u *UI) spins() bool {
+ return u.mode == ModeRich && !u.opts.Quiet && !u.accessible && u.stderrTTY
+}
+
+func (u *UI) startSpinner(s *Step) *spinner {
+ accent := u.themed().Accent
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if u.spin != nil {
+ return nil
+ }
+ sp := &spinner{u: u, step: s, accent: accent, stop: make(chan struct{})}
+ if f, ok := u.opts.Stderr.(interface{ Fd() uintptr }); ok {
+ if w, _, err := term.GetSize(int(f.Fd())); err == nil {
+ sp.width = w
+ }
+ }
+ u.spin = sp
+ sp.draw()
+ sp.wg.Add(1)
+ go sp.run()
+ return sp
+}
+
+func (u *UI) stopSpinner(sp *spinner) {
+ if sp == nil {
+ return
+ }
+ close(sp.stop)
+ sp.wg.Wait()
+ u.mu.Lock()
+ sp.clear()
+ u.spin = nil
+ u.mu.Unlock()
+}
+
+func (u *UI) Step(ctx context.Context, title string, fn func(ctx context.Context, s *Step) error) error {
+ s := &Step{ui: u, title: title}
+ var sp *spinner
+ switch {
+ case u.spins():
+ sp = u.startSpinner(s)
+ case u.mode != ModeJSON && !u.opts.Quiet:
+ s.announce = true
+ if u.accessible || u.opts.Verbose {
+ u.emit(title + "\n")
+ }
+ }
+ err := fn(ctx, s)
+ u.stopSpinner(sp)
+ if err != nil {
+ if !u.opts.Verbose {
+ if logs := s.Logs(); len(logs) > 0 {
+ u.emit(u.theme.Dim.Render(strings.Join(logs, "\n")) + "\n")
+ }
+ }
+ return err
+ }
+ if done := s.doneText(); done != "" {
+ u.OK("%s", done)
+ }
+ return nil
+}
+
+func Bytes(n int64) string {
+ const unit = 1000
+ if n < unit {
+ return fmt.Sprintf("%d B", n)
+ }
+ units := []string{"KB", "MB", "GB", "TB", "PB"}
+ v := float64(n) / unit
+ i := 0
+ for v >= unit && i < len(units)-1 {
+ v /= unit
+ i++
+ }
+ s := fmt.Sprintf("%.1f", v)
+ s = strings.TrimSuffix(s, ".0")
+ return s + " " + units[i]
+}