KScript 文档
ZH

格式化

项目规则

内置的 KScript 样式为 CLI 和编辑器设置默认值。将 kscript.rules.kscript 放在 kscript.json 旁边。命令行和编辑器在检查或格式化项目文件时都会读取它。

<Style indent_size="4" print_width="100" />

<Lint code="KS9001" element="img" missing_attribute="alt" message="Give this image alternative text." />

<Format element="img" attributes="one_per_line" />
<Format model="Attachments" options="one_per_line" />
Style(indent_size: 4, print_width: 100)

Lint(
  code: 'KS9001',
  element: 'img',
  missing_attribute: 'alt',
  message: 'Give this image alternative text.',
)

Format(element: 'img', attributes: 'one_per_line')
Format(model: 'Attachments', options: 'one_per_line')
  • Style 会覆盖整个文档的格式默认值。它接受 indent_size、use_tabs、print_width、max_blank_lines、end_of_line 以及 关闭规则 下列出的开关。格式化从内置样式开始,然后依次应用编辑器缩进、项目 Style 设置,以及 kscript.json 中显式的 format 设置。
  • Lint 检查元素是否存在 missing_attribute 或 forbidden_attribute。代码必须唯一,并使用 KS9xxx。默认严重级别为 warning。将 severity: 设为 error、warning、info 或 hint,或在 kscript.json 中使用 "lint": { "rules": { "KS9001": "error" } } 覆盖它。
  • Format 将 HTML 或 XML 标签的属性布局设置为 one_per_line 或 inline。它也可以将脚本模型的选项每行拆分一个,并添加末尾逗号。对所有标签或模型使用 '*'。指定的布局优先于 '*'。
  • 对于 print_width 或 use_tabs 等字面布局设置,请使用数字或布尔值。字面文本设置请加引号。

函数规则

当规则依赖于文档时,请使用fn(value) => ...。此规则会修剪字面量alt属性。插值属性以及事件或绑定表达式将保留其原始文本。

<Format element="img" attribute="alt" value="fn(text) => $text->trim()" />
Format(
  element: 'img',
  attribute: 'alt',
  value: fn(text) => $text->trim(),
)

布局函数返回 'one_per_line'、'inline' 或 null 以使用常规布局。例如,此规则会把空块压缩为 Something(val1, val2) {},并在块中有内容时展开带尾随逗号的参数。

<Format statement="Something" arguments="fn(node) => $node.has_body_content ? 'one_per_line' : 'inline'" />
Format(
  statement: 'Something',
  arguments: fn(node) => $node.has_body_content ? 'one_per_line' : 'inline',
)

使用 attributes: 配合 HTML 或 XML element: 以相同方式选择其布局。传递给函数的节点具有 name、kind、attributes 和 has_body_content。lint check: 函数可以返回自己的消息,true 表示声明的消息,或使用 false 或 null 跳过该诊断。

<Lint code="KS9002" element="img" check="fn(node) => $node.attributes->has('alt') ? null : 'An image needs alternative text.'" />
Lint(
  code: 'KS9002',
  element: 'img',
  check: fn(node) => $node.attributes->has('alt') ? null : 'An image needs alternative text.',
)

函数在受限的表达式上下文中运行,可以访问其参数、比较、条件判断以及文本操作,例如 trim()、upper() 和 starts_with()。项目规则文件使用声明式语法,不能导入包或调用命令。