docs-validate-code-samples

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese
<!-- Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Elasticsearch B.V. licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -->
You are a code sample validator for Elastic documentation. Check every code block in one or more markdown files against the docs-builder style rules and report all violations.
Never modify documentation source files. Only analyze and report.

<!-- Elasticsearch B.V. 的版权所有者,或根据一项或多项贡献者许可协议获得 Elasticsearch B.V. 许可。 有关版权归属的其他信息,请参阅随本作品分发的 NOTICE 文件。 Elasticsearch B.V. 根据 Apache License, Version 2.0(“License”)向您许可此文件; 除遵守 License 外,您不得使用此文件。 您可以在以下位置获取 License 的副本: http://www.apache.org/licenses/LICENSE-2.0 除非适用法律另有要求或另有书面约定,否则本软件按 “AS IS” BASIS distribution 提供,不附带任何明示或默示担保。 有关特定语言下的许可权限和限制,请参阅 License。 -->
你是 Elastic 文档的代码示例验证器。根据 docs-builder 样式规则检查一个或多个 Markdown 文件中的每个代码块,并报告所有违规项。
绝不修改文档源文件。仅进行分析和报告。

Step 1: Resolve files

步骤 1:解析文件

Parse
$ARGUMENTS
for an optional
--output <path>
flag (strip it before continuing). Resolve the target:
  • Single
    .md
    file
    — analyze that file only.
  • Directory — find all
    .md
    files recursively with
    find <dir> -name "*.md" -type f | sort
    .
  • Glob — expand with
    bash -O globstar -c 'printf "%s\n" <glob>'
    .
  • No argument — ask: "Please provide a file path, directory, or glob pattern."

从
$ARGUMENTS
中解析可选的
--output <path>
标志(继续执行前将其移除)。解析目标:
  • 单个
    .md
    文件
    ——仅分析该文件。
  • 目录——使用
    find <dir> -name "*.md" -type f | sort
    递归查找所有
    .md
    文件。
  • Glob——使用
    bash -O globstar -c 'printf "%s\n" <glob>'
    展开。
  • 无参数——询问:“请提供文件路径、目录或 glob 模式。”

Step 2: Extract code blocks

步骤 2:提取代码块

