tokzip 1.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.
- tokzip/__init__.py +5 -0
- tokzip/__main__.py +5 -0
- tokzip/cleaners/__init__.py +1 -0
- tokzip/cleaners/chat.py +116 -0
- tokzip/cleaners/code.py +243 -0
- tokzip/cleaners/common.py +52 -0
- tokzip/cleaners/json_fmt.py +17 -0
- tokzip/cleaners/text.py +107 -0
- tokzip/cli.py +150 -0
- tokzip/clipboard.py +58 -0
- tokzip/config.py +130 -0
- tokzip/deps.py +53 -0
- tokzip/dictionary.py +266 -0
- tokzip/gui.py +615 -0
- tokzip/logging_setup.py +64 -0
- tokzip/pathguard.py +207 -0
- tokzip/runner.py +351 -0
- tokzip/tokens.py +52 -0
- tokzip/version.py +1 -0
- tokzip-1.0.0.dist-info/METADATA +127 -0
- tokzip-1.0.0.dist-info/RECORD +25 -0
- tokzip-1.0.0.dist-info/WHEEL +5 -0
- tokzip-1.0.0.dist-info/entry_points.txt +2 -0
- tokzip-1.0.0.dist-info/licenses/LICENSE +22 -0
- tokzip-1.0.0.dist-info/top_level.txt +1 -0
tokzip/__init__.py
ADDED
tokzip/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Content-aware cleaners used by the compression runner."""
|
tokzip/cleaners/chat.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections import Counter
|
|
3
|
+
|
|
4
|
+
from ..config import TAGS, ModeCfg
|
|
5
|
+
from .common import EMOJI_RE, _normalize, fenced_lines, strip_markdown_safe
|
|
6
|
+
|
|
7
|
+
_REACT = "👁❤👍👎🔥💋💩🦄🍓🍌🌭💯⭐🫡🙏🎉👏"
|
|
8
|
+
RE_MSG_HEADER = re.compile(r"^\s*>?\s*\*{0,2}(.*?)\*{0,2}\s+·\s+`?(\d{2}:\d{2})`?")
|
|
9
|
+
RE_MSG_HEADER_ML = re.compile(r"(?m)^[ \t]*>?[ \t]*\*{0,2}[^\n]{1,60}?\*{0,2}[ \t]+·[ \t]+`?\d{2}:\d{2}`?")
|
|
10
|
+
RE_DATE = re.compile(r"^###\s+(\d+\s+[а-яА-Яa-zA-Z0-9]+)")
|
|
11
|
+
RE_DATE_ML = re.compile(r"(?m)^###\s+\d+\s+[а-яА-Яa-zA-Z]+")
|
|
12
|
+
RE_REPLY = re.compile(r"^\s*>?\s*\*?↩\s*(.*?):")
|
|
13
|
+
# Reaction rows contain only emoji, optional counts, and surrounding markup.
|
|
14
|
+
RE_REACT_PURE = re.compile(rf"^[\s>*_]*(?:[{_REACT}]\uFE0F?[\s\d×x·,]*)+[*_]*$")
|
|
15
|
+
_INDENTED = re.compile(r"^(?:[ \t]*>[ \t]?)*(?: {2}|\t)")
|
|
16
|
+
_MEDIA_MAP = [
|
|
17
|
+
(re.compile(r"\*?\[(\d+)\s+фото\]\*?"), r"$\1P"),
|
|
18
|
+
(re.compile(r"\*?\[(\d+)\s+видео\]\*?"), r"$\1V"),
|
|
19
|
+
(re.compile(r"\*?\[фото\]\*?"), "$P"),
|
|
20
|
+
(re.compile(r"\*?\[видео\]\*?"), "$V"),
|
|
21
|
+
(re.compile(r"\*?\[стикер\]\*?"), "$S"),
|
|
22
|
+
(re.compile(r"\*?\[голосовое сообщение\]\*?"), "$A"),
|
|
23
|
+
(re.compile(r"\*?\[документ\]\*?"), "$D"),
|
|
24
|
+
]
|
|
25
|
+
_MEDIA_LEGEND = {
|
|
26
|
+
"en": "$P photo, $V video, $S sticker, $A voice, $D document",
|
|
27
|
+
"ru": "$P фото, $V видео, $S стикер, $A голосовое, $D документ",
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def looks_like_chat(text: str) -> bool:
|
|
32
|
+
# Message-looking lines inside sample code do not indicate a chat export.
|
|
33
|
+
head = "\n".join(line for line, protected in fenced_lines(text[:30000]) if not protected)
|
|
34
|
+
hdr = len(RE_MSG_HEADER_ML.findall(head))
|
|
35
|
+
return hdr >= 3 or (hdr >= 1 and len(RE_DATE_ML.findall(head)) >= 2)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _is_reaction(line: str) -> bool:
|
|
39
|
+
return bool(RE_REACT_PURE.fullmatch(line))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def clean_chat(text: str, cfg: ModeCfg, lang: str = "en") -> str:
|
|
43
|
+
lines = list(fenced_lines(text.replace("\r\n", "\n").replace("\r", "\n")))
|
|
44
|
+
authors = Counter()
|
|
45
|
+
for line, protected in lines:
|
|
46
|
+
if not protected and not _INDENTED.match(line):
|
|
47
|
+
match = RE_MSG_HEADER.match(line)
|
|
48
|
+
if match:
|
|
49
|
+
authors[match[1].replace("*", "").strip()] += 1
|
|
50
|
+
users = {name: f"U{i}" for i, (name, _) in enumerate(authors.most_common()) if name}
|
|
51
|
+
out = []
|
|
52
|
+
message = []
|
|
53
|
+
sender = stamp = reply = ""
|
|
54
|
+
media_used = False
|
|
55
|
+
previous = None
|
|
56
|
+
|
|
57
|
+
def flush() -> None:
|
|
58
|
+
nonlocal previous
|
|
59
|
+
while message and message[-1] == ("", False):
|
|
60
|
+
message.pop()
|
|
61
|
+
start = next((i for i, line in enumerate(message) if line != ("", False)), len(message))
|
|
62
|
+
if start < len(message):
|
|
63
|
+
content = "\n".join(line for line, _ in message[start:])
|
|
64
|
+
multiline = len(message) - start > 1 or message[start][1]
|
|
65
|
+
key = (sender, reply, stamp)
|
|
66
|
+
if not sender:
|
|
67
|
+
out.append(content)
|
|
68
|
+
previous = None
|
|
69
|
+
elif not multiline and key == previous:
|
|
70
|
+
out[-1] += " // " + content
|
|
71
|
+
else:
|
|
72
|
+
header = (f"{stamp} " if stamp else "") + sender + (f">{reply}" if reply else "")
|
|
73
|
+
out.append(header + (":\n" if multiline else ": ") + content)
|
|
74
|
+
previous = None if multiline else key
|
|
75
|
+
message.clear()
|
|
76
|
+
|
|
77
|
+
for raw, fenced in lines:
|
|
78
|
+
if fenced or _INDENTED.match(raw):
|
|
79
|
+
message.append((raw, True))
|
|
80
|
+
continue
|
|
81
|
+
line = _normalize(raw).strip().replace("\\_", "_")
|
|
82
|
+
date = RE_DATE.match(line)
|
|
83
|
+
header = RE_MSG_HEADER.match(line)
|
|
84
|
+
if date:
|
|
85
|
+
flush()
|
|
86
|
+
out.append(f"#{date[1]}")
|
|
87
|
+
sender = stamp = reply = ""
|
|
88
|
+
previous = None
|
|
89
|
+
elif header:
|
|
90
|
+
flush()
|
|
91
|
+
name = header[1].replace("*", "").strip()
|
|
92
|
+
sender = users.get(name, name)
|
|
93
|
+
stamp = "" if cfg.flatten else header[2]
|
|
94
|
+
reply = ""
|
|
95
|
+
elif sender and (target := RE_REPLY.match(line)):
|
|
96
|
+
name = target[1].replace("*", "").strip()
|
|
97
|
+
reply = users.get(name, name)
|
|
98
|
+
elif line not in ("---", ">", ">>") and not _is_reaction(line):
|
|
99
|
+
for pattern, substitute in _MEDIA_MAP:
|
|
100
|
+
line, changed = pattern.subn(substitute, line)
|
|
101
|
+
media_used |= bool(changed)
|
|
102
|
+
if cfg.strip_markup:
|
|
103
|
+
line = strip_markdown_safe(line)
|
|
104
|
+
if cfg.strip_emoji:
|
|
105
|
+
line = EMOJI_RE.sub("", line)
|
|
106
|
+
message.append((re.sub(r"[ \t]{2,}", " ", line), False))
|
|
107
|
+
flush()
|
|
108
|
+
|
|
109
|
+
tags = TAGS[lang]
|
|
110
|
+
headers = []
|
|
111
|
+
if media_used:
|
|
112
|
+
headers.append(f"[{tags['media']}] {_MEDIA_LEGEND[lang]}")
|
|
113
|
+
if users:
|
|
114
|
+
listing = " ".join(f"{alias}={name}" for name, alias in users.items())
|
|
115
|
+
headers.append(f"[{tags['users']}] {listing}")
|
|
116
|
+
return "\n".join(headers + out)
|
tokzip/cleaners/code.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import io
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import tokenize
|
|
8
|
+
import warnings
|
|
9
|
+
from functools import lru_cache
|
|
10
|
+
|
|
11
|
+
from ..config import ModeCfg
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
CODE_STYLES = {}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _register(style: str, *extensions: str) -> None:
|
|
18
|
+
CODE_STYLES.update(dict.fromkeys(extensions, style))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_register("py", ".py", ".pyw")
|
|
22
|
+
_register("hash", ".sh", ".bash", ".zsh", ".rb", ".pl", ".yml", ".yaml", ".toml", ".r", ".mk")
|
|
23
|
+
_register("ps", ".ps1", ".psm1", ".psd1")
|
|
24
|
+
_register("bat", ".bat", ".cmd")
|
|
25
|
+
_register("c", ".js", ".mjs", ".cjs", ".ts", ".jsx", ".tsx", ".c", ".h", ".cc", ".cpp", ".hpp", ".cs",
|
|
26
|
+
".java", ".go", ".rs", ".php", ".kt", ".kts", ".swift", ".dart", ".scala", ".groovy",
|
|
27
|
+
".gradle", ".scss", ".less")
|
|
28
|
+
_register("css", ".css")
|
|
29
|
+
_register("sql", ".sql")
|
|
30
|
+
_register("html", ".html", ".htm", ".xml", ".xaml", ".csproj")
|
|
31
|
+
|
|
32
|
+
_CHAR_LIT_EXTS = {".c", ".h", ".cc", ".cpp", ".hpp", ".cs", ".java", ".go", ".rs", ".kt", ".kts", ".swift", ".scala"}
|
|
33
|
+
_RE_BAT_COMMENT = re.compile(r"(?im)^[ \t]*(?:@?rem(?:[ \t][^\n]*)?|::[^\n]*)$\n?")
|
|
34
|
+
_HEREDOC = re.compile(r"<<[-~]?[ \t]*[\\'\"]?\w")
|
|
35
|
+
_YAML_SCALAR = re.compile(r"(?m)(?:^|:[ \t]+|-[ \t]+)[ \t]*[|>][-+1-9]{0,2}[ \t]*(?:#.*)?$")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _tokens(code: str) -> list[tokenize.TokenInfo]:
|
|
39
|
+
return list(tokenize.generate_tokens(io.StringIO(code).readline))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _python_string_lines(tokens: list[tokenize.TokenInfo]) -> set[int]:
|
|
43
|
+
protected = set()
|
|
44
|
+
interpolated = []
|
|
45
|
+
for token in tokens:
|
|
46
|
+
kind = tokenize.tok_name[token.type]
|
|
47
|
+
if kind in ("FSTRING_START", "TSTRING_START"):
|
|
48
|
+
interpolated.append(token.start[0])
|
|
49
|
+
elif kind in ("FSTRING_END", "TSTRING_END"):
|
|
50
|
+
start = interpolated.pop()
|
|
51
|
+
if start < token.end[0]:
|
|
52
|
+
protected.update(range(start, token.end[0] + 1))
|
|
53
|
+
elif token.type == tokenize.STRING and token.start[0] < token.end[0]:
|
|
54
|
+
protected.update(range(token.start[0], token.end[0] + 1))
|
|
55
|
+
return protected
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _python_edits(code: str, tree: ast.AST, tokens: list[tokenize.TokenInfo]) -> str:
|
|
59
|
+
lines = code.split("\n")
|
|
60
|
+
starts = [0]
|
|
61
|
+
for line in lines:
|
|
62
|
+
starts.append(starts[-1] + len(line) + 1)
|
|
63
|
+
edits = []
|
|
64
|
+
|
|
65
|
+
def character_offset(line: int, byte_column: int) -> int:
|
|
66
|
+
prefix = lines[line - 1].encode("utf-8")[:byte_column]
|
|
67
|
+
return starts[line - 1] + len(prefix.decode("utf-8"))
|
|
68
|
+
|
|
69
|
+
for node in ast.walk(tree):
|
|
70
|
+
if not isinstance(node, (ast.Module, ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
71
|
+
continue
|
|
72
|
+
if ast.get_docstring(node, clean=False) is None:
|
|
73
|
+
continue
|
|
74
|
+
doc, *rest = node.body
|
|
75
|
+
start = character_offset(doc.lineno, doc.col_offset)
|
|
76
|
+
end = character_offset(doc.end_lineno, doc.end_col_offset)
|
|
77
|
+
tail = lines[doc.end_lineno - 1][end - starts[doc.end_lineno - 1]:]
|
|
78
|
+
next_is_string = (rest and isinstance(rest[0], ast.Expr)
|
|
79
|
+
and isinstance(rest[0].value, ast.Constant)
|
|
80
|
+
and isinstance(rest[0].value.value, str))
|
|
81
|
+
needs_pass = (not rest and not isinstance(node, ast.Module)) or next_is_string
|
|
82
|
+
if not needs_pass and tail.lstrip().startswith(";"):
|
|
83
|
+
after_semicolon = tail.split(";", 1)[1]
|
|
84
|
+
end += len(tail) - len(after_semicolon.lstrip(" \t"))
|
|
85
|
+
edits.append((start, end, "pass" if needs_pass else ""))
|
|
86
|
+
|
|
87
|
+
for token in tokens:
|
|
88
|
+
if token.type == tokenize.COMMENT:
|
|
89
|
+
line, column = token.start
|
|
90
|
+
if line == 1 and column == 0 and token.string.startswith("#!"):
|
|
91
|
+
continue
|
|
92
|
+
edits.append((starts[line - 1] + column, starts[line - 1] + token.end[1], ""))
|
|
93
|
+
|
|
94
|
+
parts, cursor = [], 0
|
|
95
|
+
for start, end, replacement in sorted(edits):
|
|
96
|
+
if start >= cursor:
|
|
97
|
+
parts.extend((code[cursor:start], replacement))
|
|
98
|
+
cursor = end
|
|
99
|
+
parts.append(code[cursor:])
|
|
100
|
+
return "".join(parts)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _clean_python(original: str, cfg: ModeCfg) -> str:
|
|
104
|
+
code = original.replace("\r\n", "\n").replace("\r", "\n")
|
|
105
|
+
try:
|
|
106
|
+
with warnings.catch_warnings():
|
|
107
|
+
warnings.simplefilter("ignore", SyntaxWarning)
|
|
108
|
+
warnings.simplefilter("ignore", DeprecationWarning)
|
|
109
|
+
tree = ast.parse(code)
|
|
110
|
+
if cfg.strip_comments:
|
|
111
|
+
compile(tree, "<input>", "exec", dont_inherit=True)
|
|
112
|
+
code = _python_edits(code, tree, _tokens(code))
|
|
113
|
+
tree = ast.parse(code)
|
|
114
|
+
compile(tree, "<input>", "exec", dont_inherit=True)
|
|
115
|
+
protected = _python_string_lines(_tokens(code))
|
|
116
|
+
# Explicit continuation backslashes need their following physical lines.
|
|
117
|
+
lines = code.split("\n")
|
|
118
|
+
if any(line.endswith("\\") and i not in protected for i, line in enumerate(lines, 1)):
|
|
119
|
+
return code
|
|
120
|
+
formatted = _format_lines(code, protected, cfg.blank_code)
|
|
121
|
+
if ast.dump(ast.parse(formatted)) == ast.dump(tree):
|
|
122
|
+
return formatted
|
|
123
|
+
return code
|
|
124
|
+
except (SyntaxError, ValueError, UnicodeError, RecursionError, tokenize.TokenError):
|
|
125
|
+
return original
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@lru_cache(maxsize=None)
|
|
129
|
+
def _style_regex(style: str, ext: str) -> re.Pattern:
|
|
130
|
+
dq = r'"(?:\\[\s\S]|[^"\\\n])*"'
|
|
131
|
+
sq = r"'(?:\\[\s\S]|[^'\\\n])*'"
|
|
132
|
+
if style == "hash":
|
|
133
|
+
strings = r"""\"{3}[\s\S]*?\"{3}|'{3}[\s\S]*?'{3}|"(?:\\[\s\S]|[^"\\])*"|'[^']*'"""
|
|
134
|
+
comments = r"(?<![^\s])#[^\n]*"
|
|
135
|
+
elif style == "ps":
|
|
136
|
+
strings = (r'@"[ \t]*\n[\s\S]*?^[ \t]*"@|@\x27[ \t]*\n[\s\S]*?^[ \t]*\x27@|'
|
|
137
|
+
r'"(?:\x60[\s\S]|""|[^"\x60])*"|\x27(?:\x27\x27|[^\x27])*\x27')
|
|
138
|
+
comments = r"<#[\s\S]*?#>|(?<![^\s])#[^\n]*"
|
|
139
|
+
elif style in ("c", "css"):
|
|
140
|
+
if ext in _CHAR_LIT_EXTS:
|
|
141
|
+
sq = r"'(?:\\(?:u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|u\{[0-9a-fA-F]+\}|[\s\S])|[^'\\\n])'"
|
|
142
|
+
parts = [r'(?P<raw_quotes>"{3,})[\s\S]*?(?P=raw_quotes)', dq, sq,
|
|
143
|
+
r"\x60(?:\\[\s\S]|[^\x60\\])*\x60"]
|
|
144
|
+
if ext == ".cs":
|
|
145
|
+
parts.insert(0, r'@"(?:[^"]|"")*"')
|
|
146
|
+
elif ext in {".c", ".h", ".cc", ".cpp", ".hpp"}:
|
|
147
|
+
parts.insert(0, r'R"(?P<cpp_delimiter>[^()\s\\]{0,16})\([\s\S]*?\)(?P=cpp_delimiter)"')
|
|
148
|
+
elif ext == ".rs":
|
|
149
|
+
parts.insert(0, r'(?<!\w)[bc]?r(?P<rust_hashes>#*)"[\s\S]*?"(?P=rust_hashes)')
|
|
150
|
+
strings = "|".join(parts)
|
|
151
|
+
comments = r"/\*[\s\S]*?\*/" if style == "css" else r"/\*[\s\S]*?\*/|(?<!:)//[^\n]*"
|
|
152
|
+
elif style == "sql":
|
|
153
|
+
strings = r"(?P<dollar>\$(?:[A-Za-z_]\w*)?\$)[\s\S]*?(?P=dollar)|'(?:''|[^'])*'|\"(?:\"\"|[^\"])*\""
|
|
154
|
+
comments = r"--[^\n]*|/\*[\s\S]*?\*/"
|
|
155
|
+
else: # HTML and XML
|
|
156
|
+
strings = r"<!\[CDATA\[[\s\S]*?\]\]>|" + dq + "|" + sq
|
|
157
|
+
comments = r"<!--[\s\S]*?-->"
|
|
158
|
+
return re.compile(f"(?P<literal>{strings})|(?P<comment>{comments})", re.MULTILINE)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _protected_lines(code: str, regex: re.Pattern) -> set[int]:
|
|
162
|
+
protected = set()
|
|
163
|
+
line, previous = 1, 0
|
|
164
|
+
for match in regex.finditer(code):
|
|
165
|
+
if match["literal"] is None:
|
|
166
|
+
continue
|
|
167
|
+
span = match[0].count("\n")
|
|
168
|
+
if span:
|
|
169
|
+
line += code.count("\n", previous, match.start())
|
|
170
|
+
previous = match.start()
|
|
171
|
+
protected.update(range(line, line + span + 1))
|
|
172
|
+
return protected
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _indent_unit(code: str, protected: set[int]) -> int:
|
|
176
|
+
unit = 0
|
|
177
|
+
for i, line in enumerate(code.split("\n"), 1):
|
|
178
|
+
if i not in protected and line.strip():
|
|
179
|
+
lead = line[:len(line) - len(line.lstrip(" \t"))]
|
|
180
|
+
if "\t" in lead:
|
|
181
|
+
return 0
|
|
182
|
+
unit = math.gcd(unit, len(lead))
|
|
183
|
+
return unit
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _format_lines(code: str, protected: set[int], max_blank: int, unit: int = 0,
|
|
187
|
+
flatten: bool = False) -> str:
|
|
188
|
+
out, blank = [], 0
|
|
189
|
+
for i, line in enumerate(code.split("\n"), 1):
|
|
190
|
+
if i in protected:
|
|
191
|
+
out.append(line)
|
|
192
|
+
blank = 0
|
|
193
|
+
continue
|
|
194
|
+
line = line.rstrip()
|
|
195
|
+
if not line:
|
|
196
|
+
blank += 1
|
|
197
|
+
if blank <= max_blank:
|
|
198
|
+
out.append("")
|
|
199
|
+
continue
|
|
200
|
+
blank = 0
|
|
201
|
+
if flatten:
|
|
202
|
+
line = line.lstrip(" \t")
|
|
203
|
+
elif unit > 1:
|
|
204
|
+
body = line.lstrip(" ")
|
|
205
|
+
line = " " * ((len(line) - len(body)) // unit) + body
|
|
206
|
+
out.append(line)
|
|
207
|
+
return "\n".join(out).strip("\n")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def clean_code(code: str, ext: str, cfg: ModeCfg) -> str:
|
|
211
|
+
ext = ext.lower()
|
|
212
|
+
style = CODE_STYLES.get(ext)
|
|
213
|
+
if style == "py":
|
|
214
|
+
return _clean_python(code, cfg)
|
|
215
|
+
if not style:
|
|
216
|
+
return code
|
|
217
|
+
# Whitespace in these constructs can be data or shell syntax.
|
|
218
|
+
if (ext in {".sh", ".bash", ".zsh", ".rb", ".pl", ".php"} and _HEREDOC.search(code)
|
|
219
|
+
or ext in {".yaml", ".yml"} and _YAML_SCALAR.search(code)):
|
|
220
|
+
return code
|
|
221
|
+
code = code.replace("\r\n", "\n").replace("\r", "\n")
|
|
222
|
+
if style == "bat":
|
|
223
|
+
return _format_lines(_RE_BAT_COMMENT.sub("", code) if cfg.strip_comments else code,
|
|
224
|
+
set(), cfg.blank_code)
|
|
225
|
+
regex = _style_regex(style, ext)
|
|
226
|
+
if cfg.strip_comments:
|
|
227
|
+
def replace(match: re.Match) -> str:
|
|
228
|
+
literal = match["literal"]
|
|
229
|
+
if literal is not None:
|
|
230
|
+
return literal
|
|
231
|
+
comment = match["comment"]
|
|
232
|
+
if match.start() == 0 and comment.startswith("#!"):
|
|
233
|
+
return comment
|
|
234
|
+
if comment.startswith(("/*", "<#", "<!--")):
|
|
235
|
+
return "\n" * comment.count("\n") or " "
|
|
236
|
+
return ""
|
|
237
|
+
|
|
238
|
+
code = regex.sub(replace, code)
|
|
239
|
+
protected = _protected_lines(code, regex)
|
|
240
|
+
reindent = cfg.reindent and style not in {"hash", "html"}
|
|
241
|
+
return _format_lines(code, protected, cfg.blank_code,
|
|
242
|
+
_indent_unit(code, protected) if reindent else 0,
|
|
243
|
+
cfg.flatten and reindent and ext != ".scala")
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from typing import Iterator
|
|
3
|
+
|
|
4
|
+
_ZW_RE = re.compile(r"[\u200b\u200c\u200d\u2060\ufeff]")
|
|
5
|
+
EMOJI_RE = re.compile("[\U0001F000-\U0001FAFF\u2600-\u27BF\u2B00-\u2BFF\uFE0F\u200d]")
|
|
6
|
+
MD_EXTS = {"", ".md", ".markdown", ".txt"}
|
|
7
|
+
_FENCE = re.compile(r"^[ \t]*(?:>[ \t]*)*(" + chr(96) + r"{3,}|~{3,})(.*)$")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _normalize(text: str) -> str:
|
|
11
|
+
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
12
|
+
return _ZW_RE.sub("", text)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def strip_markdown_safe(s: str) -> str:
|
|
16
|
+
"""Убирает **жирный**, *курсив*, _курсив_ и заголовки #, не трогая snake_case, __init__, *.py и т.п."""
|
|
17
|
+
s = re.sub(r"(?<![\w*])\*\*(?=\S)(.+?)(?<=\S)\*\*(?![\w*])", r"\1", s)
|
|
18
|
+
s = re.sub(r"(?<![\w*])\*(?=[^\s*])([^*\n]+?)(?<=[^\s*])\*(?![\w*])", r"\1", s)
|
|
19
|
+
s = re.sub(r"(?<![\w_])_(?=[^\s_])([^_\n]+?)(?<=[^\s_])_(?![\w_])", r"\1", s)
|
|
20
|
+
s = re.sub(r"(?m)^[ \t]{0,3}#{1,6}[ \t]+", "", s)
|
|
21
|
+
return s
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _squeeze_blank(lines: list, max_blank: int) -> list:
|
|
25
|
+
out, run = [], 0
|
|
26
|
+
for ln in lines:
|
|
27
|
+
if ln.strip():
|
|
28
|
+
run = 0
|
|
29
|
+
out.append(ln)
|
|
30
|
+
else:
|
|
31
|
+
run += 1
|
|
32
|
+
if run <= max_blank:
|
|
33
|
+
out.append("")
|
|
34
|
+
return out
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def fenced_lines(text: str) -> Iterator[tuple[str, bool]]:
|
|
38
|
+
"""Yield lines with the opening and closing fences marked as protected."""
|
|
39
|
+
fence = ""
|
|
40
|
+
for line in text.split("\n"):
|
|
41
|
+
match = _FENCE.match(line)
|
|
42
|
+
if fence:
|
|
43
|
+
yield line, True
|
|
44
|
+
if match:
|
|
45
|
+
run, tail = match.groups()
|
|
46
|
+
if run.startswith(fence) and not tail.strip():
|
|
47
|
+
fence = ""
|
|
48
|
+
elif match:
|
|
49
|
+
fence = match[1]
|
|
50
|
+
yield line, True
|
|
51
|
+
else:
|
|
52
|
+
yield line, False
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Remove JSON whitespace while preserving string and number spellings."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
_WHITESPACE_OR_STRING = re.compile(r'"(?:\\[\s\S]|[^"\\])*"|[ \t\r\n]+')
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def clean_json(text: str) -> Optional[str]:
|
|
12
|
+
try:
|
|
13
|
+
# Hooks avoid converting large integers or reformatting numeric lexemes.
|
|
14
|
+
json.loads(text, parse_int=str, parse_float=str)
|
|
15
|
+
except (ValueError, RecursionError):
|
|
16
|
+
return None
|
|
17
|
+
return _WHITESPACE_OR_STRING.sub(lambda match: match[0] if match[0].startswith('"') else "", text)
|
tokzip/cleaners/text.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Plain-text cleanup and Unicode directory trees."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from ..config import TAGS, ModeCfg
|
|
6
|
+
from .common import EMOJI_RE, MD_EXTS, _normalize, fenced_lines, strip_markdown_safe
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
_FLATTEN_EXTS = MD_EXTS | {".log"}
|
|
10
|
+
_HRULE = re.compile(r"[-=_*~]{3,}")
|
|
11
|
+
_TREE_ROW = re.compile(r"((?: {4}|│ {3})*)([├└])── (.+)")
|
|
12
|
+
_TREE_BLOCK = re.compile(r"(?m)(?:^(?: {4}|│ {3})*[├└]── .+(?:\n|$))+")
|
|
13
|
+
_TREE_HINT = {"en": "depth +/- names", "ru": "глубина +/- имена"}
|
|
14
|
+
_PACKED_ROW = re.compile(r"([0-9]+)([+-]) (.+)")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def clean_text(text: str, ext: str, cfg: ModeCfg) -> str:
|
|
18
|
+
lines = []
|
|
19
|
+
blank = 0
|
|
20
|
+
text = text.replace("\r\n", "\n").replace("\r", "\n")
|
|
21
|
+
for raw, fenced in fenced_lines(text):
|
|
22
|
+
if fenced or cfg.compact_tree and _TREE_ROW.fullmatch(raw):
|
|
23
|
+
lines.append((raw, True))
|
|
24
|
+
blank = 0
|
|
25
|
+
continue
|
|
26
|
+
line = _normalize(raw).rstrip()
|
|
27
|
+
if ext in MD_EXTS:
|
|
28
|
+
line = line.replace("\\_", "_")
|
|
29
|
+
if _HRULE.fullmatch(line.strip()):
|
|
30
|
+
line = ""
|
|
31
|
+
elif cfg.strip_markup:
|
|
32
|
+
line = strip_markdown_safe(line)
|
|
33
|
+
if cfg.strip_emoji:
|
|
34
|
+
line = EMOJI_RE.sub("", line)
|
|
35
|
+
body = line.lstrip(" \t")
|
|
36
|
+
if body:
|
|
37
|
+
lead = "" if cfg.flatten and ext in _FLATTEN_EXTS else line[:len(line) - len(body)]
|
|
38
|
+
lines.append((lead.replace("\t", " ") + re.sub(r"[ \t]{2,}", " ", body), False))
|
|
39
|
+
blank = 0
|
|
40
|
+
else:
|
|
41
|
+
blank += 1
|
|
42
|
+
if blank <= cfg.blank_text:
|
|
43
|
+
lines.append(("", False))
|
|
44
|
+
start, end = 0, len(lines)
|
|
45
|
+
while start < end and lines[start] == ("", False):
|
|
46
|
+
start += 1
|
|
47
|
+
while end > start and lines[end - 1] == ("", False):
|
|
48
|
+
end -= 1
|
|
49
|
+
return "\n".join(line for line, _ in lines[start:end])
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def compact_trees(text: str, lang: str) -> str:
|
|
53
|
+
def replace(match: re.Match) -> str:
|
|
54
|
+
block = match[0]
|
|
55
|
+
tag = TAGS[lang]["tree"]
|
|
56
|
+
rows = [f"[{tag}: {_TREE_HINT[lang]}]"]
|
|
57
|
+
guides = [""]
|
|
58
|
+
previous = None
|
|
59
|
+
for line in block.rstrip("\n").split("\n"):
|
|
60
|
+
indent, branch, name = _TREE_ROW.fullmatch(line).groups()
|
|
61
|
+
depth = len(indent) // 4
|
|
62
|
+
if depth >= len(guides) or guides[depth] != indent or "|" in name:
|
|
63
|
+
return block
|
|
64
|
+
guides[depth + 1:] = [indent + ("│ " if branch == "├" else " ")]
|
|
65
|
+
key = (depth, branch)
|
|
66
|
+
if key == previous:
|
|
67
|
+
rows[-1] += "|" + name
|
|
68
|
+
else:
|
|
69
|
+
rows.append(f"{depth}{'+' if branch == '├' else '-'} {name}")
|
|
70
|
+
previous = key
|
|
71
|
+
rows.append(f"[/{tag}]")
|
|
72
|
+
compact = "\n".join(rows) + ("\n" if block.endswith("\n") else "")
|
|
73
|
+
return compact if len(compact.encode("utf-8")) < len(block.encode("utf-8")) else block
|
|
74
|
+
|
|
75
|
+
# Stop tree detection at fences without dropping any separator lines.
|
|
76
|
+
parts, prose = [], []
|
|
77
|
+
for line, protected in fenced_lines(text):
|
|
78
|
+
if protected:
|
|
79
|
+
if prose:
|
|
80
|
+
parts.append(_TREE_BLOCK.sub(replace, "\n".join(prose)))
|
|
81
|
+
prose.clear()
|
|
82
|
+
parts.append(line)
|
|
83
|
+
else:
|
|
84
|
+
prose.append(line)
|
|
85
|
+
if prose:
|
|
86
|
+
parts.append(_TREE_BLOCK.sub(replace, "\n".join(prose)))
|
|
87
|
+
return "\n".join(parts)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def expand_tree(rows: list[str]) -> list[str]:
|
|
91
|
+
guides = [""]
|
|
92
|
+
lines = []
|
|
93
|
+
for row in rows:
|
|
94
|
+
match = _PACKED_ROW.fullmatch(row)
|
|
95
|
+
if match is None:
|
|
96
|
+
raise ValueError(f"Invalid compact tree row: {row}")
|
|
97
|
+
depth = int(match[1])
|
|
98
|
+
if depth >= len(guides):
|
|
99
|
+
raise ValueError(f"Invalid compact tree depth: {depth}")
|
|
100
|
+
indent = guides[depth]
|
|
101
|
+
branch = "├" if match[2] == "+" else "└"
|
|
102
|
+
names = match[3].split("|")
|
|
103
|
+
if not all(names):
|
|
104
|
+
raise ValueError("Missing name in compact tree")
|
|
105
|
+
lines.extend(f"{indent}{branch}── {name}" for name in names)
|
|
106
|
+
guides[depth + 1:] = [indent + ("│ " if branch == "├" else " ")]
|
|
107
|
+
return lines
|