github.com/MichaelDarr/ahab@v0.0.0-20200528062404-c74c5106e605/pkg/print.go (about)

     1  package internal
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"strings"
     8  )
     9  
    10  // PrintCmd prints a single command to the console
    11  func PrintCmd(cmd *exec.Cmd) {
    12  	StylePrint("cyan", "$ "+strings.Join(cmd.Args, " "))
    13  }
    14  
    15  // PrintErr prints an error to the console (if non-nil)
    16  func PrintErr(err error) {
    17  	if errStr := err.Error(); errStr != "" {
    18  		StylePrint("red", errStr)
    19  	}
    20  }
    21  
    22  // PrintErrStr prints an error string to the console
    23  func PrintErrStr(errStr string) {
    24  	StylePrint("red", errStr)
    25  }
    26  
    27  // PrintErrFatal prints an error to the console and terminates the program (if non-nil)
    28  func PrintErrFatal(err error) {
    29  	if err != nil {
    30  		PrintErr(err)
    31  		os.Exit(1)
    32  	}
    33  }
    34  
    35  // PrintIndentedPair prints a key/val pair in a human-readable format
    36  func PrintIndentedPair(key string, val string) {
    37  	fmt.Printf("  %-12s%s\n", key, val)
    38  }
    39  
    40  // PrintWarning prints a warning string to the console
    41  func PrintWarning(warning string) {
    42  	StylePrint("yellow", warning)
    43  }
    44  
    45  // StylePrint prints a string after surrounding it with appropriate style tags
    46  func StylePrint(style string, str string) {
    47  	stylizedStr := stylize(style, str)
    48  	fmt.Println(stylizedStr)
    49  }
    50  
    51  // console style code map
    52  var textCodes = map[string]string{
    53  	"blue":    "\x1b[34m",
    54  	"bold":    "\x1b[1m",
    55  	"cyan":    "\x1b[36m",
    56  	"green":   "\x1b[32m",
    57  	"magenta": "\x1b[35m",
    58  	"red":     "\x1b[31m",
    59  	"reset":   "\x1b[0m",
    60  	"yellow":  "\x1b[33m",
    61  }
    62  
    63  // appendToStrList is a helper for creating human-readable comma-separated lists
    64  func appendToStrList(list string, newEl string) (finalStr string) {
    65  	if list == "" {
    66  		return newEl
    67  	}
    68  	return list + ", " + newEl
    69  }
    70  
    71  // stylize surrounds a string with style codes
    72  func stylize(style string, str string) string {
    73  	if textCode, ok := textCodes[style]; ok {
    74  		return textCode + str + textCodes["reset"]
    75  	}
    76  	PrintWarning("Unsupported text style: " + style)
    77  	return str
    78  }