isatty_windows.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. //go:build windows && !appengine
  2. // +build windows,!appengine
  3. package isatty
  4. import (
  5. "strings"
  6. "syscall"
  7. "unicode/utf16"
  8. "unsafe"
  9. )
  10. const (
  11. fileNameInfo uintptr = 2
  12. fileTypePipe = 3
  13. )
  14. var (
  15. kernel32 = syscall.NewLazyDLL("kernel32.dll")
  16. procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
  17. procGetFileInformationByHandleEx = kernel32.NewProc("GetFileInformationByHandleEx")
  18. procGetFileType = kernel32.NewProc("GetFileType")
  19. )
  20. func init() {
  21. // Check if GetFileInformationByHandleEx is available.
  22. if procGetFileInformationByHandleEx.Find() != nil {
  23. procGetFileInformationByHandleEx = nil
  24. }
  25. }
  26. // IsTerminal return true if the file descriptor is terminal.
  27. func IsTerminal(fd uintptr) bool {
  28. var st uint32
  29. r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, fd, uintptr(unsafe.Pointer(&st)), 0)
  30. return r != 0 && e == 0
  31. }
  32. // Check pipe name is used for cygwin/msys2 pty.
  33. // Cygwin/MSYS2 PTY has a name like:
  34. // \{cygwin,msys}-XXXXXXXXXXXXXXXX-ptyN-{from,to}-master
  35. func isCygwinPipeName(name string) bool {
  36. token := strings.Split(name, "-")
  37. if len(token) < 5 {
  38. return false
  39. }
  40. if token[0] != `\msys` && token[0] != `\cygwin` {
  41. return false
  42. }
  43. if token[1] == "" {
  44. return false
  45. }
  46. if !strings.HasPrefix(token[2], "pty") {
  47. return false
  48. }
  49. if token[3] != `from` && token[3] != `to` {
  50. return false
  51. }
  52. if token[4] != "master" {
  53. return false
  54. }
  55. return true
  56. }
  57. // IsCygwinTerminal() return true if the file descriptor is a cygwin or msys2
  58. // terminal.
  59. func IsCygwinTerminal(fd uintptr) bool {
  60. if procGetFileInformationByHandleEx == nil {
  61. return false
  62. }
  63. // Cygwin/msys's pty is a pipe.
  64. ft, _, e := syscall.Syscall(procGetFileType.Addr(), 1, fd, 0, 0)
  65. if ft != fileTypePipe || e != 0 {
  66. return false
  67. }
  68. var buf [2 + syscall.MAX_PATH]uint16
  69. r, _, e := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(),
  70. 4, fd, fileNameInfo, uintptr(unsafe.Pointer(&buf)),
  71. uintptr(len(buf)*2), 0, 0)
  72. if r == 0 || e != 0 {
  73. return false
  74. }
  75. l := *(*uint32)(unsafe.Pointer(&buf))
  76. return isCygwinPipeName(string(utf16.Decode(buf[2 : 2+l/2])))
  77. }