Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get colors to work with golang tabwriter?

Tags:

go

I am using the tabwriter and I cannot get it to work with colors. I am using the "github.com/fatih/color" package.

Basically the problem is that I need to call tabwriter's w.Flush() in order to get the colors to render... I cannot switch colors if I have not called a flush.

Calling Flush in turn screws with the tabwriter formatting.

Any ideas on how to combine the two?

    package main

    import "fmt"
    import "text/tabwriter"
    import "os"
    import "github.com/fatih/color"

    func main() {
        w := new(tabwriter.Writer)
        w.Init(os.Stderr, 0, 8, 0, '\t', 0)
        color.Set(color.FgGreen)
        fmt.Fprintln(w, "ID\tNAME\tSIZE\tFIELD1\tSTATUS\tSTATE")
        // ------> Calling w.Flush() here cases problems.
        color.Set(color.FgYellow)
        fmt.Fprintln(w, "8617833164795356724\tfoo1\t1.1 Gb\t3\tsome_status\tsome_state")
        fmt.Fprintln(w) 
        w.Flush()
    }
like image 600
steve landiss Avatar asked Feb 14 '16 21:02

steve landiss


2 Answers

Despite what the accepted answer says, it is possible, you just have to be very careful about field length.

Wrap each "field" (i.e. a specific row and column) with a color+reset code. If all codes are of the same string length, tabwriter will give you a good result.

I have a crude demonstration here: https://play.golang.org/p/r6GNeV1gbH

enter image description here

I didn't do so in my demo, but you should also add the background codes as well (you can simply add them together as in RedText + YellowBackground), providing a default background. In this way, everything will be of equal length and you'll have background support as well.

Please note that I am a beginner Go programmer. I don't claim that my code is any good.

like image 122
Dave Avatar answered Nov 17 '22 14:11

Dave


Short answer

You can't.

Naive answer

Use the color.Color.SprintFunc() method to get a function and wrap your strigns using this function.

Real answer

That won't work either, because the color is set using a special character sequence that isn't recognized by the tabwriter, so this row will be shorter by the length of twice the marker (one to set the color and one to get back to the standard color).

Solution

Write an alternative tabwriter (the algoerithm isn't even complex) that recognized the color character sequence and ignore it.

like image 40
Elwinar Avatar answered Nov 17 '22 13:11

Elwinar