Skip to content

Commit

Permalink
- support MSYS/Cygwin terminals
Browse files Browse the repository at this point in the history
inspired by https://github.com/msys2/MINGW-packages/pull/2675/files
MSYS/Cygwin terminals (mintty) have filenames of the specific pattterns:
(msys|cygwin)-<GUID>-pty<NUMBER>-(from|to)-master
GetFileInformationByHandleEx is used to obtain a filename from the file descriptor
https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getfileinformationbyhandleex

Signed-off-by: SSE4 <tomskside@gmail.com>
  • Loading branch information
SSE4 committed Oct 7, 2021
1 parent b760506 commit 72682a6
Showing 1 changed file with 35 additions and 1 deletion.
36 changes: 35 additions & 1 deletion colorama/ansitowin32.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import re
import sys
import os
import ctypes

from .ansi import AnsiFore, AnsiBack, AnsiStyle, Style
from .winterm import WinTerm, WinColor, WinStyle
Expand All @@ -13,6 +14,39 @@
winterm = WinTerm()


def is_msys_cygwin_tty(stream):
try:
import msvcrt
except ImportError:
return False

if not hasattr(stream, "fileno"):
return False

if not hasattr(ctypes, "windll") or not hasattr(ctypes.windll.kernel32, "GetFileInformationByHandleEx"):
return False

fileno = stream.fileno()
handle = msvcrt.get_osfhandle(fileno)
FileNameInfo = 2

class FILE_NAME_INFO(ctypes.Structure):
_fields_ = [('FileNameLength', ctypes.c_ulong),
('FileName', ctypes.c_wchar * 40)]

info = FILE_NAME_INFO()
ret = ctypes.windll.kernel32.GetFileInformationByHandleEx(handle,
FileNameInfo,
ctypes.byref(info),
ctypes.sizeof(info))
if ret == 0:
return False

msys_pattern = r"\\msys-[0-9a-f]{16}-pty\d-(to|from)-master"
cygwin_pattern = r"\\cygwin-[0-9a-f]{16}-pty\d-(to|from)-master"
return re.match(msys_pattern, info.FileName) is not None or \
re.match(cygwin_pattern, info.FileName) is not None

class StreamWrapper(object):
'''
Wraps a stream (such as stdout), acting as a transparent proxy for all
Expand Down Expand Up @@ -50,7 +84,7 @@ def isatty(self):
except AttributeError:
return False
else:
return stream_isatty()
return stream_isatty() or is_msys_cygwin_tty(stream)

@property
def closed(self):
Expand Down

0 comments on commit 72682a6

Please sign in to comment.