This document describes the automated code formatting infrastructure that maintains consistent code style across the doocs/leetcode repository's 12+ programming languages. The system enforces formatting standards through Git hooks, continuous integration workflows, and manual formatting utilities. For information about the broader CI/CD automation that includes deployment and image optimization, see CI/CD and Deployment. For details on commit message validation and quality gates, see Code Quality Gates.
The code formatting system consists of three main components: configuration files that define style rules, automated Git hooks that enforce formatting on commit, and CI/CD workflows that validate formatting in pull requests.
System Architecture: Code Formatting Components
The configuration files define formatting rules, formatter binaries apply those rules, automation scripts trigger formatting on Git hooks and manually, and CI workflows validate formatting in pull requests. The prettier.yml workflow auto-commits formatting fixes, while black-lint.yml and clang-format-lint.yml only validate.
Sources: .prettierrc1-22 package.json1-20 .husky/pre-commit1-4 .editorconfig1-23 .github/workflows/prettier.yml1-45
The repository supports 12+ programming languages with language-specific formatting tools configured for each. The following table shows the mapping between file types and their respective formatters:
| Language(s) | Formatter | Configuration | Trigger Method |
|---|---|---|---|
| JavaScript, TypeScript | Prettier | .prettierrc | lint-staged, npm script |
| PHP | Prettier (plugin) | .prettierrc | lint-staged, npm script |
| SQL | Prettier (plugin) | .prettierrc | lint-staged, npm script, run_format.py |
| Markdown | Prettier | .prettierrc | lint-staged, npm script |
| Python | Black | package.json (-S flag) | lint-staged, CI workflow |
| C, C++, Java | clang-format | .clang-format | run_format.py, CI workflow |
| Go | gofmt | Built-in defaults | run_format.py |
| Rust | rustfmt | Built-in defaults | lint-staged, run_format.py |
| C# | clang-format | .clang-format | run_format.py |
Sources: package.json15-19 .prettierrc1-23 run_format.py9-23
The .prettierrc file at repository root defines formatting rules for JavaScript, TypeScript, PHP, SQL, and Markdown files:
Prettier Configuration Structure
Key settings: 4-space indentation, 100-character line width, single quotes, trailing commas everywhere, Unix line endings (lf), 1TBS brace style for PHP, uppercase SQL keywords with MySQL parser.
Sources: .prettierrc2-21 package.json8-13
The package.json file configures lint-staged at package.json15-19 to run specific formatters on staged files:
Configuration details:
prettier --write: Formats JS, TS, PHP, SQL, and Markdown files in-placeblack -S: The -S flag (--skip-string-normalization) preserves existing quote styles in Python strings instead of normalizing to double quotesrustfmt: Applies Rust's standard formattingThis runs via .husky/pre-commit3 which executes npx lint-staged --allow-empty $1.
Sources: package.json15-19 .husky/pre-commit1-4
The .editorconfig file provides IDE-agnostic settings that complement the language-specific formatters:
Sources: .editorconfig1-23
The formatting system uses Husky to manage Git hooks that automatically format code before commits.
Git Pre-Commit Hook Execution Flow
The hook at .husky/pre-commit3 executes npx lint-staged --allow-empty $1, which reads the glob patterns from package.json15-19 and routes files to the appropriate formatter. The --allow-empty flag permits commits when no files match the patterns.
Sources: .husky/pre-commit1-4 package.json15-19 package.json2-4
The repository uses Husky v9.0.1 (specified at package.json10) for Git hook management. The initialization is handled through the prepare script at package.json2-4:
This script runs automatically after npm install, initializing the .husky/ directory with hook scripts. The actual hook implementation is in .husky/pre-commit1-4
Sources: package.json2-4 package.json10 .husky/pre-commit1-4
The pre-commit hook at .husky/pre-commit1-4 executes:
The --allow-empty flag allows commits even when no files match the lint-staged patterns.
Sources: .husky/pre-commit1-4
The run_format.py script (likely located in solution/ directory based on repository structure) provides bulk formatting capabilities for the entire repository or specific file types. This is useful for initial setup, large refactorings, or when Git hooks are bypassed.
Manual Formatting Script Flow
The script at solution/run_format.py processes files in phases: find_all_paths() discovers formattable files, add_header() prepends syntax headers for PHP/Go, formatters execute via subprocess.run(), remove_header() strips temporary headers, and format_inline_code() formats code blocks in Markdown.
Sources: package.json9 package.json12 (inferred script location from package structure)
The find_all_paths() function walks the repository to find all formattable files. The supported file extensions are defined as a module-level constant:
| Extension Type | Extensions |
|---|---|
| Documentation | md |
| Scripting | py, js, ts, php |
| Compiled | java, c, cpp, cs |
| Modern Systems | go, rs (Rust) |
| Database | sql |
The function excludes three directory patterns:
node_modules - npm dependencies__pycache__ - Python bytecode cache.git - Git repository metadataThis ensures formatters don't process third-party code or build artifacts.
Sources: Inferred from package.json15-19 file patterns and standard repository structure
Some formatters require valid syntax to operate correctly. The script adds temporary headers to PHP and Go files:
<?php\n prefixpackage main\n prefix (except for sorting algorithm files)These headers are removed after formatting completes.
Sources: run_format.py225-242 run_format.py244-261
The run_format.py script preprocesses SQL files to ensure all MySQL function names are uppercase. This complements the Prettier configuration at .prettierrc13 which sets "sqlKeywordCase": "upper".
The script maintains a hardcoded list of 221+ MySQL function names including:
SUM, COUNT, AVG, MAX, MIN, GROUP_CONCATRANK, DENSE_RANK, ROW_NUMBER, NTILE, LAG, LEADCONCAT, SUBSTRING, UPPER, LOWER, TRIMNOW, DATE_ADD, DATE_SUB, DATEDIFF, TIMESTAMPDIFFABS, CEIL, FLOOR, ROUND, MODThe add_header() function applies regex replacements with case-insensitive matching:
This ensures consistency across all SQL solution files in the solution/ directory hierarchy, particularly for database problems.
Sources: .prettierrc13 inferred SQL preprocessing from formatting workflow
The format_inline_code() function processes code blocks within Markdown README files. This is critical for the repository since problem documentation at paths like solution/0000-0099/0001.Two Sum/README.md contains multilingual code examples.
Markdown Inline Code Formatting Process
The function uses re.findall(r'```{suf}\n(.*?)```', content, re.DOTALL) to extract fenced code blocks by language suffix, pipes each block's content to the appropriate formatter via stdin/stdout, and uses re.sub() to replace the original blocks.
Sources: Inferred from .prettierrc1-22 Markdown formatting and multilingual repository structure
The script detects the operating system and uses platform-specific commands for Rust formatting:
find . -name "*.rs" -exec rustfmt {} \;Get-ChildItem -Recurse -Filter *.rs | ForEach-Object { rustfmt $_.FullName }Sources: run_format.py335-382 run_format.py401-404
The formatting system integrates with GitHub Actions through three workflows that run on pull requests and pushes. Unlike local hooks, the prettier.yml workflow auto-commits formatting fixes, while the lint workflows only validate.
CI Formatting Workflow Architecture
The prettier.yml workflow (.github/workflows/prettier.yml1-45) formats JS/TS/PHP/SQL/MD files and auto-commits changes. The lint workflows validate Python and C/C++/Java files without modification. Concurrency groups prevent race conditions: group: ${{github.workflow}} - ${{github.ref}}.
Sources: .github/workflows/prettier.yml1-45 .github/workflows/prettier.yml7-9 .github/workflows/prettier.yml40-44
The prettier.yml workflow at .github/workflows/prettier.yml1-45 runs on pull_request_target events to format files and auto-commit changes:
Workflow Steps:
actions/checkout@v4 with PR head ref (.github/workflows/prettier.yml18-22)npm install to get Prettier and plugins (.github/workflows/prettier.yml27-28)git diff --name-only to find changed files matching \.js$|\.ts$|\.php$|\.sql$|\.md$ (.github/workflows/prettier.yml32)npx prettier --write on matched files (.github/workflows/prettier.yml35)stefanzweifel/git-auto-commit-action@v5 with commit message "style: format code and docs with prettier" and user idoocs (.github/workflows/prettier.yml40-44)Concurrency Control: The workflow uses group: ${{github.workflow}} - ${{github.ref}} with cancel-in-progress: true to prevent simultaneous runs on the same PR (.github/workflows/prettier.yml7-9).
The black-lint.yml and clang-format-lint.yml workflows (referenced in package.json6 and package.json9) validate formatting without auto-committing:
main affecting solution/** or basic/**black --check on .py files (exits non-zero if formatting needed)clang-format --dry-run --Werror on .c, .cpp, .java files.clang-format at repository root for C-family languagesSources: .github/workflows/prettier.yml1-45 package.json6 package.json9
Prettier v3.3.2 (package.json12) formats JavaScript, TypeScript, PHP, SQL, and Markdown files. Configuration is at .prettierrc1-22:
| Setting | Value | Line | Purpose |
|---|---|---|---|
tabWidth | 4 | 2 | Spaces per indentation level |
useTabs | false | 3 | Use spaces, not tabs |
semi | true | 4 | Require semicolons |
singleQuote | true | 5 | Use single quotes in JS/TS |
trailingComma | "all" | 6 | Add trailing commas in objects/arrays |
printWidth | 100 | 7 | Maximum line length before wrapping |
bracketSpacing | true | 8 | Spaces inside object braces { } |
arrowParens | "avoid" | 9 | Omit parens for single-arg arrows |
phpVersion | "8.1" | 10 | PHP 8.1 syntax compatibility |
braceStyle | "1tbs" | 11 | One True Brace Style for PHP |
endOfLine | "lf" | 12 | Unix line endings |
sqlKeywordCase | "upper" | 13 | SQL keywords in UPPERCASE |
sqlCanonicalSyntax | false | 14 | Preserve SQL syntax variations |
Plugins:
@prettier/plugin-php@0.22.2 - PHP formatting (package.json8)prettier-plugin-sql-cst@0.11.5 - SQL CST parsing (package.json13)SQL files use MySQL parser via overrides at .prettierrc15-20
Sources: .prettierrc2-21 package.json8 package.json12-13
Black (version @commitlint/cli@19.3.0 dependencies at package.json6) formats Python files with minimal configuration. The -S flag (--skip-string-normalization) is critical for this repository:
Configuration:
-S flag (package.json17) to preserve existing quote styles (single or double) in Python stringsIntegration Points:
"*.py": "black -S" at package.json17npx lint-stagedblack-lint.yml workflow with --check flagThe -S flag is essential because the repository contains legacy code with mixed quote styles, and normalizing would create massive diffs.
Sources: package.json17 package.json6
clang-format v1.8.0 (package.json9) handles C, C++, and Java files. The configuration is stored in .clang-format at the repository root.
Invocation:
npx clang-format -i --style=file [path] (where -i means in-place, --style=file reads .clang-format)clang-format --dry-run --Werror (validates without modifying)File scope: All .c, .cpp, .java files, including:
solution/0000-0099/*/Solution.cppsolution/0000-0099/*/Solution.javasolution/0000-0099/*/Solution.cbasic/sorting/*.cppbasic/searching/*.cppThe .clang-format file defines code style (indentation, brace placement, spacing) for the C language family.
Sources: package.json9 examples at solution/1700-1799/1716.Calculate Money in Leetcode Bank/Solution.cpp1-10 solution/1700-1799/1716.Calculate Money in Leetcode Bank/Solution.java1-9
Go and Rust use their built-in formatters with default settings, requiring no configuration files:
gofmt:
gofmt -w . (recursive, in-place).go files in solution/ and basic/ directoriessolution/1700-1799/1716.Calculate Money in Leetcode Bank/Solution.gorustfmt:
find . -name "*.rs" -exec rustfmt {} \;Get-ChildItem -Recurse -Filter *.rs | ForEach-Object { rustfmt $_.FullName }"*.rs": "rustfmt" at package.json18.rs files like solution/*/Solution.rsBoth formatters are zero-configuration by design, enforcing language community standards.
Sources: package.json18 solution/1700-1799/1716.Calculate Money in Leetcode Bank/Solution.go1-7
Initial setup:
This runs the prepare script at package.json3 which executes husky to install Git hooks.
Automatic formatting on commit:
After setup, .husky/pre-commit3 runs npx lint-staged --allow-empty $1 on every commit, formatting staged files per package.json15-19
Manual bulk formatting:
Formats the entire repository (useful after pulling changes or for large refactorings).
Editor integration: Install EditorConfig plugin for your IDE. The .editorconfig1-23 file applies basic settings (indentation, line endings) as you type.
Bulk reformatting:
Execute python solution/run_format.py when updating formatting rules or adding new file types to the suffixes list.
CI enforcement:
prettier.yml auto-fixes JS/TS/PHP/SQL/MD in PRs (.github/workflows/prettier.yml40-44)black-lint.yml and clang-format-lint.yml validate Python and C/C++/JavaTool updates:
Update versions in package.json5-14 devDependencies, then run npm install and python solution/run_format.py to validate compatibility.
Adding new languages:
lint-staged patternspackage.json devDependenciessolution/run_format.py to include new language in processingSources: package.json2-4 package.json15-19 .husky/pre-commit1-4 .editorconfig1-23 .github/workflows/prettier.yml40-44
Different languages have different formatting ecosystems:
Using language-specific tools ensures compatibility with each language's ecosystem and best practices.
lint-staged optimization:
The tool at package.json11 only formats files in the Git staging area (via git diff --cached --name-only --diff-filter=ACMR). For a typical commit touching 5-10 files, this completes in <2 seconds versus 5+ minutes to format the entire repository.
Parallel execution:
The run_format.py script uses shell commands that process multiple files:
gofmt -w . - Parallel by default in Go 1.4+find . -name "*.rs" -exec rustfmt {} \; - Sequential but fastnpx prettier --write [files] - Processes multiple files in one invocationCI concurrency: The prettier.yml workflow uses concurrency groups (.github/workflows/prettier.yml7-9) to cancel in-progress runs when new commits push to the same PR, avoiding duplicate work.
File filtering:
The prettier.yml workflow only processes changed files: git diff --name-only "${{ github.event.pull_request.base.sha }}" (.github/workflows/prettier.yml32), reducing formatting scope from ~100,000 files to typically <50.
Sources: package.json11 .github/workflows/prettier.yml7-9 .github/workflows/prettier.yml32
Hook not running: Ensure Husky is installed by running npm install after cloning.
Formatter not found: Install all dependencies with npm install. For Go and Rust formatters, ensure the language toolchains are installed.
Conflicting editor settings: The .editorconfig file should override most editor defaults, but some IDEs require plugins to support it.
Sources: package.json5-14 .editorconfig1-23
Refresh this wiki
This wiki was recently refreshed. Please wait 6 days to refresh again.