github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/yaml/cmd/ycat/ycat.go (about)

     1  package main
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"os"
     8  
     9  	"github.com/bingoohuang/gg/pkg/yaml"
    10  	"github.com/bingoohuang/gg/pkg/yaml/lexer"
    11  	"github.com/bingoohuang/gg/pkg/yaml/printer"
    12  	"github.com/fatih/color"
    13  	"github.com/mattn/go-colorable"
    14  )
    15  
    16  const escape = "\x1b"
    17  
    18  func format(attr color.Attribute) string {
    19  	return fmt.Sprintf("%s[%dm", escape, attr)
    20  }
    21  
    22  func _main(args []string) error {
    23  	if len(args) < 2 {
    24  		return errors.New("ycat: usage: ycat file.yml")
    25  	}
    26  	filename := args[1]
    27  	bytes, err := ioutil.ReadFile(filename)
    28  	if err != nil {
    29  		return err
    30  	}
    31  	tokens := lexer.Tokenize(string(bytes))
    32  	var p printer.Printer
    33  	p.LineNumber = true
    34  	p.LineNumberFormat = func(num int) string {
    35  		fn := color.New(color.Bold, color.FgHiWhite).SprintFunc()
    36  		return fn(fmt.Sprintf("%2d | ", num))
    37  	}
    38  	p.Bool = func() *printer.Property {
    39  		return &printer.Property{
    40  			Prefix: format(color.FgHiMagenta),
    41  			Suffix: format(color.Reset),
    42  		}
    43  	}
    44  	p.Number = func() *printer.Property {
    45  		return &printer.Property{
    46  			Prefix: format(color.FgHiMagenta),
    47  			Suffix: format(color.Reset),
    48  		}
    49  	}
    50  	p.MapKey = func() *printer.Property {
    51  		return &printer.Property{
    52  			Prefix: format(color.FgHiCyan),
    53  			Suffix: format(color.Reset),
    54  		}
    55  	}
    56  	p.Anchor = func() *printer.Property {
    57  		return &printer.Property{
    58  			Prefix: format(color.FgHiYellow),
    59  			Suffix: format(color.Reset),
    60  		}
    61  	}
    62  	p.Alias = func() *printer.Property {
    63  		return &printer.Property{
    64  			Prefix: format(color.FgHiYellow),
    65  			Suffix: format(color.Reset),
    66  		}
    67  	}
    68  	p.String = func() *printer.Property {
    69  		return &printer.Property{
    70  			Prefix: format(color.FgHiGreen),
    71  			Suffix: format(color.Reset),
    72  		}
    73  	}
    74  	writer := colorable.NewColorableStdout()
    75  	writer.Write([]byte(p.PrintTokens(tokens) + "\n"))
    76  	return nil
    77  }
    78  
    79  func main() {
    80  	if err := _main(os.Args); err != nil {
    81  		fmt.Printf("%v\n", yaml.FormatError(err, true, true))
    82  	}
    83  }