colorfulstring 0.0.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.
@@ -0,0 +1,38 @@
1
+ name: Upload Python Package
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ deploy:
12
+ runs-on: ubuntu-latest
13
+
14
+ steps:
15
+ - name: Checkout
16
+ uses: actions/checkout@v3
17
+ with:
18
+ submodules: recursive
19
+ - name: Set up Python
20
+ uses: actions/setup-python@v3
21
+ with:
22
+ python-version: "3.12.7"
23
+ - name: Upgrade pip
24
+ run: python -m pip install --upgrade pip
25
+ - name: Install yaml
26
+ run: python -m pip install pyyaml
27
+ - name: Install build
28
+ run: python -m pip install build
29
+ - name: Install twine
30
+ run: python -m pip install twine
31
+ - name: Install cfgtools
32
+ run: python -m pip install cfgtools
33
+ - name: Install re-extensions
34
+ run: python -m pip install re-extensions
35
+ - name: Build package
36
+ run: python install.py
37
+ - name: Publish package
38
+ run: twine upload dist/* --username __token__ --password ${{ secrets.PYPI_API_TOKEN }}
@@ -0,0 +1,160 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
@@ -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.
@@ -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,71 @@
1
+ # colorfulstring
2
+ `colorfulstring` is a lightweight Python utility for building ANSI-colored terminal strings with a fluent, chainable API.
3
+
4
+ ## Installation
5
+
6
+ ```bash
7
+ pip install colorfulstring
8
+ ```
9
+
10
+ ## Quick Start
11
+
12
+ ```python
13
+ from colorfulstring import c
14
+
15
+ print(c.r << "Error:" << " something went wrong")
16
+ print(c.g("OK"))
17
+ ```
18
+
19
+ ## Usage
20
+
21
+ ### 1) Color Shortcuts
22
+
23
+ Available color properties are `d/r/g/y/b/p/c/w`, which map to dark, red, green, yellow, blue, purple, cyan, and white.
24
+
25
+ ```python
26
+ print(c.y << "Warning")
27
+ ```
28
+
29
+ ### 2) Pipe-Style Chaining
30
+
31
+ Use `<<` (or `@`) to append fragments in sequence:
32
+
33
+ ```python
34
+ print(c.b << "[INFO]" << " service started")
35
+ ```
36
+
37
+ ### 3) Conditional Output
38
+
39
+ - `iftrue(condition)`: include the next fragment only when `condition` is `True`.
40
+ - `ifnot(condition)`: include the next fragment only when `condition` is `False`.
41
+ - `ifelse(condition)`: choose between the next two fragments.
42
+
43
+ ```python
44
+
45
+ ok = True
46
+ line = c << "status: " << c.ifelse(ok) << c.g("success") << c.r("failed")
47
+ print(line)
48
+ ```
49
+
50
+ ### 4) Immediate Printing
51
+
52
+ `c.print` outputs each generated fragment immediately (without an automatic newline). It can be combined with `c.endl`.
53
+
54
+ ```python
55
+ line = c.print << "hello" << c.endl
56
+ ```
57
+
58
+ ## See Also
59
+ ### Github repository
60
+ * https://github.com/Chitaoji/colorfulstring/
61
+
62
+ ### PyPI project
63
+ * https://pypi.org/project/colorfulstring/
64
+
65
+
66
+ ## License
67
+ This project falls under the BSD 3-Clause License.
68
+
69
+ ## History
70
+ ### v0.0.0
71
+ * Initial release.
@@ -0,0 +1,107 @@
1
+ """Install the package."""
2
+
3
+ #!/usr/bin/env python
4
+ # -*- coding: utf-8 -*-
5
+ import os
6
+ import re
7
+ from pathlib import Path
8
+ from typing import Final
9
+
10
+ import cfgtools as cfg
11
+ from re_extensions import rsplit, word_wrap
12
+
13
+ here = Path(__file__).parent
14
+
15
+ # Load the package's meta-data from pyproject.toml.
16
+ f = cfg.read_toml(here / "pyproject.toml")
17
+ project = f["project"].asdict()
18
+ NAME: Final[str] = project["name"]
19
+ SUMMARY: Final[str] = project["description"]
20
+ HOMEPAGE: Final[str] = project["urls"]["Repository"]
21
+ REQUIRES: Final[list[str]] = project["dependencies"]
22
+ SOURCE = "src"
23
+ LICENSE = (here / project["license-files"][0]).read_text().partition("\n")[0]
24
+ VERSION = project["version"]
25
+
26
+ # Import the README and use it as the long-description.
27
+ readme_path = here / project["readme"]
28
+ if readme_path.exists():
29
+ long_description = "\n" + readme_path.read_text(encoding="utf-8")
30
+ else:
31
+ long_description = SUMMARY
32
+
33
+
34
+ def _readme2doc(
35
+ readme: str,
36
+ name: str = NAME,
37
+ requires: list[str] = REQUIRES,
38
+ homepage: str = HOMEPAGE,
39
+ pkg_license: str = LICENSE,
40
+ ) -> tuple[str, str]:
41
+ doc, rd = "", ""
42
+ for i, s in enumerate(rsplit("\n## ", readme)):
43
+ head = re.search(" .*\n", s).group()[1:-1]
44
+ if i == 0:
45
+ s = re.sub("^\n# .*", f"\n# {name}", s)
46
+ elif head == "Requirements":
47
+ s = re.sub(
48
+ "```txt.*```",
49
+ "```txt\n" + "\n".join(requires) + "\n```",
50
+ s,
51
+ flags=re.DOTALL,
52
+ )
53
+ elif head == "Installation":
54
+ s = re.sub(
55
+ "```sh.*```", f"```sh\n$ pip install {name}\n```", s, flags=re.DOTALL
56
+ )
57
+ elif head == "See Also":
58
+ pypipage = f"https://pypi.org/project/{name}/"
59
+ s = re.sub(
60
+ "### PyPI project\n.*",
61
+ f"### PyPI project\n* {pypipage}",
62
+ re.sub(
63
+ "### Github repository\n.*",
64
+ f"### Github repository\n* {homepage}",
65
+ s,
66
+ ),
67
+ )
68
+ elif head == "License":
69
+ s = f"\n## License\nThis project falls under the {pkg_license}.\n"
70
+
71
+ rd += s
72
+ if head not in {"Installation", "Requirements", "History"}:
73
+ doc += s
74
+ doc = re.sub("<!--html-->.*<!--/html-->", "", doc, flags=re.DOTALL)
75
+ return word_wrap(doc, maximum=88) + "\n\n", rd
76
+
77
+
78
+ def _quote(readme: str) -> str:
79
+ if "'''" in readme and '"""' in readme:
80
+ raise ReadmeFormatError("Both \"\"\" and ''' are found in the README")
81
+ if '"""' in readme:
82
+ return f"'''{readme}'''"
83
+ else:
84
+ return f'"""{readme}"""'
85
+
86
+
87
+ def _version(version: str = VERSION) -> str:
88
+ return f'"""Version file."""\n\n__version__ = "{version}"\n'
89
+
90
+
91
+ class ReadmeFormatError(Exception):
92
+ """Raised when the README has a wrong format."""
93
+
94
+
95
+ if __name__ == "__main__":
96
+ # Import the __init__.py and change the module docstring.
97
+ init_path = here / SOURCE / NAME / "__init__.py"
98
+ version_path = here / SOURCE / NAME / "_version.py"
99
+ module_file = init_path.read_text(encoding="utf-8")
100
+ new_doc, long_description = _readme2doc(long_description)
101
+ module_file = re.sub(
102
+ "^\"\"\".*\"\"\"|^'''.*'''|^", _quote(new_doc), module_file, flags=re.DOTALL
103
+ )
104
+ init_path.write_text(module_file, encoding="utf-8")
105
+ readme_path.write_text(long_description.strip(), encoding="utf-8")
106
+ version_path.write_text(_version())
107
+ os.system(f"cd {here} && python -m build")
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "colorfulstring"
7
+ version = "0.0.0"
8
+ dependencies = []
9
+ requires-python = ">=3.12"
10
+ authors = [
11
+ {name = "Chitaoji", email = "2360742040@qq.com"},
12
+ ]
13
+ maintainers = [
14
+ {name = "Chitaoji", email = "2360742040@qq.com"}
15
+ ]
16
+ description = "Make colorful strings."
17
+ readme = "README.md"
18
+ license = "BSD-3-Clause"
19
+ license-files = ["LICENSE"]
20
+ keywords = ["config"]
21
+ classifiers = [
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.12"
24
+ ]
25
+
26
+ [project.urls]
27
+ Documentation = "https://github.com/Chitaoji/colorfulstring/blob/main/README.md"
28
+ Repository = "https://github.com/Chitaoji/colorfulstring/"
29
+
@@ -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"
@@ -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()