Browse Source

Fixed #31216 -- Added support for colorama terminal colors on Windows.

Modern setups on Windows support terminal colors.
The colorama library may also be used, as an
alternative to the ANSICON library.
MinchinWeb 4 years ago
parent
commit
f1585c54d0

+ 37 - 2
django/core/management/color.py

@@ -8,17 +8,52 @@ import sys
 
 from django.utils import termcolors
 
+try:
+    import colorama
+except ImportError:
+    HAS_COLORAMA = False
+else:
+    colorama.init()
+    HAS_COLORAMA = True
+
 
 def supports_color():
     """
     Return True if the running system's terminal supports color,
     and False otherwise.
     """
-    supported_platform = sys.platform != 'win32' or 'ANSICON' in os.environ
+    def vt_codes_enabled_in_windows_registry():
+        """
+        Check the Windows Registry to see if VT code handling has been enabled
+        by default, see https://superuser.com/a/1300251/447564.
+        """
+        try:
+            # winreg is only available on Windows.
+            import winreg
+        except ImportError:
+            return False
+        else:
+            reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, 'Console')
+            try:
+                reg_key_value, _ = winreg.QueryValueEx(reg_key, 'VirtualTerminalLevel')
+            except FileNotFoundError:
+                return False
+            else:
+                return reg_key_value == 1
 
     # isatty is not always implemented, #6223.
     is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty()
-    return supported_platform and is_a_tty
+
+    return is_a_tty and (
+        sys.platform != 'win32' or
+        HAS_COLORAMA or
+        'ANSICON' in os.environ or
+        # Windows Terminal supports VT codes.
+        'WT_SESSION' in os.environ or
+        # Microsoft Visual Studio Code's built-in terminal supports colors.
+        os.environ.get('TERM_PROGRAM') == 'vscode' or
+        vt_codes_enabled_in_windows_registry()
+    )
 
 
 class Style:

+ 18 - 0
docs/howto/windows.txt

@@ -91,6 +91,24 @@ by executing ``django-admin --version`` in the command prompt.
 See :ref:`database-installation` for information on database installation
 with Django.
 
+Colored terminal output
+=======================
+
+.. versionadded: 3.2
+
+A quality-of-life feature is to output colored (rather than monochrome) output
+on the terminal. This should work both on CMD and PowerShell. If for some
+reason this needs to be disabled, set the environmental variable
+:envvar:`DJANGO_COLORS` to ``nocolor``.
+
+To enable this, colorama_ must be installed::
+
+    ...\> py -m pip install colorama
+
+See :ref:`syntax-coloring` for more information on color settings.
+
+.. _colorama: https://pypi.org/project/colorama/
+
 Common pitfalls
 ===============
 

+ 2 - 0
docs/internals/contributing/writing-code/unit-tests.txt

@@ -273,6 +273,7 @@ dependencies:
 *  argon2-cffi_ 19.1.0+
 *  asgiref_ 3.2.10+ (required)
 *  bcrypt_
+*  colorama_
 *  docutils_
 *  geoip2_
 *  jinja2_ 2.7+
@@ -319,6 +320,7 @@ service.
 .. _argon2-cffi: https://pypi.org/project/argon2_cffi/
 .. _asgiref: https://pypi.org/project/asgiref/
 .. _bcrypt: https://pypi.org/project/bcrypt/
+.. _colorama: https://pypi.org/project/colorama/
 .. _docutils: https://pypi.org/project/docutils/
 .. _geoip2: https://pypi.org/project/geoip2/
 .. _jinja2: https://pypi.org/project/jinja2/

+ 38 - 6
docs/ref/django-admin.txt

@@ -1863,10 +1863,44 @@ color-coded output if your terminal supports ANSI-colored output. It
 won't use the color codes if you're piping the command's output to
 another program unless the :option:`--force-color` option is used.
 
-Under Windows, the native console doesn't support ANSI escape sequences so by
-default there is no color output. But you can install the `ANSICON`_
-third-party tool, the Django commands will detect its presence and will make
-use of its services to color output just like on Unix-based platforms.
+Windows support
+~~~~~~~~~~~~~~~
+
+On Windows 10, the `Windows Terminal`_ application, `VS Code`_, and PowerShell
+(where virtual terminal processing is enabled) allow colored output, and are
+supported by default.
+
+Under Windows, the legacy ``cmd.exe`` native console doesn't support ANSI
+escape sequences so by default there is no color output. In this case either of
+two third-party libraries are needed:
+
+* Install colorama_, a Python package that translates ANSI color codes into
+  Windows API calls. Django commands will detect its presence and will make use
+  of its services to color output just like on Unix-based platforms.
+  ``colorama`` can be installed via pip::
+
+    ...\> py -m pip install colorama
+
+* Install `ANSICON`_, a third-party tool that allows ``cmd.exe`` to process
+  ANSI color codes. Django commands will detect its presence and will make use
+  of its services to color output just like on Unix-based platforms.
+
+Other modern terminal environments on Windows, that support terminal colors,
+but which are not automatically detected as supported by Django, may "fake" the
+installation of ``ANSICON`` by setting the appropriate environmental variable,
+``ANSICON="on"``.
+
+.. versionchanged:: 3.2
+
+    Updated support for syntax coloring on Windows.
+
+.. _`Windows Terminal`: https://www.microsoft.com/en-us/p/windows-terminal-preview/9n0dx20hk701
+.. _`VS Code`: https://code.visualstudio.com
+.. _ANSICON: http://adoxa.altervista.org/ansicon/
+.. _colorama: https://pypi.org/project/colorama/
+
+Custom colors
+~~~~~~~~~~~~~
 
 The colors used for syntax highlighting can be customized. Django
 ships with three color palettes:
@@ -1956,8 +1990,6 @@ would specify the use of all the colors in the light color palette,
 *except* for the colors for errors and notices which would be
 overridden as specified.
 
-.. _ANSICON: http://adoxa.altervista.org/ansicon/
-
 Bash completion
 ---------------
 

+ 5 - 0
docs/releases/3.2.txt

@@ -272,6 +272,11 @@ Management Commands
   prior to executing the command. In previous versions, either all or none
   of the system checks were performed.
 
+* Support for colored terminal output on Windows is updated. Various modern
+  terminal environments are automatically detected, and the options for
+  enabling support in other cases are improved. See :ref:`syntax-coloring` for
+  more details.
+
 Migrations
 ~~~~~~~~~~
 

+ 1 - 0
docs/spelling_wordlist

@@ -476,6 +476,7 @@ postfix
 postgis
 postgres
 postgresql
+PowerShell
 pq
 pre
 precisions

+ 1 - 0
tests/requirements/py3.txt

@@ -16,3 +16,4 @@ PyYAML
 selenium
 sqlparse >= 0.2.2
 tblib >= 1.5.0
+colorama; sys.platform == 'win32'