write-coding-standards-from-file

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Write Coding Standards From File

基于文件编写编码规范

Use the existing syntax of the file(s) to establish the standards and style guides for the project. If more than one file or a folder is passed, loop through each file or files in the folder, appending the file's data to temporary memory or a file, then when complete use temporary data as a single instance; as if it were the file name to base the standards and style guideline on.
利用现有文件的语法来制定项目的规范和风格指南。如果传入多个文件或一个文件夹,则遍历每个文件或文件夹中的所有文件,将文件数据追加到临时内存或临时文件中,完成后将临时数据作为单一数据源,以此为基础制定规范和风格指南。

Rules and Configuration

规则与配置

Below is a set of quasi-configuration
boolean
and
string[]
variables. Conditions for handling
true
, or other values for each variable are under the level two heading
## Variable and Parameter Configuration Conditions
.
Parameters for the prompt have a text definition. There is one required parameter
${fileName}
, and several optional parameters
${folderName}
,
${instructions}
, and any
[configVariableAsParameter]
.
以下是一组类配置的
boolean
string[]
类型变量。每个变量的
true
值或其他值的处理条件见二级标题
## 变量与参数配置条件
提示的参数有文本定义。其中有一个必填参数**
${fileName}
,以及多个可选参数
${folderName}
${instructions}
,还有任意
[configVariableAsParameter]
**。

Configuration Variables

配置变量

  • addStandardsTest = false;
  • addToREADME = false;
  • addToREADMEInsertions = ["atBegin", "middle", "beforeEnd", "bestFitUsingContext"];
    • Default to beforeEnd.
  • createNewFile = true;
  • fetchStyleURL = true;
  • findInconsistencies = true;
  • fixInconsistencies = true;
  • newFileName = ["CONTRIBUTING.md", "STYLE.md", "CODE_OF_CONDUCT.md", "CODING_STANDARDS.md", "DEVELOPING.md", "CONTRIBUTION_GUIDE.md", "GUIDELINES.md", "PROJECT_STANDARDS.md", "BEST_PRACTICES.md", "HACKING.md"];
    • For each file in
      ${newFileName}
      , if file does not exist, use that file name and
      break
      , else continue to next file name of
      ${newFileName}
      .
  • outputSpecToPrompt = false;
  • useTemplate = "verbose"; // or "v"
    • Possible values are
      [["v", "verbose"], ["m", "minimal"], ["b", "best fit"], ["custom"]]
      .
    • Selects one of the two example templates at the bottom of prompt file under the level two heading
      ## Coding Standards Templates
      , or use another composition that is a better fit.
    • If custom, then apply per request.
  • addStandardsTest = false;
  • addToREADME = false;
  • addToREADMEInsertions = ["atBegin", "middle", "beforeEnd", "bestFitUsingContext"];
    • 默认值为beforeEnd
  • createNewFile = true;
  • fetchStyleURL = true;
  • findInconsistencies = true;
  • fixInconsistencies = true;
  • newFileName = ["CONTRIBUTING.md", "STYLE.md", "CODE_OF_CONDUCT.md", "CODING_STANDARDS.md", "DEVELOPING.md", "CONTRIBUTION_GUIDE.md", "GUIDELINES.md", "PROJECT_STANDARDS.md", "BEST_PRACTICES.md", "HACKING.md"];
    • 遍历
      ${newFileName}
      中的每个文件名,如果文件不存在,则使用该文件名并停止遍历,否则继续下一个文件名。
  • outputSpecToPrompt = false;
  • useTemplate = "verbose"; // 或 "v"
    • 可选值为
      [["v", "verbose"], ["m", "minimal"], ["b", "best fit"], ["custom"]]
    • 选择提示文件底部二级标题
      ## Coding Standards Templates
      下的两个示例模板之一,或使用更合适的自定义模板。
    • 如果为custom,则根据传入的请求进行调整。

Configuration Variables as Prompt Parameters

