colorfulstring 0.0.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.
@@ -0,0 +1,74 @@
1
+ """
2
+ # colorfulstring
3
+ `colorfulstring` is a lightweight Python utility for building ANSI-colored terminal
4
+ strings with a fluent, chainable API.
5
+
6
+ ## Quick Start
7
+
8
+ ```python
9
+ from colorfulstring import c
10
+
11
+ print(c.r << "Error:" << " something went wrong")
12
+ print(c.g("OK"))
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ### 1) Color Shortcuts
18
+
19
+ Available color properties are `d/r/g/y/b/p/c/w`, which map to dark, red, green, yellow,
20
+ blue, purple, cyan, and white.
21
+
22
+ ```python
23
+ print(c.y << "Warning")
24
+ ```
25
+
26
+ ### 2) Pipe-Style Chaining
27
+
28
+ Use `<<` (or `@`) to append fragments in sequence:
29
+
30
+ ```python
31
+ print(c.b << "[INFO]" << " service started")
32
+ ```
33
+
34
+ ### 3) Conditional Output
35
+
36
+ - `iftrue(condition)`: include the next fragment only when `condition` is `True`.
37
+ - `ifnot(condition)`: include the next fragment only when `condition` is `False`.
38
+ - `ifelse(condition)`: choose between the next two fragments.
39
+
40
+ ```python
41
+
42
+ ok = True
43
+ line = c << "status: " << c.ifelse(ok) << c.g("success") << c.r("failed")
44
+ print(line)
45
+ ```
46
+
47
+ ### 4) Immediate Printing
48
+
49
+ `c.print` outputs each generated fragment immediately (without an automatic newline). It
50
+ can be combined with `c.endl`.
51
+
52
+ ```python
53
+ line = c.print << "hello" << c.endl
54
+ ```
55
+
56
+ ## See Also
57
+ ### Github repository
58
+ * https://github.com/Chitaoji/colorfulstring/
59
+
60
+ ### PyPI project
61
+ * https://pypi.org/project/colorfulstring/
62
+
63
+
64
+ ## License
65
+ This project falls under the BSD 3-Clause License.
66
+
67
+ """
68
+
69
+ from . import core
70
+ from ._version import __version__
71
+ from .core import *
72
+
73
+ __all__: list[str] = []
74
+ __all__.extend(core.__all__)
@@ -0,0 +1,10 @@
1
+ """
2
+ Contains typing classes.
3
+
4
+ NOTE: this module is not intended to be imported at runtime.
5
+
6
+ """
7
+
8
+ import loggings
9
+
10
+ loggings.warning("this module is not intended to be imported at runtime")
@@ -0,0 +1,3 @@
1
+ """Version file."""
2
+
3
+ __version__ = "0.0.0"
colorfulstring/core.py ADDED
@@ -0,0 +1,252 @@
1
+ """
2
+ Contains the core of colorfulstring.
3
+
4
+ This module defines :class:`ColorfulString` and the singleton ``c`` used to build
5
+ ANSI-colored terminal strings with a fluent API.
6
+
7
+ NOTE: this module is private. All functions and objects are available in the main
8
+ `colorfulstring` namespace - use that instead.
9
+
10
+ """
11
+
12
+ from functools import partial
13
+ from typing import Any, Callable, Self
14
+
15
+ __all__ = ["c"]
16
+
17
+
18
+ class _DefaultReceiver:
19
+ """Fallback receiver used by conditional pipelines."""
20
+
21
+ def __lshift__(self, obj: "ColorfulString") -> "ColorfulString":
22
+ return obj
23
+
24
+
25
+ class ColorfulString:
26
+ """Fluent builder for ANSI-colored strings.
27
+
28
+ ``ColorfulString`` supports color shortcuts (``.r``, ``.g`` ...), concatenation,
29
+ piping with ``<<``/``@``, and conditional output with ``ifelse``/``iftrue``/``ifnot``.
30
+
31
+ Typical usage starts from the module-level singleton ``c``.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ default_color: str = "",
37
+ string: str | None = None,
38
+ status: tuple[bool, bool] | None = None,
39
+ receiver: Self | _DefaultReceiver = _DefaultReceiver(),
40
+ printer: Callable | None = None,
41
+ ) -> None:
42
+ """Create an internal builder state.
43
+
44
+ Args:
45
+ default_color: Default color token applied to plain strings.
46
+ string: Accumulated output string.
47
+ status: Internal state for conditional chaining.
48
+ receiver: Target builder used by conditional chains.
49
+ printer: Optional side-effect callback invoked on generated fragments.
50
+ """
51
+ self._default_color = default_color
52
+ self._string = string
53
+ self._status = status
54
+ self._receiver = receiver
55
+ self._printer = printer
56
+
57
+ def __repr__(self) -> str:
58
+ """Return accumulated string when finalized, else default repr."""
59
+ if self._status is None and self._string is not None:
60
+ return self._string
61
+ return super().__repr__()
62
+
63
+ def __str__(self) -> str:
64
+ """Return the user-facing string representation."""
65
+ return repr(self)
66
+
67
+ def __add__(self, string: str) -> str:
68
+ """Append a Python string to the built output."""
69
+ return self.__asstr() + string
70
+
71
+ def __radd__(self, string: str) -> str:
72
+ """Prepend a Python string to the built output."""
73
+ return string + self.__asstr()
74
+
75
+ def __call__(self, string: str) -> str:
76
+ """Convert input to colored output according to current color context."""
77
+ return self.__make_str(string)
78
+
79
+ def __lshift__(self, obj: str | Self | Any) -> Self:
80
+ """Pipe data into the builder.
81
+
82
+ ``builder << value`` appends ``value`` after converting color tokens.
83
+ Passing another ``ColorfulString`` is used internally to wire conditional chains.
84
+ """
85
+ if isinstance(obj, self.__class__):
86
+ if obj._status is not None:
87
+ if (
88
+ not isinstance(obj._receiver, _DefaultReceiver)
89
+ or obj._string is not None
90
+ ):
91
+ raise ValueError("unfinished call to ifelse(), iftrue() or ifnot()")
92
+ obj._receiver = self
93
+ return obj
94
+
95
+ if obj._string is None:
96
+ raise ValueError("<< c alone is not allowed")
97
+ return self.__recv(obj)
98
+
99
+ def __rlshift__(self, obj: str | Self | Any) -> Self:
100
+ """Support ``value << builder`` style piping."""
101
+ return c << obj << self
102
+
103
+ def __rshift__[T](self, obj: type[T]) -> T:
104
+ """Cast the finalized string to another type.
105
+
106
+ Example:
107
+ ``(c.r << "42") >> int``
108
+ """
109
+ if self._status is None and self._string is not None:
110
+ return obj(self._string)
111
+ raise ValueError(f"nothing to convert to {obj}")
112
+
113
+ def __matmul__(self, obj: str | Self | Any) -> Self:
114
+ """Alias of ``<<`` for users who prefer ``@`` syntax."""
115
+ return self << obj
116
+
117
+ def ifelse(self, condition: bool) -> Self:
118
+ """Start a two-branch conditional chain.
119
+
120
+ The first subsequent value is used when ``condition`` is true; the second one
121
+ is used otherwise.
122
+ """
123
+ if self._status is not None:
124
+ raise ValueError("duplicated call to ifelse(), iftrue() or ifnot()")
125
+ return self.copy(status=(bool(condition), True))
126
+
127
+ def iftrue(self, condition: bool) -> Self:
128
+ """Append next value only when ``condition`` is true."""
129
+ if self._status is not None:
130
+ raise ValueError("duplicated call to ifelse(), iftrue() or ifnot()")
131
+ return self.copy(string="", status=(not bool(condition), False))
132
+
133
+ def ifnot(self, condition: bool) -> Self:
134
+ """Append next value only when ``condition`` is false."""
135
+ if self._status is not None:
136
+ raise ValueError("duplicated call to ifelse(), iftrue() or ifnot()")
137
+ return self.copy(string="", status=(bool(condition), False))
138
+
139
+ def copy(
140
+ self,
141
+ *,
142
+ default_color: str = ...,
143
+ string: str | None = ...,
144
+ status: tuple[bool, bool] | None = ...,
145
+ receiver: Self | _DefaultReceiver = ...,
146
+ printer: Callable | None = ...,
147
+ ) -> Self:
148
+ """Return a cloned builder with selected fields overridden."""
149
+ return self.__class__(
150
+ self._default_color if default_color is Ellipsis else default_color,
151
+ self._string if string is Ellipsis else string,
152
+ self._status if status is Ellipsis else status,
153
+ self._receiver if receiver is Ellipsis else receiver,
154
+ self._printer if printer is Ellipsis else printer,
155
+ )
156
+
157
+ def __recv(self, obj: str | Self | Any) -> Self:
158
+ """Receive an object and merge it into current/conditional pipeline."""
159
+ if self._status is None:
160
+ return self.copy(string=self.__asstr() + self.__make_str(obj))
161
+ b, now = self._status
162
+ if now:
163
+ if b:
164
+ return self.copy(
165
+ string=self.__asstr() + self.__make_str(obj), status=(b, False)
166
+ )
167
+ return self.copy(status=(b, False))
168
+ elif b:
169
+ return self._receiver << self.copy(status=None)
170
+ return self._receiver << self.copy(
171
+ string=self.__asstr() + self.__make_str(obj), status=None
172
+ )
173
+
174
+ def __make_str(self, obj: str | Self | Any) -> str:
175
+ """Convert value to final ANSI text and optionally emit to printer."""
176
+ if isinstance(obj, ColorfulString):
177
+ string = str(obj)
178
+ else:
179
+ string = str(obj)
180
+ if self._default_color and string:
181
+ string = f"${self._default_color}{string}$"
182
+ string = (
183
+ string.replace("$D", "\033[30m") # Dark
184
+ .replace("$R", "\033[31m") # Red
185
+ .replace("$G", "\033[32m") # Green
186
+ .replace("$Y", "\033[33m") # Yellow
187
+ .replace("$B", "\033[34m") # Blue
188
+ .replace("$P", "\033[35m") # Purple
189
+ .replace("$C", "\033[36m") # Cyan
190
+ .replace("$W", "\033[37m") # White
191
+ .replace("$", "\033[0m")
192
+ )
193
+ if self._printer is not None:
194
+ self._printer(string)
195
+ return string
196
+
197
+ def __asstr(self) -> str:
198
+ """Get accumulated output or an empty string."""
199
+ return "" if self._string is None else self._string
200
+
201
+ @property
202
+ def print(self) -> Self:
203
+ """Return builder that prints each generated fragment immediately."""
204
+ return self.copy(printer=partial(print, end=""))
205
+
206
+ @property
207
+ def endl(self) -> Self:
208
+ """Return a newline fragment."""
209
+ return ColorfulString(string="\n")
210
+
211
+ @property
212
+ def d(self) -> Self:
213
+ """Return a builder with dark/black default color."""
214
+ return self.copy(default_color="D")
215
+
216
+ @property
217
+ def r(self) -> Self:
218
+ """Return a builder with red default color."""
219
+ return self.copy(default_color="R")
220
+
221
+ @property
222
+ def g(self) -> Self:
223
+ """Return a builder with green default color."""
224
+ return self.copy(default_color="G")
225
+
226
+ @property
227
+ def y(self) -> Self:
228
+ """Return a builder with yellow default color."""
229
+ return self.copy(default_color="Y")
230
+
231
+ @property
232
+ def b(self) -> Self:
233
+ """Return a builder with blue default color."""
234
+ return self.copy(default_color="B")
235
+
236
+ @property
237
+ def p(self) -> Self:
238
+ """Return a builder with purple default color."""
239
+ return self.copy(default_color="P")
240
+
241
+ @property
242
+ def c(self) -> Self:
243
+ """Return a builder with cyan default color."""
244
+ return self.copy(default_color="C")
245
+
246
+ @property
247
+ def w(self) -> Self:
248
+ """Return a builder with white default color."""
249
+ return self.copy(default_color="W")
250
+
251
+
252
+ c = ColorfulString()
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: colorfulstring
3
+ Version: 0.0.0
4
+ Summary: Make colorful strings.
5
+ Project-URL: Documentation, https://github.com/Chitaoji/colorfulstring/blob/main/README.md
6
+ Project-URL: Repository, https://github.com/Chitaoji/colorfulstring/
7
+ Author-email: Chitaoji <2360742040@qq.com>
8
+ Maintainer-email: Chitaoji <2360742040@qq.com>
9
+ License-Expression: BSD-3-Clause
10
+ License-File: LICENSE
11
+ Keywords: config
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.12
15
+ Description-Content-Type: text/markdown
16
+
17
+ # colorfulstring
18
+ `colorfulstring` is a lightweight Python utility for building ANSI-colored terminal strings with a fluent, chainable API.
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ pip install colorfulstring
24
+ ```
25
+
26
+ ## Quick Start
27
+
28
+ ```python
29
+ from colorfulstring import c
30
+
31
+ print(c.r << "Error:" << " something went wrong")
32
+ print(c.g("OK"))
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ### 1) Color Shortcuts
38
+
39
+ Available color properties are `d/r/g/y/b/p/c/w`, which map to dark, red, green, yellow, blue, purple, cyan, and white.
40
+
41
+ ```python
42
+ print(c.y << "Warning")
43
+ ```
44
+
45
+ ### 2) Pipe-Style Chaining
46
+
47
+ Use `<<` (or `@`) to append fragments in sequence:
48
+
49
+ ```python
50
+ print(c.b << "[INFO]" << " service started")
51
+ ```
52
+
53
+ ### 3) Conditional Output
54
+
55
+ - `iftrue(condition)`: include the next fragment only when `condition` is `True`.
56
+ - `ifnot(condition)`: include the next fragment only when `condition` is `False`.
57
+ - `ifelse(condition)`: choose between the next two fragments.
58
+
59
+ ```python
60
+
61
+ ok = True
62
+ line = c << "status: " << c.ifelse(ok) << c.g("success") << c.r("failed")
63
+ print(line)
64
+ ```
65
+
66
+ ### 4) Immediate Printing
67
+
68
+ `c.print` outputs each generated fragment immediately (without an automatic newline). It can be combined with `c.endl`.
69
+
70
+ ```python
71
+ line = c.print << "hello" << c.endl
72
+ ```
73
+
74
+ ## See Also
75
+ ### Github repository
76
+ * https://github.com/Chitaoji/colorfulstring/
77
+
78
+ ### PyPI project
79
+ * https://pypi.org/project/colorfulstring/
80
+
81
+
82
+ ## License
83
+ This project falls under the BSD 3-Clause License.
84
+
85
+ ## History
86
+ ### v0.0.0
87
+ * Initial release.
@@ -0,0 +1,8 @@
1
+ colorfulstring/__init__.py,sha256=3PfM3wVEUjbQXRZMFiw5u_Vn15pQLmCmvzyJTlIdHUw,1509
2
+ colorfulstring/_typing.py,sha256=hYjHTC9lc_cxiFj6weQnY2_00hNAFKISbWHEfhHhPhE,188
3
+ colorfulstring/_version.py,sha256=Yh1NHsKxLt_X-EdEq7AJFF-QqDaJmXkvE2TY7RmcOa4,43
4
+ colorfulstring/core.py,sha256=phBcXeSqP5n5vowBvLzqU7Vkgkj_Kvd96BJp6JiRPQ8,8913
5
+ colorfulstring-0.0.0.dist-info/METADATA,sha256=GU70RxJhSYosVERzwY8D6xwSMVXLzLUocrTsnhqwdOA,2046
6
+ colorfulstring-0.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
7
+ colorfulstring-0.0.0.dist-info/licenses/LICENSE,sha256=rlOb8JrIQs-p03IkqjgLlXbFGIwdABeHAaRckd4b8N8,1495
8
+ colorfulstring-0.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2023, Chitaoji
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.