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/_report.py ADDED
@@ -0,0 +1,161 @@
1
+ """Findings and reports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from ._protect import REPORTED_ONLY, Outcome
8
+
9
+
10
+ def column_letters(column: int) -> str:
11
+ """1 -> A, 26 -> Z, 27 -> AA, as spreadsheets label columns."""
12
+ letters = ""
13
+ while column > 0:
14
+ column, rem = divmod(column - 1, 26)
15
+ letters = chr(ord("A") + rem) + letters
16
+ return letters
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class Finding:
21
+ """One finding.
22
+
23
+ ``row`` and ``column`` are 1-based and count the way the opened sheet
24
+ does (a ``sep=`` line is not a row). File-level findings have
25
+ ``column=None`` and, when they do not belong to a row, ``row=None``.
26
+ ``fix`` is the cell text the policy writes instead, or ``None`` when the
27
+ policy leaves the cell as it is.
28
+ """
29
+
30
+ kind: str
31
+ message: str
32
+ row: int | None = None
33
+ column: int | None = None
34
+ value: str | None = None
35
+ action: str = REPORTED_ONLY
36
+ fix: str | None = None
37
+
38
+ @property
39
+ def cell(self) -> str | None:
40
+ """Spreadsheet-style reference such as ``B3``; ``None`` for file-level findings."""
41
+ if self.row is None or self.column is None:
42
+ return None
43
+ return f"{column_letters(self.column)}{self.row}"
44
+
45
+ def to_dict(self) -> dict[str, object]:
46
+ return {
47
+ "kind": self.kind,
48
+ "row": self.row,
49
+ "column": self.column,
50
+ "cell": self.cell,
51
+ "value": self.value,
52
+ "message": self.message,
53
+ "action": self.action,
54
+ "fix": self.fix,
55
+ }
56
+
57
+
58
+ def cell_findings(outcome: Outcome, row: int, column: int, *, handled: bool = True) -> list[Finding]:
59
+ """Findings for one analysed cell.
60
+
61
+ With ``handled=False`` risks the policy already took care of are left out
62
+ (used when auditing a file known to be cellsafe output).
63
+ """
64
+ out = []
65
+ for risk in outcome.risks:
66
+ action = outcome.action_for(risk.kind)
67
+ if not handled and action != REPORTED_ONLY:
68
+ continue
69
+ out.append(
70
+ Finding(
71
+ kind=risk.kind,
72
+ message=risk.message,
73
+ row=row,
74
+ column=column,
75
+ value=outcome.original,
76
+ action=action,
77
+ fix=outcome.output if outcome.changed else None,
78
+ )
79
+ )
80
+ return out
81
+
82
+
83
+ def _show(value: str | None, limit: int = 40) -> str:
84
+ if value is None:
85
+ return ""
86
+ text = repr(value)
87
+ if len(text) > limit:
88
+ text = text[: limit - 3] + "..."
89
+ return text
90
+
91
+
92
+ @dataclass
93
+ class Report:
94
+ """Result of :func:`cellsafe.audit`."""
95
+
96
+ findings: list[Finding] = field(default_factory=list)
97
+ source: str = "<text>"
98
+ rows: int = 0
99
+ columns: int = 0
100
+ encoding: str | None = None
101
+ bom: bool = False
102
+ delimiter: str = ","
103
+ sep_hint: bool = False
104
+ line_endings: tuple[str, ...] = ()
105
+ target: str = "excel"
106
+ policy: str = "default"
107
+
108
+ @property
109
+ def ok(self) -> bool:
110
+ """True when nothing was found."""
111
+ return not self.findings
112
+
113
+ def counts(self) -> dict[str, int]:
114
+ """Number of findings per kind, in order of first appearance."""
115
+ result: dict[str, int] = {}
116
+ for finding in self.findings:
117
+ result[finding.kind] = result.get(finding.kind, 0) + 1
118
+ return result
119
+
120
+ def to_dict(self) -> dict[str, object]:
121
+ return {
122
+ "source": self.source,
123
+ "ok": self.ok,
124
+ "rows": self.rows,
125
+ "columns": self.columns,
126
+ "encoding": self.encoding,
127
+ "bom": self.bom,
128
+ "delimiter": self.delimiter,
129
+ "sep_hint": self.sep_hint,
130
+ "line_endings": list(self.line_endings),
131
+ "target": self.target,
132
+ "policy": self.policy,
133
+ "counts": self.counts(),
134
+ "findings": [f.to_dict() for f in self.findings],
135
+ }
136
+
137
+ def format_text(self) -> str:
138
+ """Human-readable report, one line per finding."""
139
+ encoding = self.encoding or "text input"
140
+ if self.encoding:
141
+ encoding += " with BOM" if self.bom else ", no BOM"
142
+ lines = [
143
+ f"{self.source}: {self.rows} rows, {self.columns} columns, {encoding}, "
144
+ f"delimiter {self.delimiter!r}, line endings {'/'.join(self.line_endings) or 'none'}"
145
+ ]
146
+ for f in self.findings:
147
+ where = f.cell or (f"row {f.row}" if f.row is not None else "file")
148
+ line = f" {where:<8} {f.kind:<19} {f.message}"
149
+ if f.value is not None:
150
+ line += f"; value {_show(f.value)}"
151
+ if f.fix is not None:
152
+ line += f" -> {_show(f.fix)} ({f.action})"
153
+ elif f.column is not None:
154
+ line += f" ({f.action})"
155
+ lines.append(line)
156
+ if self.findings:
157
+ summary = ", ".join(f"{kind}: {n}" for kind, n in self.counts().items())
158
+ lines.append(f"{len(self.findings)} finding(s) under policy {self.policy!r}: {summary}")
159
+ else:
160
+ lines.append(f"no findings under policy {self.policy!r}")
161
+ return "\n".join(lines)
cellsafe/_writer.py ADDED
@@ -0,0 +1,397 @@
1
+ """Writer, DictWriter, dumps and the matching reader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import codecs
6
+ import csv
7
+ import io
8
+ from collections.abc import Iterable, Iterator, Mapping, Sequence
9
+ from dataclasses import dataclass
10
+
11
+ from . import _io
12
+ from ._policy import Policy, resolve_policy
13
+ from ._protect import analyse, unprotect
14
+ from ._report import Finding, cell_findings
15
+
16
+
17
+ @dataclass(frozen=True)
18
+ class Target:
19
+ """File conventions for one kind of consumer."""
20
+
21
+ name: str
22
+ encoding: str
23
+ delimiter: str
24
+ lineterminator: str
25
+ note: str
26
+
27
+
28
+ TARGETS: dict[str, Target] = {
29
+ "excel": Target(
30
+ "excel", "utf-8-sig", ",", "\r\n",
31
+ "UTF-8 with BOM so Excel on Windows does not fall back to the ANSI code page",
32
+ ),
33
+ "sheets": Target(
34
+ "sheets", "utf-8", ",", "\r\n",
35
+ "plain UTF-8; Google Sheets import reads UTF-8",
36
+ ),
37
+ "libreoffice": Target(
38
+ "libreoffice", "utf-8", ",", "\r\n",
39
+ "plain UTF-8; LibreOffice shows an import dialog where the encoding is chosen",
40
+ ),
41
+ "plain": Target(
42
+ "plain", "utf-8", ",", "\n",
43
+ "UTF-8 without BOM and LF line endings for programs rather than spreadsheets",
44
+ ),
45
+ }
46
+
47
+
48
+ def resolve_target(target: "str | Target") -> Target:
49
+ if isinstance(target, Target):
50
+ return target
51
+ try:
52
+ return TARGETS[target]
53
+ except KeyError:
54
+ raise ValueError(
55
+ f"unknown target {target!r}; choose one of {', '.join(TARGETS)}"
56
+ ) from None
57
+
58
+
59
+ def _codec(encoding: str) -> tuple[str, str, str]:
60
+ """Return ``(canonical name, Python codec, BOM text)`` for an output encoding."""
61
+ key = encoding.lower().replace("_", "-")
62
+ if key in ("utf-16", "utf16", "utf-16-le", "utf-16le"):
63
+ # Explicit little endian plus a hand-written mark: Python's "utf-16"
64
+ # codec uses the byte order of the machine it runs on.
65
+ return "utf-16", "utf-16-le", ""
66
+ if key in ("utf-8-sig", "utf8-sig"):
67
+ return "utf-8-sig", "utf-8", ""
68
+ if key in ("utf-8", "utf8"):
69
+ return "utf-8", "utf-8", ""
70
+ return encoding, encoding, ""
71
+
72
+
73
+ class _EncodingStream:
74
+ """Minimal text-to-bytes adapter.
75
+
76
+ Unlike ``io.TextIOWrapper`` it never closes the caller's binary stream,
77
+ not even when it is garbage collected.
78
+ """
79
+
80
+ def __init__(self, raw: object, codec: str) -> None:
81
+ self._raw = raw
82
+ self._encoder = codecs.getincrementalencoder(codec)("strict")
83
+
84
+ def write(self, text: str) -> int:
85
+ self._raw.write(self._encoder.encode(text)) # type: ignore[attr-defined]
86
+ return len(text)
87
+
88
+ def flush(self) -> None:
89
+ flush = getattr(self._raw, "flush", None)
90
+ if flush is not None:
91
+ flush()
92
+
93
+
94
+ class Writer:
95
+ """A ``csv.writer`` that neutralises formulas and applies a policy.
96
+
97
+ *file* is a path, a binary stream or a text stream. For a path or a
98
+ binary stream cellsafe encodes the output itself (and writes the byte
99
+ order mark the target calls for). A text stream is used as it is: its
100
+ encoding belongs to the caller and no byte order mark is written.
101
+
102
+ Extra keyword arguments (``quoting``, ``quotechar``, ...) are passed to
103
+ ``csv.writer``. Findings for the cells written so far are in
104
+ ``findings``; ``changed`` counts the cells whose text was altered.
105
+ """
106
+
107
+ def __init__(
108
+ self,
109
+ file: object,
110
+ *,
111
+ target: "str | Target" = "excel",
112
+ policy: "str | Policy | None" = None,
113
+ encoding: str | None = None,
114
+ delimiter: str | None = None,
115
+ lineterminator: str | None = None,
116
+ sep_hint: bool = False,
117
+ **fmtparams: object,
118
+ ) -> None:
119
+ self.target = resolve_target(target)
120
+ self.policy = resolve_policy(policy)
121
+ name, codec, bom = _codec(encoding or self.target.encoding)
122
+ if delimiter is None:
123
+ delimiter = "\t" if name == "utf-16" else self.target.delimiter
124
+ self.delimiter = delimiter
125
+ self.lineterminator = lineterminator or self.target.lineterminator
126
+ self.findings: list[Finding] = []
127
+ self.changed = 0
128
+ self.rows = 0
129
+ self._width: int | None = None
130
+ self._owns_stream = False
131
+
132
+ if _io.is_path(file):
133
+ self._stream = open(file, "w", encoding=codec, newline="") # type: ignore[arg-type]
134
+ self._owns_stream = True
135
+ self.encoding: str | None = name
136
+ elif _io.is_binary_stream(file):
137
+ self._stream = _EncodingStream(file, codec) # type: ignore[assignment]
138
+ self.encoding = name
139
+ else:
140
+ self._stream = file # type: ignore[assignment]
141
+ self.encoding = None
142
+ bom = ""
143
+ if bom:
144
+ self._stream.write(bom)
145
+ if sep_hint:
146
+ self._stream.write(f"sep={delimiter}{self.lineterminator}")
147
+ # Without our own hint line the first row is the first line of the
148
+ # file, and a first cell such as "sep=;" would be taken for a hint.
149
+ self._guard_first_line = not sep_hint
150
+ self._csv = csv.writer(
151
+ self._stream,
152
+ delimiter=delimiter,
153
+ lineterminator=self.lineterminator,
154
+ **fmtparams, # type: ignore[arg-type]
155
+ )
156
+ # In QUOTE_MINIMAL mode some versions of the csv module only quote
157
+ # the line-break characters that occur in the line terminator, so
158
+ # with "\n" endings a cell containing "\r" can be written bare and
159
+ # split the record on reading. To be independent of that, rows with
160
+ # a line break in a cell are written with every field quoted.
161
+ self._csv_quoted = None
162
+ if fmtparams.get("quoting", csv.QUOTE_MINIMAL) == csv.QUOTE_MINIMAL and "dialect" not in fmtparams:
163
+ self._csv_quoted = csv.writer(
164
+ self._stream,
165
+ delimiter=delimiter,
166
+ lineterminator=self.lineterminator,
167
+ **{**fmtparams, "quoting": csv.QUOTE_ALL}, # type: ignore[arg-type]
168
+ )
169
+
170
+ # -- csv.writer interface ------------------------------------------------
171
+
172
+ def writerow(self, row: Iterable[object]) -> object:
173
+ self.rows += 1
174
+ cells: list[object] = []
175
+ for index, value in enumerate(row, start=1):
176
+ outcome = analyse(value, self.policy)
177
+ if outcome.risks:
178
+ self.findings.extend(cell_findings(outcome, self.rows, index))
179
+ if outcome.changed:
180
+ self.changed += 1
181
+ cells.append(outcome.output)
182
+ elif isinstance(value, str) or value is None:
183
+ cells.append(outcome.output)
184
+ else:
185
+ cells.append(value) # keep the type for csv.QUOTE_NONNUMERIC
186
+ if self._width is None:
187
+ self._width = len(cells)
188
+ elif len(cells) != self._width:
189
+ self.findings.append(
190
+ Finding(
191
+ kind="ragged-row",
192
+ message=f"row has {len(cells)} cells, the first row has {self._width}",
193
+ row=self.rows,
194
+ )
195
+ )
196
+ writer = self._csv
197
+ if self._csv_quoted is not None and any(
198
+ isinstance(cell, str) and ("\r" in cell or "\n" in cell) for cell in cells
199
+ ):
200
+ writer = self._csv_quoted
201
+ if (
202
+ self.rows == 1
203
+ and self._guard_first_line
204
+ and cells
205
+ and isinstance(cells[0], str)
206
+ and _io.looks_like_sep_directive(cells[0])
207
+ ):
208
+ return self._write_guarded_first_row(cells, writer)
209
+ return writer.writerow(cells)
210
+
211
+ def _write_guarded_first_row(self, cells: list[object], writer: object) -> int:
212
+ """Write the first row with its first cell quoted.
213
+
214
+ A file whose first line starts with ``sep=`` is read as a separator
215
+ directive by Excel and by :func:`reader`, which would drop the row.
216
+ Quoting the cell makes the line start with the quote character; the
217
+ cell value itself is not changed, so every reader that follows the
218
+ CSV quoting rules gets the original text back.
219
+ """
220
+ first = str(cells[0])
221
+ dialect = self._csv.dialect
222
+ if dialect.quoting == csv.QUOTE_NONE:
223
+ raise csv.Error(
224
+ f"the first cell {first!r} would be read as a 'sep=' line and "
225
+ "must be quoted, but quoting is QUOTE_NONE"
226
+ )
227
+ if "sep-directive" not in self.policy.ignore:
228
+ self.findings.append(
229
+ Finding(
230
+ kind="sep-directive",
231
+ message="first cell of the file starts with 'sep=', which would be "
232
+ "read as a separator line",
233
+ row=1,
234
+ column=1,
235
+ value=first,
236
+ action="cell quoted so the line does not start with sep=",
237
+ )
238
+ )
239
+ buffer = io.StringIO(newline="")
240
+ csv.writer(buffer, dialect, quoting=csv.QUOTE_ALL).writerow([first])
241
+ head = buffer.getvalue()[: -len(dialect.lineterminator)]
242
+ if len(cells) == 1:
243
+ line = head + dialect.lineterminator
244
+ self._stream.write(line)
245
+ return len(line)
246
+ self._stream.write(head + dialect.delimiter)
247
+ rest = writer.writerow(cells[1:]) # type: ignore[attr-defined]
248
+ return len(head) + 1 + (rest if isinstance(rest, int) else 0)
249
+
250
+ def writerows(self, rows: Iterable[Iterable[object]]) -> None:
251
+ for row in rows:
252
+ self.writerow(row)
253
+
254
+ # -- resource handling ---------------------------------------------------
255
+
256
+ def close(self) -> None:
257
+ """Flush. Closes the file only if cellsafe opened it from a path."""
258
+ if self._owns_stream:
259
+ self._stream.close()
260
+ else:
261
+ flush = getattr(self._stream, "flush", None)
262
+ if flush is not None:
263
+ flush()
264
+
265
+ def __enter__(self) -> "Writer":
266
+ return self
267
+
268
+ def __exit__(self, *exc: object) -> None:
269
+ self.close()
270
+
271
+
272
+ def writer(file: object, **options: object) -> Writer:
273
+ """Create a :class:`Writer`. Mirrors ``csv.writer(file, **fmtparams)``.
274
+
275
+ Keyword options: ``target`` (``"excel"``, ``"sheets"``, ``"libreoffice"``
276
+ or ``"plain"``), ``policy``, ``encoding``, ``delimiter``,
277
+ ``lineterminator``, ``sep_hint`` and any ``csv`` formatting parameter.
278
+ """
279
+ return Writer(file, **options) # type: ignore[arg-type]
280
+
281
+
282
+ class DictWriter:
283
+ """Counterpart of ``csv.DictWriter`` built on :class:`Writer`."""
284
+
285
+ def __init__(
286
+ self,
287
+ file: object,
288
+ fieldnames: Sequence[str],
289
+ restval: object = "",
290
+ extrasaction: str = "raise",
291
+ **options: object,
292
+ ) -> None:
293
+ if extrasaction not in ("raise", "ignore"):
294
+ raise ValueError(f"extrasaction ({extrasaction!r}) must be 'raise' or 'ignore'")
295
+ self.fieldnames = list(fieldnames)
296
+ self.restval = restval
297
+ self.extrasaction = extrasaction
298
+ self.writer = Writer(file, **options) # type: ignore[arg-type]
299
+
300
+ @property
301
+ def findings(self) -> list[Finding]:
302
+ return self.writer.findings
303
+
304
+ def writeheader(self) -> object:
305
+ return self.writer.writerow(self.fieldnames)
306
+
307
+ def _row(self, rowdict: Mapping[str, object]) -> list[object]:
308
+ if self.extrasaction == "raise":
309
+ wrong = [k for k in rowdict if k not in self.fieldnames]
310
+ if wrong:
311
+ raise ValueError(
312
+ "dict contains fields not in fieldnames: "
313
+ + ", ".join(repr(k) for k in wrong)
314
+ )
315
+ return [rowdict.get(key, self.restval) for key in self.fieldnames]
316
+
317
+ def writerow(self, rowdict: Mapping[str, object]) -> object:
318
+ return self.writer.writerow(self._row(rowdict))
319
+
320
+ def writerows(self, rowdicts: Iterable[Mapping[str, object]]) -> None:
321
+ for rowdict in rowdicts:
322
+ self.writerow(rowdict)
323
+
324
+ def close(self) -> None:
325
+ self.writer.close()
326
+
327
+ def __enter__(self) -> "DictWriter":
328
+ return self
329
+
330
+ def __exit__(self, *exc: object) -> None:
331
+ self.close()
332
+
333
+
334
+ def dumps(rows: Iterable[Iterable[object]], **options: object) -> str:
335
+ """Return the CSV text for *rows*. A string carries no byte order mark."""
336
+ buffer = io.StringIO(newline="")
337
+ w = Writer(buffer, **options) # type: ignore[arg-type]
338
+ w.writerows(rows)
339
+ return buffer.getvalue()
340
+
341
+
342
+ def dumpb(rows: Iterable[Iterable[object]], **options: object) -> bytes:
343
+ """Return the encoded CSV file for *rows*, byte order mark included."""
344
+ buffer = io.BytesIO()
345
+ w = Writer(buffer, **options) # type: ignore[arg-type]
346
+ w.writerows(rows)
347
+ w.close()
348
+ return buffer.getvalue()
349
+
350
+
351
+ def _read_source(file: object, encoding: str | None, fallback_encoding: str) -> _io.Decoded:
352
+ if _io.is_path(file):
353
+ with open(file, "rb") as handle: # type: ignore[arg-type]
354
+ return _io.decode_bytes(handle.read(), fallback_encoding, encoding)
355
+ if isinstance(file, (bytes, bytearray)):
356
+ return _io.decode_bytes(bytes(file), fallback_encoding, encoding)
357
+ if _io.is_binary_stream(file):
358
+ return _io.decode_bytes(file.read(), fallback_encoding, encoding) # type: ignore[attr-defined]
359
+ read = getattr(file, "read", None)
360
+ text = read() if read is not None else "".join(file) # type: ignore[arg-type]
361
+ if not isinstance(text, str):
362
+ raise TypeError("reader() needs a path, bytes, a stream or an iterable of text lines")
363
+ return _io.Decoded(text, None, False)
364
+
365
+
366
+ def reader(
367
+ file: object,
368
+ *,
369
+ target: "str | Target" = "excel",
370
+ policy: "str | Policy | None" = None,
371
+ delimiter: str | None = None,
372
+ encoding: str | None = None,
373
+ fallback_encoding: str = _io.DEFAULT_FALLBACK,
374
+ **fmtparams: object,
375
+ ) -> Iterator[list[str]]:
376
+ """Read a file written by :func:`writer` and undo the cell protection.
377
+
378
+ Use the same *target* and *policy* as the writer. *file* is a path,
379
+ bytes, a binary or text stream, or an iterable of text lines; a ``str``
380
+ is always a path. The input is read into memory. The encoding is taken
381
+ from a byte order mark, else strict UTF-8, else *fallback_encoding*
382
+ (or pass *encoding*). A ``sep=`` first line is honoured and skipped;
383
+ otherwise the delimiter is the target's (tab for UTF-16 input).
384
+ """
385
+ pol = resolve_policy(policy)
386
+ tgt = resolve_target(target)
387
+ decoded = _read_source(file, encoding, fallback_encoding)
388
+ hinted, text = _io.split_sep_hint(decoded.text)
389
+ if delimiter is None:
390
+ if hinted is not None:
391
+ delimiter = hinted
392
+ elif decoded.encoding and decoded.encoding.lower().startswith("utf-16"):
393
+ delimiter = "\t"
394
+ else:
395
+ delimiter = tgt.delimiter
396
+ for row in csv.reader(io.StringIO(text, newline=""), delimiter=delimiter, **fmtparams): # type: ignore[arg-type]
397
+ yield [unprotect(cell, pol) if isinstance(cell, str) else cell for cell in row]