作为提示参数的配置变量

If any of the variable names are passed to prompt as-is, or as a similar but clearly related text value, then override the default variable value with the value passed to prompt.
如果任何变量名直接作为参数传入提示,或传入含义明确的相关文本值,则用传入的值覆盖变量的默认值。

Prompt Parameters

提示参数

  • fileName = The name of the file that will be analyzed in terms of: indentation, variable naming, commenting, conditional procedures, functional procedures, and other syntax related data for the coding language of the file.
  • folderName = The name of the folder that will be used to extract data from multiple files into one aggregated dataset that will be analyzed in terms of: indentation, variable naming, commenting, conditional procedures, functional procedures, and other syntax related data for the coding language of the files.
  • instructions = Additional instructions, rules, and procedures that will be provided for unique cases.
  • [configVariableAsParameter] = If passed will override the default state of the configuration variable. Example:
    • useTemplate = If passed will override the configuration
      ${useTemplate}
      default. Values are
      [["v", "verbose"], ["m", "minimal"], ["b", "best fit"]]
      .
  • fileName = 需分析的文件名,分析内容包括:缩进、变量命名、注释、条件语句、函数过程及该编码语言的其他语法相关数据。
  • folderName = 需提取数据的文件夹名,将文件夹中所有文件的数据聚合为一个数据集进行分析,分析内容包括:缩进、变量命名、注释、条件语句、函数过程及该编码语言的其他语法相关数据。
  • instructions = 针对特殊场景的额外说明、规则和流程。
  • [configVariableAsParameter] = 如果传入该参数,将覆盖对应配置变量的默认状态。示例:
    • useTemplate = 传入该参数将覆盖配置
      ${useTemplate}
      的默认值,可选值为
      [["v", "verbose"], ["m", "minimal"], ["b", "best fit"]]

Required and Optional Parameters

必填与可选参数

  • fileName - required
  • folderName - optional
  • instructions - optional
  • [configVariableAsParameter] - optional
  • fileName - 必填
  • folderName - 可选
  • instructions - 可选
  • [configVariableAsParameter] - 可选

Variable and Parameter Configuration Conditions

变量与参数配置条件

${fileName}.length > 1 || ${folderName} != undefined

${fileName}.length > 1 || ${folderName} != undefined

  • If true, toggle
    ${fixInconsistencies}
    to false.
  • 如果为true,将
    ${fixInconsistencies}
    设为false。

${addToREADME} == true

${addToREADME} == true

  • Insert the coding standards into the
    README.md
    instead of outputting to the prompt or creating a new file.
  • If true, toggle both
    ${createNewFile}
    and
    ${outputSpecToPrompt}
    to false.
  • 将编码规范插入到
    README.md
    中,而非输出到提示或创建新文件。
  • 如果为true,将
    ${outputSpecToPrompt}
    ${createNewFile}
    都设为false。

${addToREADMEInsertions} == "atBegin"

${addToREADMEInsertions} == "atBegin"

  • If
    ${addToREADME}
    is true, then insert the coding standards data at the beginning of the
    README.md
    file after the title.
  • 如果
    ${addToREADME}
    为true,则将编码规范数据插入到
    README.md
    的开头,紧跟标题之后。

${addToREADMEInsertions} == "middle"

${addToREADMEInsertions} == "middle"

  • If
    ${addToREADME}
    is true, then insert the coding standards data at the middle of the
    README.md
    file, changing the standards title heading to match that of the
    README.md
    composition.
  • 如果
    ${addToREADME}
    为true,则将编码规范数据插入到
    README.md
    的中间位置,并修改规范标题以匹配
    README.md
    的结构。

${addToREADMEInsertions} == "beforeEnd"

${addToREADMEInsertions} == "beforeEnd"

  • If
    ${addToREADME}
    is true, then insert the coding standards data at the end of the
    README.md
    file, inserting a new line after the last character, then inserting the data on a new line.
  • 如果
    ${addToREADME}
    为true,则将编码规范数据插入到
    README.md
    的末尾,在最后一个字符后插入新行,再将数据插入到新行中。

