pax_global_header00006660000000000000000000000064143420016110014502gustar00rootroot0000000000000052 comment=e63436751a3d755c82efb46c10a28889192a0249 table-1.1.0/000077500000000000000000000000001434200161100125705ustar00rootroot00000000000000table-1.1.0/.github/000077500000000000000000000000001434200161100141305ustar00rootroot00000000000000table-1.1.0/.github/workflows/000077500000000000000000000000001434200161100161655ustar00rootroot00000000000000table-1.1.0/.github/workflows/codeql-analysis.yml000066400000000000000000000037171434200161100220100ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [master] pull_request: # The branches below must be a subset of the branches above branches: [master] schedule: - cron: '18 17 * * 6' jobs: analyze: name: Analyze runs-on: ubuntu-latest strategy: fail-fast: false matrix: # Override automatic language detection by changing the below list # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] language: ['go'] # Learn more... # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection steps: - name: Checkout repository uses: actions/checkout@v2 with: # We must fetch at least the immediate parents so that if this is # a pull request then we can checkout the head. fetch-depth: 2 # If this run was triggered by a pull request event, then checkout # the head of the pull request instead of the merge commit. - run: git checkout HEAD^2 if: ${{ github.event_name == 'pull_request' }} # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: languages: ${{ matrix.language }} # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v1 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 table-1.1.0/.github/workflows/go.yml000066400000000000000000000010201434200161100173060ustar00rootroot00000000000000name: Go on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: name: Build runs-on: ubuntu-latest steps: - name: Set up Go 1.x uses: actions/setup-go@v2 with: go-version: ^1.14 id: go - name: Check out code into the Go module directory uses: actions/checkout@v2 - name: Get dependencies run: go get -v -t -d ./... - name: Build run: go build -v ./... - name: Test run: go test -v -race -cover ./... table-1.1.0/go.mod000066400000000000000000000002551434200161100137000ustar00rootroot00000000000000module github.com/rodaine/table go 1.14 require ( github.com/google/go-cmp v0.5.9 // indirect github.com/mattn/go-runewidth v0.0.9 github.com/stretchr/testify v1.6.1 ) table-1.1.0/go.sum000066400000000000000000000025301434200161100137230ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0= github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= table-1.1.0/license000066400000000000000000000021211434200161100141310ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 Chris Roche (rodaine+github@gmail.com) 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. table-1.1.0/readme.md000066400000000000000000000037611434200161100143560ustar00rootroot00000000000000# table
[![GoDoc](https://godoc.org/github.com/rodaine/table?status.svg)](https://godoc.org/github.com/rodaine/table) [![Build Status](https://travis-ci.org/rodaine/table.svg)](https://travis-ci.org/rodaine/table) ![Example Table Output With ANSI Colors](http://res.cloudinary.com/rodaine/image/upload/v1442524799/go-table-example0.png) Package table provides a convenient way to generate tabular output of any data, primarily useful for CLI tools. ## Features - Accepts all data types (`string`, `int`, `interface{}`, everything!) and will use the `String() string` method of a type if available. - Can specify custom formatting for the header and first column cells for better readability. - Columns are left-aligned and sized to fit the data, with customizable padding. - The printed output can be sent to any `io.Writer`, defaulting to `os.Stdout`. - Built to an interface, so you can roll your own `Table` implementation. - Works well with ANSI colors ([fatih/color](https://github.com/fatih/color) in the example)! - Can provide a custom `WidthFunc` to accomodate multi- and zero-width characters (such as [runewidth](https://github.com/mattn/go-runewidth)) ## Usage **Download the package:** ```sh go get github.com/rodaine/table ``` **Example:** ```go package main import ( "fmt" "strings" "github.com/fatih/color" "github.com/rodaine/table" ) func main() { headerFmt := color.New(color.FgGreen, color.Underline).SprintfFunc() columnFmt := color.New(color.FgYellow).SprintfFunc() tbl := table.New("ID", "Name", "Score", "Added") tbl.WithHeaderFormatter(headerFmt).WithFirstColumnFormatter(columnFmt) for _, widget := range getWidgets() { tbl.AddRow(widget.ID, widget.Name, widget.Cost, widget.Added) } tbl.Print() } ``` _Consult the [documentation](https://godoc.org/github.com/rodaine/table) for further examples and usage information_ ## License table is released under the MIT License (Expat). See the [full license](https://github.com/rodaine/table/blob/master/license). table-1.1.0/table.go000066400000000000000000000205461434200161100142150ustar00rootroot00000000000000// Package table provides a convenient way to generate tabular output of any // data, primarily useful for CLI tools. // // Columns are left-aligned and padded to accomodate the largest cell in that // column. // // Source: https://github.com/rodaine/table // // table.DefaultHeaderFormatter = func(format string, vals ...interface{}) string { // return strings.ToUpper(fmt.Sprintf(format, vals...)) // } // // tbl := table.New("ID", "Name", "Cost ($)") // // for _, widget := range Widgets { // tbl.AddRow(widget.ID, widget.Name, widget.Cost) // } // // tbl.Print() // // // Output: // // ID NAME COST ($) // // 1 Foobar 1.23 // // 2 Fizzbuzz 4.56 // // 3 Gizmo 78.90 package table import ( "fmt" "io" "os" "strings" "unicode/utf8" ) // These are the default properties for all Tables created from this package // and can be modified. var ( // DefaultPadding specifies the number of spaces between columns in a table. DefaultPadding = 2 // DefaultWriter specifies the output io.Writer for the Table.Print method. DefaultWriter io.Writer = os.Stdout // DefaultHeaderFormatter specifies the default Formatter for the table header. DefaultHeaderFormatter Formatter // DefaultFirstColumnFormatter specifies the default Formatter for the first column cells. DefaultFirstColumnFormatter Formatter // DefaultWidthFunc specifies the default WidthFunc for calculating column widths DefaultWidthFunc WidthFunc = utf8.RuneCountInString ) // Formatter functions expose a fmt.Sprintf signature that can be used to modify // the display of the text in either the header or first column of a Table. // The formatter should not change the width of original text as printed since // column widths are calculated pre-formatting (though this issue can be mitigated // with increased padding). // // tbl.WithHeaderFormatter(func(format string, vals ...interface{}) string { // return strings.ToUpper(fmt.Sprintf(format, vals...)) // }) // // A good use case for formatters is to use ANSI escape codes to color the cells // for a nicer interface. The package color (https://github.com/fatih/color) makes // it easy to generate these automatically: http://godoc.org/github.com/fatih/color#Color.SprintfFunc type Formatter func(string, ...interface{}) string // A WidthFunc calculates the width of a string. By default, the number of runes // is used but this may not be appropriate for certain character sets. The // package runewidth (https://github.com/mattn/go-runewidth) could be used to // accomodate multi-cell characters (such as emoji or CJK characters). type WidthFunc func(string) int // Table describes the interface for building up a tabular representation of data. // It exposes fluent/chainable methods for convenient table building. // // WithHeaderFormatter and WithFirstColumnFormatter sets the Formatter for the // header and first column, respectively. If nil is passed in (the default), no // formatting will be applied. // // New("foo", "bar").WithFirstColumnFormatter(func(f string, v ...interface{}) string { // return strings.ToUpper(fmt.Sprintf(f, v...)) // }) // // WithPadding specifies the minimum padding between cells in a row and defaults // to DefaultPadding. Padding values less than or equal to zero apply no extra // padding between the columns. // // New("foo", "bar").WithPadding(3) // // WithWriter modifies the writer which Print outputs to, defaulting to DefaultWriter // when instantiated. If nil is passed, os.Stdout will be used. // // New("foo", "bar").WithWriter(os.Stderr) // // WithWidthFunc sets the function used to calculate the width of the string in // a column. By default, the number of utf8 runes in the string is used. // // AddRow adds another row of data to the table. Any values can be passed in and // will be output as its string representation as described in the fmt standard // package. Rows can have less cells than the total number of columns in the table; // subsequent cells will be rendered empty. Rows with more cells than the total // number of columns will be truncated. References to the data are not held, so // the passed in values can be modified without affecting the table's output. // // New("foo", "bar").AddRow("fizz", "buzz").AddRow(time.Now()).AddRow(1, 2, 3).Print() // // Output: // // foo bar // // fizz buzz // // 2006-01-02 15:04:05.0 -0700 MST // // 1 2 // // Print writes the string representation of the table to the provided writer. // Print can be called multiple times, even after subsequent mutations of the // provided data. The output is always preceded and followed by a new line. type Table interface { WithHeaderFormatter(f Formatter) Table WithFirstColumnFormatter(f Formatter) Table WithPadding(p int) Table WithWriter(w io.Writer) Table WithWidthFunc(f WidthFunc) Table AddRow(vals ...interface{}) Table SetRows(rows [][]string) Table Print() } // New creates a Table instance with the specified header(s) provided. The number // of columns is fixed at this point to len(columnHeaders) and the defined defaults // are set on the instance. func New(columnHeaders ...interface{}) Table { t := table{header: make([]string, len(columnHeaders))} t.WithPadding(DefaultPadding) t.WithWriter(DefaultWriter) t.WithHeaderFormatter(DefaultHeaderFormatter) t.WithFirstColumnFormatter(DefaultFirstColumnFormatter) t.WithWidthFunc(DefaultWidthFunc) for i, col := range columnHeaders { t.header[i] = fmt.Sprint(col) } return &t } type table struct { FirstColumnFormatter Formatter HeaderFormatter Formatter Padding int Writer io.Writer Width WidthFunc header []string rows [][]string widths []int } func (t *table) WithHeaderFormatter(f Formatter) Table { t.HeaderFormatter = f return t } func (t *table) WithFirstColumnFormatter(f Formatter) Table { t.FirstColumnFormatter = f return t } func (t *table) WithPadding(p int) Table { if p < 0 { p = 0 } t.Padding = p return t } func (t *table) WithWriter(w io.Writer) Table { if w == nil { w = os.Stdout } t.Writer = w return t } func (t *table) WithWidthFunc(f WidthFunc) Table { t.Width = f return t } func (t *table) AddRow(vals ...interface{}) Table { maxNumNewlines := 0 for _, val := range vals { maxNumNewlines = max(strings.Count(fmt.Sprint(val), "\n"), maxNumNewlines) } for i := 0; i <= maxNumNewlines; i++ { row := make([]string, len(t.header)) for j, val := range vals { if j >= len(t.header) { break } v := strings.Split(fmt.Sprint(val), "\n") row[j] = safeOffset(v, i) } t.rows = append(t.rows, row) } return t } func (t *table) SetRows(rows [][]string) Table { t.rows = [][]string{} headerLength := len(t.header) for _, row := range rows { if len(row) > headerLength { t.rows = append(t.rows, row[:headerLength]) } else { t.rows = append(t.rows, row) } } return t } func (t *table) Print() { format := strings.Repeat("%s", len(t.header)) + "\n" t.calculateWidths() t.printHeader(format) for _, row := range t.rows { t.printRow(format, row) } } func (t *table) printHeader(format string) { vals := t.applyWidths(t.header, t.widths) if t.HeaderFormatter != nil { txt := t.HeaderFormatter(format, vals...) fmt.Fprint(t.Writer, txt) } else { fmt.Fprintf(t.Writer, format, vals...) } } func (t *table) printRow(format string, row []string) { vals := t.applyWidths(row, t.widths) if t.FirstColumnFormatter != nil { vals[0] = t.FirstColumnFormatter("%s", vals[0]) } fmt.Fprintf(t.Writer, format, vals...) } func (t *table) calculateWidths() { t.widths = make([]int, len(t.header)) for _, row := range t.rows { for i, v := range row { if w := t.Width(v) + t.Padding; w > t.widths[i] { t.widths[i] = w } } } for i, v := range t.header { if w := t.Width(v) + t.Padding; w > t.widths[i] { t.widths[i] = w } } } func (t *table) applyWidths(row []string, widths []int) []interface{} { out := make([]interface{}, len(row)) for i, s := range row { out[i] = s + t.lenOffset(s, widths[i]) } return out } func (t *table) lenOffset(s string, w int) string { l := w - t.Width(s) if l <= 0 { return "" } return strings.Repeat(" ", l) } func max(i1, i2 int) int { if i1 > i2 { return i1 } return i2 } func safeOffset(sarr []string, idx int) string { if idx >= len(sarr) { return "" } return sarr[idx] } table-1.1.0/table_test.go000066400000000000000000000133131434200161100152460ustar00rootroot00000000000000package table import ( "bytes" "fmt" "io/ioutil" "os" "strings" "testing" "github.com/google/go-cmp/cmp" "github.com/mattn/go-runewidth" "github.com/stretchr/testify/assert" ) func TestFormatter(t *testing.T) { t.Parallel() var formatter Formatter fn := func(a string, b ...interface{}) string { return "" } f := Formatter(fn) assert.IsType(t, formatter, f) } func TestTable_New(t *testing.T) { t.Parallel() buf := bytes.Buffer{} New("foo", "bar").WithWriter(&buf).Print() out := buf.String() assert.Contains(t, out, "foo") assert.Contains(t, out, "bar") buf.Reset() New().WithWriter(&buf).Print() out = buf.String() assert.Empty(t, strings.TrimSpace(out)) } func TestTable_WithHeaderFormatter(t *testing.T) { t.Parallel() uppercase := func(f string, v ...interface{}) string { return strings.ToUpper(fmt.Sprintf(f, v...)) } buf := bytes.Buffer{} tbl := New("foo", "bar").WithWriter(&buf).WithHeaderFormatter(uppercase) tbl.Print() out := buf.String() assert.Contains(t, out, "FOO") assert.Contains(t, out, "BAR") buf.Reset() tbl.WithHeaderFormatter(nil).Print() out = buf.String() assert.Contains(t, out, "foo") assert.Contains(t, out, "bar") } func TestTable_WithFirstColumnFormatter(t *testing.T) { t.Parallel() uppercase := func(f string, v ...interface{}) string { return strings.ToUpper(fmt.Sprintf(f, v...)) } buf := bytes.Buffer{} tbl := New("foo", "bar").WithWriter(&buf).WithFirstColumnFormatter(uppercase).AddRow("fizz", "buzz") tbl.Print() out := buf.String() assert.Contains(t, out, "foo") assert.Contains(t, out, "bar") assert.Contains(t, out, "FIZZ") assert.Contains(t, out, "buzz") buf.Reset() tbl.WithFirstColumnFormatter(nil).Print() out = buf.String() assert.Contains(t, out, "fizz") assert.Contains(t, out, "buzz") } func TestTable_WithPadding(t *testing.T) { t.Parallel() // zero value buf := bytes.Buffer{} tbl := New("foo", "bar").WithWriter(&buf).WithPadding(0) tbl.Print() out := buf.String() assert.Contains(t, out, "foobar") // positive value buf.Reset() tbl.WithPadding(4).Print() out = buf.String() assert.Contains(t, out, "foo bar ") // negative value buf.Reset() tbl.WithPadding(-1).Print() out = buf.String() assert.Contains(t, out, "foobar") } func TestTable_WithWriter(t *testing.T) { t.Parallel() // not that we haven't been using it in all these tests but: buf := bytes.Buffer{} New("foo", "bar").WithWriter(&buf).Print() assert.NotEmpty(t, buf.String()) stdout := os.Stdout temp, _ := ioutil.TempFile("", "") os.Stdout = temp defer func() { os.Stdout = stdout temp.Close() }() New("foo", "bar").WithWriter(nil).Print() temp.Seek(0, 0) out, _ := ioutil.ReadAll(temp) assert.NotEmpty(t, out) } func TestTable_AddRow(t *testing.T) { t.Parallel() buf := bytes.Buffer{} tbl := New("foo", "bar").WithWriter(&buf).AddRow("fizz", "buzz") tbl.Print() out := buf.String() assert.Contains(t, out, "fizz") assert.Contains(t, out, "buzz") lines := strings.Count(out, "\n") // empty should add empty line buf.Reset() tbl.AddRow().Print() assert.Equal(t, lines+1, strings.Count(buf.String(), "\n")) // less than one will fill left-to-right buf.Reset() tbl.AddRow("cat").Print() assert.Contains(t, buf.String(), "\ncat") // more than initial length are truncated buf.Reset() tbl.AddRow("bippity", "boppity", "boo").Print() assert.NotContains(t, buf.String(), "boo") // check the full table buf.Reset() tbl.Print() expected := `foo bar fizz buzz cat bippity boppity ` if diff := cmp.Diff(expected, buf.String()); diff != "" { t.Fatalf("table mismatch (-expected +got):\n%s\nout=%#v", diff, buf.String()) } } func TestTable_AddRow_WithNewLines(t *testing.T) { t.Parallel() buf := bytes.Buffer{} tbl := New("foo", "bar").WithWriter(&buf).AddRow("fizz", "buzz") // Add some rows tbl.AddRow() tbl.AddRow("cat") // add an entry that contains new lines tbl.AddRow("bippity", "boppity\nboop") // Add a couple more rows tbl.AddRow("a", "b") tbl.AddRow("c", "d") // and another entry with more new lines tbl.AddRow("1\n2", "x\ny\nz") // check the full table buf.Reset() tbl.Print() expected := `foo bar fizz buzz cat bippity boppity boop a b c d 1 x 2 y z ` if diff := cmp.Diff(expected, buf.String()); diff != "" { t.Fatalf("table mismatch (-expected +got):\n%s\nout=%#v", diff, buf.String()) } } func TestTable_SetRows(t *testing.T) { t.Parallel() buf := bytes.Buffer{} tbl := New("foo", "bar").WithWriter(&buf).SetRows([][]string{ {"fizz", "buzz"}, {"lorem", "ipsum"}, }) tbl.Print() out := buf.String() assert.Contains(t, out, "fizz") assert.Contains(t, out, "buzz") assert.Contains(t, out, "lorem") assert.Contains(t, out, "ipsum") assert.Equal(t, 3, strings.Count(out, "\n")) // empty should remove all rows buf.Reset() tbl.SetRows([][]string{}).Print() assert.Equal(t, 1, strings.Count(buf.String(), "\n")) // less than one will fill left-to-right buf.Reset() tbl.SetRows([][]string{{"cat"}}).Print() assert.Contains(t, buf.String(), "\ncat") // more than initial length are truncated buf.Reset() tbl.SetRows([][]string{ {"lorem", "ipsum"}, {"bippity", "boppity", "boo"}, }).Print() assert.NotContains(t, buf.String(), "boo") } func TestTable_WithWidthFunc(t *testing.T) { t.Parallel() buf := bytes.Buffer{} New("", ""). WithWriter(&buf). WithPadding(1). WithWidthFunc(runewidth.StringWidth). AddRow("请求", "alpha"). AddRow("abc", "beta"). Print() actual := buf.String() assert.Contains(t, actual, "请求 alpha") assert.Contains(t, actual, "abc beta") }