在reStructuredText和Markdown文件中的代码块上运行命令。
项目描述
doccmd
一个用于在文档文件中的代码块上运行命令的命令行工具。这允许您对文档文件中的代码块运行linters、formatters和其他工具。
安装
使用pip
需要Python 3.10+。
pip install doccmd
使用Homebrew(macOS,Linux,WSL)
需要Homebrew。
brew tap adamtheturtle/doccmd
brew install doccmd
预构建的Linux二进制文件
$ curl --fail -L https://github.com/adamtheturtle/doccmd/releases/download/2024.09.26/doccmd -o /usr/local/bin/doccmd && \
$ chmod +x /usr/local/bin/doccmd
使用doccmd作为pre-commit钩子
要使用pre-commit运行doccmd,将以下钩子添加到您的.pre-commit-config.yaml
- repo: https://github.com/adamtheturtle/doccmd-pre-commit
rev: v2024.09.26
hooks:
- id: doccmd
args: ["--language", "shell", "--command", "shellcheck --shell=bash"]
additional_dependencies: ["shellcheck-py"]
使用示例
# Run mypy against the Python code blocks in README.md and CHANGELOG.rst
$ doccmd --language=python --command="mypy" README.md CHANGELOG.rst
# Run gofmt against the Go code blocks in README.md
# This will modify the README.md file in place
$ doccmd --language=go --command="gofmt -w" README.md
# or type less...
$ doccmd -l python -c mypy README.md CHANGELOG.rst
它能在什么上工作?
reStructuredText (.rst)
.. code-block:: shell
echo "Hello, world!"
.. code:: shell
echo "Or this Hello, world!"
Markdown (.md)
```shell
echo "Hello, world!"
```
MyST (.md with MyST语法)
```{code-block} shell
echo "Hello, world!"
```
```{code} shell
echo "Or this Hello, world!"
```
需要更多?打开一个问题!
格式化和填充
使用doccmd运行linters会在与文档文件匹配的行号上给出错误和警告。它是通过在运行命令之前对代码块添加填充来实现的。
某些工具与这种填充不兼容,您可以选择隐藏行号,通过使用 --no-pad-file 标志来给工具提供不带填充的原始代码块内容。
文件名和linters忽略
doccmd 会为文档文件中的每个代码块创建临时文件。这些文件与文档文件位于同一目录,并以文档文件名和代码块行号命名。文件创建时,会使用给定的 --file-name-prefix 参数(默认 doccmd)设置前缀。
您可以使用此信息在您的代码检查器配置中忽略文件。
例如,在 pyproject.toml 中的 ruff 配置中忽略由 doccmd 创建的所有文件中的规则
[tool.ruff]
lint.per-file-ignores."doccmd_*.py" = [
# Allow hardcoded secrets in documentation.
"S105",
]
跳过代码块
紧跟在匹配 skip doccmd[all]: next 的注释之后的代码块将被跳过。
例如
reStructuredText (.rst)
.. skip doccmd[all]: next
.. code-block:: shell
echo "This will be skipped!"
.. code-block:: shell
echo "This will run"
Markdown (.md)
<-- skip doccmd[all]: next -->
```shell
echo "This will be skipped!"
```
```shell
echo "This will run"
```
MyST (.md with MyST语法)
% skip doccmd[all]: next
```{code-block} shell
echo "This will be skipped!"
```
```{code-block} shell
echo "This will run"
```
要连续跳过多个代码块,请在要跳过的代码块周围使用 skip doccmd[all]: start 和 skip doccmd[all]: end。
使用 --skip-marker 选项设置特定命令的标记,它将与 "all" 一样有效。例如,使用 --skip-marker="type-check" 跳过紧跟在匹配 skip doccmd[type-check]: next 的注释之后的代码块。此标记使用正则表达式匹配。
完整文档
请参阅 完整文档。