${addToREADMEInsertions} == "bestFitUsingContext"

${addToREADMEInsertions} == "bestFitUsingContext"

  • If
    ${addToREADME}
    is true, then insert the coding standards data at the best fitting line of the
    README.md
    file in regards to the context of the
    README.md
    composition and flow of data.
  • 如果
    ${addToREADME}
    为true,则根据
    README.md
    的内容结构和数据流向,将编码规范数据插入到最合适的位置。

${addStandardsTest} == true

${addStandardsTest} == true

  • Once the coding standards file is complete, write a test file to ensure the file or files passed to it adhere to the coding standards.
  • 编码规范文件完成后,编写一个测试文件,确保传入的文件符合编码规范要求。

${createNewFile} == true

${createNewFile} == true

  • Create a new file using the value, or one of the possible values, from
    ${newFileName}
    .
  • If true, toggle both
    ${outputSpecToPrompt}
    and
    ${addToREADME}
    to false.
  • 使用
    ${newFileName}
    中的值或其中一个可选值创建新文件。
  • 如果为true,将
    ${outputSpecToPrompt}
    ${addToREADME}
    都设为false。

${fetchStyleURL} == true

${fetchStyleURL} == true

  • Additionally use the data fetched from the links nested under level three heading
    ### Fetch Links
    as context for creating standards, specifications, and styling data for the new file, prompt, or
    README.md
    .
  • For each relevant item in
    ### Fetch Links
    , run
    #fetch ${item}
    .
  • 额外使用三级标题
    ### Fetch Links
    下的链接数据作为上下文,为新文件、提示或
    README.md
    制定规范、标准和风格数据。
  • ### Fetch Links
    中的每个相关项,执行
    #fetch ${item}

${findInconsistencies} == true

${findInconsistencies} == true

  • Evaluate syntax related to indentations, line-breaks, comments, conditional and function nesting, quotation wrappers i.e.
    '
    or
    "
    for strings, etc., and categorize.
  • For each category, make a count, and if one item does not match the majority of the count, then commit to temporary memory.
  • Depending on the status of
    ${fixInconsistencies}
    , either edit and fix the low count categories to match the majority, or output to prompt inconsistencies stored in temporary memory.
  • 评估与缩进、换行、注释、条件语句和函数嵌套、字符串引号(如
    '
    "
    )相关的语法,并进行分类。
  • 对每个分类进行计数,如果某一项的计数与多数项不符,则将其存入临时内存。
  • 根据
    ${fixInconsistencies}
    的状态,要么编辑并修复计数较少的分类使其与多数项一致,要么将临时内存中存储的不一致内容输出到提示。

${fixInconsistencies} == true

${fixInconsistencies} == true

  • Edit and fix the low count categories of syntax data to match the majority of corresponding syntax data using inconsistencies stored in temporary memory.
  • 使用临时内存中存储的不一致内容,编辑并修复计数较少的语法分类,使其与多数对应语法数据一致。

typeof ${newFileName} == "string"

typeof ${newFileName} == "string"

  • If specifically defined as a
    string
    , create a new file using the value from
    ${newFileName}
    .
  • 如果
    ${newFileName}
    明确为
    string
    类型,则使用该值创建新文件。

typeof ${newFileName} != "string"

typeof ${newFileName} != "string"

  • If NOT specifically defined as a
    string
    , but instead an
    object
    or an array, create a new file using a value from
    ${newFileName}
    by applying this rule:
    • For each file name in
      ${newFileName}
      , if file does not exist, use that file name and
      break
      , else continue to the next.
  • 如果
    ${newFileName}
    不是明确的
    string
    类型,而是
    object
    或数组,则按照以下规则使用
    ${newFileName}
    中的值创建新文件:
    • 遍历
      ${newFileName}
      中的每个文件名,如果文件不存在,则使用该文件名并停止遍历,否则继续下一个。

