فهرست منبع

Add a generic `NewColorable()` constructor

The generic constructor accepts any `os.File` pointer. This is useful
when this library is used to support a generic colorable writer stream
whose destination (stdout, stderr, log file, etc.) is determined
dynamically at runtime.
Mislav Marohnić 10 سال پیش
والد
کامیت
22ddf55578
2فایلهای تغییر یافته به همراه17 افزوده شده و 16 حذف شده
  1. 4 0
      colorable_others.go
  2. 13 16
      colorable_windows.go

+ 4 - 0
colorable_others.go

@@ -7,6 +7,10 @@ import (
 	"os"
 )
 
+func NewColorable(file *os.File) io.Writer {
+	return file
+}
+
 func NewColorableStdout() io.Writer {
 	return os.Stdout
 }

+ 13 - 16
colorable_windows.go

@@ -68,26 +68,23 @@ type Writer struct {
 	oldattr word
 }
 
-func NewColorableStdout() io.Writer {
-	var csbi consoleScreenBufferInfo
-	out := os.Stdout
-	if !isatty.IsTerminal(out.Fd()) {
-		return out
+func NewColorable(file *os.File) io.Writer {
+	if isatty.IsTerminal(file.Fd()) {
+		var csbi consoleScreenBufferInfo
+		handle := syscall.Handle(file.Fd())
+		procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
+		return &Writer{out: file, handle: handle, oldattr: csbi.attributes}
+	} else {
+		return file
 	}
-	handle := syscall.Handle(out.Fd())
-	procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
-	return &Writer{out: out, handle: handle, oldattr: csbi.attributes}
+}
+
+func NewColorableStdout() io.Writer {
+	return NewColorable(os.Stdout)
 }
 
 func NewColorableStderr() io.Writer {
-	var csbi consoleScreenBufferInfo
-	out := os.Stderr
-	if !isatty.IsTerminal(out.Fd()) {
-		return out
-	}
-	handle := syscall.Handle(out.Fd())
-	procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))
-	return &Writer{out: out, handle: handle, oldattr: csbi.attributes}
+	return NewColorable(os.Stderr)
 }
 
 var color256 = map[int]int{