LoginSignup
0
1

More than 5 years have passed since last update.

Go言語のtablewriterでWindowsのコマンドプロンプトに色付きのASCIIテーブルを出力する

Last updated at Posted at 2017-01-20

ちょっとしたツールを作ったときに、ちょっとだけ見やすく表示したい、みたいなことありますよね。

ポイントは以下の4点です。

  • Windowsの場合、mattn/go-colorableを一緒に使う
    • 使わないとANSIエスケープシーケンスが文字列でそのまま表示される
  • ヘッダ部分で色を付けるには、SetAutoFormatHeaders(false) を指定する
    • 指定しないとエスケープシーケンスの分だけテーブルが崩れ、色がつかない
  • ボディ部分の文字列に半角スペースを含む場合、SetAutoWrapText(false)を指定する
    • ASCIIエスケープシーケンス分長くなった分だけ折り返されてしまうので
  • Windowsのコマンドプロンプトで使う場合、文字用にはHiがついてる方を使う(e.g. color.FgHiRed)
    • color.FgRedだと暗くてちょっと見づらい(気がします)

サンプルです。

table.go
package main

import (
  "github.com/olekukonko/tablewriter"
  "github.com/fatih/color"
  "github.com/mattn/go-colorable"
)

func main() {
  fgRed := color.New(color.FgHiRed).SprintFunc()
  fgGreen := color.New(color.FgHiGreen).SprintFunc()
  fgYellow := color.New(color.FgHiYellow).SprintFunc()
  fgBlue := color.New(color.FgHiBlue).SprintFunc()
  fgMagenta := color.New(color.FgHiMagenta).SprintFunc()
  fgCyan := color.New(color.FgHiCyan).SprintFunc()
  fgWhite := color.New(color.FgHiWhite).SprintFunc()

  bgRed := color.New(color.BgRed).SprintFunc()
//  bgGreen := color.New(color.BgHiGreen).SprintFunc()
//  bgYellow := color.New(color.BgHiYellow).SprintFunc()
//  bgBlue := color.New(color.BgHiBlue).SprintFunc()
//  bgMagenta := color.New(color.BgHiMagenta).SprintFunc()
//  bgCyan := color.New(color.BgHiCyan).SprintFunc()
//  bgWhite := color.New(color.BgHiWhite).SprintFunc()

  table := tablewriter.NewWriter(colorable.NewColorableStdout())
  table.SetAutoFormatHeaders(false)
  table.SetAutoWrapText(false)

  table.SetHeader([]string{
    fgCyan("Title 1"), fgCyan("Title 2"), fgCyan("Title 3"),
  })

  text := fgGreen("foo") + fgYellow("bar") + fgBlue("baz")
  table.Append([]string{"foo", fgWhite("bar"), fgRed("baz")})
  table.Append([]string{ fgMagenta("foo"), bgRed(fgYellow("bar")), text})

  table.Render()
}

実行するとこんな感じになります。

無題.png

既にリクエスト出てるので、そのうち、もっとスマートにできるようになりそうですが…

Feature request: coloured output · Issue #37 · olekukonko/tablewriter

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1