Simple tables in terminal with Go

Overview

Simple tables in terminal with Go

Travis Coverage Status Go Report Card GoDoc

This package allows to generate and display ascii tables in the terminal, f.e.:

+----+------------------+--------------+-----------------------------+------+
| #  |       NAME       |    PHONE     |            EMAIL            | QTTY |
+----+------------------+--------------+-----------------------------+------+
|  1 | Newton G. Goetz  | 252-585-5166 | [email protected]     |   10 |
|  2 | Rebecca R. Edney | 865-475-4171 | [email protected]   |   12 |
|  3 | John R. Jackson  | 810-325-1417 | [email protected]    |   15 |
|  4 | Ron J. Gomes     | 217-450-8568 | [email protected]         |   25 |
|  5 | Penny R. Lewis   | 870-794-1666 | [email protected]       |    5 |
|  6 | Sofia J. Smith   | 770-333-7379 | [email protected]     |    3 |
|  7 | Karlene D. Owen  | 231-242-4157 | [email protected] |   12 |
|  8 | Daniel L. Love   | 978-210-4178 | [email protected]       |   44 |
|  9 | Julie T. Dial    | 719-966-5354 | [email protected]   |    8 |
| 10 | Juan J. Kennedy  | 908-910-8893 | [email protected]     |   16 |
+----+------------------+--------------+-----------------------------+------+
|                                                           Subtotal |  150 |
+----+------------------+--------------+-----------------------------+------+

There are the following key features:

  • Declarative style. Have to write more code, and hell with it.
  • Styling. With 7 predefined styles: MySql-like (default), compact, compact lite, compact classic, markdown, rounded and unicode. And you can change it.
  • Header and footer. Separated from table body.
  • Multiline cells support. See _example/main.go/_example/04-multiline/main.go for example.
  • Cell content alignment. Left, right or center.
  • Row spanning. By analogy with the way it is done in HTML. See Cell.Span attribute description.
  • Fast! Really fast, see _example/main.go/_example/03-benchmarks-with-others.

Installation

$ go get -u github.com/alexeyco/simpletable

To run unit tests:

$ cd $GOPATH/src/github.com/alexeyco/simpletable
$ go test -cover

To run benchmarks:

$ cd $GOPATH/src/github.com/alexeyco/simpletable
$ go test -bench=.

Comparison with similar libraries see _example/main.go/_example/03-benchmarks-with-others

Basic example

package main

import (
	"fmt"

	"github.com/alexeyco/simpletable"
)

var (
	data = [][]interface{}{
		{1, "Newton G. Goetz", 532.7},
		{2, "Rebecca R. Edney", 1423.25},
		{3, "John R. Jackson", 7526.12},
		{4, "Ron J. Gomes", 123.84},
		{5, "Penny R. Lewis", 3221.11},
	}
)

func main() {
	table := simpletable.New()

	table.Header = &simpletable.Header{
		Cells: []*simpletable.Cell{
			{Align: simpletable.AlignCenter, Text: "#"},
			{Align: simpletable.AlignCenter, Text: "NAME"},
			{Align: simpletable.AlignCenter, Text: "TAX"},
		},
	}

	subtotal := float64(0)
	for _, row := range data {
		r := []*simpletable.Cell{
			{Align: simpletable.AlignRight, Text: fmt.Sprintf("%d", row[0].(int))},
			{Text: row[1].(string)},
			{Align: simpletable.AlignRight, Text: fmt.Sprintf("$ %.2f", row[2].(float64))},
		}

		table.Body.Cells = append(table.Body.Cells, r)
		subtotal += row[2].(float64)
	}

	table.Footer = &simpletable.Footer{
		Cells: []*simpletable.Cell{
			{},
			{Align: simpletable.AlignRight, Text: "Subtotal"},
			{Align: simpletable.AlignRight, Text: fmt.Sprintf("$ %.2f", subtotal)},
		},
	}

	table.SetStyle(simpletable.StyleCompactLite)
	fmt.Println(table.String())
}

Result:

 #         NAME            TAX
--- ------------------ ------------
 1   Newton G. Goetz      $ 532.70
 2   Rebecca R. Edney    $ 1423.25
 3   John R. Jackson     $ 7526.12
 4   Ron J. Gomes         $ 123.84
 5   Penny R. Lewis      $ 3221.11
--- ------------------ ------------
             Subtotal   $ 12827.02

You can see also _example/main.go/01-styles-demo/main.go for styles demonstration.

