sgrs 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sgrs-0.1.0/LICENSE +21 -0
- sgrs-0.1.0/MANIFEST.in +3 -0
- sgrs-0.1.0/PKG-INFO +103 -0
- sgrs-0.1.0/PUBLISHING.md +151 -0
- sgrs-0.1.0/README.md +87 -0
- sgrs-0.1.0/examples/colored_logging.py +48 -0
- sgrs-0.1.0/pyproject.toml +28 -0
- sgrs-0.1.0/setup.cfg +4 -0
- sgrs-0.1.0/src/sgrs/__init__.py +219 -0
- sgrs-0.1.0/src/sgrs/__main__.py +19 -0
- sgrs-0.1.0/src/sgrs/py.typed +0 -0
- sgrs-0.1.0/src/sgrs.egg-info/PKG-INFO +103 -0
- sgrs-0.1.0/src/sgrs.egg-info/SOURCES.txt +16 -0
- sgrs-0.1.0/src/sgrs.egg-info/dependency_links.txt +1 -0
- sgrs-0.1.0/src/sgrs.egg-info/top_level.txt +1 -0
- sgrs-0.1.0/tests/test_logging.py +46 -0
- sgrs-0.1.0/tests/test_sgr.py +114 -0
sgrs-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Jae
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
sgrs-0.1.0/MANIFEST.in
ADDED
sgrs-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sgrs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed, composable ANSI SGR styles for terminal text
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/j-w-yun/sgrs
|
|
7
|
+
Keywords: ansi,colors,sgr,terminal
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Topic :: Terminals
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# sgrs
|
|
18
|
+
|
|
19
|
+
Compose ANSI Select Graphic Rendition (SGR) styles as typed, immutable Python values. Requires Python 3.10 or newer and has zero runtime dependencies.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from typing import Final
|
|
23
|
+
|
|
24
|
+
from sgrs import SGR
|
|
25
|
+
|
|
26
|
+
ERROR: Final[SGR] = SGR.BOLD + SGR.RED
|
|
27
|
+
CRITICAL: Final[SGR] = SGR.BG_RED + SGR.BRIGHT_WHITE
|
|
28
|
+
|
|
29
|
+
print(ERROR.wrap('Connection refused'))
|
|
30
|
+
print(CRITICAL.wrap('Service unavailable'))
|
|
31
|
+
assert str(ERROR) == '\x1b[1;31m'
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
To install from this checkout, run the following command in the repository root.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
python -m pip install .
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Once the package is published on PyPI, install it by name.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install sgrs
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Run `python -m sgrs` to see every named style, its escaped representation, and a sample. The preview applies colors on a terminal and respects a nonempty `NO_COLOR` and `TERM=dumb`.
|
|
49
|
+
|
|
50
|
+
## Compose, render, or wrap
|
|
51
|
+
|
|
52
|
+
| Expression | Type | Result |
|
|
53
|
+
| --- | --- | --- |
|
|
54
|
+
| `SGR.BOLD + SGR.RED` | `SGR` | One sequence with parameters `(1, 31)` |
|
|
55
|
+
| `SGR(codes=(1, 31))` | `SGR` | The same value, created from raw parameters |
|
|
56
|
+
| `str(SGR.RED)` | `str` | The terminal sequence `'\x1b[31m'` |
|
|
57
|
+
| `repr(SGR.RED)` | `str` | The debugging representation `'SGR(codes=(31,))'` |
|
|
58
|
+
| `ascii(str(SGR.RED))` | `str` | A quoted, escaped string suitable for displaying the sequence |
|
|
59
|
+
| `SGR.RED + 'text' + SGR.RESET` | `str` | Text with an explicitly placed reset |
|
|
60
|
+
| `SGR.RED.wrap('text')` | `str` | Red text followed by a full reset |
|
|
61
|
+
| `SGR().wrap('text')` | `str` | Plain text with no escape sequences |
|
|
62
|
+
|
|
63
|
+
An empty style is false and composes as an identity. `SGR.RESET` is true and sends parameter 0. Composition preserves order and duplicates, including resets and extended-color parameters. Styles compare and hash by their parameter tuples. Each style renders its escape string once at construction, so precomposed values work well in a hot logging path.
|
|
64
|
+
|
|
65
|
+
`wrap('')` returns an empty string. A full reset clears the terminal's active attributes. To resume an outer style after a differently styled span, emit that outer style again. A wrapped string preserves embedded escape sequences.
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
outer: SGR = SGR.GREEN
|
|
69
|
+
inner: SGR = SGR.BOLD + SGR.RED
|
|
70
|
+
print(f'{outer}job {inner.wrap("failed")}{outer}, retrying{SGR.RESET}')
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Attributes and colors
|
|
74
|
+
|
|
75
|
+
- Named attributes include `BOLD`, `FAINT`, `ITALIC`, `UNDERLINE`, `BLINK`, `REVERSE`, `HIDDEN`, and `STRIKETHROUGH`. Use `NORMAL_INTENSITY` to turn off both bold and faint. The other attributes have individual switches such as `NO_ITALIC` and `NO_UNDERLINE`.
|
|
76
|
+
- The eight base colors are `BLACK`, `RED`, `GREEN`, `YELLOW`, `BLUE`, `MAGENTA`, `CYAN`, and `WHITE`. Use prefixes such as `BRIGHT_RED`, `BG_RED`, and `BG_BRIGHT_RED`. `DEFAULT` and `BG_DEFAULT` restore the terminal's foreground and background defaults respectively.
|
|
77
|
+
- Use `SGR.fg_index(208)` or `SGR.bg_index(17)` for a palette index. Use `SGR.fg_rgb(255, 128, 0)` or `SGR.bg_rgb(24, 24, 24)` for true color. Index and channel values accept built-in integers from 0 through 255. Wrong types, including booleans, raise `TypeError`. Out-of-range integers raise `ValueError`.
|
|
78
|
+
- The raw constructor accepts a tuple of non-negative built-in integers. This supports terminal-specific parameters. Interpretation and color support depend on the receiving terminal.
|
|
79
|
+
|
|
80
|
+
## Logging
|
|
81
|
+
|
|
82
|
+
Keep the template and its arguments on the shared log record. Apply the style after the standard formatter has interpolated the message and added exception or stack text.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import logging
|
|
86
|
+
from typing import Final
|
|
87
|
+
|
|
88
|
+
from sgrs import SGR
|
|
89
|
+
|
|
90
|
+
_LEVEL_STYLES: Final[dict[int, SGR]] = {
|
|
91
|
+
logging.WARNING: SGR.YELLOW,
|
|
92
|
+
logging.ERROR: SGR.RED,
|
|
93
|
+
logging.CRITICAL: SGR.BG_RED + SGR.WHITE,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
class ColoredFormatter(logging.Formatter):
|
|
97
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
98
|
+
text = super().format(record)
|
|
99
|
+
style = _LEVEL_STYLES.get(record.levelno)
|
|
100
|
+
return style.wrap(text) if style is not None else text
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Use `ColoredFormatter('[{levelname}] {message}', style='{')` on a terminal handler. A plain formatter on a file handler can receive the same record. The source distribution includes a runnable example in `examples/colored_logging.py`, tests, and the manual release guide in `PUBLISHING.md`.
|
sgrs-0.1.0/PUBLISHING.md
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
# Build and publish sgrs
|
|
2
|
+
|
|
3
|
+
These Bash commands build and publish the package on Linux or macOS. Use Python 3.10 or newer.
|
|
4
|
+
|
|
5
|
+
## 1. Start with the source tree
|
|
6
|
+
|
|
7
|
+
Run the release commands from the repository root. For a fresh checkout, use the following commands.
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
git clone https://github.com/j-w-yun/sgrs
|
|
11
|
+
cd sgrs
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
To rebuild from a source archive, unpack it and enter its top-level directory instead.
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
tar -xzf sgrs-0.1.0.tar.gz
|
|
18
|
+
cd sgrs-0.1.0
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
| Path | Role |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| `src/sgrs/__init__.py` | Public implementation. Exports the typed `SGR` class. |
|
|
24
|
+
| `src/sgrs/__main__.py` | Preview invoked by `python -m sgrs`. |
|
|
25
|
+
| `src/sgrs/py.typed` | Empty marker that exposes inline types to downstream tooling. |
|
|
26
|
+
| `pyproject.toml` | Distribution name, version, supported Python, runtime dependencies, and setuptools build backend. |
|
|
27
|
+
| `README.md` | Documentation used as the PyPI project description. |
|
|
28
|
+
| `MANIFEST.in` | Includes this guide, tests and the runnable example in the source distribution. |
|
|
29
|
+
| `examples/`, `tests/` | Logging integration and regression tests. |
|
|
30
|
+
|
|
31
|
+
The wheel contains the runtime package, its typing marker and installation metadata. The source archive also gives maintainers the materials needed to rebuild it. A `setup.py` is unnecessary.
|
|
32
|
+
|
|
33
|
+
## 2. Review the release metadata
|
|
34
|
+
|
|
35
|
+
The distribution name in `pyproject.toml` is `sgrs`, its public import is `from sgrs import SGR`, and its initial version is `0.1.0`. Review the version and description before building. The project metadata identifies the GitHub repository and declares the MIT license included in `LICENSE`.
|
|
36
|
+
|
|
37
|
+
See [Choosing a project name](https://docs.pypi.org/project-management/choosing-a-name/) and [writing pyproject.toml](https://packaging.python.org/en/latest/guides/writing-pyproject-toml/).
|
|
38
|
+
|
|
39
|
+
## 3. Set up the release environment and run tests
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
python3 -m venv .venv
|
|
43
|
+
source .venv/bin/activate
|
|
44
|
+
python -m pip install --upgrade pip build twine
|
|
45
|
+
python -m pip install -e .
|
|
46
|
+
python -m unittest discover -s tests -v
|
|
47
|
+
python examples/colored_logging.py
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## 4. Build and check both artifacts
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
python -m build
|
|
54
|
+
artifacts=(dist/sgrs-0.1.0.tar.gz dist/sgrs-0.1.0-py3-none-any.whl)
|
|
55
|
+
python -m twine check --strict "${artifacts[@]}"
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
The default build creates an sdist, then builds a pure-Python wheel from that sdist. Use these exact release files for both uploads. This also avoids uploading stale versions from `dist/`.
|
|
59
|
+
|
|
60
|
+
Test the built wheel in a fresh environment. Running from a `src/` layout lets these tests import the installed copy.
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
python -m venv .wheel-test
|
|
64
|
+
.wheel-test/bin/python -m pip install --no-index --find-links=dist --only-binary=:all: 'sgrs==0.1.0'
|
|
65
|
+
.wheel-test/bin/python -m unittest discover -s tests -v
|
|
66
|
+
.wheel-test/bin/python -m sgrs
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
See [PyPA packaging tutorial](https://packaging.python.org/en/latest/tutorials/packaging-projects/).
|
|
70
|
+
|
|
71
|
+
## 5. Upload to TestPyPI and install from the index
|
|
72
|
+
|
|
73
|
+
Register on TestPyPI, verify your email, complete account security setup and create a TestPyPI API token. For a first manual upload of a new project, create an account-scoped token. Supply the token, including its `pypi-` prefix, at Twine's hidden token prompt. Subsequent releases can use a project-scoped token.
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
python -m twine upload --repository testpypi "${artifacts[@]}"
|
|
77
|
+
python -m venv .testpypi-test
|
|
78
|
+
.testpypi-test/bin/python -m pip install --no-cache-dir --no-deps --only-binary=:all: \
|
|
79
|
+
--index-url https://test.pypi.org/simple/ 'sgrs==0.1.0'
|
|
80
|
+
.testpypi-test/bin/python -m unittest discover -s tests -v
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The second environment exercises the uploaded wheel. The package has zero runtime dependencies, so TestPyPI is the only index needed for this step.
|
|
84
|
+
|
|
85
|
+
See [TestPyPI account](https://test.pypi.org/account/register/), [TestPyPI tokens](https://test.pypi.org/manage/account/#api-tokens), and [using TestPyPI](https://packaging.python.org/en/latest/guides/using-testpypi/).
|
|
86
|
+
|
|
87
|
+
## 6. Publish the same artifacts to PyPI
|
|
88
|
+
|
|
89
|
+
Create or sign in to your production PyPI account. Verify your email, complete its security setup, and create a separate PyPI token. From the same shell, upload the exact archives you tested.
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
python -m twine upload --repository pypi "${artifacts[@]}"
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Supply the production token at the prompt. After creating the project, switch to a project-scoped token for future manual releases and revoke the bootstrap token if it was created just for this release. For CI, PyPI also supports Trusted Publishing using short-lived credentials.
|
|
96
|
+
|
|
97
|
+
See [PyPI tokens](https://pypi.org/manage/account/#api-tokens) and [Trusted Publishing](https://docs.pypi.org/trusted-publishers/).
|
|
98
|
+
|
|
99
|
+
## 7. Install on client machines
|
|
100
|
+
|
|
101
|
+
In the application's virtual environment, install the release and run an independent smoke check.
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
python -m pip install 'sgrs==0.1.0'
|
|
105
|
+
python -c "from sgrs import SGR; assert (SGR.BOLD + SGR.RED).codes == (1, 31)"
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
For the latest compatible version, use `python -m pip install --upgrade sgrs`. For each subsequent release, increment `[project].version`, update the release filenames and pinned commands, and repeat from testing. PyPI does not allow reusing an uploaded filename.
|
|
109
|
+
|
|
110
|
+
---
|
|
111
|
+
|
|
112
|
+
# Check the saved PyPI API token
|
|
113
|
+
|
|
114
|
+
On the machine that has `/home/jae/.pypirc`, activate your packaging virtual environment and install the tools:
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
source .venv/bin/activate
|
|
118
|
+
python -m pip install pypitoken twine build
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Run this locally. It reads the `[pypi]` section, checks that its upload destination is production PyPI, and prints only the token's domain and identifier.
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
python - <<'PY'
|
|
125
|
+
from configparser import ConfigParser, Error
|
|
126
|
+
from pathlib import Path
|
|
127
|
+
|
|
128
|
+
from pypitoken import LoaderError, Token
|
|
129
|
+
|
|
130
|
+
path = Path('/home/jae/.pypirc')
|
|
131
|
+
config = ConfigParser(interpolation=None)
|
|
132
|
+
upload_url = 'https://upload.pypi.org/legacy/'
|
|
133
|
+
|
|
134
|
+
try:
|
|
135
|
+
with path.open(encoding='utf-8') as file:
|
|
136
|
+
config.read_file(file)
|
|
137
|
+
|
|
138
|
+
section = config['pypi']
|
|
139
|
+
if section.get('repository', upload_url).rstrip('/') != upload_url.rstrip('/'):
|
|
140
|
+
raise SystemExit('The [pypi] section points to a different upload destination.')
|
|
141
|
+
|
|
142
|
+
token = Token.load(section['password'].strip())
|
|
143
|
+
except (OSError, UnicodeError, Error, KeyError, LoaderError):
|
|
144
|
+
raise SystemExit('Could not read a PyPI API token from [pypi] password.') from None
|
|
145
|
+
|
|
146
|
+
print('Token domain:', token.domain)
|
|
147
|
+
print('Token identifier:', token.identifier)
|
|
148
|
+
PY
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
Check if the `Token identifier` matches the one shown at https://pypi.org/manage/account/
|
sgrs-0.1.0/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# sgrs
|
|
2
|
+
|
|
3
|
+
Compose ANSI Select Graphic Rendition (SGR) styles as typed, immutable Python values. Requires Python 3.10 or newer and has zero runtime dependencies.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from typing import Final
|
|
7
|
+
|
|
8
|
+
from sgrs import SGR
|
|
9
|
+
|
|
10
|
+
ERROR: Final[SGR] = SGR.BOLD + SGR.RED
|
|
11
|
+
CRITICAL: Final[SGR] = SGR.BG_RED + SGR.BRIGHT_WHITE
|
|
12
|
+
|
|
13
|
+
print(ERROR.wrap('Connection refused'))
|
|
14
|
+
print(CRITICAL.wrap('Service unavailable'))
|
|
15
|
+
assert str(ERROR) == '\x1b[1;31m'
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Install
|
|
19
|
+
|
|
20
|
+
To install from this checkout, run the following command in the repository root.
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
python -m pip install .
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Once the package is published on PyPI, install it by name.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install sgrs
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Run `python -m sgrs` to see every named style, its escaped representation, and a sample. The preview applies colors on a terminal and respects a nonempty `NO_COLOR` and `TERM=dumb`.
|
|
33
|
+
|
|
34
|
+
## Compose, render, or wrap
|
|
35
|
+
|
|
36
|
+
| Expression | Type | Result |
|
|
37
|
+
| --- | --- | --- |
|
|
38
|
+
| `SGR.BOLD + SGR.RED` | `SGR` | One sequence with parameters `(1, 31)` |
|
|
39
|
+
| `SGR(codes=(1, 31))` | `SGR` | The same value, created from raw parameters |
|
|
40
|
+
| `str(SGR.RED)` | `str` | The terminal sequence `'\x1b[31m'` |
|
|
41
|
+
| `repr(SGR.RED)` | `str` | The debugging representation `'SGR(codes=(31,))'` |
|
|
42
|
+
| `ascii(str(SGR.RED))` | `str` | A quoted, escaped string suitable for displaying the sequence |
|
|
43
|
+
| `SGR.RED + 'text' + SGR.RESET` | `str` | Text with an explicitly placed reset |
|
|
44
|
+
| `SGR.RED.wrap('text')` | `str` | Red text followed by a full reset |
|
|
45
|
+
| `SGR().wrap('text')` | `str` | Plain text with no escape sequences |
|
|
46
|
+
|
|
47
|
+
An empty style is false and composes as an identity. `SGR.RESET` is true and sends parameter 0. Composition preserves order and duplicates, including resets and extended-color parameters. Styles compare and hash by their parameter tuples. Each style renders its escape string once at construction, so precomposed values work well in a hot logging path.
|
|
48
|
+
|
|
49
|
+
`wrap('')` returns an empty string. A full reset clears the terminal's active attributes. To resume an outer style after a differently styled span, emit that outer style again. A wrapped string preserves embedded escape sequences.
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
outer: SGR = SGR.GREEN
|
|
53
|
+
inner: SGR = SGR.BOLD + SGR.RED
|
|
54
|
+
print(f'{outer}job {inner.wrap("failed")}{outer}, retrying{SGR.RESET}')
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Attributes and colors
|
|
58
|
+
|
|
59
|
+
- Named attributes include `BOLD`, `FAINT`, `ITALIC`, `UNDERLINE`, `BLINK`, `REVERSE`, `HIDDEN`, and `STRIKETHROUGH`. Use `NORMAL_INTENSITY` to turn off both bold and faint. The other attributes have individual switches such as `NO_ITALIC` and `NO_UNDERLINE`.
|
|
60
|
+
- The eight base colors are `BLACK`, `RED`, `GREEN`, `YELLOW`, `BLUE`, `MAGENTA`, `CYAN`, and `WHITE`. Use prefixes such as `BRIGHT_RED`, `BG_RED`, and `BG_BRIGHT_RED`. `DEFAULT` and `BG_DEFAULT` restore the terminal's foreground and background defaults respectively.
|
|
61
|
+
- Use `SGR.fg_index(208)` or `SGR.bg_index(17)` for a palette index. Use `SGR.fg_rgb(255, 128, 0)` or `SGR.bg_rgb(24, 24, 24)` for true color. Index and channel values accept built-in integers from 0 through 255. Wrong types, including booleans, raise `TypeError`. Out-of-range integers raise `ValueError`.
|
|
62
|
+
- The raw constructor accepts a tuple of non-negative built-in integers. This supports terminal-specific parameters. Interpretation and color support depend on the receiving terminal.
|
|
63
|
+
|
|
64
|
+
## Logging
|
|
65
|
+
|
|
66
|
+
Keep the template and its arguments on the shared log record. Apply the style after the standard formatter has interpolated the message and added exception or stack text.
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
import logging
|
|
70
|
+
from typing import Final
|
|
71
|
+
|
|
72
|
+
from sgrs import SGR
|
|
73
|
+
|
|
74
|
+
_LEVEL_STYLES: Final[dict[int, SGR]] = {
|
|
75
|
+
logging.WARNING: SGR.YELLOW,
|
|
76
|
+
logging.ERROR: SGR.RED,
|
|
77
|
+
logging.CRITICAL: SGR.BG_RED + SGR.WHITE,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
class ColoredFormatter(logging.Formatter):
|
|
81
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
82
|
+
text = super().format(record)
|
|
83
|
+
style = _LEVEL_STYLES.get(record.levelno)
|
|
84
|
+
return style.wrap(text) if style is not None else text
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Use `ColoredFormatter('[{levelname}] {message}', style='{')` on a terminal handler. A plain formatter on a file handler can receive the same record. The source distribution includes a runnable example in `examples/colored_logging.py`, tests, and the manual release guide in `PUBLISHING.md`.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Run with python examples/colored_logging.py after installing the package."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import os
|
|
7
|
+
import sys
|
|
8
|
+
from typing import Final
|
|
9
|
+
|
|
10
|
+
from sgrs import SGR
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
_LEVEL_STYLES: Final[dict[int, SGR]] = {
|
|
14
|
+
logging.DEBUG: SGR.BLUE,
|
|
15
|
+
logging.INFO: SGR.GREEN,
|
|
16
|
+
logging.WARNING: SGR.YELLOW,
|
|
17
|
+
logging.ERROR: SGR.RED,
|
|
18
|
+
logging.CRITICAL: SGR.BG_RED + SGR.WHITE,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ColoredFormatter(logging.Formatter):
|
|
23
|
+
"""Color the complete formatted entry, including any traceback."""
|
|
24
|
+
|
|
25
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
26
|
+
text = super().format(record)
|
|
27
|
+
style = _LEVEL_STYLES.get(record.levelno)
|
|
28
|
+
return style.wrap(text) if style is not None else text
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def main() -> None:
|
|
32
|
+
stream = sys.stderr
|
|
33
|
+
handler = logging.StreamHandler(stream)
|
|
34
|
+
color = stream.isatty() and not os.environ.get('NO_COLOR') and os.environ.get('TERM') != 'dumb'
|
|
35
|
+
formatter = ColoredFormatter if color else logging.Formatter
|
|
36
|
+
handler.setFormatter(formatter('[{levelname:<8}] {message}', style='{'))
|
|
37
|
+
logging.basicConfig(level=logging.DEBUG, handlers=[handler])
|
|
38
|
+
|
|
39
|
+
logger = logging.getLogger(__name__)
|
|
40
|
+
logger.debug('Loaded %d styles', len(_LEVEL_STYLES))
|
|
41
|
+
logger.info('Listening on port %d', 8080)
|
|
42
|
+
logger.warning('Retrying request')
|
|
43
|
+
logger.error('Connection failed')
|
|
44
|
+
logger.critical('Service unavailable')
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
if __name__ == '__main__':
|
|
48
|
+
main()
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "sgrs"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Typed, composable ANSI SGR styles for terminal text"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = []
|
|
13
|
+
keywords = ["ansi", "colors", "sgr", "terminal"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Operating System :: OS Independent",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Topic :: Terminals",
|
|
18
|
+
"Typing :: Typed",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Repository = "https://github.com/j-w-yun/sgrs"
|
|
23
|
+
|
|
24
|
+
[tool.setuptools.packages.find]
|
|
25
|
+
where = ["src"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.package-data]
|
|
28
|
+
sgrs = ["py.typed"]
|
sgrs-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Compose and render ANSI Select Graphic Rendition (SGR) parameters."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__: list[str] = [
|
|
6
|
+
'SGR',
|
|
7
|
+
]
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from types import NotImplementedType
|
|
11
|
+
from typing import ClassVar, Final, final, overload
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_CSI: Final[str] = '\x1b['
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _byte(value: int, name: str) -> int:
|
|
18
|
+
if type(value) is not int:
|
|
19
|
+
raise TypeError(f'{name} must be an integer')
|
|
20
|
+
if not 0 <= value <= 255:
|
|
21
|
+
raise ValueError(f'{name} must be between 0 and 255')
|
|
22
|
+
return value
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@final
|
|
26
|
+
@dataclass(frozen=True, slots=True)
|
|
27
|
+
class SGR:
|
|
28
|
+
"""An immutable, ordered sequence of non-negative integer SGR parameters."""
|
|
29
|
+
|
|
30
|
+
codes: tuple[int, ...] = ()
|
|
31
|
+
_escape: str = field(init=False, repr=False, compare=False)
|
|
32
|
+
|
|
33
|
+
RESET: ClassVar[SGR]
|
|
34
|
+
|
|
35
|
+
BOLD: ClassVar[SGR]
|
|
36
|
+
FAINT: ClassVar[SGR]
|
|
37
|
+
ITALIC: ClassVar[SGR]
|
|
38
|
+
UNDERLINE: ClassVar[SGR]
|
|
39
|
+
BLINK: ClassVar[SGR]
|
|
40
|
+
REVERSE: ClassVar[SGR]
|
|
41
|
+
HIDDEN: ClassVar[SGR]
|
|
42
|
+
STRIKETHROUGH: ClassVar[SGR]
|
|
43
|
+
|
|
44
|
+
NORMAL_INTENSITY: ClassVar[SGR]
|
|
45
|
+
NO_ITALIC: ClassVar[SGR]
|
|
46
|
+
NO_UNDERLINE: ClassVar[SGR]
|
|
47
|
+
NO_BLINK: ClassVar[SGR]
|
|
48
|
+
NO_REVERSE: ClassVar[SGR]
|
|
49
|
+
NO_HIDDEN: ClassVar[SGR]
|
|
50
|
+
NO_STRIKETHROUGH: ClassVar[SGR]
|
|
51
|
+
|
|
52
|
+
DEFAULT: ClassVar[SGR]
|
|
53
|
+
BLACK: ClassVar[SGR]
|
|
54
|
+
RED: ClassVar[SGR]
|
|
55
|
+
GREEN: ClassVar[SGR]
|
|
56
|
+
YELLOW: ClassVar[SGR]
|
|
57
|
+
BLUE: ClassVar[SGR]
|
|
58
|
+
MAGENTA: ClassVar[SGR]
|
|
59
|
+
CYAN: ClassVar[SGR]
|
|
60
|
+
WHITE: ClassVar[SGR]
|
|
61
|
+
BRIGHT_BLACK: ClassVar[SGR]
|
|
62
|
+
BRIGHT_RED: ClassVar[SGR]
|
|
63
|
+
BRIGHT_GREEN: ClassVar[SGR]
|
|
64
|
+
BRIGHT_YELLOW: ClassVar[SGR]
|
|
65
|
+
BRIGHT_BLUE: ClassVar[SGR]
|
|
66
|
+
BRIGHT_MAGENTA: ClassVar[SGR]
|
|
67
|
+
BRIGHT_CYAN: ClassVar[SGR]
|
|
68
|
+
BRIGHT_WHITE: ClassVar[SGR]
|
|
69
|
+
|
|
70
|
+
BG_DEFAULT: ClassVar[SGR]
|
|
71
|
+
BG_BLACK: ClassVar[SGR]
|
|
72
|
+
BG_RED: ClassVar[SGR]
|
|
73
|
+
BG_GREEN: ClassVar[SGR]
|
|
74
|
+
BG_YELLOW: ClassVar[SGR]
|
|
75
|
+
BG_BLUE: ClassVar[SGR]
|
|
76
|
+
BG_MAGENTA: ClassVar[SGR]
|
|
77
|
+
BG_CYAN: ClassVar[SGR]
|
|
78
|
+
BG_WHITE: ClassVar[SGR]
|
|
79
|
+
BG_BRIGHT_BLACK: ClassVar[SGR]
|
|
80
|
+
BG_BRIGHT_RED: ClassVar[SGR]
|
|
81
|
+
BG_BRIGHT_GREEN: ClassVar[SGR]
|
|
82
|
+
BG_BRIGHT_YELLOW: ClassVar[SGR]
|
|
83
|
+
BG_BRIGHT_BLUE: ClassVar[SGR]
|
|
84
|
+
BG_BRIGHT_MAGENTA: ClassVar[SGR]
|
|
85
|
+
BG_BRIGHT_CYAN: ClassVar[SGR]
|
|
86
|
+
BG_BRIGHT_WHITE: ClassVar[SGR]
|
|
87
|
+
|
|
88
|
+
def __post_init__(self) -> None:
|
|
89
|
+
codes = self.codes
|
|
90
|
+
if not isinstance(codes, tuple):
|
|
91
|
+
raise TypeError('codes must be a tuple of integers')
|
|
92
|
+
if type(codes) is not tuple:
|
|
93
|
+
codes = tuple(codes)
|
|
94
|
+
object.__setattr__(self, 'codes', codes)
|
|
95
|
+
for code in codes:
|
|
96
|
+
if type(code) is not int:
|
|
97
|
+
raise TypeError('each SGR parameter must be an integer')
|
|
98
|
+
if code < 0:
|
|
99
|
+
raise ValueError('SGR parameters must be non-negative')
|
|
100
|
+
|
|
101
|
+
parameters = ';'.join(map(str, codes))
|
|
102
|
+
object.__setattr__(self, '_escape', f'{_CSI}{parameters}m' if codes else '')
|
|
103
|
+
|
|
104
|
+
def __bool__(self) -> bool:
|
|
105
|
+
return bool(self.codes)
|
|
106
|
+
|
|
107
|
+
def __str__(self) -> str:
|
|
108
|
+
return self._escape
|
|
109
|
+
|
|
110
|
+
@overload
|
|
111
|
+
def __add__(self, other: SGR, /) -> SGR: ...
|
|
112
|
+
|
|
113
|
+
@overload
|
|
114
|
+
def __add__(self, other: str, /) -> str: ...
|
|
115
|
+
|
|
116
|
+
def __add__(self, other: object, /) -> SGR | str | NotImplementedType:
|
|
117
|
+
if isinstance(other, SGR):
|
|
118
|
+
if not self.codes:
|
|
119
|
+
return other
|
|
120
|
+
if not other.codes:
|
|
121
|
+
return self
|
|
122
|
+
return SGR(self.codes + other.codes)
|
|
123
|
+
if isinstance(other, str):
|
|
124
|
+
return self._escape + other
|
|
125
|
+
return NotImplemented
|
|
126
|
+
|
|
127
|
+
def __radd__(self, other: str, /) -> str:
|
|
128
|
+
if isinstance(other, str):
|
|
129
|
+
return other + self._escape
|
|
130
|
+
return NotImplemented
|
|
131
|
+
|
|
132
|
+
def wrap(self, text: str, /) -> str:
|
|
133
|
+
"""Apply the style to text, ending with a full reset. Empty inputs pass through."""
|
|
134
|
+
if not isinstance(text, str):
|
|
135
|
+
raise TypeError('text must be a string')
|
|
136
|
+
if not self.codes or not text:
|
|
137
|
+
return text
|
|
138
|
+
return f'{self._escape}{text}{SGR.RESET._escape}'
|
|
139
|
+
|
|
140
|
+
@staticmethod
|
|
141
|
+
def fg_index(index: int) -> SGR:
|
|
142
|
+
"""Select a foreground color from the 256-color palette."""
|
|
143
|
+
return SGR((38, 5, _byte(index, 'index')))
|
|
144
|
+
|
|
145
|
+
@staticmethod
|
|
146
|
+
def bg_index(index: int) -> SGR:
|
|
147
|
+
"""Select a background color from the 256-color palette."""
|
|
148
|
+
return SGR((48, 5, _byte(index, 'index')))
|
|
149
|
+
|
|
150
|
+
@staticmethod
|
|
151
|
+
def fg_rgb(red: int, green: int, blue: int) -> SGR:
|
|
152
|
+
"""Select a 24-bit foreground color using RGB channels from 0 to 255."""
|
|
153
|
+
return SGR((38, 2, _byte(red, 'red'), _byte(green, 'green'), _byte(blue, 'blue')))
|
|
154
|
+
|
|
155
|
+
@staticmethod
|
|
156
|
+
def bg_rgb(red: int, green: int, blue: int) -> SGR:
|
|
157
|
+
"""Select a 24-bit background color using RGB channels from 0 to 255."""
|
|
158
|
+
return SGR((48, 2, _byte(red, 'red'), _byte(green, 'green'), _byte(blue, 'blue')))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# Reset
|
|
162
|
+
SGR.RESET = SGR((0,))
|
|
163
|
+
|
|
164
|
+
# Text attributes
|
|
165
|
+
SGR.BOLD = SGR((1,))
|
|
166
|
+
SGR.FAINT = SGR((2,))
|
|
167
|
+
SGR.ITALIC = SGR((3,))
|
|
168
|
+
SGR.UNDERLINE = SGR((4,))
|
|
169
|
+
SGR.BLINK = SGR((5,))
|
|
170
|
+
SGR.REVERSE = SGR((7,))
|
|
171
|
+
SGR.HIDDEN = SGR((8,))
|
|
172
|
+
SGR.STRIKETHROUGH = SGR((9,))
|
|
173
|
+
|
|
174
|
+
# Disable text attributes
|
|
175
|
+
SGR.NORMAL_INTENSITY = SGR((22,))
|
|
176
|
+
SGR.NO_ITALIC = SGR((23,))
|
|
177
|
+
SGR.NO_UNDERLINE = SGR((24,))
|
|
178
|
+
SGR.NO_BLINK = SGR((25,))
|
|
179
|
+
SGR.NO_REVERSE = SGR((27,))
|
|
180
|
+
SGR.NO_HIDDEN = SGR((28,))
|
|
181
|
+
SGR.NO_STRIKETHROUGH = SGR((29,))
|
|
182
|
+
|
|
183
|
+
# Foreground colors
|
|
184
|
+
SGR.DEFAULT = SGR((39,))
|
|
185
|
+
SGR.BLACK = SGR((30,))
|
|
186
|
+
SGR.RED = SGR((31,))
|
|
187
|
+
SGR.GREEN = SGR((32,))
|
|
188
|
+
SGR.YELLOW = SGR((33,))
|
|
189
|
+
SGR.BLUE = SGR((34,))
|
|
190
|
+
SGR.MAGENTA = SGR((35,))
|
|
191
|
+
SGR.CYAN = SGR((36,))
|
|
192
|
+
SGR.WHITE = SGR((37,))
|
|
193
|
+
SGR.BRIGHT_BLACK = SGR((90,))
|
|
194
|
+
SGR.BRIGHT_RED = SGR((91,))
|
|
195
|
+
SGR.BRIGHT_GREEN = SGR((92,))
|
|
196
|
+
SGR.BRIGHT_YELLOW = SGR((93,))
|
|
197
|
+
SGR.BRIGHT_BLUE = SGR((94,))
|
|
198
|
+
SGR.BRIGHT_MAGENTA = SGR((95,))
|
|
199
|
+
SGR.BRIGHT_CYAN = SGR((96,))
|
|
200
|
+
SGR.BRIGHT_WHITE = SGR((97,))
|
|
201
|
+
|
|
202
|
+
# Background colors
|
|
203
|
+
SGR.BG_DEFAULT = SGR((49,))
|
|
204
|
+
SGR.BG_BLACK = SGR((40,))
|
|
205
|
+
SGR.BG_RED = SGR((41,))
|
|
206
|
+
SGR.BG_GREEN = SGR((42,))
|
|
207
|
+
SGR.BG_YELLOW = SGR((43,))
|
|
208
|
+
SGR.BG_BLUE = SGR((44,))
|
|
209
|
+
SGR.BG_MAGENTA = SGR((45,))
|
|
210
|
+
SGR.BG_CYAN = SGR((46,))
|
|
211
|
+
SGR.BG_WHITE = SGR((47,))
|
|
212
|
+
SGR.BG_BRIGHT_BLACK = SGR((100,))
|
|
213
|
+
SGR.BG_BRIGHT_RED = SGR((101,))
|
|
214
|
+
SGR.BG_BRIGHT_GREEN = SGR((102,))
|
|
215
|
+
SGR.BG_BRIGHT_YELLOW = SGR((103,))
|
|
216
|
+
SGR.BG_BRIGHT_BLUE = SGR((104,))
|
|
217
|
+
SGR.BG_BRIGHT_MAGENTA = SGR((105,))
|
|
218
|
+
SGR.BG_BRIGHT_CYAN = SGR((106,))
|
|
219
|
+
SGR.BG_BRIGHT_WHITE = SGR((107,))
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Show named styles and their literal escape sequences with python -m sgrs."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from . import SGR
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main() -> None:
|
|
10
|
+
color = sys.stdout.isatty() and not os.environ.get('NO_COLOR') and os.environ.get('TERM') != 'dumb'
|
|
11
|
+
print(f'{"MEMBER":<22} {"ANSI":<14} EXAMPLE')
|
|
12
|
+
for name, style in vars(SGR).items():
|
|
13
|
+
if isinstance(style, SGR):
|
|
14
|
+
example = style.wrap('Hello world!') if color else 'Hello world!'
|
|
15
|
+
print(f'{name:<22} {ascii(str(style)):<14} {example}')
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
if __name__ == '__main__':
|
|
19
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: sgrs
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Typed, composable ANSI SGR styles for terminal text
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/j-w-yun/sgrs
|
|
7
|
+
Keywords: ansi,colors,sgr,terminal
|
|
8
|
+
Classifier: Operating System :: OS Independent
|
|
9
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
10
|
+
Classifier: Topic :: Terminals
|
|
11
|
+
Classifier: Typing :: Typed
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
License-File: LICENSE
|
|
15
|
+
Dynamic: license-file
|
|
16
|
+
|
|
17
|
+
# sgrs
|
|
18
|
+
|
|
19
|
+
Compose ANSI Select Graphic Rendition (SGR) styles as typed, immutable Python values. Requires Python 3.10 or newer and has zero runtime dependencies.
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from typing import Final
|
|
23
|
+
|
|
24
|
+
from sgrs import SGR
|
|
25
|
+
|
|
26
|
+
ERROR: Final[SGR] = SGR.BOLD + SGR.RED
|
|
27
|
+
CRITICAL: Final[SGR] = SGR.BG_RED + SGR.BRIGHT_WHITE
|
|
28
|
+
|
|
29
|
+
print(ERROR.wrap('Connection refused'))
|
|
30
|
+
print(CRITICAL.wrap('Service unavailable'))
|
|
31
|
+
assert str(ERROR) == '\x1b[1;31m'
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
To install from this checkout, run the following command in the repository root.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
python -m pip install .
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
Once the package is published on PyPI, install it by name.
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install sgrs
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Run `python -m sgrs` to see every named style, its escaped representation, and a sample. The preview applies colors on a terminal and respects a nonempty `NO_COLOR` and `TERM=dumb`.
|
|
49
|
+
|
|
50
|
+
## Compose, render, or wrap
|
|
51
|
+
|
|
52
|
+
| Expression | Type | Result |
|
|
53
|
+
| --- | --- | --- |
|
|
54
|
+
| `SGR.BOLD + SGR.RED` | `SGR` | One sequence with parameters `(1, 31)` |
|
|
55
|
+
| `SGR(codes=(1, 31))` | `SGR` | The same value, created from raw parameters |
|
|
56
|
+
| `str(SGR.RED)` | `str` | The terminal sequence `'\x1b[31m'` |
|
|
57
|
+
| `repr(SGR.RED)` | `str` | The debugging representation `'SGR(codes=(31,))'` |
|
|
58
|
+
| `ascii(str(SGR.RED))` | `str` | A quoted, escaped string suitable for displaying the sequence |
|
|
59
|
+
| `SGR.RED + 'text' + SGR.RESET` | `str` | Text with an explicitly placed reset |
|
|
60
|
+
| `SGR.RED.wrap('text')` | `str` | Red text followed by a full reset |
|
|
61
|
+
| `SGR().wrap('text')` | `str` | Plain text with no escape sequences |
|
|
62
|
+
|
|
63
|
+
An empty style is false and composes as an identity. `SGR.RESET` is true and sends parameter 0. Composition preserves order and duplicates, including resets and extended-color parameters. Styles compare and hash by their parameter tuples. Each style renders its escape string once at construction, so precomposed values work well in a hot logging path.
|
|
64
|
+
|
|
65
|
+
`wrap('')` returns an empty string. A full reset clears the terminal's active attributes. To resume an outer style after a differently styled span, emit that outer style again. A wrapped string preserves embedded escape sequences.
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
outer: SGR = SGR.GREEN
|
|
69
|
+
inner: SGR = SGR.BOLD + SGR.RED
|
|
70
|
+
print(f'{outer}job {inner.wrap("failed")}{outer}, retrying{SGR.RESET}')
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Attributes and colors
|
|
74
|
+
|
|
75
|
+
- Named attributes include `BOLD`, `FAINT`, `ITALIC`, `UNDERLINE`, `BLINK`, `REVERSE`, `HIDDEN`, and `STRIKETHROUGH`. Use `NORMAL_INTENSITY` to turn off both bold and faint. The other attributes have individual switches such as `NO_ITALIC` and `NO_UNDERLINE`.
|
|
76
|
+
- The eight base colors are `BLACK`, `RED`, `GREEN`, `YELLOW`, `BLUE`, `MAGENTA`, `CYAN`, and `WHITE`. Use prefixes such as `BRIGHT_RED`, `BG_RED`, and `BG_BRIGHT_RED`. `DEFAULT` and `BG_DEFAULT` restore the terminal's foreground and background defaults respectively.
|
|
77
|
+
- Use `SGR.fg_index(208)` or `SGR.bg_index(17)` for a palette index. Use `SGR.fg_rgb(255, 128, 0)` or `SGR.bg_rgb(24, 24, 24)` for true color. Index and channel values accept built-in integers from 0 through 255. Wrong types, including booleans, raise `TypeError`. Out-of-range integers raise `ValueError`.
|
|
78
|
+
- The raw constructor accepts a tuple of non-negative built-in integers. This supports terminal-specific parameters. Interpretation and color support depend on the receiving terminal.
|
|
79
|
+
|
|
80
|
+
## Logging
|
|
81
|
+
|
|
82
|
+
Keep the template and its arguments on the shared log record. Apply the style after the standard formatter has interpolated the message and added exception or stack text.
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
import logging
|
|
86
|
+
from typing import Final
|
|
87
|
+
|
|
88
|
+
from sgrs import SGR
|
|
89
|
+
|
|
90
|
+
_LEVEL_STYLES: Final[dict[int, SGR]] = {
|
|
91
|
+
logging.WARNING: SGR.YELLOW,
|
|
92
|
+
logging.ERROR: SGR.RED,
|
|
93
|
+
logging.CRITICAL: SGR.BG_RED + SGR.WHITE,
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
class ColoredFormatter(logging.Formatter):
|
|
97
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
98
|
+
text = super().format(record)
|
|
99
|
+
style = _LEVEL_STYLES.get(record.levelno)
|
|
100
|
+
return style.wrap(text) if style is not None else text
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Use `ColoredFormatter('[{levelname}] {message}', style='{')` on a terminal handler. A plain formatter on a file handler can receive the same record. The source distribution includes a runnable example in `examples/colored_logging.py`, tests, and the manual release guide in `PUBLISHING.md`.
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
MANIFEST.in
|
|
3
|
+
PUBLISHING.md
|
|
4
|
+
README.md
|
|
5
|
+
pyproject.toml
|
|
6
|
+
setup.cfg
|
|
7
|
+
examples/colored_logging.py
|
|
8
|
+
src/sgrs/__init__.py
|
|
9
|
+
src/sgrs/__main__.py
|
|
10
|
+
src/sgrs/py.typed
|
|
11
|
+
src/sgrs.egg-info/PKG-INFO
|
|
12
|
+
src/sgrs.egg-info/SOURCES.txt
|
|
13
|
+
src/sgrs.egg-info/dependency_links.txt
|
|
14
|
+
src/sgrs.egg-info/top_level.txt
|
|
15
|
+
tests/test_logging.py
|
|
16
|
+
tests/test_sgr.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
sgrs
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import logging
|
|
5
|
+
import unittest
|
|
6
|
+
|
|
7
|
+
from examples.colored_logging import ColoredFormatter
|
|
8
|
+
from sgrs import SGR
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class LoggingTests(unittest.TestCase):
|
|
12
|
+
def setUp(self) -> None:
|
|
13
|
+
self.logger = logging.Logger('example')
|
|
14
|
+
self.color = io.StringIO()
|
|
15
|
+
self.plain = io.StringIO()
|
|
16
|
+
for stream, formatter in (
|
|
17
|
+
(self.color, ColoredFormatter()),
|
|
18
|
+
(self.plain, logging.Formatter()),
|
|
19
|
+
):
|
|
20
|
+
handler = logging.StreamHandler(stream)
|
|
21
|
+
handler.setFormatter(formatter)
|
|
22
|
+
self.logger.addHandler(handler)
|
|
23
|
+
self.addCleanup(handler.close)
|
|
24
|
+
|
|
25
|
+
def test_handlers_share_interpolated_message(self) -> None:
|
|
26
|
+
self.logger.info('port %d', 8080)
|
|
27
|
+
self.logger.info('loaded %(count)d%%', {'count': 75})
|
|
28
|
+
lines = ['port 8080', 'loaded 75%']
|
|
29
|
+
self.assertEqual(self.plain.getvalue().splitlines(), lines)
|
|
30
|
+
self.assertEqual(self.color.getvalue().splitlines(), [SGR.GREEN.wrap(line) for line in lines])
|
|
31
|
+
|
|
32
|
+
def test_unknown_level_is_plain(self) -> None:
|
|
33
|
+
self.logger.log(35, 'custom level')
|
|
34
|
+
self.assertEqual(self.color.getvalue(), 'custom level\n')
|
|
35
|
+
self.assertEqual(self.plain.getvalue(), 'custom level\n')
|
|
36
|
+
|
|
37
|
+
def test_traceback_uses_each_handlers_formatter(self) -> None:
|
|
38
|
+
try:
|
|
39
|
+
raise ValueError('sample failure')
|
|
40
|
+
except ValueError:
|
|
41
|
+
self.logger.exception('failed at step %d', 2)
|
|
42
|
+
text = self.plain.getvalue().removesuffix('\n')
|
|
43
|
+
self.assertTrue(text.startswith('failed at step 2\nTraceback'))
|
|
44
|
+
self.assertTrue(text.endswith('ValueError: sample failure'))
|
|
45
|
+
self.assertNotIn('\x1b', text)
|
|
46
|
+
self.assertEqual(self.color.getvalue(), SGR.RED.wrap(text) + '\n')
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import unittest
|
|
4
|
+
from dataclasses import FrozenInstanceError
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from sgrs import SGR
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class SGRTests(unittest.TestCase):
|
|
11
|
+
def test_empty_and_reset(self) -> None:
|
|
12
|
+
self.assertEqual(str(SGR()), '')
|
|
13
|
+
self.assertEqual(str(SGR.RESET), '\x1b[0m')
|
|
14
|
+
self.assertFalse(SGR())
|
|
15
|
+
self.assertTrue(SGR.RESET)
|
|
16
|
+
self.assertNotEqual(SGR(), SGR.RESET)
|
|
17
|
+
self.assertEqual(SGR() + SGR.RED, SGR.RED)
|
|
18
|
+
self.assertEqual(SGR.RED + SGR(), SGR.RED)
|
|
19
|
+
|
|
20
|
+
def test_composition_preserves_order_and_duplicates(self) -> None:
|
|
21
|
+
style = SGR.RED + SGR.RESET + SGR.BOLD + SGR.BOLD + SGR.RED
|
|
22
|
+
self.assertEqual(style.codes, (31, 0, 1, 1, 31))
|
|
23
|
+
self.assertEqual(str(style), '\x1b[31;0;1;1;31m')
|
|
24
|
+
self.assertEqual(SGR.RED.codes, (31,))
|
|
25
|
+
|
|
26
|
+
def test_value_semantics_and_repr(self) -> None:
|
|
27
|
+
style = SGR(codes=(1, 31))
|
|
28
|
+
self.assertEqual({style: 'warning'}[SGR.BOLD + SGR.RED], 'warning')
|
|
29
|
+
self.assertEqual(repr(style), 'SGR(codes=(1, 31))')
|
|
30
|
+
self.assertNotEqual(repr([SGR()]), '[]')
|
|
31
|
+
with self.assertRaises(FrozenInstanceError):
|
|
32
|
+
setattr(style, 'codes', (0,))
|
|
33
|
+
|
|
34
|
+
def test_string_concatenation_and_wrapping(self) -> None:
|
|
35
|
+
self.assertEqual(SGR.RED + 'warning' + SGR.RESET, '\x1b[31mwarning\x1b[0m')
|
|
36
|
+
self.assertEqual('prefix' + SGR.BOLD, 'prefix\x1b[1m')
|
|
37
|
+
style = SGR.BOLD + SGR.RED
|
|
38
|
+
self.assertEqual(style.wrap('warning'), '\x1b[1;31mwarning\x1b[0m')
|
|
39
|
+
self.assertEqual(SGR().wrap('plain'), 'plain')
|
|
40
|
+
self.assertEqual(style.wrap(''), '')
|
|
41
|
+
invalid: Any = b'bytes'
|
|
42
|
+
with self.assertRaises(TypeError):
|
|
43
|
+
SGR().wrap(invalid)
|
|
44
|
+
|
|
45
|
+
def test_unsupported_operands_and_reflected_dispatch(self) -> None:
|
|
46
|
+
class Reflected:
|
|
47
|
+
def __radd__(self, other: SGR, /) -> tuple[int, ...]:
|
|
48
|
+
return other.codes
|
|
49
|
+
|
|
50
|
+
self.assertEqual(SGR.RED + Reflected(), (31,))
|
|
51
|
+
unsupported: Any = 42
|
|
52
|
+
with self.assertRaises(TypeError):
|
|
53
|
+
_ = SGR.BOLD + unsupported
|
|
54
|
+
with self.assertRaises(TypeError):
|
|
55
|
+
_ = unsupported + SGR.BOLD
|
|
56
|
+
|
|
57
|
+
def test_raw_codes_require_nonnegative_builtin_integers(self) -> None:
|
|
58
|
+
class IntSubclass(int):
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
invalid: tuple[Any, ...] = ([1, 31], 31, (True,), ('31',), (1.5,), (IntSubclass(1),))
|
|
62
|
+
for codes in invalid:
|
|
63
|
+
with self.subTest(codes=codes), self.assertRaises(TypeError):
|
|
64
|
+
SGR(codes=codes)
|
|
65
|
+
with self.assertRaises(ValueError):
|
|
66
|
+
SGR(codes=(1, -1))
|
|
67
|
+
self.assertEqual(str(SGR(codes=(999,))), '\x1b[999m')
|
|
68
|
+
|
|
69
|
+
def test_tuple_subclass_is_snapshotted(self) -> None:
|
|
70
|
+
class Params(tuple[int, ...]):
|
|
71
|
+
pass
|
|
72
|
+
|
|
73
|
+
style = SGR(Params((1, 31)))
|
|
74
|
+
self.assertIs(type(style.codes), tuple)
|
|
75
|
+
self.assertEqual(hash(style), hash(SGR.BOLD + SGR.RED))
|
|
76
|
+
|
|
77
|
+
def test_named_attributes_and_colors(self) -> None:
|
|
78
|
+
attributes = {
|
|
79
|
+
'RESET': 0, 'BOLD': 1, 'FAINT': 2, 'ITALIC': 3, 'UNDERLINE': 4,
|
|
80
|
+
'BLINK': 5, 'REVERSE': 7, 'HIDDEN': 8, 'STRIKETHROUGH': 9,
|
|
81
|
+
'NORMAL_INTENSITY': 22, 'NO_ITALIC': 23, 'NO_UNDERLINE': 24,
|
|
82
|
+
'NO_BLINK': 25, 'NO_REVERSE': 27, 'NO_HIDDEN': 28, 'NO_STRIKETHROUGH': 29,
|
|
83
|
+
'DEFAULT': 39, 'BG_DEFAULT': 49,
|
|
84
|
+
}
|
|
85
|
+
colors = ('BLACK', 'RED', 'GREEN', 'YELLOW', 'BLUE', 'MAGENTA', 'CYAN', 'WHITE')
|
|
86
|
+
for prefix, first in (('', 30), ('BG_', 40), ('BRIGHT_', 90), ('BG_BRIGHT_', 100)):
|
|
87
|
+
attributes.update({prefix + name: first + offset for offset, name in enumerate(colors)})
|
|
88
|
+
for name, code in attributes.items():
|
|
89
|
+
with self.subTest(name=name):
|
|
90
|
+
self.assertEqual(getattr(SGR, name), SGR(codes=(code,)))
|
|
91
|
+
|
|
92
|
+
def test_index_and_rgb_encoding(self) -> None:
|
|
93
|
+
self.assertEqual(str(SGR.fg_index(0)), '\x1b[38;5;0m')
|
|
94
|
+
self.assertEqual(str(SGR.bg_index(255)), '\x1b[48;5;255m')
|
|
95
|
+
self.assertEqual(str(SGR.fg_rgb(0, 127, 255)), '\x1b[38;2;0;127;255m')
|
|
96
|
+
self.assertEqual(str(SGR.bg_rgb(255, 128, 0)), '\x1b[48;2;255;128;0m')
|
|
97
|
+
|
|
98
|
+
def test_color_bounds_and_types(self) -> None:
|
|
99
|
+
invalid: tuple[tuple[Any, type[Exception]], ...] = (
|
|
100
|
+
(-1, ValueError), (256, ValueError), (False, TypeError), (1.5, TypeError),
|
|
101
|
+
)
|
|
102
|
+
for value, error in invalid:
|
|
103
|
+
for indexed in (SGR.fg_index, SGR.bg_index):
|
|
104
|
+
with self.subTest(factory=indexed.__name__, value=value), self.assertRaises(error):
|
|
105
|
+
indexed(value)
|
|
106
|
+
for rgb in (SGR.fg_rgb, SGR.bg_rgb):
|
|
107
|
+
for position in range(3):
|
|
108
|
+
channels = [0, 0, 0]
|
|
109
|
+
channels[position] = value
|
|
110
|
+
with (
|
|
111
|
+
self.subTest(factory=rgb.__name__, value=value, channel=position),
|
|
112
|
+
self.assertRaises(error),
|
|
113
|
+
):
|
|
114
|
+
rgb(*channels)
|