### TripWire Use Case: Web Application Configuration Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Provides an example of configuring a web application using TripWire, including database URLs, cache settings, and security keys. ```python from tripwire import env # Database DATABASE_URL: str = env.require("DATABASE_URL", format="postgresql") # Redis cache REDIS_URL: str = env.optional("REDIS_URL", default="redis://localhost:6379") # Security SECRET_KEY: str = env.require("SECRET_KEY", secret=True, min_length=32) # API keys STRIPE_API_KEY: str = env.require("STRIPE_API_KEY", secret=True) ``` -------------------------------- ### Install and Verify TripWire (Bash) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/README.md Installs the TripWire Python package using pip and verifies the installation by checking the tool's version. Assumes pip is available in the environment. ```bash pip install tripwire-py tripwire --version ``` -------------------------------- ### Install from requirements.txt Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Installs all packages listed in the requirements.txt file, including TripWire if it's specified. ```bash pip install -r requirements.txt ``` -------------------------------- ### Install TripWire with Development Dependencies Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Installs TripWire in editable mode with development dependencies, suitable for contributors. Assumes the repository has been cloned and a virtual environment is active. ```bash pip install -e ".[dev]" ``` -------------------------------- ### Running Examples in Demo Mode Source: https://github.com/daily-nerd/tripwire/blob/main/examples/README.md Demonstrates the common pattern of using the `--demo` flag to test examples without requiring a full `.env` setup. This is useful for quick validation and testing of individual examples. ```bash python examples/basic/01_simple_require.py --demo python examples/advanced/01_range_validation.py --demo python examples/frameworks/fastapi_integration.py --demo ``` -------------------------------- ### Run README Example Tests with Pytest Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Commands to execute the Tripwire README example tests using the pytest framework. Includes options for verbose output and running specific test classes or methods. ```bash # Run all README example tests pytest tests/test_readme_examples.py # Run with verbose output pytest tests/test_readme_examples.py -v # Run specific test class pytest tests/test_readme_examples.py::TestProblemSection # Run specific test method pytest tests/test_readme_examples.py::TestProblemSection::test_database_url_none_split_raises_attribute_error ``` -------------------------------- ### Install TripWire using uv Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Installs the TripWire package using uv, a fast Python package installer and resolver. This method is recommended for speed. ```bash uv pip install tripwire-py ``` -------------------------------- ### Verify TripWire Installation Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Checks if TripWire is installed correctly by running its command-line interface and displaying the version. ```bash tripwire --version ``` -------------------------------- ### Run application with TripWire validation Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Executes a Python script that uses TripWire for environment variable validation. Shows an example error message when a required variable is missing. ```bash python config.py ``` -------------------------------- ### TripWire Error Example: Missing Variable Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Illustrates the error message displayed by TripWire when a required environment variable is not set or invalid. It provides suggestions for fixing the issue. ```text EnvironmentError: DATABASE_URL is required but not set Suggestions: 1. Add DATABASE_URL to your .env file 2. Set it as a system environment variable: export DATABASE_URL= 3. Check .env.example for expected format ``` -------------------------------- ### TripWire Use Case: CLI Application Configuration Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Shows how to configure a command-line interface (CLI) application using TripWire, including logging levels and output directories. ```python from tripwire import env # Configuration LOG_LEVEL: str = env.optional( "LOG_LEVEL", default="INFO", choices=["DEBUG", "INFO", "WARNING", "ERROR"] ) OUTPUT_DIR: str = env.optional("OUTPUT_DIR", default="./output") ``` -------------------------------- ### Define environment variables in .env file Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Example of how to define environment variables within the .env file. These variables are used by TripWire to configure your application. ```dotenv # .env DATABASE_URL=postgresql://localhost:5432/myapp API_KEY=sk-1234567890abcdef1234567890abcdef DEBUG=true PORT=8000 ``` -------------------------------- ### Initialize a TripWire Project (Bash) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/README.md Initializes a new TripWire project. This command sets up the basic structure for managing configuration and secrets within a project. ```bash tripwire init ``` -------------------------------- ### Install and Initialize Pre-commit Hooks Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/ci-cd-integration.md Commands to install the pre-commit package and initialize pre-commit hooks in the repository. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Add TripWire to requirements.txt Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Specifies the TripWire package and a minimum version in a requirements.txt file. This allows for reproducible installations. ```text tripwire-py>=0.4.1 ``` -------------------------------- ### CI Integration for README Tests (YAML) Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Shows how to integrate the README example tests into a GitHub Actions CI workflow. This ensures that documentation examples are automatically validated with every push. ```yaml # .github/workflows/ci.yml - name: Run README example tests run: pytest tests/test_readme_examples.py -v ``` -------------------------------- ### Install TripWire from PyPI Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Installs the TripWire package using pip. This is the standard method for installing Python packages from the Python Package Index (PyPI). ```bash pip install tripwire-py ``` -------------------------------- ### Clone TripWire Repository Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Clones the TripWire source code repository from GitHub. This is typically done for development or if you need to build from source. ```bash git clone https://github.com/Daily-Nerd/TripWire.git cd TripWire ``` -------------------------------- ### GitHub Actions Workflow for Environment Checks Source: https://github.com/daily-nerd/tripwire/blob/main/examples/cli_workflow.md An example GitHub Actions workflow that automates environment variable checks in a CI/CD pipeline. It installs TripWire, ensures `.env.example` is up-to-date, scans for secrets, and validates the environment structure before deployment. ```yaml name: Environment Checkon: [push, pull_request] jobs: env-check: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Python uses: actions/setup-python@v4 with: python-version: '3.11' - name: Install TripWire run: pip install tripwire - name: Check .env.example is up to date run: tripwire generate --check - name: Scan for secrets run: tripwire scan --strict - name: Validate environment structure run: | cp .env.example .env tripwire validate ``` -------------------------------- ### TripWire Use Case: Data Processing Configuration Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Illustrates configuring a data processing application with TripWire, covering API endpoints, authentication tokens, and processing parameters. ```python from tripwire import env # API credentials API_ENDPOINT: str = env.require("API_ENDPOINT", format="url") API_TOKEN: str = env.require("API_TOKEN", secret=True) # Processing settings BATCH_SIZE: int = env.optional("BATCH_SIZE", default=100, min_val=1) MAX_WORKERS: int = env.optional("MAX_WORKERS", default=4, min_val=1, max_val=32) ``` -------------------------------- ### Running Framework Examples (Server Mode) Source: https://github.com/daily-nerd/tripwire/blob/main/examples/README.md Illustrates how to run framework examples not just in demo mode (for validation) but also in actual server mode. This involves setting necessary environment variables like `DATABASE_URL` and `API_KEY` before executing the example script. ```bash # Demo mode - just validates config python examples/frameworks/fastapi_integration.py --demo # Server mode - actually starts the server export DATABASE_URL="postgresql://localhost/mydb" export API_KEY="your_api_key" python examples/frameworks/fastapi_integration.py ``` -------------------------------- ### TripWire Core Concepts: Required vs Optional Variables Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Compares the usage of `env.require()` for mandatory variables and `env.optional()` for variables with default values in TripWire. ```python # Required - fails if not set API_KEY = env.require("API_KEY") # Optional - uses default if not set DEBUG = env.optional("DEBUG", default=False, type=bool) ``` -------------------------------- ### Build and Publish Plugin to PyPI (Bash) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/plugin-development.md These bash commands guide you through building a Python package, uploading it to TestPyPI for testing, and finally publishing it to the main PyPI repository. Ensure you have `build` and `twine` installed. ```bash # Build package python -m build # Upload to TestPyPI first python -m twine upload --repository testpypi dist/* # Test installation pip install --index-url https://test.pypi.org/simple/ tripwire-http-config # Upload to PyPI python -m twine upload dist/* ``` -------------------------------- ### Verify TripWire Installation and Setup Source: https://github.com/daily-nerd/tripwire/blob/main/CONTRIBUTING.md Commands to verify the successful installation and setup of TripWire. Checks the CLI version, runs tests using pytest, and performs code style checks with Ruff and Black. ```bash # Test the CLI tripwire --version # Run tests pytest # Check code style ruff check . black . --check mypy src/tripwire ``` -------------------------------- ### Install TripWire using pipx Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Installs TripWire using pipx, which is useful for installing Python CLI applications globally without dependency conflicts. This makes the TripWire CLI available in your PATH. ```bash pipx install tripwire-py ``` -------------------------------- ### Create Project and Install TripWire (Bash) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md This snippet shows the bash commands to create a new project directory, set up a virtual environment, and install the TripWire Python package. It assumes Python 3.11+ is installed. Ensure you activate the virtual environment before proceeding. ```bash mkdir my-tripwire-app cd my-tripwire-app # Create virtual environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install TripWire pip install tripwire-py ``` -------------------------------- ### TripWire Core Concepts: Format Validation Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Demonstrates TripWire's capability to validate environment variables against specific formats like email, URL, and PostgreSQL connection strings. ```python # Email validation ADMIN_EMAIL: str = env.require("ADMIN_EMAIL", format="email") # URL validation API_URL: str = env.require("API_URL", format="url") # Database URL DATABASE_URL: str = env.require("DATABASE_URL", format="postgresql") ``` -------------------------------- ### Troubleshoot 'command not found: tripwire' Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Commands to check if TripWire is installed and to reinstall it if the CLI command is not found. This usually indicates a PATH issue or incomplete installation. ```bash # Check if installed correctly pip show tripwire-py # Reinstall pip install --force-reinstall tripwire-py ``` -------------------------------- ### Python: Test Untested Code Example Source: https://github.com/daily-nerd/tripwire/blob/main/docs/DOCUMENTATION_REVIEW_PROCESS.md Demonstrates how to add a test case to `tests/test_readme_examples.py` for a Python code example that might be missing or incorrect. It includes setup for environment variables and assertions for expected behavior. ```python def test_readme_example_basic_require(monkeypatch, tmp_path): """Test README example: basic env.require() usage.""" # Setup monkeypatch.setenv("DATABASE_URL", "postgresql://localhost/mydb") # Act - Import and use as shown in README from tripwire import env DATABASE_URL = env.require("DATABASE_URL", format="postgresql") # Assert assert DATABASE_URL == "postgresql://localhost/mydb" ``` -------------------------------- ### Provide Examples for Variables Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/configuration-as-code.md Include realistic examples for environment variables within the schema. This helps users understand the expected format and content, especially for complex values like connection strings. ```toml examples = [ "postgresql://user:pass@prod-db.company.com:5432/production", "postgresql://localhost:5432/dev" ] ``` -------------------------------- ### Python Template for New Examples Source: https://github.com/daily-nerd/tripwire/blob/main/examples/README.md Presents a Python template structure for creating new examples within the TripWire project. It includes sections for a brief title, description of what the example demonstrates, README reference, expected behavior, and instructions on how to run the example, including demo mode. ```python """Example: [Brief title] This example demonstrates [what it shows]. README Reference: [Section name] Expected behavior: - [What should happen] Run this example: export VAR="value" python examples/[category]/[number]_[name].py Or use demo mode: python examples/[category]/[number]_[name].py --demo """ ``` -------------------------------- ### Upgrade TripWire to Latest Version Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Upgrades the TripWire package to the latest available version on PyPI. This is useful for ensuring you have the most recent features and bug fixes. ```bash pip install --upgrade tripwire-py ``` -------------------------------- ### Pytest for Example Tests Source: https://github.com/daily-nerd/tripwire/blob/main/examples/README.md Provides bash commands to execute the test suite for the examples directory using Pytest. It outlines commands for running basic, advanced, and framework-specific example tests, as well as a command to run all example tests. ```bash # Test basic examples pytest tests/examples/test_basic_examples.py # Test advanced examples pytest tests/examples/test_advanced_examples.py # Test framework examples pytest tests/examples/test_framework_examples.py # Run all example tests pytest tests/examples/ ``` -------------------------------- ### Complete TripWire Configuration Example Source: https://github.com/daily-nerd/tripwire/blob/main/docs/reference/configuration.md An example of a comprehensive `pyproject.toml` file demonstrating how to configure various TripWire settings, including project metadata, CLI defaults, schema configuration, and git scanning parameters. ```toml # pyproject.toml [project] name = "my-app" version = "1.0.0" [tool.tripwire] # CLI defaults default_format = "table" strict_mode = false # Schema configuration schema_file = ".tripwire.toml" default_environment = "development" # Git scanning scan_git_history = true max_commits = 1000 ``` -------------------------------- ### Import TripWire in Python Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Demonstrates how to import modules from the TripWire package in Python. Note the package is installed as 'tripwire-py' but imported as 'tripwire'. ```python from tripwire import env ``` -------------------------------- ### TripWire Core Concepts: Type Inference Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Explains TripWire's automatic type inference from Python type annotations, simplifying variable definitions. Shows the old and new syntax for specifying types. ```python # Type inferred from annotation (int) PORT: int = env.require("PORT", min_val=1, max_val=65535) # No need to specify type= twice! # Old way (still works): PORT: int = env.require("PORT", type=int, min_val=1) ``` -------------------------------- ### GitHub Actions: Basic Environment Validation Workflow Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/ci-cd-integration.md This GitHub Actions workflow demonstrates a basic setup for validating environment files using TripWire. It checks out the code, sets up Python, installs TripWire, validates the schema, checks if the .env.example is up to date, and scans for secrets. The --strict flag is used for CI/CD compatibility. ```yaml # .github/workflows/validate-env.yml name: Validate Environment on: [push, pull_request] jobs: validate: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up Python uses: actions/setup-python@v4 with: python-version: '3.11' - name: Install TripWire run: pip install tripwire-py - name: Validate schema (CI/CD compatible) run: tripwire schema validate --strict - name: Check .env.example is up to date run: tripwire schema to-example --check - name: Scan for secrets run: tripwire security scan --strict ``` -------------------------------- ### Testing README Examples: Isolation vs. Alignment (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Highlights the importance of testing examples that are present in the README. Testing obscure edge cases not documented in the README can lead to brittle tests and confusion. ```python # BAD - Test doesn't match any README example def test_obscure_edge_case(): # Tests something not in README ``` ```python # GOOD - Test matches README example exactly def test_readme_line_142_example(): """Test example from README line 142.""" # Code that matches README example ``` -------------------------------- ### Building and Installing the Project Package Source: https://github.com/daily-nerd/tripwire/blob/main/CONTRIBUTING.md Shows the commands necessary to build the Tripwire package for distribution, install it in an editable mode for local development testing, and create a wheel distribution. ```bash # Build package python -m build # Install locally to test pip install -e . # Create distribution python -m build --wheel ``` -------------------------------- ### Generate .env Example from Schema Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/configuration-as-code.md Replaces the older `tripwire generate` command for generating `.env.example` files. This new command uses the schema to create an up-to-date example file, ensuring consistency. ```bash # Old tripwire generate # New tripwire schema to-example ``` -------------------------------- ### FastAPI Basic Setup with TripWire Configuration Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/framework-integration.md Demonstrates setting up FastAPI application configuration using TripWire for environment variables. It defines database URLs, security keys, application settings, and API keys, ensuring they are required or have defaults, and includes validation options like format, secret, minimum length, and value ranges. ```python # config.py from tripwire import env # Database DATABASE_URL: str = env.require("DATABASE_URL", format="postgresql", secret=True) REDIS_URL: str = env.optional("REDIS_URL", default="redis://localhost:6379") # Security SECRET_KEY: str = env.require("SECRET_KEY", secret=True, min_length=32) ALGORITHM: str = env.optional("ALGORITHM", default="HS256") # Application DEBUG: bool = env.optional("DEBUG", default=False) HOST: str = env.optional("HOST", default="0.0.0.0") PORT: int = env.optional("PORT", default=8000, min_val=1024, max_val=65535) # API Keys OPENAI_API_KEY: str = env.require("OPENAI_API_KEY", secret=True) ``` ```python # main.py from fastapi import FastAPI from config import DATABASE_URL, SECRET_KEY, DEBUG, HOST, PORT app = FastAPI(debug=DEBUG) @app.on_event("startup") async def startup(): # Config already validated at import time print(f"Connecting to database: {DATABASE_URL[:20]}...") print(f"Server starting on {HOST}:{PORT}") @app.get("/") async def root(): return {"message": "TripWire + FastAPI"} if __name__ == "__main__": import uvicorn uvicorn.run(app, host=HOST, port=PORT) ``` -------------------------------- ### Team Collaboration: Onboarding New Members with TripWire Source: https://github.com/daily-nerd/tripwire/blob/main/examples/cli_workflow.md A step-by-step guide for new team members to set up their local environment. It involves cloning the repository, copying the `.env.example` file to `.env`, filling in their specific values, and validating the configuration using TripWire. ```bash # 1. Clone repository git clone cd # 2. Copy example file cp .env.example .env # 3. Fill in values (use password manager/secret vault) # Edit .env with your editor # 4. Validate configuration tripwire validate ``` -------------------------------- ### Configure Travis CI for Tripwire Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/ci-cd-integration.md This configuration sets up Travis CI to install the tripwire-py package and run tripwire commands for generating, scanning, and validating. ```yaml language: python python: - "3.11" install: - pip install tripwire-py script: - tripwire generate --check - tripwire scan --strict - tripwire validate notifications: email: on_failure: always ``` -------------------------------- ### TripWire Example Script Template Source: https://github.com/daily-nerd/tripwire/blob/main/CONTRIBUTING.md A Python script template for creating TripWire examples. It includes a docstring for metadata, a function to initialize TripWire, and example usage for retrieving an environment variable. It also demonstrates how to implement a `--demo` mode for easier testing. ```python """Example: [Brief title] This example demonstrates [what it shows]. README Reference: Lines [X-Y] Expected behavior: - [Describe what should happen] - [List any important notes] Run this example: export DATABASE_URL="postgresql://localhost/mydb" python examples/basic/01_simple_require.py Or use demo mode: python examples/basic/01_simple_require.py --demo """ from tripwire import TripWire def main(): """Demonstrate [feature].""" env = TripWire() # Your example code here DATABASE_URL: str = env.require("DATABASE_URL") print(f"✅ Success: {DATABASE_URL}") return DATABASE_URL if __name__ == "__main__": import sys if "--demo" in sys.argv: import os os.environ["DATABASE_URL"] = "postgresql://localhost/demo" main() ``` -------------------------------- ### Migrating from python-dotenv to Tripwire Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/framework-integration.md Shows the migration path from using `python-dotenv` for loading environment variables to utilizing `Tripwire`. This example highlights the simplification of loading and accessing environment variables, including casting and secret handling, with Tripwire. ```python # Before: # from dotenv import load_dotenv # import os # load_dotenv() # SECRET_KEY = os.getenv('SECRET_KEY') # DEBUG = os.getenv('DEBUG') == 'true' from tripwire import env SECRET_KEY: str = env.require('SECRET_KEY', secret=True) DEBUG: bool = env.optional('DEBUG', default=False) ``` -------------------------------- ### Provide Actionable Error Messages (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/plugin-development.md Demonstrates how to provide helpful and actionable error messages when raising PluginAPIError. The good example guides the user on how to resolve the issue (e.g., installing a missing library), while the bad example shows an unhelpful, generic message. ```python # ✅ Good - tells user what to do raise PluginAPIError( self.metadata.name, "load", message="boto3 library not installed. Install with: pip install boto3" ) # ❌ Bad - unhelpful error raise PluginAPIError(self.metadata.name, "load", message="Import failed") ``` -------------------------------- ### Use TripWire environment variables in Python code Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/quick-start.md Demonstrates how to import and use environment variables in Python code using TripWire. It covers required, optional, and type-annotated variables. ```python # config.py from tripwire import env # Required variables (fail if missing) DATABASE_URL: str = env.require("DATABASE_URL", format="postgresql") API_KEY: str = env.require("API_KEY", secret=True) # Optional with defaults (type inferred from annotation) DEBUG: bool = env.optional("DEBUG", default=False) PORT: int = env.optional("PORT", default=8000, min_val=1, max_val=65535) # Now use them safely - guaranteed to be valid! print(f"Connecting to {DATABASE_URL}") print(f"Debug mode: {DEBUG}") print(f"Running on port {PORT}") ``` -------------------------------- ### Python Code Example Verification Source: https://github.com/daily-nerd/tripwire/blob/main/docs/DOCUMENTATION_REVIEW_PROCESS.md Demonstrates how Python code examples in documentation should be linked to executable scripts or tests for verification. It highlights the importance of linking to runnable examples and contrasts it with unverified inline code. ```python from tripwire import env DATABASE_URL = env.require("DATABASE_URL", format="postgresql") # See examples/basic/01_simple_require.py ``` ```python from tripwire import env # ... complex code with no test ``` -------------------------------- ### Initialize TripWire Project (Bash) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md This command initializes a new TripWire project with a 'web' project type. It automatically creates necessary configuration files like .env and .env.example, and updates .gitignore. The output confirms successful setup. ```bash tripwire init --project-type web ``` -------------------------------- ### Setup, Test, Lint, and Format TripWire Project (Bash) Source: https://github.com/daily-nerd/tripwire/blob/main/README.md This snippet details the commands for cloning the TripWire repository, setting up a Python virtual environment, installing development dependencies, running tests with pytest, checking code with ruff, and formatting code with black. These are essential steps for contributing to the project. ```bash git clone https://github.com/Daily-Nerd/TripWire.git cd tripwire python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate pip install -e ".[dev]" # Run tests pytest # Run linter ruff check . # Format code black . ``` -------------------------------- ### API Endpoint Examples (.env files) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/multi-environment.md Provides examples of how to define base URLs for APIs in .env files for development, staging, and production environments. ```bash # .env.development API_BASE_URL=http://localhost:8000/api/v1 # .env.staging API_BASE_URL=https://api-staging.example.com/v1 # .env.production API_BASE_URL=https://api.example.com/v1 ``` -------------------------------- ### Create Simple Application File (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md This snippet shows the initial setup for an `app.py` file, importing configuration variables defined in `config.py` and setting up basic logging. This serves as the foundation for building the web application. ```python # app.py """ Simple web application using TripWire configuration. """ from config import DATABASE_URL, SECRET_KEY, OPENAI_API_KEY, DEBUG, PORT, LOG_LEVEL import logging ``` -------------------------------- ### Python: FastAPI Integration with Tripwire Source: https://github.com/daily-nerd/tripwire/blob/main/README.md This example demonstrates integrating Tripwire with a FastAPI application. It shows how to validate essential configuration variables like DATABASE_URL and SECRET_KEY at import time, ensuring the FastAPI app starts with secure and valid settings. ```python from fastapi import FastAPI from tripwire import env # Validate at import time DATABASE_URL: str = env.require("DATABASE_URL", format="postgresql") SECRET_KEY: str = env.require("SECRET_KEY", secret=True, min_length=32) DEBUG: bool = env.optional("DEBUG", default=False) app = FastAPI(debug=DEBUG) @app.on_event("startup") async def startup(): print(f"Connecting to {DATABASE_URL[:20]}...") ``` -------------------------------- ### TripWire Developer Onboarding (Bash) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/configuration-as-code.md This Bash script illustrates the steps for a new developer to set up their environment using TripWire. It includes cloning the repository, initializing the environment by creating a '.env' file from a template, and validating the setup. ```bash # 1. Clone repo git clone repo-url cd repo # 2. Initialize environment tripwire schema to-example cp .env.example .env # 3. Validate setup tripwire schema validate ``` -------------------------------- ### View .env.example File Content Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md Displays the content of the generated .env.example file, showing the defined environment variables, their descriptions, and default values. ```bash cat .env.example ``` -------------------------------- ### Uninstall and Reinstall TripWire Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Removes any existing installations of tripwire or tripwire-py and then installs the correct tripwire-py package. This resolves 'ImportError' due to incorrect package names or installations. ```bash pip uninstall tripwire tripwire-py pip install tripwire-py ``` -------------------------------- ### Use Tripwire Plugins in Python Application Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/cli-reference.md Demonstrates how to integrate installed Tripwire plugins into a Python application. It shows how to auto-discover plugins, import specific plugin source classes, initialize them with necessary credentials and configurations, and then use them with `TripWireV2` to retrieve environment variables. This example requires the `tripwire` Python library. ```python from tripwire import TripWireV2 # Auto-discover installed plugins TripWireV2.discover_plugins() # Import plugin source classes from tripwire.plugins.sources import VaultEnvSource, AWSSecretsSource # Initialize plugin sources vault = VaultEnvSource( url="https://vault.company.com", token="hvs.xxx", mount_point="secret", path="myapp/config" ) aws = AWSSecretsSource( secret_name="myapp/production", region_name="us-east-1" ) # Use with TripWire (supports multiple sources) env = TripWireV2(sources=[vault, aws]) DATABASE_URL = env.require("DATABASE_URL") API_KEY = env.require("API_KEY") ``` -------------------------------- ### Verify TripWire Installation Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Checks if the tripwire-py package is installed correctly. This involves using pip to show package information. It's a preliminary step for troubleshooting installation issues. ```bash pip show tripwire-py ``` -------------------------------- ### Check .env File Against .env.example Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md Compares the local .env file against the .env.example template to identify missing or extra environment variables. This ensures the local configuration is up-to-date. ```bash tripwire check ``` -------------------------------- ### Generate .env.example File Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md Automatically generates a .env.example file by scanning Python files for environment variable definitions. This helps in creating a template for configuration variables. ```bash tripwire generate ``` -------------------------------- ### F-string Example Bug (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Demonstrates a documentation inaccuracy where a README claimed an f-string example would raise a TypeError, but it actually produced a string 'Bearer None'. This highlights the need for accurate code examples. ```python # README claimed this raised TypeError token = None header = f"Bearer {token}" # Actually produces "Bearer None" ``` -------------------------------- ### Install TripWire Dependencies with uv or pip Source: https://github.com/daily-nerd/tripwire/blob/main/CONTRIBUTING.md Installs TripWire in editable mode along with development dependencies using either 'uv' (recommended for speed) or 'pip'. This includes linters, formatters, and testing tools. ```bash # Using uv (recommended - faster) uv pip install -e ".[dev]" # OR using pip pip install -e ".[dev]" ``` -------------------------------- ### Force Regenerate .env.example File Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md Forces the regeneration of the .env.example file, even if it already exists. This is useful when configuration definitions have changed. ```bash tripwire generate --force ``` -------------------------------- ### Generate .env.example from TripWire Schema Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/configuration-as-code.md Automatically generates a comprehensive `.env.example` file based on the `.tripwire.toml` schema. The generated file includes descriptions, types, examples, and validation rules for each environment variable. ```bash tripwire schema to-example ``` -------------------------------- ### Invalid PluginMetadata Example (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/plugin-development.md Illustrates an example of invalid `PluginMetadata` that would cause a `PluginValidationError`. It highlights common mistakes in the 'name', 'version', 'author', and 'description' fields. ```python # INVALID - will raise PluginValidationError metadata = PluginMetadata( name="my plugin!", # Contains space and special character version="invalid", # Not semantic versioning author="", # Empty author description="" # Empty description ) ``` -------------------------------- ### Base .env Configuration Example Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/multi-environment.md An example of a base `.env` file containing application-wide settings that are safe to commit. It includes application name, logging format, and database pool configurations, explicitly stating that no secrets should be included. ```dotenv # Base configuration - shared across all environments # NO SECRETS HERE! # Application APP_NAME=MyApp LOG_FORMAT=json # Database DB_POOL_SIZE=5 DB_POOL_MAX_OVERFLOW=10 # Features FEATURE_ANALYTICS=true ``` -------------------------------- ### Quart Application with Environment Configuration Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/framework-integration.md An asynchronous web application using Quart, configured with environment variables via Tripwire. It includes startup logic to print the database URL and a root route. ```python # config.py from tripwire import env SECRET_KEY: str = env.require("SECRET_KEY", secret=True) DATABASE_URL: str = env.require("DATABASE_URL", format="postgresql") REDIS_URL: str = env.optional("REDIS_URL", default="redis://localhost:6379/0") ``` ```python # app.py from quart import Quart from config import SECRET_KEY, DATABASE_URL app = Quart(__name__) app.config['SECRET_KEY'] = SECRET_KEY @app.before_serving async def startup(): print(f"Connecting to {DATABASE_URL[:20]}...") @app.route('/') async def index(): return {'message': 'TripWire + Quart'} if __name__ == '__main__': app.run() ``` -------------------------------- ### Example: Testing Invalid Custom Regex Pattern Rejection Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Shows how to test the failure case for Tripwire's `env.require` with a custom regex pattern. This involves setting an invalid environment variable and asserting that an exception is raised. ```python def test_custom_regex_pattern_rejects_invalid(self, monkeypatch: pytest.MonkeyPatch) -> None: """Verify custom regex pattern rejects invalid values.""" from tripwire import TripWire monkeypatch.setenv("API_KEY", "invalid-format") env = TripWire(load_dotenv=False) with pytest.raises(Exception): # Should raise validation error env.require("API_KEY", pattern=r"^sk-[a-zA-Z0-9]{32}$") ``` -------------------------------- ### Run Tripwire Application Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md Executes the main Python application script. This command is used to start the application and observe its logging output. ```bash python app.py ``` -------------------------------- ### Handle ImportError for External Dependencies (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/plugin-development.md This Python code demonstrates how to gracefully handle `ImportError` when an external library is missing. It uses a try-except block to catch the error and raises a custom `PluginAPIError` with a helpful message guiding the user on how to install the dependency. ```python try: import external_lib except ImportError as e: raise PluginAPIError( self.metadata.name, "load", original_error=e, message="external_lib not installed. Install with: pip install external_lib" ) from e ``` -------------------------------- ### Testing Error Scenarios (Anti-Patterns) Source: https://github.com/daily-nerd/tripwire/blob/main/examples/README.md Shows how to run examples located in the `problems/` directory, which are designed to fail and illustrate anti-patterns or common errors encountered without TripWire. These examples help in understanding the necessity of robust configuration validation. ```bash # These demonstrate errors you'd encounter without TripWire python examples/problems/01_os_getenv_none.py python examples/problems/02_int_conversion_error.py ``` -------------------------------- ### Example: Testing Custom Regex Pattern Validation with Tripwire Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Demonstrates how to write a pytest for Tripwire's `env.require` function with a custom regex pattern. This includes setting up environment variables using monkeypatch and asserting the validation success. ```python # In README.md API_KEY: str = env.require("API_KEY", pattern=r"^sk-[a-zA-Z0-9]{32}$") # In tests/test_readme_examples.py class TestFormatValidatorsSection: """Tests for 'Format Validators' examples (README lines X-Y).""" def test_custom_regex_pattern(self, monkeypatch: pytest.MonkeyPatch) -> None: """Verify custom regex pattern validation (README line X). README example: API_KEY: str = env.require("API_KEY", pattern=r"^sk-[a-zA-Z0-9]{32}$") This tests that regex patterns are enforced correctly. """ from tripwire import TripWire # Set up test environment monkeypatch.setenv("API_KEY", "sk-abcdefghijklmnopqrstuvwxyz012345") env = TripWire(load_dotenv=False) result = env.require("API_KEY", pattern=r"^sk-[a-zA-Z0-9]{32}$") # Verify behavior matches README claim assert result.startswith("sk-") assert len(result) == 35 # "sk-" + 32 characters ``` -------------------------------- ### Integrate Tripwire Generate into Pre-commit Hooks Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Automate the generation and checking of `.env.example` files in CI/CD pipelines. Ensure `.env.example` is kept in sync by adding a pre-commit hook to regenerate it. ```yaml # .pre-commit-config.yaml - id: tripwire-generate entry: tripwire generate --check ``` -------------------------------- ### int(os.getenv()) Example Bug (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Illustrates another documentation inaccuracy where a README claimed `int(os.getenv('PORT'))` would raise a ValueError, but it actually raises a TypeError when the environment variable is not set. This emphasizes the importance of correct error type documentation. ```python # README claimed ValueError, actually raises TypeError PORT = int(os.getenv("PORT")) # TypeError when PORT not set ``` -------------------------------- ### Reinstall TripWire Package Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Forces a reinstallation of the tripwire-py package to resolve potential corruption or configuration issues. This command ensures a fresh installation. ```bash pip install --force-reinstall tripwire-py ``` -------------------------------- ### Add New Example Scripts Source: https://github.com/daily-nerd/tripwire/blob/main/CONTRIBUTING.md This command sequence outlines the process for adding new runnable code examples to the project. It involves creating a Python script in the appropriate subdirectory within the `examples/` directory and then linking to it from the relevant documentation file. ```bash # Create script in appropriate subdirectory examples/basic/01_simple_require.py examples/problems/01_os_getenv_none.py examples/advanced/01_custom_validators.py examples/frameworks/fastapi_example.py ``` -------------------------------- ### Retrieve Python Version for Debugging Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Get the version of the Python interpreter being used. This is important diagnostic information when troubleshooting issues with Python-based tools like Tripwire. ```bash python --version ``` -------------------------------- ### Check Python Virtual Environment Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Verifies the currently active Python interpreter and its location. Essential for ensuring that TripWire is installed and used within the correct virtual environment. ```bash which python ``` -------------------------------- ### Database URL Examples (.env files) Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/multi-environment.md Illustrates common patterns for setting database connection URLs in .env files for development, staging, and production environments. ```bash # .env.development DATABASE_URL=postgresql://localhost:5432/myapp_dev # .env.staging DATABASE_URL=postgresql://staging:5432/myapp # .env.production DATABASE_URL=postgresql://user:pass@prod-db.internal:5432/myapp ``` -------------------------------- ### Configure Jenkins Pipeline for Tripwire Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/ci-cd-integration.md This Jenkinsfile defines a pipeline to install tripwire-py, perform environment validation, and conduct security scans, archiving the audit results. ```groovy pipeline { agent any stages { stage('Setup') { steps { sh 'pip install tripwire-py' } } stage('Validate Environment') { steps { sh 'tripwire generate --check' sh 'tripwire validate' } } stage('Security Scan') { steps { sh 'tripwire scan --strict' sh 'tripwire audit --all --json > audit.json' } } } post { always { archiveArtifacts artifacts: 'audit.json', allowEmptyArchive: true } } } ``` -------------------------------- ### Initialize Git Repository and Commit Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Provides the basic git commands to initialize a new repository, add files, and make an initial commit. This is necessary if TripWire's audit functionality requires a git repository context. ```bash # Initialize git if needed git init git add . git commit -m "Initial commit" ``` -------------------------------- ### Testing Internal Implementation (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Demonstrates an anti-pattern in testing where internal implementation details are tested. It is recommended to test the public interface and documented behavior instead. ```python def test_validator_uses_regex_internally(): from tripwire.validation import validate_email # Don't test HOW it works, test THAT it works ``` -------------------------------- ### Generate .env.example from Schema Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/configuration-as-code.md Generate an example .env file from the TripWire schema. Options include forcing an overwrite of existing files and specifying a custom output file path. The generated file includes descriptions, types, validation rules, and default values. ```bash # Generate .env.example tripwire schema to-example # Force overwrite tripwire schema to-example --force # Custom output file tripwire schema to-example --output .env.template ``` -------------------------------- ### Check TripWire CLI Path Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Verifies if the tripwire executable is accessible in the system's PATH environment variable. If 'which tripwire' returns a path, the CLI is correctly installed and discoverable. ```bash which tripwire ``` -------------------------------- ### CI Best Practice: Use --strict Flag Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/ci-cd-integration.md Examples of using the `--strict` flag with Tripwire commands in CI pipelines to ensure failures when issues are found. ```yaml # Fail pipeline if issues found - run: tripwire generate --check # Fails if .env.example outdated - run: tripwire scan --strict # Fails if secrets detected - run: tripwire validate --strict # Fails if validation errors ``` -------------------------------- ### Configure Python Logging Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md Sets up basic logging for the application. It configures the logging level and format, and logs various application events including startup, debug information, server port, database connection, and API key configuration. ```python import logging LOG_LEVEL = "INFO" DEBUG = True PORT = 8000 DATABASE_URL = "postgresql://localhost:5432/mydatabase" logging.basicConfig( level=getattr(logging, LOG_LEVEL), format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) def main(): """Main application entry point.""" logger.info("Starting application...") logger.debug(f"Debug mode: {DEBUG}") logger.info(f"Server will run on port {PORT}") # Simulate database connection logger.info(f"Connecting to database: {DATABASE_URL[:30]}...") # Simulate API setup logger.info("OpenAI API key configured") # Your application logic here logger.info("Application ready!") if __name__ == "__main__": try: main() except Exception as e: logger.error(f"Application failed to start: {e}") raise ``` -------------------------------- ### Synchronize .env File Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/your-first-project.md Updates the local .env file based on the .env.example template, adding any missing variables. This helps in maintaining consistency across development environments. ```bash tripwire sync ``` -------------------------------- ### Initialize TripWire Schema Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/configuration-as-code.md Initializes a new `.tripwire.toml` schema file with a starter template. This command is used to begin defining your environment variable contracts. ```bash tripwire schema init ``` -------------------------------- ### Troubleshoot Git Command Failures Source: https://github.com/daily-nerd/tripwire/blob/main/docs/advanced/troubleshooting.md Diagnose and resolve errors encountered when running Git commands. Ensure Git is installed and properly configured. Fetching all branches can also resolve certain issues. ```bash git --version git config user.name git config user.email git fetch --all ``` -------------------------------- ### Troubleshoot ImportError: No module named tripwire Source: https://github.com/daily-nerd/tripwire/blob/main/docs/getting-started/installation.md Commands to resolve 'ImportError: No module named tripwire'. This involves uninstalling potential conflicting names and reinstalling the correct package, then verifying the import in Python. ```bash # Ensure correct package name pip uninstall tripwire tripwire-py pip install tripwire-py # Verify in Python python -c "from tripwire import env; print('Success!')" ``` -------------------------------- ### Testing Documented Interface (Python) Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md Illustrates the recommended approach to testing by focusing on the public API and documented behavior of the TripWire class. This approach makes tests more resilient to internal changes. ```python # GOOD - Testing documented interface def test_email_validator_accepts_valid_emails(): from tripwire import TripWire env = TripWire(load_dotenv=False) # Test the public API as documented ``` -------------------------------- ### Bash: TripWire Project Initialization Source: https://github.com/daily-nerd/tripwire/blob/main/README.md Shows the command to initialize a new project with TripWire. This command automatically creates essential configuration files like `.env` and `.env.example`, and updates `.gitignore` to ensure proper setup and security. ```bash $ tripwire init Welcome to TripWire! 🎯 ✅ Created .env ✅ Created .env.example ✅ Updated .gitignore Setup complete! ✅ Next steps: 1. Edit .env with your configuration values 2. Import in your code: from tripwire import env 3. Use variables: API_KEY = env.require('API_KEY') ``` -------------------------------- ### Initialize TripWire Project CLI Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/cli-reference.md Initializes a new TripWire project by creating essential configuration files such as `.env`, `.env.example`, and updating `.gitignore`. It supports different project types and can force overwrites. This command is run once per project. ```bash tripwire init tripwire init --project-type web tripwire init --project-type cli tripwire init --force ``` -------------------------------- ### Require Environment Variable with Regex Pattern Matching Source: https://github.com/daily-nerd/tripwire/blob/main/docs/reference/api.md This example illustrates using `env.require()` with a regular expression pattern to validate the format of an API key. The pattern ensures the key starts with 'sk-' followed by alphanumeric characters. ```python # With pattern matching API_KEY: str = env.require("API_KEY", pattern=r"^sk-[a-zA-Z0-9]{32}$") ``` -------------------------------- ### Synchronize .env with .env.example using TripWire CLI Source: https://github.com/daily-nerd/tripwire/blob/main/examples/cli_workflow.md Applies changes from `.env.example` to the `.env` file, adding any missing variables while preserving existing values. This command helps ensure local development environments are up-to-date with the project's defined variables. Options include dry-run for preview and interactive mode for confirmation. ```bash tripwire sync --dry-run tripwire sync tripwire sync --interactive ``` -------------------------------- ### Test Pattern: Demonstrating Anti-Patterns Source: https://github.com/daily-nerd/tripwire/blob/main/tests/README_TEST_GUIDE.md A pytest pattern designed to showcase problematic code practices ('anti-patterns') as found in documentation. This test explicitly demonstrates why a certain approach should be avoided, often by showing unexpected behavior. ```python def test_anti_pattern_demonstrates_problem(self) -> None: """Demonstrate why os.getenv() pattern is problematic (README line X). This is an anti-pattern test showing WHAT NOT TO DO. """ import os # Show the problem os.environ["DEBUG"] = "True" assert os.getenv("DEBUG") == "true" is False # Fails unexpectedly ``` -------------------------------- ### Flask Application Factory with Configuration Management Source: https://github.com/daily-nerd/tripwire/blob/main/docs/guides/framework-integration.md Demonstrates the application factory pattern in Flask using Tripwire for environment configuration. It includes base, development, production, and test configurations, loading them based on the environment. ```python # config.py from tripwire import env class Config: """Base configuration.""" # Already validated by TripWire at import time SECRET_KEY: str = env.require("SECRET_KEY", secret=True, min_length=32) DEBUG: bool = env.optional("DEBUG", default=False) # Database SQLALCHEMY_DATABASE_URI: str = env.require("DATABASE_URL", format="postgresql") SQLALCHEMY_TRACK_MODIFICATIONS: bool = False # Redis REDIS_URL: str = env.optional("REDIS_URL", default="redis://localhost:6379/0") class DevelopmentConfig(Config): """Development configuration.""" DEBUG = True class ProductionConfig(Config): """Production configuration.""" DEBUG = False class TestConfig(Config): """Test configuration.""" TESTING = True SQLALCHEMY_DATABASE_URI = "sqlite:///:memory:" ``` ```python # app.py from flask import Flask from config import DevelopmentConfig, ProductionConfig import os def create_app(config_name=None): """Application factory.""" app = Flask(__name__) # Load config if config_name == 'production': app.config.from_object(ProductionConfig) else: app.config.from_object(DevelopmentConfig) # Initialize extensions from extensions import db, redis_client db.init_app(app) redis_client.init_app(app) # Register blueprints from routes import main_bp app.register_blueprint(main_bp) return app if __name__ == '__main__': app = create_app() app.run() ``` -------------------------------- ### Require Environment Variable with Basic Usage and Type Inference Source: https://github.com/daily-nerd/tripwire/blob/main/docs/reference/api.md This example shows the basic usage of `env.require()` to get an environment variable. It also illustrates type inference for a string variable and how to specify numeric constraints for an integer variable. ```python # Basic usage API_KEY: str = env.require("API_KEY") # With type inference PORT: int = env.require("PORT", min_val=1024, max_val=65535) ```