PyBannerLibrary 1.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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: PyBannerLibrary
3
+ Version: 1.0.0
4
+ Summary: Banners, títulos, marcos y separadores para la terminal sin dependencias.
5
+ Author: programador777lolxddd-dot
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/programador777lolxddd-dot/PyBanner
8
+ Project-URL: Repository, https://github.com/programador777lolxddd-dot/PyBanner
9
+ Project-URL: Issues, https://github.com/programador777lolxddd-dot/PyBanner/issues
10
+ Keywords: banner,terminal,cli,ansi,console,toolkit
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: Terminals
23
+ Requires-Python: >=3.8
24
+ License-File: LICENSE
25
+ Dynamic: license-file
@@ -0,0 +1,25 @@
1
+ Metadata-Version: 2.4
2
+ Name: PyBannerLibrary
3
+ Version: 1.0.0
4
+ Summary: Banners, títulos, marcos y separadores para la terminal sin dependencias.
5
+ Author: programador777lolxddd-dot
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/programador777lolxddd-dot/PyBanner
8
+ Project-URL: Repository, https://github.com/programador777lolxddd-dot/PyBanner
9
+ Project-URL: Issues, https://github.com/programador777lolxddd-dot/PyBanner/issues
10
+ Keywords: banner,terminal,cli,ansi,console,toolkit
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.8
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
22
+ Classifier: Topic :: Terminals
23
+ Requires-Python: >=3.8
24
+ License-File: LICENSE
25
+ Dynamic: license-file
@@ -0,0 +1,8 @@
1
+ LICENSE
2
+ README.md
3
+ pybanner.py
4
+ pyproject.toml
5
+ PyBannerLibrary.egg-info/PKG-INFO
6
+ PyBannerLibrary.egg-info/SOURCES.txt
7
+ PyBannerLibrary.egg-info/dependency_links.txt
8
+ PyBannerLibrary.egg-info/top_level.txt
@@ -0,0 +1,36 @@
1
+ # PyBannerLibrary
2
+
3
+ Banners, títulos, marcos y separadores para la terminal con Python, sin dependencias externas.
4
+
5
+ ## Instalación
6
+
7
+ ```bash
8
+ pip install PyBannerLibrary
9
+ ```
10
+
11
+ ## Uso rápido
12
+
13
+ ```python
14
+ from pybanner import show, title, box, separator, banner
15
+
16
+ show("Hola, mundo", color="cyan")
17
+ title("Mi programa", style="double")
18
+ box("Operación completada", color="green")
19
+ separator("-", length=40)
20
+ banner("PyBanner", subtitle="Terminal toolkit", color="magenta")
21
+ ```
22
+
23
+ ## Funciones
24
+
25
+ - `show(text, color=None, style="simple", center=False)`: muestra texto con formato opcional.
26
+ - `title(text, style="simple", color=None)`: muestra un título destacado.
27
+ - `box(text, color=None, style="single", padding=1)`: dibuja un marco.
28
+ - `separator(char="-", length=40, color=None)`: imprime una línea divisoria.
29
+ - `banner(text, subtitle=None, color=None, style="box")`: combina título y subtítulo.
30
+ - `set_color_mode(mode="auto")`: configura los colores ANSI (`auto`, `always` o `never`).
31
+
32
+ Colores disponibles: `red`, `green`, `yellow`, `blue`, `magenta`, `cyan` y `white`.
33
+
34
+ ## Licencia
35
+
36
+ Apache-2.0. Consulta el archivo [LICENSE](LICENSE).
@@ -0,0 +1,480 @@
1
+ """
2
+ PyBanner
3
+ ========
4
+
5
+ Pequeña librería sin dependencias para crear banners, títulos, marcos y
6
+ separadores en la terminal, sin repetir llamadas a ``print()``.
7
+
8
+ Uso rápido::
9
+
10
+ from pybanner import show, title, box, separator, banner
11
+
12
+ show("Hola, mundo", color="cyan")
13
+ title("Mi programa", style="double")
14
+ box("Operación completada", color="green")
15
+ separator("-", length=40)
16
+ banner("PyBanner", subtitle="Terminal toolkit", color="magenta")
17
+
18
+ Colores
19
+ -------
20
+ Se admiten los nombres ``red``, ``green``, ``yellow``, ``blue``,
21
+ ``magenta``, ``cyan`` y ``white``. Los códigos ANSI solo se emiten cuando
22
+ la salida es una terminal interactiva (modo ``auto``). El comportamiento
23
+ se puede cambiar con :func:`set_color_mode` o con la variable de entorno
24
+ ``PYBANNER_COLOR`` (``auto``, ``always`` o ``never``). La variable estándar
25
+ ``NO_COLOR`` también desactiva el color.
26
+
27
+ Estilos
28
+ -------
29
+ ``simple``, ``minimal``, ``box`` (esquinas redondeadas), ``single``,
30
+ ``double`` y ``ascii``.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import os
36
+ import re
37
+ import shutil
38
+ import sys
39
+ import unicodedata
40
+ from typing import Dict, List, Optional, Sequence
41
+
42
+ __all__ = ["show", "title", "box", "separator", "banner", "set_color_mode"]
43
+ __version__ = "1.0.0"
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Constantes internas
47
+ # ---------------------------------------------------------------------------
48
+
49
+ _RESET: str = "\033[0m"
50
+
51
+ _COLORS: Dict[str, str] = {
52
+ "red": "\033[31m",
53
+ "green": "\033[32m",
54
+ "yellow": "\033[33m",
55
+ "blue": "\033[34m",
56
+ "magenta": "\033[35m",
57
+ "cyan": "\033[36m",
58
+ "white": "\033[37m",
59
+ }
60
+
61
+ _BORDERS: Dict[str, Dict[str, str]] = {
62
+ "single": {"tl": "┌", "tr": "┐", "bl": "└", "br": "┘", "h": "─", "v": "│"},
63
+ "double": {"tl": "╔", "tr": "╗", "bl": "╚", "br": "╝", "h": "═", "v": "║"},
64
+ "box": {"tl": "╭", "tr": "╮", "bl": "╰", "br": "╯", "h": "─", "v": "│"},
65
+ "ascii": {"tl": "+", "tr": "+", "bl": "+", "br": "+", "h": "-", "v": "|"},
66
+ }
67
+
68
+ _STYLES: Sequence[str] = ("simple", "minimal", "box", "single", "double", "ascii")
69
+
70
+ _ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
71
+
72
+ # Modo global de color: "auto" | "always" | "never".
73
+ _color_mode: str = "auto"
74
+
75
+
76
+ # ---------------------------------------------------------------------------
77
+ # Configuración de color
78
+ # ---------------------------------------------------------------------------
79
+
80
+ def set_color_mode(mode: str = "auto") -> None:
81
+ """Configura el modo global de emisión de color.
82
+
83
+ Args:
84
+ mode: ``"auto"`` (colorear solo si la salida es una terminal),
85
+ ``"always"`` (forzar color) o ``"never"`` (desactivar color).
86
+
87
+ Raises:
88
+ TypeError: Si ``mode`` no es una cadena.
89
+ ValueError: Si ``mode`` no es uno de los valores admitidos.
90
+ """
91
+ global _color_mode
92
+ if not isinstance(mode, str):
93
+ raise TypeError(f"mode debe ser str, se recibió {type(mode).__name__}")
94
+ normalized = mode.strip().lower()
95
+ if normalized not in ("auto", "always", "never"):
96
+ raise ValueError(
97
+ f"mode inválido: {mode!r}. Valores válidos: 'auto', 'always', 'never'"
98
+ )
99
+ _color_mode = normalized
100
+
101
+
102
+ def _use_color() -> bool:
103
+ """Indica si deben emitirse secuencias ANSI en la salida estándar."""
104
+ mode = os.environ.get("PYBANNER_COLOR", _color_mode).strip().lower()
105
+ if mode not in ("auto", "always", "never"):
106
+ mode = _color_mode
107
+ if mode == "always":
108
+ return True
109
+ if mode == "never":
110
+ return False
111
+ if os.environ.get("NO_COLOR"):
112
+ return False
113
+ try:
114
+ return bool(sys.stdout.isatty())
115
+ except (AttributeError, ValueError):
116
+ return False
117
+
118
+
119
+ # ---------------------------------------------------------------------------
120
+ # Validaciones
121
+ # ---------------------------------------------------------------------------
122
+
123
+ def _validate_color(color: Optional[str]) -> Optional[str]:
124
+ """Valida y normaliza un nombre de color."""
125
+ if color is None:
126
+ return None
127
+ if not isinstance(color, str):
128
+ raise TypeError(f"color debe ser str o None, se recibió {type(color).__name__}")
129
+ normalized = color.strip().lower()
130
+ if normalized not in _COLORS:
131
+ raise ValueError(
132
+ f"color inválido: {color!r}. Válidos: {', '.join(_COLORS)}"
133
+ )
134
+ return normalized
135
+
136
+
137
+ def _validate_style(style: str, allowed: Sequence[str] = _STYLES) -> str:
138
+ """Valida y normaliza un nombre de estilo."""
139
+ if not isinstance(style, str):
140
+ raise TypeError(f"style debe ser str, se recibió {type(style).__name__}")
141
+ normalized = style.strip().lower()
142
+ if normalized not in allowed:
143
+ raise ValueError(
144
+ f"style inválido: {style!r}. Válidos: {', '.join(allowed)}"
145
+ )
146
+ return normalized
147
+
148
+
149
+ def _validate_non_negative_int(value: object, name: str) -> int:
150
+ """Valida que ``value`` sea un entero mayor o igual que cero."""
151
+ if isinstance(value, bool) or not isinstance(value, int):
152
+ raise TypeError(f"{name} debe ser int, se recibió {type(value).__name__}")
153
+ if value < 0:
154
+ raise ValueError(f"{name} no puede ser negativo (recibido {value})")
155
+ return value
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # Utilidades de texto / terminal
160
+ # ---------------------------------------------------------------------------
161
+
162
+ def _to_lines(text: object) -> List[str]:
163
+ """Convierte cualquier valor en una lista de líneas normalizadas."""
164
+ if text is None:
165
+ return [""]
166
+ if not isinstance(text, str):
167
+ text = str(text)
168
+ text = text.replace("\r\n", "\n").replace("\r", "\n")
169
+ return text.split("\n")
170
+
171
+
172
+ def _display_width(text: str) -> int:
173
+ """Calcula el ancho visual de ``text`` ignorando códigos ANSI."""
174
+ stripped = _ANSI_RE.sub("", text)
175
+ width = 0
176
+ for char in stripped:
177
+ if unicodedata.combining(char):
178
+ continue
179
+ if unicodedata.category(char) in ("Mn", "Me", "Cf", "Cc"):
180
+ continue
181
+ width += 2 if unicodedata.east_asian_width(char) in ("W", "F") else 1
182
+ return width
183
+
184
+
185
+ def _term_width() -> int:
186
+ """Devuelve el ancho de la terminal (80 columnas como reserva)."""
187
+ try:
188
+ return shutil.get_terminal_size((80, 24)).columns
189
+ except (OSError, ValueError):
190
+ return 80
191
+
192
+
193
+ def _paint(text: str, color: Optional[str]) -> str:
194
+ """Aplica color ANSI a ``text`` si procede."""
195
+ if color is None or not _use_color():
196
+ return text
197
+ return f"{_COLORS[color]}{text}{_RESET}"
198
+
199
+
200
+ def _pad_center(text: str, width: int) -> str:
201
+ """Rellena ``text`` con espacios hasta ``width``, centrándolo."""
202
+ current = _display_width(text)
203
+ if current >= width:
204
+ return text
205
+ left = (width - current) // 2
206
+ right = width - current - left
207
+ return " " * left + text + " " * right
208
+
209
+
210
+ def _center_block(lines: Sequence[str]) -> List[str]:
211
+ """Centra cada línea respecto al ancho de la terminal."""
212
+ term = _term_width()
213
+ centered: List[str] = []
214
+ for line in lines:
215
+ left = max(0, (term - _display_width(line)) // 2)
216
+ centered.append(" " * left + line)
217
+ return centered
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Renderizado compartido
222
+ # ---------------------------------------------------------------------------
223
+
224
+ def _frame(
225
+ lines: Sequence[str],
226
+ border: Dict[str, str],
227
+ padding: int = 0,
228
+ color: Optional[str] = None,
229
+ ) -> List[str]:
230
+ """Envuelve ``lines`` con el marco descrito por ``border``."""
231
+ inner = max((_display_width(line) for line in lines), default=0)
232
+ pad = " " * padding
233
+ total = inner + padding * 2
234
+
235
+ top = border["tl"] + border["h"] * total + border["tr"]
236
+ bottom = border["bl"] + border["h"] * total + border["br"]
237
+
238
+ rendered: List[str] = [top]
239
+ for line in lines:
240
+ fill = " " * max(0, inner - _display_width(line))
241
+ rendered.append(border["v"] + pad + line + fill + pad + border["v"])
242
+ rendered.append(bottom)
243
+
244
+ return [_paint(line, color) for line in rendered]
245
+
246
+
247
+ def _render_block(
248
+ lines: Sequence[str],
249
+ style: str,
250
+ color: Optional[str] = None,
251
+ padding: int = 0,
252
+ ) -> List[str]:
253
+ """Renderiza un bloque de líneas según el estilo indicado."""
254
+ if style == "simple":
255
+ return [_paint(line, color) for line in lines]
256
+ if style == "minimal":
257
+ return [_paint("│ " + line, color) for line in lines]
258
+ return _frame(lines, _BORDERS[style], padding=padding, color=color)
259
+
260
+
261
+ # ---------------------------------------------------------------------------
262
+ # API pública
263
+ # ---------------------------------------------------------------------------
264
+
265
+ def show(
266
+ text: object,
267
+ color: Optional[str] = None,
268
+ style: str = "simple",
269
+ center: bool = False,
270
+ ) -> None:
271
+ """Imprime ``text`` con formato opcional.
272
+
273
+ Args:
274
+ text: Contenido a mostrar. Cualquier objeto se convierte a ``str``.
275
+ Se admiten varias líneas separadas por ``\\n``.
276
+ color: Nombre de color ANSI o ``None``.
277
+ style: ``simple``, ``minimal``, ``box``, ``single``, ``double``
278
+ o ``ascii``.
279
+ center: Si es ``True``, centra cada línea en la terminal.
280
+
281
+ Raises:
282
+ TypeError: Si ``color``, ``style`` o ``center`` tienen un tipo inválido.
283
+ ValueError: Si ``color`` o ``style`` no son valores admitidos.
284
+ """
285
+ style = _validate_style(style)
286
+ color = _validate_color(color)
287
+ if not isinstance(center, bool):
288
+ raise TypeError(f"center debe ser bool, se recibió {type(center).__name__}")
289
+
290
+ rendered = _render_block(_to_lines(text), style, color, padding=0)
291
+ if center:
292
+ rendered = _center_block(rendered)
293
+
294
+ for line in rendered:
295
+ print(line)
296
+
297
+
298
+ def title(text: object, style: str = "simple", color: Optional[str] = None) -> None:
299
+ """Imprime un título destacado.
300
+
301
+ Con el estilo ``simple`` se dibuja un subrayado del ancho del título;
302
+ con ``minimal`` se añade una barra lateral; el resto de estilos usa
303
+ marcos adaptables al contenido.
304
+
305
+ Args:
306
+ text: Texto del título (admite multilínea y Unicode).
307
+ style: ``simple``, ``minimal``, ``box``, ``single``, ``double``
308
+ o ``ascii``.
309
+ color: Nombre de color ANSI o ``None``.
310
+
311
+ Raises:
312
+ TypeError: Si ``color`` o ``style`` tienen un tipo inválido.
313
+ ValueError: Si ``color`` o ``style`` no son valores admitidos.
314
+ """
315
+ style = _validate_style(style)
316
+ color = _validate_color(color)
317
+ lines = _to_lines(text)
318
+
319
+ if style == "simple":
320
+ width = max((_display_width(line) for line in lines), default=0)
321
+ rendered = [_paint(line, color) for line in lines]
322
+ rendered.append(_paint("─" * width, color))
323
+ elif style == "minimal":
324
+ rendered = [_paint("▌ " + line, color) for line in lines]
325
+ else:
326
+ rendered = _render_block(lines, style, color, padding=1)
327
+
328
+ for line in rendered:
329
+ print(line)
330
+
331
+
332
+ def box(
333
+ text: object,
334
+ color: Optional[str] = None,
335
+ style: str = "single",
336
+ padding: int = 1,
337
+ ) -> None:
338
+ """Dibuja un marco adaptable alrededor de ``text``.
339
+
340
+ Args:
341
+ text: Contenido del marco (admite multilínea y Unicode).
342
+ color: Nombre de color ANSI o ``None``.
343
+ style: ``box``, ``single``, ``double``, ``ascii``, ``minimal``
344
+ o ``simple``. En ``minimal`` y ``simple`` no se dibuja marco
345
+ y ``padding`` se ignora.
346
+ padding: Espacios horizontales entre el borde y el contenido.
347
+
348
+ Raises:
349
+ TypeError: Si algún parámetro tiene un tipo inválido.
350
+ ValueError: Si ``color``/``style`` no son válidos o ``padding`` < 0.
351
+ """
352
+ style = _validate_style(style)
353
+ color = _validate_color(color)
354
+ padding = _validate_non_negative_int(padding, "padding")
355
+
356
+ for line in _render_block(_to_lines(text), style, color, padding=padding):
357
+ print(line)
358
+
359
+
360
+ def separator(char: str = "-", length: int = 40, color: Optional[str] = None) -> None:
361
+ """Dibuja una línea divisoria.
362
+
363
+ Args:
364
+ char: Carácter único con el que se construye la línea.
365
+ length: Número de repeticiones del carácter.
366
+ color: Nombre de color ANSI o ``None``.
367
+
368
+ Raises:
369
+ TypeError: Si ``char`` no es ``str`` o ``length`` no es ``int``.
370
+ ValueError: Si ``char`` no es un carácter imprimible o ``length`` < 0.
371
+ """
372
+ if not isinstance(char, str):
373
+ raise TypeError(f"char debe ser str, se recibió {type(char).__name__}")
374
+ if len(char) != 1:
375
+ raise ValueError("char debe ser un único carácter")
376
+ if char in ("\n", "\r", "\t") or unicodedata.category(char) == "Cc":
377
+ raise ValueError("char no puede ser un carácter de control")
378
+
379
+ length = _validate_non_negative_int(length, "length")
380
+ color = _validate_color(color)
381
+
382
+ print(_paint(char * length, color))
383
+
384
+
385
+ def banner(
386
+ text: object,
387
+ subtitle: Optional[object] = None,
388
+ color: Optional[str] = None,
389
+ style: str = "box",
390
+ ) -> None:
391
+ """Combina título y subtítulo en un banner completo.
392
+
393
+ Args:
394
+ text: Título principal (admite multilínea).
395
+ subtitle: Subtítulo opcional (admite multilínea). Si es ``None``
396
+ no se añade.
397
+ color: Nombre de color ANSI o ``None``.
398
+ style: ``box``, ``single``, ``double``, ``ascii``, ``minimal``
399
+ o ``simple``.
400
+
401
+ Raises:
402
+ TypeError: Si ``color`` o ``style`` tienen un tipo inválido.
403
+ ValueError: Si ``color`` o ``style`` no son valores admitidos.
404
+ """
405
+ style = _validate_style(style)
406
+ color = _validate_color(color)
407
+
408
+ main_lines = _to_lines(text)
409
+ sub_lines = _to_lines(subtitle) if subtitle is not None else []
410
+
411
+ content: List[str] = list(main_lines)
412
+ if sub_lines:
413
+ divider_width = max(
414
+ (_display_width(line) for line in main_lines + sub_lines), default=0
415
+ )
416
+ content.append("─" * divider_width)
417
+ content.extend(sub_lines)
418
+
419
+ if style in ("simple", "minimal"):
420
+ rendered = _render_block(content, style, color, padding=1)
421
+ else:
422
+ block_width = max((_display_width(line) for line in content), default=0)
423
+ centered = [_pad_center(line, block_width) for line in content]
424
+ rendered = _render_block(centered, style, color, padding=1)
425
+
426
+ for line in rendered:
427
+ print(line)
428
+
429
+
430
+ # ---------------------------------------------------------------------------
431
+ # Demo oficial
432
+ # ---------------------------------------------------------------------------
433
+
434
+ if __name__ == "__main__":
435
+ # Demo oficial de PyBanner
436
+ print("\n=== PyBanner · demo oficial ===\n")
437
+
438
+ banner("PyBanner", subtitle="Terminal toolkit for Python", color="cyan")
439
+ separator("=", 60, color="cyan")
440
+
441
+ print("\n[show]")
442
+ show("Texto simple sin color")
443
+ show("Texto en verde", color="green")
444
+ show("Texto centrado en la terminal", color="magenta", center=True)
445
+
446
+ print("\n[title]")
447
+ title("Título simple", color="blue")
448
+ title("Título minimal", style="minimal", color="green")
449
+ title("Título en caja", style="box", color="cyan")
450
+ title("Título doble", style="double", color="yellow")
451
+ title("Título ascii", style="ascii", color="red")
452
+
453
+ print("\n[box]")
454
+ box("Operación completada", color="green")
455
+ box("Línea 1\nLínea 2\nLínea 3", style="double", color="cyan")
456
+ box("Contenido vacío:\n", style="box", color="yellow")
457
+ box("Unicode: ñ á é í ó ú 漢字 🐍", style="ascii", color="magenta")
458
+
459
+ print("\n[separator]")
460
+ separator("-", 40)
461
+ separator("=", 40, color="blue")
462
+ separator("*", 20, color="yellow")
463
+
464
+ print("\n[banner]")
465
+ banner("CHX Library", subtitle="Official Demo", color="cyan")
466
+ banner("Solo título", style="double", color="green")
467
+ banner(
468
+ "Multilínea\nen banner",
469
+ subtitle="con subtítulo\nen dos líneas",
470
+ style="box",
471
+ color="magenta",
472
+ )
473
+
474
+ print("\n[show con cada estilo]")
475
+ for current_style in _STYLES:
476
+ show(f"estilo = {current_style}", style=current_style, color="cyan")
477
+
478
+ print()
479
+ separator("=", 60, color="cyan")
480
+ print("Fin de la demo.")
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "PyBannerLibrary"
7
+ version = "1.0.0"
8
+ description = "Banners, títulos, marcos y separadores para la terminal sin dependencias."
9
+ requires-python = ">=3.8"
10
+ license = "Apache-2.0"
11
+ authors = [
12
+ { name = "programador777lolxddd-dot" }
13
+ ]
14
+ keywords = ["banner", "terminal", "cli", "ansi", "console", "toolkit"]
15
+ classifiers = [
16
+ "Development Status :: 5 - Production/Stable",
17
+ "Environment :: Console",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.8",
22
+ "Programming Language :: Python :: 3.9",
23
+ "Programming Language :: Python :: 3.10",
24
+ "Programming Language :: Python :: 3.11",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Topic :: Software Development :: Libraries :: Python Modules",
27
+ "Topic :: Terminals",
28
+ ]
29
+
30
+ [project.urls]
31
+ Homepage = "https://github.com/programador777lolxddd-dot/PyBanner"
32
+ Repository = "https://github.com/programador777lolxddd-dot/PyBanner"
33
+ Issues = "https://github.com/programador777lolxddd-dot/PyBanner/issues"
34
+
35
+ [tool.setuptools]
36
+ py-modules = ["pybanner"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+