[Python-modules-commits] [colorclass] 01/06: import colorclass_2.2.0.orig.tar.gz
Carl Suster
arcresu-guest at moszumanska.debian.org
Fri Jan 6 08:59:06 UTC 2017
This is an automated email from the git hooks/post-receive script.
arcresu-guest pushed a commit to branch master
in repository colorclass.
commit bf531346100de79a1a832ec54d3c5c8c8a9f16a5
Author: Carl Suster <carl at contraflo.ws>
Date: Thu Jan 5 12:59:44 2017 +1100
import colorclass_2.2.0.orig.tar.gz
---
.gitignore | 69 +++++++
.travis.yml | 25 +++
CONTRIBUTING.md | 35 ++++
LICENSE | 21 ++
README.rst | 229 +++++++++++++++++++++
appveyor.yml | 17 ++
colorclass/__init__.py | 38 ++++
colorclass/__main__.py | 33 +++
colorclass/codes.py | 229 +++++++++++++++++++++
colorclass/color.py | 220 ++++++++++++++++++++
colorclass/core.py | 342 +++++++++++++++++++++++++++++++
colorclass/parse.py | 96 +++++++++
colorclass/search.py | 49 +++++
colorclass/toggles.py | 42 ++++
colorclass/windows.py | 388 +++++++++++++++++++++++++++++++++++
example.png | Bin 0 -> 295535 bytes
example.py | 229 +++++++++++++++++++++
example_windows.png | Bin 0 -> 155348 bytes
setup.py | 63 ++++++
tests/__init__.py | 1 +
tests/conftest.py | 78 +++++++
tests/screenshot.py | 299 +++++++++++++++++++++++++++
tests/sub_box_green_win10.bmp | Bin 0 -> 5026 bytes
tests/sub_box_green_winxp.bmp | Bin 0 -> 7254 bytes
tests/sub_box_sans_win10.bmp | Bin 0 -> 5026 bytes
tests/sub_box_sans_winxp.bmp | Bin 0 -> 7254 bytes
tests/sub_red_dark_fg_win10.bmp | Bin 0 -> 446 bytes
tests/sub_red_dark_fg_winxp.bmp | Bin 0 -> 702 bytes
tests/sub_red_light_fg_win10.bmp | Bin 0 -> 418 bytes
tests/sub_red_light_fg_winxp.bmp | Bin 0 -> 702 bytes
tests/sub_red_sans_win10.bmp | Bin 0 -> 446 bytes
tests/sub_red_sans_winxp.bmp | Bin 0 -> 882 bytes
tests/test___main__.py | 64 ++++++
tests/test_codes.py | 137 +++++++++++++
tests/test_color.py | 185 +++++++++++++++++
tests/test_core.py | 398 ++++++++++++++++++++++++++++++++++++
tests/test_example.py | 96 +++++++++
tests/test_parse.py | 79 +++++++
tests/test_search.py | 51 +++++
tests/test_toggles.py | 29 +++
tests/test_windows.py | 429 +++++++++++++++++++++++++++++++++++++++
tox.ini | 78 +++++++
42 files changed, 4049 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..11757d4
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,69 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+env/
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+*.egg-info/
+.installed.cfg
+*.egg
+*.rpm
+requirements*.txt
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*,cover
+.hypothesis/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+#Ipython Notebook
+.ipynb_checkpoints
+
+# IntelliJ
+.idea/
+
+test*.png
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..e919857
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,25 @@
+# Configure.
+language: python
+python: 3.5
+sudo: false
+
+# Run.
+install: pip install appveyor-artifacts coveralls tox
+script: tox -e lint,py35,py34,py33,pypy3,pypy,py27,py26
+after_success:
+ - mv .coverage .coverage.travis
+ - appveyor-artifacts -mi download
+ - coverage combine
+ - coveralls
+
+# Deploy.
+deploy:
+ provider: pypi
+ user: Robpol86
+ password:
+ secure:
+ "JYR5ZVOHqZnr4uq8qtA9bM0+pBCfenTUApgSK2eMY3AoQ/Xi4UmcJvsGQkX70wq4twstRm\
+ twpb/oFkAuxLMKkK7AJOTt9lKzqjF62xm/yGilDIYMZGCWi30OcRuUSQsEaE1Bq0H1TxciV\
+ /ztcdwcXpTq2+oNQz9M7sbH7Czmdbw="
+ on:
+ tags: true
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..2ac3098
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,35 @@
+# Contributing
+
+Everyone that wants to contribute to the project should read this document.
+
+## Getting Started
+
+You may follow these steps if you wish to create a pull request. Fork the repo and clone it on your local machine. Then
+in the project's directory:
+
+```bash
+virtualenv env # Create a virtualenv for the project's dependencies.
+source env/bin/activate # Activate the virtualenv.
+pip install tox # Install tox, which runs linting and tests.
+tox # This runs all tests on your local machine. Make sure they pass.
+```
+
+If you don't have Python 2.6, 2.7, and 3.4 installed, you can manually run tests on one specific version by running
+`tox -e lint,py27` (for Python 2.7) instead.
+
+## Consistency and Style
+
+Keep code style consistent with the rest of the project. Some suggestions:
+
+1. **Write tests for your new features.** `if new_feature else` **Write tests for bug-causing scenarios.**
+2. Write docstrings for all classes, functions, methods, modules, etc.
+3. Document all function/method arguments and return values.
+4. Document all class variables instance variables.
+5. Documentation guidelines also apply to tests, though not as strict.
+6. Keep code style consistent, such as the kind of quotes to use and spacing.
+7. Don't use `except:` or `except Exception:` unless you have a `raise` in the block. Be specific about error handling.
+8. Don't use `isinstance()` (it breaks [duck typing](https://en.wikipedia.org/wiki/Duck_typing#In_Python)).
+
+## Thanks
+
+Thanks for fixing bugs or adding features to the project!
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d314c3c
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Robpol86
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..b236580
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,229 @@
+==========
+colorclass
+==========
+
+Yet another ANSI color text library for Python. Provides "auto colors" for dark/light terminals. Works on Linux, OS X,
+and Windows. For Windows support you just need to call ``Windows.enable()`` in your application.
+
+On Linux/OS X ``autocolors`` are toggled by calling ``set_light_background()`` and ``set_dark_background()``. On Windows
+this can be done automatically if you call ``Windows.enable(auto_colors=True)``. Even though the latest Windows 10 does
+support ANSI color codes natively, you still need to run Windows.enable() to take advantage of automatically detecting
+the console's background color.
+
+In Python2.x this library subclasses ``unicode``, while on Python3.x it subclasses ``str``.
+
+* Python 2.6, 2.7, PyPy, PyPy3, 3.3, 3.4, and 3.5 supported on Linux and OS X.
+* Python 2.6, 2.7, 3.3, 3.4, and 3.5 supported on Windows (both 32 and 64 bit versions of Python).
+
+.. image:: https://img.shields.io/appveyor/ci/Robpol86/colorclass/master.svg?style=flat-square&label=AppVeyor%20CI
+ :target: https://ci.appveyor.com/project/Robpol86/colorclass
+ :alt: Build Status Windows
+
+.. image:: https://img.shields.io/travis/Robpol86/colorclass/master.svg?style=flat-square&label=Travis%20CI
+ :target: https://travis-ci.org/Robpol86/colorclass
+ :alt: Build Status
+
+.. image:: https://img.shields.io/coveralls/Robpol86/colorclass/master.svg?style=flat-square&label=Coveralls
+ :target: https://coveralls.io/github/Robpol86/colorclass
+ :alt: Coverage Status
+
+.. image:: https://img.shields.io/pypi/v/colorclass.svg?style=flat-square&label=Latest
+ :target: https://pypi.python.org/pypi/colorclass
+ :alt: Latest Version
+
+.. image:: https://img.shields.io/pypi/dm/colorclass.svg?style=flat-square&label=PyPI%20Downloads
+ :target: https://pypi.python.org/pypi/colorclass
+ :alt: Downloads
+
+Quickstart
+==========
+
+Install:
+
+.. code:: bash
+
+ pip install colorclass
+
+Piped Command Line
+==================
+
+It is possible to pipe curly-bracket tagged (or regular ANSI coded) text to Python in the command line to produce color
+text. Some examples:
+
+.. code:: bash
+
+ echo "{red}Red{/red}" |python -m colorclass # Red colored text.
+ echo -e "\033[31mRed\033[0m" | COLOR_DISABLE=true python -m colorclass # Strip colors
+ echo -e "\033[31mRed\033[0m" | COLOR_ENABLE=true python -m colorclass &> file.txt # Force colors.
+
+Export these environment variables as "true" to enable/disable some features:
+
+=============== ============================================
+Env Variable Description
+=============== ============================================
+COLOR_ENABLE Force colors even when piping to a file.
+COLOR_DISABLE Strip all colors from incoming text.
+COLOR_LIGHT Use light colored text for dark backgrounds.
+COLOR_DARK Use dark colored text for light backgrounds.
+=============== ============================================
+
+Example Implementation
+======================
+
+.. image:: https://github.com/Robpol86/colorclass/raw/master/example.png?raw=true
+ :alt: Example Script Screenshot
+
+.. image:: https://github.com/Robpol86/colorclass/raw/master/example_windows.png?raw=true
+ :alt: Example Windows Screenshot
+
+Source code for the example code is: `example.py <https://github.com/Robpol86/colorclass/blob/master/example.py>`_
+
+Usage
+=====
+
+Different colors are chosen using curly-bracket tags, such as ``{red}{/red}``. For a list of available colors, call
+``colorclass.list_tags()``.
+
+The available "auto colors" tags are:
+
+* autoblack
+* autored
+* autogreen
+* autoyellow
+* autoblue
+* automagenta
+* autocyan
+* autowhite
+* autobgblack
+* autobgred
+* autobggreen
+* autobgyellow
+* autobgblue
+* autobgmagenta
+* autobgcyan
+* autobgwhite
+
+Methods of Class instances try to return sane data, such as:
+
+.. code:: python
+
+ from colorclass import Color
+ color_string = Color('{red}Test{/red}')
+
+ color_string
+ u'\x1b[31mTest\x1b[39m'
+
+ len(color_string)
+ 4
+
+ color_string.istitle()
+ True
+
+There are also a couple of helper attributes for all Color instances:
+
+.. code:: python
+
+ color_string.value_colors
+ '\x1b[31mTest\x1b[39m'
+
+ color_string.value_no_colors
+ 'Test'
+
+Changelog
+=========
+
+This project adheres to `Semantic Versioning <http://semver.org/>`_.
+
+2.2.0 - 2016-05-14
+------------------
+
+Added
+ * ``disable_if_no_tty()`` function to conditionally disable colors when STDERR and STDOUT are not streams.
+
+Changed
+ * Colors enabled by default always, like it was before v2.0.0.
+
+2.1.1 - 2016-05-10
+------------------
+
+Fixed
+ * Printing box drawing characters on Windows from Python 2.6.
+
+2.1.0 - 2016-05-07
+------------------
+
+Added
+ * ``keep_tags`` boolean keyword argument to Color(). Prevents colorclass from parsing curly brackets.
+ * Automatically skip replacing stderr/stdout streams on latest Windows 10 versions with native ANSI color support.
+
+Changed
+ * Refactored most of windows.py.
+ * Background color determined from either stderr or stdout, instead of just one stream (e.g. piping stderr to file).
+
+Fixed
+ * https://github.com/Robpol86/colorclass/issues/16
+ * https://github.com/Robpol86/colorclass/issues/18
+
+2.0.0 - 2016-04-10
+------------------
+
+Added
+ * Python 3.5 support.
+ * ``enable_all_colors()``, ``is_enabled()``, and ``is_light()`` toggle functions.
+ * Library can be used as a script (e.g. ``echo "{red}Red{/red}" |python -m colorclass``).
+ * Ability to add/multiply Color instances just like str.
+ * Ability to iterate a Color instance and have each character keep its color codes.
+
+Changed
+ * Converted library from Python module to a package.
+ * ``set_light_background()`` and ``set_dark_background()`` no longer enable colors. Use ``enable_all_colors()``.
+ * Colors are disabled by default when STDERR and STDOUT are not streams (piped to files/null). Similar to ``grep``.
+ * Reduce size of ANSI escape sequences by removing codes that have no effect. e.g. ``\033[31;35m`` to ``\033[35m``.
+ * Color methods that return strings now return Color instances instead of str instances.
+
+Fixed
+ * https://github.com/Robpol86/colorclass/issues/15
+ * https://github.com/Robpol86/colorclass/issues/17
+
+1.2.0 - 2015-03-19
+------------------
+
+Added
+ * Convenience single-color methods by `Marc Abramowitz <https://github.com/msabramo>`_.
+
+1.1.2 - 2015-01-07
+------------------
+
+Fixed
+ * Maintaining ``Color`` type through ``.encode()`` and ``.decode()`` chains.
+
+1.1.1 - 2014-11-03
+------------------
+
+Fixed
+ * Python 2.7 64-bit original colors bug on Windows.
+ * resetting colors when ``reset_atexit`` is True.
+ * Improved sorting of ``list_tags()``.
+
+1.1.0 - 2014-11-01
+------------------
+
+Added
+ * Native Windows support and automatic background colors.
+
+1.0.2 - 2014-10-20
+------------------
+
+Added
+ * Ability to disable/strip out all colors.
+
+1.0.1 - 2014-09-11
+------------------
+
+Fixed
+ * ``splitlines()`` method.
+
+1.0.0 - 2014-09-01
+------------------
+
+* Initial release.
diff --git a/appveyor.yml b/appveyor.yml
new file mode 100644
index 0000000..5b14160
--- /dev/null
+++ b/appveyor.yml
@@ -0,0 +1,17 @@
+# Configure.
+artifacts:
+ - path: .coverage
+
+# Run.
+init: set PATH=C:\Python35-x64;C:\Python35-x64\Scripts;%PATH%
+install:
+ - appveyor DownloadFile https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-desktop.ps1
+ - ps: .\enable-desktop
+build_script: pip install tox
+test_script: tox -e lint,py35,py34,py33,py27,py26,py35x64,py34x64,py33x64,py27x64,py26x64
+
+# Post.
+on_finish:
+ - appveyor PushArtifact test_example_test_windows_screenshot.png
+ - appveyor PushArtifact test_windows_test_enable_disable.png
+ - appveyor PushArtifact test_windows_test_box_characters.png
diff --git a/colorclass/__init__.py b/colorclass/__init__.py
new file mode 100644
index 0000000..cae4016
--- /dev/null
+++ b/colorclass/__init__.py
@@ -0,0 +1,38 @@
+"""Colorful worry-free console applications for Linux, Mac OS X, and Windows.
+
+Supported natively on Linux and Mac OSX (Just Works), and on Windows it works the same if Windows.enable() is called.
+
+Gives you expected and sane results from methods like len() and .capitalize().
+
+https://github.com/Robpol86/colorclass
+https://pypi.python.org/pypi/colorclass
+"""
+
+from colorclass.codes import list_tags # noqa
+from colorclass.color import Color # noqa
+from colorclass.toggles import disable_all_colors # noqa
+from colorclass.toggles import disable_if_no_tty # noqa
+from colorclass.toggles import enable_all_colors # noqa
+from colorclass.toggles import is_enabled # noqa
+from colorclass.toggles import is_light # noqa
+from colorclass.toggles import set_dark_background # noqa
+from colorclass.toggles import set_light_background # noqa
+from colorclass.windows import Windows # noqa
+
+
+__all__ = (
+ 'Color',
+ 'disable_all_colors',
+ 'enable_all_colors',
+ 'is_enabled',
+ 'is_light',
+ 'list_tags',
+ 'set_dark_background',
+ 'set_light_background',
+ 'Windows',
+)
+
+
+__author__ = '@Robpol86'
+__license__ = 'MIT'
+__version__ = '2.2.0'
diff --git a/colorclass/__main__.py b/colorclass/__main__.py
new file mode 100644
index 0000000..d8f3f00
--- /dev/null
+++ b/colorclass/__main__.py
@@ -0,0 +1,33 @@
+"""Called by "python -m". Allows package to be used as a script.
+
+Example usage:
+echo "{red}Red{/red}" |python -m colorclass
+"""
+
+from __future__ import print_function
+
+import fileinput
+import os
+
+from colorclass.color import Color
+from colorclass.toggles import disable_all_colors
+from colorclass.toggles import enable_all_colors
+from colorclass.toggles import set_dark_background
+from colorclass.toggles import set_light_background
+from colorclass.windows import Windows
+
+TRUTHY = ('true', '1', 'yes', 'on')
+
+
+if __name__ == '__main__':
+ if os.environ.get('COLOR_ENABLE', '').lower() in TRUTHY:
+ enable_all_colors()
+ elif os.environ.get('COLOR_DISABLE', '').lower() in TRUTHY:
+ disable_all_colors()
+ if os.environ.get('COLOR_LIGHT', '').lower() in TRUTHY:
+ set_light_background()
+ elif os.environ.get('COLOR_DARK', '').lower() in TRUTHY:
+ set_dark_background()
+ Windows.enable()
+ for LINE in fileinput.input():
+ print(Color(LINE))
diff --git a/colorclass/codes.py b/colorclass/codes.py
new file mode 100644
index 0000000..b0ecb03
--- /dev/null
+++ b/colorclass/codes.py
@@ -0,0 +1,229 @@
+"""Handles mapping between color names and ANSI codes and determining auto color codes."""
+
+import sys
+from collections import Mapping
+
+BASE_CODES = {
+ '/all': 0, 'b': 1, 'f': 2, 'i': 3, 'u': 4, 'flash': 5, 'outline': 6, 'negative': 7, 'invis': 8, 'strike': 9,
+ '/b': 22, '/f': 22, '/i': 23, '/u': 24, '/flash': 25, '/outline': 26, '/negative': 27, '/invis': 28,
+ '/strike': 29, '/fg': 39, '/bg': 49,
+
+ 'black': 30, 'red': 31, 'green': 32, 'yellow': 33, 'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37,
+
+ 'bgblack': 40, 'bgred': 41, 'bggreen': 42, 'bgyellow': 43, 'bgblue': 44, 'bgmagenta': 45, 'bgcyan': 46,
+ 'bgwhite': 47,
+
+ 'hiblack': 90, 'hired': 91, 'higreen': 92, 'hiyellow': 93, 'hiblue': 94, 'himagenta': 95, 'hicyan': 96,
+ 'hiwhite': 97,
+
+ 'hibgblack': 100, 'hibgred': 101, 'hibggreen': 102, 'hibgyellow': 103, 'hibgblue': 104, 'hibgmagenta': 105,
+ 'hibgcyan': 106, 'hibgwhite': 107,
+
+ 'autored': None, 'autoblack': None, 'automagenta': None, 'autowhite': None, 'autoblue': None, 'autoyellow': None,
+ 'autogreen': None, 'autocyan': None,
+
+ 'autobgred': None, 'autobgblack': None, 'autobgmagenta': None, 'autobgwhite': None, 'autobgblue': None,
+ 'autobgyellow': None, 'autobggreen': None, 'autobgcyan': None,
+
+ '/black': 39, '/red': 39, '/green': 39, '/yellow': 39, '/blue': 39, '/magenta': 39, '/cyan': 39, '/white': 39,
+ '/hiblack': 39, '/hired': 39, '/higreen': 39, '/hiyellow': 39, '/hiblue': 39, '/himagenta': 39, '/hicyan': 39,
+ '/hiwhite': 39,
+
+ '/bgblack': 49, '/bgred': 49, '/bggreen': 49, '/bgyellow': 49, '/bgblue': 49, '/bgmagenta': 49, '/bgcyan': 49,
+ '/bgwhite': 49, '/hibgblack': 49, '/hibgred': 49, '/hibggreen': 49, '/hibgyellow': 49, '/hibgblue': 49,
+ '/hibgmagenta': 49, '/hibgcyan': 49, '/hibgwhite': 49,
+
+ '/autored': 39, '/autoblack': 39, '/automagenta': 39, '/autowhite': 39, '/autoblue': 39, '/autoyellow': 39,
+ '/autogreen': 39, '/autocyan': 39,
+
+ '/autobgred': 49, '/autobgblack': 49, '/autobgmagenta': 49, '/autobgwhite': 49, '/autobgblue': 49,
+ '/autobgyellow': 49, '/autobggreen': 49, '/autobgcyan': 49,
+}
+
+
+class ANSICodeMapping(Mapping):
+ """Read-only dictionary, resolves closing tags and automatic colors. Iterates only used color tags.
+
+ :cvar bool DISABLE_COLORS: Disable colors (strip color codes).
+ :cvar bool LIGHT_BACKGROUND: Use low intensity color codes.
+ """
+
+ DISABLE_COLORS = False
+ LIGHT_BACKGROUND = False
+
+ def __init__(self, value_markup):
+ """Constructor.
+
+ :param str value_markup: String with {color} tags.
+ """
+ self.whitelist = [k for k in BASE_CODES if '{' + k + '}' in value_markup]
+
+ def __getitem__(self, item):
+ """Return value for key or None if colors are disabled.
+
+ :param str item: Key.
+
+ :return: Color code integer.
+ :rtype: int
+ """
+ if item not in self.whitelist:
+ raise KeyError(item)
+ if self.DISABLE_COLORS:
+ return None
+ return getattr(self, item, BASE_CODES[item])
+
+ def __iter__(self):
+ """Iterate dictionary."""
+ return iter(self.whitelist)
+
+ def __len__(self):
+ """Dictionary length."""
+ return len(self.whitelist)
+
+ @classmethod
+ def disable_all_colors(cls):
+ """Disable all colors. Strips any color tags or codes."""
+ cls.DISABLE_COLORS = True
+
+ @classmethod
+ def enable_all_colors(cls):
+ """Enable all colors. Strips any color tags or codes."""
+ cls.DISABLE_COLORS = False
+
+ @classmethod
+ def disable_if_no_tty(cls):
+ """Disable all colors only if there is no TTY available.
+
+ :return: True if colors are disabled, False if stderr or stdout is a TTY.
+ :rtype: bool
+ """
+ if sys.stdout.isatty() or sys.stderr.isatty():
+ return False
+ cls.disable_all_colors()
+ return True
+
+ @classmethod
+ def set_dark_background(cls):
+ """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds."""
+ cls.LIGHT_BACKGROUND = False
+
+ @classmethod
+ def set_light_background(cls):
+ """Choose dark colors for all 'auto'-prefixed codes for readability on light backgrounds."""
+ cls.LIGHT_BACKGROUND = True
+
+ @property
+ def autoblack(self):
+ """Return automatic black foreground color depending on background color."""
+ return BASE_CODES['black' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiblack']
+
+ @property
+ def autored(self):
+ """Return automatic red foreground color depending on background color."""
+ return BASE_CODES['red' if ANSICodeMapping.LIGHT_BACKGROUND else 'hired']
+
+ @property
+ def autogreen(self):
+ """Return automatic green foreground color depending on background color."""
+ return BASE_CODES['green' if ANSICodeMapping.LIGHT_BACKGROUND else 'higreen']
+
+ @property
+ def autoyellow(self):
+ """Return automatic yellow foreground color depending on background color."""
+ return BASE_CODES['yellow' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiyellow']
+
+ @property
+ def autoblue(self):
+ """Return automatic blue foreground color depending on background color."""
+ return BASE_CODES['blue' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiblue']
+
+ @property
+ def automagenta(self):
+ """Return automatic magenta foreground color depending on background color."""
+ return BASE_CODES['magenta' if ANSICodeMapping.LIGHT_BACKGROUND else 'himagenta']
+
+ @property
+ def autocyan(self):
+ """Return automatic cyan foreground color depending on background color."""
+ return BASE_CODES['cyan' if ANSICodeMapping.LIGHT_BACKGROUND else 'hicyan']
+
+ @property
+ def autowhite(self):
+ """Return automatic white foreground color depending on background color."""
+ return BASE_CODES['white' if ANSICodeMapping.LIGHT_BACKGROUND else 'hiwhite']
+
+ @property
+ def autobgblack(self):
+ """Return automatic black background color depending on background color."""
+ return BASE_CODES['bgblack' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgblack']
+
+ @property
+ def autobgred(self):
+ """Return automatic red background color depending on background color."""
+ return BASE_CODES['bgred' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgred']
+
+ @property
+ def autobggreen(self):
+ """Return automatic green background color depending on background color."""
+ return BASE_CODES['bggreen' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibggreen']
+
+ @property
+ def autobgyellow(self):
+ """Return automatic yellow background color depending on background color."""
+ return BASE_CODES['bgyellow' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgyellow']
+
+ @property
+ def autobgblue(self):
+ """Return automatic blue background color depending on background color."""
+ return BASE_CODES['bgblue' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgblue']
+
+ @property
+ def autobgmagenta(self):
+ """Return automatic magenta background color depending on background color."""
+ return BASE_CODES['bgmagenta' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgmagenta']
+
+ @property
+ def autobgcyan(self):
+ """Return automatic cyan background color depending on background color."""
+ return BASE_CODES['bgcyan' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgcyan']
+
+ @property
+ def autobgwhite(self):
+ """Return automatic white background color depending on background color."""
+ return BASE_CODES['bgwhite' if ANSICodeMapping.LIGHT_BACKGROUND else 'hibgwhite']
+
+
+def list_tags():
+ """List the available tags.
+
+ :return: List of 4-item tuples: opening tag, closing tag, main ansi value, closing ansi value.
+ :rtype: list
+ """
+ # Build reverse dictionary. Keys are closing tags, values are [closing ansi, opening tag, opening ansi].
+ reverse_dict = dict()
+ for tag, ansi in sorted(BASE_CODES.items()):
+ if tag.startswith('/'):
+ reverse_dict[tag] = [ansi, None, None]
+ else:
+ reverse_dict['/' + tag][1:] = [tag, ansi]
+
+ # Collapse
+ four_item_tuples = [(v[1], k, v[2], v[0]) for k, v in reverse_dict.items()]
+
+ # Sort.
+ def sorter(four_item):
+ """Sort /all /fg /bg first, then b i u flash, then auto colors, then dark colors, finally light colors.
+
+ :param iter four_item: [opening tag, closing tag, main ansi value, closing ansi value]
+
+ :return Sorting weight.
+ :rtype: int
+ """
+ if not four_item[2]: # /all /fg /bg
+ return four_item[3] - 200
+ if four_item[2] < 10 or four_item[0].startswith('auto'): # b f i u or auto colors
+ return four_item[2] - 100
+ return four_item[2]
+ four_item_tuples.sort(key=sorter)
+
+ return four_item_tuples
diff --git a/colorclass/color.py b/colorclass/color.py
new file mode 100644
index 0000000..2849d06
--- /dev/null
+++ b/colorclass/color.py
@@ -0,0 +1,220 @@
+"""Color class used by library users."""
+
+from colorclass.core import ColorStr
+
+
+class Color(ColorStr):
+ """Unicode (str in Python3) subclass with ANSI terminal text color support.
+
+ Example syntax: Color('{red}Sample Text{/red}')
+
+ Example without parsing logic: Color('{red}Sample Text{/red}', keep_tags=True)
+
+ For a list of codes, call: colorclass.list_tags()
+ """
+
+ @classmethod
+ def colorize(cls, color, string, auto=False):
+ """Color-code entire string using specified color.
+
+ :param str color: Color of string.
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ tag = '{0}{1}'.format('auto' if auto else '', color)
+ return cls('{%s}%s{/%s}' % (tag, string, tag))
+
+ @classmethod
+ def black(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('black', string, auto=auto)
+
+ @classmethod
+ def bgblack(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('bgblack', string, auto=auto)
+
+ @classmethod
+ def red(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('red', string, auto=auto)
+
+ @classmethod
+ def bgred(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('bgred', string, auto=auto)
+
+ @classmethod
+ def green(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('green', string, auto=auto)
+
+ @classmethod
+ def bggreen(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('bggreen', string, auto=auto)
+
+ @classmethod
+ def yellow(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('yellow', string, auto=auto)
+
+ @classmethod
+ def bgyellow(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('bgyellow', string, auto=auto)
+
+ @classmethod
+ def blue(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('blue', string, auto=auto)
+
+ @classmethod
+ def bgblue(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('bgblue', string, auto=auto)
+
+ @classmethod
+ def magenta(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('magenta', string, auto=auto)
+
+ @classmethod
+ def bgmagenta(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('bgmagenta', string, auto=auto)
+
+ @classmethod
+ def cyan(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
+ """
+ return cls.colorize('cyan', string, auto=auto)
+
+ @classmethod
+ def bgcyan(cls, string, auto=False):
+ """Color-code entire string.
+
+ :param str string: String to colorize.
+ :param bool auto: Enable auto-color (dark/light terminal).
+
+ :return: Class instance for colorized string.
+ :rtype: Color
... 3327 lines suppressed ...
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/colorclass.git
More information about the Python-modules-commits
mailing list