command.go
This file
Path
table/command.go
181 lines · 4.2 KiB · Go
Last changed by
chore: prepare v2 (#1116)Drew Smirnoffbefore adoption02d6f06
History of this fileTake it
1package table23import (4 "encoding/csv"5 "fmt"6 "os"78 "charm.land/bubbles/v2/help"9 "charm.land/bubbles/v2/table"10 tea "charm.land/bubbletea/v2"11 "charm.land/gum/v2/internal/stdin"12 "charm.land/gum/v2/internal/timeout"13 "charm.land/gum/v2/internal/tty"14 "charm.land/gum/v2/style"15 "charm.land/lipgloss/v2"16 ltable "charm.land/lipgloss/v2/table"17 "golang.org/x/text/encoding"18 "golang.org/x/text/encoding/unicode"19 "golang.org/x/text/transform"20)2122// Run provides a shell script interface for rendering tabular data (CSV).23func (o Options) Run() error {24 var input *os.File25 if o.File != "" {26 var err error27 input, err = os.Open(o.File)28 if err != nil {29 return fmt.Errorf("could not render file: %w", err)30 }31 } else {32 if stdin.IsEmpty() {33 return fmt.Errorf("no data provided")34 }35 input = os.Stdin36 }37 defer input.Close() //nolint: errcheck3839 transformer := unicode.BOMOverride(encoding.Nop.NewDecoder())40 reader := csv.NewReader(transform.NewReader(input, transformer))41 reader.LazyQuotes = o.LazyQuotes42 reader.FieldsPerRecord = o.FieldsPerRecord43 separatorRunes := []rune(o.Separator)44 if len(separatorRunes) != 1 {45 return fmt.Errorf("separator must be single character")46 }47 reader.Comma = separatorRunes[0]4849 writer := csv.NewWriter(os.Stdout)50 writer.Comma = separatorRunes[0]5152 var columnNames []string53 var err error54 // If no columns are provided we'll use the first row of the CSV as the55 // column names.56 if len(o.Columns) <= 0 {57 columnNames, err = reader.Read()58 if err != nil {59 return fmt.Errorf("unable to parse columns")60 }61 } else {62 columnNames = o.Columns63 }6465 data, err := reader.ReadAll()66 if err != nil {67 return fmt.Errorf("invalid data provided")68 }69 columns := make([]table.Column, 0, len(columnNames))7071 for i, title := range columnNames {72 width := lipgloss.Width(title)73 if len(o.Widths) > i {74 width = o.Widths[i]75 }76 columns = append(columns, table.Column{77 Title: title,78 Width: width,79 })80 }8182 defaultStyles := table.DefaultStyles()83 top, right, bottom, left := style.ParsePadding(o.Padding)8485 styles := table.Styles{86 Cell: defaultStyles.Cell.Inherit(o.CellStyle.ToLipgloss()),87 Header: defaultStyles.Header.Inherit(o.HeaderStyle.ToLipgloss()),88 Selected: o.SelectedStyle.ToLipgloss(),89 }9091 rows := make([]table.Row, 0, len(data))92 for row := range data {93 if len(data[row]) > len(columns) {94 return fmt.Errorf("invalid number of columns")95 }9697 // fixes the data in case we have more columns than rows:98 for len(data[row]) < len(columns) {99 data[row] = append(data[row], "")100 }101102 for i, col := range data[row] {103 if len(o.Widths) == 0 {104 width := lipgloss.Width(col)105 if width > columns[i].Width {106 columns[i].Width = width107 }108 }109 }110111 rows = append(rows, table.Row(data[row]))112 }113114 if o.Print {115 table := ltable.New().116 Headers(columnNames...).117 Rows(data...).118 BorderStyle(o.BorderStyle.ToLipgloss()).119 Border(style.Border[o.Border]).120 StyleFunc(func(row, _ int) lipgloss.Style {121 if row == 0 {122 return styles.Header123 }124 return styles.Cell125 })126127 tty.Println(table.Render())128 return nil129 }130131 opts := []table.Option{132 table.WithColumns(columns),133 table.WithFocused(true),134 table.WithRows(rows),135 table.WithStyles(styles),136 }137 if o.Height > 0 {138 opts = append(opts, table.WithHeight(o.Height-top-bottom))139 }140141 table := table.New(opts...)142143 ctx, cancel := timeout.Context(o.Timeout)144 defer cancel()145146 m := model{147 table: table,148 showHelp: o.ShowHelp,149 hideCount: o.HideCount,150 help: help.New(),151 keymap: defaultKeymap(),152 padding: []int{top, right, bottom, left},153 }154 tm, err := tea.NewProgram(155 m,156 tea.WithOutput(os.Stderr),157 tea.WithContext(ctx),158 ).Run()159 if err != nil {160 return fmt.Errorf("failed to start tea program: %w", err)161 }162163 if tm == nil {164 return fmt.Errorf("failed to get selection")165 }166167 m = tm.(model)168 if o.ReturnColumn > 0 && o.ReturnColumn <= len(m.selected) {169 if err = writer.Write([]string{m.selected[o.ReturnColumn-1]}); err != nil {170 return fmt.Errorf("failed to write col %d of selected row: %w", o.ReturnColumn, err)171 }172 } else {173 if err = writer.Write([]string(m.selected)); err != nil {174 return fmt.Errorf("failed to write selected row: %w", err)175 }176 }177178 writer.Flush()179180 return nil181}