### Command Output Examples Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Standard output format for the setup command and the specific output when using the --print-path flag. ```text Creating worktree [blog-feature-login] on branch [feature/login] Worktree ready. +---------------+------------------------------------------+ | Path | /Users/you/Sites/blog-feature-login | | Branch | feature/login | | URL | https://blog-feature-login.test | | Database | blog_feature_login | | Test database | blog_feature_login_testing | +---------------+------------------------------------------+ ``` ```text [stderr output...] /Users/you/Sites/blog-feature-login ``` -------------------------------- ### Worktree Setup Command Examples Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Common usage patterns for the worktree:setup command, including branch naming, base branch selection, and shell integration. ```bash # Create a worktree for a named branch php artisan worktree:setup feature/login # Auto-generate branch name php artisan worktree:setup # Base off develop instead of main php artisan worktree:setup --base=develop # Skip dependencies and steps (database only) php artisan worktree:setup --no-install # Skip everything except git worktree creation php artisan worktree:setup --no-database --no-install # Seed the database after migrating php artisan worktree:setup --seed # Get the path for shell integration (e.g., cd into it) WORKTREE=$(php artisan worktree:setup --print-path) cd "$WORKTREE" ``` -------------------------------- ### Worktree path output example Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Example output showing the resolved filesystem path. ```text /Users/you/Sites/blog-feature-login ``` -------------------------------- ### Worktree list output example Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Example output table showing branch, path, URL, and database columns. ```text +----------------+--------------------------------------+----------------------------------+---------------------+ | Branch | Path | URL | Database | +----------------+--------------------------------------+----------------------------------+---------------------+ | feature/login | /Users/you/Sites/blog-feature-login | https://blog-feature-login.test | blog_feature_login | | feature/search | /Users/you/Sites/blog-feature-search | https://blog-feature-search.test | blog_feature_search | +----------------+--------------------------------------+----------------------------------+---------------------+ ``` -------------------------------- ### Configuration Merging Example Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/07-service-provider.md Demonstrates how default and user-published configurations are combined during the merge process. ```php // Default config [ 'host' => [ 'template' => '{repo}-{branch}', 'tld' => 'test', 'remap_source_host' => true, ], 'steps' => ['npm run build', 'php artisan storage:link'], ] // User published config (partial override) [ 'host' => [ 'template' => 'app-{slug}', // tld and remap_source_host not specified ], 'steps' => ['php artisan storage:link'], ] // After merging [ 'host' => [ 'template' => 'app-{slug}', // User value 'tld' => 'test', // Default (filled in) 'remap_source_host' => true, // Default (filled in) ], 'steps' => ['php artisan storage:link'], // User list (not merged) ] ``` -------------------------------- ### Worktree path usage examples Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Examples of using the worktree:path command for direct output and shell integration. ```bash # Get the path for a branch php artisan worktree:path feature/login # Output: /Users/you/Sites/blog-feature-login # Use with cd in shell integration cd "$(php artisan worktree:path feature/login)" # Warp terminal config example [[panes]] id = "main" type = "terminal" directory = "{{repo}}" commands = [ '''cd "$(php artisan worktree:path {{branch}})"''', ] ``` -------------------------------- ### Command Output Example Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Typical console output after successfully running the command. ```text Finishing worktree [blog-feature-login] on branch [feature/login] Pushing branch and opening PR... Branch pushed. Pull request opened at https://github.com/user/repo/pull/123 Dropping database [blog_feature_login] and test database [blog_feature_login_testing] Unsecuring site [blog-feature-login.test] Unlinking site [blog-feature-login] Removing git worktree Done. ``` -------------------------------- ### Creating and Navigating to Worktrees Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Automate the setup and directory change process using the --print-path flag. ```bash # Create and cd in one command WORKTREE=$(php artisan worktree:setup --print-path) cd "$WORKTREE" # Or in a function function wt-new() { WORKTREE=$(php artisan worktree:setup ${1} --print-path) cd "$WORKTREE" } # Usage wt-new feature/login ``` -------------------------------- ### Common Command Examples Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Various ways to invoke the command for different cleanup scenarios. ```bash # Interactive mode - choose worktree and finish method php artisan worktree:teardown # Open a pull request php artisan worktree:teardown feature/login --pr # Merge into main php artisan worktree:teardown feature/login --into=main # Merge into develop php artisan worktree:teardown feature/login --into=develop # Throw away the branch php artisan worktree:teardown feature/login --abandon --force # Skip database drops php artisan worktree:teardown feature/login --abandon --keep-database # Custom commit message for PR php artisan worktree:teardown feature/login --pr --message="Add login feature" ``` -------------------------------- ### Interactive Mode Example Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Example of the interactive prompt flow when no arguments are provided. ```text Which worktree do you want to finish? [0] feature/login [1] feature/search > 0 How do you want to finish this? [0] Open a pull request with gh [1] Merge into main (or choose another branch) [2] Throw it away > 0 ``` -------------------------------- ### Complete configuration file structure Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md A full example of the configuration array structure used to define worktree behavior, database connections, and dependency management. ```php env('WORKTREE_PATH', '.worktrees'), 'base_branch' => env('WORKTREE_BASE_BRANCH', 'main'), 'herd' => env('WORKTREE_HERD', 'secure'), 'host' => [ 'template' => env('WORKTREE_HOST_TEMPLATE', '{repo}-{branch}'), 'tld' => env('WORKTREE_TLD', 'test'), 'remap_source_host' => (bool) env('WORKTREE_REMAP_HOST', true), ], 'env' => [ 'source' => '.env', 'copy' => ['.env.testing'], 'app_url_key' => 'APP_URL', 'replace' => [ 'REDIS_PREFIX' => '{value}{slug}_', 'CACHE_PREFIX' => '{slug}_cache_', ], ], 'database' => [ 'enabled' => (bool) env('WORKTREE_DATABASE', true), 'migrate' => env('WORKTREE_MIGRATE', 'fresh'), 'seed' => (bool) env('WORKTREE_SEED', false), 'phpunit_files' => ['phpunit.xml', 'phpunit.xml.dist'], 'connections' => [ [ 'connection' => null, 'env' => 'DB_DATABASE', 'name' => '{slug}', 'test' => [ 'env' => 'DB_DATABASE', 'name' => '{slug}_testing', ], ], [ 'connection' => 'analytics', 'env' => 'ANALYTICS_DB_DATABASE', 'name' => '{slug}_analytics', 'test' => [ 'env' => 'ANALYTICS_DB_DATABASE', 'name' => '{slug}_analytics_testing', ], ], ], ], 'dependencies' => [ 'vendor' => [ 'copy' => (bool) env('WORKTREE_COPY_VENDOR', false), 'path' => 'vendor', 'manifest' => 'composer.json', 'lock' => 'composer.lock', 'install' => 'composer install', ], 'node_modules' => [ 'copy' => (bool) env('WORKTREE_COPY_NODE_MODULES', false), 'path' => 'node_modules', 'manifest' => 'package.json', 'lock' => 'package-lock.json', 'install' => 'npm ci', ], ], 'steps' => [ 'npm run build --if-present', 'php artisan storage:link', ], ]; ``` -------------------------------- ### Test Worktree Integration with PHPUnit Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Demonstrates testing the worktree:setup command and validating configuration constraints for database connections. ```php namespace Tests\Feature; use Illuminate\Support\Facades\Artisan; use Mozex\Worktree\Exceptions\WorktreeException; use Tests\TestCase; class WorktreeTest extends TestCase { /** @test */ public function it_creates_a_worktree() { // Call setup command $result = Artisan::call('worktree:setup', [ 'branch' => 'feature/test', '--no-install' => true, ]); $this->assertEquals(0, $result); } /** @test */ public function it_refuses_duplicate_databases() { // Test that duplicate database names are caught config([ 'worktree.database.connections' => [ ['connection' => null, 'env' => 'DB_DATABASE', 'name' => '{slug}'], ['connection' => 'other', 'env' => 'OTHER_DB', 'name' => '{slug}'], ], ]); $this->expectException(WorktreeException::class); Artisan::call('worktree:setup', ['branch' => 'feature/x']); } } ``` -------------------------------- ### Multiple Database Connections Configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Example of configuring multiple database connections for a single worktree. ```php 'database' => [ 'connections' => [ // Main application database [ 'connection' => null, 'env' => 'DB_DATABASE', 'name' => '{slug}', 'test' => [ 'env' => 'DB_DATABASE', 'name' => '{slug}_testing', ], ], // Analytics database [ 'connection' => 'analytics', 'env' => 'ANALYTICS_DB_DATABASE', 'name' => '{slug}_analytics', 'test' => [ 'env' => 'ANALYTICS_DB_DATABASE', 'name' => '{slug}_analytics_testing', ], ], ], ], ``` -------------------------------- ### Command Signature and Configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md The internal Artisan signature definition and description for the worktree:setup command. ```php protected $signature = 'worktree:setup {branch? : The branch to work on (auto-generated when omitted)} {--base= : Base branch used when creating a new branch} {--no-database : Skip creating databases and patching PHPUnit} {--no-migrate : Skip migrating the application database} {--no-install : Skip installing or copying dependencies, plus the migrations and steps that need them} {--seed : Seed the application database after migrating} {--print-path : Print only the resolved worktree path (status goes to stderr), for shell integration}'; protected $description = 'Create an isolated git worktree with its own Herd site and databases'; ``` -------------------------------- ### Value escaping examples Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/02-env-file-editor.md Demonstrates how special characters are handled when escaping values for environment files. ```text // Space in value → quoted 'my secret' → "my secret" // Hash in value → quoted 'value#hash' → "value#hash" // Quote in value → escaped and quoted 'say "hello"' → "say \"hello\"" // No special chars → unquoted 'simple' → simple ``` -------------------------------- ### worktree:setup Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Creates an isolated git worktree with its own Herd site, databases, and environment configuration. ```APIDOC ## worktree:setup ### Description Creates an isolated git worktree with its own Herd site, databases, and environment configuration. This command must be run from the main repository. ### Usage `php artisan worktree:setup [branch] [options]` ### Arguments - **branch** (string) - Optional - Git branch name (e.g., feature/login). Auto-generated as feature/auto-{date}-{time} if omitted. ### Options - **--base** (string) - Optional - Base branch for new worktrees (defaults to config base_branch, usually main). - **--no-database** (flag) - Optional - Skip database creation and PHPUnit patching. - **--no-migrate** (flag) - Optional - Skip running migrations (databases created empty). - **--no-install** (flag) - Optional - Skip installing/copying dependencies and all provisioning steps. - **--seed** (flag) - Optional - Run seeders after migration. - **--print-path** (flag) - Optional - Print only the worktree path to stdout; all status output goes to stderr (useful for shell integration). ### Examples ```bash # Create a worktree for a named branch php artisan worktree:setup feature/login # Auto-generate branch name php artisan worktree:setup # Base off develop instead of main php artisan worktree:setup --base=develop # Get the path for shell integration WORKTREE=$(php artisan worktree:setup --print-path) cd "$WORKTREE" ``` ``` -------------------------------- ### Handle unreadablePhpunitFile exception Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/06-errors.md Example of catching an unreadablePhpunitFile exception when parsing configuration. ```php try { $config = PhpunitConfig::fromFile('phpunit.xml'); } catch (WorktreeException $e) { // Check the XML syntax in phpunit.xml // Use an XML validator to identify the issue } ``` -------------------------------- ### Throw WorktreeException Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Example of throwing and catching a WorktreeException. ```php use Mozex\Worktree\Exceptions\WorktreeException; try { throw WorktreeException::unsupportedDriver('oracle'); } catch (WorktreeException $e) { echo $e->getMessage(); // Database driver [oracle] has no server to create a database on... } ``` -------------------------------- ### Handle worktreeNotFound exception Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/06-errors.md Example of catching and handling a worktreeNotFound exception. ```php try { // worktree:teardown or worktree:path } catch (WorktreeException $e) { if (str_contains($e->getMessage(), 'No worktree found')) { echo 'Run: php artisan worktree:list'; } } ``` -------------------------------- ### Navigate and Work in a Worktree Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Retrieves the worktree path to facilitate directory switching and environment setup. ```bash # Get the path for navigation WORKTREE=$(php artisan worktree:path feature/login) # Change into the worktree cd "$WORKTREE" # Edit code, run tests php artisan migrate npm run dev ``` -------------------------------- ### Handle commandFailed exceptions Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/06-errors.md Example of catching and processing commandFailed exceptions to extract command output. ```php try { $command->handle(); } catch (WorktreeException $e) { if (str_contains($e->getMessage(), 'Command [') && str_contains($e->getMessage(), '] failed')) { // Extract the command and output from the message // Log or display to the user echo $e->getMessage(); } } ``` -------------------------------- ### Define Custom Environment Replacements Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Defines patterns for automatically rewriting environment variables based on the worktree slug. The example shows the configuration mapping and the resulting transformation from original to worktree-specific values. ```php // config/worktree.php 'env' => [ 'replace' => [ 'REDIS_PREFIX' => '{value}{slug}_', 'CACHE_PREFIX' => '{slug}_cache_', 'SESSION_PREFIX' => '{slug}_session_', 'QUEUE_PREFIX' => 'queue_{slug}_', 'LOG_FILE' => 'storage/logs/{slug}.log', 'BROADCAST_QUEUE' => 'broadcast_{slug}', ], ], // Original .env REDIS_PREFIX=laravel_database_ CACHE_PREFIX=default_ SESSION_PREFIX=default_ QUEUE_PREFIX=default_ LOG_FILE=storage/logs/laravel.log BROADCAST_QUEUE=broadcast // Worktree .env (automatically rewritten) REDIS_PREFIX=laravel_database_blog_feature_login_ CACHE_PREFIX=blog_feature_login_cache_ SESSION_PREFIX=blog_feature_login_session_ QUEUE_PREFIX=queue_blog_feature_login_ LOG_FILE=storage/logs/blog-feature-login.log BROADCAST_QUEUE=broadcast_blog_feature_login ``` -------------------------------- ### Define Provisioning Steps Source: https://github.com/mozex/laravel-worktree/blob/main/README.md Specify commands to run after provisioning, such as building assets or linking storage. ```php 'steps' => [ 'npm run build --if-present', 'php artisan storage:link', ], ``` -------------------------------- ### Initialize EnvFile from file Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/02-env-file-editor.md Create an EnvFile instance by loading contents from a specified file path. ```php use Mozex\Worktree\Support\EnvFile; $env = EnvFile::fromFile('/path/to/.env'); ``` -------------------------------- ### Configure post-provisioning steps in PHP Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Define shell commands to execute within the worktree after dependencies are provisioned. ```php 'steps' => [ 'npm run build --if-present', 'php artisan storage:link', 'php artisan ziggy:generate', ], ``` -------------------------------- ### Derive Worktree Configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/01-worktree-value-object.md Demonstrates initializing a Worktree instance and deriving database names, paths, and hostnames from the configuration. ```php $config = config('worktree'); $worktree = Worktree::make('/path/to/repo', 'feature/x', $config); // Use derived values everywhere: $dbName = $worktree->database('{slug}'); // blog_feature_x $dbTestName = $worktree->database('{slug}_testing'); // blog_feature_x_testing $path = $worktree->path(); // /path/to/.worktrees/blog-feature-x $host = $worktree->host(); // blog-feature-x.test ``` -------------------------------- ### Handle worktreeExists exception Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/06-errors.md Example of catching and handling a worktreeExists exception during command execution. ```php use Mozex\Worktree\Exceptions\WorktreeException; try { $command->handle(); } catch (WorktreeException $e) { if (str_contains($e->getMessage(), 'already exists')) { // Run teardown for the conflicting worktree // Then retry setup } } ``` -------------------------------- ### Use HerdMode Enum Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Example usage of HerdMode methods to determine scheme and enabled status. ```php $mode = HerdMode::Secure; echo $mode->scheme(); // https echo $mode->enabled(); // true $mode = HerdMode::None; echo $mode->enabled(); // false ``` -------------------------------- ### Instantiate Worktree via Constructor Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/01-worktree-value-object.md The constructor requires the source path, branch name, and configuration array. ```php public function __construct( protected string $sourcePath, protected string $branch, protected array $config, ): void ``` -------------------------------- ### Publish and customize configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Publish the package configuration file and define settings for paths, databases, environment variables, and dependencies. ```bash # Publish the config file php artisan vendor:publish --tag=worktree-config ``` ```php // config/worktree.php return [ 'path' => env('WORKTREE_PATH', '.worktrees'), 'base_branch' => env('WORKTREE_BASE_BRANCH', 'develop'), 'herd' => env('WORKTREE_HERD', 'secure'), 'host' => [ 'template' => env('WORKTREE_HOST_TEMPLATE', 'app-{slug}'), 'tld' => env('WORKTREE_TLD', 'localhost'), 'remap_source_host' => true, ], 'database' => [ 'enabled' => true, 'migrate' => 'fresh', 'seed' => false, 'connections' => [ [ 'connection' => null, 'env' => 'DB_DATABASE', 'name' => '{slug}', 'test' => [ 'env' => 'DB_DATABASE', 'name' => '{slug}_testing', ], ], [ 'connection' => 'analytics', 'env' => 'ANALYTICS_DATABASE', 'name' => '{slug}_analytics', 'test' => [ 'env' => 'ANALYTICS_DATABASE', 'name' => '{slug}_analytics_testing', ], ], ], ], 'env' => [ 'source' => '.env', 'copy' => ['.env.testing', '.env.local'], 'replace' => [ 'REDIS_PREFIX' => '{value}{slug}_', 'CACHE_PREFIX' => '{slug}_cache_', 'QUEUE_PREFIX' => 'queue_{slug}_', ], ], 'dependencies' => [ 'vendor' => [ 'copy' => true, // Copy instead of install 'path' => 'vendor', 'manifest' => 'composer.json', 'lock' => 'composer.lock', 'install' => 'composer install', ], 'node_modules' => [ 'copy' => true, // Copy instead of install 'path' => 'node_modules', 'manifest' => 'package.json', 'lock' => 'package-lock.json', 'install' => 'npm ci', ], ], 'steps' => [ 'npm run build', 'php artisan storage:link', 'php artisan ziggy:generate', ], ]; ``` -------------------------------- ### Create and Verify Databases Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Initialize a DatabaseManager to create application or test databases and verify their existence. ```php use Mozex\Worktree\Support\DatabaseManager; $config = config('database.connections.mysql'); $db = new DatabaseManager($config); // Create an application database $db->create('blog_feature_login'); // Create a test database $db->create('blog_feature_login_testing'); // Check if database exists if ($db->exists('blog_feature_login')) { echo 'Database already exists'; } ``` -------------------------------- ### Command Usage Syntax Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/03-commands.md Basic command structure for initializing a new worktree. ```bash php artisan worktree:setup [branch] [options] ``` -------------------------------- ### Initialize PhpunitConfig instance Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Create a new instance from an existing PHPUnit XML file. ```php use Mozex\Worktree\Support\PhpunitConfig; $config = PhpunitConfig::fromFile('phpunit.xml'); ``` -------------------------------- ### Get a Worktree Path Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/README.md Retrieves the filesystem path for a specific worktree, useful for shell integration. ```bash php artisan worktree:path feature/login # Output: /path/to/worktree (useful for cd integration) ``` -------------------------------- ### Get environment variable value Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/02-env-file-editor.md Retrieve the value of a specific key, with automatic trimming of whitespace and quotes. ```php $env = EnvFile::fromFile('.env'); // Given: APP_URL="https://blog.test" echo $env->get('APP_URL'); // Output: https://blog.test // Given: DB_PASSWORD=secret echo $env->get('DB_PASSWORD'); // Output: secret // Key does not exist echo $env->get('MISSING_KEY'); // Output: null ``` -------------------------------- ### Create Database Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Create a new database on the server using the configured driver. ```php $db = new DatabaseManager(config('database.connections.mysql')); $db->create('blog_feature_x'); ``` -------------------------------- ### Create Worktree Instance Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/01-worktree-value-object.md Use the make factory method to initialize a Worktree instance with the required repository path, branch, and configuration. ```php use Mozex\Worktree\Worktree; $worktree = Worktree::make( '/Users/you/Sites/blog', 'feature/login', config('worktree') ); ``` -------------------------------- ### Install Laravel Worktree as a dev dependency Source: https://github.com/mozex/laravel-worktree/blob/main/README.md Use Composer to add the package to your project's development dependencies. ```bash composer require mozex/laravel-worktree --dev ``` -------------------------------- ### Create a Worktree Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/INDEX.md Commands to initialize a new worktree, optionally specifying a branch name, base branch, or printing the path. ```bash php artisan worktree:setup feature/login php artisan worktree:setup # Auto-generate branch php artisan worktree:setup --base=develop # Base off develop php artisan worktree:setup --print-path # Get path for shell ``` -------------------------------- ### List worktrees Source: https://github.com/mozex/laravel-worktree/blob/main/resources/boost/skills/laravel-worktree/SKILL.md Displays the branch, path, URL, and database name for each existing worktree. ```bash php artisan worktree:list ``` -------------------------------- ### Customize Configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/INDEX.md Publish the package configuration file to the project's config directory. ```bash php artisan vendor:publish --tag=worktree-config # Edit config/worktree.php ``` -------------------------------- ### Create a Worktree Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/README.md Commands to initialize a new worktree, optionally specifying a branch or base branch. ```bash php artisan worktree:setup feature/login # Output: path, branch, URL, databases # Or auto-generate branch name php artisan worktree:setup # Or specify base branch php artisan worktree:setup --base=develop # Get path for shell integration php artisan worktree:setup --print-path ``` -------------------------------- ### Publish Configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Command to publish the package configuration file to the local project. ```bash php artisan vendor:publish --tag=worktree-config ``` -------------------------------- ### List and Navigate Worktrees Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/INDEX.md Commands to list existing worktrees and retrieve their filesystem paths for navigation. ```bash php artisan worktree:list # List all php artisan worktree:path feature/login # Get path cd "$(php artisan worktree:path feature/login)" # Jump to worktree ``` -------------------------------- ### DatabaseManager::__construct Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Initializes the DatabaseManager with the provided database configuration. ```APIDOC ## __construct(array $config) ### Description Initializes the DatabaseManager instance with database connection configuration. ### Parameters - **config** (array) - Required - Database connection configuration containing driver, host, port, username, password, and database. ``` -------------------------------- ### Customize Configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/README.md Publishes the configuration file to allow customization of worktree behavior. ```bash # Publish the config file php artisan vendor:publish --tag=worktree-config # Edit config/worktree.php # Changes take effect immediately (unless config is cached) ``` -------------------------------- ### Configure Environment Copy Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Lists additional gitignored environment files to copy into the worktree. ```php 'env' => [ 'copy' => ['.env.testing', '.env.local'], ], ``` -------------------------------- ### Apply Multiple Environment Changes Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/02-env-file-editor.md Use the fluent interface to chain multiple configuration updates and save the file in a single operation. ```php $env = EnvFile::fromFile($source) ->set('DB_DATABASE', $dbName) ->set('REDIS_PREFIX', $redisPrefix) ->set('CACHE_PREFIX', $cachePrefix) ->remapHost($sourceHost, $worktreeHost) ->save($targetPath); ``` -------------------------------- ### Build Custom Worktree Templates Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/01-worktree-value-object.md Shows how to define custom database connection templates within the Worktree configuration. ```php // App-specific template with two connections $config = [ 'database' => [ 'connections' => [ ['connection' => null, 'name' => '{slug}'], ['connection' => 'analytics', 'name' => '{slug}_analytics'], ], ], ]; $worktree = Worktree::make('/path/to/repo', 'feature/x', $config); $appDb = $worktree->database(config('worktree.database.connections.0.name')); $analyticsDb = $worktree->database(config('worktree.database.connections.1.name')); ``` -------------------------------- ### EnvFile::fromFile(string $path) Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/02-env-file-editor.md Creates a new EnvFile instance by loading the contents of a .env file from the specified disk path. ```APIDOC ## EnvFile::fromFile(string $path) ### Description Loads .env file contents from disk and returns a new instance of the EnvFile class. ### Parameters - **path** (string) - Required - Path to the .env file ### Returns - **self** - New EnvFile instance ### Throws - **Exception** - If file cannot be read ``` -------------------------------- ### Create a new worktree Source: https://github.com/mozex/laravel-worktree/blob/main/resources/boost/skills/laravel-worktree/SKILL.md Run this command from the main repository to initialize a new worktree for a specific branch. ```bash php artisan worktree:setup feature/login ``` -------------------------------- ### Configure Composer Dependencies Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Settings for provisioning Composer vendor directories. ```php 'dependencies' => [ 'vendor' => [ 'copy' => (bool) env('WORKTREE_COPY_VENDOR', false), 'path' => 'vendor', 'manifest' => 'composer.json', 'lock' => 'composer.lock', 'install' => 'composer install', ], ], ``` -------------------------------- ### Manage Multiple Environment Files Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Process multiple environment files, such as standard and testing configurations, for a single worktree. ```php // Main .env $env = EnvFile::fromFile('.env') ->set('DB_DATABASE', 'blog_feature_x') ->remapHost('blog.test', 'blog-feature-x.test') ->save('/path/to/worktree/.env'); // .env.testing (if it exists in source) $envTesting = EnvFile::fromFile('.env.testing') ->set('DB_DATABASE', 'blog_feature_x_testing') ->remapHost('blog.test', 'blog-feature-x.test') ->save('/path/to/worktree/.env.testing'); ``` -------------------------------- ### Configure Multi-Connection Databases Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Maps multiple database connections to worktree-specific names and test environments within the configuration file. ```php // config/database.php 'connections' => [ 'default' => [ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'blog', ], 'analytics' => [ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'analytics', ], 'cache_db' => [ 'driver' => 'sqlite', 'database' => 'database/cache.sqlite', ], ], // config/worktree.php 'database' => [ 'connections' => [ // Default connection [ 'connection' => null, 'env' => 'DB_DATABASE', 'name' => '{slug}', 'test' => ['env' => 'DB_DATABASE', 'name' => '{slug}_testing'], ], // Analytics connection [ 'connection' => 'analytics', 'env' => 'ANALYTICS_DB_DATABASE', 'name' => '{slug}_analytics', 'test' => ['env' => 'ANALYTICS_DB_DATABASE', 'name' => '{slug}_analytics_testing'], ], // Cache database (SQLite, no test needed) [ 'connection' => 'cache_db', 'env' => 'CACHE_DB_DATABASE', 'name' => '{name}/cache.sqlite', // No test block - SQLite is isolated ], ], ], ``` -------------------------------- ### Copy and Modify .env Files Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/02-env-file-editor.md Load an existing .env file, apply modifications to database and host settings, and save the result to a new location. ```php use Mozex\\\Worktree\\\Support\\\EnvFile; use Illuminate\\\Support\\\Facades\\\File; $source = '/path/to/main/.env'; $worktree = '/path/to/worktree'; // Load from source $env = EnvFile::fromFile($source); // Apply database changes $env->set('DB_DATABASE', 'blog_feature_x'); // Remap the host $env->remapHost('blog.test', 'blog-feature-x.test'); // Save to worktree $env->save($worktree . '/.env'); ``` -------------------------------- ### Initialize DatabaseManager Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Constructor for the DatabaseManager class requiring a configuration array. ```php public function __construct(protected array $config): void ``` -------------------------------- ### DatabaseManager::create Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Creates a new database on the server. ```APIDOC ## create(string $database) ### Description Creates a database on the server. Throws WorktreeException on unsupported drivers. ### Parameters - **database** (string) - Required - The name of the database to create. ``` -------------------------------- ### Configure Node Dependencies Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Settings for provisioning node_modules using npm ci. ```php 'dependencies' => [ 'node_modules' => [ 'copy' => (bool) env('WORKTREE_COPY_NODE_MODULES', false), 'path' => 'node_modules', 'manifest' => 'package.json', 'lock' => 'package-lock.json', 'install' => 'npm ci', ], ], ``` -------------------------------- ### Enable Dependency Copying Source: https://github.com/mozex/laravel-worktree/blob/main/README.md Enable directory copying for vendor and node_modules to speed up worktree creation when lock files match the main repository. ```php 'dependencies' => [ 'vendor' => ['copy' => true, /* ... */], 'node_modules' => ['copy' => true, /* ... */], ], ``` -------------------------------- ### PhpunitConfig::fromFile(string $path) Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Creates a new instance of PhpunitConfig by loading a PHPUnit XML configuration file. ```APIDOC ## PhpunitConfig::fromFile(string $path) ### Description Loads a phpunit.xml or phpunit.xml.dist file into a new PhpunitConfig instance. ### Parameters - **path** (string) - Required - Path to the PHPUnit XML file. ### Returns - **self** - A new instance of PhpunitConfig. ### Throws - **WorktreeException** - If the file cannot be parsed as valid XML. ### Example ```php use Mozex\Worktree\Support\PhpunitConfig; $config = PhpunitConfig::fromFile('phpunit.xml'); ``` ``` -------------------------------- ### Create a Worktree via CLI Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Initializes a new worktree for a specific branch using the artisan command. ```bash # Interactive: creates worktree and shows summary php artisan worktree:setup feature/login # Output: # Creating worktree [blog-feature-login] on branch [feature/login] # Worktree ready. # +---------------+------------------------------------------+ # | Path | /Users/you/Sites/blog-feature-login | # | Branch | feature/login | # | URL | https://blog-feature-login.test | # | Database | blog_feature_login | # | Test database | blog_feature_login_testing | # +---------------+------------------------------------------+ ``` -------------------------------- ### Configure Environment Source Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Specifies the source environment file to copy into the worktree. ```php 'env' => [ 'source' => '.env', ], ``` -------------------------------- ### Read Environment Variables Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Retrieve specific keys or list all available keys from an environment file. ```php $env = EnvFile::fromFile('.env'); // Get a value $appUrl = $env->get('APP_URL'); // https://blog.test $dbHost = $env->get('DB_HOST'); // localhost $missing = $env->get('MISSING_KEY'); // null // Get all keys $keys = $env->keys(); // ['APP_NAME', 'APP_URL', 'DB_HOST', 'DB_DATABASE', ...] ``` -------------------------------- ### Accessing Configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/07-service-provider.md Retrieve configuration values using the Config facade or the Arr helper. ```php use Illuminate\Support\Facades\Config; $config = Config::get('worktree'); $path = Config::get('worktree.path'); $herd = Config::get('worktree.herd'); ``` ```php use Illuminate\Support\Arr; $template = Arr::get($config, 'host.template', '{repo}-{branch}'); ``` -------------------------------- ### Common Artisan Commands Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/00-START-HERE.md Standard CLI commands for managing worktree lifecycles and configuration. ```bash php artisan worktree:setup feature/login ``` ```bash php artisan worktree:teardown ``` ```bash php artisan worktree:list ``` ```bash php artisan worktree:path feature/login ``` ```bash php artisan vendor:publish --tag=worktree-config ``` -------------------------------- ### Handle SQLite Database Files Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Ensure file-based SQLite databases are correctly initialized and identified. ```php $config = config('database.connections.sqlite'); $db = new DatabaseManager($config); // Ensure SQLite file exists $db->ensureFile('/path/to/database.sqlite'); // Check if it's a file-based driver if ($db->isFile()) { echo 'SQLite driver detected'; } ``` -------------------------------- ### Architecture Overview Diagram Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/README.md Visual representation of the package components, including service providers, commands, and core value objects. ```text WorktreeServiceProvider ├── Registers config/worktree.php ├── Registers 4 Artisan commands └── Deep-merges published config overrides SetupCommand (worktree:setup) ├── Validates main repository ├── CreateWorktree: git worktree add ├── ServeWithHerd: herd link + secure ├── PrepareEnvironment: copy .env, remap host ├── CopyExtraEnvironmentFiles: .env.testing ├── ProvisionDependencies: vendor, node_modules ├── PrepareDatabase: create databases, patch phpunit.xml └── RunSteps: npm run build, storage:link, etc. TeardownCommand (worktree:teardown) ├── FinishBranch: --pr, --into, --abandon ├── DropDatabases: per connection + parallel derivatives ├── UnsecureSite: herd unsecure ├── UnlinkSite: herd unlink └── RemoveWorktree: git worktree remove Worktree (value object) ├── name(): template expansion ├── host(): full hostname ├── path(): resolved directory ├── slug(): database-safe name ├── database(template): fitted database name └── tokens(): all available tokens EnvFile (value object) ├── get/set: read/write keys ├── remapHost: rewrite hostnames └── save: write to disk DatabaseManager (value object) ├── create/drop: database operations ├── exists: check if database exists ├── isServer/isFile: driver classification └── parallelDerivatives: discover test databases ``` -------------------------------- ### Package Registered Method Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/07-service-provider.md Defines the hook called after package registration to handle configuration logic. ```php public function packageRegistered(): void ``` -------------------------------- ### Project Directory Structure Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/README.md Visual representation of the package file hierarchy, including source code, configuration, and test directories. ```text src/ Worktree.php # Value object: names, paths, databases WorktreeServiceProvider.php # Package registration Commands/ WorktreeCommand.php # Base class, shared logic SetupCommand.php # worktree:setup TeardownCommand.php # worktree:teardown ListCommand.php # worktree:list PathCommand.php # worktree:path Support/ EnvFile.php # .env file editor DatabaseManager.php # Database operations PhpunitConfig.php # phpunit.xml editor WorktreeList.php # Parse git worktree list Directory.php # Recursive delete, isEmpty Enums/ HerdMode.php # secure | link | none MigrateMode.php # fresh | migrate | none FinishMode.php # pr | merge | abandon Exceptions/ WorktreeException.php # All exceptions config/ worktree.php # Default configuration tests/ ArchTest.php # Architecture tests CommandsTest.php # Full command integration tests ConfigMergeTest.php # Config deep-merge tests DatabaseManagerTest.php # Database operations tests [... unit tests for each class] ``` -------------------------------- ### Retrieve source path Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/01-worktree-value-object.md Returns the absolute path to the main repository directory with normalized separators. ```php public function sourcePath(): string ``` ```php echo $worktree->sourcePath(); // Output: /Users/you/Sites/blog ``` -------------------------------- ### Configure Environment Replacements Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Defines templates for rewriting specific environment variables per worktree. ```php 'env' => [ 'replace' => [ 'REDIS_PREFIX' => '{value}{slug}_', 'CACHE_PREFIX' => '{slug}_cache_', 'QUEUE_PREFIX' => 'queue_{slug}_', ], // Given REDIS_PREFIX=laravel_database_ // Becomes: laravel_database_blog_feature_login_ ], ``` -------------------------------- ### Configure Database Migration Strategy Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Defines the migration behavior for the default database connection. ```php 'database' => [ 'migrate' => env('WORKTREE_MIGRATE', 'fresh'), ], ``` -------------------------------- ### Navigating to Worktrees via Shell Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Use shell expansion or custom functions to quickly change directories into a specific worktree path. ```bash # Directly with shell expansion WORKTREE=$(php artisan worktree:path feature/login) cd "$WORKTREE" # Or in a shell function function cdt() { cd "$(php artisan worktree:path $1)" || return } # Usage cdt feature/login ``` -------------------------------- ### Configure Host Remapping Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Enables automatic rewriting of the source host in the copied .env file. ```php 'host' => [ 'remap_source_host' => (bool) env('WORKTREE_REMAP_HOST', true), // Given APP_URL=https://blog.test, becomes https://blog-feature-login.test ], ``` -------------------------------- ### Extend the Base Service Provider Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/07-service-provider.md Override configurePackage or packageRegistered methods to inject custom logic into the package lifecycle. ```php // In a custom service provider namespace App\Providers; use Mozex\Worktree\WorktreeServiceProvider as BaseProvider; use Spatie\LaravelPackageTools\Package; class WorktreeServiceProvider extends BaseProvider { public function configurePackage(Package $package): void { parent::configurePackage($package); // Add custom commands, config, etc. } public function packageRegistered(): void { parent::packageRegistered(); // Custom post-registration logic } } ``` -------------------------------- ### Ensure SQLite File Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Create the SQLite database file if it does not already exist. ```php $db = new DatabaseManager(config('database.connections.sqlite')); $db->ensureFile('/path/to/database.sqlite'); ``` -------------------------------- ### Configure App URL Key Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Defines the environment key used for the application URL. ```php 'env' => [ 'app_url_key' => 'APP_URL', ], ``` -------------------------------- ### Configure Multiple Database Connections Source: https://github.com/mozex/laravel-worktree/blob/main/README.md Define isolation settings for multiple database connections by specifying the connection name and environment keys. ```php 'database' => [ 'connections' => [ [ 'connection' => null, 'env' => 'DB_DATABASE', 'name' => '{slug}', 'test' => ['env' => 'DB_DATABASE', 'name' => '{slug}_testing'], ], [ 'connection' => 'analytics', // the name from config/database.php 'env' => 'ANALYTICS_DB_DATABASE', // this connection's .env key 'name' => '{slug}_analytics', 'test' => ['env' => 'ANALYTICS_DB_DATABASE', 'name' => '{slug}_analytics_testing'], ], ], ], ``` -------------------------------- ### List Worktrees Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/README.md Displays a list of active worktrees with their associated branch, path, URL, and database. ```bash php artisan worktree:list # Shows: branch, path, URL, database per worktree ``` -------------------------------- ### Retrieve TLD Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/01-worktree-value-object.md Returns the top-level domain from the configuration. ```php public function tld(): string ``` ```php echo $worktree->tld(); // Output: test ``` -------------------------------- ### Interactive Worktree Selection Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Integrate with fzf to interactively select a branch and navigate to its corresponding worktree. ```bash # Use fzf to pick a worktree and cd into it function wt-cd() { local branch=$(git branch --list | fzf --preview 'php artisan worktree:path {}') if [ -n "$branch" ]; then cd "$(php artisan worktree:path $branch)" fi } # Usage wt-cd ``` -------------------------------- ### Configure Worktree Path Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Sets the base directory where worktrees are created. ```php 'path' => env('WORKTREE_PATH', '..'), ``` -------------------------------- ### Copy Gitignored Environment Files Source: https://github.com/mozex/laravel-worktree/blob/main/README.md Configure the package to copy specific gitignored environment files into the worktree. ```php 'env' => [ 'copy' => ['.env.testing'], ], ``` -------------------------------- ### Perform Environment Variable Replacement Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/01-worktree-value-object.md Illustrates using the expand method to replace tokens like {slug} and {value} within environment variable strings. ```php // Configuration $config = [ 'env' => [ 'replace' => [ 'REDIS_PREFIX' => '{value}{slug}_', 'CACHE_PREFIX' => '{slug}_cache_', ], ], ]; $worktree = Worktree::make('/path/to/repo', 'feature/x', $config); // Expansion with {value} token $newRedisPrefix = $worktree->expand( 'laravel_database_{value}{slug}_', ['value' => 'laravel_database_'] ); // Output: laravel_database_laravel_database_blog_feature_x_ ``` -------------------------------- ### Set environment variables in configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Update or create an environment variable within the configuration instance. ```php $config = PhpunitConfig::fromFile('phpunit.xml') ->setEnv('DB_DATABASE', 'blog_feature_x_testing'); ``` -------------------------------- ### Read PHPUnit configuration Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/08-usage-examples.md Access environment variables from a phpunit.xml file using the PhpunitConfig helper. ```php use Mozex\Worktree\Support\PhpunitConfig; $config = PhpunitConfig::fromFile('phpunit.xml'); // Read the test database connection $connection = $config->env('DB_CONNECTION'); // Returns: 'mysql', 'sqlite', or null if not configured // Read a custom variable $customValue = $config->env('CUSTOM_VAR'); ``` -------------------------------- ### Retrieve source host Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/01-worktree-value-object.md Returns the hostname of the main repository, used to identify which hosts in the copied .env need remapping. ```php public function sourceHost(): string ``` ```php echo $worktree->sourceHost(); // Output: blog.test ``` -------------------------------- ### Configure Host Template Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Sets the template used for generating worktree hostnames. ```php 'host' => [ 'template' => env('WORKTREE_HOST_TEMPLATE', '{repo}-{branch}'), // Result: blog-feature-login + .test = blog-feature-login.test ], ``` -------------------------------- ### Save configuration changes to disk Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/04-support-classes.md Persist modifications back to a specified XML file path. ```php $config = PhpunitConfig::fromFile('phpunit.xml') ->setEnv('DB_DATABASE', 'blog_feature_x_testing') ->save('phpunit.xml'); ``` -------------------------------- ### Specify Additional PHPUnit Configuration Files Source: https://github.com/mozex/laravel-worktree/blob/main/README.md List multiple PHPUnit configuration files to be patched for test database isolation. ```php 'phpunit_files' => ['phpunit.xml', 'phpunit.browser.xml'], ``` -------------------------------- ### Define Database Connection Structure Source: https://github.com/mozex/laravel-worktree/blob/main/_autodocs/05-configuration.md Shows the required structure for individual database connection entries. ```php [ 'connection' => null, // Laravel connection name, or null for app default 'env' => 'DB_DATABASE', // The .env key holding the database name 'name' => '{slug}', // The worktree database name template 'test' => [ // Optional: test database 'env' => 'DB_DATABASE', // PHPUnit key 'name' => '{slug}_testing', // Test database name template ], ] ```