77 "fmt"
88 "io"
99 "io/ioutil"
10+ "math"
1011 "net/http"
1112 "os"
1213 "regexp"
@@ -24,6 +25,7 @@ import (
2425 "github.com/cli/cli/pkg/cmdutil"
2526 "github.com/cli/cli/pkg/iostreams"
2627 "github.com/cli/cli/pkg/jsoncolor"
28+ "github.com/mgutz/ansi"
2729 "github.com/spf13/cobra"
2830)
2931
@@ -320,8 +322,31 @@ func processResponse(resp *http.Response, opts *ApiOptions, headersOutputStream
320322 }
321323
322324 if opts .Template != "" {
325+ templateFuncs := map [string ]interface {}{
326+ "color" : func (colorName string , input interface {}) (string , error ) {
327+ var text string
328+ switch tt := input .(type ) {
329+ case string :
330+ text = tt
331+ case float64 :
332+ if math .Trunc (tt ) == tt {
333+ text = strconv .FormatFloat (tt , 'f' , 0 , 64 )
334+ } else {
335+ text = strconv .FormatFloat (tt , 'f' , 2 , 64 )
336+ }
337+ case nil :
338+ text = ""
339+ case bool :
340+ text = fmt .Sprintf ("%v" , tt )
341+ default :
342+ return "" , fmt .Errorf ("cannot convert type to string: %v" , tt )
343+ }
344+ return ansi .Color (text , colorName ), nil
345+ },
346+ }
347+
323348 // TODO: reuse parsed template across pagination invocations
324- t := template .Must (template .New ("" ).Parse (opts .Template ))
349+ t := template .Must (template .New ("" ).Funcs ( templateFuncs ). Parse (opts .Template ))
325350
326351 var jsonData []byte
327352 jsonData , err = ioutil .ReadAll (responseBody )
0 commit comments