github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/log/console_windows.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package log
     7  
     8  import (
     9  	"os"
    10  
    11  	"github.com/mattn/go-isatty"
    12  	"golang.org/x/sys/windows"
    13  )
    14  
    15  func enableVTMode(console windows.Handle) bool {
    16  	mode := uint32(0)
    17  	err := windows.GetConsoleMode(console, &mode)
    18  	if err != nil {
    19  		return false
    20  	}
    21  
    22  	// EnableVirtualTerminalProcessing is the console mode to allow ANSI code
    23  	// interpretation on the console. See:
    24  	// https://docs.microsoft.com/en-us/windows/console/setconsolemode
    25  	// It only works on windows 10. Earlier terminals will fail with an err which we will
    26  	// handle to say don't color
    27  	mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
    28  	err = windows.SetConsoleMode(console, mode)
    29  	return err == nil
    30  }
    31  
    32  func init() {
    33  	if isatty.IsTerminal(os.Stdout.Fd()) {
    34  		CanColorStdout = enableVTMode(windows.Stdout)
    35  	} else {
    36  		CanColorStdout = isatty.IsCygwinTerminal(os.Stderr.Fd())
    37  	}
    38  
    39  	if isatty.IsTerminal(os.Stderr.Fd()) {
    40  		CanColorStderr = enableVTMode(windows.Stderr)
    41  	} else {
    42  		CanColorStderr = isatty.IsCygwinTerminal(os.Stderr.Fd())
    43  	}
    44  }