Debian Codegraph @

cmd/csv2table/csv2table.go

raw
1 package main
2
3 import (
4 "encoding/csv"
5 "flag"
6 "fmt"
7 "io"
8 "math"
9 "os"
10 "strings"
11 "unicode/utf8"
12
13 "github.com/olekukonko/ll"
14 "github.com/olekukonko/ll/lh"
15 "github.com/olekukonko/ts" // For terminal size
16
17 "github.com/olekukonko/tablewriter"
18 "github.com/olekukonko/tablewriter/renderer"
19 "github.com/olekukonko/tablewriter/tw"
20 )
21
22 var (
23 fileName = flag.String("f", "", "Set CSV file path (e.g., sample.csv). If empty and -p is not set, STDIN is used.")
24 delimiter = flag.String("d", ",", "Set CSV delimiter (e.g., \",\" \"|\" \"\\t\"). For tab, use actual tab or '\\t'.")
25 header = flag.Bool("h", true, "Treat the first row as a header.")
26 align = flag.String("a", "none", "Set global cell alignment (none|left|right|center). 'none' uses renderer defaults.")
27 pipe = flag.Bool("p", false, "Read CSV data from STDIN (standard input). Overrides -f if both are set.")
28 border = flag.Bool("b", true, "Enable/disable table borders and lines (overall structure).")
29 streaming = flag.Bool("s", false, "Enable streaming mode (processes row-by-row). Might not support all features like AutoHide.")
30 rendererType = flag.String("renderer", "blueprint", "Set table renderer (blueprint|colorized|markdown|html|svg|ocean).")
31 symbolStyle = flag.String("symbols", "light", "Set border symbol style (light|ascii|heavy|double|rounded|markdown|graphical|dotted|arrow|starry|hearts|tech|nature|artistic|8-bit|chaos|dots|blocks|zen|none).")
32 rowAutoWrap = flag.String("wrap", "normal", "Set row auto-wrap mode (normal|truncate|break|none).")
33 inferColumns = flag.Bool("infer", true, "Attempt to infer and normalize column counts if CSV rows are ragged. If false, CSV parsing errors on mismatched columns will halt.")
34 tableMaxWidth = flag.Int("maxwidth", 0, "Set maximum table width in characters (0 for auto based on 90% terminal width or content).")
35 debug = flag.Bool("debug", false, "Enable debug logging for tablewriter operations.")
36
37 // add namespace
38 logger = ll.Namespace("csv2table").Handler(lh.NewColorizedHandler(os.Stdout))
39 )
40
41 func main() {
42 flag.Usage = func() {
43 fmt.Fprintf(os.Stderr, "Usage: %s [options] [file]\n", os.Args[0])
44 fmt.Fprintf(os.Stderr, "Reads CSV data from a file or STDIN and renders it as a formatted table.\n\n")
45 fmt.Fprintf(os.Stderr, "If [file] is provided, it overrides the -f flag.\n")
46 fmt.Fprintf(os.Stderr, "If no [file] and no -f is provided, and -p is not set, STDIN is used.\n\n")
47 fmt.Fprintf(os.Stderr, "Options:\n")
48 flag.PrintDefaults()
49 }
50 flag.Parse()
51
52 // Handle non-flag filename argument
53 if flag.NArg() > 0 {
54 *fileName = flag.Arg(0)
55 logger.Infof("Using filename from argument: %s", *fileName)
56 }
57
58 // Determine input source
59 var inputReader io.Reader
60 var err error
61
62 if *pipe {
63 logger.Info("Reading CSV from STDIN (pipe mode).")
64 inputReader = os.Stdin
65 } else if *fileName != "" {
66 logger.Infof("Reading CSV from file: %s", *fileName)
67 file, errFile := os.Open(*fileName)
68 if errFile != nil {
69 logger.Fatal("failed to open file '%s': %w", *fileName, errFile)
70 }
71 defer file.Close()
72 inputReader = file
73 } else {
74 logger.Info("No file specified and pipe mode not active. Reading CSV from STDIN.")
75 inputReader = os.Stdin
76 }
77
78 // Leading newline for cleaner output, unless it's HTML/SVG etc.
79 if !isGraphicalRenderer(*rendererType) {
80 fmt.Println()
81 }
82
83 err = process(inputReader)
84 if err != nil {
85 logger.Fatal(err) // process will return specific errors
86 }
87
88 if !isGraphicalRenderer(*rendererType) {
89 fmt.Println() // Trailing newline
90 }
91 }
92
93 func process(r io.Reader) error {
94 // CSV Reader Configuration
95 csvInputReader := csv.NewReader(r)
96 if *delimiter != "" {
97 // Handle literal \t for tab delimiter
98 d := *delimiter
99 if d == "\\t" {
100 d = "\t"
101 }
102 runeVal, size := utf8.DecodeRuneInString(d)
103 if size == 0 {
104 logger.Warn("Invalid or empty delimiter specified, using default comma ','.")
105 runeVal = ','
106 }
107 csvInputReader.Comma = runeVal
108 }
109 // If inferring columns, we need to allow variable fields in the first pass.
110 // If not inferring, `FieldsPerRecord = 0` will cause csv.Reader to error on inconsistent rows.
111 if !*inferColumns {
112 csvInputReader.FieldsPerRecord = 0 // Standard Go CSV behavior: error on inconsistent fields after first.
113 } else {
114 csvInputReader.FieldsPerRecord = -1 // Allow variable fields for the first pass if inferring.
115 }
116
117 // Symbol Selection
118 var selectedSymbols tw.Symbols
119 // (Full switch statement for symbolStyle as provided previously)
120 switch strings.ToLower(*symbolStyle) {
121 case "ascii":
122 selectedSymbols = tw.NewSymbols(tw.StyleASCII)
123 case "light", "default":
124 selectedSymbols = tw.NewSymbols(tw.StyleLight)
125 case "heavy":
126 selectedSymbols = tw.NewSymbols(tw.StyleHeavy)
127 case "double":
128 selectedSymbols = tw.NewSymbols(tw.StyleDouble)
129 case "rounded":
130 selectedSymbols = tw.NewSymbols(tw.StyleRounded)
131 case "markdown":
132 selectedSymbols = tw.NewSymbols(tw.StyleMarkdown)
133 case "graphical":
134 selectedSymbols = tw.NewSymbols(tw.StyleGraphical)
135 case "dotted":
136 selectedSymbols = tw.NewSymbolCustom("Dotted").WithRow("·").WithColumn(":").WithTopLeft(".").WithTopMid("·").WithTopRight(".").WithMidLeft(":").WithCenter("+").WithMidRight(":").WithBottomLeft("'").WithBottomMid("·").WithBottomRight("'")
137 case "arrow":
138 selectedSymbols = tw.NewSymbolCustom("Arrow").WithRow("→").WithColumn("↓").WithTopLeft("↗").WithTopMid("↑").WithTopRight("↖").WithMidLeft("→").WithCenter("↔").WithMidRight("←").WithBottomLeft("↘").WithBottomMid("↓").WithBottomRight("↙")
139 case "starry":
140 selectedSymbols = tw.NewSymbolCustom("Starry").WithRow("★").WithColumn("☆").WithTopLeft("✧").WithTopMid("✯").WithTopRight("✧").WithMidLeft("✦").WithCenter("✶").WithMidRight("✦").WithBottomLeft("✧").WithBottomMid("✯").WithBottomRight("✧")
141 case "hearts":
142 selectedSymbols = tw.NewSymbolCustom("Hearts").WithRow("♥").WithColumn("❤").WithTopLeft("❥").WithTopMid("♡").WithTopRight("❥").WithMidLeft("❣").WithCenter("✚").WithMidRight("❣").WithBottomLeft("❦").WithBottomMid("♡").WithBottomRight("❦")
143 case "tech":
144 selectedSymbols = tw.NewSymbolCustom("Tech").WithRow("=").WithColumn("||").WithTopLeft("/*").WithTopMid("##").WithTopRight("*/").WithMidLeft("//").WithCenter("<>").WithMidRight("\\").WithBottomLeft("\\*").WithBottomMid("##").WithBottomRight("*/")
145 case "nature":
146 selectedSymbols = tw.NewSymbolCustom("Nature").WithRow("~").WithColumn("|").WithTopLeft("🌱").WithTopMid("🌿").WithTopRight("🌱").WithMidLeft("🍃").WithCenter("❀").WithMidRight("🍃").WithBottomLeft("🌻").WithBottomMid("🌾").WithBottomRight("🌻")
147 case "artistic":
148 selectedSymbols = tw.NewSymbolCustom("Artistic").WithRow("▬").WithColumn("▐").WithTopLeft("◈").WithTopMid("◊").WithTopRight("◈").WithMidLeft("◀").WithCenter("⬔").WithMidRight("▶").WithBottomLeft("◭").WithBottomMid("▣").WithBottomRight("◮")
149 case "8-bit":
150 selectedSymbols = tw.NewSymbolCustom("8-Bit").WithRow("■").WithColumn("█").WithTopLeft("╔").WithTopMid("▲").WithTopRight("╗").WithMidLeft("◄").WithCenter("♦").WithMidRight("►").WithBottomLeft("╚").WithBottomMid("▼").WithBottomRight("╝")
151 case "chaos":
152 selectedSymbols = tw.NewSymbolCustom("Chaos").WithRow("≈").WithColumn("§").WithTopLeft("⌘").WithTopMid("∞").WithTopRight("⌥").WithMidLeft("⚡").WithCenter("☯").WithMidRight("♞").WithBottomLeft("⌂").WithBottomMid("∆").WithBottomRight("◊")
153 case "dots":
154 selectedSymbols = tw.NewSymbolCustom("Dots").WithRow("·").WithColumn(" ").WithTopLeft("·").WithTopMid("·").WithTopRight("·").WithMidLeft(" ").WithCenter("·").WithMidRight(" ").WithBottomLeft("·").WithBottomMid("·").WithBottomRight("·")
155 case "blocks":
156 selectedSymbols = tw.NewSymbolCustom("Blocks").WithRow("▀").WithColumn("█").WithTopLeft("▛").WithTopMid("▀").WithTopRight("▜").WithMidLeft("▌").WithCenter("█").WithMidRight("▐").WithBottomLeft("▙").WithBottomMid("▄").WithBottomRight("▟")
157 case "zen":
158 selectedSymbols = tw.NewSymbolCustom("Zen").WithRow("~").WithColumn(" ").WithTopLeft(" ").WithTopMid("♨").WithTopRight(" ").WithMidLeft(" ").WithCenter("☯").WithMidRight(" ").WithBottomLeft(" ").WithBottomMid("♨").WithBottomRight(" ")
159 case "none":
160 selectedSymbols = tw.NewSymbols(tw.StyleNone)
161 default:
162 logger.Warnf("Default symbol style '%s', using default (Light).", *symbolStyle)
163 selectedSymbols = tw.NewSymbols(tw.StyleLight)
164 }
165
166 // Base Rendition Configuration
167 borderCfg := tw.Border{Left: tw.Off, Right: tw.Off, Top: tw.Off, Bottom: tw.Off}
168 linesCfg := tw.Lines{ShowTop: tw.Off, ShowBottom: tw.Off, ShowHeaderLine: tw.Off, ShowFooterLine: tw.Off}
169 separatorsCfg := tw.Separators{BetweenColumns: tw.Off, ShowHeader: tw.Off, ShowFooter: tw.Off, BetweenRows: tw.Off}
170
171 if *border {
172 borderCfg = tw.Border{Left: tw.On, Right: tw.On, Top: tw.On, Bottom: tw.On}
173 linesCfg = tw.Lines{ShowTop: tw.On, ShowBottom: tw.On, ShowHeaderLine: tw.On, ShowFooterLine: tw.On}
174 separatorsCfg = tw.Separators{ShowHeader: tw.On, ShowFooter: tw.On, BetweenRows: tw.Off, BetweenColumns: tw.On}
175 }
176
177 rendererConfiguredSpecifically := false
178 switch strings.ToLower(*rendererType) {
179 case "markdown":
180 selectedSymbols = tw.NewSymbols(tw.StyleMarkdown)
181 borderCfg = tw.Border{Left: tw.On, Right: tw.On, Top: tw.Off, Bottom: tw.Off}
182 linesCfg = tw.Lines{ShowTop: tw.Off, ShowBottom: tw.Off, ShowHeaderLine: tw.On, ShowFooterLine: tw.Off}
183 separatorsCfg = tw.Separators{BetweenColumns: tw.On, ShowHeader: tw.On, BetweenRows: tw.Off, ShowFooter: tw.Off}
184 if !*border {
185 borderCfg = tw.Border{Left: tw.Off, Right: tw.Off, Top: tw.Off, Bottom: tw.Off}
186 linesCfg.ShowHeaderLine = tw.Off
187 separatorsCfg.BetweenColumns = tw.Off
188 }
189 rendererConfiguredSpecifically = true
190 case "html", "svg": // These renderers manage their own structure
191 borderCfg = tw.Border{}
192 linesCfg = tw.Lines{}
193 separatorsCfg = tw.Separators{}
194 selectedSymbols = tw.NewSymbols(tw.StyleNone)
195 rendererConfiguredSpecifically = true
196 }
197
198 baseRendition := tw.Rendition{
199 Borders: borderCfg,
200 Settings: tw.Settings{Separators: separatorsCfg, Lines: linesCfg, CompactMode: tw.Off},
201 Symbols: selectedSymbols,
202 }
203
204 // Renderer Instantiation
205 var selectedRenderer tw.Renderer
206 // For CLI, os.Stdout is the writer. For HTML/SVG, their renderers handle this.
207 outputTarget := io.Writer(os.Stdout) // Default to os.Stdout
208
209 switch strings.ToLower(*rendererType) {
210 case "markdown":
211 selectedRenderer = renderer.NewMarkdown(baseRendition)
212 case "html":
213 selectedRenderer = renderer.NewHTML(renderer.HTMLConfig{EscapeContent: true})
214 case "svg":
215 selectedRenderer = renderer.NewSVG(renderer.SVGConfig{FontSize: 12, Padding: 5, Debug: *debug})
216 case "colorized":
217 selectedRenderer = renderer.NewColorized()
218 if r, ok := selectedRenderer.(tw.Renditioning); ok && !rendererConfiguredSpecifically {
219 r.Rendition(baseRendition)
220 }
221 case "ocean":
222 selectedRenderer = renderer.NewOcean()
223 if r, ok := selectedRenderer.(tw.Renditioning); ok && !rendererConfiguredSpecifically {
224 r.Rendition(baseRendition)
225 }
226 case "blueprint":
227 fallthrough
228 default:
229 if *rendererType != "" && strings.ToLower(*rendererType) != "blueprint" {
230 logger.Warnf("Default renderer type '%s', using Blueprint.", *rendererType)
231 }
232 selectedRenderer = renderer.NewBlueprint(baseRendition)
233 }
234
235 // Table Options & Creation
236 calculatedMaxWidth := 0
237 if *tableMaxWidth > 0 {
238 calculatedMaxWidth = *tableMaxWidth
239 } else {
240 termSize, err := ts.GetSize()
241 if err == nil && termSize.Col() > 0 {
242 calculatedMaxWidth = int(math.Floor(float64(termSize.Col()) * 0.90))
243 }
244 // If termSize fails or is 0, calculatedMaxWidth remains 0 (content-based width)
245 }
246 if calculatedMaxWidth > 0 {
247 logger.Infof("Calculated table max width: %d", calculatedMaxWidth)
248 }
249
250 tableOpts := []tablewriter.Option{
251 tablewriter.WithDebug(*debug),
252 tablewriter.WithHeaderConfig(getHeaderConfig(*align, *rowAutoWrap)), // Can use same wrap for header or add specific
253 tablewriter.WithRowConfig(getRowConfig(*align, *rowAutoWrap)),
254 tablewriter.WithRenderer(selectedRenderer),
255 tablewriter.WithTableMax(calculatedMaxWidth), // Apply max width
256 }
257
258 if *streaming {
259 tableOpts = append(tableOpts, tablewriter.WithStreaming(tw.StreamConfig{Enable: true}))
260 logger.Info("Streaming mode ENABLED.")
261 } else {
262 logger.Info("Streaming mode DISABLED (batch mode).")
263 }
264
265 table := tablewriter.NewTable(outputTarget, tableOpts...)
266
267 // Data Ingestion and Normalization (Two-Pass if inferring)
268 var headerData []string
269 var dataRecords [][]string
270
271 if *inferColumns {
272 logger.Info("Inferring columns (two-pass CSV read).")
273 // Pass 1: Get all records and find max columns
274 firstPassReader := csv.NewReader(r) // r is the original io.Reader
275 // Re-apply delimiter for firstPassReader
276 if *delimiter != "" {
277 d := *delimiter
278 if d == "\\t" {
279 d = "\t"
280 }
281 runeVal, size := utf8.DecodeRuneInString(d)
282 if size == 0 {
283 runeVal = ','
284 }
285 firstPassReader.Comma = runeVal
286 }
287 firstPassReader.FieldsPerRecord = -1 // Allow variable fields
288
289 allRawRecords, errRead := firstPassReader.ReadAll()
290 if errRead != nil {
291 return fmt.Errorf("error reading CSV during inference pass: %w", errRead)
292 }
293 if len(allRawRecords) == 0 {
294 fmt.Println("No data to display (CSV empty or unreadable in inference pass).")
295 return nil
296 }
297
298 maxCols := 0
299 if *header && len(allRawRecords) > 0 {
300 headerData = allRawRecords[0]
301 if len(headerData) > maxCols {
302 maxCols = len(headerData)
303 }
304 if len(allRawRecords) > 1 {
305 dataRecords = allRawRecords[1:]
306 }
307 } else {
308 dataRecords = allRawRecords
309 }
310
311 for _, rec := range dataRecords {
312 if len(rec) > maxCols {
313 maxCols = len(rec)
314 }
315 }
316 if maxCols == 0 && len(headerData) > 0 { // Only header was present
317 maxCols = len(headerData)
318 }
319 logger.Infof("Inferred max columns: %d", maxCols)
320
321 // Normalize header
322 if *header && len(headerData) > 0 {
323 normHeader := make([]string, maxCols)
324 copy(normHeader, headerData)
325 // Padding with empty strings is implicit if normHeader is shorter
326 table.Header(normHeader)
327 }
328 // Normalize data records
329 for i := range dataRecords {
330 normRecord := make([]string, maxCols)
331 copy(normRecord, dataRecords[i])
332 // Padding with empty strings is implicit if normRecord is shorter
333 dataRecords[i] = normRecord
334 }
335 } else {
336 logger.Info("Not inferring columns (standard CSV parsing). Errors on inconsistent rows are fatal.")
337 // If not inferring, use the original csvInputReader (already configured)
338 // For batch mode, ReadAll is natural. For streaming, we'll read line by line.
339 if !*streaming {
340 allRawRecords, errRead := csvInputReader.ReadAll()
341 if errRead != nil {
342 return fmt.Errorf("error reading CSV (ReadAll, no inference): %w.\nIf CSV has ragged rows, try enabling -infer flag", errRead)
343 }
344 if len(allRawRecords) == 0 {
345 fmt.Println("No data to display.")
346 return nil
347 }
348 if *header && len(allRawRecords) > 0 {
349 headerData = allRawRecords[0]
350 table.Header(headerData)
351 if len(allRawRecords) > 1 {
352 dataRecords = allRawRecords[1:]
353 }
354 } else {
355 dataRecords = allRawRecords
356 }
357 }
358 // Streaming mode without inference will handle records directly from csvInputReader later.
359 }
360
361 // Table Population and Rendering
362 if table.Config().Stream.Enable {
363 logger.Info("Populating table in STREAMING mode.")
364 if err := table.Start(); err != nil {
365 return fmt.Errorf("error starting streaming table: %w", err)
366 }
367 defer table.Close() // Ensure close is called
368
369 if *inferColumns { // We already have normalized headerData and dataRecords
370 // Header already set if *header was true
371 for i, record := range dataRecords {
372 if err := table.Append(record); err != nil {
373 return fmt.Errorf("error appending stream record %d (inferred): %w", i, err)
374 }
375 }
376 } else { // Not inferring, read directly
377 lineNum := 1
378 if *header { // Header would be the first record read by csvInputReader
379 headerRow, errH := csvInputReader.Read()
380 if errH != nil && errH != io.EOF {
381 return fmt.Errorf("error reading header for streaming (no inference): %w", errH)
382 }
383 if errH != io.EOF && len(headerRow) > 0 {
384 table.Header(headerRow)
385 }
386 lineNum = 2
387 }
388 for {
389 record, errL := csvInputReader.Read()
390 if errL == io.EOF {
391 break
392 }
393 if errL != nil {
394 return fmt.Errorf("error reading CSV record for streaming on data line approx %d (no inference): %w", lineNum, errL)
395 }
396 if errA := table.Append(record); errA != nil {
397 return fmt.Errorf("error appending stream record on data line approx %d (no inference): %w", lineNum, errA)
398 }
399 lineNum++
400 }
401 }
402 } else { // Batch mode
403 logger.Info("Populating table in BATCH mode.")
404 // If inferring, headerData and dataRecords are already prepared and normalized.
405 // If not inferring, they were populated from ReadAll().
406 // Header was already set if *header was true.
407 if err := table.Bulk(dataRecords); err != nil {
408 return fmt.Errorf("error appending batch records: %w", err)
409 }
410 if err := table.Render(); err != nil {
411 return fmt.Errorf("error rendering batch table: %w", err)
412 }
413 }
414 return nil
415 }
416
417 func getHeaderConfig(alignFlag, wrapFlag string) tw.CellConfig {
418 cfgFmt := tw.CellFormatting{Alignment: tw.AlignCenter, AutoFormat: tw.On}
419 switch strings.ToLower(alignFlag) {
420 case "left":
421 cfgFmt.Alignment = tw.AlignLeft
422 case "right":
423 cfgFmt.Alignment = tw.AlignRight
424 case "center":
425 cfgFmt.Alignment = tw.AlignCenter
426 }
427 switch strings.ToLower(wrapFlag) {
428 case "truncate":
429 cfgFmt.AutoWrap = tw.WrapTruncate
430 case "break":
431 cfgFmt.AutoWrap = tw.WrapBreak
432 case "none":
433 cfgFmt.AutoWrap = tw.WrapNone
434 case "normal":
435 cfgFmt.AutoWrap = tw.WrapNormal
436 default:
437 cfgFmt.AutoWrap = tw.WrapTruncate // Default for headers
438 }
439 return tw.CellConfig{
440 Formatting: cfgFmt,
441 Padding: tw.CellPadding{Global: tw.Padding{Left: " ", Right: " "}},
442 }
443 }
444
445 func getRowConfig(alignFlag, wrapFlag string) tw.CellConfig {
446 cfgFmt := tw.CellFormatting{}
447 switch strings.ToLower(alignFlag) {
448 case "left":
449 cfgFmt.Alignment = tw.AlignLeft
450 case "right":
451 cfgFmt.Alignment = tw.AlignRight
452 case "center":
453 cfgFmt.Alignment = tw.AlignCenter
454 default:
455 cfgFmt.Alignment = tw.AlignLeft
456 }
457 switch strings.ToLower(wrapFlag) {
458 case "truncate":
459 cfgFmt.AutoWrap = tw.WrapTruncate
460 case "break":
461 cfgFmt.AutoWrap = tw.WrapBreak
462 case "none":
463 cfgFmt.AutoWrap = tw.WrapNone
464 default:
465 cfgFmt.AutoWrap = tw.WrapNormal
466 }
467 return tw.CellConfig{
468 Formatting: cfgFmt,
469 Padding: tw.CellPadding{Global: tw.Padding{Left: " ", Right: " "}},
470 }
471 }
472
473 func getFooterConfig() tw.CellConfig { // Footer doesn't currently take wrap/align flags from CLI
474 return tw.CellConfig{
475 Formatting: tw.CellFormatting{Alignment: tw.AlignRight, AutoWrap: tw.WrapNormal},
476 }
477 }
478
479 func isGraphicalRenderer(rendererName string) bool {
480 name := strings.ToLower(rendererName)
481 return name == "html" || name == "svg"
482 }