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/__init__.py +7 -0
- md2site/__main__.py +10 -0
- md2site/assets.py +211 -0
- md2site/build.py +152 -0
- md2site/cli.py +354 -0
- md2site/config.py +444 -0
- md2site/diagnostics.py +167 -0
- md2site/frontmatter.py +245 -0
- md2site/hook.py +129 -0
- md2site/init_cmd.py +153 -0
- md2site/links.py +1403 -0
- md2site/markdown.py +408 -0
- md2site/model.py +80 -0
- md2site/nav.py +286 -0
- md2site/paths.py +130 -0
- md2site/render.py +306 -0
- md2site/scanner.py +273 -0
- md2site/search.py +96 -0
- md2site/server.py +267 -0
- md2site/skill/SKILL.md +50 -0
- md2site/slug.py +40 -0
- md2site/static/css/md2site.css +974 -0
- md2site/static/js/app.js +301 -0
- md2site/static/js/mermaid-init.js +93 -0
- md2site/static/js/search.js +577 -0
- md2site/static/js/theme-init.js +24 -0
- md2site/static/vendor/mermaid.min.js +4329 -0
- md2site/templates/base.html +82 -0
- md2site/templates/landing.html +30 -0
- md2site/templates/page.html +13 -0
- md2site/templates/partials/breadcrumbs.html +15 -0
- md2site/templates/partials/nav.html +37 -0
- md2site/templates/partials/prevnext.html +20 -0
- md2site/templates/partials/toc.html +14 -0
- md2site/titles.py +96 -0
- md2site/watcher.py +447 -0
- md2site/wikilinks.py +314 -0
- md2site_cli-0.2.0.dist-info/METADATA +280 -0
- md2site_cli-0.2.0.dist-info/RECORD +43 -0
- md2site_cli-0.2.0.dist-info/WHEEL +4 -0
- md2site_cli-0.2.0.dist-info/entry_points.txt +3 -0
- md2site_cli-0.2.0.dist-info/licenses/LICENSE +21 -0
- md2site_cli-0.2.0.dist-info/licenses/THIRD_PARTY_LICENSES.md +36 -0
md2site/frontmatter.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""Minimal YAML-subset front matter parser for md2site."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
_KEY_VALUE_RE = re.compile(r"^([A-Za-z0-9_-]+):(?:[ \t]+(.*)|[ \t]*)$")
|
|
9
|
+
_INT_RE = re.compile(r"^-?\d+$")
|
|
10
|
+
_FLOAT_RE = re.compile(r"^-?\d+\.\d+$")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _parse_scalar(raw: str) -> tuple[Any, str | None]:
|
|
14
|
+
"""Parse a single YAML scalar token (quoted string, bool, number, or string)."""
|
|
15
|
+
val = raw.strip()
|
|
16
|
+
if not val:
|
|
17
|
+
return "", None
|
|
18
|
+
|
|
19
|
+
if val[0] in ('"', "'"):
|
|
20
|
+
quote_char = val[0]
|
|
21
|
+
if len(val) < 2 or val[-1] != quote_char:
|
|
22
|
+
return None, f"Unterminated quoted string: {raw}"
|
|
23
|
+
inner = val[1:-1]
|
|
24
|
+
if quote_char == '"':
|
|
25
|
+
try:
|
|
26
|
+
unescaped = _unescape_double_quoted(inner)
|
|
27
|
+
except ValueError as exc:
|
|
28
|
+
return None, str(exc)
|
|
29
|
+
return unescaped, None
|
|
30
|
+
return inner.replace("''", "'"), None
|
|
31
|
+
|
|
32
|
+
if val.startswith(("{", "&", "*", "!", "|", ">")):
|
|
33
|
+
return None, f"Unsupported YAML construct: {val}"
|
|
34
|
+
|
|
35
|
+
lower = val.lower()
|
|
36
|
+
if lower == "true":
|
|
37
|
+
return True, None
|
|
38
|
+
if lower == "false":
|
|
39
|
+
return False, None
|
|
40
|
+
if lower in ("null", "~"):
|
|
41
|
+
return None, None
|
|
42
|
+
|
|
43
|
+
if _INT_RE.match(val):
|
|
44
|
+
return int(val), None
|
|
45
|
+
if _FLOAT_RE.match(val):
|
|
46
|
+
return float(val), None
|
|
47
|
+
|
|
48
|
+
if '"' in val or "'" in val:
|
|
49
|
+
return None, f"Unexpected quote in unquoted scalar: {val}"
|
|
50
|
+
|
|
51
|
+
return val, None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _unescape_double_quoted(text: str) -> str:
|
|
55
|
+
"""Process basic YAML double-quoted escape sequences."""
|
|
56
|
+
out: list[str] = []
|
|
57
|
+
i = 0
|
|
58
|
+
n = len(text)
|
|
59
|
+
while i < n:
|
|
60
|
+
ch = text[i]
|
|
61
|
+
if ch != "\\":
|
|
62
|
+
out.append(ch)
|
|
63
|
+
i += 1
|
|
64
|
+
continue
|
|
65
|
+
if i + 1 >= n:
|
|
66
|
+
raise ValueError("Trailing backslash in double-quoted string")
|
|
67
|
+
nxt = text[i + 1]
|
|
68
|
+
escapes = {
|
|
69
|
+
'"': '"',
|
|
70
|
+
"\\": "\\",
|
|
71
|
+
"n": "\n",
|
|
72
|
+
"t": "\t",
|
|
73
|
+
"r": "\r",
|
|
74
|
+
"/": "/",
|
|
75
|
+
}
|
|
76
|
+
if nxt not in escapes:
|
|
77
|
+
raise ValueError(f"Unsupported escape sequence '\\{nxt}' in quoted string")
|
|
78
|
+
out.append(escapes[nxt])
|
|
79
|
+
i += 2
|
|
80
|
+
return "".join(out)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _parse_inline_list(raw: str) -> tuple[list[Any] | None, str | None]:
|
|
84
|
+
"""Parse a YAML inline list such as ``[a, "b, c", 1]``."""
|
|
85
|
+
stripped = raw.strip()
|
|
86
|
+
if not stripped.startswith("[") or not stripped.endswith("]"):
|
|
87
|
+
return None, f"Malformed inline list: {raw}"
|
|
88
|
+
inner = stripped[1:-1].strip()
|
|
89
|
+
if not inner:
|
|
90
|
+
return [], None
|
|
91
|
+
|
|
92
|
+
items: list[str] = []
|
|
93
|
+
buf: list[str] = []
|
|
94
|
+
quote_char: str | None = None
|
|
95
|
+
escaped = False
|
|
96
|
+
|
|
97
|
+
for ch in inner:
|
|
98
|
+
if escaped:
|
|
99
|
+
buf.append(ch)
|
|
100
|
+
escaped = False
|
|
101
|
+
continue
|
|
102
|
+
if quote_char == '"' and ch == "\\":
|
|
103
|
+
buf.append(ch)
|
|
104
|
+
escaped = True
|
|
105
|
+
continue
|
|
106
|
+
if quote_char is not None:
|
|
107
|
+
buf.append(ch)
|
|
108
|
+
if ch == quote_char:
|
|
109
|
+
quote_char = None
|
|
110
|
+
continue
|
|
111
|
+
if ch in ('"', "'"):
|
|
112
|
+
quote_char = ch
|
|
113
|
+
buf.append(ch)
|
|
114
|
+
continue
|
|
115
|
+
if ch in ("[", "{"):
|
|
116
|
+
return None, f"Nested collections are not supported in inline list: {raw}"
|
|
117
|
+
if ch == ",":
|
|
118
|
+
items.append("".join(buf).strip())
|
|
119
|
+
buf.clear()
|
|
120
|
+
continue
|
|
121
|
+
buf.append(ch)
|
|
122
|
+
|
|
123
|
+
if quote_char is not None:
|
|
124
|
+
return None, f"Unterminated quote in inline list: {raw}"
|
|
125
|
+
|
|
126
|
+
last = "".join(buf).strip()
|
|
127
|
+
if not last:
|
|
128
|
+
return None, f"Trailing comma in inline list: {raw}"
|
|
129
|
+
items.append(last)
|
|
130
|
+
|
|
131
|
+
parsed: list[Any] = []
|
|
132
|
+
for item in items:
|
|
133
|
+
if not item:
|
|
134
|
+
return None, f"Empty item in inline list: {raw}"
|
|
135
|
+
val, err = _parse_scalar(item)
|
|
136
|
+
if err is not None:
|
|
137
|
+
return None, err
|
|
138
|
+
parsed.append(val)
|
|
139
|
+
return parsed, None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def split_front_matter(text: str) -> tuple[dict[str, Any], str, int, str | None]:
|
|
143
|
+
"""Split optional YAML-subset front matter from a Markdown document.
|
|
144
|
+
|
|
145
|
+
Returns ``(meta, body, body_line_offset, error)``. Tolerates UTF-8 BOM and
|
|
146
|
+
CRLF line endings. On malformed front matter, returns empty ``meta`` and
|
|
147
|
+
an ``error`` message without raising.
|
|
148
|
+
"""
|
|
149
|
+
cleaned = text.lstrip("\ufeff").replace("\r\n", "\n").replace("\r", "\n")
|
|
150
|
+
lines = cleaned.split("\n")
|
|
151
|
+
if not lines or lines[0].rstrip(" \t") != "---":
|
|
152
|
+
return {}, cleaned, 0, None
|
|
153
|
+
|
|
154
|
+
close_idx: int | None = None
|
|
155
|
+
for idx in range(1, len(lines)):
|
|
156
|
+
if lines[idx].rstrip(" \t") in ("---", "..."):
|
|
157
|
+
close_idx = idx
|
|
158
|
+
break
|
|
159
|
+
|
|
160
|
+
if close_idx is None:
|
|
161
|
+
return {}, cleaned, 0, "Unterminated front matter block (missing closing '---')"
|
|
162
|
+
|
|
163
|
+
body = "\n".join(lines[close_idx + 1 :])
|
|
164
|
+
body_line_offset = close_idx + 1
|
|
165
|
+
|
|
166
|
+
meta: dict[str, Any] = {}
|
|
167
|
+
current_list_key: str | None = None
|
|
168
|
+
|
|
169
|
+
for line_idx in range(1, close_idx):
|
|
170
|
+
raw_line = lines[line_idx]
|
|
171
|
+
stripped = raw_line.strip()
|
|
172
|
+
if not stripped or stripped.startswith("#"):
|
|
173
|
+
continue
|
|
174
|
+
|
|
175
|
+
if stripped.startswith("- ") or stripped == "-":
|
|
176
|
+
if current_list_key is None:
|
|
177
|
+
return (
|
|
178
|
+
{},
|
|
179
|
+
body,
|
|
180
|
+
body_line_offset,
|
|
181
|
+
f"Unexpected list item at front matter line {line_idx + 1}",
|
|
182
|
+
)
|
|
183
|
+
item_raw = stripped[1:].strip()
|
|
184
|
+
if not item_raw:
|
|
185
|
+
return (
|
|
186
|
+
{},
|
|
187
|
+
body,
|
|
188
|
+
body_line_offset,
|
|
189
|
+
f"Empty list item at front matter line {line_idx + 1}",
|
|
190
|
+
)
|
|
191
|
+
item_val, err = _parse_scalar(item_raw)
|
|
192
|
+
if err is not None:
|
|
193
|
+
return {}, body, body_line_offset, f"Front matter line {line_idx + 1}: {err}"
|
|
194
|
+
existing = meta[current_list_key]
|
|
195
|
+
if existing is None:
|
|
196
|
+
meta[current_list_key] = [item_val]
|
|
197
|
+
elif isinstance(existing, list):
|
|
198
|
+
existing.append(item_val)
|
|
199
|
+
else:
|
|
200
|
+
return (
|
|
201
|
+
{},
|
|
202
|
+
body,
|
|
203
|
+
body_line_offset,
|
|
204
|
+
f"Invalid list item under non-list key '{current_list_key}' "
|
|
205
|
+
f"at line {line_idx + 1}",
|
|
206
|
+
)
|
|
207
|
+
continue
|
|
208
|
+
|
|
209
|
+
if raw_line[0] in (" ", "\t"):
|
|
210
|
+
return (
|
|
211
|
+
{},
|
|
212
|
+
body,
|
|
213
|
+
body_line_offset,
|
|
214
|
+
f"Unsupported indented syntax at front matter line {line_idx + 1}",
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
match = _KEY_VALUE_RE.match(raw_line)
|
|
218
|
+
if not match:
|
|
219
|
+
return (
|
|
220
|
+
{},
|
|
221
|
+
body,
|
|
222
|
+
body_line_offset,
|
|
223
|
+
f"Invalid front matter syntax at line {line_idx + 1}: {raw_line}",
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
key, val_raw = match.group(1), match.group(2)
|
|
227
|
+
if val_raw is None or not val_raw.strip():
|
|
228
|
+
meta[key] = None
|
|
229
|
+
current_list_key = key
|
|
230
|
+
continue
|
|
231
|
+
|
|
232
|
+
current_list_key = None
|
|
233
|
+
val_stripped = val_raw.strip()
|
|
234
|
+
if val_stripped.startswith("["):
|
|
235
|
+
parsed_list, err = _parse_inline_list(val_stripped)
|
|
236
|
+
if err is not None:
|
|
237
|
+
return {}, body, body_line_offset, f"Front matter line {line_idx + 1}: {err}"
|
|
238
|
+
meta[key] = parsed_list
|
|
239
|
+
else:
|
|
240
|
+
parsed_val, err = _parse_scalar(val_stripped)
|
|
241
|
+
if err is not None:
|
|
242
|
+
return {}, body, body_line_offset, f"Front matter line {line_idx + 1}: {err}"
|
|
243
|
+
meta[key] = parsed_val
|
|
244
|
+
|
|
245
|
+
return meta, body, body_line_offset, None
|
md2site/hook.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Agent post-edit hook handler for ``md2site hook``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from md2site.build import run_pipeline
|
|
10
|
+
from md2site.config import Config, ConfigError, load_config
|
|
11
|
+
from md2site.diagnostics import format_diagnostics
|
|
12
|
+
|
|
13
|
+
_MD_EXTENSIONS = frozenset({".md", ".markdown"})
|
|
14
|
+
_DEFAULT_DOC_DIR_NAMES = frozenset({"docs", "doc", "documentation"})
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _extract_file_path(payload: object) -> str | None:
|
|
18
|
+
if not isinstance(payload, dict):
|
|
19
|
+
return None
|
|
20
|
+
tool_input = payload.get("tool_input")
|
|
21
|
+
if isinstance(tool_input, dict):
|
|
22
|
+
fp = tool_input.get("file_path")
|
|
23
|
+
if isinstance(fp, str) and fp.strip():
|
|
24
|
+
return fp.strip()
|
|
25
|
+
for key in ("file_path", "path"):
|
|
26
|
+
val = payload.get(key)
|
|
27
|
+
if isinstance(val, str) and val.strip():
|
|
28
|
+
return val.strip()
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _is_within(path: Path, root: Path) -> bool:
|
|
33
|
+
try:
|
|
34
|
+
path.relative_to(root)
|
|
35
|
+
return True
|
|
36
|
+
except ValueError:
|
|
37
|
+
return False
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _discover_config_for_file(file_path: Path) -> Config | None:
|
|
41
|
+
"""Find an explicit or implied md2site config covering ``file_path``."""
|
|
42
|
+
resolved = file_path.resolve()
|
|
43
|
+
parent = resolved.parent
|
|
44
|
+
ancestors = [parent, *parent.parents]
|
|
45
|
+
|
|
46
|
+
# Stop upward search at git root if inside a git repository.
|
|
47
|
+
bounded: list[Path] = []
|
|
48
|
+
for anc in ancestors:
|
|
49
|
+
bounded.append(anc)
|
|
50
|
+
if (anc / ".git").exists():
|
|
51
|
+
break
|
|
52
|
+
|
|
53
|
+
# 1. Explicit md2site.config.json in an ancestor directory
|
|
54
|
+
for anc in bounded:
|
|
55
|
+
cfg_file = anc / "md2site.config.json"
|
|
56
|
+
if cfg_file.is_file():
|
|
57
|
+
cfg = load_config(anc, config_file=cfg_file)
|
|
58
|
+
docs_res = cfg.docs_dir.resolve()
|
|
59
|
+
out_res = cfg.output_dir.resolve()
|
|
60
|
+
if _is_within(resolved, docs_res) and not _is_within(resolved, out_res):
|
|
61
|
+
return cfg
|
|
62
|
+
return None
|
|
63
|
+
|
|
64
|
+
# 2. Zero-config implied docs/ directory inside repo/ancestors
|
|
65
|
+
for anc in bounded:
|
|
66
|
+
if anc.name.lower() in _DEFAULT_DOC_DIR_NAMES:
|
|
67
|
+
cfg = load_config(anc)
|
|
68
|
+
out_res = cfg.output_dir.resolve()
|
|
69
|
+
if _is_within(resolved, anc.resolve()) and not _is_within(resolved, out_res):
|
|
70
|
+
return cfg
|
|
71
|
+
return None
|
|
72
|
+
|
|
73
|
+
return None
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def run_hook(
|
|
77
|
+
stdin_text: str | None = None,
|
|
78
|
+
*,
|
|
79
|
+
cwd: Path | None = None,
|
|
80
|
+
) -> tuple[int, str]:
|
|
81
|
+
"""Process an agent post-edit JSON hook payload.
|
|
82
|
+
|
|
83
|
+
Returns ``(exit_code, stderr_message)``. Exits ``0`` silently for non-Markdown
|
|
84
|
+
files, malformed payloads, or files outside an md2site project. Runs check
|
|
85
|
+
and quiet build for matching Markdown files, returning ``2`` with compact
|
|
86
|
+
diagnostics on stderr when diagnostics are present.
|
|
87
|
+
"""
|
|
88
|
+
raw = sys.stdin.read() if stdin_text is None else stdin_text
|
|
89
|
+
if not raw.strip():
|
|
90
|
+
return 0, ""
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
payload = json.loads(raw)
|
|
94
|
+
except json.JSONDecodeError:
|
|
95
|
+
return 0, ""
|
|
96
|
+
|
|
97
|
+
raw_path = _extract_file_path(payload)
|
|
98
|
+
if raw_path is None:
|
|
99
|
+
return 0, ""
|
|
100
|
+
|
|
101
|
+
candidate = Path(raw_path)
|
|
102
|
+
if candidate.suffix.lower() not in _MD_EXTENSIONS:
|
|
103
|
+
return 0, ""
|
|
104
|
+
|
|
105
|
+
base_cwd = cwd
|
|
106
|
+
if base_cwd is None and isinstance(payload, dict):
|
|
107
|
+
payload_cwd = payload.get("cwd")
|
|
108
|
+
if isinstance(payload_cwd, str) and payload_cwd.strip():
|
|
109
|
+
cwd_path = Path(payload_cwd)
|
|
110
|
+
if cwd_path.is_dir():
|
|
111
|
+
base_cwd = cwd_path
|
|
112
|
+
if base_cwd is None:
|
|
113
|
+
base_cwd = Path.cwd()
|
|
114
|
+
|
|
115
|
+
resolved_file = (candidate if candidate.is_absolute() else base_cwd / candidate).resolve()
|
|
116
|
+
if not resolved_file.is_file():
|
|
117
|
+
return 0, ""
|
|
118
|
+
|
|
119
|
+
try:
|
|
120
|
+
cfg = _discover_config_for_file(resolved_file)
|
|
121
|
+
if cfg is None:
|
|
122
|
+
return 0, ""
|
|
123
|
+
result = run_pipeline(cfg, drafts=False, write=True)
|
|
124
|
+
except (ConfigError, OSError):
|
|
125
|
+
return 0, ""
|
|
126
|
+
|
|
127
|
+
if result.diagnostics:
|
|
128
|
+
return 2, format_diagnostics(result.diagnostics)
|
|
129
|
+
return 0, ""
|
md2site/init_cmd.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
"""Implementation of the ``md2site init`` command."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import importlib.resources
|
|
6
|
+
import json
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from md2site.config import default_config_dict
|
|
11
|
+
|
|
12
|
+
_CUSTOM_CSS_STUB = """\
|
|
13
|
+
/* Custom styles for md2site (loaded after built-in styles).
|
|
14
|
+
* Example: override the light/dark accent color:
|
|
15
|
+
*
|
|
16
|
+
* :root {
|
|
17
|
+
* --accent: #0ea5e9;
|
|
18
|
+
* }
|
|
19
|
+
* [data-theme="dark"] {
|
|
20
|
+
* --accent: #38bdf8;
|
|
21
|
+
* }
|
|
22
|
+
*/
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class InitError(RuntimeError):
|
|
27
|
+
"""Raised when ``md2site init`` cannot proceed safely."""
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class InitResult:
|
|
32
|
+
"""Summary of files created and notices from ``md2site init``."""
|
|
33
|
+
|
|
34
|
+
target_dir: Path
|
|
35
|
+
config_path: Path
|
|
36
|
+
custom_css_path: Path
|
|
37
|
+
output_dir: Path
|
|
38
|
+
gitignore_path: Path | None
|
|
39
|
+
gitignore_entry: str | None
|
|
40
|
+
gitignore_updated: bool
|
|
41
|
+
notices: tuple[str, ...]
|
|
42
|
+
skill_path: Path | None = None
|
|
43
|
+
skill_written: bool = False
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _find_git_root(start: Path) -> Path | None:
|
|
47
|
+
resolved = start.resolve()
|
|
48
|
+
for candidate in (resolved, *resolved.parents):
|
|
49
|
+
if (candidate / ".git").exists():
|
|
50
|
+
return candidate
|
|
51
|
+
return None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _read_packaged_skill() -> bytes:
|
|
55
|
+
skill_ref = importlib.resources.files("md2site").joinpath("skill", "SKILL.md")
|
|
56
|
+
return skill_ref.read_bytes()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def run_init(
|
|
60
|
+
path: Path | str = ".",
|
|
61
|
+
*,
|
|
62
|
+
force: bool = False,
|
|
63
|
+
with_skill: bool = False,
|
|
64
|
+
) -> InitResult:
|
|
65
|
+
"""Initialize md2site config, custom.css stub, output dir, .gitignore, and optional skill."""
|
|
66
|
+
target = Path(path)
|
|
67
|
+
if target.exists() and not target.is_dir():
|
|
68
|
+
raise InitError(f"Target path is not a directory: {target}")
|
|
69
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
70
|
+
target_dir = target.resolve()
|
|
71
|
+
|
|
72
|
+
config_path = target_dir / "md2site.config.json"
|
|
73
|
+
custom_css_path = target_dir / "custom.css"
|
|
74
|
+
output_dir = target_dir / "_site"
|
|
75
|
+
|
|
76
|
+
if not force:
|
|
77
|
+
existing = [p for p in (config_path, custom_css_path) if p.exists()]
|
|
78
|
+
if existing:
|
|
79
|
+
names = ", ".join(p.name for p in existing)
|
|
80
|
+
raise InitError(f"Refusing to overwrite existing file(s) ({names}); pass --force")
|
|
81
|
+
|
|
82
|
+
git_root = _find_git_root(target_dir)
|
|
83
|
+
notices: list[str] = []
|
|
84
|
+
|
|
85
|
+
skill_path: Path | None = None
|
|
86
|
+
skill_written = False
|
|
87
|
+
skill_bytes: bytes | None = None
|
|
88
|
+
if with_skill:
|
|
89
|
+
skill_bytes = _read_packaged_skill()
|
|
90
|
+
skill_base = git_root if git_root is not None else target_dir
|
|
91
|
+
skill_path = skill_base / ".claude" / "skills" / "md2site" / "SKILL.md"
|
|
92
|
+
if skill_path.exists() and not force:
|
|
93
|
+
try:
|
|
94
|
+
if skill_path.read_bytes() != skill_bytes:
|
|
95
|
+
raise InitError(
|
|
96
|
+
f"Refusing to overwrite modified skill file ({skill_path}); pass --force"
|
|
97
|
+
)
|
|
98
|
+
except OSError as exc:
|
|
99
|
+
raise InitError(f"Unable to read existing skill file {skill_path}: {exc}") from exc
|
|
100
|
+
|
|
101
|
+
config_payload = json.dumps(default_config_dict(), indent=2) + "\n"
|
|
102
|
+
config_path.write_text(config_payload, encoding="utf-8")
|
|
103
|
+
custom_css_path.write_text(_CUSTOM_CSS_STUB, encoding="utf-8")
|
|
104
|
+
output_dir.mkdir(parents=True, exist_ok=True)
|
|
105
|
+
|
|
106
|
+
if with_skill and skill_path is not None and skill_bytes is not None:
|
|
107
|
+
if skill_path.exists() and not force:
|
|
108
|
+
notices.append(f"SKILL.md already up to date at {skill_path}")
|
|
109
|
+
else:
|
|
110
|
+
skill_path.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
if not skill_path.exists() or skill_path.read_bytes() != skill_bytes:
|
|
112
|
+
skill_path.write_bytes(skill_bytes)
|
|
113
|
+
skill_written = True
|
|
114
|
+
else:
|
|
115
|
+
notices.append(f"SKILL.md already up to date at {skill_path}")
|
|
116
|
+
if git_root is None:
|
|
117
|
+
notices.append("Outside a git repository; installed SKILL.md under target directory.")
|
|
118
|
+
|
|
119
|
+
gitignore_path: Path | None = None
|
|
120
|
+
gitignore_entry: str | None = None
|
|
121
|
+
gitignore_updated = False
|
|
122
|
+
|
|
123
|
+
if git_root is None:
|
|
124
|
+
notices.append("Outside a git repository; skipped .gitignore update.")
|
|
125
|
+
else:
|
|
126
|
+
gitignore_path = git_root / ".gitignore"
|
|
127
|
+
rel_out = output_dir.relative_to(git_root).as_posix().rstrip("/")
|
|
128
|
+
gitignore_entry = f"{rel_out}/"
|
|
129
|
+
existing_lines: list[str] = []
|
|
130
|
+
raw_gi = ""
|
|
131
|
+
if gitignore_path.is_file():
|
|
132
|
+
raw_gi = gitignore_path.read_text(encoding="utf-8")
|
|
133
|
+
existing_lines = [line.strip() for line in raw_gi.splitlines()]
|
|
134
|
+
|
|
135
|
+
if gitignore_entry in existing_lines or rel_out in existing_lines:
|
|
136
|
+
notices.append(f"{gitignore_entry} already present in {gitignore_path}")
|
|
137
|
+
else:
|
|
138
|
+
prefix = "" if (not raw_gi or raw_gi.endswith("\n")) else "\n"
|
|
139
|
+
gitignore_path.write_text(f"{raw_gi}{prefix}{gitignore_entry}\n", encoding="utf-8")
|
|
140
|
+
gitignore_updated = True
|
|
141
|
+
|
|
142
|
+
return InitResult(
|
|
143
|
+
target_dir=target_dir,
|
|
144
|
+
config_path=config_path,
|
|
145
|
+
custom_css_path=custom_css_path,
|
|
146
|
+
output_dir=output_dir,
|
|
147
|
+
gitignore_path=gitignore_path,
|
|
148
|
+
gitignore_entry=gitignore_entry,
|
|
149
|
+
gitignore_updated=gitignore_updated,
|
|
150
|
+
notices=tuple(notices),
|
|
151
|
+
skill_path=skill_path,
|
|
152
|
+
skill_written=skill_written,
|
|
153
|
+
)
|