// Package termenv provides detect color support of the current terminal. // And with some utils for terminal env.
package termenv import ( ) var ( lastErr error // debug mode debugMode bool // support color of current terminal supportColor bool // value of os color render and display // // NOTICE: // if ENV: NO_COLOR is not empty, will disable color render. noColor = os.Getenv("NO_COLOR") != "" // the color support level for current terminal // needVTP - need enable VTP, only for Windows OS colorLevel, needVTP = detectTermColorLevel() ) // SetDebugMode sets debug mode. func ( bool) { debugMode = } // LastErr returns the last error. func () error { defer func() { lastErr = nil // reset on get }() return lastErr } func debugf( string, ...any) { if debugMode { fmt.Printf("TERMENV: "++"\n", ...) } } func setLastErr( error) { if != nil { debugf("TERMENV: last error: %v", ) lastErr = } } // exec: `stty -a 2>&1` // const ( // mac: speed 9600 baud; 97 rows; 362 columns; // macSttyMsgPattern = `(\d+)\s+rows;\s*(\d+)\s+columns;` // linux: speed 38400 baud; rows 97; columns 362; line = 0; // linuxSttyMsgPattern = `rows\s+(\d+);\s*columns\s+(\d+);` // ) var terminalWidth, terminalHeight int // GetTermSize for current console terminal. will first try to get from environment variables COLUMNS and LINES. func ( ...bool) ( int, int) { if terminalWidth > 0 && (len() == 0 || ![0]) { return terminalWidth, terminalHeight } // 首先尝试从环境变量获取 if := os.Getenv("COLUMNS"); != "" { if , := strconv.Atoi(); == nil && > 0 { terminalWidth = } } if := os.Getenv("LINES"); != "" { if , := strconv.Atoi(); == nil && > 0 { terminalHeight = } } if terminalWidth > 0 && terminalHeight > 0 { return terminalWidth, terminalHeight } var error , , = term.GetSize(syscallStdoutFd()) if != nil { debugf("get terminal size error: %v", ) return } // cache result terminalWidth, terminalHeight = , debugf("get terminal size: %d,%d", , ) return } // ReadPassword from console terminal func ( ...string) string { if len() > 0 { print([0]) } else { print("Enter Password: ") } , := term.ReadPassword(syscallStdinFd()) if != nil { return "" } println() // new line return string() }