github.com/graemephi/kahugo@v0.62.3-0.20211121071557-d78c0423784d/common/terminal/colors.go (about)

     1  // Copyright 2018 The Hugo Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  // Package terminal contains helper for the terminal, such as coloring output.
    15  package terminal
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  	"runtime"
    21  	"strings"
    22  
    23  	isatty "github.com/mattn/go-isatty"
    24  )
    25  
    26  const (
    27  	errorColor   = "\033[1;31m%s\033[0m"
    28  	warningColor = "\033[0;33m%s\033[0m"
    29  	noticeColor  = "\033[1;36m%s\033[0m"
    30  )
    31  
    32  // IsTerminal return true if the file descriptor is terminal and the TERM
    33  // environment variable isn't a dumb one.
    34  func IsTerminal(f *os.File) bool {
    35  	if runtime.GOOS == "windows" {
    36  		return false
    37  	}
    38  
    39  	fd := f.Fd()
    40  	return os.Getenv("TERM") != "dumb" && (isatty.IsTerminal(fd) || isatty.IsCygwinTerminal(fd))
    41  }
    42  
    43  // Notice colorizes the string in a noticeable color.
    44  func Notice(s string) string {
    45  	return colorize(s, noticeColor)
    46  }
    47  
    48  // Error colorizes the string in a colour that grabs attention.
    49  func Error(s string) string {
    50  	return colorize(s, errorColor)
    51  }
    52  
    53  // Warning colorizes the string in a colour that warns.
    54  func Warning(s string) string {
    55  	return colorize(s, warningColor)
    56  }
    57  
    58  // colorize s in color.
    59  func colorize(s, color string) string {
    60  	s = fmt.Sprintf(color, doublePercent(s))
    61  	return singlePercent(s)
    62  }
    63  
    64  func doublePercent(str string) string {
    65  	return strings.Replace(str, "%", "%%", -1)
    66  }
    67  
    68  func singlePercent(str string) string {
    69  	return strings.Replace(str, "%%", "%", -1)
    70  }