hc-migrate 0.2.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.
hc_migrate/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Turn notebooks into handcalcs v2 scripts, and migrate handcalcs v1 notebooks and scripts to v2."""
2
+
3
+ __version__ = "0.2.0"
hc_migrate/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
hc_migrate/cli.py ADDED
@@ -0,0 +1,418 @@
1
+ """
2
+ The ``hc-migrate`` command.
3
+
4
+ hc-migrate calc.ipynb --to ipynb -o calc_v2.ipynb # v1 notebook -> v2 notebook
5
+ hc-migrate calc.ipynb --to py -o calc.py # notebook -> v2 script
6
+ hc-migrate calcs/ --to py --output scripts # notebooks -> scripts
7
+
8
+ Existing files are never changed: a script is written next to its notebook
9
+ (or under DEST), and a converted notebook or ``.py`` file is a new file.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import fnmatch
16
+ import os
17
+ import shutil
18
+ import sys
19
+ from dataclasses import dataclass, field
20
+ from pathlib import Path
21
+
22
+ from . import __version__
23
+ from .convert import GUIDE
24
+ from .export import ExportOptions, export_notebook
25
+ from .notebook import FileResult, convert_notebook, convert_script
26
+
27
+ CONVERTIBLE = (".ipynb", ".py")
28
+ DEFAULT_EXCLUDES = (".git", ".ipynb_checkpoints", "__pycache__", ".venv", ".DS_Store")
29
+
30
+ DESCRIPTION = """\
31
+ Two conversions:
32
+
33
+ --to ipynb update notebooks (and .py files) written for handcalcs v1 so
34
+ they work with handcalcs v2. They stay notebooks.
35
+ --to py turn notebooks, written for handcalcs v1 or v2, into handcalcs
36
+ v2 scripts (.py) that render as the notebook showed (the
37
+ default).
38
+
39
+ In a script, Markdown cells become comments (prose and headings), %%render
40
+ cells become plain lines, and the other code cells run but are hidden. A v1
41
+ notebook is converted to v2 on the way.
42
+
43
+ SOURCE is a file or a directory. A directory is searched for notebooks (and
44
+ .py files), and with -o its tree is copied to DEST, the notebooks and Python
45
+ files converted. Existing files are never changed.
46
+ """
47
+
48
+ EPILOG = f"""\
49
+ examples:
50
+ hc-migrate beam.ipynb writes beam.py
51
+ hc-migrate beam.ipynb -o out/beam.py
52
+ hc-migrate calcs/ writes a .py next to each notebook
53
+ hc-migrate calcs/ -o scripts --report report.md
54
+ hc-migrate beam.ipynb --to ipynb writes beam_v2.ipynb (v1 -> v2)
55
+ hc-migrate calcs/ --to ipynb --output v2 writes v2/, the notebooks converted
56
+ hc-migrate calcs/ --dry-run only reports what would be written
57
+
58
+ What changes, and what to check by hand afterwards, is reported for each file.
59
+ The handcalcs v1 to v2 guide: {GUIDE}
60
+ """
61
+
62
+
63
+ @dataclass
64
+ class Summary:
65
+ exported: int = 0
66
+ converted: int = 0
67
+ unchanged: int = 0
68
+ copied: int = 0
69
+ skipped: int = 0
70
+ failed: int = 0
71
+ warnings: int = 0
72
+ written: set[Path] = field(default_factory=set)
73
+ report: list[str] = field(default_factory=list)
74
+
75
+
76
+ def build_parser() -> argparse.ArgumentParser:
77
+ parser = argparse.ArgumentParser(
78
+ prog="hc-migrate",
79
+ description=DESCRIPTION,
80
+ epilog=EPILOG,
81
+ formatter_class=argparse.RawDescriptionHelpFormatter,
82
+ allow_abbrev=False,
83
+ )
84
+ parser.add_argument(
85
+ "source", metavar="SOURCE", type=Path, help="a file or directory"
86
+ )
87
+ parser.add_argument(
88
+ "-o",
89
+ "--output",
90
+ metavar="DEST",
91
+ type=Path,
92
+ help="where to write: a file, or a directory for a tree "
93
+ "(default: next to SOURCE)",
94
+ )
95
+ parser.add_argument(
96
+ "--to",
97
+ choices=("py", "ipynb"),
98
+ default="py",
99
+ help="py: notebooks (v1 or v2) become handcalcs v2 scripts (the "
100
+ "default); ipynb: notebooks written for v1 are converted to v2 and stay "
101
+ "notebooks",
102
+ )
103
+ parser.add_argument(
104
+ "--from",
105
+ dest="source_version",
106
+ choices=("auto", "v1", "v2"),
107
+ default="auto",
108
+ help="the handcalcs the source was written for (default: tell from "
109
+ "the source; v2 when nothing tells)",
110
+ )
111
+ parser.add_argument(
112
+ "-f",
113
+ "--force",
114
+ "--overwrite",
115
+ action="store_true",
116
+ help="overwrite files (or DEST) that exist",
117
+ )
118
+ parser.add_argument(
119
+ "-n",
120
+ "--dry-run",
121
+ action="store_true",
122
+ help="report what would be written, and write nothing",
123
+ )
124
+ parser.add_argument(
125
+ "--report",
126
+ metavar="FILE",
127
+ type=Path,
128
+ help="also write the report to FILE (Markdown)",
129
+ )
130
+ parser.add_argument(
131
+ "--show-code",
132
+ action="store_true",
133
+ help="scripts: show the code cells the notebook didn't render",
134
+ )
135
+ parser.add_argument(
136
+ "--no-black", action="store_true", help="scripts: don't format with black"
137
+ )
138
+ parser.add_argument(
139
+ "--keep-v1-precision",
140
+ action="store_true",
141
+ help="v1: show numbers with 3 decimal places where v1 used its default "
142
+ "(v2's default is 5 significant figures)",
143
+ )
144
+ parser.add_argument(
145
+ "--v1-names",
146
+ action="store_true",
147
+ help="v1: keep v1's nested subscripts (x_a_b) and Greek names (phiM) "
148
+ "with set_option calls",
149
+ )
150
+ parser.add_argument(
151
+ "--clear-outputs",
152
+ action="store_true",
153
+ help="--to ipynb: clear the outputs of converted cells (they show the "
154
+ "v1 render)",
155
+ )
156
+ parser.add_argument(
157
+ "--exclude",
158
+ metavar="PATTERN",
159
+ action="append",
160
+ default=[],
161
+ help="skip files and directories matching PATTERN (repeatable; "
162
+ f"always skipped: {', '.join(DEFAULT_EXCLUDES)})",
163
+ )
164
+ parser.add_argument(
165
+ "--only-converted",
166
+ action="store_true",
167
+ help="with a directory DEST, write only notebooks and Python files, "
168
+ "not the other files",
169
+ )
170
+ parser.add_argument(
171
+ "-q", "--quiet", action="store_true", help="report only files with warnings"
172
+ )
173
+ parser.add_argument(
174
+ "-V", "--version", action="version", version=f"%(prog)s {__version__}"
175
+ )
176
+ return parser
177
+
178
+
179
+ def default_output(source: Path, to: str) -> Path | None:
180
+ """Where to write when no DEST is given; None: next to each notebook."""
181
+ if source.is_dir():
182
+ if to == "py":
183
+ return None
184
+ return source.with_name(source.resolve().name + "_v2")
185
+ if to == "py" and source.suffix == ".ipynb":
186
+ return source.with_suffix(".py")
187
+ return source.with_name(f"{source.stem}_v2{source.suffix}")
188
+
189
+
190
+ def file_dest(source: Path, output: Path | None, to: str) -> Path:
191
+ """Where a single SOURCE file goes: DEST, or a file in DEST if it is a directory."""
192
+ if output is None:
193
+ return default_output(source, to)
194
+ if output.is_dir() or (output.suffix == "" and not output.exists()):
195
+ name = source.with_suffix(".py").name if exports(source, to) else source.name
196
+ return output / name
197
+ return output
198
+
199
+
200
+ def exports(path: Path, to: str) -> bool:
201
+ return to == "py" and path.suffix == ".ipynb"
202
+
203
+
204
+ def convert_file(path: Path, to: str, options: ExportOptions) -> FileResult:
205
+ text = path.read_text(encoding="utf-8")
206
+ if exports(path, to):
207
+ return export_notebook(text, options, path.stem)
208
+ if path.suffix == ".ipynb":
209
+ return convert_notebook(text, options)
210
+ return convert_script(text, options)
211
+
212
+
213
+ def is_excluded(name: str, patterns: list[str]) -> bool:
214
+ return any(fnmatch.fnmatch(name, p) for p in (*DEFAULT_EXCLUDES, *patterns))
215
+
216
+
217
+ def plural(n: int, word: str) -> str:
218
+ return f"{n} {word}{'' if n == 1 else 's'}"
219
+
220
+
221
+ def handle_file(
222
+ source: Path,
223
+ dest: Path,
224
+ shown_as: str,
225
+ args: argparse.Namespace,
226
+ options: ExportOptions,
227
+ summary: Summary,
228
+ per_file_force: bool,
229
+ ) -> None:
230
+ """Convert, export or copy one file and record it in the summary."""
231
+ if source.suffix not in CONVERTIBLE:
232
+ if not args.only_converted:
233
+ if not args.dry_run:
234
+ dest.parent.mkdir(parents=True, exist_ok=True)
235
+ shutil.copy2(source, dest)
236
+ summary.copied += 1
237
+ return
238
+ if dest.resolve() in summary.written:
239
+ summary.skipped += 1
240
+ print(f"skipped {shown_as}: another file was written to {dest}")
241
+ return
242
+ if per_file_force and dest.exists() and not args.force:
243
+ summary.skipped += 1
244
+ if not args.quiet:
245
+ print(f"skipped {shown_as}: {dest} exists (use --force)")
246
+ return
247
+ exporting = exports(source, args.to)
248
+ try:
249
+ result = convert_file(source, args.to, options)
250
+ except (ValueError, UnicodeDecodeError, OSError) as error:
251
+ summary.failed += 1
252
+ if exporting:
253
+ print(f"FAILED {shown_as}: {error}", file=sys.stderr)
254
+ summary.report.append(f"## {shown_as}\n\nFailed: {error}.\n")
255
+ return
256
+ print(f"FAILED {shown_as}: {error}; copied unchanged", file=sys.stderr)
257
+ summary.report.append(f"## {shown_as}\n\nFailed: {error}. Copied unchanged.\n")
258
+ if not args.dry_run:
259
+ dest.parent.mkdir(parents=True, exist_ok=True)
260
+ shutil.copy2(source, dest)
261
+ return
262
+ summary.written.add(dest.resolve())
263
+ if not args.dry_run:
264
+ dest.parent.mkdir(parents=True, exist_ok=True)
265
+ if exporting:
266
+ dest.write_text(result.text, encoding="utf-8", newline="\n")
267
+ elif result.changed:
268
+ dest.write_text(result.text, encoding="utf-8", newline="")
269
+ shutil.copystat(source, dest)
270
+ else:
271
+ shutil.copy2(source, dest)
272
+ if not exporting and not result.uses_handcalcs:
273
+ summary.copied += 1
274
+ return
275
+ warnings = result.warnings
276
+ summary.warnings += len(warnings)
277
+ if exporting:
278
+ summary.exported += 1
279
+ status = "exported"
280
+ elif result.changed:
281
+ summary.converted += 1
282
+ status = "converted"
283
+ else:
284
+ summary.unchanged += 1
285
+ status = "no changes needed"
286
+ changes = [(w, n) for w, n in result.notes if n.level == "change"]
287
+ line = f"{status:<17} {shown_as}"
288
+ if exporting:
289
+ line += f" -> {dest.name}"
290
+ if changes or warnings:
291
+ line += (
292
+ f" ({plural(len(changes), 'change')}, {plural(len(warnings), 'warning')})"
293
+ )
294
+ if warnings or not args.quiet:
295
+ print(line)
296
+ for where, note in warnings:
297
+ print(f" warning: {where + ', ' if where else ''}{note}")
298
+ report = [f"## {shown_as}\n", f"{status}.\n"]
299
+ for title, items in (("Check by hand", warnings), ("Changes", changes)):
300
+ if items:
301
+ report.append(f"\n**{title}:**\n")
302
+ report.extend(
303
+ f"- {where + ', ' if where else ''}{note}\n" for where, note in items
304
+ )
305
+ summary.report.append("".join(report))
306
+
307
+
308
+ def walk(source: Path, patterns: list[str]):
309
+ """The files under ``source``, as paths relative to it, in order."""
310
+ for root, dirs, files in os.walk(source):
311
+ dirs[:] = sorted(
312
+ d
313
+ for d in dirs
314
+ if not is_excluded(d, patterns) and not Path(root, d).is_symlink()
315
+ )
316
+ for name in sorted(files):
317
+ if not is_excluded(name, patterns):
318
+ yield Path(root, name).relative_to(source)
319
+
320
+
321
+ def main(argv: list[str] | None = None) -> int:
322
+ parser = build_parser()
323
+ if argv is None:
324
+ argv = sys.argv[1:]
325
+ if not argv:
326
+ parser.print_help()
327
+ return 0
328
+ args = parser.parse_args(argv)
329
+ # Windows PowerShell passes '~' through as it is.
330
+ source: Path = args.source.expanduser()
331
+ output: Path | None = args.output.expanduser() if args.output else None
332
+ if not source.exists():
333
+ parser.error(f"{source}: no such file or directory")
334
+ if source.is_file() and source.suffix not in CONVERTIBLE:
335
+ parser.error(f"{source}: not a notebook (.ipynb) or Python file (.py)")
336
+ options = ExportOptions(
337
+ source=args.source_version,
338
+ keep_v1_precision=args.keep_v1_precision,
339
+ v1_names=args.v1_names,
340
+ clear_outputs=args.clear_outputs,
341
+ show_code=args.show_code,
342
+ black=not args.no_black,
343
+ )
344
+
345
+ summary = Summary()
346
+ if source.is_file():
347
+ dest = file_dest(source, output, args.to)
348
+ if dest.resolve() == source.resolve():
349
+ parser.error("DEST is SOURCE: existing files are never changed")
350
+ if dest.exists() and not (args.force or args.dry_run):
351
+ parser.error(f"{dest} exists: use --force to overwrite it")
352
+ handle_file(source, dest, str(source), args, options, summary, False)
353
+ shown_dest = dest
354
+ elif output is None and args.to == "py":
355
+ # Each notebook's script next to it; nothing else is written.
356
+ for relative in walk(source, args.exclude):
357
+ if relative.suffix == ".ipynb":
358
+ path = source / relative
359
+ handle_file(
360
+ path,
361
+ path.with_suffix(".py"),
362
+ relative.as_posix(),
363
+ args,
364
+ options,
365
+ summary,
366
+ True,
367
+ )
368
+ shown_dest = source
369
+ else:
370
+ dest = output or default_output(source, args.to)
371
+ if dest.resolve() == source.resolve():
372
+ parser.error("DEST is SOURCE: existing files are never changed")
373
+ if dest.resolve().is_relative_to(source.resolve()):
374
+ parser.error("DEST is inside SOURCE: choose a DEST outside it")
375
+ if dest.exists() and not (args.force or args.dry_run):
376
+ parser.error(f"{dest} exists: use --force to overwrite it")
377
+ for relative in walk(source, args.exclude):
378
+ target = dest / relative
379
+ if exports(relative, args.to):
380
+ target = target.with_suffix(".py")
381
+ handle_file(
382
+ source / relative,
383
+ target,
384
+ relative.as_posix(),
385
+ args,
386
+ options,
387
+ summary,
388
+ False,
389
+ )
390
+ shown_dest = dest
391
+
392
+ totals = []
393
+ if summary.exported or args.to == "py":
394
+ totals.append(plural(summary.exported, "notebook") + " exported")
395
+ if summary.converted or summary.unchanged or args.to == "ipynb":
396
+ totals.append(plural(summary.converted, "file") + " converted")
397
+ totals.append(f"{summary.unchanged} already fine")
398
+ if source.is_dir() and summary.copied:
399
+ totals.append(f"{summary.copied} copied")
400
+ if summary.skipped:
401
+ totals.append(f"{summary.skipped} skipped")
402
+ totals.append(plural(summary.warnings, "warning"))
403
+ if summary.failed:
404
+ totals.append(f"{summary.failed} failed")
405
+ verb = "Would write" if args.dry_run else "Wrote"
406
+ print(f"\n{', '.join(totals)}.")
407
+ if summary.written or summary.copied:
408
+ print(f"{verb} {shown_dest}")
409
+ if args.report:
410
+ heading = f"# hc-migrate: {source}\n\n{', '.join(totals)}.\n\n"
411
+ args.report.parent.mkdir(parents=True, exist_ok=True)
412
+ args.report.write_text(heading + "\n".join(summary.report), encoding="utf-8")
413
+ print(f"Report: {args.report}")
414
+ return 1 if summary.failed else 0
415
+
416
+
417
+ if __name__ == "__main__":
418
+ sys.exit(main())