swiftlang/swift-format
Formatting technology for Swift source code
Healthy across the board
Permissive license, no critical CVEs, actively maintained — safe to depend on.
Has a license, tests, and CI — clean foundation to fork and modify.
Documented and popular — useful reference codebase to read through.
No critical CVEs, sane security posture — runnable as-is.
- ✓Last commit 2d ago
- ✓17 active contributors
- ✓Distributed ownership (top contributor 32% of recent commits)
Show 3 more →Show less
- ✓Apache-2.0 licensed
- ✓CI configured
- ✓Tests present
Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests
Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.
Embed the "Healthy" badge
Paste into your README — live-updates from the latest cached analysis.
[](https://repopilot.app/r/swiftlang/swift-format)Paste at the top of your README.md — renders inline like a shields.io badge.
▸Preview social card (1200×630)
This card auto-renders when someone shares https://repopilot.app/r/swiftlang/swift-format on X, Slack, or LinkedIn.
Onboarding doc
Onboarding: swiftlang/swift-format
Generated by RepoPilot · 2026-05-10 · Source
🤖Agent protocol
If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:
- Verify the contract. Run the bash script in Verify before trusting
below. If any check returns
FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding. - Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
- Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/swiftlang/swift-format shows verifiable citations alongside every claim.
If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.
🎯Verdict
GO — Healthy across the board
- Last commit 2d ago
- 17 active contributors
- Distributed ownership (top contributor 32% of recent commits)
- Apache-2.0 licensed
- CI configured
- Tests present
<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>
✅Verify before trusting
This artifact was generated by RepoPilot at a point in time. Before an
agent acts on it, the checks below confirm that the live swiftlang/swift-format
repo on your machine still matches what RepoPilot saw. If any fail,
the artifact is stale — regenerate it at
repopilot.app/r/swiftlang/swift-format.
What it runs against: a local clone of swiftlang/swift-format — the script
inspects git remote, the LICENSE file, file paths in the working
tree, and git log. Read-only; no mutations.
| # | What we check | Why it matters |
|---|---|---|
| 1 | You're in swiftlang/swift-format | Confirms the artifact applies here, not a fork |
| 2 | License is still Apache-2.0 | Catches relicense before you depend on it |
| 3 | Default branch main exists | Catches branch renames |
| 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code |
| 5 | Last commit ≤ 32 days ago | Catches sudden abandonment since generation |
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of swiftlang/swift-format. If you don't
# have one yet, run these first:
#
# git clone https://github.com/swiftlang/swift-format.git
# cd swift-format
#
# Then paste this script. Every check is read-only — no mutations.
set +e
fail=0
ok() { echo "ok: $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }
# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
echo "FAIL: not inside a git repository. cd into your clone of swiftlang/swift-format and re-run."
exit 2
fi
# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "swiftlang/swift-format(\\.git)?\\b" \\
&& ok "origin remote is swiftlang/swift-format" \\
|| miss "origin remote is not swiftlang/swift-format (artifact may be from a fork)"
# 2. License matches what RepoPilot saw
(grep -qiE "^(Apache-2\\.0)" LICENSE 2>/dev/null \\
|| grep -qiE "\"license\"\\s*:\\s*\"Apache-2\\.0\"" package.json 2>/dev/null) \\
&& ok "license is Apache-2.0" \\
|| miss "license drift — was Apache-2.0 at generation time"
# 3. Default branch
git rev-parse --verify main >/dev/null 2>&1 \\
&& ok "default branch main exists" \\
|| miss "default branch main no longer exists"
# 4. Critical files exist
test -f "Sources/SwiftFormat/API/SwiftFormatter.swift" \\
&& ok "Sources/SwiftFormat/API/SwiftFormatter.swift" \\
|| miss "missing critical file: Sources/SwiftFormat/API/SwiftFormatter.swift"
test -f "Sources/SwiftFormat/Core/Rule.swift" \\
&& ok "Sources/SwiftFormat/Core/Rule.swift" \\
|| miss "missing critical file: Sources/SwiftFormat/Core/Rule.swift"
test -f "Sources/SwiftFormat/Core/FormatPipeline.swift" \\
&& ok "Sources/SwiftFormat/Core/FormatPipeline.swift" \\
|| miss "missing critical file: Sources/SwiftFormat/Core/FormatPipeline.swift"
test -f "Sources/SwiftFormat/Core/LintPipeline.swift" \\
&& ok "Sources/SwiftFormat/Core/LintPipeline.swift" \\
|| miss "missing critical file: Sources/SwiftFormat/Core/LintPipeline.swift"
test -f "Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift" \\
&& ok "Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift" \\
|| miss "missing critical file: Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift"
# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 32 ]; then
ok "last commit was $days_since_last days ago (artifact saw ~2d)"
else
miss "last commit was $days_since_last days ago — artifact may be stale"
fi
echo
if [ "$fail" -eq 0 ]; then
echo "artifact verified (0 failures) — safe to trust"
else
echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/swiftlang/swift-format"
exit 1
fi
Each check prints ok: or FAIL:. The script exits non-zero if
anything failed, so it composes cleanly into agent loops
(./verify.sh || regenerate-and-retry).
⚡TL;DR
swift-format is a source code formatter and linter for Swift that parses Swift syntax trees (via SwiftSyntax) and applies configurable style transformations to normalize whitespace, indentation, bracket placement, and naming conventions. It powers the formatting engine in SourceKit-LSP and can be used as a standalone CLI tool or embedded as a Swift Package library to automatically reformat Swift code according to configurable rules. Monorepo structure: Sources/SwiftFormat/ is the main package split into API/ (public interface: SwiftFormatter.swift, SwiftLinter.swift, Configuration.swift) and Core/ (internal parsing/formatting logic). Plugins/ contains two Swift Package plugins: FormatPlugin and LintPlugin for build-time integration. Documentation/ holds configuration and development guides. Tests/ likely mirrors the source structure. CLI and plugins share the same underlying SwiftFormatter and SwiftLinter APIs.
👥Who it's for
Swift developers and teams who need automated code formatting and linting; IDE/LSP developers integrating formatting into Swift editing environments (like SourceKit-LSP); contributors to the Swift toolchain ecosystem who want a pluggable, testable formatting system rather than ad-hoc style scripts.
🌱Maturity & risk
Production-ready and actively maintained. The project has multi-version Swift support (5.7 through nightly main), comprehensive CI via GitHub Actions (.github/workflows/pull_request.yml, publish_release.yml), semantic versioning tied to SwiftSyntax versions (e.g., 508.0.0 for Swift 5.8), and integration as an official Swift project. It's a foundational component of SourceKit-LSP, signaling stable, relied-upon status.
Low risk for general use; main risks are Swift version coupling (SwiftSyntax major/minor versions must match toolchain for Swift <5.8, per README version table) and the caveat that 'no default Swift code style guidelines have yet been proposed'—meaning the rules are experimental and not officially standardized. Dependency on SwiftSyntax is tight but necessary; risk mitigated by modern CMake build system and separate test suite.
Active areas of work
Active maintenance on Swift version compatibility: .swiftci/ configs show testing on Swift 5.7–5.10 and nightly 6.0/main branches. GitHub Actions pipelines (auto_update_version.yml, automerge.yml) suggest automated versioning and PR merging. The project is tracking SwiftSyntax updates and ensuring parser changes are reflected in formatting rules.
🚀Get running
Clone and build with Swift Package Manager: git clone https://github.com/swiftlang/swift-format.git && cd swift-format && swift build. Verify with the Swift version you're using (match the README table). Run tests with swift test. For CLI use: swift run swift-format --help.
Daily commands:
swift build builds the formatter library and CLI. swift run swift-format <file> formats a file (or swift run swift-format --help for options). For Xcode integration: use the FormatPlugin target. For linting: swift run swift-format --lint mode (SwiftLinter API).
🗺️Map of the codebase
Sources/SwiftFormat/API/SwiftFormatter.swift— Primary public API entry point for formatting operations; all formatting requests flow through this interfaceSources/SwiftFormat/Core/Rule.swift— Base protocol defining the rule system architecture; all formatting and linting rules inherit from thisSources/SwiftFormat/Core/FormatPipeline.swift— Orchestrates the formatting execution pipeline; critical for understanding rule application order and precedenceSources/SwiftFormat/Core/LintPipeline.swift— Orchestrates the linting execution pipeline; mirrors FormatPipeline for lint rule applicationSources/SwiftFormat/PrettyPrint/PrettyPrint.swift— Core pretty-printing engine that transforms syntax trees into formatted source; handles whitespace and layout decisionsSources/SwiftFormat/Core/RuleRegistry+Generated.swift— Generated registry of all available rules; required to understand how rules are discovered and instantiatedPackage.swift— Swift Package Manager manifest defining dependencies (SwiftSyntax, ArgumentParser) and build configuration
🛠️How to make changes
Add a New Formatting Rule
- Create new rule file in Sources/SwiftFormat/Rules/ inheriting from SyntaxFormatRule (
Sources/SwiftFormat/Rules/DoNotUseSemicolons.swift) - Implement the required visit(_:) method to transform syntax nodes (
Sources/SwiftFormat/Core/SyntaxFormatRule.swift) - Run code generation to register rule in RuleRegistry and Pipelines (
Sources/SwiftFormat/Core/RuleRegistry+Generated.swift) - Update configuration file to expose rule options if needed (
Sources/SwiftFormat/API/Configuration.swift)
Add a New Linting Rule
- Create new rule file in Sources/SwiftFormat/Rules/ inheriting from SyntaxLintRule (
Sources/SwiftFormat/Rules/NeverForceUnwrap.swift) - Implement visit(_:) and emit findings using diagnose() helper (
Sources/SwiftFormat/Core/SyntaxLintRule.swift) - Rule automatically registers via code generation (
Sources/SwiftFormat/Core/RuleRegistry+Generated.swift) - Configure rule severity and categories in rule class definition (
Sources/SwiftFormat/API/Finding.swift)
Extend Configuration Options
- Add new option property to Configuration struct or nested type (
Sources/SwiftFormat/API/Configuration.swift) - Define default value in Configuration+Default.swift (
Sources/SwiftFormat/API/Configuration+Default.swift) - Update rules that need the option to read from context.configuration (
Sources/SwiftFormat/Core/Context.swift) - Update JSON schema export if needed via Configuration+Dump.swift (
Sources/SwiftFormat/API/Configuration+Dump.swift)
🔧Why these technologies
- SwiftSyntax — Provides syntax tree parsing and manipulation for Swift source code; as of Swift 5.8, parser is written in Swift enabling cross-platform compilation
- Rule-based architecture — Modular design allowing independent rule composition; rules can be selectively enabled/disabled via configuration without coupling
- Pretty Printing algorithm — Separates formatting logic from syntax tree traversal; enables complex whitespace and line-breaking decisions independent of rule implementation
- Pipeline pattern — Orchestrates sequential rule application with clear phase separation between parsing, transformation, and output generation
⚖️Trade-offs already made
-
Code generation for rule registry and pipelines
- Why: Eliminates need for runtime reflection; provides compile-time safety and type checking
- Consequence: Requires manual generation step after adding new rules; adds build complexity but improves performance
-
Immutable syntax tree transformations
- Why: Prevents accidental mutations and enables rule composition; each rule creates new tree
- Consequence: Higher memory usage during formatting; mitigated by single-pass pipeline design
-
Configuration as single strongly-typed struct
- Why: Type-safe configuration with compile-time defaults; easier than string-based maps
- Consequence: Requires recompilation to add options; documented in Configuration.swift as intended design
-
Separate FormatPipeline and LintPipeline
- Why: Linting and formatting have different semantics (emit findings vs. transform code)
- Consequence: Some rule logic duplication; justified by clearer separation of concerns
🚫Non-goals (don't propose these)
- Does not propose a default Swift style guideline (explicitly stated in README)
- Does not provide IDE integration directly (SourceKit-LSP is the integration layer)
- Does not guarantee formatting of syntactically invalid Swift code
- Does not support partial/incremental formatting of selected regions (operates on full source)
🪤Traps & gotchas
Swift version locking: for Swift ≤5.7, you must use the corresponding swift-format release branch (e.g., release/5.6 for Xcode 13.3); mismatched versions will fail to parse new syntax. The .swift-format config file at the repository root is both documentation and functional—it formats itself; ensure consistency. SwiftSyntax breaking changes can silently break custom formatting logic if you extend Core/; always check release notes. No default style is prescribed—teams must explicitly choose rules in their .swift-format file or accept the hardcoded defaults in Configuration+Default.swift.
🏗️Architecture
💡Concepts to learn
- Abstract Syntax Tree (AST) Visitor Pattern — swift-format walks the Swift syntax tree recursively to locate and transform nodes; understanding visitor pattern is essential to implement custom formatting rules in Core/
- Pretty Printing / Wadler Layout — swift-format uses layout algorithms to decide where to break lines and how to indent; Documentation/PrettyPrinter.md describes this approach
- Trivia (whitespace and comments preservation) — SwiftSyntax separates trivia (whitespace, comments) from syntax tokens; swift-format must manage trivia carefully to preserve comments while reformatting
- Configuration Schema and Validation — swift-format reads .swift-format YAML files and validates them; Configuration.swift implements schema enforcement critical for reproducible formatting
- Build Plugin Architecture (Swift Package Plugins) — Plugins/FormatPlugin and LintPlugin implement the SPM build plugin protocol, allowing IDE and build integration without forking the main codebase
- Version-Locked Dependency Management (SwiftSyntax coupling) — For Swift ≤5.7, swift-format version major.minor must match SwiftSyntax and the toolchain; this tight coupling is necessary but requires careful version coordination
- Finding and Categorization (Lint violations as structured data) — Sources/SwiftFormat/API/Finding.swift and FindingCategorizing.swift model lint violations as queryable objects; enables IDE integration and filtering of violations
🔗Related repos
swiftlang/swift-syntax— The foundational parser and AST library that swift-format depends on; understanding SwiftSyntax tree structure is essential for implementing new formatting rulesswiftlang/sourcekit-lsp— The Language Server Protocol implementation for Swift that uses swift-format as its formatting backend; a primary consumer of the SwiftFormatter APIapple/swift— The official Swift compiler repository; swift-format tracks language evolution and new syntax features from hereswiftlang/swift-evolution— Tracks Swift language proposals and design decisions that influence what formatting rules swift-format should supportrealm/SwiftLint— Complementary linting tool for Swift with overlapping (but distinct) rules; often used alongside swift-format for comprehensive code quality
🪄PR ideas
To work on one of these in Claude Code or Cursor, paste:
Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.
Add comprehensive test coverage for Configuration+Dump.swift
The repo has Configuration.swift and Configuration+Default.swift but no visible test file for Configuration+Dump.swift. This extension likely handles dumping configuration to various formats (YAML/JSON). Adding tests would ensure the dump functionality works correctly across different configuration scenarios and output formats.
- [ ] Create Tests/SwiftFormat/API/ConfigurationDumpTests.swift
- [ ] Add tests for dumping default configurations
- [ ] Add tests for dumping custom configurations with various rule options
- [ ] Add tests for round-trip: dump → parse → dump consistency
- [ ] Add tests for edge cases (empty configs, special characters in paths, etc.)
Add unit tests for FindingCategorizing.swift logic
The file Sources/SwiftFormat/API/FindingCategorizing.swift appears to handle categorization of linting findings, but there's no visible corresponding test file. This is critical for ensuring linting results are properly categorized and reported to users.
- [ ] Create Tests/SwiftFormat/API/FindingCategorizingTests.swift
- [ ] Add tests for categorizing different finding types
- [ ] Add tests for filtering findings by category
- [ ] Add tests for edge cases (duplicate findings, overlapping ranges)
- [ ] Add integration tests with actual linting pipeline
Create integration tests for the FormatPipeline and LintPipeline with real Swift code samples
The Core directory contains FormatPipeline.swift and LintPipeline.swift, but testing with actual Swift source code examples is essential. Adding a test suite with real-world Swift code snippets will catch regressions and ensure the pipelines work correctly with various syntax patterns.
- [ ] Create Tests/SwiftFormat/Core/PipelineIntegrationTests.swift
- [ ] Add test fixtures directory with Swift code samples (various syntax patterns)
- [ ] Test FormatPipeline with samples: enums, extensions, protocol conformances, closures, generics
- [ ] Test LintPipeline with samples to verify rules are applied correctly
- [ ] Add regression tests for any reported issues or edge cases from GitHub issues
🌿Good first issues
- Add comprehensive formatting rule tests for edge cases in Sources/SwiftFormat/Core/—examine existing test patterns and create exhaustive test coverage for a single rule (e.g., brace placement rules) that currently lacks tests.
- Extend Documentation/Configuration.md with concrete before/after code examples for each formatting rule option (currently many rules are documented but lack runnable examples showing the exact formatting change).
- Implement or improve error messages in Sources/SwiftFormat/API/SwiftFormatError.swift to include source location details (file, line, column) when formatting or configuration fails, matching modern IDE expectations.
⭐Top contributors
Click to expand
Top contributors
- @bnbarham — 32 commits
- @TTOzzi — 16 commits
- @rintaro — 15 commits
- @dependabot[bot] — 8 commits
- @ahoppen — 8 commits
📝Recent commits
Click to expand
Recent commits
4c86a1a— Merge pull request #1197 from bkhouri/revert-1195-revert-1156-t/main/gh_870_add_swift-format-ignore-file-support (rintaro)f285c12— Revert "Revert "Add support for .swift-format-ignore files"" (bkhouri)d981232— Revert "Add support for .swift-format-ignore files" (bkhouri)7ed8260— Merge pull request #1156 from bkhouri/t/main/gh_870_add_swift-format-ignore-file-support (rintaro)31eda7e— Add support for .swift-format-ignore files (bkhouri)b71b738— Bump the swiftlang-actions group across 1 directory with 3 updates (#1190) (dependabot[bot])68efc74— Improve error messages on invalid configuration files (#1184) (Wilfred)467b866— Add missing encoding for Configuration.multilineTrailingCommaBehavior (#1191) (li-bei)8edc4d5— Add group for swiftlang GitHub Actions (#1185) (shahmishal)e276f58— Correctly formatunsafewhen preceding aforloop pattern. (#1189) (allevato)
🔒Security observations
The swift-format codebase demonstrates good security practices overall. The project is a well-structured formatting tool with no obvious injection vulnerabilities, hardcoded secrets, or exposed credentials visible in the file structure. The codebase follows Swift best practices with appropriate separation of concerns (API, Core, Rules, PrettyPrint modules). Primary recommendations focus on ensuring dependency management is robust and CI/CD workflows follow security best practices. The inability to review Package.swift and workflow configurations prevents a higher security score.
- Low · Missing Package.swift Dependency Details —
Package.swift. The Package.swift file content was not provided for analysis. Unable to verify if dependencies are pinned to secure versions or if vulnerable packages are present. Fix: Provide Package.swift content for dependency analysis. Ensure all dependencies are pinned to specific versions and regularly updated to address security patches. - Low · Pre-commit Hooks Configuration —
.pre-commit-hooks.yaml. The .pre-commit-hooks.yaml file is present but its content was not provided. Pre-commit hooks could be misconfigured or point to untrusted sources. Fix: Review the pre-commit configuration to ensure all hooks are from trusted sources and properly validate code before commits. - Low · License Header Template Present —
.license_header_template. A .license_header_template file exists, which should be reviewed to ensure it doesn't contain sensitive information or incorrect licensing claims. Fix: Verify the license header template contains only appropriate licensing information and no embedded credentials or sensitive data.
LLM-derived; treat as a starting point, not a security audit.
👉Where to read next
- Open issues — current backlog
- Recent PRs — what's actively shipping
- Source on GitHub
Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.