cysight 1.1.2__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.
cysight/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .console import cprint, set_color_mode
2
+ from .format import cformat, print_format
3
+ from .hexdump import hexdump, print_bytes
4
+ from .mail import dump_mail
cysight/console.py ADDED
@@ -0,0 +1,124 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import sys
5
+ from typing import Optional, Union
6
+
7
+ import colorama
8
+
9
+ _MODES = ("auto", "always", "never")
10
+
11
+ _mode = "auto"
12
+ _console_fixed = False
13
+
14
+ _COLOR_NAMES = {
15
+ "black": colorama.Fore.BLACK,
16
+ "red": colorama.Fore.RED,
17
+ "green": colorama.Fore.GREEN,
18
+ "yellow": colorama.Fore.YELLOW,
19
+ "blue": colorama.Fore.BLUE,
20
+ "magenta": colorama.Fore.MAGENTA,
21
+ "cyan": colorama.Fore.CYAN,
22
+ "white": colorama.Fore.WHITE,
23
+ "bright_black": colorama.Fore.LIGHTBLACK_EX,
24
+ "bright_red": colorama.Fore.LIGHTRED_EX,
25
+ "bright_green": colorama.Fore.LIGHTGREEN_EX,
26
+ "bright_yellow": colorama.Fore.LIGHTYELLOW_EX,
27
+ "bright_blue": colorama.Fore.LIGHTBLUE_EX,
28
+ "bright_magenta": colorama.Fore.LIGHTMAGENTA_EX,
29
+ "bright_cyan": colorama.Fore.LIGHTCYAN_EX,
30
+ "bright_white": colorama.Fore.LIGHTWHITE_EX,
31
+ }
32
+ _COLOR_NAMES.update({k.replace("bright_", "light_"): v for k, v in _COLOR_NAMES.items()})
33
+
34
+ _STYLE_NAMES = {
35
+ "dim": colorama.Style.DIM,
36
+ "normal": colorama.Style.NORMAL,
37
+ "bright": colorama.Style.BRIGHT,
38
+ "bold": colorama.Style.BRIGHT,
39
+ "reset": colorama.Style.RESET_ALL,
40
+ }
41
+
42
+
43
+ def ensure_console() -> None:
44
+ global _console_fixed
45
+ if not _console_fixed:
46
+ try:
47
+ colorama.just_fix_windows_console()
48
+ except AttributeError:
49
+ colorama.init()
50
+ _console_fixed = True
51
+
52
+
53
+ def set_color_mode(mode: str) -> None:
54
+ global _mode
55
+ if mode not in _MODES:
56
+ raise ValueError(f"mode must be one of {_MODES!r}")
57
+ _mode = mode
58
+
59
+
60
+ def get_color_mode() -> str:
61
+ return _mode
62
+
63
+
64
+ def _env_flag(name: str) -> bool:
65
+ value = os.environ.get(name, "")
66
+ return bool(value) and value.lower() not in ("0", "false", "no", "off")
67
+
68
+
69
+ def colors_enabled(stream: Optional[object] = None) -> bool:
70
+ if stream is None:
71
+ stream = sys.stdout
72
+ if _mode == "never":
73
+ return False
74
+ if _mode == "always":
75
+ return True
76
+ if _env_flag("NO_COLOR"):
77
+ return False
78
+ if _env_flag("FORCE_COLOR"):
79
+ return True
80
+ isatty = getattr(stream, "isatty", None)
81
+ return bool(isatty and isatty())
82
+
83
+
84
+ def _resolve(value: object, names: dict, kind: str) -> str:
85
+ if isinstance(value, str):
86
+ if value.startswith("\x1b"):
87
+ return value
88
+ key = value.lower()
89
+ if key in names:
90
+ return names[key]
91
+ raise ValueError(f"unknown {kind} name: {value!r}")
92
+
93
+
94
+ def resolve_color(color: object) -> str:
95
+ return _resolve(color, _COLOR_NAMES, "color")
96
+
97
+
98
+ def resolve_style(style: object) -> str:
99
+ return _resolve(style, _STYLE_NAMES, "style")
100
+
101
+
102
+ def cprint(
103
+ *values: object,
104
+ color: Optional[Union[str, object]] = None,
105
+ style: Optional[Union[str, object]] = None,
106
+ sep: str = " ",
107
+ end: str = "\n",
108
+ file: Optional[object] = None,
109
+ force: bool = False,
110
+ ) -> None:
111
+ stream = sys.stdout if file is None else file
112
+ enabled = force or colors_enabled(stream)
113
+ prefix = suffix = ""
114
+ if color is not None or style is not None:
115
+ codes = []
116
+ if color is not None:
117
+ codes.append(resolve_color(color))
118
+ if style is not None:
119
+ codes.append(resolve_style(style))
120
+ if enabled:
121
+ ensure_console()
122
+ prefix = "".join(codes)
123
+ suffix = colorama.Style.RESET_ALL
124
+ stream.write(prefix + sep.join(str(v) for v in values) + suffix + end)
cysight/format.py ADDED
@@ -0,0 +1,76 @@
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import sys
5
+ from typing import Optional
6
+
7
+ import colorama
8
+
9
+ from . import console
10
+
11
+ _TAG_RE = re.compile(r"\{(/?)([A-Za-z_]*)\}")
12
+
13
+
14
+ def _known_tag(name: str) -> bool:
15
+ for resolver in (console.resolve_color, console.resolve_style):
16
+ try:
17
+ resolver(name)
18
+ return True
19
+ except ValueError:
20
+ pass
21
+ return False
22
+
23
+
24
+ def _apply_tags(template: str, enabled: bool) -> str:
25
+ out = []
26
+ i = 0
27
+ n = len(template)
28
+ while i < n:
29
+ ch = template[i]
30
+ if ch == "{" and i + 1 < n and template[i + 1] == "{":
31
+ out.append("{{")
32
+ i += 2
33
+ continue
34
+ if ch == "{":
35
+ m = _TAG_RE.match(template, i)
36
+ if m is not None:
37
+ closing = m.group(1) == "/"
38
+ name = m.group(2)
39
+ if closing or _known_tag(name):
40
+ if enabled:
41
+ if closing:
42
+ out.append(colorama.Style.RESET_ALL)
43
+ else:
44
+ try:
45
+ out.append(console.resolve_color(name))
46
+ except ValueError:
47
+ out.append(console.resolve_style(name))
48
+ i = m.end()
49
+ continue
50
+ out.append(ch)
51
+ i += 1
52
+ return "".join(out)
53
+
54
+
55
+ def cformat(
56
+ template: str,
57
+ *args: object,
58
+ stream: Optional[object] = None,
59
+ force: bool = False,
60
+ **kwargs: object,
61
+ ) -> str:
62
+ enabled = force or console.colors_enabled(stream)
63
+ return _apply_tags(template, enabled).format(*args, **kwargs)
64
+
65
+
66
+ def print_format(
67
+ template: str,
68
+ *args: object,
69
+ file: Optional[object] = None,
70
+ end: str = "\n",
71
+ force: bool = False,
72
+ **kwargs: object,
73
+ ) -> None:
74
+ stream = sys.stdout if file is None else file
75
+ text = cformat(template, *args, stream=stream, force=force, **kwargs)
76
+ stream.write(text + end)
cysight/hexdump.py ADDED
@@ -0,0 +1,57 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from typing import Optional
5
+
6
+ import colorama
7
+
8
+ from . import console
9
+
10
+
11
+ def hexdump(
12
+ data: bytes,
13
+ width: int = 16,
14
+ colorize: bool = True,
15
+ force: bool = False,
16
+ stream: Optional[object] = None,
17
+ ) -> str:
18
+ if width < 2 or width % 2 != 0:
19
+ raise ValueError("width must be a positive even integer")
20
+ if not data:
21
+ return ""
22
+ enabled = colorize and (force or console.colors_enabled(stream))
23
+ half = width // 2
24
+ dim = colorama.Style.DIM
25
+ cyan = colorama.Fore.CYAN
26
+ reset = colorama.Style.RESET_ALL
27
+ lines = []
28
+ for offset in range(0, len(data), width):
29
+ chunk = data[offset:offset + width]
30
+ pairs = [f"{b:02x}" for b in chunk]
31
+ hex_left = " ".join(pairs[:half]).ljust(3 * half - 1)
32
+ hex_right = " ".join(pairs[half:]).ljust(3 * (width - half) - 1)
33
+ plain = "".join(chr(b) if 32 <= b < 127 else "." for b in chunk)
34
+ ascii_chars = []
35
+ for b in chunk:
36
+ if 32 <= b < 127:
37
+ ascii_chars.append(cyan + chr(b) + reset if enabled else chr(b))
38
+ else:
39
+ ascii_chars.append(dim + "." + reset if enabled else ".")
40
+ padding = " " * (width - len(chunk))
41
+ prefix = dim + f"{offset:08x}" + reset if enabled else f"{offset:08x}"
42
+ lines.append(f"{prefix} {hex_left} {hex_right} |{''.join(ascii_chars)}{padding}|")
43
+ return "\n".join(lines)
44
+
45
+
46
+ def print_bytes(
47
+ data: bytes,
48
+ width: int = 16,
49
+ colorize: bool = True,
50
+ force: bool = False,
51
+ end: str = "\n",
52
+ file: Optional[object] = None,
53
+ ) -> None:
54
+ stream = sys.stdout if file is None else file
55
+ text = hexdump(data, width=width, colorize=colorize, force=force, stream=stream)
56
+ if text:
57
+ stream.write(text + end)
cysight/mail.py ADDED
@@ -0,0 +1,80 @@
1
+ from __future__ import annotations
2
+
3
+ import sys
4
+ from typing import Optional, Union
5
+
6
+ import mailreader
7
+
8
+ from . import console
9
+ from .hexdump import hexdump
10
+
11
+ _LINE = "-" * 60
12
+
13
+
14
+ def dump_mail(
15
+ raw_or_doc: Union[bytes, bytearray, str, "mailreader.MailDocument"],
16
+ include_payload: bool = False,
17
+ show_bytes: bool = False,
18
+ file: Optional[object] = None,
19
+ ) -> "mailreader.MailDocument":
20
+ stream = sys.stdout if file is None else file
21
+ doc = raw_or_doc
22
+ if isinstance(raw_or_doc, (bytes, bytearray, str)):
23
+ raw = bytes(raw_or_doc) if isinstance(raw_or_doc, bytearray) else raw_or_doc
24
+ doc = mailreader.parse_mail(raw, include_payload=include_payload)
25
+ _print_headers(doc, stream)
26
+ _print_body(doc, stream)
27
+ _print_attachments(doc, show_bytes, stream)
28
+ _print_parts(doc, stream)
29
+ return doc
30
+
31
+
32
+ def _print_headers(doc, stream) -> None:
33
+ console.cprint(doc.subject or "(no subject)", color="bright_cyan", style="bright", file=stream)
34
+ console.cprint(f"From: {doc.from_}" if doc.from_ else "From: (unknown)", color="green", file=stream)
35
+ for key, value in doc.headers.items():
36
+ if key.lower() in ("subject", "from"):
37
+ continue
38
+ console.cprint(f"{key}: {value}", style="dim", file=stream)
39
+ console.cprint(_LINE, style="dim", file=stream)
40
+
41
+
42
+ def _print_body(doc, stream) -> None:
43
+ if doc.text:
44
+ stream.write(doc.text + "\n\n")
45
+
46
+
47
+ def _print_attachments(doc, show_bytes: bool, stream) -> None:
48
+ if doc.attachments:
49
+ console.cprint("Attachments:", color="yellow", style="bright", file=stream)
50
+ for att in doc.attachments:
51
+ name = att.get("filename") or "(unnamed)"
52
+ ctype = att.get("content_type") or "?"
53
+ size = att.get("size") or 0
54
+ console.cprint(f" {name} ({ctype}, {size} bytes)", color="yellow", file=stream)
55
+ if show_bytes:
56
+ payload = att.get("payload")
57
+ if payload is not None:
58
+ stream.write(hexdump(bytes(payload), stream=stream) + "\n")
59
+ else:
60
+ console.cprint(" (payload not loaded; parse with include_payload=True)", style="dim", file=stream)
61
+ if doc.inline_images:
62
+ console.cprint("Inline images:", color="yellow", style="bright", file=stream)
63
+ for img in doc.inline_images:
64
+ name = img.get("filename") or img.get("content_id") or "(unnamed)"
65
+ ctype = img.get("content_type") or "?"
66
+ size = img.get("size") or 0
67
+ console.cprint(f" {name} ({ctype}, {size} bytes)", color="yellow", file=stream)
68
+
69
+
70
+ def _print_parts(doc, stream) -> None:
71
+ if not doc.parts:
72
+ return
73
+ console.cprint("Parts:", color="magenta", style="bright", file=stream)
74
+ for part in doc.parts:
75
+ ctype = part.get("content_type") or "?"
76
+ charset = part.get("charset") or "-"
77
+ disp = part.get("disposition") or "-"
78
+ fname = part.get("filename") or "-"
79
+ size = part.get("size") or 0
80
+ console.cprint(f" {ctype} charset={charset} disposition={disp} filename={fname} size={size}", color="magenta", file=stream)
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: cysight
3
+ Version: 1.1.2
4
+ Summary: Colored terminal output and mail dumping.
5
+ Author-email: jiniuse <jiniuse@gmail.com>
6
+ License: MIT
7
+ Keywords: color,colorama,terminal,mail,mailreader,hexdump
8
+ Classifier: Development Status :: 5 - Production/Stable
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3.8
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Communications :: Email
19
+ Classifier: Topic :: Terminals
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: colorama
25
+ Requires-Dist: mailreader
26
+ Dynamic: license-file
27
+
28
+ Colored terminal output for Python and a one-call colored dump. Works on Windows, macOS,
29
+ and Linux. cysight is a printer, nothing else: it formats and writes color.
30
+
31
+ ## Installation
32
+
33
+ ```powershell
34
+ pip install cysight
35
+ ```
36
+
37
+ ## Quick start
38
+
39
+ ```python
40
+ import cysight
41
+
42
+ cysight.cprint("ready", color="cyan")
43
+ print(cysight.hexdump(b"Hello World!"))
44
+ cysight.print_format("{red}Error:{/red} code={code}", code=42)
45
+
46
+ raw = open("message.eml", "rb").read()
47
+ doc = cysight.dump_mail(raw, include_payload=True, show_bytes=True)
48
+ ```
49
+
50
+ ## API
51
+
52
+ | Function | Description |
53
+ |---|---|
54
+ | `cprint(*values, color=None, style=None, sep=" ", end="\n", file=None, force=False)` | Print with a single color/style applied to the whole line. `color`/`style` accept colorama constants or names (`"red"`, `"bright_cyan"`, `"dim"`, `"bold"`). |
55
+ | `hexdump(data, width=16, colorize=True, force=False, stream=None)` | Classic offset/hex/ASCII dump as a string. Printable ASCII rendered cyan, non-printables dim. `width` must be a positive even integer. |
56
+ | `print_bytes(data, width=16, colorize=True, force=False, end="\n", file=None)` | Print `hexdump()` to a stream. |
57
+ | `cformat(template, *args, stream=None, force=False, **kwargs)` | Resolve inline color tags (`{red}`, `{bold}`, `{dim}`, `{/red}`, `{/}`) to ANSI codes, then apply `str.format`. Returns a string. Unknown tag names pass through to `format`; use `{{red}}` for a literal. |
58
+ | `print_format(template, *args, file=None, end="\n", force=False, **kwargs)` | `cformat` + write to a stream. |
59
+ | `dump_mail(raw_or_doc, include_payload=False, show_bytes=False, file=None)` | Accept raw mail (`bytes`/`str`, parsed via `mailreader.parse_mail`) or an already-parsed `MailDocument`. Subject cyan, From green, other headers dim, body plain, attachments/inline images yellow, parts magenta, payloads hex-dumped when `show_bytes=True`. Returns the document. |
60
+ | `set_color_mode(mode)` | Global override: `"auto"` (default), `"always"`, `"never"`. |
61
+ | `console.colors_enabled(stream=None)` | Whether color codes will be emitted for a stream. |
62
+
63
+ ## Color policy
64
+
65
+ Colors auto-disable when the target stream is not a TTY (piped or
66
+ redirected output). Two environment variables are honored:
67
+
68
+ | Variable | Effect |
69
+ |---|---|
70
+ | `NO_COLOR` | Force colors off (https://no-color.org). |
71
+ | `FORCE_COLOR` | Force colors on, even when piped. |
72
+
73
+ Per call, `force=True` overrides detection for that call. Windows
74
+ ANSI/VT support is enabled once via `colorama.just_fix_windows_console()`;
75
+ legacy consoles fall back to colorama's sequence converter. macOS and
76
+ Linux use native ANSI.
77
+
78
+ ## Errors
79
+
80
+ Unknown color/style/tag names, and an invalid `set_color_mode` value,
81
+ raise `ValueError`. `dump_mail` propagates mailreader's error subtree
82
+ (`MailReaderError`) untouched.
83
+
84
+ ## License
85
+
86
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,10 @@
1
+ cysight/__init__.py,sha256=YdgVhllLT2ZQagODcfTKOOymf1805v33to33u2eOqKU,156
2
+ cysight/console.py,sha256=D_OhzbvfM6TCnsTkXvAlOw7SkRHyI1gAJh2BjnDlXe4,3411
3
+ cysight/format.py,sha256=LlSD82-3PHSUkEY5cVFuqcT7jj8o81qnC1AtpWYPSdI,2000
4
+ cysight/hexdump.py,sha256=eTERS7wpD0N_7wVJlS7rLKw1e4_aS2v28wJSHFRJEf0,1803
5
+ cysight/mail.py,sha256=C12sMWKZiJWMA-t18YoSyARSku5-ivteSABBE2g8_UA,3136
6
+ cysight-1.1.2.dist-info/licenses/LICENSE,sha256=VTH8A6tM5k1a96FJr75zLJs525Z5r9XnsOIvvUxvMUo,1064
7
+ cysight-1.1.2.dist-info/METADATA,sha256=QBDa08JKSBbuLPDTeyyyy61gQIAR6NssT1QGAfcR_kc,3875
8
+ cysight-1.1.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ cysight-1.1.2.dist-info/top_level.txt,sha256=rJGN01LpDlfWIaSPlniTzbtJ0Lbk4SfXdsEYtFH2qsE,8
10
+ cysight-1.1.2.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 jiniuse
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
+ cysight