From 5b581a6b67612f19b44158b7a179ef60f32d48d4 Mon Sep 17 00:00:00 2001 From: Matt Wilson Date: Tue, 17 Nov 2026 08:10:19 +1100 Subject: [PATCH 1/2] feat(woad.Python): add the portable colour policy in 0.1.0-alpha1 Add BOLD and BLINKING and the Unix half of the woad 0.3.0 colour contract: colour_policy, refresh, supports_colour, and seq_for. Decision rows 1-22 are covered. Windows virtual-terminal gating and mintty recognition stay for a later alpha. --- .editorconfig | 44 +++++ .gitattributes | 9 + .github/workflows/python-package.yml | 30 +++- .gitignore | 9 + .sis/project_name.txt | 1 + .sis/script_info_lines.txt | 2 + .vimrc | 57 ++++++ .vscode/settings.json | 43 +++++ CHANGES.md | 12 ++ NEWS.md | 10 +- README.md | 29 ++- TODO.md | 6 +- examples/conditional.py | 25 +++ pyproject.toml | 21 ++- run_all_unit_tests.sh | 233 ++++++++++++++++++++++++ setup.py | 2 +- tests/test_woad.py | 257 ++++++++++++++++++++++++++- woad/__init__.py | 224 ++++++++++++++++++++++- 18 files changed, 998 insertions(+), 16 deletions(-) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .sis/project_name.txt create mode 100644 .sis/script_info_lines.txt create mode 100644 .vimrc create mode 100644 .vscode/settings.json create mode 100644 examples/conditional.py create mode 100755 run_all_unit_tests.sh diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..762ee86 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,44 @@ +root = true + +# Language indent/EOL/charset overlap with .vscode/settings.json. +# Rulers, renderWhitespace, detectIndentation, mergeEditor, and +# language-server settings cannot be expressed here — they stay in +# settings.json. + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 2 +indent_style = tab +insert_final_newline = true +trim_trailing_whitespace = true + +# [json] +[*.json] +indent_size = 2 +indent_style = space + +# [markdown] +[*.md] +indent_size = 2 +indent_style = space + +# [python] +[*.py] +indent_size = 4 +indent_style = space + +# [shellscript] +[*.{bash,sh,zsh}] +indent_size = 2 +indent_style = space + +# [toml] +[*.toml] +indent_size = 2 +indent_style = tab + +# [yaml] +[*.{yaml,yml}] +indent_size = 2 +indent_style = space diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..990aa80 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +*.c linguist-language=C +*.cpp linguist-language=C++ +*.h linguist-language=C +*.hpp linguist-language=C++ +*.html linguist-detectable=false +*.py linguist-language=Python +*.sh linguist-detectable=false +*.vimrc linguist-detectable=false +makefile linguist-detectable=false diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 1fa4359..67e7326 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -2,7 +2,7 @@ # the sdist/wheel on a range of Python versions. # # Created: 15th August 2026 -# Updated: 15th August 2026 +# Updated: 17th November 2026 # name: Python package @@ -10,10 +10,10 @@ name: Python package on: push: branches: - - boilerplate + - master - dev + - boilerplate - idiomatic - - master - rc1 - rc2 - rc3 @@ -27,6 +27,28 @@ defaults: shell: bash jobs: + lint: + name: Lint (ruff) + runs-on: ubuntu-latest + + steps: + - name: Checking out code + uses: actions/checkout@v4 + + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: "3.14" + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install ruff + + - name: Lint with ruff + run: | + ruff check . + build: runs-on: ubuntu-latest @@ -66,7 +88,7 @@ jobs: python -m pip install build python -m build python -m pip install dist/woad-*.whl - python -c "import woad; assert woad.__version__ == '0.0.1'; print(woad.__version__)" + python -c "import woad; assert woad.__version__ == '0.1.0-alpha1'; print(woad.__version__)" build-py27: diff --git a/.gitignore b/.gitignore index e342279..75d68ed 100644 --- a/.gitignore +++ b/.gitignore @@ -1,9 +1,14 @@ + # directories (by name) +/.bin/ +/.pytest_cache/ +/.ruff_cache/ /.venv/ build/ dist/ +dist-old/ scratch/ *.egg-info/ @@ -11,11 +16,15 @@ scratch/ # directories (by pattern) +**/__pycache__/ + # files (by name) .DS_Store +notes.txt + # files (by pattern) diff --git a/.sis/project_name.txt b/.sis/project_name.txt new file mode 100644 index 0000000..b2579f8 --- /dev/null +++ b/.sis/project_name.txt @@ -0,0 +1 @@ +woad.Python diff --git a/.sis/script_info_lines.txt b/.sis/script_info_lines.txt new file mode 100644 index 0000000..4583584 --- /dev/null +++ b/.sis/script_info_lines.txt @@ -0,0 +1,2 @@ +woad.Python provides minimal ANSI terminal colour codes for Python +Copyright (c) 2026, Matthew Wilson and Synesis Information Systems diff --git a/.vimrc b/.vimrc new file mode 100644 index 0000000..d07167a --- /dev/null +++ b/.vimrc @@ -0,0 +1,57 @@ +" Synesis Python project .vimrc — aligned with .vscode/settings.json (Python) + +set nocompatible +filetype indent plugin on +syntax enable +set autoindent +set backspace=indent,eol,start +set hlsearch +set incsearch +set number + +" files.insertFinalNewline +set eol +set fixeol + +" editor.renderWhitespace: all +set list +set listchars=tab:->,trail:-,extends:>,precedes:<,nbsp:+ + +" editor.detectIndentation: false — global defaults match [python] (editor.tabSize: 4, insertSpaces: true) +set colorcolumn=76 +set expandtab +set shiftwidth=4 +set softtabstop=4 +set tabstop=4 + +" colorcolumn draws a full-column tint in Vim (not a VS Code-style 1px line). +" Keep it subtle via the ColorColumn highlight group; reapply after colorscheme changes. +if has('termguicolors') + " set termguicolors +endif + +function! s:ConfigureColorColumn() abort + highlight ColorColumn ctermbg=236 guibg=#2a2a2a cterm=NONE gui=NONE +endfunction + +call s:ConfigureColorColumn() +autocmd ColorScheme * call s:ConfigureColorColumn() + +" files.trimTrailingWhitespace +autocmd BufWritePre * %s/\s\+$//e + +augroup sis_python + autocmd! + + " [json] / [markdown] / [yaml] + autocmd FileType json,markdown,yaml setlocal expandtab tabstop=2 shiftwidth=2 softtabstop=2 + + " [python] — match .vscode [python] tabSize 4 / insertSpaces true / rulers 50,60,76,120 + autocmd FileType python setlocal expandtab tabstop=4 shiftwidth=4 softtabstop=4 colorcolumn=50,60,76,120 + + " [shellscript] + autocmd FileType sh,bash,zsh setlocal expandtab tabstop=2 shiftwidth=2 softtabstop=2 colorcolumn=60,76 + + " [toml] + autocmd FileType toml setlocal noexpandtab tabstop=2 shiftwidth=2 softtabstop=2 +augroup END diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..95b7da0 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,43 @@ +{ + "[json]": { + "editor.tabSize": 2, + }, + "[markdown]": { + "editor.insertSpaces": true, + "editor.tabSize": 2, + }, + "[python]": { + "diffEditor.ignoreTrimWhitespace": false, + "editor.insertSpaces": true, + "editor.rulers": [ 50, 60, 76, 120 ], + "editor.tabSize": 4, + }, + "[shellscript]": { + "editor.insertSpaces": true, + "editor.rulers": [ 60, 76 ], + "editor.tabSize": 2, + }, + "[toml]": { + "editor.insertSpaces": false, + "editor.tabSize": 2, + }, + "[yaml]": { + "editor.insertSpaces": true, + "editor.tabSize": 2, + }, + "editor.detectIndentation": false, + "editor.insertSpaces": false, + "editor.renderWhitespace": "all", + "editor.rulers": [ 76 ], + "editor.tabSize": 2, + "files.exclude": { + "**/*.egg-info": true, + "**/*.swp": true, + "**/__pycache__": true, + }, + "files.insertFinalNewline": true, + "files.trimTrailingWhitespace": true, + "git.mergeEditor": false, + "python.analysis.typeCheckingMode": "standard", + "python.languageServer": "Pylance", +} diff --git a/CHANGES.md b/CHANGES.md index 2477a70..66f4b1b 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -1,6 +1,18 @@ # woad.Python - Changes +## 0.1.0-alpha1 - 17th November 2026 + +* Added `BLINKING` and `BOLD`; +* Portable colour policy (`colour_policy`, `refresh`, `supports_colour`, `seq_for`), including `TERM=dumb` and file attachment; +* Windows virtual-terminal gating and mintty recognition are not in this alpha; + + +## 0.0.2 - 14th September 2026 + +* packaging, documentation, and CI modernisation (canonical CI, **ruff**, helper scripts, **MANIFEST.in**); + + ## 0.0.1 - 15th August 2026 * SGR colour and reset codes (`RESET`, `FG_*`, `BG_*`, including bright variants); diff --git a/NEWS.md b/NEWS.md index fb5536a..85d99fe 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,9 +1,11 @@ # woad.Python - News -| Date | News Item | -| ---------------- | ------------------------------------------------------------------------------------------ | -| 15th August 2026 | [**woad.Python** 0.0.1](https://github.com/synesissoftware/woad.Python/releases/tag/0.0.1) | -| 15th August 2026 | [**woad.Python** 0.0.0](https://github.com/synesissoftware/woad.Python/releases/tag/0.0.0) | +| Date | News Item | Details | +| ------------------- | ------------------------------------------------------------------------------------------ | ------- | +| 17th November 2026 | [**woad.Python** 0.1.0-alpha1](https://github.com/synesissoftware/woad.Python/releases/tag/0.1.0-alpha1) | `BOLD`, `BLINKING`; portable colour policy; Windows VT not in this alpha | +| 14th September 2026 | [**woad.Python** 0.0.2](https://github.com/synesissoftware/woad.Python/releases/tag/0.0.2) | Packaging / CI modernisation | +| 15th August 2026 | [**woad.Python** 0.0.1](https://github.com/synesissoftware/woad.Python/releases/tag/0.0.1) | SGR colour and reset codes | +| 15th August 2026 | [**woad.Python** 0.0.0](https://github.com/synesissoftware/woad.Python/releases/tag/0.0.0) | Initial scaffolding; Python 2.7 and 3.8+ | diff --git a/README.md b/README.md index e34d50c..97c5549 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Minimal ANSI terminal colour codes, for Python ## Table of Contents - [Introduction](#introduction) +- [Developer Experience](#developer-experience) - [Installation](#installation) - [Components](#components) - [Project Information](#project-information) @@ -34,6 +35,32 @@ Minimal ANSI terminal colour codes, for Python **woad.Python** is the **Python** implementation. It supports **Python 2.7** and **Python 3.8+**. +## Developer Experience + +**Python 2.7** or **Python 3.8+** is required. The library uses the standard library only. From a checkout: + +```bash +python -m unittest discover -s tests +python examples/conditional.py +``` + +The smallest useful call prints a sequence only when the stream supports colour: + +```Python +import sys + +import woad + +stream = sys.stdout +green = woad.seq_for(stream, woad.FG_GREEN) +reset = woad.seq_for(stream, woad.RESET) + +print(green + "ok" + reset) +``` + +That is [examples/conditional.py](./examples/conditional.py). Fixed sequences (`BOLD`, `BLINKING`, `FG_*`, `BG_*`) always contain the SGR bytes. `colour_policy`, `supports_colour`, and `seq_for` apply the cached environment policy. `refresh` drops that cache. A `None` sequence yields `""`. + + ## Installation Install via **pip**: @@ -53,7 +80,7 @@ print(woad.FG_GREEN + "ok" + woad.RESET) ## Components -**woad.Python** ships SGR string constants (`RESET`, `FG_*`, `BG_*`, including bright variants). TTY/stream gating and Windows virtual-terminal opt-in are not implemented yet. +**woad.Python** ships fixed SGR sequences (`BLINKING`, `BOLD`, `RESET`, `FG_*`, `BG_*`, including bright variants) and the portable colour policy: `colour_policy`, `refresh`, `supports_colour`, and `seq_for`. On Unix a terminal supports colour when the policy is automatic and `TERM` is not `dumb`. Windows virtual-terminal mode and mintty PTY recognition are not implemented. ## Project Information diff --git a/TODO.md b/TODO.md index 3a58029..190e32c 100644 --- a/TODO.md +++ b/TODO.md @@ -3,9 +3,9 @@ ## Functional improvements -* [x] ~~~SGR colour and reset codes~~~ ✅; -* [ ] TTY-conditional colour codes (process and per-stream); -* [ ] Windows virtual-terminal gating (OS build + `GetConsoleMode`); +* [x] ~~~SGR colour and reset codes~~~ - ✅; +* [x] ~~~portable colour policy (Unix attachment, `TERM=dumb`, conditional emission)~~~ - ✅; +* [ ] Windows virtual-terminal gating (`SetConsoleMode`, `WOAD_SET_CONSOLE_MODE`, mintty PTY names); ## Performance improvements diff --git a/examples/conditional.py b/examples/conditional.py new file mode 100644 index 0000000..6c12007 --- /dev/null +++ b/examples/conditional.py @@ -0,0 +1,25 @@ +#! /usr/bin/env python + +"""Print a sequence only when the stream supports colour.""" + +from __future__ import print_function + +import sys + +import woad + + +def main(): + + stream = sys.stdout + green = woad.seq_for(stream, woad.FG_GREEN) + reset = woad.seq_for(stream, woad.RESET) + + print(green + 'ok' + reset) + + return 0 + + +if __name__ == '__main__': + + sys.exit(main()) diff --git a/pyproject.toml b/pyproject.toml index c819640..5dff309 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -42,7 +42,7 @@ license = { text = "BSD-3-Clause" } name = "woad" readme = "README.md" requires-python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*, !=3.7.*" -version = "0.0.1" +version = "0.1.0-alpha1" [project.urls] "Bug Tracker" = "https://github.com/synesissoftware/woad.Python/issues" @@ -50,6 +50,25 @@ Changelog = "https://github.com/synesissoftware/woad.Python/blob/master/CHANGES. Homepage = "https://github.com/synesissoftware/woad.Python" Repository = "https://github.com/synesissoftware/woad.Python" +[project.optional-dependencies] +dev = [ + "pytest", + "ruff>=0.4.0", +] + + +[tool.ruff] +line-length = 76 +target-version = "py38" + +[tool.ruff.lint] +ignore = [ + "E501", +] +select = [ + "E", + "F", +] [tool.setuptools.packages.find] exclude = [ diff --git a/run_all_unit_tests.sh b/run_all_unit_tests.sh new file mode 100755 index 0000000..b13bc2c --- /dev/null +++ b/run_all_unit_tests.sh @@ -0,0 +1,233 @@ +#! /bin/bash + +# ######################################################################## # +# File: run_all_unit_tests.sh +# +# Purpose: Executes the unit-tests of a Python project regardless of +# calling directory +# +# Created: 13th February 2019 +# Updated: 14th September 2026 +# +# Copyright (c) Matthew Wilson, 2019-2026 +# All rights reserved +# +# Redistribution and use in Source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, +# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ######################################################################## # + + +# constants + +Source="${BASH_SOURCE[0]}" +while [ -h "$Source" ]; do + + Dir="$(cd -P "$(dirname "$Source")" && pwd)" + Source="$(readlink "$Source")" + [[ $Source != /* ]] && Source="$Dir/$Source" +done +Dir="$(cd -P "$( dirname "$Source" )" && pwd)" +Basename="$(basename "$Source")" + +ProjectNameFile="$Dir/.sis/project_name.txt" +if [ -f "$ProjectNameFile" ]; then + ProjectName=$(tr -d '[:space:]' < "$ProjectNameFile") +else + ProjectName=$(basename "$Dir") +fi + + +AssumePython2= +IncludePython2InSearch= +PythonCommandPath= + + +# regular command-line handling + + +while [[ $# -gt 0 ]] +do + + case "$1" in + + --assume-python2) + + AssumePython2=1 + ;; + --include-python2-in-search) + + IncludePython2InSearch=1 + ;; + --python-cmd-path|-p) + + shift + + PythonCommandPath=$1 + ;; + --help) + + [ -f "$Dir/.sis/script_info_lines.txt" ] && cat "$Dir/.sis/script_info_lines.txt" + echo + cat << EOF +USAGE: $Basename { | --help | [ --assume-python2 ] [ --include-python2-in-search ] [ --python-cmd-path | -p ] } + +${ProjectName} unit tests + +flags/options: + + --help + shows this help and terminates + + --assume-python2 + uses the python2 command when no -p / --python-cmd-path is given + + --include-python2-in-search + includes python2 in automatic interpreter discovery (after python3 and python) + + -p + --python-cmd-path + specifies explicitly the path of the Python command to be executed (rather than discover it) +EOF + + exit 0 + ;; + *) + + >&2 echo "unrecognised argument; use --help for usage" + + exit 1 + ;; + esac + + shift +done + + +# validate / discover python executable path + +if [ "x_$PythonCommandPath" = "x_" ] && [ ! -z "$AssumePython2" ]; then + + PythonCommandPath=python2 +fi + +if [ "x_$PythonCommandPath" != "x_" ]; then + + # check the given command + + if ! { [ -x "$PythonCommandPath" ] || command -v "$PythonCommandPath" > /dev/null; }; then + + >&2 echo "given python-cmd-path '$PythonCommandPath' is not executable" + + exit 1 + fi +else + + # try and find a suitable command + + # Prefer a project-local venv when present (avoids Apple/Xcode python3 on + # PATH, which must not be used for local install/test). + if [ "x_$PythonCommandPath" = "x_" ]; then + + if [ -x "$Dir/.venv/bin/python" ]; then + + PythonCommandPath="$Dir/.venv/bin/python" + + echo "found project venv python '$PythonCommandPath'" + fi + fi + + if [ "x_$PythonCommandPath" = "x_" ]; then + + if [ "y_$PYTHON_COMMAND_PATH" != "y_" ]; then + + if command -v "$PYTHON_COMMAND_PATH" > /dev/null; then + + PythonCommandPath=$PYTHON_COMMAND_PATH + fi + fi + fi + + if [ "x_$PythonCommandPath" = "x_" ]; then + + if [ "y_$PYTHON_CMD_PATH" != "y_" ]; then + + if command -v "$PYTHON_CMD_PATH" > /dev/null; then + + PythonCommandPath=$PYTHON_CMD_PATH + fi + fi + fi + + if [ "x_$PythonCommandPath" = "x_" ]; then + + PossiblePythonCommands=(python3 python) + + if [ ! -z "$IncludePython2InSearch" ]; then + + PossiblePythonCommands+=(python2) + fi + + for p in "${PossiblePythonCommands[@]}" + do + + if command -v "$p" > /dev/null; then + + PythonCommandPath=$p + + echo "found valid python command '$p'" + + break + fi + done + fi + + if [ "x_$PythonCommandPath" = "x_" ]; then + + if [ -z "$IncludePython2InSearch" ] && [ -z "$AssumePython2" ] && command -v python2 > /dev/null; then + + >&2 echo "only python2 was found on PATH; pass --include-python2-in-search to allow it during discovery, or --assume-python2 to use python2 explicitly" + + exit 1 + fi + + >&2 echo "no valid python command path discovered" + + exit 1 + fi +fi + + +# executing tests + + +# This will operate recursively as long as each subdirectory of $Dir/tests +# contains an __init__.py file (which may be empty) +"$PythonCommandPath" -m unittest discover -s "$Dir/tests" + + +# ############################## end of file ############################# # diff --git a/setup.py b/setup.py index ce7eba8..55b618b 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ name='woad', python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, !=3.6.*, !=3.7.*', - version='0.0.1', + version='0.1.0-alpha1', author='Matt Wilson', author_email='matthew@synesis.com.au', diff --git a/tests/test_woad.py b/tests/test_woad.py index 9ed9b3a..18aaf5f 100644 --- a/tests/test_woad.py +++ b/tests/test_woad.py @@ -1,18 +1,84 @@ +import os import unittest import woad +_MANAGED = ( + 'CLICOLOR', + 'CLICOLOR_FORCE', + 'FORCE_COLOR', + 'NO_COLOR', + 'TERM', + 'WOAD_COLOR', + 'WOAD_COLOUR', +) + + +class _Terminal(object): + + def isatty(self): + + return True + + +class _File(object): + + def isatty(self): + + return False + + +def _saved_environment(): + + saved = {} + + for name in _MANAGED: + if name in os.environ: + saved[name] = os.environ[name] + else: + saved[name] = None + + return saved + + +def _restore_environment(saved): + + for name in _MANAGED: + value = saved[name] + + if value is None: + if name in os.environ: + del os.environ[name] + else: + os.environ[name] = value + + +def _clear_managed(): + + for name in _MANAGED: + if name in os.environ: + del os.environ[name] + + class Test_woad(unittest.TestCase): def test_version(self): - self.assertEqual('0.0.1', woad.__version__) + self.assertEqual('0.1.0-alpha1', woad.__version__) def test_RESET(self): self.assertEqual('\033[0m', woad.RESET) + def test_BOLD(self): + + self.assertEqual('\033[1m', woad.BOLD) + + def test_BLINKING(self): + + self.assertEqual('\033[5m', woad.BLINKING) + def test_FG_RED(self): self.assertEqual('\033[31m', woad.FG_RED) @@ -27,6 +93,9 @@ def test_all_codes_are_csi_sgr(self): code = getattr(woad, name) + if not isinstance(code, type(woad.RESET)): + continue + self.assertTrue( code.startswith('\033['), name, @@ -35,3 +104,189 @@ def test_all_codes_are_csi_sgr(self): code.endswith('m'), name, ) + + +class Test_policy(unittest.TestCase): + + def setUp(self): + + self._saved = _saved_environment() + self._terminal = _Terminal() + self._file = _File() + _clear_managed() + woad.refresh() + + def tearDown(self): + + _restore_environment(self._saved) + woad.refresh() + + def _assign(self, pairs): + + _clear_managed() + + for name, value in pairs: + os.environ[name] = value + + woad.refresh() + + def _expect(self, attachment, policy, colour): + + stream = self._terminal if attachment else self._file + + self.assertEqual(policy, woad.colour_policy()) + self.assertEqual(colour, woad.supports_colour(stream)) + + sequence = woad.seq_for(stream, woad.FG_GREEN) + + if colour: + self.assertEqual(woad.FG_GREEN, sequence) + else: + self.assertEqual('', sequence) + + def test_row_01_none_terminal(self): + + self._assign(()) + self._expect(True, 0, True) + + def test_row_02_none_file(self): + + self._assign(()) + self._expect(False, 0, False) + + def test_row_03_term_dumb(self): + + self._assign((('TERM', 'dumb'),)) + self._expect(True, 0, False) + + def test_row_04_term_DUMB(self): + + self._assign((('TERM', 'DUMB'),)) + self._expect(True, 0, False) + + def test_row_05_woad_colour_1(self): + + self._assign((('WOAD_COLOUR', '1'),)) + self._expect(False, 1, True) + + def test_row_06_woad_color_always(self): + + self._assign((('WOAD_COLOR', 'always'),)) + self._expect(False, 1, True) + + def test_row_07_woad_colour_never(self): + + self._assign((('WOAD_COLOUR', 'never'),)) + self._expect(True, 2, False) + + def test_row_08_woad_colour_auto_terminal(self): + + self._assign((('WOAD_COLOUR', 'auto'),)) + self._expect(True, 0, True) + + def test_row_09_woad_colour_auto_file(self): + + self._assign((('WOAD_COLOUR', 'auto'),)) + self._expect(False, 0, False) + + def test_row_10_woad_colour_purple(self): + + self._assign((('WOAD_COLOUR', 'purple'),)) + self._expect(True, 0, True) + + def test_row_11_no_color_beats_clicolor_force(self): + + self._assign(( + ('CLICOLOR_FORCE', '1'), + ('NO_COLOR', '1'), + )) + self._expect(True, 2, False) + + def test_row_12_clicolor_force(self): + + self._assign((('CLICOLOR_FORCE', '1'),)) + self._expect(False, 1, True) + + def test_row_13_clicolor_force_0_then_clicolor_0(self): + + self._assign(( + ('CLICOLOR', '0'), + ('CLICOLOR_FORCE', '0'), + )) + self._expect(True, 2, False) + + def test_row_14_force_color(self): + + self._assign((('FORCE_COLOR', '1'),)) + self._expect(False, 1, True) + + def test_row_15_force_color_false_then_clicolor_0(self): + + self._assign(( + ('CLICOLOR', '0'), + ('FORCE_COLOR', 'false'), + )) + self._expect(True, 2, False) + + def test_row_16_force_color_FALSE(self): + + self._assign((('FORCE_COLOR', 'FALSE'),)) + self._expect(False, 0, False) + + def test_row_17_force_color_0(self): + + self._assign((('FORCE_COLOR', '0'),)) + self._expect(True, 0, True) + + def test_row_18_clicolor_0(self): + + self._assign((('CLICOLOR', '0'),)) + self._expect(True, 2, False) + + def test_row_19_clicolor_1(self): + + self._assign((('CLICOLOR', '1'),)) + self._expect(True, 0, True) + + def test_row_20_empty_woad_colour_falls_through(self): + + self._assign(( + ('NO_COLOR', '1'), + ('WOAD_COLOUR', ''), + )) + self._expect(True, 2, False) + + def test_row_21_empty_no_color_is_absent(self): + + self._assign((('NO_COLOR', ''),)) + self._expect(True, 0, True) + + def test_row_22_refresh_drops_the_cache(self): + + os.environ['WOAD_COLOUR'] = '1' + woad.refresh() + self.assertEqual(1, woad.colour_policy()) + + woad.refresh() + del os.environ['WOAD_COLOUR'] + os.environ['NO_COLOR'] = '1' + + self._expect(True, 2, False) + + def test_seq_for_none_is_empty(self): + + self._assign((('WOAD_COLOUR', '1'),)) + self.assertEqual('', woad.seq_for(self._terminal, None)) + + def test_missing_isatty_is_not_a_terminal(self): + + self._assign(()) + self.assertFalse(woad.supports_colour(object())) + + def test_force_ignores_term_dumb(self): + + self._assign(( + ('TERM', 'dumb'), + ('WOAD_COLOUR', '1'), + )) + self._expect(False, 1, True) diff --git a/woad/__init__.py b/woad/__init__.py index 4210930..525401c 100644 --- a/woad/__init__.py +++ b/woad/__init__.py @@ -3,6 +3,9 @@ Minimal ANSI terminal colour codes, for Python. """ +import os +import threading + __author__ = 'Matt Wilson' __copyright__ = 'Copyright 2026, Synesis Information Systems' __credits__ = [ @@ -12,7 +15,13 @@ __license__ = 'BSD-3-Clause' __maintainer__ = 'Matt Wilson' __status__ = 'Alpha' -__version__ = '0.0.1' +__version__ = '0.1.0-alpha1' + + +# Attributes + +BLINKING = '\033[5m' +BOLD = '\033[1m' # Reset @@ -68,6 +77,210 @@ BG_BRIGHT_WHITE = '\033[107m' +# Colour policy. The values are the woad 0.3.0 discriminants. + +COLOUR_POLICY_AUTO = 0 +COLOUR_POLICY_FORCE = 1 +COLOUR_POLICY_INHIBIT = 2 + + +_FALSEY = ( + '0', + 'false', + 'never', + 'no', + 'none', + 'off', +) +_TRUEY = ( + '1', + 'always', + 'force', + 'on', + 'true', + 'yes', +) + +_lock = threading.Lock() +_determined = False +_policy = COLOUR_POLICY_AUTO +_term_is_dumb = False + + +def _nonempty(name): + """The environment value when the variable is set and not empty.""" + + if name not in os.environ: + return None + + value = os.environ[name] + + if value == '': + return None + + return value + + +def _listed(value, tokens): + """Whether value equals one of tokens, ignoring case.""" + + folded = value.lower() + + for token in tokens: + if folded == token: + return True + + return False + + +def _policy_from_environment(): + """The colour policy from the current environment, ignoring the cache.""" + + value = _nonempty('WOAD_COLOUR') + + if value is None: + value = _nonempty('WOAD_COLOR') + + if value is not None: + if _listed(value, _TRUEY): + return COLOUR_POLICY_FORCE + elif _listed(value, _FALSEY): + return COLOUR_POLICY_INHIBIT + else: + return COLOUR_POLICY_AUTO + + if _nonempty('NO_COLOR') is not None: + return COLOUR_POLICY_INHIBIT + + value = _nonempty('CLICOLOR_FORCE') + + if value is not None and value != '0': + return COLOUR_POLICY_FORCE + + value = _nonempty('FORCE_COLOR') + + if value is not None and value != '0' and value.lower() != 'false': + return COLOUR_POLICY_FORCE + + value = _nonempty('CLICOLOR') + + if value is not None and value == '0': + return COLOUR_POLICY_INHIBIT + + return COLOUR_POLICY_AUTO + + +def _term_is_dumb_from_environment(): + """Whether TERM equals dumb, ignoring case. Absent or empty is not dumb.""" + + value = _nonempty('TERM') + + if value is None: + return False + + return value.lower() == 'dumb' + + +def _ensure(): + """Fills the cache when it has been dropped. Caller holds _lock.""" + + global _determined + global _policy + global _term_is_dumb + + if not _determined: + _policy = _policy_from_environment() + _term_is_dumb = _term_is_dumb_from_environment() + _determined = True + + +def _colour_state(): + """The cached policy and the cached TERM=dumb flag.""" + + _lock.acquire() + + try: + _ensure() + + return _policy, _term_is_dumb + finally: + _lock.release() + + +def _attached(stream): + """True only when stream.isatty exists and returns true.""" + + isatty = getattr(stream, 'isatty', None) + + if not callable(isatty): + return False + + try: + return True if isatty() else False + except Exception: + return False + + +def colour_policy(): + """The cached colour policy: 0 auto, 1 force, 2 inhibit. + + An unset or empty variable is absent. Values are not trimmed. The + first match wins: non-empty WOAD_COLOUR, else non-empty WOAD_COLOR + (truey forces, falsey inhibits, anything else selects auto and does + not fall through); non-empty NO_COLOR inhibits; non-empty + CLICOLOR_FORCE other than the exact bytes 0 forces; non-empty + FORCE_COLOR other than exact 0 or false (any capitalisation) forces; + CLICOLOR equal to the exact bytes 0 inhibits; otherwise auto. + """ + + policy, _ignored = _colour_state() + + return policy + + +def refresh(): + """Drops the cached policy and the cached TERM=dumb flag. + + The next query reads the environment again. On Unix there is no + console cache to drop. + """ + + global _determined + + _lock.acquire() + + try: + _determined = False + finally: + _lock.release() + + +def supports_colour(stream): + """Whether colour should be emitted for this file object. + + Force is yes for every object. Inhibit is no for every object. + Auto is yes only when the object is a terminal and TERM is not dumb. + """ + + policy, term_is_dumb = _colour_state() + + if policy == COLOUR_POLICY_FORCE: + return True + elif policy == COLOUR_POLICY_INHIBIT: + return False + else: + return _attached(stream) and not term_is_dumb + + +def seq_for(stream, sequence): + """The sequence when the stream supports colour; otherwise ''.""" + + if sequence is None or not supports_colour(stream): + return '' + + return sequence + + __all__ = [ 'BG_BLACK', 'BG_BLUE', @@ -85,6 +298,11 @@ 'BG_RED', 'BG_WHITE', 'BG_YELLOW', + 'BLINKING', + 'BOLD', + 'COLOUR_POLICY_AUTO', + 'COLOUR_POLICY_FORCE', + 'COLOUR_POLICY_INHIBIT', 'FG_BLACK', 'FG_BLUE', 'FG_BRIGHT_BLACK', @@ -102,4 +320,8 @@ 'FG_WHITE', 'FG_YELLOW', 'RESET', + 'colour_policy', + 'refresh', + 'seq_for', + 'supports_colour', ] From 77821d729fbfd687fd2db8ee03f9d087102a3f9c Mon Sep 17 00:00:00 2001 From: Matt Wilson Date: Tue, 17 Nov 2026 08:13:11 +1100 Subject: [PATCH 2/2] ci(woad.Python): run Python 3.8 and 3.9 on ubuntu-24.04 setup-python has no 3.8 or 3.9 build for Ubuntu 26.04, so those matrix cells fail on ubuntu-latest. Keep the 3.8 floor by pinning only those two cells to ubuntu-24.04. --- .github/workflows/python-package.yml | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 67e7326..7a202d8 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -51,18 +51,26 @@ jobs: build: - runs-on: ubuntu-latest + # 3.8 and 3.9 have no setup-python build for Ubuntu 26.04 + # (ubuntu-latest). Those cells stay on ubuntu-24.04 so the 3.8 floor + # remains exercised. + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: + os: + - ubuntu-latest python-version: - - "3.8" - - "3.9" - "3.10" - "3.11" - "3.12" - "3.13" - "3.14" + include: + - os: ubuntu-24.04 + python-version: "3.8" + - os: ubuntu-24.04 + python-version: "3.9" steps: - name: Checking out code