226 lines
14 KiB
Markdown
226 lines
14 KiB
Markdown
# STYLE.md
|
||
|
||
> ### Normative Requirement Levels (RFC 2119 / RFC 8174)
|
||
> The key words **MUST**, **MUST NOT**, **REQUIRED**, **SHALL**, **SHALL NOT**, **SHOULD**, **SHOULD NOT**, **RECOMMENDED**, **NOT RECOMMENDED**, **MAY**, and **OPTIONAL** in this document are to be interpreted as described in [BCP 14](https://www.rfc-editor.org/info/bcp14) ([RFC 2119](https://www.rfc-editor.org/rfc/rfc2119.txt) and [RFC 8174](https://www.rfc-editor.org/rfc/rfc8174.txt)) when, and only when, they appear in all capitals, as shown here.
|
||
|
||
---
|
||
|
||
## 1. Universal Formatting & Merge Request Optimization
|
||
|
||
1. **Merge Request Context & Narrow-Line Formatting**:
|
||
- Code, configuration, and data MUST be structured to maximize human readability and minimize line noise during diff and merge request reviews.
|
||
- Long lines and complex expressions MUST be broken across multiple lines rather than collapsed into dense single-line statements (e.g., compound `if` conditions testing multiple criteria, nested data structures, long parameter lists).
|
||
- Splitting expressions across dedicated lines ensures that future diffs highlight the exact changed variable or condition rather than obscuring edits in the middle of a wide line.
|
||
2. **File Granularity & Concise Sizing**:
|
||
- Files SHOULD remain compact, focused, and single-purpose in languages and configuration formats that support modular decomposition.
|
||
- Monolithic files MUST be decomposed into cohesive, logically grouped sub-components.
|
||
3. **Deterministic Lexicographical Sorting**:
|
||
- Where the order of code blocks, dictionary keys, variable definitions, exports, or lists does not affect semantic execution or program logic, items MUST be sorted alphabetically/lexicographically.
|
||
- Consistent sorting guarantees deterministic diffs and prevents spurious ordering conflicts during parallel merges.
|
||
|
||
---
|
||
|
||
## 2. Defensive Syntax & Error-Exposing Idioms
|
||
|
||
1. **Compile-Time & Static Error-Exposing Constructs**:
|
||
- Code MUST be written using defensive syntax idioms that turn common typos or logical accidents into immediate compile-time or static analysis errors.
|
||
2. **Constant-First Comparisons (Yoda Conditions)**:
|
||
- In languages where assignment within conditional expressions is syntactically valid (e.g., C, C++, PHP, Java, Perl), equality comparisons MUST place the constant or literal on the left-hand side:
|
||
- Preferred: `if (1 == variable)` or `if (NULL == ptr)`
|
||
- Prohibited: `if (variable = 1)` accidental assignment bugs.
|
||
- Placing the literal first causes accidental single-equal assignments (`1 = variable`) to immediately fail compilation or linting rather than executing undetected.
|
||
|
||
---
|
||
|
||
## 3. Ansible & YAML Formatting Standards
|
||
|
||
1. **Native YAML Syntax & Multiline Arguments**:
|
||
- Module parameters MUST use native YAML key-value mapping over legacy `key=value` inline shorthand strings.
|
||
- Every parameter MUST reside on its own line to ensure concise git diffs and visual clarity during reviews.
|
||
2. **Mandatory Explicit Task & Play Naming**:
|
||
- Every play, task, and block MUST include a descriptive, human-readable `name:` string stating its explicit intent.
|
||
3. **Deterministic Variable & Key Ordering**:
|
||
- Dictionary keys, task arguments, and variable lists MUST be sorted alphabetically unless a specific execution order is functionally required.
|
||
4. **Jinja2 Spacing & Quoting Integrity**:
|
||
- Jinja2 delimiters MUST have consistent inner single-space padding: `{{ variable_name }}` (not `{{variable_name}}`).
|
||
- YAML values starting with template delimiters MUST always be explicitly quoted (`"{{ var }}"`) to prevent parser syntax errors.
|
||
|
||
---
|
||
|
||
## 4. OpenTofu & Terraform Standards
|
||
|
||
1. **Standardized Formatting & Indentation**:
|
||
- All HCL code MUST be formatted using standard 2-space indentation (enforced via `tofu fmt` / `terraform fmt`).
|
||
2. **Deterministic Attribute & Block Sorting**:
|
||
- Attributes inside resources, data sources, locals, and variable blocks MUST be sorted alphabetically where evaluation order is order-independent.
|
||
- Meta-arguments (`count`, `for_each`, `lifecycle`, `depends_on`, `provider`) SHOULD appear in a standardized order (meta-arguments at the top, followed by sorted resource arguments, with `lifecycle` and `depends_on` at the bottom).
|
||
3. **Mandatory Documentation Attributes**:
|
||
- Every `variable` and `output` declaration MUST include an explicit `description` string explaining its purpose, expected format, and constraints.
|
||
4. **Multiline Collection Declarations**:
|
||
- Maps, lists, and complex objects MUST be formatted across multiple lines with trailing commas on list/map elements to ensure clean, one-line diffs when elements are appended.
|
||
|
||
---
|
||
|
||
## 5. JSON Formatting Standards
|
||
|
||
1. **Strict 2-Space Indentation**:
|
||
- All JSON files MUST be formatted with 2-space indentation and a terminating newline.
|
||
2. **Deterministic Key Sorting**:
|
||
- Keys in JSON objects MUST be sorted alphabetically unless document schemas require specific positional ordering.
|
||
3. **Multiline Formatting for Objects & Arrays**:
|
||
- JSON objects and arrays containing multiple items MUST be expanded across multiple lines. Single-line minification is restricted to binary release artifacts only.
|
||
|
||
---
|
||
|
||
## 6. Rust Standards (Systems & Kernel Rust)
|
||
|
||
1. **Standardized Formatting (`rustfmt`)**:
|
||
- Code MUST be formatted with 4-space indentation adhering to the standard `rustfmt` rules.
|
||
2. **Explicit Error Propagation & Prohibition of Panics**:
|
||
- Production code and kernel/system modules MUST NOT use `.unwrap()` or `.expect()` on fallible operations.
|
||
- Errors MUST be propagated explicitly using `Result<T, E>`, `Option<T>`, or custom error types with the `?` operator.
|
||
3. **Safe Rust Default & Explicit Unsafe Auditing**:
|
||
- All code MUST be `#![deny(unsafe_code)]` by default.
|
||
- When `unsafe` blocks are strictly required (e.g., FFI, kernel drivers, memory-mapped I/O), every `unsafe` block MUST include an explicit `// SAFETY:` explanatory comment proving memory safety invariants.
|
||
4. **Deterministic Import & Module Sorting**:
|
||
- `use` declarations MUST be sorted alphabetically and grouped: `std` / `core` / `alloc` -> external crates -> internal modules.
|
||
|
||
---
|
||
|
||
## 7. Systems Programming, Kernel & eBPF Standards (C, C++, Assembly, eBPF)
|
||
|
||
1. **Indentation & Block Formatting**:
|
||
- Userland C/C++ MUST use 4-space indentation.
|
||
- Linux Kernel modules, drivers, and low-level subsystem source files MUST follow the Linux Kernel Coding Style (8-character tabs, K&R brace placement).
|
||
2. **Defensive Yoda Comparisons**:
|
||
- Equality comparisons against literals or constants MUST place the constant on the left: `if (0 == result)` and `if (NULL == ptr)`.
|
||
3. **Extended BPF / eBPF Standards**:
|
||
- eBPF C programs (`*.bpf.c`) MUST adhere to BPF CO-RE (Compile Once – Run Everywhere) conventions using `vmlinux.h`.
|
||
- BPF maps and license declarations (`SEC("license")`) MUST be explicitly named and placed at file boundaries.
|
||
4. **Assembly (ASM) & Linker Scripts (`.s`, `.S`, `.ld`, `.lds`)**:
|
||
- Assembly files MUST use standard tab alignment for labels, instructions, operands, and comments.
|
||
- Hardware register names and instruction mnemonics MUST be lowercase.
|
||
5. **Zero Compiler Warnings**:
|
||
- Userland code MUST compile cleanly under `-Wall -Wextra -Werror -Wpedantic` (or MSVC `/W4 /WX`). Kernel code MUST compile cleanly with zero sparse / static analysis warnings.
|
||
|
||
---
|
||
|
||
## 8. Build Systems, Grammars & Device Trees (Make, Kconfig, Bison/Flex, DTS)
|
||
|
||
1. **Makefiles & Kbuild (`Makefile`, `*.mk`, `Kconfig`, `Kbuild`)**:
|
||
- Recipe lines in Makefiles MUST be indented with literal tab characters (`\t`).
|
||
- Kconfig option declarations MUST be sorted logically with complete `help` documentation strings.
|
||
2. **Device Tree Source (`.dts`, `.dtsi`)**:
|
||
- DTS node names and properties MUST use standard 8-character tab indentation.
|
||
- Node labels MUST follow standard naming conventions (`node_name@unit_address`).
|
||
3. **Parser & Lexer Grammars (Bison `.y`, Flex `.l`)**:
|
||
- Grammars MUST use tab-indented production rules with explicit semantic error handlers (`yyerror`).
|
||
|
||
---
|
||
|
||
## 9. Shell & Scripting Standards (BASH, SH, KSH, CSH/TCSH, AWK, Sed)
|
||
|
||
1. **Strict Execution Header & Shebang**:
|
||
- **Bash**: `#!/usr/bin/env bash` with `set -euo pipefail`.
|
||
- **POSIX / Bourne Shell (`sh`)**: `#!/usr/bin/env sh` with `set -eu`.
|
||
- **Korn Shell (`ksh`)**: `#!/usr/bin/env ksh` with `set -e -u`.
|
||
- **C Shell / TC Shell (`csh` / `tcsh`)**: Scripts in CSH/TCSH are NOT RECOMMENDED for automation logic; if required for legacy shell environments, they MUST begin with `#!/bin/csh -f` or `#!/bin/tcsh -f` and check `$status` after every command.
|
||
2. **Defensive Variable Quoting & Modern Expansion**:
|
||
- Every variable expansion MUST be enclosed in double quotes (e.g., `"$target_dir"`, `"${items[@]}"`) to prevent field splitting and globbing.
|
||
- Command substitution in POSIX/Bash/Ksh MUST use standard `$()` syntax instead of legacy backticks (`` `...` ``).
|
||
3. **AWK & Sed Scripting Standards**:
|
||
- AWK scripts (`.awk`) MUST use 4-space indentation with explicit `BEGIN` and `END` blocks.
|
||
- Complex regular expressions in Sed/AWK MUST be documented with inline comments explaining matching groups.
|
||
4. **Deterministic Exit & Cleanup Traps**:
|
||
- Temporary files or resources created by a script MUST be cleaned up via an explicit `trap cleanup EXIT INT TERM` handler.
|
||
|
||
---
|
||
|
||
## 10. Perl Standards
|
||
|
||
1. **Strict Pragmas Mandate**:
|
||
- Every Perl script (`.pl`) and module (`.pm`) MUST explicitly enable strict mode and warnings at the top of the file:
|
||
```perl
|
||
#!/usr/bin/env perl
|
||
use strict;
|
||
use warnings;
|
||
use utf8;
|
||
```
|
||
2. **Formatting & Scoping**:
|
||
- Indentation MUST be 4 spaces.
|
||
- All variables MUST be lexically scoped using `my` (package variables `our` used only when strictly necessary).
|
||
- Global package variables (`$var`, `$@`) and direct typeglobs are prohibited.
|
||
3. **Subroutine Signatures**:
|
||
- Modern Perl subroutine signatures (`use feature 'signatures';`) SHOULD be used for explicit argument validation.
|
||
|
||
---
|
||
|
||
## 11. Python Standards
|
||
|
||
1. **PEP 8 Adherence & 4-Space Indentation**:
|
||
- All Python code MUST conform to PEP 8 standards with strict 4-space indentation.
|
||
2. **Mandatory Type Annotations (`typing`)**:
|
||
- All function signatures and module interfaces MUST declare complete static type hints (`typing` / Python 3.10+ union types `str | None`).
|
||
3. **Deterministic Import Sorting**:
|
||
- Imports MUST be sorted and grouped in standard order (Standard Library -> Third-Party -> Local) using tools like `isort` or `ruff`.
|
||
4. **Multiline Call & Data Formatting**:
|
||
- Dictionaries, lists, and multi-argument function calls MUST be formatted across multiple lines with trailing commas on multiline structures.
|
||
|
||
---
|
||
|
||
## 12. Enterprise & Compiled Languages (Java & Go)
|
||
|
||
1. **Java Standards**:
|
||
- Indentation MUST be 4 spaces.
|
||
- Class members and methods MUST be ordered: static constants -> member fields -> constructors -> public methods -> private methods.
|
||
- Constant-first equality checks: `"constant".equals(variable)` to eliminate `NullPointerException` risks.
|
||
2. **Go (Golang) Standards**:
|
||
- Code MUST be formatted strictly using standard `gofmt` (tab-based indentation).
|
||
- Error handling MUST be explicit and fail-fast: `if err != nil { return fmt.Errorf(...) }`.
|
||
- Struct field declarations and imports MUST be formatted and sorted via `goimports`.
|
||
|
||
---
|
||
|
||
## 13. Web & Backend Scripting (PHP)
|
||
|
||
1. **PSR-12 Extended Coding Style**:
|
||
- All PHP code MUST adhere strictly to PSR-12 formatting with 4-space indentation.
|
||
2. **Strict Typing Mandate**:
|
||
- Every PHP file MUST begin with `declare(strict_types=1);` immediately after `<?php`.
|
||
- All function parameters and return types MUST declare explicit types.
|
||
3. **Defensive Yoda Comparisons**:
|
||
- Use constant-first comparisons (`if (true === $flag)` or `if (null === $data)`).
|
||
|
||
---
|
||
|
||
## 14. Windows Scripting Standards (PowerShell & CMD)
|
||
|
||
1. **PowerShell (`.ps1`, `.psm1`) Standards**:
|
||
- Scripts MUST include `$ErrorActionPreference = 'Stop'` at the top to enforce fail-fast execution.
|
||
- Indentation MUST be 4 spaces.
|
||
- Use approved PowerShell verb-noun naming conventions for functions (e.g., `Get-Resource`, `Set-Configuration`).
|
||
- All parameters MUST be explicitly typed (`[string]$Path`, `[int]$Count`).
|
||
2. **Windows Command Script (`.bat`, `.cmd`) Standards**:
|
||
- CMD scripts MUST begin with `@echo off` and `setlocal enableextensions enabledelayedexpansion`.
|
||
- Explicitly check `%ERRORLEVEL%` after critical invocations: `if %ERRORLEVEL% neq 0 exit /b %ERRORLEVEL%`.
|
||
- Files MUST use Windows CRLF line endings as required by the Windows Command interpreter.
|
||
|
||
---
|
||
|
||
## 15. Accessible Code Formatting & Documentation Style
|
||
|
||
1. **Phonetic & Voice-Coding Naming Clarity**:
|
||
- Variable, function, task, and file names MUST be descriptive, pronounceable, and phonetically distinct.
|
||
- Avoid ambiguous single-character variables (except standard loop indices `i`, `j` where unavoidable), cryptic phonetic abbreviations, or homophones that impede speech-to-text dictation (e.g., Talon Voice) or screen-reader comprehension.
|
||
2. **Audio Cognitive Ergonomics & Spoken Phrasing**:
|
||
- Playbook task names and block descriptions MUST be written as concise, natural spoken sentences (e.g., `name: Ensure Apache Web Daemon Is Active and Enabled`).
|
||
- Configuration maps and data schemas SHOULD avoid nesting deeper than 4 levels to prevent auditory disorientation on speech synthesizers.
|
||
3. **Prohibition of Decorative Visual ASCII Art**:
|
||
- Purely visual ASCII art, boxed comment headers (`/*******************/`), decorative divider lines, and ASCII pseudo-diagrams are strictly prohibited.
|
||
- Code comments MUST use clean, natural phrasing without decorative punctuation noise that confuses screen readers and Braille displays.
|
||
4. **Semantic Documentation & Mandatory Alt Text**:
|
||
- Technical documentation and markdown files MUST use strict hierarchical heading levels (`#`, `##`, `###` in sequential order without skipping levels).
|
||
- All embedded diagrams, architecture flowcharts, and screenshots MUST include meaningful, descriptive `alt` text and plain textual summary descriptions.
|
||
5. **Editor Configuration (.editorconfig) Baseline**:
|
||
- All repository contributors and automation agents MUST respect `.editorconfig` rules across all supported languages.
|