${outputSpecToPrompt} == true

${outputSpecToPrompt} == true

  • Output the coding standards to the prompt instead of creating a file or adding to README.
  • If true, toggle both
    ${createNewFile}
    and
    ${addToREADME}
    to false.
  • 将编码规范输出到提示,而非创建文件或插入到README中。
  • 如果为true,将
    ${createNewFile}
    ${addToREADME}
    都设为false。

${useTemplate} == "v" || ${useTemplate} == "verbose"

${useTemplate} == "v" || ${useTemplate} == "verbose"

  • Use data under the level three heading
    ### "v", "verbose"
    as guiding template when composing the data for coding standards.
  • 编写编码规范数据时,以三级标题
    ### "v", "verbose"
    下的数据为指导模板。

${useTemplate} == "m" || ${useTemplate} == "minimal"

${useTemplate} == "m" || ${useTemplate} == "minimal"

  • Use data under the level three heading
    ### "m", "minimal"
    as guiding template when composing the data for coding standards.
  • 编写编码规范数据时,以三级标题
    ### "m", "minimal"
    下的数据为指导模板。

${useTemplate} == "b" || ${useTemplate} == "best"

${useTemplate} == "b" || ${useTemplate} == "best"

  • Use either the data under the level three heading
    ### "v", "verbose"
    or
    ### "m", "minimal"
    , depending on the data extracted from
    ${fileName}
    , and use the best fit as guiding template when composing the data for coding standards.
  • 根据从
    ${fileName}
    中提取的数据,选择三级标题
    ### "v", "verbose"
    ### "m", "minimal"
    下的模板,以最匹配的模板作为编写编码规范数据的指导。

${useTemplate} == "custom" || ${useTemplate} == "<ANY_NAME>"

${useTemplate} == "custom" || ${useTemplate} == "<ANY_NAME>"

  • Use the custom prompt, instructions, template, or other data passed as guiding template when composing the data for coding standards.
  • 编写编码规范数据时,以传入的自定义提示、说明、模板或其他数据为指导模板。

if
${fetchStyleURL} == true

if
${fetchStyleURL} == true

Depending on the programming language, for each link in list below, run
#fetch (URL)
, if programming language is
${fileName} == [<Language> Style Guide]
.
根据编程语言,对以下列表中的每个链接,如果编程语言匹配
${fileName} == [<Language> Style Guide]
,则执行
#fetch (URL)

Fetch Links

Fetch Links

Coding Standards Templates

编码规范模板

"m", "minimal"

"m", "minimal"

text
    ```markdown
    ## 1. Introduction
    *   **Purpose:** Briefly explain why the coding standards are being established (e.g., to improve code quality, maintainability, and team collaboration).
    *   **Scope:** Define which languages, projects, or modules this specification applies to.

    ## 2. Naming Conventions
    *   **Variables:** `camelCase`
    *   **Functions/Methods:** `PascalCase` or `camelCase`.
    *   **Classes/Structs:** `PascalCase`.
    *   **Constants:** `UPPER_SNAKE_CASE`.

    ## 3. Formatting and Style
    *   **Indentation:** Use 4 spaces per indent (or tabs).
    *   **Line Length:** Limit lines to a maximum of 80 or 120 characters.
    *   **Braces:** Use the "K&R" style (opening brace on the same line) or the "Allman" style (opening brace on a new line).
    *   **Blank Lines:** Specify how many blank lines to use for separating logical blocks of code.

    ## 4. Commenting
    *   **Docstrings/Function Comments:** Describe the function's purpose, parameters, and return values.
    *   **Inline Comments:** Explain complex or non-obvious logic.
    *   **File Headers:** Specify what information should be included in a file header, such as author, date, and file description.

    ## 5. Error Handling
    *   **General:** How to handle and log errors.
    *   **Specifics:** Which exception types to use, and what information to include in error messages.

    ## 6. Best Practices and Anti-Patterns
    *   **General:** List common anti-patterns to avoid (e.g., global variables, magic numbers).
    *   **Language-specific:** Specific recommendations based on the project's programming language.

    ## 7. Examples
    *   Provide a small code example demonstrating the correct application of the rules.
    *   Provide a small code example of an incorrect implementation and how to fix it.

    ## 8. Contribution and Enforcement
    *   Explain how the standards are to be enforced (e.g., via code reviews).
    *   Provide a guide for contributing to the standards document itself.
    ```