$ cd $GOPATH/src/github.com/alexeyco/simpletable/_example/01-styles-demo
$ go run main.go

More examples: For more examples see _example directory:

$ cd $GOPATH/src/github.com/alexeyco/simpletable/_example
$ ls -F | grep /

01-styles-demo/
02-ugly-span/
03-benchmarks-with-others/
04-multiline/

Styling

There is 6 styles available. To view them, run _example/main.go/01-styles-demo/main.go:

$ cd $GOPATH/src/github.com/alexeyco/simpletable/_example/01-styles-demo
$ go run main.go

Cell content alignment

You can set cell content alignment:

c := &simpletable.Cell{
	// or simpletable.AlignLeft (default), or simpletable.AlignCenter
	Align:   simpletable.AlignRight, 
	Content: "Subtotal",
}

Column spanning

By analogy with HTML:

c := &simpletable.Cell{
	Span:    2, // Default: 1
	Content: "Subtotal",
}

Note: by default Span is 1. If you try to set it to 0, the value will still be 1.

License

Copyright (c) 2017 Alexey Popov

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Issues
  • can you support chinese?

    can you support chinese?

    Hello, I found this a very useful tool, but can you support Chinese, because if the table content is Chinese and the table cannot be aligned, I try to modify the realLength function in content.go and change utf8.RuneCountInString to len, but it no effect

    opened by crusj 3
  • Fix alignment issue for unicode

    Fix alignment issue for unicode

    Fix #6.

    For CJK characters, when displayed in terminal, they take more that one position. For whatever reason, what is returned by utf8.RuneCountInString is not expected.

    this patch uses https://github.com/mattn/go-runewidth to get the correct content length of the cell. see https://play.golang.org/p/2xDzwKjK7H8

    opened by woosley 2
  • Strip ansi escape sequences before calculating cells

    Strip ansi escape sequences before calculating cells

    Thanks for the package!

    Might be nice to strip ansi escape sequences with something like this hack, so that the cells are still calculated properly allowing colors etc.

    opened by tj 2
  • Add CompactClassic style

    Add CompactClassic style

    Simple but powerful wheels. The only regret is that there is always a divider line between header(footer) and body even with customized style.

    This PR fix the problem and add a predefined style called CompactClassic which do not have separator line between header and body. Inspired by kubectl

    table := st.New()
    table.Header = &st.Header{
        Cells: []*st.Cell{
            {Text: "UUID", Align: st.AlignLeft},
            {Text: "NAME", Align: st.AlignLeft},
            ...
        },
    }
    
    table.Body.Cells = ...
    
    // no footer
    
    table.SetStyle(st.StyleCompactClassic)
    fmt.Println(table.String())
    

    Will output

    UUID                                   NAME         NAMESPACE    STATUS
    1aaf112f-c398-4fe8-a25b-638da8df372c   myname       my-ns        Ready
    

    Very common table output style for various terminal applications.

    opened by povsister 1
  • Make table.Body sortable

    Make table.Body sortable

    This PR implements the sort interface for table.Body

    You can call table.Body.SortByField(index) to sort Body.Cells by given field index using lexical order. or you can call table.Body.SortByFieldWithFunc(index, LessFunc) to sort Cells by given field index using your own LessFunc implementation.

    opened by povsister 0
  • unknown field 'Content' in struct literal of type simpletable.Cell when trying out example

    unknown field 'Content' in struct literal of type simpletable.Cell when trying out example

    Hi, when I try the example on Go 1.9.4, it returns these errors: image

    (unknown field 'Content' in struct literal of type simpletable.Cell)

    EDIT: in the image, I tried changing Content to content on line 24, 25, and 26, this is why it's lowercase there

    opened by elisaado 0
  • Is Span supported in the header?

    Is Span supported in the header?

    Hey Alex,

    Thanks for this great library.

    I am having an issue adding Span to the header. Any idea what I am doing wrong? I posted the error and code below.

    Regards, Maruf

    Error:

    /usr/local/Cellar/go/1.15.5/libexec/bin/go build -o /private/var/folders/wh/fnt_yh0n5mxfmttpjts9l9jc0000gp/T/___go_build_main_go__2_ /Users/m0a00v4/go/src/github.com/simpletable/_example/05-colorize/main.go #gosetup
    /private/var/folders/wh/fnt_yh0n5mxfmttpjts9l9jc0000gp/T/___go_build_main_go__2_
    panic: runtime error: invalid memory address or nil pointer dereference
    [signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x10d2ca9]
    
    goroutine 1 [running]:
    github.com/alexeyco/simpletable.(*Table).prepareColumns(0xc0000de000)
            /Users/m0a00v4/go/src/github.com/alexeyco/simpletable/table.go:257 +0xb69
    github.com/alexeyco/simpletable.(*Table).String(0xc0000de000, 0xc000092b60, 0xc0000ac040)
            /Users/m0a00v4/go/src/github.com/alexeyco/simpletable/table.go:34 +0xdc
    github.com/alexeyco/simpletable.(*Table).Println(0xc0000de000)
            /Users/m0a00v4/go/src/github.com/alexeyco/simpletable/table.go:65 +0x2f
    main.main()
            /Users/m0a00v4/go/src/github.com/simpletable/_example/05-colorize/main.go:47 +0x97f
    
    Process finished with exit code 2
    

    Code:

    func main() {
    	table := simpletable.New()
    
    	table.Header = &simpletable.Header{
    		Cells: []*simpletable.Cell{
    			{Align: simpletable.AlignCenter, Text: "FOO"},
    			{Align: simpletable.AlignCenter, Text: "BAZ"},
    			{Align: simpletable.AlignRight, Span: 2, Text: "BAR"},
    		},
    	}
    
    	table.Body = &simpletable.Body{
    		Cells: [][]*simpletable.Cell{
    			{
    				&simpletable.Cell{Text: red("I am red")},
    				&simpletable.Cell{Text: green("I am green")},
    				&simpletable.Cell{Text: blue("I am blue")},
    				&simpletable.Cell{Text: blue("I am blue 2")},
    
    			},
    		},
    	}
    
    	table.Footer = &simpletable.Footer{
    		Cells: []*simpletable.Cell{
    			{Align: simpletable.AlignCenter, Span: 4, Text: gray("And all columns is well sized")},
    		},
    	}
    
    	table.Println()
    } 
    
    opened by marufaytekin 1
