...

Source file src/edge-infra.dev/pkg/sds/lib/colors/text.go

Documentation: edge-infra.dev/pkg/sds/lib/colors

     1  package colors
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/gleisonmv/colors"
     8  	"golang.org/x/term"
     9  )
    10  
    11  type Color int64
    12  
    13  const (
    14  	FgBlue Color = iota
    15  	FgBlueBold
    16  	FgRed
    17  	BgBlue
    18  	BgGreen
    19  	FgRedBold
    20  	BgRed
    21  	FgGreenBold
    22  	BgYellow
    23  	FgYellow
    24  	FgYellowBold
    25  	BgBrightBlack
    26  )
    27  
    28  // Text generates a string with args using sprintf and gleisonmv/colors.
    29  func Text(text string, color Color, args ...any) string {
    30  	if len(args) > 0 {
    31  		text = formatText(text, args...)
    32  	}
    33  	switch color {
    34  	case FgBlue:
    35  		return colors.Text(text).FgBlue().String()
    36  	case FgBlueBold:
    37  		return colors.Text(text).FgBlue().Bold().String()
    38  	case FgRed:
    39  		return colors.Text(text).FgRed().String()
    40  	case BgBlue:
    41  		return colors.Text(text).BgBlue().String()
    42  	case BgGreen:
    43  		return colors.Text(text).BgGreen().String()
    44  	case FgRedBold:
    45  		return colors.Text(text).FgRed().Bold().String()
    46  	case BgRed:
    47  		return colors.Text(text).BgRed().String()
    48  	case FgGreenBold:
    49  		return colors.Text(text).FgGreen().Bold().String()
    50  	case BgYellow:
    51  		return colors.Text(text).FgBlack().BgYellow().String()
    52  	case FgYellow:
    53  		return colors.Text(text).FgYellow().String()
    54  	case FgYellowBold:
    55  		return colors.Text(text).FgYellow().Bold().String()
    56  	case BgBrightBlack:
    57  		return colors.Text(text).BgBrightBlack().String()
    58  	}
    59  
    60  	return text
    61  }
    62  
    63  // BufferedText returns a colored string with length of terminal width buffered with spaces.
    64  func BufferedText(text string, color Color, args ...any) string {
    65  	if len(args) > 0 {
    66  		text = formatText(text, args...)
    67  	}
    68  
    69  	termWidth, _, err := term.GetSize(int(os.Stdout.Fd()))
    70  	if err != nil {
    71  		termWidth = len(text)
    72  	}
    73  
    74  	// Right pad text to width of terminal using spaces
    75  	text = fmt.Sprintf("%- *s", termWidth, text)
    76  
    77  	return Text(text, color)
    78  }
    79  
    80  func formatText(text string, args ...any) string {
    81  	return fmt.Sprintf(text, args...)
    82  }
    83  

View as plain text