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/cli.py ADDED
@@ -0,0 +1,229 @@
1
+ """Command line interface: ``cellsafe audit | fix | explain | kinds``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import csv
7
+ import json
8
+ import os
9
+ import pathlib
10
+ import sys
11
+ import textwrap
12
+ from collections.abc import Sequence
13
+
14
+ from . import __version__, _io
15
+ from ._audit import audit
16
+ from ._kinds import KINDS
17
+ from ._policy import POLICIES, POLICY_SUMMARIES, Policy, resolve_policy
18
+ from ._protect import unprotect
19
+ from ._writer import TARGETS, Writer
20
+
21
+ EXIT_OK = 0
22
+ EXIT_RISKS = 1
23
+ EXIT_ERROR = 2
24
+
25
+
26
+ def _add_policy_options(parser: argparse.ArgumentParser) -> None:
27
+ parser.add_argument("--target", choices=list(TARGETS), default="excel",
28
+ help="who will open the file (default: excel)")
29
+ parser.add_argument("--policy", choices=list(POLICIES), default="default",
30
+ help="what to do about risky cells (default: default)")
31
+ parser.add_argument("--digits", choices=["keep", "ascii"], default=None,
32
+ help="ascii: rewrite Arabic-Indic/Persian numbers with ASCII digits")
33
+ parser.add_argument("--bidi", choices=["keep", "strip"], default=None,
34
+ help="strip: remove bidi control characters from cells")
35
+ parser.add_argument("--ignore", action="append", default=[], metavar="KIND",
36
+ help="risk kind to leave alone; may be repeated")
37
+ parser.add_argument("--delimiter", default=None, metavar="CHAR",
38
+ help="input delimiter (a character, or tab/comma/semicolon/pipe); "
39
+ "default: the sep= line, else the most frequent of , ; tab | "
40
+ "in the first record")
41
+ parser.add_argument("--fallback-encoding", default=_io.DEFAULT_FALLBACK, metavar="ENC",
42
+ help="encoding to use when the input has no BOM and is not valid "
43
+ "UTF-8 (default: cp1252); encodings are never guessed")
44
+
45
+
46
+ def build_parser() -> argparse.ArgumentParser:
47
+ parser = argparse.ArgumentParser(
48
+ prog="cellsafe",
49
+ description="Write and check CSV files so that spreadsheet programs open "
50
+ "them without damaging or misusing the data.",
51
+ )
52
+ parser.add_argument("--version", action="version", version=f"cellsafe {__version__}")
53
+ sub = parser.add_subparsers(dest="command", required=True)
54
+
55
+ p_audit = sub.add_parser("audit", help="report risky cells; exit status 1 if any")
56
+ p_audit.add_argument("file")
57
+ p_audit.add_argument("--format", choices=["text", "json"], default="text")
58
+ p_audit.add_argument("--no-header", action="store_true",
59
+ help="do not treat the first row as column names")
60
+ p_audit.add_argument("--protected", action="store_true",
61
+ help="the file was written by cellsafe with --policy; "
62
+ "do not report cells that are already protected")
63
+ _add_policy_options(p_audit)
64
+
65
+ p_fix = sub.add_parser("fix", help="write a protected copy; never edits in place")
66
+ p_fix.add_argument("input")
67
+ p_fix.add_argument("-o", "--output", required=True)
68
+ p_fix.add_argument("--force", action="store_true",
69
+ help="overwrite the output file if it exists")
70
+ p_fix.add_argument("--encoding", default=None, choices=["utf-8-sig", "utf-8", "utf-16"],
71
+ help="output encoding (default: what the target calls for); "
72
+ "utf-16 means UTF-16 LE with BOM and a tab delimiter")
73
+ p_fix.add_argument("--out-delimiter", default=None, metavar="CHAR",
74
+ help="output delimiter (default: comma, or tab for utf-16)")
75
+ p_fix.add_argument("--sep-hint", action="store_true",
76
+ help="start the output with a sep= line")
77
+ p_fix.add_argument("--from-policy", choices=list(POLICIES), default=None,
78
+ help="the input was written by cellsafe with this policy; "
79
+ "undo it first so cells are not protected twice")
80
+ _add_policy_options(p_fix)
81
+
82
+ p_explain = sub.add_parser("explain", help="explain one risk kind")
83
+ p_explain.add_argument("kind")
84
+
85
+ sub.add_parser("kinds", help="list risk kinds and policies")
86
+ return parser
87
+
88
+
89
+ def _policy_from(args: argparse.Namespace) -> Policy:
90
+ overrides: dict[str, object] = {}
91
+ if args.digits:
92
+ overrides["digits"] = args.digits
93
+ if args.bidi:
94
+ overrides["bidi"] = args.bidi
95
+ if args.ignore:
96
+ overrides["ignore"] = frozenset(args.ignore)
97
+ if overrides:
98
+ overrides["name"] = args.policy
99
+ return resolve_policy(args.policy, **overrides)
100
+
101
+
102
+ def _cmd_audit(args: argparse.Namespace) -> int:
103
+ report = audit(
104
+ pathlib.Path(args.file),
105
+ target=args.target,
106
+ policy=_policy_from(args),
107
+ delimiter=_io.parse_delimiter(args.delimiter) if args.delimiter else None,
108
+ fallback_encoding=args.fallback_encoding,
109
+ header=not args.no_header,
110
+ protected=args.protected,
111
+ )
112
+ if args.format == "json":
113
+ print(json.dumps(report.to_dict(), ensure_ascii=False, indent=2))
114
+ else:
115
+ print(report.format_text())
116
+ return EXIT_OK if report.ok else EXIT_RISKS
117
+
118
+
119
+ def _same_file(a: str, b: str) -> bool:
120
+ try:
121
+ return os.path.samefile(a, b)
122
+ except OSError:
123
+ return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b))
124
+
125
+
126
+ def _cmd_fix(args: argparse.Namespace) -> int:
127
+ if _same_file(args.input, args.output):
128
+ raise ValueError("input and output are the same file; cellsafe never edits in place")
129
+ policy = _policy_from(args)
130
+ with open(args.input, "rb") as handle:
131
+ decoded = _io.decode_bytes(handle.read(), args.fallback_encoding)
132
+ hinted, text = _io.split_sep_hint(decoded.text)
133
+ if args.delimiter:
134
+ delimiter = _io.parse_delimiter(args.delimiter)
135
+ elif hinted is not None:
136
+ delimiter = hinted
137
+ else:
138
+ delimiter = _io.sniff_delimiter(text)
139
+ rows = _io.parse_rows(text, delimiter)
140
+ if args.from_policy:
141
+ rows = [[unprotect(cell, args.from_policy) for cell in row] for row in rows]
142
+
143
+ try:
144
+ out = open(args.output, "wb" if args.force else "xb")
145
+ except FileExistsError:
146
+ raise ValueError(
147
+ f"{args.output} already exists; choose another name or pass --force"
148
+ ) from None
149
+ with out:
150
+ w = Writer(
151
+ out,
152
+ target=args.target,
153
+ policy=policy,
154
+ encoding=args.encoding,
155
+ delimiter=_io.parse_delimiter(args.out_delimiter) if args.out_delimiter else None,
156
+ sep_hint=args.sep_hint,
157
+ )
158
+ w.writerows(rows)
159
+ w.close()
160
+ unprotected = sum(1 for f in w.findings if f.column is not None and f.fix is None)
161
+ print(
162
+ f"wrote {args.output}: {w.rows} rows, {w.changed} cell(s) changed, "
163
+ f"encoding {w.encoding}, delimiter {w.delimiter!r}"
164
+ )
165
+ if decoded.fallback_used:
166
+ print(f"note: input was not UTF-8 and was decoded as {decoded.encoding}")
167
+ if unprotected:
168
+ print(
169
+ f"note: {unprotected} finding(s) were reported only and left as they are "
170
+ f"under policy {policy.name!r}; run 'cellsafe audit' on the input for details"
171
+ )
172
+ return EXIT_OK
173
+
174
+
175
+ def _wrap(text: str, indent: str = "") -> str:
176
+ return textwrap.fill(text, width=78, initial_indent=indent, subsequent_indent=indent)
177
+
178
+
179
+ def _cmd_explain(args: argparse.Namespace) -> int:
180
+ kind = KINDS.get(args.kind)
181
+ if kind is None:
182
+ raise ValueError(
183
+ f"unknown kind {args.kind!r}; run 'cellsafe kinds' for the list"
184
+ )
185
+ print(f"{kind.name} ({kind.scope}-level)")
186
+ print(_wrap(kind.summary))
187
+ print()
188
+ print(_wrap(kind.explanation))
189
+ return EXIT_OK
190
+
191
+
192
+ def _cmd_kinds(args: argparse.Namespace) -> int:
193
+ print("Risk kinds:")
194
+ for kind in KINDS.values():
195
+ print(f" {kind.name:<19} {kind.scope:<5} {kind.summary}")
196
+ print()
197
+ print("Policies:")
198
+ for name in POLICIES:
199
+ print(f" {name:<11} {POLICY_SUMMARIES[name]}")
200
+ return EXIT_OK
201
+
202
+
203
+ _COMMANDS = {
204
+ "audit": _cmd_audit,
205
+ "fix": _cmd_fix,
206
+ "explain": _cmd_explain,
207
+ "kinds": _cmd_kinds,
208
+ }
209
+
210
+
211
+ def main(argv: Sequence[str] | None = None) -> int:
212
+ """Run the CLI and return the exit status (0 ok, 1 risks found, 2 error)."""
213
+ for stream in (sys.stdout, sys.stderr):
214
+ reconfigure = getattr(stream, "reconfigure", None)
215
+ if reconfigure is not None:
216
+ try:
217
+ reconfigure(errors="backslashreplace")
218
+ except (ValueError, OSError):
219
+ pass
220
+ args = build_parser().parse_args(argv)
221
+ try:
222
+ return _COMMANDS[args.command](args)
223
+ except (OSError, ValueError, LookupError, csv.Error) as exc:
224
+ print(f"cellsafe: error: {exc}", file=sys.stderr)
225
+ return EXIT_ERROR
226
+
227
+
228
+ if __name__ == "__main__":
229
+ sys.exit(main())