md2site-cli 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.
md2site/cli.py ADDED
@@ -0,0 +1,354 @@
1
+ """Command-line interface for md2site."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from collections import defaultdict
8
+ from dataclasses import replace
9
+ from pathlib import Path
10
+
11
+ from md2site import __version__
12
+ from md2site.build import run_pipeline
13
+ from md2site.config import Config, ConfigError, load_config
14
+ from md2site.diagnostics import format_diagnostic, to_json
15
+ from md2site.hook import run_hook
16
+ from md2site.init_cmd import InitError, run_init
17
+ from md2site.model import Diagnostic
18
+ from md2site.watcher import watch_and_serve
19
+
20
+ _HELP_EPILOG = """\
21
+ examples:
22
+ md2site init docs
23
+ md2site build docs --strict
24
+ md2site check docs --json
25
+ md2site watch docs --port 8000 --open
26
+ md2site hook < hook-payload.json
27
+ """
28
+
29
+
30
+ def build_parser() -> argparse.ArgumentParser:
31
+ """Construct the top-level CLI argument parser."""
32
+ parser = argparse.ArgumentParser(
33
+ prog="md2site",
34
+ description="Compile a folder of Markdown into a static, offline-capable HTML docs site.",
35
+ epilog=_HELP_EPILOG,
36
+ formatter_class=argparse.RawDescriptionHelpFormatter,
37
+ )
38
+ parser.add_argument(
39
+ "--version",
40
+ action="version",
41
+ version=f"%(prog)s {__version__}",
42
+ )
43
+
44
+ subparsers = parser.add_subparsers(dest="command", required=True)
45
+
46
+ # md2site init [PATH] [--force] [--with-skill]
47
+ init_parser = subparsers.add_parser(
48
+ "init",
49
+ help="Initialize md2site config and supporting files in a docs directory.",
50
+ )
51
+ init_parser.add_argument(
52
+ "path",
53
+ nargs="?",
54
+ default=".",
55
+ help="Target docs directory (default: .).",
56
+ )
57
+ init_parser.add_argument(
58
+ "--force",
59
+ action="store_true",
60
+ help="Overwrite existing files if present.",
61
+ )
62
+ init_parser.add_argument(
63
+ "--with-skill",
64
+ action="store_true",
65
+ help="Install SKILL.md into <git root>/.claude/skills/md2site/SKILL.md.",
66
+ )
67
+
68
+ # md2site build [PATH] [--config FILE] [--mode ...] [--out DIR]
69
+ # [--strict] [--json] [--quiet] [--drafts]
70
+ build_parser_cmd = subparsers.add_parser(
71
+ "build",
72
+ help="Build the static HTML documentation site.",
73
+ )
74
+ build_parser_cmd.add_argument(
75
+ "path",
76
+ nargs="?",
77
+ default=".",
78
+ help="Target docs directory (default: .).",
79
+ )
80
+ build_parser_cmd.add_argument(
81
+ "--config",
82
+ metavar="FILE",
83
+ default=None,
84
+ help="Path to md2site.config.json.",
85
+ )
86
+ build_parser_cmd.add_argument(
87
+ "--mode",
88
+ choices=("relative", "editor", "remote", "auto"),
89
+ default=None,
90
+ help="Override source_link_mode for this run.",
91
+ )
92
+ build_parser_cmd.add_argument(
93
+ "--out",
94
+ metavar="DIR",
95
+ default=None,
96
+ help="Override output directory.",
97
+ )
98
+ build_parser_cmd.add_argument(
99
+ "--strict",
100
+ action="store_true",
101
+ help="Exit non-zero if any warnings or errors are emitted.",
102
+ )
103
+ build_parser_cmd.add_argument(
104
+ "--json",
105
+ action="store_true",
106
+ dest="json_output",
107
+ help="Emit machine-readable JSON summary and diagnostics to stdout.",
108
+ )
109
+ build_parser_cmd.add_argument(
110
+ "--quiet",
111
+ action="store_true",
112
+ help="Suppress non-error human-readable output.",
113
+ )
114
+ build_parser_cmd.add_argument(
115
+ "--drafts",
116
+ action="store_true",
117
+ help="Include pages marked draft: true.",
118
+ )
119
+
120
+ # md2site check [PATH] [--config FILE] [--strict] [--json]
121
+ check_parser = subparsers.add_parser(
122
+ "check",
123
+ help="Validate links and references without writing output.",
124
+ )
125
+ check_parser.add_argument(
126
+ "path",
127
+ nargs="?",
128
+ default=".",
129
+ help="Target docs directory (default: .).",
130
+ )
131
+ check_parser.add_argument(
132
+ "--config",
133
+ metavar="FILE",
134
+ default=None,
135
+ help="Path to md2site.config.json.",
136
+ )
137
+ check_parser.add_argument(
138
+ "--strict",
139
+ action="store_true",
140
+ help="Exit non-zero if any diagnostics are present.",
141
+ )
142
+ check_parser.add_argument(
143
+ "--json",
144
+ action="store_true",
145
+ dest="json_output",
146
+ help="Emit machine-readable JSON summary and diagnostics to stdout.",
147
+ )
148
+
149
+ # md2site watch [PATH] [--config FILE] [--host 127.0.0.1] [--port 8000] [--open]
150
+ watch_parser = subparsers.add_parser(
151
+ "watch",
152
+ help="Serve the built site locally and rebuild on changes.",
153
+ )
154
+ watch_parser.add_argument(
155
+ "path",
156
+ nargs="?",
157
+ default=".",
158
+ help="Target docs directory (default: .).",
159
+ )
160
+ watch_parser.add_argument(
161
+ "--config",
162
+ metavar="FILE",
163
+ default=None,
164
+ help="Path to md2site.config.json.",
165
+ )
166
+ watch_parser.add_argument(
167
+ "--host",
168
+ default="127.0.0.1",
169
+ help="Host interface to bind (default: 127.0.0.1).",
170
+ )
171
+ watch_parser.add_argument(
172
+ "--port",
173
+ type=int,
174
+ default=8000,
175
+ help="Port to bind (default: 8000).",
176
+ )
177
+ watch_parser.add_argument(
178
+ "--open",
179
+ action="store_true",
180
+ dest="open_browser",
181
+ help="Open the local URL in the default browser.",
182
+ )
183
+
184
+ # md2site hook
185
+ subparsers.add_parser(
186
+ "hook",
187
+ help="Handle agent post-edit hook JSON payload on stdin.",
188
+ )
189
+
190
+ return parser
191
+
192
+
193
+ def _print_grouped_diagnostics(diagnostics: list[Diagnostic]) -> None:
194
+ if not diagnostics:
195
+ return
196
+ by_file: dict[str, list[Diagnostic]] = defaultdict(list)
197
+ for diag in diagnostics:
198
+ by_file[diag.file].append(diag)
199
+ for file_rel in sorted(by_file):
200
+ for diag in by_file[file_rel]:
201
+ print(format_diagnostic(diag), file=sys.stderr)
202
+
203
+
204
+ def _load_cli_config(
205
+ path: str,
206
+ *,
207
+ config_file: str | None = None,
208
+ mode: str | None = None,
209
+ out_dir: str | None = None,
210
+ ) -> Config:
211
+ cfg = load_config(path, config_file=config_file)
212
+ if mode is not None:
213
+ cfg = replace(cfg, source_link_mode=mode)
214
+ if out_dir is not None:
215
+ cfg = replace(cfg, output_dir=Path(out_dir).resolve())
216
+ return cfg
217
+
218
+
219
+ def _handle_init(args: argparse.Namespace) -> int:
220
+ try:
221
+ res = run_init(args.path, force=args.force, with_skill=args.with_skill)
222
+ except (InitError, OSError) as exc:
223
+ print(f"md2site init: {exc}", file=sys.stderr)
224
+ return 2
225
+
226
+ print(f"Initialized md2site in {res.target_dir}", file=sys.stderr)
227
+ print(f" created {res.config_path}", file=sys.stderr)
228
+ print(f" created {res.custom_css_path}", file=sys.stderr)
229
+ print(f" ensured {res.output_dir}", file=sys.stderr)
230
+ if res.skill_written and res.skill_path is not None:
231
+ print(f" created {res.skill_path}", file=sys.stderr)
232
+ if res.gitignore_updated and res.gitignore_path is not None:
233
+ print(f" added {res.gitignore_entry} to {res.gitignore_path}", file=sys.stderr)
234
+ for notice in res.notices:
235
+ print(f" note: {notice}", file=sys.stderr)
236
+ return 0
237
+
238
+
239
+ def _handle_build(args: argparse.Namespace) -> int:
240
+ try:
241
+ cfg = _load_cli_config(
242
+ args.path,
243
+ config_file=args.config,
244
+ mode=args.mode,
245
+ out_dir=args.out,
246
+ )
247
+ if not args.quiet:
248
+ for warn in cfg.warnings:
249
+ print(f"warning: {warn}", file=sys.stderr)
250
+ result = run_pipeline(cfg, drafts=args.drafts, write=True)
251
+ except (ConfigError, OSError) as exc:
252
+ print(f"md2site build: {exc}", file=sys.stderr)
253
+ return 2
254
+
255
+ if args.json_output:
256
+ print(
257
+ to_json(
258
+ result.diagnostics,
259
+ pages=len(result.site.pages),
260
+ duration_ms=result.duration_ms,
261
+ ),
262
+ file=sys.stdout,
263
+ )
264
+ elif not args.quiet:
265
+ _print_grouped_diagnostics(result.diagnostics)
266
+ err_cnt = sum(1 for d in result.diagnostics if d.level == "error")
267
+ warn_cnt = sum(1 for d in result.diagnostics if d.level == "warning")
268
+ print(
269
+ f"Built {len(result.site.pages)} pages "
270
+ f"({len(result.written_files)} written, {result.skipped_count} unchanged, "
271
+ f"{len(result.removed_files)} removed) in {result.duration_ms} ms "
272
+ f"[{err_cnt} errors, {warn_cnt} warnings]",
273
+ file=sys.stderr,
274
+ )
275
+
276
+ has_errors = any(d.level == "error" for d in result.diagnostics)
277
+ if has_errors or (args.strict and result.diagnostics):
278
+ return 1
279
+ return 0
280
+
281
+
282
+ def _handle_check(args: argparse.Namespace) -> int:
283
+ try:
284
+ cfg = _load_cli_config(args.path, config_file=args.config)
285
+ if not args.json_output:
286
+ for warn in cfg.warnings:
287
+ print(f"warning: {warn}", file=sys.stderr)
288
+ result = run_pipeline(cfg, drafts=False, write=False)
289
+ except (ConfigError, OSError) as exc:
290
+ print(f"md2site check: {exc}", file=sys.stderr)
291
+ return 2
292
+
293
+ if args.json_output:
294
+ print(
295
+ to_json(
296
+ result.diagnostics,
297
+ pages=len(result.site.pages),
298
+ duration_ms=result.duration_ms,
299
+ ),
300
+ file=sys.stdout,
301
+ )
302
+ else:
303
+ _print_grouped_diagnostics(result.diagnostics)
304
+ err_cnt = sum(1 for d in result.diagnostics if d.level == "error")
305
+ warn_cnt = sum(1 for d in result.diagnostics if d.level == "warning")
306
+ print(
307
+ f"Checked {len(result.site.pages)} pages in {result.duration_ms} ms "
308
+ f"[{err_cnt} errors, {warn_cnt} warnings]",
309
+ file=sys.stderr,
310
+ )
311
+
312
+ return 1 if result.diagnostics else 0
313
+
314
+
315
+ def _handle_watch(args: argparse.Namespace) -> int:
316
+ try:
317
+ cfg = _load_cli_config(args.path, config_file=args.config)
318
+ for warn in cfg.warnings:
319
+ print(f"warning: {warn}", file=sys.stderr)
320
+ return watch_and_serve(
321
+ cfg,
322
+ path_arg=args.path,
323
+ config_file=args.config,
324
+ host=args.host,
325
+ port=args.port,
326
+ open_browser=args.open_browser,
327
+ emit_msg=lambda msg: print(msg, file=sys.stderr),
328
+ )
329
+ except (ConfigError, OSError) as exc:
330
+ print(f"md2site watch: {exc}", file=sys.stderr)
331
+ return 2
332
+
333
+
334
+ def main(argv: list[str] | None = None) -> int:
335
+ """CLI entry point returning a process exit code."""
336
+ parser = build_parser()
337
+ args = parser.parse_args(argv)
338
+
339
+ if args.command == "init":
340
+ return _handle_init(args)
341
+ if args.command == "build":
342
+ return _handle_build(args)
343
+ if args.command == "check":
344
+ return _handle_check(args)
345
+ if args.command == "watch":
346
+ return _handle_watch(args)
347
+ if args.command == "hook":
348
+ rc, err_msg = run_hook()
349
+ if err_msg:
350
+ print(err_msg, file=sys.stderr)
351
+ return rc
352
+
353
+ print(f"md2site {args.command}: not implemented yet", file=sys.stderr)
354
+ return 2