sgrs 0.1.0__py3-none-any.whl

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/__init__.py 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,))
sgrs/__main__.py ADDED
@@ -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()
sgrs/py.typed ADDED
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,8 @@
1
+ sgrs/__init__.py,sha256=X81gfMjRVc4ZNFXoMZlbGBVGRwRDyCYh9JwZPe_o6jE,6641
2
+ sgrs/__main__.py,sha256=23r4pwjReRpm4Qz0aa6EblgSsguE7fB8uVaFVcUSnvw,559
3
+ sgrs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ sgrs-0.1.0.dist-info/licenses/LICENSE,sha256=q732hJ3pezpoIQul_HrdXH3OWrn_RpyGXR5vEEZZ72o,1060
5
+ sgrs-0.1.0.dist-info/METADATA,sha256=UtXNdL3Ldg7PObcp5Rg7AKFWhQLlcRpZO0Nl-kSsZCQ,4762
6
+ sgrs-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
7
+ sgrs-0.1.0.dist-info/top_level.txt,sha256=Y-AyUJRHAnrLob046D4IX0RZUaaubshJIS-UXUXAJBY,5
8
+ sgrs-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -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.
@@ -0,0 +1 @@
1
+ sgrs