text
    ```markdown
    ## 1. 引言
    *   **目的:** 简要说明制定编码规范的原因(例如:提升代码质量、可维护性和团队协作效率)。
    *   **范围:** 定义本规范适用的语言、项目或模块。

    ## 2. 命名约定
    *   **变量:** `camelCase`
    *   **函数/方法:** `PascalCase` 或 `camelCase`。
    *   **类/结构体:** `PascalCase`。
    *   **常量:** `UPPER_SNAKE_CASE`。

    ## 3. 格式与风格
    *   **缩进:** 每级缩进使用4个空格(或制表符)。
    *   **行长度:** 每行最多80或120个字符。
    *   **大括号:** 使用“K&R”风格(左大括号与语句同行)或“Allman”风格(左大括号单独一行)。
    *   **空行:** 指定分隔逻辑代码块的空行数量。

    ## 4. 注释规范
    *   **文档字符串/函数注释:** 描述函数的用途、参数和返回值。
    *   **行内注释:** 解释复杂或非直观的逻辑。
    *   **文件头:** 指定文件头应包含的信息,例如作者、日期和文件描述。

    ## 5. 错误处理
    *   **通用规则:** 如何处理和记录错误。
    *   **具体要求:** 使用哪些异常类型,错误消息应包含哪些信息。

    ## 6. 最佳实践与反模式
    *   **通用规则:** 列出应避免的常见反模式(例如:全局变量、魔法数字)。
    *   **语言特定规则:** 基于项目编程语言的特定建议。

    ## 7. 示例
    *   提供一个符合规则的简短代码示例。
    *   提供一个不符合规则的代码示例,并说明如何修复。

    ## 8. 贡献与执行
    *   说明如何执行规范(例如:通过代码审查)。
    *   提供修改本规范文档的指南。
    ```

"v", verbose"

"v", verbose"

text
    ```markdown

    # Style Guide

    This document defines the style and conventions used in this project.
    All contributions should follow these rules unless otherwise noted.

    ## 1. General Code Style

    - Favor clarity over brevity.
    - Keep functions and methods small and focused.
    - Avoid repeating logic; prefer shared helpers/utilities.
    - Remove unused variables, imports, code paths, and files.

    ## 2. Naming Conventions

    Use descriptive names. Avoid abbreviations unless well-known.

    | Item            | Convention           | Example            |
    |-----------------|----------------------|--------------------|
    | Variables       | `lower_snake_case`   | `buffer_size`      |
    | Functions       | `lower_snake_case()` | `read_file()`      |
    | Constants       | `UPPER_SNAKE_CASE`   | `MAX_RETRIES`      |
    | Types/Structs   | `PascalCase`         | `FileHeader`       |
    | File Names      | `lower_snake_case`   | `file_reader.c`    |

    ## 3. Formatting Rules

    - Indentation: **4 spaces**
    - Line length: **max 100 characters**
    - Encoding: **UTF-8**, no BOM
    - End files with a newline

    ### Braces (example in C, adjust for your language)

        ```c
        if (condition) {
            do_something();
        } else {
            do_something_else();
        }
        ```

    ### Spacing

    - One space after keywords: `if (x)`, not `if(x)`
    - One blank line between top-level functions

    ## 4. Comments & Documentation

    - Explain *why*, not *what*, unless intent is unclear.
    - Keep comments up-to-date as code changes.
    - Public functions should include a short description of purpose and parameters.

    Recommended tags:

        ```text
        TODO: follow-up work
        FIXME: known incorrect behavior
        NOTE: non-obvious design decision
        ```

    ## 5. Error Handling

    - Handle error conditions explicitly.
    - Avoid silent failures; either return errors or log them appropriately.
    - Clean up resources (files, memory, handles) before returning on failure.

    ## 6. Commit & Review Practices

    ### Commits
    - One logical change per commit.
    - Write clear commit messages:

        ```text
        Short summary (max ~50 chars)
        Optional longer explanation of context and rationale.
        ```

    ### Reviews
    - Keep pull requests reasonably small.
    - Be respectful and constructive in review discussions.
    - Address requested changes or explain if you disagree.

    ## 7. Tests

    - Write tests for new functionality.
    - Tests should be deterministic (no randomness without seeding).
    - Prefer readable test cases over complex test abstraction.

    ## 8. Changes to This Guide

    Style evolves.
    Propose improvements by opening an issue or sending a patch updating this document.
    ```