Owner
Alexey Popov
Alexey Popov
✨ #PTerm is a modern go module to beautify console output. Featuring charts, progressbars, tables, trees, and many more 🚀 It's completely configurable and 100% cross-platform compatible.

?? PTerm | Pretty Terminal Printer A golang module to print pretty text Show Demo Code PTerm.sh | Installation | Documentation | Quick Start | Example

null 2.6k Jun 21, 2022
Tabular simplifies printing ASCII tables from command line utilities

tabular Tabular simplifies printing ASCII tables from command line utilities without the need to pass large sets of data to it's API. Simply define th

InVision 63 May 26, 2022
Intuitive package for prettifying terminal/console output. http://godoc.org/github.com/ttacon/chalk

chalk Chalk is a go package for styling console/terminal output. Check out godoc for some example usage: http://godoc.org/github.com/ttacon/chalk The

Trey Tacon 396 Jun 15, 2022
An ANSI colour terminal package for Go

colourize An ANSI colour terminal package for Go. Supports all ANSI colours and emphasis. Not compatible with Windows systems. Installation go get gi

Trey Bastian 25 Mar 8, 2022
Console Text Colors - The non-invasive cross-platform terminal color library does not need to modify the Print method

ctc - Console Text Colors The non-invasive cross-platform terminal color library does not need to modify the Print method Virtual unix-like environmen

null 37 Dec 15, 2021
Terminal based dashboard.

Termdash is a cross-platform customizable terminal based dashboard. The feature set is inspired by the gizak/termui project, which in turn was inspire

Jakub Sobon 2k Jun 21, 2022
Golang terminal dashboard

termui termui is a cross-platform and fully-customizable terminal dashboard and widget library built on top of termbox-go. It is inspired by blessed-c

Zack Guo 11.9k Jun 26, 2022
uilive is a go library for updating terminal output in realtime

uilive uilive is a go library for updating terminal output in realtime. It provides a buffered io.Writer that is flushed at a timed interval. uilive p

Greg Osuri 1.5k Jun 20, 2022
A go library to render progress bars in terminal applications

uiprogress A Go library to render progress bars in terminal applications. It provides a set of flexible features with a customizable API. Progress bar

Greg Osuri 1.9k Jun 23, 2022
A go library to improve readability in terminal apps using tabular data

uitable uitable is a go library for representing data as tables for terminal applications. It provides primitives for sizing and wrapping columns to i

