Build a comprehensive code style guide with automated linter and formatter configurations covering naming conventions, file organization, error handling patterns, testing standards, and enforcement through CI/CD pipelines.
## ROLE You are a staff engineer who has established and maintained coding standards across engineering organizations with [TEAM SIZE: 10 to 200+] developers. You understand that a good style guide is not about personal preferences — it is about reducing cognitive load during code review, enabling faster onboarding, preventing entire categories of bugs through consistent patterns, and creating a codebase that reads as if one person wrote it. You know that rules without automated enforcement become suggestions that erode over time, so you pair every guideline with a linter rule, formatter configuration, or CI check. You have navigated the political challenge of introducing style guides to teams with strong individual preferences, and you know how to build consensus by focusing on the objective benefits of consistency rather than subjective aesthetic preferences. ## OBJECTIVE Create a comprehensive code style guide and automated tooling configuration for a [LANGUAGE: TypeScript / JavaScript / Python / Java / Go / Rust / C# / Ruby / PHP / Kotlin] project using [FRAMEWORK: React / Next.js / Express / Django / Flask / Spring Boot / Gin / Rails / Laravel / .NET]. The team has [EXPERIENCE: mostly junior developers / mixed seniority / mostly senior developers]. The project type is [TYPE: web application / API service / library or SDK / CLI tool / mobile app / monorepo with multiple packages]. The current state of code consistency is [STATE: no standards exist / informal conventions / partial linting / comprehensive but outdated]. ## TASK: COMPLETE STYLE GUIDE & LINTER CONFIGURATION ### Section 1 — Formatting & Syntax Rules Define the automated formatting rules that eliminate all debates about whitespace, brackets, and syntax style. Configure [FORMATTER: Prettier / Black / gofmt / rustfmt / clang-format / dotnet-format / rubocop] with these specific settings: indentation using [INDENT: 2 spaces / 4 spaces / tabs] consistently across all file types, maximum line length of [LENGTH: 80 / 100 / 120] characters with clear rules for how to break long lines (break before operators, one argument per line for long function calls, continuation indent), semicolons [SEMICOLONS: always / never / ASI-safe only] for JavaScript and TypeScript, quote style [QUOTES: single / double] with consistent exceptions for strings containing the quote character, trailing commas [COMMAS: all / es5 / none] with the recommendation to use trailing commas everywhere they are syntactically valid to reduce diff noise, brace style [BRACES: same line / next line / K&R] for control structures and function definitions, and import sorting order with groups separated by blank lines: built-in modules first, then external dependencies, then internal aliases, then relative imports. Generate the exact configuration file content for the formatter that can be copied directly into the project root. Include the editor configuration in .editorconfig format to ensure basic formatting consistency regardless of individual editor choice. Define the git hooks configuration using [TOOL: husky + lint-staged / pre-commit / lefthook] that runs the formatter on staged files before every commit, preventing unformatted code from ever entering the repository. ### Section 2 — Linter Rules & Static Analysis Configure [LINTER: ESLint / Pylint + Flake8 + mypy / golangci-lint / Clippy / SonarQube / RuboCop / PHPStan] with rules organized by severity. Error-level rules catch bugs and must never be disabled without a documented exception: no unused variables or imports, no unreachable code, no implicit any types in TypeScript, no empty catch blocks that swallow errors silently, no console.log or print statements in production code (use a proper logger), no hardcoded secrets or credentials patterns, no unsafe type assertions without validation, and no direct DOM manipulation in framework components. Warning-level rules enforce consistency and should be fixed in new code but do not block commits in existing code during migration: maximum function length of [LENGTH: 30-50] lines as a signal to extract helper functions, maximum file length of [LENGTH: 200-400] lines as a signal to split modules, maximum cyclomatic complexity of [COMPLEXITY: 10-15] per function, consistent return types (no mixing explicit and implicit returns), consistent error handling patterns (always use custom error classes, never throw strings), and documentation requirements for exported functions and classes. Define [NUMBER: 5-10] custom lint rules specific to your project's architecture: enforce that API handlers always use the error wrapper function, require that database queries go through the repository layer rather than being inlined in handlers, enforce that environment variables are accessed only through the config module, require that test files follow the naming convention, and prevent importing from internal modules of sibling packages in a monorepo. Generate the complete linter configuration file with comments explaining the rationale for each non-default rule. ### Section 3 — Naming Conventions & Code Organization Define the naming conventions for every code element with examples. Variables and functions use [CASE: camelCase / snake_case / PascalCase] with these specific patterns: boolean variables start with is, has, should, or can (isVisible, hasPermission, shouldRetry), array variables use plural nouns (users, orderItems, validationErrors), functions that return booleans follow the same prefix pattern, functions that transform data use a fromX or toX pattern (fromDTO, toResponse, parseConfig), and async functions use explicit naming when the async behavior is non-obvious. Constants use [CASE: UPPER_SNAKE_CASE / PascalCase] and are defined in a dedicated constants file or co-located with their usage depending on scope. Classes and interfaces use PascalCase with these conventions: interfaces are not prefixed with I (use User not IUser) unless the team has established this convention, abstract classes may use a Base prefix (BaseRepository), implementation classes include their purpose (PostgresUserRepository), and type aliases describe the shape rather than the implementation. File naming follows [CONVENTION: kebab-case / camelCase / PascalCase / snake_case] with consistent patterns: component files match the component name, test files use the .test or .spec suffix, type definition files use the .types or .d suffix, constant files use the .constants suffix, and barrel export files are always named index. Directory structure follows [PATTERN: feature-based / layer-based / domain-driven] organization with a template showing the standard directory tree for a new feature including all expected files. ### Section 4 — Error Handling & Logging Standards Define the error handling patterns that ensure consistent, debuggable, and user-friendly error behavior across the entire codebase. Create a custom error class hierarchy: a base ApplicationError with code, message, statusCode, and isOperational fields, extending into specific categories like ValidationError, NotFoundError, AuthenticationError, AuthorizationError, ConflictError, ExternalServiceError, and RateLimitError. Each error class should include a unique error code string that can be used for monitoring alerts and client-side error handling. Define the error propagation rules: functions should throw typed errors rather than returning null or undefined for error cases, catch blocks should only catch errors they can handle meaningfully and re-throw everything else, error boundaries at the API layer should catch all errors and transform them into a consistent response format, and every catch block must log the error with appropriate context before handling it. Establish logging standards using [LIBRARY: winston / pino / bunyan / zerolog / slog / log4j / serilog]: define log levels (debug for development diagnostics, info for normal operations, warn for recoverable anomalies, error for failures requiring attention, fatal for unrecoverable failures), require structured logging with consistent fields (timestamp, requestId, userId, service, operation, duration, error), prohibit string interpolation in log messages (use structured fields instead so logs are searchable), and define the correlation ID pattern for tracing requests across services. Include [NUMBER: 3-5] concrete before-and-after examples showing poorly handled errors transformed into properly handled errors following these standards. ### Section 5 — Testing Standards & Conventions Define the testing standards that ensure tests are valuable, maintainable, and trustworthy. Specify the testing pyramid targets: [UNIT: 70-80]% of tests should be unit tests covering individual functions and classes in isolation, [INTEGRATION: 15-25]% should be integration tests covering module interactions and API endpoints with real dependencies, and [E2E: 5-10]% should be end-to-end tests covering critical user flows through the full application stack. Define the test file organization: test files live [LOCATION: adjacent to source files / in a separate test directory mirroring source structure], test fixtures and factories live in a shared test/fixtures or test/factories directory, and test utilities and custom matchers live in a test/helpers directory. Establish the test naming convention: describe blocks use the name of the module or function under test, nested describe blocks use context phrases starting with when or given, and it or test blocks use should phrases describing the expected behavior. Define what makes a good test: each test verifies exactly one behavior, tests are independent and can run in any order, tests do not depend on external services or network calls (use mocks and fixtures), test data is created within the test or in a factory function rather than relying on shared mutable state, and assertions use the most specific matcher available (toBe for primitives, toEqual for objects, toContain for arrays, toThrow for errors). Establish the mocking policy: mock external dependencies (HTTP clients, database drivers, file system, time), do not mock the module under test or its internal implementation details, prefer dependency injection over module-level mocking, and reset all mocks in afterEach to prevent test pollution. Define the coverage requirements and enforcement: minimum [COVERAGE: 80]% line coverage on all new code, coverage reports generated in CI and displayed in pull requests, and no PR merged if coverage drops below the threshold. Include a template for each test type showing the complete structure from imports through setup, execution, and assertions. ### Section 6 — CI Enforcement & Migration Strategy Design the CI pipeline that enforces every rule in this style guide automatically. The pipeline should run on every pull request and include these sequential stages: formatting check that runs the formatter in check mode and fails if any file would be reformatted, linting that runs the full linter configuration and fails on any error-level violation, type checking that runs the type checker in strict mode and fails on any type error, unit tests that run the full test suite and fail if any test fails or coverage drops below the threshold, and a build verification that compiles the full project and fails on any compilation warning treated as error. Configure the pipeline to post inline review comments on the PR for each violation, making it easy for developers to see exactly where the issues are without reading CI logs. For existing codebases with inconsistent style, define the migration strategy: run the formatter on the entire codebase in a single dedicated PR to establish the baseline, enable error-level linter rules immediately for all new code, create a tech debt backlog for existing warning-level violations with a target to resolve [PERCENTAGE: 10-20]% per sprint, use the lint-staged configuration to enforce rules only on changed files during the transition period, and track linting violation count over time in a dashboard to visualize progress. Include the exact CI configuration file for [PLATFORM: GitHub Actions / GitLab CI / CircleCI / Jenkins] with all stages defined, caching configured for dependencies and lint results, and appropriate timeout and retry settings.
Or press ⌘C to copy