mdsite-cli 0.1.1__tar.gz
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.
- mdsite_cli-0.1.1/.gitignore +9 -0
- mdsite_cli-0.1.1/LICENSE +21 -0
- mdsite_cli-0.1.1/PKG-INFO +84 -0
- mdsite_cli-0.1.1/README.md +60 -0
- mdsite_cli-0.1.1/pyproject.toml +52 -0
- mdsite_cli-0.1.1/src/mdsite_cli/__init__.py +3 -0
- mdsite_cli-0.1.1/src/mdsite_cli/__main__.py +5 -0
- mdsite_cli-0.1.1/src/mdsite_cli/assets/main.html +18 -0
- mdsite_cli-0.1.1/src/mdsite_cli/cli.py +369 -0
- mdsite_cli-0.1.1/tests/test_cli.py +168 -0
- mdsite_cli-0.1.1/uv.lock +423 -0
mdsite_cli-0.1.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 int2t05
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mdsite-cli
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Preview and build websites directly from Markdown directories
|
|
5
|
+
Project-URL: Homepage, https://github.com/int2t05/mdsite-cli
|
|
6
|
+
Project-URL: Issues, https://github.com/int2t05/mdsite-cli/issues
|
|
7
|
+
Project-URL: Source, https://github.com/int2t05/mdsite-cli
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: cli,documentation,markdown,zensical
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Documentation
|
|
21
|
+
Requires-Python: >=3.11
|
|
22
|
+
Requires-Dist: zensical==0.1.2
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# mdsite-cli
|
|
26
|
+
|
|
27
|
+
[](https://github.com/int2t05/mdsite-cli/actions/workflows/ci.yml)
|
|
28
|
+
[](https://pypi.org/project/mdsite-cli/)
|
|
29
|
+
[](LICENSE)
|
|
30
|
+
|
|
31
|
+
Preview and build a browsable website directly from a Markdown directory. The source files are read through a temporary directory link and are never copied or rewritten.
|
|
32
|
+
|
|
33
|
+
## Quick start
|
|
34
|
+
|
|
35
|
+
Run this from the Markdown root:
|
|
36
|
+
|
|
37
|
+
~~~powershell
|
|
38
|
+
uvx --from mdsite-cli mdsite
|
|
39
|
+
~~~
|
|
40
|
+
|
|
41
|
+
To run the latest GitHub version directly:
|
|
42
|
+
|
|
43
|
+
~~~powershell
|
|
44
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite
|
|
45
|
+
~~~
|
|
46
|
+
|
|
47
|
+
Preview opens at `http://127.0.0.1:8000`. Stop it with `Ctrl+C`.
|
|
48
|
+
|
|
49
|
+
Preview another directory or use a different port:
|
|
50
|
+
|
|
51
|
+
~~~powershell
|
|
52
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite --path "D:\notes"
|
|
53
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite serve --port 8080
|
|
54
|
+
~~~
|
|
55
|
+
|
|
56
|
+
Build a static site into `site/` under the Markdown root:
|
|
57
|
+
|
|
58
|
+
~~~powershell
|
|
59
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite build
|
|
60
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite build --path "D:\notes" --output "D:\published-notes"
|
|
61
|
+
~~~
|
|
62
|
+
|
|
63
|
+
`build` refuses to replace an existing directory unless its ownership marker matches both the source and output paths. Custom output directories must be outside the Markdown root.
|
|
64
|
+
|
|
65
|
+
## Features and limits
|
|
66
|
+
|
|
67
|
+
- Reads the folder tree directly; the source directory is not rewritten.
|
|
68
|
+
- Supports Markdown, Mermaid diagrams, and MathJax formulas.
|
|
69
|
+
- Formula rendering loads MathJax from a CDN, so it needs an internet connection.
|
|
70
|
+
- Requires Python 3.11 or newer and uv.
|
|
71
|
+
|
|
72
|
+
## Development
|
|
73
|
+
|
|
74
|
+
~~~powershell
|
|
75
|
+
uv sync --locked --all-groups
|
|
76
|
+
uv run ruff check .
|
|
77
|
+
uv run ruff format --check .
|
|
78
|
+
uv run python -m unittest discover -s tests -v
|
|
79
|
+
uv build
|
|
80
|
+
~~~
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
MIT; see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# mdsite-cli
|
|
2
|
+
|
|
3
|
+
[](https://github.com/int2t05/mdsite-cli/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/mdsite-cli/)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
Preview and build a browsable website directly from a Markdown directory. The source files are read through a temporary directory link and are never copied or rewritten.
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
Run this from the Markdown root:
|
|
12
|
+
|
|
13
|
+
~~~powershell
|
|
14
|
+
uvx --from mdsite-cli mdsite
|
|
15
|
+
~~~
|
|
16
|
+
|
|
17
|
+
To run the latest GitHub version directly:
|
|
18
|
+
|
|
19
|
+
~~~powershell
|
|
20
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite
|
|
21
|
+
~~~
|
|
22
|
+
|
|
23
|
+
Preview opens at `http://127.0.0.1:8000`. Stop it with `Ctrl+C`.
|
|
24
|
+
|
|
25
|
+
Preview another directory or use a different port:
|
|
26
|
+
|
|
27
|
+
~~~powershell
|
|
28
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite --path "D:\notes"
|
|
29
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite serve --port 8080
|
|
30
|
+
~~~
|
|
31
|
+
|
|
32
|
+
Build a static site into `site/` under the Markdown root:
|
|
33
|
+
|
|
34
|
+
~~~powershell
|
|
35
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite build
|
|
36
|
+
uvx --from git+https://github.com/int2t05/mdsite-cli mdsite build --path "D:\notes" --output "D:\published-notes"
|
|
37
|
+
~~~
|
|
38
|
+
|
|
39
|
+
`build` refuses to replace an existing directory unless its ownership marker matches both the source and output paths. Custom output directories must be outside the Markdown root.
|
|
40
|
+
|
|
41
|
+
## Features and limits
|
|
42
|
+
|
|
43
|
+
- Reads the folder tree directly; the source directory is not rewritten.
|
|
44
|
+
- Supports Markdown, Mermaid diagrams, and MathJax formulas.
|
|
45
|
+
- Formula rendering loads MathJax from a CDN, so it needs an internet connection.
|
|
46
|
+
- Requires Python 3.11 or newer and uv.
|
|
47
|
+
|
|
48
|
+
## Development
|
|
49
|
+
|
|
50
|
+
~~~powershell
|
|
51
|
+
uv sync --locked --all-groups
|
|
52
|
+
uv run ruff check .
|
|
53
|
+
uv run ruff format --check .
|
|
54
|
+
uv run python -m unittest discover -s tests -v
|
|
55
|
+
uv build
|
|
56
|
+
~~~
|
|
57
|
+
|
|
58
|
+
## License
|
|
59
|
+
|
|
60
|
+
MIT; see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "mdsite-cli"
|
|
3
|
+
version = "0.1.1"
|
|
4
|
+
description = "Preview and build websites directly from Markdown directories"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
|
+
dependencies = ["zensical==0.1.2"]
|
|
10
|
+
keywords = ["markdown", "documentation", "zensical", "cli"]
|
|
11
|
+
classifiers = [
|
|
12
|
+
"Development Status :: 4 - Beta",
|
|
13
|
+
"Environment :: Console",
|
|
14
|
+
"License :: OSI Approved :: MIT License",
|
|
15
|
+
"Operating System :: OS Independent",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.11",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Topic :: Documentation",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.urls]
|
|
25
|
+
Homepage = "https://github.com/int2t05/mdsite-cli"
|
|
26
|
+
Issues = "https://github.com/int2t05/mdsite-cli/issues"
|
|
27
|
+
Source = "https://github.com/int2t05/mdsite-cli"
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
mdsite = "mdsite_cli.cli:main"
|
|
31
|
+
|
|
32
|
+
[build-system]
|
|
33
|
+
requires = ["hatchling"]
|
|
34
|
+
build-backend = "hatchling.build"
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.wheel]
|
|
37
|
+
packages = ["src/mdsite_cli"]
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.sdist]
|
|
40
|
+
include = ["src/**", "tests/**", "pyproject.toml", "README.md", "LICENSE", "uv.lock"]
|
|
41
|
+
|
|
42
|
+
[tool.ruff]
|
|
43
|
+
line-length = 100
|
|
44
|
+
target-version = "py311"
|
|
45
|
+
|
|
46
|
+
[tool.ruff.lint]
|
|
47
|
+
select = ["E", "F", "I", "UP"]
|
|
48
|
+
|
|
49
|
+
[dependency-groups]
|
|
50
|
+
dev = [
|
|
51
|
+
"ruff>=0.17.5",
|
|
52
|
+
]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
{% extends "base.html" %}
|
|
2
|
+
{% block scripts %}
|
|
3
|
+
<script>
|
|
4
|
+
window.MathJax = {
|
|
5
|
+
tex: {
|
|
6
|
+
inlineMath: [["\\(", "\\)"]],
|
|
7
|
+
displayMath: [["\\[", "\\]"]],
|
|
8
|
+
processEscapes: true,
|
|
9
|
+
processEnvironments: true
|
|
10
|
+
},
|
|
11
|
+
options: {
|
|
12
|
+
ignoreHtmlClass: ".*|",
|
|
13
|
+
processHtmlClass: "arithmatex"
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
</script>
|
|
17
|
+
{{ super() }}
|
|
18
|
+
{% endblock %}
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""把当前 Markdown 目录临时挂接到 Zensical,提供预览和静态构建。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
import stat
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import tempfile
|
|
14
|
+
import uuid
|
|
15
|
+
from collections.abc import Iterator
|
|
16
|
+
from contextlib import contextmanager
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from urllib.parse import quote
|
|
19
|
+
|
|
20
|
+
_MARKER_NAME = ".mdsite-generated"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MdsiteError(RuntimeError):
|
|
24
|
+
"""命令执行时可直接展示给用户的错误。"""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _toml_string(value: str) -> str:
|
|
28
|
+
"""用 TOML 基础字符串表示路径和标题。"""
|
|
29
|
+
return json.dumps(value, ensure_ascii=False)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _source_path(value: Path | None) -> Path:
|
|
33
|
+
"""解析并校验 Markdown 根目录。"""
|
|
34
|
+
candidate = value if value is not None else Path.cwd()
|
|
35
|
+
try:
|
|
36
|
+
source = candidate.expanduser().resolve(strict=True)
|
|
37
|
+
except (OSError, RuntimeError) as exc:
|
|
38
|
+
raise MdsiteError(f"目录不存在或无法访问:{candidate}") from exc
|
|
39
|
+
if not source.is_dir():
|
|
40
|
+
raise MdsiteError(f"指定路径不是目录:{source}")
|
|
41
|
+
return source
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _create_directory_link(link_path: Path, target_path: Path) -> None:
|
|
45
|
+
"""在临时项目中创建指向原目录的链接。"""
|
|
46
|
+
if os.name != "nt":
|
|
47
|
+
link_path.symlink_to(target_path, target_is_directory=True)
|
|
48
|
+
return
|
|
49
|
+
|
|
50
|
+
powershell = shutil.which("powershell.exe") or shutil.which("pwsh.exe")
|
|
51
|
+
if powershell is None:
|
|
52
|
+
raise MdsiteError("未找到 PowerShell,无法创建 Windows 目录联接。")
|
|
53
|
+
|
|
54
|
+
# 单引号字面量会把路径作为数据传入 PowerShell,避免创建临时脚本。
|
|
55
|
+
link_literal = "'{}'".format(str(link_path).replace("'", "''"))
|
|
56
|
+
target_literal = "'{}'".format(str(target_path).replace("'", "''"))
|
|
57
|
+
command = (
|
|
58
|
+
f"New-Item -ItemType Junction -Path {link_literal} -Target {target_literal} | Out-Null"
|
|
59
|
+
)
|
|
60
|
+
result = subprocess.run(
|
|
61
|
+
[powershell, "-NoProfile", "-NonInteractive", "-Command", command],
|
|
62
|
+
capture_output=True,
|
|
63
|
+
text=True,
|
|
64
|
+
check=False,
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
if result.returncode != 0:
|
|
68
|
+
detail = result.stderr.strip() or result.stdout.strip()
|
|
69
|
+
raise MdsiteError(f"创建目录联接失败:{detail}")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _write_workspace(
|
|
73
|
+
source: Path,
|
|
74
|
+
workspace: Path,
|
|
75
|
+
output_to_exclude: Path | None,
|
|
76
|
+
) -> Path:
|
|
77
|
+
"""生成仅存在于临时目录中的 Zensical 项目。"""
|
|
78
|
+
docs = workspace / "docs"
|
|
79
|
+
docs.mkdir(parents=True)
|
|
80
|
+
_create_directory_link(docs / "source", source)
|
|
81
|
+
|
|
82
|
+
overrides = workspace / "overrides"
|
|
83
|
+
overrides.mkdir()
|
|
84
|
+
bundled_template = Path(__file__).parent / "assets" / "main.html"
|
|
85
|
+
shutil.copyfile(bundled_template, overrides / "main.html")
|
|
86
|
+
|
|
87
|
+
title = source.name or "Markdown"
|
|
88
|
+
intro = [
|
|
89
|
+
f"# {title}",
|
|
90
|
+
"",
|
|
91
|
+
"此站点直接读取原目录中的 Markdown 文件,不会复制或改写源文件。",
|
|
92
|
+
"",
|
|
93
|
+
"请从左侧导航的 **source** 分类浏览文档。",
|
|
94
|
+
]
|
|
95
|
+
readme = source / "README.md"
|
|
96
|
+
if readme.is_file():
|
|
97
|
+
intro.extend(["", f"[打开 README](source/{quote(readme.name)})"])
|
|
98
|
+
(docs / "index.md").write_text("\n".join(intro) + "\n", encoding="utf-8")
|
|
99
|
+
|
|
100
|
+
excluded = ["/**", "!/source/**", "!/index.md"]
|
|
101
|
+
if output_to_exclude is not None:
|
|
102
|
+
relative_output = output_to_exclude.relative_to(source).as_posix()
|
|
103
|
+
excluded.append(f"/source/{relative_output}/**")
|
|
104
|
+
|
|
105
|
+
config = workspace / "zensical.toml"
|
|
106
|
+
config.write_text(
|
|
107
|
+
"\n".join(
|
|
108
|
+
[
|
|
109
|
+
"[project]",
|
|
110
|
+
f"site_name = {_toml_string(title)}",
|
|
111
|
+
'docs_dir = "docs"',
|
|
112
|
+
'site_dir = "site"',
|
|
113
|
+
f"watch = [{_toml_string(str(source))}]",
|
|
114
|
+
"exclude_docs = {}".format(_toml_string("\n".join(excluded))),
|
|
115
|
+
'extra_javascript = ["https://unpkg.com/mathjax@3/es5/tex-mml-chtml.js"]',
|
|
116
|
+
"",
|
|
117
|
+
"[project.theme]",
|
|
118
|
+
'language = "zh"',
|
|
119
|
+
'custom_dir = "overrides"',
|
|
120
|
+
"",
|
|
121
|
+
"[project.markdown_extensions]",
|
|
122
|
+
"pymdownx.arithmatex.generic = true",
|
|
123
|
+
"pymdownx.superfences.custom_fences = [",
|
|
124
|
+
' { name = "mermaid", class = "mermaid", '
|
|
125
|
+
'format = "pymdownx.superfences.fence_code_format" },',
|
|
126
|
+
"]",
|
|
127
|
+
"",
|
|
128
|
+
]
|
|
129
|
+
),
|
|
130
|
+
encoding="utf-8",
|
|
131
|
+
)
|
|
132
|
+
return config
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@contextmanager
|
|
136
|
+
def _project_workspace(
|
|
137
|
+
source: Path,
|
|
138
|
+
output_to_exclude: Path | None = None,
|
|
139
|
+
) -> Iterator[tuple[Path, Path]]:
|
|
140
|
+
"""运行期间保留临时配置;先移除目录联接,再清理临时文件。"""
|
|
141
|
+
workspace = Path(tempfile.mkdtemp(prefix="mdsite-"))
|
|
142
|
+
link_path = workspace / "docs" / "source"
|
|
143
|
+
try:
|
|
144
|
+
config = _write_workspace(source, workspace, output_to_exclude)
|
|
145
|
+
yield workspace, config
|
|
146
|
+
finally:
|
|
147
|
+
if os.path.lexists(link_path):
|
|
148
|
+
try:
|
|
149
|
+
if os.name == "nt":
|
|
150
|
+
# Windows 上 rmdir 删除联接本身,不触碰原目录内容。
|
|
151
|
+
os.rmdir(link_path)
|
|
152
|
+
else:
|
|
153
|
+
link_path.unlink()
|
|
154
|
+
except OSError as exc:
|
|
155
|
+
raise MdsiteError(
|
|
156
|
+
f"无法安全移除临时目录链接;为保护源文件,保留临时目录:{workspace}"
|
|
157
|
+
) from exc
|
|
158
|
+
shutil.rmtree(workspace)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _zensical_command(*arguments: str) -> list[str]:
|
|
162
|
+
"""定位当前 uvx 环境中的 Zensical 命令。"""
|
|
163
|
+
executable = shutil.which("zensical")
|
|
164
|
+
if executable is None:
|
|
165
|
+
raise MdsiteError("找不到 Zensical 命令,请检查 mdsite-cli 的安装环境。")
|
|
166
|
+
return [executable, *arguments]
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _run_preview(source: Path, port: int, open_browser: bool) -> int:
|
|
170
|
+
default_output = source / "site"
|
|
171
|
+
output_to_exclude = default_output if _has_output_marker(default_output, source) else None
|
|
172
|
+
with _project_workspace(source, output_to_exclude) as (workspace, config):
|
|
173
|
+
command = _zensical_command(
|
|
174
|
+
"serve",
|
|
175
|
+
"--config-file",
|
|
176
|
+
str(config),
|
|
177
|
+
"--dev-addr",
|
|
178
|
+
f"127.0.0.1:{port}",
|
|
179
|
+
)
|
|
180
|
+
if open_browser:
|
|
181
|
+
command.append("--open")
|
|
182
|
+
return subprocess.run(command, cwd=workspace, check=False).returncode
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _is_reparse_point(path: Path) -> bool:
|
|
186
|
+
"""识别 Windows 联接点,兼容 Python 3.11。"""
|
|
187
|
+
if os.name != "nt" or not os.path.lexists(path):
|
|
188
|
+
return False
|
|
189
|
+
is_junction = getattr(path, "is_junction", None)
|
|
190
|
+
if is_junction is not None:
|
|
191
|
+
return is_junction()
|
|
192
|
+
try:
|
|
193
|
+
attributes = os.lstat(path).st_file_attributes
|
|
194
|
+
except OSError:
|
|
195
|
+
return False
|
|
196
|
+
flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
|
|
197
|
+
return bool(attributes & flag)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _resolve_output(source: Path, requested: Path | None) -> tuple[Path, Path | None]:
|
|
201
|
+
"""限制输出位置,避免覆盖源目录或把构建结果再次打包。"""
|
|
202
|
+
source = source.resolve(strict=True)
|
|
203
|
+
output = (requested if requested is not None else source / "site").expanduser()
|
|
204
|
+
if not output.is_absolute():
|
|
205
|
+
output = source / output
|
|
206
|
+
output = output.absolute()
|
|
207
|
+
if os.path.lexists(output):
|
|
208
|
+
if output.is_symlink() or _is_reparse_point(output):
|
|
209
|
+
raise MdsiteError(f"输出目录不能是符号链接或目录联接:{output}")
|
|
210
|
+
resolved = output.resolve(strict=False)
|
|
211
|
+
|
|
212
|
+
if resolved == source or source.is_relative_to(resolved):
|
|
213
|
+
raise MdsiteError("输出目录不能等于或包含 Markdown 根目录。")
|
|
214
|
+
|
|
215
|
+
default_output = (source / "site").resolve(strict=False)
|
|
216
|
+
if resolved.is_relative_to(source) and resolved != default_output:
|
|
217
|
+
raise MdsiteError(
|
|
218
|
+
"自定义输出目录请放在 Markdown 根目录之外;默认目录 site/ 可以放在根目录内。"
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
excluded = resolved if resolved == default_output else None
|
|
222
|
+
return output, excluded
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _marker_value(output: Path, source: Path) -> str:
|
|
226
|
+
"""生成绑定源目录和输出位置的归属标记。"""
|
|
227
|
+
output_key = os.path.normcase(str(output.resolve(strict=False)))
|
|
228
|
+
source_key = os.path.normcase(str(source.resolve(strict=True)))
|
|
229
|
+
digest = hashlib.sha256(f"{source_key}\0{output_key}".encode())
|
|
230
|
+
return f"mdsite-cli\n{digest.hexdigest()}\n"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _has_output_marker(output: Path, source: Path) -> bool:
|
|
234
|
+
"""判断目录是否带有本工具写入的归属标记。"""
|
|
235
|
+
if not os.path.lexists(output):
|
|
236
|
+
return False
|
|
237
|
+
if output.is_symlink() or _is_reparse_point(output) or not output.is_dir():
|
|
238
|
+
return False
|
|
239
|
+
marker = output / _MARKER_NAME
|
|
240
|
+
try:
|
|
241
|
+
return marker.is_file() and marker.read_text(encoding="utf-8") == _marker_value(
|
|
242
|
+
output, source
|
|
243
|
+
)
|
|
244
|
+
except (OSError, UnicodeError):
|
|
245
|
+
return False
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _owned_output(output: Path, source: Path) -> bool:
|
|
249
|
+
"""只允许覆盖本工具之前生成的普通目录。"""
|
|
250
|
+
if not os.path.lexists(output):
|
|
251
|
+
return False
|
|
252
|
+
if output.is_symlink() or _is_reparse_point(output) or not output.is_dir():
|
|
253
|
+
raise MdsiteError(f"输出路径已存在且不是可安全替换的 mdsite 目录:{output}")
|
|
254
|
+
if not _has_output_marker(output, source):
|
|
255
|
+
raise MdsiteError(f"输出目录已存在且不是由 mdsite 生成;请更换 --output:{output}")
|
|
256
|
+
return True
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _publish_site(built_site: Path, output: Path, source: Path) -> None:
|
|
260
|
+
"""复制构建结果到目标目录,并保留已有非工具目录。"""
|
|
261
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
262
|
+
had_output = _owned_output(output, source)
|
|
263
|
+
suffix = uuid.uuid4().hex
|
|
264
|
+
staging = output.parent / f".{output.name}.mdsite-stage-{suffix}"
|
|
265
|
+
backup = output.parent / f".{output.name}.mdsite-backup-{suffix}"
|
|
266
|
+
|
|
267
|
+
try:
|
|
268
|
+
shutil.copytree(built_site, staging)
|
|
269
|
+
(staging / _MARKER_NAME).write_text(_marker_value(output, source), encoding="utf-8")
|
|
270
|
+
if had_output:
|
|
271
|
+
output.rename(backup)
|
|
272
|
+
try:
|
|
273
|
+
staging.rename(output)
|
|
274
|
+
except OSError:
|
|
275
|
+
if had_output and backup.exists() and not output.exists():
|
|
276
|
+
backup.rename(output)
|
|
277
|
+
raise
|
|
278
|
+
if had_output:
|
|
279
|
+
shutil.rmtree(backup)
|
|
280
|
+
finally:
|
|
281
|
+
if staging.exists():
|
|
282
|
+
shutil.rmtree(staging)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _run_build(source: Path, requested_output: Path | None) -> int:
|
|
286
|
+
output, output_to_exclude = _resolve_output(source, requested_output)
|
|
287
|
+
_owned_output(output, source)
|
|
288
|
+
with _project_workspace(source, output_to_exclude) as (workspace, config):
|
|
289
|
+
command = _zensical_command("build", "--config-file", str(config))
|
|
290
|
+
result = subprocess.run(command, cwd=workspace, check=False)
|
|
291
|
+
if result.returncode != 0:
|
|
292
|
+
return result.returncode
|
|
293
|
+
built_site = workspace / "site"
|
|
294
|
+
if not (built_site / "index.html").is_file():
|
|
295
|
+
raise MdsiteError("Zensical 构建结束,但没有生成 index.html。")
|
|
296
|
+
_publish_site(built_site, output, source)
|
|
297
|
+
print(f"静态网页已生成:{output}")
|
|
298
|
+
return 0
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _port(value: str) -> int:
|
|
302
|
+
"""校验本地预览端口。"""
|
|
303
|
+
try:
|
|
304
|
+
port = int(value)
|
|
305
|
+
except ValueError as exc:
|
|
306
|
+
raise argparse.ArgumentTypeError("端口必须是整数") from exc
|
|
307
|
+
if not 1 <= port <= 65535:
|
|
308
|
+
raise argparse.ArgumentTypeError("端口范围为 1–65535")
|
|
309
|
+
return port
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _parser() -> argparse.ArgumentParser:
|
|
313
|
+
parser = argparse.ArgumentParser(
|
|
314
|
+
prog="mdsite",
|
|
315
|
+
description="将当前目录的 Markdown 文件预览或构建成网站。",
|
|
316
|
+
)
|
|
317
|
+
parser.add_argument("--path", type=Path, default=None, help="Markdown 根目录,默认当前目录")
|
|
318
|
+
commands = parser.add_subparsers(dest="command")
|
|
319
|
+
|
|
320
|
+
serve = commands.add_parser("serve", help="启动本地预览(默认操作)")
|
|
321
|
+
serve.add_argument(
|
|
322
|
+
"--path",
|
|
323
|
+
type=Path,
|
|
324
|
+
default=argparse.SUPPRESS,
|
|
325
|
+
help="Markdown 根目录,默认当前目录",
|
|
326
|
+
)
|
|
327
|
+
serve.add_argument("--port", type=_port, default=8000, help="本地端口,默认 8000")
|
|
328
|
+
serve.add_argument("--no-open", action="store_true", help="启动后不打开浏览器")
|
|
329
|
+
|
|
330
|
+
build = commands.add_parser("build", help="生成静态网页")
|
|
331
|
+
build.add_argument(
|
|
332
|
+
"--path",
|
|
333
|
+
type=Path,
|
|
334
|
+
default=argparse.SUPPRESS,
|
|
335
|
+
help="Markdown 根目录,默认当前目录",
|
|
336
|
+
)
|
|
337
|
+
build.add_argument("--output", type=Path, help="输出目录,默认根目录下的 site/")
|
|
338
|
+
|
|
339
|
+
return parser
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def _configure_console() -> None:
|
|
343
|
+
"""让非 UTF-8 控制台转义不可编码字符,避免命令意外崩溃。"""
|
|
344
|
+
for stream in (sys.stdout, sys.stderr):
|
|
345
|
+
reconfigure = getattr(stream, "reconfigure", None)
|
|
346
|
+
if reconfigure is not None:
|
|
347
|
+
try:
|
|
348
|
+
reconfigure(errors="backslashreplace")
|
|
349
|
+
except (OSError, ValueError):
|
|
350
|
+
pass
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def main(argv: list[str] | None = None) -> int:
|
|
354
|
+
_configure_console()
|
|
355
|
+
args = _parser().parse_args(argv)
|
|
356
|
+
try:
|
|
357
|
+
source = _source_path(args.path)
|
|
358
|
+
if args.command == "build":
|
|
359
|
+
return _run_build(source, args.output)
|
|
360
|
+
return _run_preview(
|
|
361
|
+
source,
|
|
362
|
+
getattr(args, "port", 8000),
|
|
363
|
+
not getattr(args, "no_open", False),
|
|
364
|
+
)
|
|
365
|
+
except MdsiteError as exc:
|
|
366
|
+
print(f"mdsite: {exc}", file=sys.stderr)
|
|
367
|
+
return 2
|
|
368
|
+
except KeyboardInterrupt:
|
|
369
|
+
return 130
|