go-pretty

repository·main·Indexed 25 days ago

https://github.com/jedib0t/go-pretty

A collection of Go utilities for prettifying console output. It includes packages for creating customizable tables with support for ASCII, HTML, Markdown, and CSV formats; hierarchical lists with multiple indentation levels; progress trackers with ETA and speed calculations; and text manipulation tools for alignment, colors, and formatting.

Tokens
7.4K
Snippets
19
Records
46
Agent score
86%

What's inside go-pretty

  1. Overview of go-pretty packages

    main

    The go-pretty library provides utilities to prettify console output with a focus on customization. Available packages include:

    • Table: Pretty-print tables with colors, auto-merge, sorting, paging, and multiple output formats (ASCII, HTML, Markdown, CSV, TSV).
    • Progress: Track progress of tasks with ETA, speed calculation, indeterminate indicators, and customizable styles.
    • List: Pretty-print hierarchical lists with multiple levels, indentation, and multiple output formats (ASCII, HTML, Markdown).
    • Text: Utility functions for string manipulation, including alignment, colors, formatting, cursor control, and text transformations.
  2. Track progress of multiple tasks with the Progress package

    main

    The progress package allows you to track the progress of one or more tasks simultaneously (e.g., parallel downloads). It supports both determinate trackers (where a Total is provided) and indeterminate trackers (without a Total).

    Key capabilities include:

    • ETA Calculation: Automatically estimates time of arrival.
    • Speed Calculation: Calculates items or bytes per second.
    • Error Tracking: Mark failed tasks using MarkAsErrored().
    • Aggregation: An overall progress tracker can aggregate progress across all individual trackers.
  3. Table Features Overview

    main

    The go-pretty table package supports a wide range of formatting and structural features, including:

    • Auto-Indexing: Automatically generate row numbers or column indices.
    • Headers and Footers: Define specific rows for titles or summary data (e.g., totals).
    • Alignment: Custom horizontal and vertical (VAlign) alignment for columns.
    • Multi-line Rows: Support for cells containing multiple lines of text.
    • Separators: Insert divider rows between groups of data.
    • Pagination: Control PageSize and handle page breaks.
    • Row Constraints: Set an Allowed Row Length to manage terminal width.
    • Styling: Multiple built-in styles such as StyleLight, StyleDouble, StyleColoredBright, and funkyStyle.
    • Export Formats: Generate output in various formats including:
      • Plain Text (with various border styles)
      • CSV
      • HTML
      • Markdown
  4. Supported List Styles and Formats

    main

    The go-pretty list package supports various visual styles and output formats:

    Visual Styles

    • Default: A simple bulleted list.
    • StyleBulletCircle: Uses circle bullets (●).
    • StyleConnectedRounded: Uses tree-like connections (╭─, ├─, ╰─) for hierarchical structures.
    • funkyStyle: Uses a custom character-based format.

    Output Formats

    • HTML: Generates nested <ul> and <li> elements with specific classes (e.g., go-pretty-table, go-pretty-table-1).
    • Markdown: Generates standard Markdown nested bullet lists.
  5. Build nested lists with the List package

    main
    The list package allows you to create pretty-printed lists with multiple indentation levels. You can append items one-by-one or as a group. The package automatically handles tabs by converting them to spaces and supports multi-line items where newlines are preserved. You can reset the list to its initial state for reuse.
  6. Customize table styles and colors

    main

    Apply pre-defined styles or create custom ones using SetStyle or Style().

    Pre-defined Styles:

    • StyleDefault: Classic ASCII borders.
    • StyleLight: Light box-drawing characters.
    • StyleBold: Bold box-drawing characters.
    • StyleDouble: Double box-drawing characters.
    • StyleRounded: Rounded box-drawing characters.
    • StyleColoredBright / StyleColoredDark: Colored variants without borders.
    • Various color variants: Blue, Cyan, Green, Magenta, Red, Yellow.

    Customization Options:

    • SetRowPainter(func): Define a custom function to paint rows (can access row number and sorted position).
    • ColumnConfig.Colors: Set per-column colors for body, header, or footer.
    • ColumnConfig.Transformer: Use built-in transformers (e.g., Number, JSON, Time, URL) or custom functions to transform cell content.
  7. Sort and filter table data

    main

    Apply sorting and filtering logic to your table data before rendering.

    Sorting:

    • SortBy(columns...): Sort by one or more columns.
    • Supports modes: Alphabetical, Numeric, Alpha-numeric, Numeric-alpha.
    • IgnoreCase: Option for case-insensitive sorting.
    • CustomLess(func): Provide a custom comparison function.

    Filtering:

    • FilterBy(columns...): Apply filters using AND logic (all must match).
    • Operators:
      • Equality: Equal, NotEqual
      • Numeric: GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual
      • String: Contains, NotContains, StartsWith, EndsWith
      • Regex: RegexMatch, RegexNotMatch
    • IgnoreCase: Option for case-insensitive filtering.
    • CustomFilter(func): Provide a custom filtering function.
    • Filters are applied before sorting.
  8. Build a basic table with go-pretty

    main

    Use the Table package to create ASCII/Unicode tables. You can build tables by adding headers, footers, and rows one-by-one or in groups.

    Core building methods include:

    • AppendRow(args...): Add a single row.
    • AppendRows(args...): Add multiple rows.
    • AppendHeader(args...): Add header rows.
    • AppendFooter(args...): Add footer rows.
    • AppendSeparator(): Manually add a separator after a row.
    • SetTitle(string): Add a title above the table.
    • SetCaption(string): Add a caption below the table.
    • ImportGrid(grid): Import 1D or 2D arrays/grids as rows.
    • Reset*(): Reset headers, rows, or footers to reuse the writer.
  9. Import go-pretty packages

    main

    Import the specific sub-packages required for your task. The core packages are table, list, progress, and text.

    import (
        "github.com/jedib0t/go-pretty/v6/table"
        "github.com/jedib0t/go-pretty/v6/list"
        "github.com/jedib0t/go-pretty/v6/progress"
        "github.com/jedib0t/go-pretty/v6/text"
    )
  10. Enable auto-merging for rows and columns

    main

    You can enable cell merging (horizontal and vertical) by using RowConfig{AutoMerge: true} when appending rows or by configuring specific columns via SetColumnConfigs with ColumnConfig{AutoMerge: true}.

        rowConfigAutoMerge := table.RowConfig{AutoMerge: true}
    
        t := table.NewWriter()
        t.AppendHeader(table.Row{"Node IP", "Pods"}, rowConfigAutoMerge)
        t.AppendRow(table.Row{"1.1.1.1", "Pod 1A"}, rowConfigAutoMerge)
        t.AppendRow(table.Row{"1.1.1.1", "Pod 1B"}, rowConfigAutoMerge)
    
        t.SetColumnConfigs([]table.ColumnConfig{
            {Number: 1, AutoMerge: true},
            {Number: 2, AutoMerge: true},
        })
        fmt.Println(t.Render())