### Site Specification Example Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md An example of a site specification used directly on the command line, defining the user, server, Drupal root, and URI for a command execution. ```bash drush user@server/path/to/drupal#uri core:status ``` -------------------------------- ### Example Drush Configuration Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/example.drush.yml.md This snippet shows a comprehensive example of a drush.yml file, demonstrating various configuration options for Drush commands and behaviors. ```yaml --8<-- "examples/example.drush.yml" ``` -------------------------------- ### Drush Command Examples Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/example.prompt.sh.md This snippet contains various Drush commands for common operations. Ensure Drush is installed and accessible in your PATH. ```shell --8<-- "examples/example.prompt.sh" ``` -------------------------------- ### Install Drush and Dependencies Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Standard procedure to clone the Drush repository and install its dependencies using Composer. ```bash git clone https://github.com/drush-ops/drush.git cd drush composer install ``` -------------------------------- ### Drush Site Configuration Example Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/example.site.yml.md This YAML snippet demonstrates a comprehensive example of Drush site configuration. It includes settings for database connections, aliases, and other operational parameters. Ensure this file is placed in the correct Drush configuration directory. ```yaml --8<-- "examples/example.site.yml" ``` -------------------------------- ### Setup System Under Test (SUT) for Drush Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Initializes the System Under Test (SUT) environment for Drush testing. Refer to composer.json for detailed configuration. ```bash composer sut:si ``` -------------------------------- ### Git Bisect Example with Drush Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/git-bisect.example.sh.md This script demonstrates how to use git bisect to find a bug in Drush. It assumes you have a working Drush installation and a Git repository. ```shell #!/bin/bash # This script is an example of how to use git bisect to find a bug in Drush. # It assumes you have a working Drush installation and a Git repository. # Define a function to test a specific commit. # This function should return 0 if the commit is good, and 1 if it is bad. function test_commit { # Build and install Drush. make drush make install # Test Drush. drush --version if [ $? -eq 0 ]; then return 0 else return 1 fi } # Start the git bisect process. git bisect start # Add a known good commit. git bisect good # Add a known bad commit. git bisect bad # Run the bisect process. while git bisect list | grep -q 'running'; do test_commit if [ $? -eq 0 ]; then git bisect good else git bisect bad fi done # Print the result. git bisect log ``` -------------------------------- ### Find Module Dependents (All) Source: https://github.com/drush-ops/drush/blob/14.x/docs/drupal-dependencies.md Retrieves all module dependents, regardless of installation status. Use `--format` for machine-readable output like YAML or JSON. ```bash drush why:module node --type=module --no-only-installed ``` -------------------------------- ### Hello World Drush Script Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/helloworld.script.md A basic Drush script that prints 'Hello world!'. This is a good starting point for creating custom Drush commands. ```php --8<-- "examples/helloworld.script" ``` -------------------------------- ### Start DDEV Containers for Drush Tests Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Initiates the Docker containers managed by DDEV for running Drush tests in a containerized environment. ```bash ddev start ``` -------------------------------- ### Find Module Dependents (Installed) Source: https://github.com/drush-ops/drush/blob/14.x/docs/drupal-dependencies.md Shows all installed modules that depend on a specific module. Results are rendered as a tree, marking circular dependencies. ```bash drush why:module node --type=module ``` -------------------------------- ### Example PSR4 Autoload Configuration Source: https://github.com/drush-ops/drush/blob/14.x/docs/generators.md This JSON snippet shows how to configure PSR4 autoloading for a third-party library, which is necessary for global Drush generators. ```json "autoload": { "psr-4": { "My\\Custom\\Library\\": "src" } } ``` -------------------------------- ### Get Help for Migrate Import Command Source: https://github.com/drush-ops/drush/blob/14.x/docs/migrate.md To understand the options and usage of a specific migrate command, such as 'migrate:import', use the --help flag. This provides detailed information about the command's parameters and functionality. ```bash drush migrate:import --help ``` -------------------------------- ### List All Migrate Commands Source: https://github.com/drush-ops/drush/blob/14.x/docs/migrate.md Use this command to display all available Drush commands related to the migrate module. Ensure the 'migrate' module is enabled in your Drupal installation. ```bash drush --filter=migrate ``` -------------------------------- ### Complex Site Alias Configuration Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Example of a comprehensive site alias configuration file defining host, user, root, URI, SSH options, paths, environment variables, and command-specific options. ```yaml live: host: server.domain.com user: www-admin root: /other/path/to/drupal uri: http://example.com ssh: options: '-p 100' paths: drush-script: '/path/to/drush' env-vars: PATH: /bin:/usr/bin:/home/www-admin/.composer/vendor/bin DRUPAL_ENV: live command: site: install: options: admin-password: 'secret-secret' ``` -------------------------------- ### Filter by Multiple Fields with AND Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Combine multiple filter conditions using the logical AND operator '&&'. This example searches for core requirement notices where the title matches a regex and the severity is 'warning'. ```shell drush core:requirements --filter='title~=#(php|gd)#i&&severity=warning' ``` -------------------------------- ### Execute Drush Commands Source: https://github.com/drush-ops/drush/blob/14.x/docs/install.md After installing Drush via Composer, execute commands from your project root using the vendor binary. Adding the vendor/bin directory to your PATH simplifies this process. ```bash vendor/bin/drush ``` -------------------------------- ### Custom Drush Generator Class Example Source: https://github.com/drush-ops/drush/blob/14.x/docs/generators.md An example of a custom Drush generator class that follows PSR4 auto-discovery rules. The class namespace should be `[BaseNamespace]\Drush\Generators`. ```php io()->success('Generator executed.'); } } ``` -------------------------------- ### Configure Drush Alias Path Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Example of how to configure Drush to look for site alias files in a custom directory, useful for service providers managing multiple sites. ```yaml drush: paths: alias-path: - '${env.HOME}/.drush/sites/provider-name' ``` -------------------------------- ### Drush Alias for Kubernetes Transport Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Configure Drush to run commands on a Kubernetes cluster using kubectl. This example specifies the context, namespace, resource, and container for the Drupal deployment. ```yaml prod: kubectl: context: "gke_production_cluster" namespace: 'my-drupal-namespace' resource: 'pods/my-drupal-pod' container: 'drupal' ``` -------------------------------- ### Site Alias Alter Commands Example Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/SiteAliasAlterCommands.php.md This PHP code demonstrates how to implement site alias alter commands in Drush. It shows how to define a command that can modify alias definitions. ```php 'http://example.com', 'root' => '/path/to/drupal/root', 'user' => 'www-data', 'db-url' => 'mysql://user:password@host/database', ]; $this->logger()->success(dt('Added alias @alias.', ['@alias' => 'example-site'])); } // Example: Modify an existing alias definition. if (isset($aliases['production'])) { $aliases['production']['user'] = 'prod_user'; $this->logger()->success(dt('Modified user for alias @alias.', ['@alias' => 'production'])); } } } ``` -------------------------------- ### Execute Command on Local Site Alias Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Run Drush commands targeting a specific environment of a local site alias. This command targets the 'dev' environment of the 'example' site alias. ```bash drush @example.dev status ``` -------------------------------- ### Exclude Rows with Negation Operator Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Use the negation operator '!' to exclude rows that match a specific condition. This example excludes watchdog entries where the type is 'locale'. ```shell drush watchdog:show --filter="type!=locale" ``` -------------------------------- ### Drush Alias for Docker Compose Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Example Drush alias configuration for a Docker hosted Drupal site using the DockerCompose transport. This configuration specifies service details and paths. ```yaml # File: mysite.site.yml local: This environment is an example of the DockerCompose transport. docker: service: drupal exec: options: --user USER stage: uri: http://stage.example.com root: /path/to/remote/drupal/root host: mystagingserver.myisp.com user: publisher os: Linux paths: - files: sites/mydrupalsite.com/files - custom: /my/custom/path command: sql: sync: options: no-dump: true dev: root: /path/to/docroot uri: https://dev.example.com ``` -------------------------------- ### Execute Command on Remote Environment Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Run Drush commands on a specific remote environment by prefixing the environment name with '@'. For example, to rebuild the cache on the 'live' environment. ```bash drush @live cache:rebuild ``` -------------------------------- ### Filter by Regular Expression Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Use the '~=' operator with a regular expression to find rows where a field matches a pattern. This example finds core requirement notices whose title contains 'php' or 'gd', case-insensitively. ```shell drush core:requirements --filter='title~=#(php|gd)#i' ``` -------------------------------- ### List All Sites and Environments Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Command to list all sites and environments available within a specified provider's alias path. ```bash drush site:alias @provider-name ``` -------------------------------- ### Equivalent Command Without Alias Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md This command demonstrates the equivalent of using a site alias, showing the explicit --root and --uri options required to achieve the same result. ```bash drush --root=/path/to/drupal --uri=http://example.com status ``` -------------------------------- ### Inject Services with create() Method Source: https://github.com/drush-ops/drush/blob/14.x/docs/dependency-injection.md Implement a create() method in command files to inject services when not using Autowire. This method receives a PSR container and should return an instance of the command class. ```php class WootStaticFactoryCommand extends Command { protected $configFactory; protected function __construct($configFactory) { $this->configFactory = $configFactory; } public static function create(Psr\Container\ContainerInterface $container): self { return new static($container->get('config.factory')); } } ``` -------------------------------- ### Reference Site Alias by Full Name Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Demonstrates how to reference a site alias using its full name, including the provider name, from the command line. ```bash drush @provider-name.example.dev ``` -------------------------------- ### List All Site Aliases Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Display all defined site aliases for the current site using the 'site:alias' command with the '@self' specifier. ```bash drush site:alias @self ``` -------------------------------- ### Drush Help Command for Version Output Formats Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md The `help` command for a specific Drush command lists available output formats, such as json, string, var_export, and yaml. ```shell $ drush help version Show drush version. Options: --format= Select output format. Available: json, string, var_export, yaml. Default is key-value. ``` -------------------------------- ### Run Drush Command Source: https://github.com/drush-ops/drush/blob/14.x/docs/usage.md Execute Drush commands from your project's root directory. Use the `help` command to discover available options and commands. ```bash drush [options] [argument1] [argument2] ``` ```bash drush help pm:list ``` ```bash drush topic ``` -------------------------------- ### List Site and Environment Names Only Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Command to list only the names of sites and environments, excluding alias record values, by using the --format=list option. ```bash drush site:alias @provider-name --format=list ``` -------------------------------- ### Drush Help Command for Views List Fields Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md The `help` text for a command details the available fields, including their human-readable and machine names. ```shell $ drush help views:list Get a list of all views in the system. Options: --fields=FIELDS Available fields: Machine name (machine-name), Name (label), Description (description), Status (status), Tag (tag) [default: "machine-name,label,description,status"] ``` -------------------------------- ### Filter by Field Containing String Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Use the '*=' operator to find rows where a specific field contains a given string. This example finds views whose machine name contains 'content'. ```shell drush views:list --filter='machine-name*=content' ``` -------------------------------- ### Basic Drush Extension Test Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Demonstrates a simple test case for a custom Drush command using Drush test traits. It calls a command with parameters and flags, then asserts the output. ```php public function testMyCommand() { $this->drush('my:command', ['param'], ['flag' => 'value']); $this->assertOutputEquals('The parameter is "param" and the "flag" option is "value"'); } ``` -------------------------------- ### Drush Deploy Command Sequence Source: https://github.com/drush-ops/drush/blob/14.x/docs/deploycommand.md This sequence outlines the typical steps executed by the Drush deploy command. Note that `drush cache:warm` is only available in Drupal 11.2+. ```shell drush updatedb drush config:import drush cache:rebuild drush deploy:hook drush cache:warm (Drupal 11.2+) ``` -------------------------------- ### Drush Views List with Selected Fields Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Use the `--fields` option to specify which columns to display and in what order from the `views:list` command. ```shell $ drush views:list --fields=machine-name,status +-------------------+----------+ | Machine name | Status | +-------------------+----------+ | block_content | Enabled | | comment | Enabled | | comments_recent | Enabled | | content | Enabled | | content_recent | Enabled | | files | Enabled | | frontpage | Enabled | | taxonomy_term | Enabled | | user_admin_people | Enabled | | watchdog | Enabled | | who_s_new | Enabled | | who_s_online | Enabled | | archive | Disabled | | glossary | Disabled | +-------------------+----------+ ``` -------------------------------- ### Hourly Drush Cron Crontab Entry Source: https://github.com/drush-ops/drush/blob/14.x/docs/cron.md This crontab entry runs Drush cron tasks every hour at ten minutes past the hour. Ensure [DOCROOT] is replaced with your Drupal installation's document root and your.drupalsite.org with your site's URI. ```bash 10 * * * * cd [DOCROOT] && /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 ../vendor/bin/drush --uri=your.drupalsite.org --quiet maint:status && /usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin COLUMNS=72 ../vendor/bin/drush --uri=your.drupalsite.org --quiet cron ``` -------------------------------- ### Change Site Name using Configuration Override Source: https://github.com/drush-ops/drush/blob/14.x/docs/config-exporting.md Use the configuration override system in settings.php to change configuration values for a specific site instance, such as the development server. This method is preferred for per-environment changes but may not work for all configurations. ```php $config['system.site']['name'] = 'Local Install of Awesome Widgets, Inc.'; ``` -------------------------------- ### Define Local Site Environments Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Configure local site environments by creating a self.site.yml file in the project's drush/sites directory. This file defines different environments like 'live' and 'stage' with their respective host, user, root, and URI. ```yaml # File: self.site.yml live: host: server.domain.com user: www-admin root: /other/path/to/live/drupal uri: http://example.com stage: host: server.domain.com user: www-admin root: /other/path/to/stage/drupal uri: http://stage.example.com ``` -------------------------------- ### Define Local Drupal Site Alias Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Create an alias file for a local Drupal site by naming the file after the alias (e.g., example.site.yml). This file defines environments for the local site, such as 'dev'. ```yaml # File: example.site.yml dev: root: /path/to/drupal uri: http://example.com ``` -------------------------------- ### Run All Drush Test Suites Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Execute all available test suites for Drush using Composer. ```bash composer test ``` -------------------------------- ### Create a New Drupal Module Source: https://github.com/drush-ops/drush/blob/14.x/docs/generators.md If the target module for your generator does not exist, use this command to create a new one first. ```bash drush generate module ``` -------------------------------- ### Inject Drush and Drupal Services with AutowireTrait Source: https://github.com/drush-ops/drush/blob/14.x/docs/dependency-injection.md Use AutowireTrait in command files to inject services via constructor parameter type hints or #[Autowire] attributes. This is the recommended approach for Drush 12.5+. ```php protected readonly Consolidation\OutputFormatters\FormatterManager $formatterManager protected readonly Psr\Log\LoggerInterface $logger protected readonly Drush\SiteAlias\ProcessManager $processManager protected readonly Consolidation\SiteAlias\SiteAliasManagerInterface $siteAliasManager protected readonly \Drush\Config\DrushConfig $drushConfig protected readonly Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager ``` -------------------------------- ### Drush Version Output in Table and JSON Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Use the `--format` option to switch between the default human-readable table and machine-parsable JSON output for the `version` command. ```shell $ drush version Drush version : 10.3.1 ``` ```shell $ drush version --format=json { "drush-version": "10.3.1" } ``` -------------------------------- ### Create a New Drush Generator Source: https://github.com/drush-ops/drush/blob/14.x/docs/generators.md Use this command to initiate the creation of a new Drush generator. You will be prompted to select a module to own the generated files. ```bash drush generate drush:generator ``` -------------------------------- ### Find Config Entities Depending on a Module Source: https://github.com/drush-ops/drush/blob/14.x/docs/drupal-dependencies.md Identifies all configuration entities that depend on a given module. The `--format` option can be used to obtain structured data. ```bash drush why:module node --type=config ``` -------------------------------- ### Run Specific Drush Test Suites Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Commands to execute individual test suites: unit, integration, or functional. ```bash composer unit ``` ```bash composer integration ``` ```bash composer functional ``` -------------------------------- ### Implement a Drush Listener Source: https://github.com/drush-ops/drush/blob/14.x/docs/listeners.md To implement a listener, create a class within the `Drupal\\Drush\Listeners` namespace. The class must end with 'Listener.php' and implement the `AsEventListener` attribute. Logic is defined in the `__invoke` method, which accepts an event object. ```php #[Symfony\Component\EventDispatcher\Attribute\AsEventListener] public function __invoke(ConsoleDefinitionsEvent $event) { // Listener logic here } ``` -------------------------------- ### Global Drush Options Source: https://github.com/drush-ops/drush/blob/14.x/docs/using-drush-configuration.md Configure global Drush options such as the base URL for generating links, specifying a non-standard configuration location, or enabling verbose mode. ```yml options: # Specify the base_url that should be used when generating links. uri: 'https://example.com/subdir' # Load Drush config from a non-standard location config: '/home/USER/workspace/drupal' # Enable verbose mode. verbose: true ``` -------------------------------- ### Specify Personal Config Files Source: https://github.com/drush-ops/drush/blob/14.x/docs/using-drush-configuration.md Load personal Drush configuration files from a specified path. The path can point to a file or a directory containing `drush.yml` files. This is silently skipped if the path is not found. ```yml drush: paths: config: # Load any personal config files. Is silently skipped if not found. Filename must be drush.yml - ${env.HOME}/.drush/config/drush.yml ``` -------------------------------- ### Compare Drush Filter with Grep (Semantic vs. Line-based) Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Illustrates the difference between Drush's semantic filtering and grep's line-based searching. Drush filters semantically on fields, while grep searches entire lines. ```shell #!shell drush core:requirements --filter='severity=warning' ``` ```shell #!shell drush core:requirements | grep -i warning ``` -------------------------------- ### Define Drush Command using Console Attributes (Recommended) Source: https://github.com/drush-ops/drush/blob/14.x/docs/commands.md This snippet demonstrates the recommended way to define a Drush command using Symfony Console attributes, available in Drush 13.7+. Ensure your class name ends with 'Command.php'. Dependencies like FormatterManager, TwigEnvironment, and LoggerInterface are injected via the constructor. ```php namespace Drupal\[module-name]\Drush\Commands; use Consolidation\OutputFormatters\FormatterManager; use Consolidation\OutputFormatters\StructuredData\RowsOfFields; use Drupal\Core\Template\TwigEnvironment; use Drush\Attributes as CLI; use Drush\Commands\AutowireTrait; use Drush\Formatters\FormatterTrait; use Psr\Log\LoggerInterface; use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; #[AsCommand( name: self::NAME, description: 'Find potentially unused Twig templates.', aliases: ['twu'], )] #[CLI\FieldLabels(labels: ['template' => 'Template', 'compiled' => 'Compiled'])] #[CLI\DefaultTableFields(fields: ['template', 'compiled'])] #[CLI\FilterDefaultField(field: 'template')] #[CLI\Formatter(returnType: RowsOfFields::class, defaultFormatter: 'table')] final class TwigUnusedCommand extends Command { use AutowireTrait; use FormatterTrait; public const NAME = 'twig:unused'; public function __construct( protected readonly FormatterManager $formatterManager, protected readonly TwigEnvironment $twig, private readonly LoggerInterface $logger ) { parent::__construct(); } protected function configure(): void { $this ->setHelp('Immediately before running this command, web crawl your entire web site.') ->addArgument('searchpaths', InputArgument::REQUIRED, 'A comma delimited list of paths to recursively search.') ->addUsage('twig:unused /var/www/mass.local/docroot/modules/custom'); } public function execute(InputInterface $input, OutputInterface $output): int { $data = $this->doExecute($input, $output, $input->getArgument('searchpaths')); $this->writeFormattedOutput($input, $output, $data); return Command::SUCCESS; } public function doExecute(InputInterface $input, OutputInterface $output, string $searchpaths): RowsOfFields { $this->logger->notice('Found {count} unused', ['count' => count($rows)]); return new RowsOfFields($unused); } } ``` -------------------------------- ### PHP Policy Listener Implementation Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/PolicyListener.php.md This snippet shows a basic implementation of a Policy Listener in PHP. It defines a class that can be used to intercept and modify command execution within Drush. ```php notice(sprintf('PolicyListener: Pre-command event for %s', $command)); // You can return a value to alter the command's execution flow. // For example, returning a specific exit code might abort the command. // return 1; // Abort command } // Handle other events as needed. if ($event === 'post-command') { Drush::logger()->notice('PolicyListener: Post-command event triggered.'); } } /** * {@inheritdoc} */ public static function getSubscribedEvents(): array { return [ 'pre-command' => ['onEvent', 0], 'post-command' => ['onEvent', 0], // Add other events to subscribe to. // 'pre-execute' => ['onEvent', 0], // 'post-execute' => ['onEvent', 0], ]; } } ``` -------------------------------- ### Implement Custom Event Hook Source: https://github.com/drush-ops/drush/blob/14.x/docs/hooks.md This command uses a custom event 'my-event' to collect data from handlers. Ensure the hook manager is injected into the command handler via `setHookManager()` for handlers to be found. ```php /** * This command uses a custom event 'my-event' to collect data. Note that * the event handlers will not be found unless the hook manager is * injected into this command handler object via `setHookManager()` * (defined in CustomEventAwareTrait). */ #[CLI\]Command(name: 'example:command')] public function exampleCommand() { $myEventHandlers = $this->getCustomEventHandlers('my-event'); $result = []; foreach ($myEventHandlers as $handler) { $result[] = $handler(); } sort($result); return implode(',', $result); } ``` -------------------------------- ### Configure Bash Shell Completion Source: https://github.com/drush-ops/drush/blob/14.x/docs/install.md Optional: Append Drush completion commands to your .bashrc (or equivalent for ZSH/Fish) to enable tab completion for Drush commands. Refer to `drush completion --help` for more details. ```bash drush completion --help ``` -------------------------------- ### Use Drush Site Aliases Source: https://github.com/drush-ops/drush/blob/14.x/docs/usage.md Run Drush commands on remote servers using site aliases. Aliases are defined with the '@' nomenclature and can reference specific files or directories. ```bash # Run pending updates on staging site. drush @staging updatedb ``` ```bash # Synchronize staging files to production drush rsync @staging:%files/ @live:%files ``` ```bash # Synchronize database from production to local, excluding the cache table drush sql:sync --structure-tables-key=custom @live @self ``` -------------------------------- ### XkcdFetchCommand.php Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/XkcdFetchCommand.php.md This PHP code defines a custom Drush command for fetching XKCD comics. It requires the 'guzzlehttp/guzzle' package for making HTTP requests. The command allows fetching a specific comic by its number or the latest comic if no number is provided. ```php httpClient = $httpClient; $this->logger = $logger; parent::__construct(); } /** * {@inheritdoc} */ public function setLogger(LoggerInterface $logger) { $this->logger = $logger; } /** * {@inheritdoc} */ protected function configure() { $this->setName('xkcd:fetch') ->setDescription($this->trans('Fetch XKCD comic')) ->setHelp($this->trans('Fetch XKCD comic by number or the latest comic.')) ->addArgument('comic-number', InputArgument::OPTIONAL, $this->trans('The comic number to fetch. If omitted, the latest comic is fetched.')) ->addOption('skip-image', null, InputOption::VALUE_NONE, $this->trans('Do not download the comic image.')); } /** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $comicNumber = $input->getArgument('comic-number'); $skipImage = $input->getOption('skip-image'); try { $url = 'https://xkcd.com/info.0.json'; if ($comicNumber) { $url = sprintf('https://xkcd.com/%s/info.0.json', $comicNumber); } $response = $this->httpClient->request('GET', $url); $data = json_decode($response->getBody()->getContents(), true); if (!$data) { $output->writeln('Failed to decode JSON response.'); return Command::FAILURE; } $output->writeln(sprintf('Comic #%s: %s', $data['num'], $data['title'])); $output->writeln(sprintf('Alt text: %s', $data['alt'])); $output->writeln(sprintf('Date: %s/%s/%s', $data['month'], $data['day'], $data['year'])); if (!$skipImage) { $imageUrl = $data['img']; $imageResponse = $this->httpClient->request('GET', $imageUrl, ['sink' => 'xkcd_comic.png']); $output->writeln(sprintf('Image downloaded to %s', $imageResponse->getHeader('Content-Type')[0])); } return Command::SUCCESS; } catch ( GuzzleHttp\Exception\RequestException $e) { $this->logger->error($e->getMessage()); $output->writeln('Failed to fetch XKCD comic.'); return Command::FAILURE; } } /** * @param string $string * * @return string */ private function trans(string $string): string { // In a real command, you would use a proper translation system. return $string; } } ``` -------------------------------- ### Generate JUnit XML Results for Drush Tests Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Runs functional tests and outputs the results in JUnit XML format to a specified file. ```bash composer functional -- --log-junit results.xml ``` -------------------------------- ### Define Custom Art Commands in PHP Source: https://github.com/drush-ops/drush/blob/14.x/docs/examples/ArtCommands.php.md This snippet shows how to define custom Drush commands in PHP, specifically for art-related operations. Ensure the file is placed in the appropriate Drush commands directory. ```php io()->success('Listing art pieces...'); // In a real scenario, this would fetch and display art data. } /** * @command art:create * @description Create a new art piece. * @param string $title The title of the art piece. * @option string $artist The artist's name. * @aliases art-create,ac */ public function createArt($title, array $options = ['artist' => null]) { $artist = $options['artist']; $this->io()->success("Creating art piece '$title' by artist '$artist'..."); // In a real scenario, this would save the new art data. } /** * @command art:delete * @description Delete an art piece. * @param int $id The ID of the art piece to delete. * @aliases art-delete,ad */ public function deleteArt(int $id) { $this->io()->success("Deleting art piece with ID: $id..."); // In a real scenario, this would remove the art data. } } ``` -------------------------------- ### Set Drush Site URI Source: https://github.com/drush-ops/drush/blob/14.x/docs/usage.md Specify the domain of your site for commands that generate links. This can be done via the DRUSH_OPTIONS_URL environment variable or the --uri option. ```bash drush --uri=http://example.com user:login ``` -------------------------------- ### Specify Backup Directory Source: https://github.com/drush-ops/drush/blob/14.x/docs/using-drush-configuration.md Set a specific folder for Drush to store backup files, including temporary SQL dump files generated during `sql:sync` operations. If not specified, it defaults to `$HOME/drush-backups`. ```yml drush: paths: backup-dir: /tmp/drush-backups ``` -------------------------------- ### Wildcard Alias for Service Providers Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Use a wildcard alias to represent all environments for a service provider. The `${env-name}` variable is substituted with the environment name. ```yaml # File: remote-example.site.yml '*': host: ${env-name}.server.domain.com user: www-admin root: /path/to/${env-name} uri: http://${env-name}.remote-example.com ``` -------------------------------- ### Find Config Entities Depending on Another Config Entity Source: https://github.com/drush-ops/drush/blob/14.x/docs/drupal-dependencies.md Determines which configuration entities depend on a specific configuration entity. Output can be formatted as JSON, YAML, etc. ```bash drush why:config node.type.article ``` -------------------------------- ### Specify Folders for Drush Command Files Source: https://github.com/drush-ops/drush/blob/14.x/docs/using-drush-configuration.md Define directories where Drush should search for command files. These paths are merged with include paths specified on the command line or in other configuration files. ```yml drush: include: - '${env.HOME}/.drush/commands' - /usr/share/drush/commands ``` -------------------------------- ### Specify Folders for Drush Alias Files Source: https://github.com/drush-ops/drush/blob/14.x/docs/using-drush-configuration.md Configure directories where Drush should look for alias files (`*.site.yml`). These paths are merged with alias paths provided via the command line or other configuration sources. ```yml drush: paths: alias-path: - '${env.HOME}/.drush/sites' - /etc/drush/sites ``` -------------------------------- ### Filter Role List by Permission Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Use the --filter option with the default filter field 'perms' to limit the output of the role:list command to roles containing a specific permission. ```shell $ drush role:list --filter='post comments' ``` -------------------------------- ### Run Drush Functional Test with Dirty Environment Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Executes a specific functional test, allowing for changes to the System Under Test (SUT) by setting the UNISH_DIRTY environment variable. ```bash UNISH_DIRTY=1 composer functional -- --filter testUserRole ``` -------------------------------- ### Drush Configuration for Global Commands Source: https://github.com/drush-ops/drush/blob/14.x/docs/commands.md Configure your drush.yml file to include a search location for global commandfiles. This allows Drush to discover commands placed in the specified directory. ```yaml drush: paths: include: - '${env.home}/.drush/commands' ``` -------------------------------- ### Specify Bootstrap Level with Annotation Source: https://github.com/drush-ops/drush/blob/14.x/docs/bootstrap.md Use the `@bootstrap` annotation in a docblock to define the minimum bootstrap level required for a Drush command. This is an alternative to using PHP8 Attributes. ```php /** * @bootstrap none */ public function fetch($search = null, $options = ['image-viewer' => 'open', 'google-custom-search-api-key' => 'AIza']) { $this->doFetch($search, $options); } ``` -------------------------------- ### Drush Views List with Single Field Output Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Using the singular `--field` option forces the output format to `string` and displays only the specified field's values, one per line. ```shell $ drush views:list --field=machine-name block_content comment comments_recent content content_recent files frontpage taxonomy_term user_admin_people watchdog who_s_new who_s_online archive glossary ``` -------------------------------- ### Add Vendor Bin to PATH for Global Access Source: https://github.com/drush-ops/drush/blob/14.x/docs/install.md To call Drush from anywhere without changing directories, add the vendor/bin directory to your system's PATH environment variable. This is particularly useful if you only have one Drupal codebase. ```bash ./vendor/bin ``` -------------------------------- ### Define Custom Event Hook with Annotations Source: https://github.com/drush-ops/drush/blob/14.x/docs/hooks.md Implement a custom event hook using Annotations. The `@hook` annotation specifies the event target. ```php /** * @hook on-event my-event */ public function hookOne() { return 'one'; } ``` -------------------------------- ### Specify Bootstrap Level with PHP8 Attribute Source: https://github.com/drush-ops/drush/blob/14.x/docs/bootstrap.md Use the `#[CLIootstrap]` attribute to define the minimum bootstrap level required for a Drush command. This is useful for commands that do not require a full Drupal environment. ```php use Drush\Attributes as CLI; #[CLI\Bootstrap(level: DrupalBootLevels::NONE)] public function fetch($search = null, $options = ['image-viewer' => 'open', 'google-custom-search-api-key' => 'AIza']) { $this->doFetch($search, $options); } ``` -------------------------------- ### Filter PM List by Status Source: https://github.com/drush-ops/drush/blob/14.x/docs/output-formats-filters.md Filter the output of the pm:list command to show only enabled extensions by specifying a condition on the 'status' field. ```shell $ drush pm:list --filter='status=enabled' ``` -------------------------------- ### Drush Command using Annotated Attributes (Deprecated) Source: https://github.com/drush-ops/drush/blob/14.x/docs/commands.md This snippet shows a deprecated method for defining Drush commands using annotated attributes. It is recommended to use the Console Commands approach instead. ```php use Drush\Attributes as CLI; ``` -------------------------------- ### Displaying Current PATH Environment Variable Source: https://github.com/drush-ops/drush/blob/14.x/docs/cron.md Use this command to display your current PATH environment variable. The output should be used to configure the PATH in your crontab entry for Drush to execute correctly. ```bash echo $PATH ``` -------------------------------- ### Check Drush SUT Status Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Verifies the status of the Drush System Under Test (SUT) environment. ```bash ./drush @sut.dev status ``` -------------------------------- ### Running Drush Cron as a Specific User Source: https://github.com/drush-ops/drush/blob/14.x/docs/cron.md This command demonstrates how to edit the crontab for a specific user, such as 'www-data', which is often the user running the web server. This ensures cron tasks have the correct permissions. ```bash sudo crontab -u www-data -e ``` -------------------------------- ### Drush rsync with Exclude Paths Source: https://github.com/drush-ops/drush/blob/14.x/docs/site-aliases.md Configure default rsync options within a Drush alias, specifically for 'exclude-paths'. This allows for selective synchronization of files by excluding specified directories. ```yaml dev: root: /path/to/docroot uri: https://dev.example.com command: core: rsync: options: mode: rlptz exclude-paths: 'css:imagecache:ctools:js:tmp:php:styles' ``` -------------------------------- ### Run a Specific Drush Test with DDEV Source: https://github.com/drush-ops/drush/blob/14.x/docs/contribute/unish.md Executes a specific functional test within the DDEV environment, filtering by a test name. ```bash ddev exec drupal composer functional -- --filter testUserRole ```