github.com/10XDev/rclone@v1.52.3-0.20200626220027-16af9ab76b2a/lib/terminal/terminal.go (about) 1 // Package terminal provides VT100 terminal codes and a windows 2 // implementation of that. 3 package terminal 4 5 import ( 6 "io" 7 "os" 8 "runtime" 9 "sync" 10 11 colorable "github.com/mattn/go-colorable" 12 "golang.org/x/crypto/ssh/terminal" 13 ) 14 15 // VT100 codes 16 const ( 17 EraseLine = "\x1b[2K" 18 MoveToStartOfLine = "\x1b[1G" 19 MoveUp = "\x1b[1A" 20 21 Reset = "\x1b[0m" 22 Bright = "\x1b[1m" 23 Dim = "\x1b[2m" 24 Underscore = "\x1b[4m" 25 Blink = "\x1b[5m" 26 Reverse = "\x1b[7m" 27 Hidden = "\x1b[8m" 28 29 BlackFg = "\x1b[30m" 30 RedFg = "\x1b[31m" 31 GreenFg = "\x1b[32m" 32 YellowFg = "\x1b[33m" 33 BlueFg = "\x1b[34m" 34 MagentaFg = "\x1b[35m" 35 CyanFg = "\x1b[36m" 36 WhiteFg = "\x1b[37m" 37 38 BlackBg = "\x1b[40m" 39 RedBg = "\x1b[41m" 40 GreenBg = "\x1b[42m" 41 YellowBg = "\x1b[43m" 42 BlueBg = "\x1b[44m" 43 MagentaBg = "\x1b[45m" 44 CyanBg = "\x1b[46m" 45 WhiteBg = "\x1b[47m" 46 47 HiBlackFg = "\x1b[90m" 48 HiRedFg = "\x1b[91m" 49 HiGreenFg = "\x1b[92m" 50 HiYellowFg = "\x1b[93m" 51 HiBlueFg = "\x1b[94m" 52 HiMagentaFg = "\x1b[95m" 53 HiCyanFg = "\x1b[96m" 54 HiWhiteFg = "\x1b[97m" 55 56 HiBlackBg = "\x1b[100m" 57 HiRedBg = "\x1b[101m" 58 HiGreenBg = "\x1b[102m" 59 HiYellowBg = "\x1b[103m" 60 HiBlueBg = "\x1b[104m" 61 HiMagentaBg = "\x1b[105m" 62 HiCyanBg = "\x1b[106m" 63 HiWhiteBg = "\x1b[107m" 64 ) 65 66 var ( 67 // make sure that start is only called once 68 once sync.Once 69 ) 70 71 // Start the terminal - must be called before use 72 func Start() { 73 once.Do(func() { 74 f := os.Stdout 75 if !terminal.IsTerminal(int(f.Fd())) { 76 // If stdout not a tty then remove escape codes 77 Out = colorable.NewNonColorable(f) 78 } else if runtime.GOOS == "windows" && os.Getenv("TERM") != "" { 79 // If TERM is set just use stdout 80 Out = f 81 } else { 82 Out = colorable.NewColorable(f) 83 } 84 }) 85 } 86 87 // WriteString writes the string passed in to the terminal 88 func WriteString(s string) { 89 Write([]byte(s)) 90 } 91 92 // GetSize reads the dimensions of the current terminal or returns a 93 // sensible default 94 func GetSize() (w, h int) { 95 w, h, err := terminal.GetSize(int(os.Stdout.Fd())) 96 if err != nil { 97 w, h = 80, 25 98 } 99 return w, h 100 } 101 102 // Out is an io.Writer which can be used to write to the terminal 103 // eg for use with fmt.Fprintf(terminal.Out, "terminal fun: %d\n", n) 104 var Out io.Writer 105 106 // Write sends out to the VT100 terminal. 107 // It will initialise the terminal if this is the first call. 108 func Write(out []byte) { 109 Start() 110 _, _ = Out.Write(out) 111 }