cellsafe 0.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.
- cellsafe/__init__.py +51 -0
- cellsafe/__main__.py +7 -0
- cellsafe/_audit.py +169 -0
- cellsafe/_detect.py +227 -0
- cellsafe/_io.py +160 -0
- cellsafe/_kinds.py +253 -0
- cellsafe/_policy.py +126 -0
- cellsafe/_protect.py +198 -0
- cellsafe/_report.py +161 -0
- cellsafe/_writer.py +397 -0
- cellsafe/cli.py +229 -0
- cellsafe-0.1.2.dist-info/METADATA +609 -0
- cellsafe-0.1.2.dist-info/RECORD +17 -0
- cellsafe-0.1.2.dist-info/WHEEL +5 -0
- cellsafe-0.1.2.dist-info/entry_points.txt +2 -0
- cellsafe-0.1.2.dist-info/licenses/LICENSE +21 -0
- cellsafe-0.1.2.dist-info/top_level.txt +1 -0
cellsafe/__init__.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
"""cellsafe: write and check CSV files that spreadsheet programs open safely.
|
|
2
|
+
|
|
3
|
+
Public API::
|
|
4
|
+
|
|
5
|
+
cellsafe.writer(file, target="excel", policy="default") # like csv.writer
|
|
6
|
+
cellsafe.DictWriter(file, fieldnames, ...) # like csv.DictWriter
|
|
7
|
+
cellsafe.dumps(rows, ...) / cellsafe.dumpb(rows, ...) # str / encoded bytes
|
|
8
|
+
cellsafe.reader(file, policy=...) # reads back, undoes protection
|
|
9
|
+
cellsafe.sanitize(value, policy) / cellsafe.unprotect(text, policy)
|
|
10
|
+
cellsafe.risks(value) # list[Risk]
|
|
11
|
+
cellsafe.audit(path_or_text) # Report
|
|
12
|
+
|
|
13
|
+
The rules encode documented spreadsheet behaviour. They were not verified
|
|
14
|
+
against a running Excel, LibreOffice or Google Sheets; see the README.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.2"
|
|
18
|
+
|
|
19
|
+
from ._audit import audit
|
|
20
|
+
from ._detect import Risk
|
|
21
|
+
from ._io import EncodingError
|
|
22
|
+
from ._kinds import KINDS, Kind
|
|
23
|
+
from ._policy import POLICIES, Policy, resolve_policy
|
|
24
|
+
from ._protect import risks, sanitize, unprotect
|
|
25
|
+
from ._report import Finding, Report
|
|
26
|
+
from ._writer import TARGETS, DictWriter, Target, Writer, dumpb, dumps, reader, writer
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"KINDS",
|
|
30
|
+
"POLICIES",
|
|
31
|
+
"TARGETS",
|
|
32
|
+
"DictWriter",
|
|
33
|
+
"EncodingError",
|
|
34
|
+
"Finding",
|
|
35
|
+
"Kind",
|
|
36
|
+
"Policy",
|
|
37
|
+
"Report",
|
|
38
|
+
"Risk",
|
|
39
|
+
"Target",
|
|
40
|
+
"Writer",
|
|
41
|
+
"__version__",
|
|
42
|
+
"audit",
|
|
43
|
+
"dumpb",
|
|
44
|
+
"dumps",
|
|
45
|
+
"reader",
|
|
46
|
+
"resolve_policy",
|
|
47
|
+
"risks",
|
|
48
|
+
"sanitize",
|
|
49
|
+
"unprotect",
|
|
50
|
+
"writer",
|
|
51
|
+
]
|
cellsafe/__main__.py
ADDED
cellsafe/_audit.py
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"""Audit a CSV file or CSV text."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
from . import _io
|
|
8
|
+
from ._policy import Policy, resolve_policy
|
|
9
|
+
from ._protect import analyse, unprotect
|
|
10
|
+
from ._report import Finding, Report, cell_findings
|
|
11
|
+
from ._writer import Target, resolve_target
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _load(source: object, fallback_encoding: str) -> tuple[_io.Decoded, str]:
|
|
15
|
+
if isinstance(source, (bytes, bytearray)):
|
|
16
|
+
return _io.decode_bytes(bytes(source), fallback_encoding), "<bytes>"
|
|
17
|
+
if isinstance(source, str) and ("\n" in source or "\r" in source):
|
|
18
|
+
return _io.Decoded(source, None, False), "<text>"
|
|
19
|
+
if _io.is_path(source):
|
|
20
|
+
with open(source, "rb") as handle: # type: ignore[arg-type]
|
|
21
|
+
return _io.decode_bytes(handle.read(), fallback_encoding), os.fspath(source) # type: ignore[arg-type]
|
|
22
|
+
read = getattr(source, "read", None)
|
|
23
|
+
if read is None:
|
|
24
|
+
raise TypeError("audit() needs a path, CSV text, bytes or a readable stream")
|
|
25
|
+
data = read()
|
|
26
|
+
name = str(getattr(source, "name", "<stream>"))
|
|
27
|
+
if isinstance(data, (bytes, bytearray)):
|
|
28
|
+
return _io.decode_bytes(bytes(data), fallback_encoding), name
|
|
29
|
+
return _io.Decoded(data, None, False), name
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def audit(
|
|
33
|
+
source: object,
|
|
34
|
+
*,
|
|
35
|
+
target: "str | Target" = "excel",
|
|
36
|
+
policy: "str | Policy | None" = None,
|
|
37
|
+
delimiter: str | None = None,
|
|
38
|
+
fallback_encoding: str = _io.DEFAULT_FALLBACK,
|
|
39
|
+
header: bool = True,
|
|
40
|
+
protected: bool = False,
|
|
41
|
+
) -> Report:
|
|
42
|
+
"""Check a CSV file and report what a spreadsheet would damage or misuse.
|
|
43
|
+
|
|
44
|
+
*source* is a path (``os.PathLike``, or a ``str`` without line breaks),
|
|
45
|
+
CSV text (a ``str`` containing at least one line break), ``bytes``, or a
|
|
46
|
+
readable stream. Nothing is modified.
|
|
47
|
+
|
|
48
|
+
Each finding carries the row and column, the kind, the value, and the
|
|
49
|
+
cell text *policy* would write instead (``fix``), if any.
|
|
50
|
+
|
|
51
|
+
delimiter
|
|
52
|
+
Taken from a ``sep=`` first line if present, else from this
|
|
53
|
+
argument, else chosen among ``, ; tab |`` by counting them in the
|
|
54
|
+
first record.
|
|
55
|
+
fallback_encoding
|
|
56
|
+
Used only when the input has no byte order mark and is not valid
|
|
57
|
+
UTF-8. cellsafe does not guess encodings.
|
|
58
|
+
header
|
|
59
|
+
Treat the first row as column names and check them.
|
|
60
|
+
protected
|
|
61
|
+
The file was written by cellsafe with *policy*: cells that already
|
|
62
|
+
are in protected form are not reported again.
|
|
63
|
+
"""
|
|
64
|
+
pol = resolve_policy(policy)
|
|
65
|
+
tgt = resolve_target(target)
|
|
66
|
+
decoded, name = _load(source, fallback_encoding)
|
|
67
|
+
hinted, text = _io.split_sep_hint(decoded.text)
|
|
68
|
+
if hinted is not None:
|
|
69
|
+
delimiter = hinted
|
|
70
|
+
elif delimiter is None:
|
|
71
|
+
delimiter = _io.sniff_delimiter(text)
|
|
72
|
+
rows = _io.parse_rows(text, delimiter)
|
|
73
|
+
terminators = _io.record_terminators(text)
|
|
74
|
+
|
|
75
|
+
report = Report(
|
|
76
|
+
source=name,
|
|
77
|
+
rows=len(rows),
|
|
78
|
+
columns=len(rows[0]) if rows else 0,
|
|
79
|
+
encoding=decoded.encoding,
|
|
80
|
+
bom=decoded.bom,
|
|
81
|
+
delimiter=delimiter,
|
|
82
|
+
sep_hint=hinted is not None,
|
|
83
|
+
line_endings=tuple(sorted(terminators)),
|
|
84
|
+
target=tgt.name,
|
|
85
|
+
policy=pol.name,
|
|
86
|
+
)
|
|
87
|
+
out = report.findings
|
|
88
|
+
|
|
89
|
+
# -- file level ----------------------------------------------------------
|
|
90
|
+
if decoded.fallback_used:
|
|
91
|
+
out.append(
|
|
92
|
+
Finding(
|
|
93
|
+
"encoding-fallback",
|
|
94
|
+
f"not valid UTF-8 and no byte order mark; decoded as {decoded.encoding}",
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
if (
|
|
98
|
+
tgt.name == "excel"
|
|
99
|
+
and decoded.encoding == "utf-8"
|
|
100
|
+
and not decoded.bom
|
|
101
|
+
and not text.isascii()
|
|
102
|
+
):
|
|
103
|
+
out.append(
|
|
104
|
+
Finding(
|
|
105
|
+
"missing-bom",
|
|
106
|
+
"non-ASCII text in UTF-8 without a byte order mark; Excel on "
|
|
107
|
+
"Windows reads it in the ANSI code page",
|
|
108
|
+
)
|
|
109
|
+
)
|
|
110
|
+
if len(terminators) > 1:
|
|
111
|
+
detail = ", ".join(f"{n} {kind}" for kind, n in sorted(terminators.items()))
|
|
112
|
+
out.append(Finding("mixed-line-endings", f"records end in different ways: {detail}"))
|
|
113
|
+
if (
|
|
114
|
+
hinted is None
|
|
115
|
+
and "sep-directive" not in pol.ignore
|
|
116
|
+
and _io.looks_like_sep_directive(text)
|
|
117
|
+
):
|
|
118
|
+
out.append(
|
|
119
|
+
Finding(
|
|
120
|
+
"sep-directive",
|
|
121
|
+
"the first line starts with 'sep=' but is read here as data; a "
|
|
122
|
+
"spreadsheet may take it for a separator line and drop it",
|
|
123
|
+
1,
|
|
124
|
+
1,
|
|
125
|
+
rows[0][0] if rows and rows[0] else None,
|
|
126
|
+
)
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
# -- header --------------------------------------------------------------
|
|
130
|
+
if header and rows:
|
|
131
|
+
seen: dict[str, int] = {}
|
|
132
|
+
for index, cell in enumerate(rows[0], start=1):
|
|
133
|
+
label = cell.strip(" ")
|
|
134
|
+
if not label:
|
|
135
|
+
out.append(Finding("empty-header", "header cell is empty", 1, index, cell))
|
|
136
|
+
elif label in seen:
|
|
137
|
+
out.append(
|
|
138
|
+
Finding(
|
|
139
|
+
"duplicate-header",
|
|
140
|
+
f"header {label!r} is also used in column {seen[label]}",
|
|
141
|
+
1,
|
|
142
|
+
index,
|
|
143
|
+
cell,
|
|
144
|
+
)
|
|
145
|
+
)
|
|
146
|
+
else:
|
|
147
|
+
seen[label] = index
|
|
148
|
+
|
|
149
|
+
# -- rows and cells ------------------------------------------------------
|
|
150
|
+
width = len(rows[0]) if rows else 0
|
|
151
|
+
for row_number, row in enumerate(rows, start=1):
|
|
152
|
+
if row and len(row) != width:
|
|
153
|
+
out.append(
|
|
154
|
+
Finding(
|
|
155
|
+
"ragged-row",
|
|
156
|
+
f"row has {len(row)} cells, the first row has {width}",
|
|
157
|
+
row_number,
|
|
158
|
+
)
|
|
159
|
+
)
|
|
160
|
+
for column, cell in enumerate(row, start=1):
|
|
161
|
+
if protected:
|
|
162
|
+
outcome = analyse(unprotect(cell, pol), pol)
|
|
163
|
+
if outcome.output == cell:
|
|
164
|
+
out.extend(cell_findings(outcome, row_number, column, handled=False))
|
|
165
|
+
continue
|
|
166
|
+
outcome = analyse(cell, pol)
|
|
167
|
+
if outcome.risks:
|
|
168
|
+
out.extend(cell_findings(outcome, row_number, column))
|
|
169
|
+
return report
|
cellsafe/_detect.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
"""Detection of risky cell values. Pure functions, no policy decisions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass(frozen=True)
|
|
11
|
+
class Risk:
|
|
12
|
+
"""One reason a cell may be damaged or misused by a spreadsheet."""
|
|
13
|
+
|
|
14
|
+
kind: str
|
|
15
|
+
message: str
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# --------------------------------------------------------------------------
|
|
19
|
+
# Formula triggers
|
|
20
|
+
# --------------------------------------------------------------------------
|
|
21
|
+
|
|
22
|
+
_TRIGGERS = "=+-@"
|
|
23
|
+
_FULLWIDTH_TRIGGERS = {
|
|
24
|
+
"=": "=", # FULLWIDTH EQUALS SIGN
|
|
25
|
+
"+": "+", # FULLWIDTH PLUS SIGN
|
|
26
|
+
"-": "-", # FULLWIDTH HYPHEN-MINUS
|
|
27
|
+
"@": "@", # FULLWIDTH COMMERCIAL AT
|
|
28
|
+
}
|
|
29
|
+
_LEADING_QUOTES = "'\""
|
|
30
|
+
|
|
31
|
+
_PLAIN_NUMBER = re.compile(
|
|
32
|
+
r"[+-]?(?:[0-9]+(?:[.,][0-9]+)*|[.,][0-9]+)(?:[eE][+-]?[0-9]+)?%?"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def formula_reason(text: str) -> str | None:
|
|
37
|
+
"""Return why *text* would be treated as a formula, or ``None``.
|
|
38
|
+
|
|
39
|
+
The leading run of whitespace and quote characters is skipped. A tab or
|
|
40
|
+
carriage return anywhere in that run is itself a trigger (OWASP lists
|
|
41
|
+
both), otherwise the first other character decides.
|
|
42
|
+
"""
|
|
43
|
+
skipped = False
|
|
44
|
+
for ch in text:
|
|
45
|
+
if ch == "\t":
|
|
46
|
+
return "starts with a tab character"
|
|
47
|
+
if ch == "\r":
|
|
48
|
+
return "starts with a carriage return"
|
|
49
|
+
if ch.isspace() or ch in _LEADING_QUOTES:
|
|
50
|
+
skipped = True
|
|
51
|
+
continue
|
|
52
|
+
if ch in _TRIGGERS:
|
|
53
|
+
if skipped:
|
|
54
|
+
return f"starts with {ch!r} after leading whitespace or quote characters"
|
|
55
|
+
return f"starts with {ch!r}"
|
|
56
|
+
if ch in _FULLWIDTH_TRIGGERS:
|
|
57
|
+
return (
|
|
58
|
+
f"starts with full-width {_FULLWIDTH_TRIGGERS[ch]!r} "
|
|
59
|
+
f"(U+{ord(ch):04X})"
|
|
60
|
+
)
|
|
61
|
+
return None
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def is_plain_number(text: str) -> bool:
|
|
66
|
+
"""True for an optionally signed number and nothing else.
|
|
67
|
+
|
|
68
|
+
Accepted: ASCII digits with '.' or ',' as decimal or grouping separators,
|
|
69
|
+
an optional exponent and an optional trailing percent sign. No spaces,
|
|
70
|
+
letters (other than the exponent's e), references or operators.
|
|
71
|
+
"""
|
|
72
|
+
return _PLAIN_NUMBER.fullmatch(text) is not None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# --------------------------------------------------------------------------
|
|
76
|
+
# Data-damage patterns
|
|
77
|
+
# --------------------------------------------------------------------------
|
|
78
|
+
|
|
79
|
+
_DECIMAL = re.compile(r"([+-]?)([0-9]*)(?:\.([0-9]*))?")
|
|
80
|
+
_EXPONENT_ID = re.compile(r"[0-9]+[eE][0-9]+")
|
|
81
|
+
_NUMERIC_DATE = re.compile(r"([0-9]{1,4})([-/])([0-9]{1,4})(?:\2([0-9]{1,4}))?")
|
|
82
|
+
_MONTH = (
|
|
83
|
+
"jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|"
|
|
84
|
+
"aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?"
|
|
85
|
+
)
|
|
86
|
+
_MONTH_THEN_NUMBER = re.compile(
|
|
87
|
+
rf"(?:{_MONTH})[-/ .]?[0-9]{{1,4}}(?:(?:, ?| )[0-9]{{2,4}})?", re.IGNORECASE
|
|
88
|
+
)
|
|
89
|
+
_NUMBER_THEN_MONTH = re.compile(
|
|
90
|
+
rf"[0-9]{{1,4}}[-/ .]?(?:{_MONTH})(?:[-/ .,]{{1,2}}[0-9]{{1,4}})?", re.IGNORECASE
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _is_month(n: int) -> bool:
|
|
95
|
+
return 1 <= n <= 12
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _valid_date(year: int, month: int, day: int) -> bool:
|
|
99
|
+
try:
|
|
100
|
+
datetime.date(year, month, day)
|
|
101
|
+
except ValueError:
|
|
102
|
+
return False
|
|
103
|
+
return True
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _numeric_date_risk(core: str) -> Risk | None:
|
|
107
|
+
m = _NUMERIC_DATE.fullmatch(core)
|
|
108
|
+
if m is None:
|
|
109
|
+
return None
|
|
110
|
+
a, b, c = m.group(1), m.group(3), m.group(4)
|
|
111
|
+
ia, ib = int(a), int(b)
|
|
112
|
+
if c is None:
|
|
113
|
+
if (_is_month(ia) and ib >= 1) or (_is_month(ib) and ia >= 1):
|
|
114
|
+
return Risk("date-like", f"{core!r} is read as a date, not kept as text")
|
|
115
|
+
return None
|
|
116
|
+
ic = int(c)
|
|
117
|
+
if len(a) == 4 and _valid_date(ia, ib, ic):
|
|
118
|
+
return None # complete year-first date; conversion is normally wanted
|
|
119
|
+
if len(c) == 4 and 1 <= ia <= 31 and 1 <= ib <= 31 and (_is_month(ia) or _is_month(ib)):
|
|
120
|
+
if _is_month(ia) and _is_month(ib) and ia != ib:
|
|
121
|
+
return Risk(
|
|
122
|
+
"locale-date",
|
|
123
|
+
f"{core!r} is day/month or month/day depending on the reader's locale",
|
|
124
|
+
)
|
|
125
|
+
if _is_month(ia) and _is_month(ib):
|
|
126
|
+
return None # e.g. 05/05/2024: same date either way
|
|
127
|
+
return Risk(
|
|
128
|
+
"locale-date",
|
|
129
|
+
f"{core!r} becomes a date in some locales and stays text in others",
|
|
130
|
+
)
|
|
131
|
+
if _is_month(ia) or _is_month(ib) or _is_month(ic):
|
|
132
|
+
return Risk("date-like", f"{core!r} is read as a date, not kept as text")
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def data_risks(text: str) -> list[Risk]:
|
|
137
|
+
"""Risks of silent data damage for a text cell (formula risk excluded)."""
|
|
138
|
+
found: list[Risk] = []
|
|
139
|
+
core = text.strip(" ")
|
|
140
|
+
|
|
141
|
+
m = _DECIMAL.fullmatch(core)
|
|
142
|
+
if m and (m.group(2) or m.group(3)):
|
|
143
|
+
sign, int_part, frac_part = m.group(1), m.group(2) or "", m.group(3) or ""
|
|
144
|
+
significant = (int_part + frac_part).strip("0")
|
|
145
|
+
if len(significant) > 15:
|
|
146
|
+
found.append(
|
|
147
|
+
Risk(
|
|
148
|
+
"precision-loss",
|
|
149
|
+
f"{len(significant)} significant digits; only 15 survive as a number",
|
|
150
|
+
)
|
|
151
|
+
)
|
|
152
|
+
elif len(int_part.lstrip("0")) >= 12:
|
|
153
|
+
found.append(
|
|
154
|
+
Risk(
|
|
155
|
+
"scientific-display",
|
|
156
|
+
f"{len(int_part.lstrip('0'))}-digit integer is shown in scientific notation",
|
|
157
|
+
)
|
|
158
|
+
)
|
|
159
|
+
if len(int_part) > 1 and int_part[0] == "0":
|
|
160
|
+
found.append(Risk("leading-zero", "leading zeros are dropped"))
|
|
161
|
+
if sign == "+":
|
|
162
|
+
found.append(Risk("plus-sign", "the leading '+' is dropped"))
|
|
163
|
+
elif _EXPONENT_ID.fullmatch(core):
|
|
164
|
+
found.append(Risk("exponent", f"{core!r} is read as a number in E notation"))
|
|
165
|
+
elif core.upper() in ("TRUE", "FALSE"):
|
|
166
|
+
found.append(Risk("boolean", f"{core!r} becomes a boolean value"))
|
|
167
|
+
else:
|
|
168
|
+
date = _numeric_date_risk(core)
|
|
169
|
+
if date is not None:
|
|
170
|
+
found.append(date)
|
|
171
|
+
elif _MONTH_THEN_NUMBER.fullmatch(core) or _NUMBER_THEN_MONTH.fullmatch(core):
|
|
172
|
+
found.append(Risk("date-like", f"{core!r} is read as a date, not kept as text"))
|
|
173
|
+
|
|
174
|
+
if text.startswith("'"):
|
|
175
|
+
found.append(
|
|
176
|
+
Risk("leading-apostrophe", "a leading apostrophe is a text marker in spreadsheets")
|
|
177
|
+
)
|
|
178
|
+
return found
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# --------------------------------------------------------------------------
|
|
182
|
+
# Right-to-left helpers
|
|
183
|
+
# --------------------------------------------------------------------------
|
|
184
|
+
|
|
185
|
+
BIDI_CONTROLS = frozenset(
|
|
186
|
+
"" # ARABIC LETTER MARK
|
|
187
|
+
"" # LRM, RLM
|
|
188
|
+
"" # LRE, RLE, PDF, LRO, RLO
|
|
189
|
+
"" # LRI, RLI, FSI, PDI
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
_DIGIT_MAP: dict[int, str] = {}
|
|
193
|
+
for _i in range(10):
|
|
194
|
+
_DIGIT_MAP[0x0660 + _i] = str(_i) # Arabic-Indic
|
|
195
|
+
_DIGIT_MAP[0x06F0 + _i] = str(_i) # Extended Arabic-Indic (Persian, Urdu)
|
|
196
|
+
_FOREIGN_DIGITS = frozenset(chr(cp) for cp in _DIGIT_MAP)
|
|
197
|
+
_DIGIT_MAP[0x066B] = "." # ARABIC DECIMAL SEPARATOR
|
|
198
|
+
_DIGIT_MAP[0x066C] = "," # ARABIC THOUSANDS SEPARATOR
|
|
199
|
+
_DIGIT_MAP[0x066A] = "%" # ARABIC PERCENT SIGN
|
|
200
|
+
|
|
201
|
+
_D = "0-9٠-٩۰-۹"
|
|
202
|
+
_FOREIGN_NUMBER = re.compile(
|
|
203
|
+
rf"[+-]?[{_D}]+(?:[.,٫٬][{_D}]+)*[%٪]?"
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def bidi_controls_in(text: str) -> list[str]:
|
|
208
|
+
"""The bidi control characters present in *text*, in order of appearance."""
|
|
209
|
+
return [ch for ch in text if ch in BIDI_CONTROLS]
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def strip_bidi_controls(text: str) -> str:
|
|
213
|
+
return "".join(ch for ch in text if ch not in BIDI_CONTROLS)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def is_non_ascii_number(text: str) -> bool:
|
|
217
|
+
"""True when the whole cell is a number using Arabic-Indic/Persian digits."""
|
|
218
|
+
core = text.strip(" ")
|
|
219
|
+
return (
|
|
220
|
+
any(ch in _FOREIGN_DIGITS for ch in core)
|
|
221
|
+
and _FOREIGN_NUMBER.fullmatch(core) is not None
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def normalise_digits(text: str) -> str:
|
|
226
|
+
"""Rewrite a non-ASCII-digit number with ASCII digits and separators."""
|
|
227
|
+
return text.translate(_DIGIT_MAP)
|
cellsafe/_io.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
"""Decoding input and small CSV text helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import codecs
|
|
6
|
+
import csv
|
|
7
|
+
import io
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
DEFAULT_FALLBACK = "cp1252"
|
|
13
|
+
|
|
14
|
+
# Longest first: the UTF-32 LE mark starts with the UTF-16 LE mark.
|
|
15
|
+
_BOMS = (
|
|
16
|
+
(codecs.BOM_UTF32_LE, "utf-32-le"),
|
|
17
|
+
(codecs.BOM_UTF32_BE, "utf-32-be"),
|
|
18
|
+
(codecs.BOM_UTF8, "utf-8"),
|
|
19
|
+
(codecs.BOM_UTF16_LE, "utf-16-le"),
|
|
20
|
+
(codecs.BOM_UTF16_BE, "utf-16-be"),
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class EncodingError(ValueError):
|
|
25
|
+
"""The input could not be decoded with the detected or fallback encoding."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Decoded:
|
|
30
|
+
text: str
|
|
31
|
+
encoding: str | None # None when the input was already text
|
|
32
|
+
bom: bool
|
|
33
|
+
fallback_used: bool = False
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def decode_bytes(data: bytes, fallback: str = DEFAULT_FALLBACK, encoding: str | None = None) -> Decoded:
|
|
37
|
+
"""Decode *data* without guessing.
|
|
38
|
+
|
|
39
|
+
Order: an explicit *encoding* if given; otherwise a byte order mark
|
|
40
|
+
(UTF-8, UTF-16, UTF-32); otherwise strict UTF-8; otherwise *fallback*.
|
|
41
|
+
"""
|
|
42
|
+
if encoding is not None:
|
|
43
|
+
try:
|
|
44
|
+
text = data.decode(encoding)
|
|
45
|
+
except (UnicodeDecodeError, LookupError) as exc:
|
|
46
|
+
raise EncodingError(f"cannot decode input as {encoding}: {exc}") from None
|
|
47
|
+
bom = text.startswith("")
|
|
48
|
+
return Decoded(text[1:] if bom else text, encoding, bom)
|
|
49
|
+
for mark, name in _BOMS:
|
|
50
|
+
if data.startswith(mark):
|
|
51
|
+
try:
|
|
52
|
+
return Decoded(data[len(mark):].decode(name), name, True)
|
|
53
|
+
except UnicodeDecodeError as exc:
|
|
54
|
+
raise EncodingError(f"file has a {name} byte order mark but is not valid {name}: {exc}") from None
|
|
55
|
+
try:
|
|
56
|
+
return Decoded(data.decode("utf-8"), "utf-8", False)
|
|
57
|
+
except UnicodeDecodeError:
|
|
58
|
+
pass
|
|
59
|
+
try:
|
|
60
|
+
return Decoded(data.decode(fallback), fallback, False, fallback_used=True)
|
|
61
|
+
except (UnicodeDecodeError, LookupError) as exc:
|
|
62
|
+
raise EncodingError(
|
|
63
|
+
f"input has no byte order mark, is not valid UTF-8 and cannot be "
|
|
64
|
+
f"decoded with the fallback encoding {fallback!r}: {exc}"
|
|
65
|
+
) from None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def is_binary_stream(obj: object) -> bool:
|
|
69
|
+
if isinstance(obj, (io.RawIOBase, io.BufferedIOBase)):
|
|
70
|
+
return True
|
|
71
|
+
if isinstance(obj, io.TextIOBase):
|
|
72
|
+
return False
|
|
73
|
+
return "b" in str(getattr(obj, "mode", ""))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def is_path(obj: object) -> bool:
|
|
77
|
+
return isinstance(obj, (str, os.PathLike))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_SEP_HINT = re.compile(r"sep=([^\r\n])(\r\n|\r|\n|$)")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def split_sep_hint(text: str) -> tuple[str | None, str]:
|
|
84
|
+
"""Split off a leading ``sep=X`` line. Returns ``(delimiter, rest)``."""
|
|
85
|
+
m = _SEP_HINT.match(text)
|
|
86
|
+
if m is None:
|
|
87
|
+
return None, text
|
|
88
|
+
return m.group(1), text[m.end():]
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
# Broader than _SEP_HINT on purpose: any first line that begins with "sep="
|
|
92
|
+
# in any letter case, after spaces or tabs, may be taken for a separator
|
|
93
|
+
# directive by a spreadsheet, so the writer quotes such a first cell.
|
|
94
|
+
_SEP_DIRECTIVE = re.compile(r"[ \t]*sep=", re.IGNORECASE)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def looks_like_sep_directive(text: str) -> bool:
|
|
98
|
+
"""True if *text*, at the start of a file, could be read as a ``sep=`` line."""
|
|
99
|
+
return _SEP_DIRECTIVE.match(text) is not None
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
_CANDIDATES = (",", ";", "\t", "|")
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def sniff_delimiter(text: str, quotechar: str = '"') -> str:
|
|
106
|
+
"""Pick the separator among ``, ; tab |`` from the first record.
|
|
107
|
+
|
|
108
|
+
Deliberately simple: the candidate that occurs most often outside quotes
|
|
109
|
+
in the first non-empty record wins; ties and zero counts fall back to the
|
|
110
|
+
comma. Pass the delimiter explicitly when this is not good enough.
|
|
111
|
+
"""
|
|
112
|
+
counts = dict.fromkeys(_CANDIDATES, 0)
|
|
113
|
+
in_quotes = False
|
|
114
|
+
seen_content = False
|
|
115
|
+
for ch in text:
|
|
116
|
+
if ch == quotechar:
|
|
117
|
+
in_quotes = not in_quotes
|
|
118
|
+
seen_content = True
|
|
119
|
+
elif not in_quotes and ch in "\r\n":
|
|
120
|
+
if seen_content:
|
|
121
|
+
break
|
|
122
|
+
else:
|
|
123
|
+
seen_content = True
|
|
124
|
+
if not in_quotes and ch in counts:
|
|
125
|
+
counts[ch] += 1
|
|
126
|
+
best = max(_CANDIDATES, key=lambda c: counts[c]) # first wins on ties
|
|
127
|
+
return best if counts[best] else ","
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
_TERMINATOR = re.compile(r'"|\r\n|\r|\n')
|
|
131
|
+
_TERMINATOR_NAMES = {"\r\n": "CRLF", "\n": "LF", "\r": "CR"}
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def record_terminators(text: str) -> dict[str, int]:
|
|
135
|
+
"""Count record terminators, ignoring line breaks inside quoted cells."""
|
|
136
|
+
counts: dict[str, int] = {}
|
|
137
|
+
in_quotes = False
|
|
138
|
+
for m in _TERMINATOR.finditer(text):
|
|
139
|
+
token = m.group()
|
|
140
|
+
if token == '"':
|
|
141
|
+
in_quotes = not in_quotes
|
|
142
|
+
elif not in_quotes:
|
|
143
|
+
name = _TERMINATOR_NAMES[token]
|
|
144
|
+
counts[name] = counts.get(name, 0) + 1
|
|
145
|
+
return counts
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def parse_rows(text: str, delimiter: str, **fmtparams: object) -> list[list[str]]:
|
|
149
|
+
return list(csv.reader(io.StringIO(text, newline=""), delimiter=delimiter, **fmtparams))
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def parse_delimiter(spec: str) -> str:
|
|
153
|
+
"""Accept a single character or one of the names tab, comma, semicolon, pipe."""
|
|
154
|
+
names = {"tab": "\t", "\\t": "\t", "comma": ",", "semicolon": ";", "pipe": "|", "space": " "}
|
|
155
|
+
value = names.get(spec.lower(), spec)
|
|
156
|
+
if len(value) != 1:
|
|
157
|
+
raise ValueError(
|
|
158
|
+
f"delimiter must be one character or one of {', '.join(n for n in names if n != chr(92) + 't')}; got {spec!r}"
|
|
159
|
+
)
|
|
160
|
+
return value
|