Greg Osuri 650 Jun 10, 2022
Yet Another CLi Spinner; providing over 70 easy to use and customizable terminal spinners for multiple OSes

Yet Another CLi Spinner (for Go) Package yacspin provides yet another CLi spinner for Go, taking inspiration (and some utility code) from the https://

Tim Heckman 345 Jun 19, 2022
Terminal string styling for go done right, with full and painless Windows 10 support.

GChalk GChalk is a library heavily inspired by chalk, the popular Node.js terminal color library, and using go ports of supports-color and ansi-styles

Jason Walton 302 Jun 20, 2022
Small library for simple and convenient formatted stylized output to the console.

cfmt cfmt is a small library for simple and convenient formatted stylized output to the console, providing an interface that is exactly the same as th

Makhnev Petr 42 Jun 23, 2022
A tiny library for super simple Golang tables

Tabby A tiny library for super simple Golang tables Get Tabby go get github.com/cheynewallace/tabby Import Tabby import "github.com/cheynewallace/tabb

Cheyne Wallace 318 Jun 22, 2022
✨ #PTerm is a modern go module to beautify console output. Featuring charts, progressbars, tables, trees, and many more 🚀 It's completely configurable and 100% cross-platform compatible.

?? PTerm | Pretty Terminal Printer A golang module to print pretty text Show Demo Code PTerm.sh | Installation | Documentation | Quick Start | Example

null 2.6k Jun 21, 2022
Tabular simplifies printing ASCII tables from command line utilities

tabular Tabular simplifies printing ASCII tables from command line utilities without the need to pass large sets of data to it's API. Simply define th

InVision 63 May 26, 2022
Fast, realtime regex-extraction, and aggregation into common formats such as histograms, numerical summaries, tables, and more!

rare A file scanner/regex extractor and realtime summarizor. Supports various CLI-based graphing and metric formats (histogram, table, etc). Features

Chris LaPointe 151 Jun 16, 2022
Utilities to prettify console output of tables, lists, progress-bars, text, etc.

go-pretty Utilities to prettify console output of tables, lists, progress-bars, text, etc. Table Pretty-print tables into ASCII/Unicode strings.

Naveen Mahalingam 1.3k Jun 20, 2022
Generate PlantUML ER diagram textual description from PostgreSQL tables

Generate PlantUML ER diagram textual description from PostgreSQL tables

Akira Chiku 463 Jun 21, 2022
The utility that created for easily database and their tables rolling up

The utility that created for easily database and their tables rolling up

null 0 Nov 6, 2021
CloudQuery extracts, transforms, and loads your cloud assets into normalized PostgreSQL tables.

The open-source cloud asset inventory backed by SQL. CloudQuery extracts, transforms, and loads your cloud assets into normalized PostgreSQL tables. C

CloudQuery 2.3k Jun 21, 2022
A CLI tool which loads data from yaml files into the Google Cloud Spanner tables

splanter A CLI tool which loads data from yaml files into the Google Cloud Spanner tables (mainly for the development).

Yuki Ito 6 Jun 20, 2022
RecordLite: a library (and executable) that declaratively maintains SQLite tables and views of semi-structured data

RecordLite RecordLite is a library (and executable) that declaratively maintains

François Saint-Jacques 22 May 29, 2022
Create Mermaid-Js ERD diagrams from existing tables

Mermerd Create Mermaid-Js ERD diagrams from existing tables. Features Supports PostgreSQL and MySQL Select from available schemas Select only the tabl

null 55 Jun 16, 2022
Genpc - Discord bot for automating Numenera (and eventually other system) tables

GenPC Discord bot for automating Numenera (and eventually other system) tables.

Maxwell Banks 0 Feb 16, 2022
RbacCustom - Create Tables Before executing the APIs

rbacCas Create Tables Before executing the APIs Members Table CREATE TABLE publi

Akash Desale 0 Feb 8, 2022
Metrics dashboards on terminal (a grafana inspired terminal version)

Grafterm Visualize metrics dashboards on the terminal, like a simplified and minimalist version of Grafana for terminal. Features Multiple widgets (gr

Xabier Larrakoetxea Gallego 763 Jun 24, 2022
Stonks is a terminal based stock visualizer and tracker that displays realtime stocks in graph format in a terminal.

Stonks is a terminal based stock visualizer and tracker. Installation Requirements: golang >= 1.13 Manual Clone the repo Run make && make install Pack

Eric Moynihan 510 Jun 21, 2022