text
    ```markdown

    # 风格指南

    本文档定义了本项目使用的编码风格与约定。所有贡献都应遵循这些规则,除非另有说明。

    ## 1. 通用代码风格

    - 优先考虑清晰性而非简洁性。
    - 保持函数和方法小巧且聚焦单一职责。
    - 避免重复逻辑;优先使用共享工具/辅助函数。
    - 删除未使用的变量、导入、代码路径和文件。

    ## 2. 命名约定

    使用描述性名称。除非是广为人知的缩写,否则避免使用缩写。

    | 项            | 约定               | 示例               |
    |-----------------|----------------------|--------------------|
    | 变量            | `lower_snake_case`   | `buffer_size`      |
    | 函数            | `lower_snake_case()` | `read_file()`      |
    | 常量            | `UPPER_SNAKE_CASE`   | `MAX_RETRIES`      |
    | 类型/结构体     | `PascalCase`         | `FileHeader`       |
    | 文件名          | `lower_snake_case`   | `file_reader.c`    |

    ## 3. 格式规则

    - 缩进:**4个空格**
    - 行长度:**最多100个字符**
    - 编码:**UTF-8**,无BOM
    - 文件末尾保留空行

    ### 大括号(以C语言为例,可根据语言调整)

        ```c
        if (condition) {
            do_something();
        } else {
            do_something_else();
        }
        ```

    ### 空格

    - 关键字后保留一个空格:`if (x)`,而非`if(x)`
    - 顶层函数之间保留一个空行

    ## 4. 注释与文档

    - 解释*为什么*,而非*是什么*,除非意图不明确。
    - 代码变更时同步更新注释。
    - 公共函数应包含对用途和参数的简短描述。

    推荐标签:

        ```text
        TODO: 后续待处理工作
        FIXME: 已知的错误行为
        NOTE: 非直观的设计决策
        ```

    ## 5. 错误处理

    - 显式处理错误条件。
    - 避免静默失败;要么返回错误,要么适当记录错误。
    - 失败返回前清理资源(文件、内存、句柄)。

    ## 6. 提交与审查实践

    ### 提交
    - 每次提交对应一个逻辑变更。
    - 编写清晰的提交信息:

        ```text
        简短摘要(最多约50个字符)
        可选的详细说明,解释背景和理由。
        ```

    ### 审查
    - 保持拉取请求的规模合理。
    - 审查讨论中保持尊重和建设性。
    - 处理要求的变更,或解释不同意的原因。

    ## 7. 测试

    - 为新功能编写测试。
    - 测试应具有确定性(无随机行为,除非设置了种子)。
    - 优先选择可读性强的测试用例,而非复杂的测试抽象。

    ## 8. 本指南的变更

    编码风格会不断演进。
    可通过提交issue或发送补丁来提出改进建议,更新本文档。
    ```