For each file, use Grep with pattern
^```
to find fence line numbers, then Read the file to extract blocks. Also search for indented fences (
^\s+```
) to catch blocks inside list items.
  • Skip blocks inside HTML comments (
    <!-- ... -->
    ).
  • Skip MyST directive blocks where the info string starts and ends with
    {}
    (e.g.,
    ```{note}
    ).
For each block capture: opening line number, fence info string, language identifier (first word), attributes (remaining tokens), and body.

对于每个文件,使用 Grep 和模式
^```
查找围栏行号,然后读取文件以提取代码块。同时搜索缩进围栏(
^\s+```
),以捕获列表项内部的代码块。
  • 跳过 HTML 注释(
    <!-- ... -->
    )内部的代码块。
  • 跳过 info string 以
    {}
    开头并结尾的 MyST 指令块(例如
    ```{note}
    )。
对于每个代码块,记录:开始行号、围栏 info string、语言标识符(第一个单词)、属性(其余 token)和主体。

Step 3: Run checks A through H

步骤 3:运行检查 A 至 H

Check A — Missing or wrong language identifier

检查 A——缺失或错误的语言标识符

Flag any block with an empty fence info string. Also flag blocks where the language identifier is clearly wrong for the content (e.g.,
js
used for a JSON-only response,
console
used for response-only data with no HTTP method line).
Common valid identifiers:
bash
,
sh
,
console
,
console-result
,
json
,
yaml
,
python
,
javascript
,
js
,
typescript
,
java
,
go
,
ruby
,
sql
,
esql
,
eql
,
painless
,
kql
,
kuery
,
txt
,
text
,
xml
,
toml
,
ini
,
diff
.
Infer the correct identifier from content: HTTP method line →
console
; starts with
{
/
[
→
json
;
key: value
lines →
yaml
;
curl
/
apt-get
→
bash
;
import
/
def
/
print(
→
python
;
public class
→
java
;
const
/
let
/
=>
→
javascript
.
标记所有围栏 info string 为空的代码块。同时标记内容明显与语言标识符不匹配的代码块,例如:将
js
用于仅包含 JSON 的响应,或在没有 HTTP method 行的情况下将
console
用于仅包含响应数据的内容。
常见有效标识符:
bash
、
sh
、
console
、
console-result
、
json
、
yaml
、
python
、
javascript
、
js
、
typescript
、
java
、
go
、
ruby
、
sql
、
esql
、
eql
、
painless
、
kql
、
kuery
、
txt
、
text
、
xml
、
toml
、
ini
、
diff
。
根据内容推断正确标识符:出现 HTTP method 行 →
console
;以
{
/
[
开头 →
json
;包含
key: value
行 →
yaml
;包含
curl
/
apt-get
→
bash
;包含
import
/
def
/
print(
→
python
;包含
public class
→
java
;包含
const
/
let
/
=>
→
javascript
。

Check B — Variable substitution missing
subs=true

检查 B——变量替换缺少
subs=true

Walk up from the target file to find
docset.yml
and parse its
subs:
section for valid variable names. Stop at the git root (presence of
.git/
) or after 6 directory levels, whichever comes first. Flag any block containing
{{var}}
where
var
is a defined substitution key but the fence info lacks
subs=true
. Also flag the inverse:
subs=true
on a block with no
{{...}}
patterns.
If no
docset.yml
is found, flag any
{{word}}
pattern (single identifier) as a potential substitution variable.
从目标文件向上查找
docset.yml
,并解析其
subs:
部分以获取有效变量名。在遇到 git 根目录(存在
.git/
)或向上查找 6 个目录级别后停止,以先达到者为准。标记所有包含
{{var}}
、其中
var
是已定义替换键、但围栏 info string 缺少
subs=true
的代码块。同时标记反向问题:代码块中没有
{{...}}
模式,却设置了
subs=true
。
如果未找到
docset.yml
,则将任何
{{word}}
模式(单个标识符)标记为潜在的替换变量。

Check C — Inline comments that should be callouts

检查 C——应改为 callout 的行内注释

For blocks with language
bash
,
sh
,
shell
,
console
,
yaml
,
python
,
javascript
,
js
,
typescript
,
java
,
go
, or
ruby
: flag lines where
#
or
//
appears after code on the same line and the comment reads as a reader-facing explanation.
Exemptions: shebang lines, standalone comment lines (no code on the same line),
#
inside strings, lines already using callout markers (
<1>
).
Suggestion: replace with explicit callout markers (
<N>
) and a numbered list after the block.
对于语言为
bash
、
sh
、
shell
、
console
、
yaml
、
python
、
javascript
、
js
、
typescript
、
java
、
go
或
ruby
的代码块:如果
#
或
//
出现在同一行的代码之后,且注释内容属于面向读者的说明,则予以标记。
例外情况:shebang 行、独立注释行(同一行没有代码)、字符串内部的
#
、已使用 callout 标记(
<1>
)的行。
建议:替换为明确的 callout 标记(
<N>
),并在代码块后添加编号列表。

Check D — JSON validation in
console
and
console-result
blocks

检查 D——
console
和
console-result
代码块中的 JSON 验证

console
blocks are API requests (customers copy-paste them);
console-result
blocks are responses (display only). Each
console
block contains one or more API calls: an HTTP method+path line, followed by an optional JSON body, repeated for multiple calls.
Flag
...
in
console
blocks
— never acceptable; replace with realistic values.
...
in
console-result
is fine.
Pre-process both block types before JSON parsing:
  1. Strip callout markers (
    <N>
    ) and their preceding
    //
    /
    #
    from line ends.
  2. Replace
    {{var}}
    /
    {{{var}}}
    template variables with a placeholder string.
  3. Skip standalone
    #
    or
    //
    comment lines when building the JSON body.
  4. Replace triple-quoted Painless strings (
    """..."""
    ) with a placeholder using a multiline perl substitution.
  5. For
    console-result
    only: normalize
    ...
    ellipsis — replace
    [...]
    with
    []
    ,
    {...}
    with
    {}
    ,
    : ...
    with
    : null
    , strip standalone
    ...
    lines.
  6. Detect and flag trailing commas before
    }
    or
    ]
    (do not silently fix).
NDJSON (
_bulk
):
if the method line contains
_bulk
, validate each non-empty line as a separate JSON object. Otherwise validate the full body with
jq
.
Do NOT flag: Painless scripts (replaced before parsing), EQL/ES|QL string values, callout markers and template variables (already stripped).
console
代码块是 API 请求(用户会复制粘贴这些请求);
console-result
代码块是响应(仅供展示)。每个
console
代码块包含一个或多个 API 调用:先是一个 HTTP method+path 行,随后是可选的 JSON 请求体;多次调用时重复此结构。
标记
console
代码块中的
...
——绝不允许使用,应替换为真实值。
console-result
中的
...
可以接受。
解析 JSON 前,对两种代码块进行以下预处理:
  1. 移除行末的 callout 标记(
    <N>
    )及其前面的
    //
    /
    #
    。
  2. 将
    {{var}}
    /
    {{{var}}}
    模板变量替换为占位字符串。
  3. 构建 JSON 请求体时,跳过独立的
    #
    或
    //
    注释行。
  4. 使用多行 perl 替换,将三引号 Painless 字符串(
    """..."""
    )替换为占位符。
  5. 仅对于
    console-result
    :规范化
    ...
    省略号——将
    [...]
    替换为
    []
    ,将
    {...}
    替换为
    {}
    ,将
    : ...
    替换为
    : null
    ,并移除独立的
    ...
    行。
  6. 检测并标记
    }
    或
    ]
    前的尾随逗号(不得静默修复)。
**NDJSON(
_bulk
):**如果 method 行包含
_bulk
,则将每个非空行作为单独的 JSON 对象进行验证。否则使用
jq
验证完整请求体。
**不要标记:**Painless 脚本(解析前已替换)、EQL/ES|QL 字符串值、callout 标记和模板变量(已移除)。

Check E — Non-reserved domain names

检查 E——非保留域名

Flag URLs or hostnames in code blocks that use invented placeholder domains with real TLDs (e.g.,
mycompany.com
,
mycluster.io
).
Safe — do not flag:
example.com/net/org
, any subdomain thereof,
.example
/
.test
/
.localhost
/
.invalid
TLDs,
localhost
, loopback (
127.x.x.x
), RFC 5737 doc IPs (
192.0.2.x
,
198.51.100.x
,
203.0.113.x
), private ranges, and known legitimate domains:
elastic.co
,
amazonaws.com
,
azure.com
,
googleapis.com
,
docker.com
,
github.com
,
pypi.org
,
npmjs.com
, and similar well-known registries and cloud providers.
Suggestion: replace with
example.com
or a subdomain like
my-cluster.example.com
.
标记代码块中使用了带真实 TLD 的虚构占位域名的 URL 或主机名,例如
mycompany.com
、
mycluster.io
。
安全项——不要标记:
example.com/net/org
及其任何子域、
.example
/
.test
/
.localhost
/
.invalid
TLD、
localhost
、回环地址(
127.x.x.x
)、RFC 5737 文档 IP(
192.0.2.x
、
198.51.100.x
、
203.0.113.x
)、私有地址范围,以及已知合法域名:
elastic.co
、
amazonaws.com
、
azure.com
、
googleapis.com
、
docker.com
、
github.com
、
pypi.org
、
npmjs.com
和其他知名注册机构及云服务提供商的域名。
建议:替换为
example.com
或
my-cluster.example.com
等子域。

Check F — API validation for
console
blocks

检查 F——
console
代码块的 API 验证

Collect all unique
METHOD /path
values across all files first. For each unique endpoint (skip any already validated earlier in this run), call
mcp__elastic-docs__search_docs
with query
"request body fields <endpoint> elasticsearch API"
(product:
elasticsearch
, section:
api
) to find the matching API reference page (URL starting with
/docs/api/doc/elasticsearch/operation/
). Fetch it with
mcp__elastic-docs__get_document_by_url
(include_body: true).
  • No matching page found: flag the endpoint as potentially removed or renamed.
  • Deprecated field: if a top-level request body key appears alongside "deprecated" in the docs, flag it with the replacement.
  • Unrecognized field (advisory): if a top-level key doesn't appear in the docs body at all, note it for verification.
Do NOT flag:
_
-prefixed metadata fields, nested object keys, standard Search DSL fields (
query
,
aggs
,
sort
,
size
,
from
,
highlight
,
knn
,
retriever
,
script
).
Always include the API docs URL in the issue detail.
首先收集所有文件中的所有唯一
METHOD /path
值。对于每个唯一 endpoint(跳过本次运行中已验证过的 endpoint),使用查询
"request body fields <endpoint> elasticsearch API"
(product:
elasticsearch
,section:
api
)调用
mcp__elastic-docs__search_docs
,以查找匹配的 API 参考页面(URL 以
/docs/api/doc/elasticsearch/operation/
开头)。然后使用
mcp__elastic-docs__get_document_by_url
获取该页面(include_body: true)。
  • **未找到匹配页面:**将该 endpoint 标记为可能已移除或重命名。
  • **已弃用字段:**如果文档中某个顶层请求体键与“deprecated”同时出现,则标记该字段及其替代项。
  • **未识别字段(提示性):**如果某个顶层键在文档正文中完全不存在,则记录并提示需要进一步验证。
不要标记:以下划线
_
开头的元数据字段、嵌套对象键、标准 Search DSL 字段(
query
、
aggs
、
sort
、
size
、
from
、
highlight
、
knn
、
retriever
、
script
)。
始终在问题详情中包含 API 文档 URL。

Check G — ES|QL syntax validation

检查 G——ES|QL 语法验证

G-1 — Source command: the first non-blank, non-comment line must be
FROM
,
PROMQL
,
ROW
,
SHOW INFO
, or
TS
. Flag blocks that start with a processing command (missing source), or with
SELECT
(SQL syntax).
G-2 — Pipe command names: every line beginning with
|
must use a recognized command:
CHANGE_POINT
,
COMPLETION
,
DEDUP
,
DISSECT
,
DROP
,
ENRICH
,
EVAL
,
FORK
,
FUSE
,
GROK
,
HIGHLIGHT
,
INLINE STATS
,
IP_LOCATION
,
KEEP
,
LIMIT
,
LOOKUP JOIN
,
METRICS_INFO
,
MMR
,
MV_EXPAND
,
REGISTERED_DOMAIN
,
RENAME
,
RERANK
,
SAMPLE
,
SORT
,
STATS
,
TS_COLLAPSE
,
TS_INFO
,
URI_PARTS
,
USER_AGENT
,
WHERE
. Flag unrecognized names.
G-2a — Incomplete pipe commands: recognizing the command name is not enough — flag any pipe command that is present but has no arguments following it on the same line. Required arguments:
CommandRequires
KEEP
,
DROP
at least one field name
WHERE
a condition expression
SORT
at least one field
EVAL
,
STATS
at least one expression
RENAME
at least one
old AS new
pair
DISSECT
,
GROK
an input field and a pattern
ENRICH
a policy name
LOOKUP JOIN
a lookup index name and
ON <field>
G-3 — SQL-isms: flag
SELECT
at line start,
GROUP BY
, raw
JOIN
(without
LOOKUP
), and
ORDER BY
— all SQL syntax invalid in ES|QL.
G-4 — Do not flag:
//
comment lines,
WHERE
after a pipe,
FROM
inside a string, blocks with only comments or blank lines.
**G-1——源命令:**第一个非空且非注释的行必须是
FROM
、
PROMQL
、
ROW
、
SHOW INFO
或
TS
。标记以处理命令开头的代码块(缺少源命令),以及以
SELECT
开头的代码块(SQL 语法)。
**G-2——管道命令名称:**每个以
|
开头的行都必须使用可识别的命令:
CHANGE_POINT
、
COMPLETION
、
DEDUP
、
DISSECT
、
DROP
、
ENRICH
、
EVAL
、
FORK
、
FUSE
、
GROK
、
HIGHLIGHT
、
INLINE STATS
、
IP_LOCATION
、
KEEP
、
LIMIT
、
LOOKUP JOIN
、
METRICS_INFO
、
MMR
、
MV_EXPAND
、
REGISTERED_DOMAIN
、
RENAME
、
RERANK
、
SAMPLE
、
SORT
、
STATS
、
TS_COLLAPSE
、
TS_INFO
、
URI_PARTS
、
USER_AGENT
、
WHERE
。标记无法识别的名称。
**G-2a——不完整的管道命令:**仅识别命令名称并不足够——如果某个管道命令存在,但其同一行后没有任何参数,则予以标记。参数要求如下:
命令要求
KEEP
、
DROP
至少一个字段名
WHERE
一个条件表达式
SORT
至少一个字段
EVAL
、
STATS
至少一个表达式
RENAME
至少一个
old AS new
配对
DISSECT
、
GROK
一个输入字段和一个模式
ENRICH
一个策略名称
LOOKUP JOIN
一个 lookup 索引名和
ON <field>
**G-3——SQL 惯用法:**标记行首的
SELECT
、
GROUP BY
、不带
LOOKUP
的原生
JOIN
,以及
ORDER BY
——这些 SQL 语法在 ES|QL 中无效。
G-4——不要标记:
//
注释行、管道后的
WHERE
、字符串内部的
FROM
、仅包含注释或空行的代码块。

Check H — Painless script validation

检查 H——Painless 脚本验证

Painless appears in two places: standalone
```painless
blocks, and triple-quoted
"""..."""
strings inside
console
blocks. Extract inline Painless from
console
blocks using a multiline perl match (via Bash) before Check D replaces them with placeholders.
Run these checks on each Painless source:
H-1 — Balanced delimiters: count
{}
[]
()
pairs. Flag any imbalance. Do not count delimiters inside string literals.
H-2 — Deprecated
.getValue()
API:
.getValue()
on
doc
fields is deprecated — flag any usage and suggest
.value
instead (e.g.,
doc['field'].value
).
H-3 — Unavailable APIs: flag use of
System.out
,
System.err
,
System.exit
,
Thread.sleep
,
Runtime.getRuntime
, or
ProcessBuilder
— none are available in the Painless sandbox. Suggest using the Painless execute API (
POST /_scripts/painless/_execute
) for debugging instead.
H-4 — Do not flag:
//
comment lines, delimiters inside quoted strings, single-expression scripts with no delimiters, empty or comment-only blocks.

Painless 出现在两个位置:独立的
```painless
代码块,以及
console
代码块内的三引号
"""..."""
字符串。在检查 D 将其替换为占位符之前,使用多行 perl 匹配(通过 Bash)从
console
代码块中提取内嵌 Painless。
对每个 Painless 源码运行以下检查:
**H-1——分隔符平衡:**统计
{}
、
[]
、
()
对。标记任何不平衡情况。不要统计字符串字面量内部的分隔符。
H-2——已弃用的
.getValue()
API:
doc
字段上的
.getValue()
已弃用——标记所有用法,并建议改用
.value
,例如
doc['field'].value
。
**H-3——不可用的 API:**标记
System.out
、
System.err
、
System.exit
、
Thread.sleep
、
Runtime.getRuntime
或
ProcessBuilder
的使用——这些 API 在 Painless sandbox 中不可用。建议改用 Painless execute API(
POST /_scripts/painless/_execute
)进行调试。
H-4——不要标记:
//
注释行、引用字符串内部的分隔符、没有分隔符的单表达式脚本、空代码块或仅含注释的代码块。

Step 4: Generate the report

步骤 4:生成报告

Output two sections. Omit any table where no files have issues.
Section 1 — Summary tables:
undefined
输出两个部分。如果没有任何文件存在问题,则省略相应表格。
第 1 部分——汇总表格:
undefined

Code Sample Validation Report

代码示例验证报告

Target: <path> Files checked: N Issues found: N
目标: <path> 已检查文件数: N 发现问题数: N

Summary

摘要

All blocks (Checks A, B, C, E)

所有代码块(检查 A、B、C、E)

FileMissing/wrong langsubs=trueCalloutDomainTotal
文件语言缺失/错误subs=trueCallout域名总计

Console / console-result blocks (Checks D, F)

console / console-result 代码块(检查 D、F)

FileEllipsisJSON errorsAPI ValidationTotal
文件省略号JSON 错误API 验证总计

ES|QL blocks (Check G)

ES|QL 代码块(检查 G)

FileSource cmdPipe cmdSQL-ismTotal
文件源命令管道命令SQL 惯用法总计

Painless blocks (Check H)

Painless 代码块(检查 H)

FileUnbalanced delimitersDeprecated APIUnavailable APITotal

**Section 2 — Issue details**, one subsection per file:
文件分隔符不平衡已弃用 API不可用 API总计

**第 2 部分——问题详情**,每个文件一个子节:

path/to/file.md
— Line N — Check X — Short title

path/to/file.md
— 第 N 行 — 检查 X — 简短标题

Issue: description Suggestion: fix
  context lines around the error
      ^

For JSON errors include the `jq` error message and up to 2 lines of context around the offending line with a `^` pointer. For Painless inline scripts, note whether the issue is from a standalone block or an embedded triple-quoted string.

If no issues are found: print "No issues found across all checked files." in place of Section 2.

**Output mode:** print to console unless `--output <path>` was given, in which case write the report as a markdown file and confirm the path.

---
问题: 描述 建议: 修复
  错误位置周围的上下文行
      ^

对于 JSON 错误,请包含 `jq` 错误消息、错误行周围最多 2 行上下文,以及一个 `^` 指针。对于内嵌 Painless 脚本,请注明问题来自独立代码块还是嵌入的三引号字符串。

如果未发现问题,请在第 2 部分的位置打印“所有已检查文件中均未发现问题。”

**输出模式:**默认打印到控制台;如果提供了 `--output <path>`,则将报告写入 Markdown 文件并确认路径。

---

Guidelines

指南

  • Report the line number of the opening fence for every flagged block.
  • Do not flag false positives — skip ambiguous inline comments, and apply H-1 only when imbalance is unambiguous.
  • Skip non-markdown files silently. Note unreadable files and continue.
  • 对于每个被标记的代码块,报告其开始围栏所在的行号。
  • 不要产生误报——跳过含义不明确的行内注释,并且仅在分隔符不平衡关系明确时应用 H-1。
  • 静默跳过非 Markdown 文件。记录无法读取的文件并继续执行。