### Install Docker Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/pre-commit-hooks.md Provides instructions to install Docker, noting that the process varies by OS. Verify the installation with `docker --version`. ```bash # Install Docker (varies by OS) # See: https://docs.docker.com/get-docker/ # Verify installation docker --version ``` -------------------------------- ### Install Thai-Lint and Dependencies Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/publishing-checklist.md Sets up a Python virtual environment, installs Thai-Lint from PyPI, and verifies the installation by checking the version. ```bash # Create virtual environment python3 -m venv .venv source .venv/bin/activate # Install thailint from PyPI pip install thailint # Verify installation thailint --version ``` -------------------------------- ### Install Dependencies Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/AGENTS.md Use this command to install all necessary project dependencies before development or testing. ```bash # Install dependencies just install ``` -------------------------------- ### Install Pre-commit Framework with Pip Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/pre-commit-hooks.md Install the pre-commit framework using pip. Verify the installation by checking the version. ```bash # Using pip pip install pre-commit # Or using pip3 pip3 install pre-commit # Verify installation pre-commit --version ``` -------------------------------- ### Install Thai-Lint from Source Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/deployment-modes.md Clone the repository and install Thai-Lint in editable mode. ```bash # From source git clone https://github.com/YOUR_USERNAME/thai-lint.git cd thai-lint pip install -e . ``` -------------------------------- ### Configure Logging Early in Python Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/print-statements-linter.md Set up basic logging configuration at the start of your project to avoid accumulating print statements later. This example shows how to configure the root logger. ```python # logging_config.py import logging logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) ``` -------------------------------- ### Install Thai Lint from Source Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/cli-reference.md Clone the Thai Lint repository and install it from the source code. ```bash git clone https://github.com/be-wise-be-kind/thai-lint.git cd thai-lint pip install -e . ``` -------------------------------- ### Local Development Setup Commands Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/ai-doc-standard.md Commands to start and verify local development infrastructure for event-driven messaging. Includes Docker Compose for services and cURL commands to check their status. ```bash # Start infrastructure docker-compose up -d rabbitmq schema-registry prometheus grafana # Verify services curl http://localhost:15672 # RabbitMQ Management UI (guest/guest) curl http://localhost:8081 # Schema Registry curl http://localhost:3000 # Grafana # Set environment variables export RABBITMQ_URL=amqp://localhost:5672 export SCHEMA_REGISTRY_URL=http://localhost:8081 ``` -------------------------------- ### Install and Configure Pre-commit Hooks Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/publishing-checklist.md Installs the `pre-commit` framework and sets up a configuration file (`.pre-commit-config.yaml`) to run Thai-Lint's nesting check as a system hook. Installs the git hooks. ```bash # Install pre-commit framework pip install pre-commit # Create pre-commit config cat > .pre-commit-config.yaml << 'EOF' repos: - repo: local hooks: - id: thailint-nesting name: Check nesting depth entry: thailint nesting --config .thailint.yaml language: system files: \\.py$ EOF # Install hooks pre-commit install # Test hooks pre-commit run --all-files # Should detect nesting violations ``` -------------------------------- ### Set PYTHONPATH for Examples Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/cli-reference.md Ensure PYTHONPATH is set correctly to run thai-lint examples. ```bash export PYTHONPATH=/path/to/thai-lint python examples/basic_usage.py ``` -------------------------------- ### Install and Test Package in Clean Environment Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/releasing.md Create a new virtual environment, install the package from the local build, and test its CLI and library functionality. ```bash # Create clean virtual environment python -m venv /tmp/test-thailint-env source /tmp/test-thailint-env/bin/activate # Install from local build pip install dist/thailint-*.whl # Test CLI works thailint --help thailint --version # Test library import python -c "from thailint import Linter; print('Library import works')" # Test file-placement linter thailint lint file-placement --help # Deactivate and cleanup deactivate rm -rf /tmp/test-thailint-env ``` -------------------------------- ### Install Thai Lint from Source Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/index.md Clone the repository and install Thai Lint with development dependencies from the source code. ```bash # Clone repository git clone https://github.com/be-wise-be-kind/thai-lint.git cd thai-lint # Install dependencies pip install -e ".[dev]" ``` -------------------------------- ### Install and Test Pre-commit Hooks Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/pre-commit-hooks.md Quickly install the pre-commit framework, git hooks, and run an initial test across all files. ```bash # 1. Install pre-commit framework pip install pre-commit # 2. Install git hooks pre-commit install pre-commit install --hook-type pre-push # 3. Test it works pre-commit run --all-files ``` -------------------------------- ### Install and Run Thai-Lint Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/lazy-ignores-linter.md Install the thailint package and run it on the src/ directory to check for lazy ignores. ```bash pip install thailint thailint lazy-ignores src/ ``` -------------------------------- ### Install Thai-Lint from Source Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/troubleshooting.md Use this command when the PyPI package is not yet published or if you need to install directly from the repository. ```bash git clone https://github.com/be-wise-be-kind/thai-lint.git cd thai-lint pip install -e ".[dev]" ``` -------------------------------- ### Install Pre-commit Framework Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/pre-commit-hooks.md Installs the pre-commit framework using pip. This is a prerequisite for using pre-commit hooks. ```bash pip install pre-commit # or pip3 install pre-commit ``` -------------------------------- ### thailint Configuration Example (.thailint.yaml) Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/examples/README.md Example of a thailint configuration file in YAML format, specifying rules and their parameters like 'allow' and 'deny' lists for file placement. ```yaml rules: file-placement: allow: - ".*\.py$" deny: - ".*test.*\.py$" ``` -------------------------------- ### Install thailint from Source with pip Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/getting-started.md Clone the repository and install thailint using pip in editable mode. Suitable for development. ```bash git clone https://github.com/YOUR_USERNAME/thai-lint.git cd thai-lint pip install -e . ``` -------------------------------- ### Install and Run Stateless Class Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/stateless-class-linter.md Install the thailint package and run the linter on your source code directory. ```bash pip install thailint thailint stateless-class src/ ``` -------------------------------- ### Install thailint Library Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/deployment-modes.md Install the thailint package using pip. This is the same command as for the CLI. ```bash # Same as CLI pip install thailint ``` -------------------------------- ### Install Poetry Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/pre-commit-hooks.md Installs the Poetry dependency manager using a curl script or pip. Verify the installation with `poetry --version`. ```bash # Install Poetry curl -sSL https://install.python-poetry.org | python3 - # Or using pip pip install poetry # Verify installation poetry --version ``` -------------------------------- ### Install thailint from Source with Poetry Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/getting-started.md Clone the repository and install thailint using Poetry. This method is for development or custom builds. ```bash git clone https://github.com/YOUR_USERNAME/thai-lint.git cd thai-lint poetry install ``` -------------------------------- ### thailint Configuration Example (.thailint.json) Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/examples/README.md Example of a thailint configuration file in JSON format, defining rules and their settings. This is an alternative to the YAML configuration. ```json { "rules": { "file-placement": { "allow": [".*\.py$"], "deny": [".*test.*\.py$"] } } } ``` -------------------------------- ### Install and Run Version Freshness Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/version-freshness-linter.md Install the thailint package and run the version-freshness linter on the current directory. ```bash pip install thailint thailint version-freshness . ``` -------------------------------- ### Test Various Installation Methods Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/releasing.md Tests installing the package using different package managers and containerization. This confirms compatibility across various deployment scenarios. ```bash # Test pip install pip install thailint # Test Poetry install poetry add thailint # Test Docker pull (if published) docker pull washad/thailint:X.Y.Z ``` -------------------------------- ### Install and Run thailint Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/blocking-async-linter.md Install the thailint package and run it against your source code to detect blocking operations in async functions. ```bash pip install thailint thailint blocking-async src/ ``` -------------------------------- ### Install Git Hooks Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/pre-commit-hooks.md Installs the pre-commit git hooks for the current repository. Use `--hook-type pre-push` to also install hooks for the push event. ```bash pre-commit install pre-commit install --hook-type pre-push ``` -------------------------------- ### Install Thai-Lint from PyPI Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/publishing-checklist.md Installs the Thai-Lint package from the Python Package Index (PyPI) into the active virtual environment. It can install the latest version or a specific version. ```bash # Install from PyPI pip install thailint # Or install specific version VERSION=$(grep '^version = ' pyproject.toml | cut -d'"' -f2) pip install "thailint==$VERSION" ``` -------------------------------- ### Install and Run Performance Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/performance-linter.md Install the thailint package and run the performance linter on your source code directory. ```bash pip install thailint thailint perf src/ ``` -------------------------------- ### Alternative Pre-commit Framework Installation Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/pre-commit-hooks.md Install the pre-commit framework using alternative package managers like Homebrew or conda. ```bash # Using Homebrew (macOS) brew install pre-commit # Using conda conda install -c conda-forge pre-commit ``` -------------------------------- ### Install and Run SRP Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/srp-linter.md Install the thailint package and run the SRP linter on your source code directory. ```bash pip install thailint thailint srp src/ ``` -------------------------------- ### Install Thai-Lint with Poetry Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/troubleshooting.md Recommended for development environments, this command installs Thai-Lint and its development dependencies using Poetry. ```bash git clone https://github.com/be-wise-be-kind/thai-lint.git cd thai-lint poetry install ``` -------------------------------- ### Complete SRP Linter Configuration Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/srp-linter.md A comprehensive example combining language-specific thresholds, default settings, and keyword detection for the SRP linter. ```yaml srp: enabled: true # Language-specific thresholds python: max_methods: 8 max_loc: 200 typescript: max_methods: 10 max_loc: 250 javascript: max_methods: 10 max_loc: 225 rust: max_methods: 8 max_loc: 200 # Default for other languages max_methods: 8 max_loc: 200 # Keyword detection check_keywords: true keywords: - Manager - Handler - Processor - Utility - Helper ``` -------------------------------- ### Install and Run Collection Pipeline Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/collection-pipeline-linter.md Install the thailint package and run the linter on your source code directory. ```bash pip install thailint thailint pipeline src/ ``` -------------------------------- ### Install and Run Thai-Lint Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/print-statements-linter.md Install the thailint package using pip and run it on your source directory to check for print statements. ```bash pip install thailint thailint print-statements src/ ``` -------------------------------- ### Install and Run File Header Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/file-header-linter.md Install the thailint package and run it on a source directory to check for missing file header fields. ```bash pip install thailint thailint file-header src/ ``` -------------------------------- ### Initialize Development Environment Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/CONTRIBUTING.md Clone the repository, navigate to the directory, and run the initialization command. This sets up the project and its dependencies. ```bash git clone https://github.com/be-wise-be-kind/thai-lint.git cd thai-lint just init ``` -------------------------------- ### Get Prefix Method Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/method-property-linter.md Methods with a 'get_' prefix that return an instance attribute are flagged for potential property conversion. ```python def get_name(self): return self._name ``` -------------------------------- ### Install and Run Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/method-property-linter.md Install the thailint package and run it on your source code directory to detect method-property violations. ```bash pip install thailint thailint method-property src/ ``` -------------------------------- ### Get Published Version from pyproject.toml Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/publishing-checklist.md Retrieves the current version number from the pyproject.toml file. This is used to construct the PyPI URL and specify the version for installation. ```bash # Get published version VERSION=$(grep '^version = ' pyproject.toml | cut -d'"' -f2) ``` -------------------------------- ### Dummy Project Setup for Integration Test Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/publishing-checklist.md Creates a sample Python project structure, including source files, test files, and a README. Initializes a Git repository for the project. ```bash # Create project structure mkdir -p ~/test-thailint-integration cd ~/test-thailint-integration mkdir -p src tests docs touch README.md # Create sample Python files cat > src/main.py << 'EOF' """Main application module.""" def main(): """Entry point for the application.""" print("Hello, World!") if __name__ == "__main__": main() EOF cat > src/utils.py << 'EOF' """Utility functions.""" def process_items(items): """Process a list of items with complex nesting.""" results = [] for item in items: if item: try: if item.startswith("test"): if len(item) > 10: results.append(item.upper()) except AttributeError: pass return results EOF cat > tests/test_main.py << 'EOF' """Tests for main module.""" from src.main import main def test_main(): """Test main function.""" main() # Should run without errors EOF # Initialize git git init git add . git commit -m "Initial commit" ``` -------------------------------- ### Verify Development Setup Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/CONTRIBUTING.md After initialization, run these commands to ensure your development environment is correctly set up and all checks pass. ```bash just test just lint-full just format ``` -------------------------------- ### Initial Thai-Lint DRY Configuration Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/dry-linter.md Example of initial Thai-Lint configuration for the DRY linter. It's recommended to start with permissive thresholds and gradually reduce them. ```yaml # Initial configuration dry: enabled: true min_duplicate_lines: 5 # Start higher min_occurrences: 3 # Require more occurrences ``` -------------------------------- ### Thai-Lint Violation Example: get_* Methods Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/method-property-linter.md Demonstrates Python code where methods starting with 'get_' are used instead of @property, violating the linter's rules. ```python class User: def __init__(self, name, email): self._name = name self._email = email def get_name(self): # Violation return self._name def get_email(self): # Violation return self._email ``` -------------------------------- ### Configure `ignore` list for example and benchmark files Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md Add directories like `examples/`, `benches/`, and `tests/` to the `ignore` list in the linter configuration to prevent flagging code within them. ```yaml # Problem - ignore list does not include the directory unwrap-abuse: ignore: [] # Solution - add directories to ignore list unwrap-abuse: ignore: - "examples/" - "benches/" - "tests/" ``` -------------------------------- ### Example Version Freshness Linter Output Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/version-freshness-linter.md Example output from the version-freshness linter indicating an end-of-life version and a suggestion for an upgrade. ```text Dockerfile:1 [ERROR] version-freshness.eol-version: python 3.8 has reached end of life (EOL: 2024-10-14) Suggestion: Upgrade to 3.13 ``` -------------------------------- ### Ignore DRY Violation (TypeScript) Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/how-to-ignore-violations.md Example of ignoring a 'dry' violation in TypeScript. This is useful when code duplication is intentional for test readability, making setup explicit. ```typescript // thailint: ignore[dry] - Intentional duplication for test readability test('validates email', () => { // Repeated setup code that's clearer when explicit }); ``` -------------------------------- ### Set up LBYL check in GitHub Actions Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/lbyl-linter.md Integrate the LBYL linter into your GitHub Actions workflow. This example shows how to install `thailint` and run the LBYL check on your source code. ```yaml name: Lint on: [push, pull_request] jobs: lbyl-check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install thailint run: pip install thailint - name: Check for LBYL patterns run: thailint lbyl src/ ``` -------------------------------- ### Ignore Example Files Configuration Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/clone-abuse-linter.md Configuration to add directories like 'examples/', 'benches/', and 'tests/' to the ignore list, preventing clones within these paths from being flagged. ```bash # Problem: examples/ not in ignore list # Solution: Add to ignore paths clone-abuse: ignore: - "examples/" - "benches/" - "tests/" ``` -------------------------------- ### Distributed Tracing with OpenTelemetry Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/ai-doc-standard.md Example of using distributed tracing to track an event's lifecycle through the system. It starts a span, logs success or error status, and finishes the span. ```typescript const span = tracer.startSpan('process-order-created', { childOf: extractSpanContext(event.metadata.traceId), tags: { 'event.id': event.eventId, 'event.type': event.eventType, 'service.name': 'notification-service', }, }); try { await processEvent(event); span.setTag('status', 'success'); } catch (error) { span.setTag('status', 'error'); span.setTag('error', true); span.log({ 'error.message': error.message }); throw error; } finally { span.finish(); } ``` -------------------------------- ### Linter Filter: Safe Prefix Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/law-of-demeter-linter.md Illustrates a chain that is allowed by the 'Safe prefix' filter, which permits access to attributes or methods starting with common prefixes like 'self.', 'cls.', or 'this.'. ```python self.db.query() ``` -------------------------------- ### Google Python Style Module Docstring Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/ai-doc-standard.md Example of a module-level docstring following Google's Python style guide. It includes a brief description of the module's purpose and its main functionalities. ```python """Module for processing payments. This module contains classes and functions for handling payment processing operations including validation, authorization, and settlement of transactions. """ ``` -------------------------------- ### GitHub Actions Workflow for DRY Check Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/dry-linter.md Integrates Thai-Lint's DRY check into a GitHub Actions workflow. This setup runs on push and pull request events, installs the linter, performs the check, and uploads the report as an artifact. ```yaml name: DRY Check on: [push, pull_request] jobs: dry-lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install thailint run: pip install thailint - name: Check for duplicate code run: thailint dry --format json src/ > dry-report.json - name: Upload report uses: actions/upload-artifact@v3 if: always() with: name: dry-report path: dry-report.json ``` -------------------------------- ### Excessive Nesting Depth Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/validation-findings.md Demonstrates deep code nesting (13 levels) within a Python function, involving loops, branches, and conditional logic. Deep nesting significantly increases cognitive complexity and is discouraged by coding style guides. ```python def decode_line(self, line: str) -> Text: for plain_text, sgr, osc in _ansi_tokenize(line): # depth 1 if plain_text: # depth 2 append(plain_text, self.style or None) elif sgr is not None: # depth 2 codes = [...] for code in iter_codes: # depth 3 if code == 0: # depth 4 self.style = _Style.null() elif code == 38: # depth 4 with suppress(StopIteration): # depth 5 color_type = next(iter_codes) if color_type == 5: # depth 6 self.style += _Style.from_color( from_ansi(next(iter_codes)) ) elif color_type == 2: # depth 6 self.style += _Style.from_color( # depth 7+ from_rgb( next(iter_codes), next(iter_codes), next(iter_codes), ) ) ``` -------------------------------- ### Thai Lint Configuration Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/version-freshness-linter.md An example of how to configure the `version-freshness` linter in a `.thailint.yaml` file. It shows how to enable the linter and control its behavior regarding end-of-life and outdated versions, cache settings, and file ignores. ```yaml version-freshness: enabled: true # Flag end-of-life versions (default: true) check_eol: true # Flag non-latest supported versions (default: false, stricter) check_outdated: false # Cache refresh interval in hours (default: 24) cache_ttl_hours: 24 # Files/patterns to ignore ignore: - "Dockerfile.legacy" - "tests/**" - ".github/workflows/compat-test.yml" ``` -------------------------------- ### Verify Thai Lint Installation Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/cli-reference.md Check the installed version of the thailint CLI to confirm successful installation. ```bash thailint --version ``` -------------------------------- ### Example .thailint.yaml Configuration Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/quick-reference/plugin-guide.html Demonstrates how to configure a lint rule in .thailint.yaml, including global settings and language-specific overrides for thresholds. ```yaml # .thailint.yaml my-rule: enabled: true threshold: 5 python: threshold: 3 # Stricter for Python typescript: threshold: 7 # More lenient for TypeScript ``` -------------------------------- ### Check Thai-Lint Installation with pip Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/troubleshooting.md Verify if Thai-Lint is installed in your Python environment by listing installed packages and filtering for 'thai-lint'. ```bash pip list | grep thai-lint ``` -------------------------------- ### Complete Linter Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/api-reference.md A full example demonstrating how to initialize the Linter, run it with specific rules, and report any violations found. This script exits with a non-zero status code if violations are detected. ```python from src import Linter from pathlib import Path def lint_project(): """Lint entire project with file placement rules.""" # Initialize linter linter = Linter(config_file='.thailint.yaml') # Lint project violations = linter.lint('.', rules=['file-placement']) # Report results if violations: print(f"Found {len(violations)} violations:\n") for v in violations: print(f" {v.file_path}") print(f" Rule: {v.rule_id}") print(f" Message: {v.message}") print(f" Severity: {v.severity.name}") print() return 1 # Exit code for violations else: print("No violations found!") return 0 # Success if __name__ == "__main__": import sys sys.exit(lint_project()) ``` -------------------------------- ### thailint High-Level API Initialization and Linting Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/examples/README.md Demonstrates initializing the Linter with a configuration file or project root, and then linting a directory or a single file with all or specific rules. ```python from src import Linter # Initialize linter = Linter(config_file='.thailint.yaml') linter = Linter(project_root='/path/to/project') # Lint violations = linter.lint('src/') # All rules violations = linter.lint('src/', rules=['file-placement']) # Specific rules violations = linter.lint('file.py') # Single file ``` -------------------------------- ### Split Configuration and Logic: Before - FilePlacementLinter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/srp-linter.md Demonstrates a class that handles both configuration loading and business logic, violating SRP. ```python class FilePlacementLinter: # 33 methods, 382 LOC - Violation def load_config(self): pass def validate_config(self): pass def check_pattern(self): pass def check_directory(self): pass def check_global(self): pass # ... 28 more methods ``` -------------------------------- ### Install `tree-sitter-rust` for AST-based Rust detection Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md Ensure `tree-sitter-rust` is installed for accurate AST-based detection of Rust code. Without it, the analyzer may not report any results. ```bash # Check that tree-sitter-rust is installed python -c "import tree_sitter_rust; print('OK')" # Check that the file is detected as Rust thailint unwrap-abuse --verbose src/main.rs ``` -------------------------------- ### CI/CD Integration Examples Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/cli-reference.md Shows how to integrate Thai-Lint into CI/CD pipelines like GitHub Actions, Jenkins, and Azure Pipelines for automated checks. ```bash # GitHub Actions / GitLab CI thai-lint file-placement . --format json > lint-report.json if [ $? -ne 0 ]; then echo "Linting failed - see lint-report.json" exit 1 fi ``` ```bash # Jenkins thai-lint file-placement --config .thailint.yaml . || exit 1 ``` ```bash # Azure Pipelines thai-lint file-placement --format json . | tee lint-report.json test ${PIPESTATUS[0]} -eq 0 ``` -------------------------------- ### Verify Thai-Lint Installation Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/deployment-modes.md Check the installed version of Thai-Lint. ```bash # Verify thai-lint --version ``` -------------------------------- ### Test PyPI Installation with Virtual Environment Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/publishing-checklist.md This script validates PyPI installation by creating a temporary virtual environment, installing the 'thailint' package, and checking its version. It cleans up the environment afterward. ```bash #!/bin/bash # validate-publication.sh set -e echo "Validating thai-lint publication..." # Test PyPI installation python3 -m venv /tmp/test-env source /tmp/test-env/bin/activate pip install thailint thailint --version deactivate rm -rf /tmp/test-env echo "PyPI validation passed" ``` -------------------------------- ### CLI Usage: With Configuration File Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/stringly-typed-linter.md Specify a configuration file to use for linting. ```bash # Use config file thailint stringly-typed --config .thailint.yaml src/ ``` -------------------------------- ### Rust Error Propagation Example (Good) Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md Shows idiomatic Rust error handling using the `?` operator to propagate errors, avoiding panics. ```rust fn load_config() -> Result> { let file = File::open("config.toml")?; let contents = std::io::read_to_string(file)?; let config = toml::from_str(&contents)?; Ok(config) } ``` -------------------------------- ### thailint Direct Linter Import Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/examples/README.md Shows how to directly import and use a specific linter, such as file_placement, with custom configuration. This is useful for targeted linting. ```python from src.linters import file_placement config = {"allow": [r".*\.py$"]} violations = file_placement.lint(Path("src/"), config) ``` -------------------------------- ### Install Thai-Lint Package Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/cli-reference.md Install the thai-lint package in editable mode if the command is not found. ```bash # Solution 2: Install package pip install -e . thai-lint --help ``` -------------------------------- ### Rust Unwrap Abuse Example (Bad) Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md Demonstrates incorrect usage of `.unwrap()` which can lead to runtime panics if the `Result` is an `Err`. ```rust fn load_config() -> Config { let file = File::open("config.toml").unwrap(); let contents = std::io::read_to_string(file).unwrap(); toml::from_str(&contents).unwrap() } ``` -------------------------------- ### Rust Code Examples for Unwrap Abuse Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md These examples demonstrate how the linter identifies .unwrap() calls in different contexts. Calls within #[test] functions or #[cfg(test)] modules are skipped by default, while calls in production code are flagged as violations. ```rust // Skipped - inside #[test] function #[test] fn test_parsing() { let result = parse("input").unwrap(); // OK in tests assert_eq!(result, expected); } // Skipped - inside #[cfg(test)] module #[cfg(test)] mod tests { fn helper() { let val = compute().unwrap(); // OK in test modules } } // Flagged - production code fn process_request(input: &str) -> Response { let data = parse(input).unwrap(); // VIOLATION build_response(data) } ``` -------------------------------- ### Verify thailint installation Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/getting-started.md Check the installed version of thailint by running the version command. ```bash thai-lint --version ``` -------------------------------- ### Standard Unwrap Abuse Linter Configuration Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md The default configuration for the unwrap-abuse linter. It enables the linter, allows unwraps in tests and with .expect(), and ignores common directories like examples, benches, and tests. ```yaml unwrap-abuse: enabled: true allow_in_tests: true allow_expect: true ignore: - "examples/" - "benches/" - "tests/" ``` -------------------------------- ### Acceptable Unwrap and Expect Usage in Tests and Specific Cases Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md Provides examples of code where .unwrap() and .expect() are considered acceptable. This includes usage within test functions (when `allow_in_tests` is true) and .expect() calls with messages when `allow_expect` is true (the default). ```rust // Test code - OK (allow_in_tests: true) #[test] fn test_parsing() { let result = parse("valid input").unwrap(); assert_eq!(result.value, 42); } // Test module - OK (allow_in_tests: true) #[cfg(test)] mod tests { use super::*; #[test] fn test_connection() { let conn = connect("localhost").unwrap(); assert!(conn.is_alive()); } } // .expect() with message - OK (allow_expect: true, default) fn init() { let logger = Logger::init().expect("Logger must initialize"); } ``` -------------------------------- ### GitHub Actions with SARIF Upload for Code Scanning Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md Integrates the unwrap abuse linter into GitHub Actions, generating SARIF output for code scanning. This workflow includes steps to install thailint, run the check, and upload the SARIF results to GitHub. ```yaml name: Lint on: [push, pull_request] jobs: unwrap-abuse-check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install thailint run: pip install thailint - name: Check for unwrap abuse run: | thailint unwrap-abuse --format sarif src/ > unwrap-abuse.sarif continue-on-error: true - name: Upload SARIF results uses: github/codeql-action/upload-sarif@v2 with: sarif_file: unwrap-abuse.sarif ``` -------------------------------- ### GitHub Actions CI/CD Integration Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md Set up a GitHub Actions workflow to automatically check for unwrap abuse on push and pull request events. This snippet installs the thailint package and runs the unwrap-abuse check on the src/ directory. ```yaml name: Lint on: [push, pull_request] jobs: unwrap-abuse-check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Install thailint run: pip install thailint - name: Check for unwrap abuse run: | thailint unwrap-abuse src/ ``` -------------------------------- ### Pre-commit Hook Configuration Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/unwrap-abuse-linter.md Configure a pre-commit hook to automatically check for unwrap abuse in Rust files before committing. This setup uses a local repository hook that executes the thailint unwrap-abuse command. ```yaml # .pre-commit-config.yaml repos: - repo: local hooks: - id: unwrap-abuse-check name: Check for unwrap abuse in Rust entry: thailint unwrap-abuse language: python types: [rust] pass_filenames: true ``` -------------------------------- ### Verify Git Hooks Installation Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/pre-commit-hooks.md Verifies that the pre-commit and pre-push hooks have been installed in the .git/hooks directory. ```bash ls -la .git/hooks/pre-commit .git/hooks/pre-push ``` -------------------------------- ### Example Lazy Ignore Output Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/lazy-ignores-linter.md This is an example of the output produced by thailint when it detects an unjustified suppression. ```text src/utils.py:45:20 - Unjustified suppression: # noqa: PLR0912 To fix, add entry to file header Suppressions section: Suppressions: - PLR0912: [Your justification here] IMPORTANT: Suppression requires human approval. Do not add without explicit permission from a human reviewer. ``` -------------------------------- ### Multi-project Setup with Docker Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/deployment-modes.md Lint different projects using Docker, mounting each project's directory as the workspace. Allows for project-specific configurations. ```bash # Lint project A docker run --rm -v ~/projects/project-a:/workspace \ washad/thailint lint file-placement /workspace # Lint project B with different config docker run --rm -v ~/projects/project-b:/workspace \ washad/thailint lint file-placement --config /workspace/.thailint.yaml /workspace ``` -------------------------------- ### Configure Logging Level at Application Startup (Python) Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/improper-logging-linter.md Demonstrates how to configure the logging level (DEBUG or INFO) based on a verbose flag at the application's startup. This is useful for controlling the amount of log output. ```python import logging def configure_logging(verbose: bool): level = logging.DEBUG if verbose else logging.INFO logging.basicConfig( level=level, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) ``` -------------------------------- ### Python Docstring Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/file-header-linter.md Example of a Python function docstring that might be flagged if not a file header. ```python # Problem def parse_date(date_str: str) -> datetime: """Parse date from format YYYY-MM-DD.""" # False positive ``` -------------------------------- ### Use Configuration File Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/collection-pipeline-linter.md Specify a configuration file for linting rules. ```bash # Use config file thailint pipeline --config .thailint.yaml src/ ``` -------------------------------- ### Run Thai-Lint from Project Root Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/troubleshooting.md Demonstrates the correct and incorrect ways to run Thai-Lint based on your current directory. Running from the project root ensures configuration files are found. ```bash # Wrong - running from parent of project cd /home/user/Projects thailint magic-numbers my-project/src/ # Config won't be found! # Correct - run from project root cd /home/user/Projects/my-project thailint magic-numbers src/ # Config will be found # OR use explicit config thailint magic-numbers --config /path/to/.thailint.yaml src/ ``` -------------------------------- ### JSON Output Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/cli-reference.md Example of JSON output detailing nesting violations, suitable for programmatic parsing. ```json { "violations": [ { "file_path": "src/processor.py", "line_number": 15, "rule_id": "nesting.excessive-depth", "message": "Function 'process_data' has nesting depth 5 (max: 3)", "severity": "ERROR" }, { "file_path": "src/handler.py", "line_number": 42, "rule_id": "nesting.excessive-depth", "message": "Function 'handle_request' has nesting depth 4 (max: 3)", "severity": "ERROR" } ], "total": 2 } ``` -------------------------------- ### Python Code Comment Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/file-header-linter.md Example of a Python code comment describing concurrent behavior that should be rephrased. ```python # Problem - describing concurrent behavior """ Overview: Handles currently active connections... """ ``` -------------------------------- ### Python Module Docstring Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/file-header-linter.md Example of a Python module docstring with purpose, scope, and overview fields. ```python """ Purpose: Description here Scope: Scope description Overview: Multi-line overview with continuation indentation """ ``` -------------------------------- ### Install and Run Thai Lint with Docker Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/index.md Pull the latest Thai Lint image from Docker Hub and run the CLI tool. ```bash # Pull from Docker Hub docker pull washad/thailint:latest # Run CLI docker run --rm washad/thailint:latest --help ``` -------------------------------- ### Example Linter Output Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/file-header-linter.md This is an example of the output generated by the file header linter when mandatory fields are missing. ```text src/utils.py:1 - Missing mandatory field: Purpose src/utils.py:1 - Missing mandatory field: Overview ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/CONTRIBUTING.md Examples illustrating the Conventional Commits format for different types of changes. ```markdown feat(linters): Add collection pipeline linter for Python fix(cli): Correct SARIF output schema version docs: Update linter acceptance criteria ``` -------------------------------- ### CLI Options Help Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/file-header-linter.md Display help message showing available CLI options and their descriptions. ```bash Options: -c, --config PATH Path to config file -f, --format [text|json|sarif] Output format --recursive / --no-recursive Scan directories recursively --help Show this message and exit ``` -------------------------------- ### Using Multiple Thai-Lint Configs Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/cli-reference.md Demonstrates how to specify different configuration files for Thai-Lint, such as development, production, and test configurations. ```bash # Development config thai-lint file-placement --config .thailint.dev.yaml . ``` ```bash # Production config thai-lint file-placement --config .thailint.prod.yaml . ``` ```bash # Test config thai-lint file-placement --config .thailint.test.yaml tests/ ``` -------------------------------- ### Use a Configuration File Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/getting-started.md Configure Thai-Lint rules by creating a `.thailint.yaml` file in your project root. Then, specify the config file when running the linter. ```yaml rules: file-placement: allow: - ".*\\.py$" # Allow Python files deny: - "test_.*\\.py$" # Deny test files (should be in tests/) ignore: - "__pycache__/" - "*.pyc" - ".venv/" ``` ```bash thai-lint file-placement . --config .thailint.yaml ``` -------------------------------- ### Specify Configuration File Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/quick-reference/cli-cheatsheet.html Use the --config or -c flag followed by the path to a specific configuration file. ```bash thailint --config path/to/.thailintrc.json ``` ```bash thailint -c path/to/.thailintrc.js ``` -------------------------------- ### CLI with Development Configuration Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/deployment-modes.md Use this command to run Thai-Lint with a development-specific configuration file via the command-line interface. ```bash thai-lint file-placement --config .thailint.dev.yaml . ``` -------------------------------- ### Install and Run DRY Linter Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/dry-linter.md Install the thailint package and run the DRY linter on your source code directory. ```bash pip install thailint thailint dry src/ ``` -------------------------------- ### AI Suppression Request Example Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/lazy-ignores-linter.md An example of how an AI assistant should request human approval before adding a suppression comment. ```text "I'm encountering a MyPy error on line 45. I've tried several approaches but cannot resolve it without a type: ignore. May I add a suppression with the justification 'Dynamic attribute from decorator'?" ``` -------------------------------- ### Create and Activate Fresh Virtual Environment Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/publishing-checklist.md Sets up a new, isolated virtual environment for testing PyPI installations. This ensures that the test is not affected by existing packages or configurations. ```bash # Create fresh virtual environment python3 -m venv /tmp/test-thailint-pypi source /tmp/test-thailint-pypi/bin/activate ``` -------------------------------- ### Example Linter Output Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/method-property-linter.md This is an example of the output you might see from the method-property linter, indicating a method that should be converted to a property. ```text src/models.py:45 - Method 'get_full_name' should be a @property Suggestion: Replace 'def get_full_name(self):' with '@property def full_name(self):' ``` -------------------------------- ### Thai-Lint Development Setup with Docker Compose Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/getting-started.md Configure Docker Compose to run Thai-Lint, mounting the current directory and setting a default command to lint. ```yaml version: '3.8' services: linter: image: washad/thailint:latest volumes: - .:/workspace command: lint file-placement /workspace ``` -------------------------------- ### CLI with Production Configuration Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/deployment-modes.md Execute Thai-Lint with a strict production configuration file using the command-line interface. ```bash thai-lint file-placement --config .thailint.prod.yaml . ``` -------------------------------- ### Show Configuration in YAML Format Source: https://github.com/be-wise-be-kind/thai-lint/blob/main/docs/cli-reference.md Validate and display the current thai-lint configuration in YAML format. ```bash thai-lint config show --format yaml ```