clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
name: drush
type: php
docroot: sut
php_version: "8.1"
webserver_type: nginx-fpm
router_http_port: "87"
router_https_port: "444"
xdebug_enabled: false
additional_hostnames: []
additional_fqdns: []
nfs_mount_enabled: false
mutagen_enabled: false
use_dns_when_possible: true
composer_version: ""
disable_settings_management: true
webimage_extra_packages:
- bash-completion
- asciinema
# https://ddev.readthedocs.io/en/latest/users/extend/database-types/
# When switching DBs, use ddev delete --omit-snapshot
#database:
# type: postgres
# version: 14
web_environment:
- UNISH_DB_URL=mysql://root:root@db
# - "UNISH_DB_URL=sqlite://:memory:"
# - UNISH_DB_URL=pgsql://db:db@db:5432
- DRUSH_OPTIONS_URI=$DDEV_PRIMARY_URL
- EDITOR=nano
@@ -0,0 +1,6 @@
#!/usr/bin/env sh
#@todo make this not fail on Symfony 5-.
# Make ./drush available on PATH.
export PATH=/var/www/html:$PATH
# Suppress error output because this command is not present on Symfony 4.
eval "$(drush completion bash 2>/dev/null)"
+11
View File
@@ -0,0 +1,11 @@
ARG BASE_IMAGE
FROM $BASE_IMAGE
# Install Autocast https://github.com/k9withabone/autocast/tree/main#installation
# https://stackoverflow.com/questions/67092242/how-can-i-add-to-the-path-in-the-ddev-web-container-for-drush-for-example
RUN echo 'export PATH="$PATH:$HOME/.cargo/bin"' >/etc/bashrc/commandline-addons.bashrc
# https://ddev.readthedocs.io/en/latest/users/extend/customizing-images/#adding-extra-dockerfiles-for-webimage-and-dbimage
USER $uid
RUN curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash
RUN cargo-binstall --no-confirm autocast
USER root
+1
View File
@@ -0,0 +1 @@
github: [weitzman]
@@ -0,0 +1,31 @@
---
name: Bug report or support request
about: For support requests, please use Drupal Answers instead. See http://drupal.stackexchange.com/questions/tagged/drush
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
What did you do?
**Expected behavior**
What did you expect would happen?
**Actual behavior**
What happened instead?
**Workaround**
Is there another way to do the desired action?
### System Configuration
| Q | A
| --------------- | ---
| Drush version? | 12.x/11.x/10.x/8.x (please be specific, and try latest release)
| Drupal version? | 10.x/9.x/8.x/7.x
| PHP version | 8.x/7.x
| OS? | Mac/Linux/Windows
**Additional information**
Add any other context about the problem here.
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: false
contact_links:
- name: 💬 Drush Slack
url: https://drupal.slack.com/archives/C62H9CWQM
about: Join the Drush Community to talk, exchange experiences or ask and answer questions.
- name: 📒 Drupal Answers (powered by Stack Overflow)
url: https://stackoverflow.com/questions/tagged/drush
about: Support requests belong here.
@@ -0,0 +1,18 @@
---
name: Documentation request
about: If you know what the documentation change should be, please consider submitting
a pull request instead.
---
**Existing document**
Please provide a link to the existing document that is unclear or incomplete.
**What are you attempting to do**
Please explain the task you are attempting to accomplish.
**In what way is the existing documentation unclear or incomplete**
Please explain any confusion or ambiguities in the existing documentation.
**What should the documentation say instead?**
To the best of your ability, explain what additional information would allow you to complete your task. If you already know what the documentation should say, please consider submitting a documentation pull request instead.
@@ -0,0 +1,17 @@
---
name: Feature request
about: Suggest an idea for this project
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+74
View File
@@ -0,0 +1,74 @@
name: Build docs site
on:
push:
branches: [11.x, 12.x]
tags: ["11.*", "12.*"]
jobs:
build:
permissions:
contents: write # for git push
name: Build docs and push
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
- name: Setup Git
run: |
git config --local user.email "[email protected]"
git config --local user.name "Drush Documentation Bot"
- name: Set up Python 3.8
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
pip install mkdocs==1.4.3 mkdocs-material mike mkdocs-git-authors-plugin mkdocs-redirects mkdocs-git-revision-date-localized-plugin pymdown-extensions git+https://gitlab.com/blacs30/mkdocs-edit-url.git
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: 8.1
extensions: dom, curl, gd, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite
coverage: none
tools: composer:v2
- name: Install Composer dependencies
run: composer install --prefer-dist --no-interaction
- name: Install Drupal
run: composer sut:si
env:
UNISH_DB_URL: sqlite://sites/default/files/.ht.sqlite
- name: Drush status
run: ./drush --uri=dev st
- name: Drush mk:docs
run: composer mk:docs
- name: Mike config
run: |
mike alias 12.x latest
mike set-default latest
- name: Mike deploy
run: mike deploy --push ${GITHUB_REF_NAME}
# Build Doctum to gh-pages/api in the gh-pages branch.
- name: Checkout gh-pages branch
uses: actions/checkout@v2
with:
ref: gh-pages
path: gh-pages
fetch-depth: 0
- name: Git pull
run: cd gh-pages && git pull
- name: Install Doctum
run: composer doctum-install
- name: Doctum build
run: |
rm -rf gh-pages/latest/api
composer api -- --only-version=${GITHUB_REF_NAME}
- uses: stefanzweifel/git-auto-commit-action@v4
with:
commit_message: "[CI] Add Doctum build"
repository: gh-pages
commit_user_name: "Drush Documentation Bot"
commit_user_email: "[email protected]"
+27
View File
@@ -0,0 +1,27 @@
tests/phpunit.xml
.ddev/config.personal.yaml
vendor
box.phar
drush.phar
#The mkdocs output directory and generated file.
site
gh-pages
mkdocs.yml
#The Commands site output directory.
docs/commands
docs/generators
#The Doctum output directories
api
.doctum-cache
# IDE config
.idea/
sut/*
!sut/drush
sut/drush/sites/*test.site.yml
!sut/modules
sut/modules/contrib
/sandbox/
.env
# Test fixtures
sut/drush/sites/synctest.site.yml
/tests/.phpunit.result.cache
+35
View File
@@ -0,0 +1,35 @@
# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners
#
# We are always looking for more maintainers! Please submit a couple PRs in an
# area and then submit a PR to add yourself to this file :).
#
# These owners will be the default owners for everything in
# the repo. Unless a later match takes precedence,
# @global-owner1 and @global-owner2 will be requested for
# review when someone opens a pull request.
* @weitzman @greg-1-anderson
/src/Commands/config/ @bircher
/src/Commands/core/MigrateRunnerCommands.php @claudiu-cristea
/src/Drupal/Migrate/ @claudiu-cristea
/src/Commands/field/ @DieterHolvoet
/src/Commands/core/RunServerCommands.php @grugnog
/includes/batch.inc @jonhattan
/src/Commands/core/BatchCommands.php @jonhattan
/src/Commands/core/CliCommands.php @damiankloip
/src/Psysh @damiankloip
/src/Commands/core/UpdateDBCommands.php @pfrenssen
/src/Commands/core/LocaleCommands.php @Sutharsan
/src/Commands/core/QueueCommands.php @davereid
+24
View File
@@ -0,0 +1,24 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/CONTRIBUTING.md
---
Drush is built by people like you! Please [join us](https://github.com/drush-ops/drush).
## Git and Pull requests
* Contributions are submitted, reviewed, and accepted using GitHub pull requests.
* The latest changes are in the `13.x` branch. PR's should initially target this branch.
* See the test-specific [README.md](https://github.com/drush-ops/drush/blob/12.x/docs/contribute/unish.md) for instructions on running the test suite. Test before you push. Get familiar with Unish, our test suite. Optionally run tests in the provided Docker containers.
* We maintain branches named 13.x, 12.x, etc. These are release branches. From these branches, we make new tags for patch and minor versions.
## Development Environment
* You may choose to use the [DDEV](https://ddev.readthedocs.io/) for a [standardized development environment](/.ddev/config.yaml).
* See `composer run-script -l` for a list of helper scripts.
## Coding style
* Do write comments. You don't have to comment every line, but if you come up with something that's a bit complex/weird, just leave a comment. Bear in mind that you will probably leave the project at some point and that other people will read your code. Undocumented huge amounts of code are nearly worthless!
* We use [PSR-12](https://www.php-fig.org/psr/psr-12/).
* Keep it compatible. Do not introduce changes to the public API, or configurations too casually. Don't make incompatible changes without good reasons!
* Run `composer cs` to check the project for coding style issues and run `composer cbf` to fix them automatically where possible. These scripts use [`PHP_CodeSniffer`](https://github.com/squizlabs/PHP_CodeSniffer) in background.
## Documentation
* The docs are on our [web site](https://www.drush.org). You may also read these from within Drush, with the `drush topic` command.
* Documentation should be kept up-to-date. This means, whenever you add a new API method, add a new hook or change the database model, pack the relevant changes to the docs in the same pull request.
+11
View File
@@ -0,0 +1,11 @@
Drush is a command line shell and Unix scripting interface for Drupal. Please see www.drush.org for documentation.
[![Latest Stable Version](https://poser.pugx.org/drush/drush/v/stable.png)](https://packagist.org/packages/drush/drush) [![Total Downloads](https://poser.pugx.org/drush/drush/downloads.png)](https://packagist.org/packages/drush/drush) [![License](https://poser.pugx.org/drush/drush/license.png)](https://packagist.org/packages/drush/drush) <a href="https://circleci.com/gh/drush-ops/drush"><img src="https://circleci.com/gh/drush-ops/drush.svg?style=shield"></a> [![Twitter](https://img.shields.io/badge/Twitter-%40DrushCli-blue.svg)](https://twitter.com/intent/user?screen_name=DrushCli)
Support
-----------
* See www.drush.org for documentation.
* Post support requests to [Drupal Answers](http://drupal.stackexchange.com/questions/tagged/drush). Tag questions with 'drush'.
* Report bugs and request features in the [GitHub Drush Issue Queue](https://github.com/drush-ops/drush/issues).
* Report security vulnerabilities privately, [in GitHub](https://github.com/drush-ops/drush/security/advisories).
* Use pull requests (PRs) to contribute to Drush.
+80
View File
@@ -0,0 +1,80 @@
build: false
shallow_clone: false
platform: 'x86'
clone_folder: C:\projects\work
branches:
only:
- 12.x
## Cache composer bits
cache:
- '%LOCALAPPDATA%\Composer\files -> composer.lock'
services:
- mysql
init:
#https://github.com/composer/composer/blob/master/appveyor.yml
#- SET ANSICON=121x90 (121x90)
# Inspired by https://github.com/Codeception/base/blob/master/appveyor.yml and https://github.com/phpmd/phpmd/blob/master/appveyor.yml
install:
- ps: Set-Service wuauserv -StartupType Manual
- git clone -q https://github.com/acquia/DevDesktopCommon.git #For tar, cksum, ...
- SET PATH=%APPVEYOR_BUILD_FOLDER%/DevDesktopCommon/bintools-win/msys/bin;%PATH%
- SET PATH=C:\Program Files\MySql\MySQL Server 5.7\bin\;%PATH%
- choco search php --exact --all-versions -r
#Install PHP per https://blog.wyrihaximus.net/2016/11/running-php-unit-tests-on-windows-using-appveyor-and-chocolatey/
- ps: appveyor-retry cinst --limit-output --ignore-checksums -y php --version 8.1.16
- cd c:\tools\php81
- copy php.ini-production php.ini
# https://github.com/php-coveralls/php-coveralls/pull/223/files
# - appveyor DownloadFile https://curl.se/ca/cacert.pem -FileName C:\cacert.pem
- curl -fsS -o C:\cacert.pem https://curl.se/ca/cacert.pem
- echo curl.cainfo=C:\cacert.pem >> php.ini
- echo extension_dir=ext >> php.ini
- echo extension=php_openssl.dll >> php.ini
- echo date.timezone="UTC" >> php.ini
- echo variables_order="EGPCS" >> php.ini #May be unneeded.
- echo mbstring.http_input=pass >> php.ini
- echo mbstring.http_output=pass >> php.ini
- echo sendmail_path=nul >> php.ini
- echo extension=php_mbstring.dll >> php.ini
- echo extension=php_curl.dll >> php.ini
- echo extension=php_pdo_mysql.dll >> php.ini
- echo extension=php_pdo_pgsql.dll >> php.ini
- echo extension=php_pdo_sqlite.dll >> php.ini
- echo extension=php_pgsql.dll >> php.ini
- echo extension=php_gd.dll >> php.ini
- echo extension=php_fileinfo.dll >> php.ini
- echo memory_limit=256M >> php.ini
- SET PATH=C:\tools\php81;%PATH%
#Install Composer
- cd %APPVEYOR_BUILD_FOLDER%
#- appveyor DownloadFile https://getcomposer.org/composer.phar
- php -r "readfile('http://getcomposer.org/installer');" | php
- echo @php %cd%\composer.phar %%* > composer.bat
# Install dependencies via Composer.
- php composer.phar install --prefer-dist -n
- SET PATH=%APPVEYOR_BUILD_FOLDER%;%APPVEYOR_BUILD_FOLDER%/vendor/bin;%PATH%
# Uncomment this and on_finish line below to enable RDP into build machine https://www.appveyor.com/docs/how-to/rdp-to-build-worker/
# - ps: iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
test_script:
- composer info phpunit/phpunit
- vendor/bin/phpunit --colors=always --configuration tests --testsuite functional --debug
- vendor/bin/phpunit --colors=always --configuration tests --testsuite integration --debug
- vendor/bin/phpunit --colors=always --configuration tests --testsuite unit --debug
on_finish:
# Uncomment this and above line to enable RDP into build machine https://www.appveyor.com/docs/how-to/rdp-to-build-worker/
# - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1'))
# environment variables
environment:
global:
# php_ver_target: 7.3
UNISH_DB_URL: "mysql://root:Password12!@localhost"
APPVEYOR_RDP_PASSWORD: un1sh@Windows
+133
View File
@@ -0,0 +1,133 @@
{
"name": "drush/drush",
"description": "Drush is a command line shell and scripting interface for Drupal, a veritable Swiss Army knife designed to make life easier for those of us who spend some of our working hours hacking away at the command prompt.",
"homepage": "http://www.drush.org",
"license": "GPL-2.0-or-later",
"minimum-stability": "dev",
"prefer-stable": true,
"authors": [
{ "name": "Moshe Weitzman", "email": "[email protected]" },
{ "name": "Owen Barton", "email": "[email protected]" },
{ "name": "Greg Anderson", "email": "[email protected]" },
{ "name": "Jonathan Araña Cruz", "email": "[email protected]" },
{ "name": "Jonathan Hedstrom", "email": "[email protected]" },
{ "name": "Christopher Gervais", "email": "[email protected]" },
{ "name": "Dave Reid", "email": "[email protected]" },
{ "name": "Damian Lee", "email": "[email protected]" }
],
"support": {
"forum": "http://drupal.stackexchange.com/questions/tagged/drush",
"slack": "https://drupal.slack.com/messages/C62H9CWQM",
"security": "https://github.com/drush-ops/drush/security/advisories"
},
"bin": [
"drush"
],
"repositories": {
"drupal_org": {
"type": "composer",
"url": "https://packages.drupal.org/8"
}
},
"require": {
"php": ">=8.1",
"ext-dom": "*",
"composer-runtime-api": "^2.2",
"chi-teck/drupal-code-generator": "^3.0",
"composer/semver": "^1.4 || ^3",
"consolidation/annotated-command": "^4.9.2",
"consolidation/config": "^2.1.2",
"consolidation/filter-via-dot-access-data": "^2.0.2",
"consolidation/output-formatters": "^4.3.2",
"consolidation/robo": "^4.0.6",
"consolidation/site-alias": "^4",
"consolidation/site-process": "^5.2.0",
"grasmash/yaml-cli": "^3.1",
"guzzlehttp/guzzle": "^7.0",
"league/container": "^4",
"psy/psysh": "~0.11",
"symfony/event-dispatcher": "^6",
"symfony/filesystem": "^6.1",
"symfony/finder": "^6",
"symfony/var-dumper": "^6.0",
"symfony/yaml": "^6.0",
"webflo/drupal-finder": "^1.2"
},
"require-dev": {
"composer/installers": "^2",
"cweagans/composer-patches": "~1.0",
"drupal/core-recommended": "^10",
"drupal/semver_example": "2.3.0",
"phpunit/phpunit": "^9",
"rector/rector": "^0.12",
"squizlabs/php_codesniffer": "^3.7"
},
"conflict": {
"drupal/core": "< 10.0",
"drupal/migrate_run": "*",
"drupal/migrate_tools": "<= 5"
},
"autoload": {
"psr-4": {
"Drush\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Unish\\": "tests/unish",
"Custom\\Library\\": "tests/fixtures/lib"
},
"classmap": [
"sut/core/modules/migrate/src"
]
},
"config": {
"allow-plugins": {
"composer/installers": true,
"cweagans/composer-patches": true
},
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"process-timeout": 9600,
"platform": {
"php": "8.1"
}
},
"scripts": {
"cs": "phpcs",
"cbf": "phpcbf",
"lint": [
"find includes -name '*.inc' -print0 | xargs -0 -n1 php -l",
"find src -name '*.php' -and ! -path 'src/Attributes/*' -print0 | xargs -0 -n1 php -l",
"find tests -name '*.php' -print0 | xargs -0 -n1 php -l"
],
"test": [
"@lint",
"@phpunit",
"@cs"
],
"api": "php $HOME/bin/doctum.phar --ansi --ignore-parse-errors update doctum-config.php",
"doctum-install": "mkdir -p $HOME/bin && curl --output $HOME/bin/doctum.phar https://doctum.long-term.support/releases/latest/doctum.phar && chmod +x $HOME/bin/doctum.phar",
"mk:docs": "./drush --uri=dev -v mk:docs",
"rector": "rector process",
"sut": "./drush --uri=dev",
"sut:si": "./drush --uri=dev site:install ${INSTALL_PROFILE:-testing} --sites-subdir=dev --db-url=${UNISH_DB_URL:-mysql://root:password@mariadb}/unish_dev -v",
"phpunit": "php -d sendmail_path='true' vendor/bin/phpunit --colors=always --testdox --configuration tests",
"unit": "composer phpunit -- --testsuite unit",
"integration": "composer phpunit -- --testsuite integration",
"functional": "composer phpunit -- --testsuite functional"
},
"extra": {
"installer-paths": {
"sut/core": ["type:drupal-core"],
"sut/libraries/{$name}": ["type:drupal-library"],
"sut/modules/unish/{$name}": ["drupal/devel"],
"sut/themes/unish/{$name}": ["drupal/empty_theme"],
"sut/modules/contrib/{$name}": ["type:drupal-module"],
"sut/profiles/contrib/{$name}": ["type:drupal-profile"],
"sut/themes/contrib/{$name}": ["type:drupal-theme"],
"sut/drush/contrib/{$name}": ["type:drupal-drush"]
}
}
}
+7692
View File
File diff suppressed because it is too large. Load diff
+70
View File
@@ -0,0 +1,70 @@
The Drush Bootstrap Process
===========================
When preparing to run a command, Drush works by *bootstrapping* the Drupal environment in very much the same way that is done during a normal page request from the web server, so most Drush commands run in the context of a fully-initialized website.
For efficiency and convenience, some Drush commands can work without first bootstrapping a Drupal site, or by only partially bootstrapping a site. This is faster than a full bootstrap. It is also a matter of convenience, because some commands are useful even when you don't have a working Drupal site.
Commands may specify their bootstrap level with via an attribute or an annotation. Commands supplied by Drupal modules are always `full`.
=== "PHP8 Attribute"
```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);
}
```
=== "Annotation"
```php
/**
* @bootstrap none
*/
public function fetch($search = null, $options = ['image-viewer' => 'open', 'google-custom-search-api-key' => 'AIza']) {
$this->doFetch($search, $options);
}
```
Prior to bootstrapping, Drush goes through the *preflight* process, where the following things occur:
!!! example "Preflight"
1. Commandline arguments are parsed.
1. Configuration files are read.
1. The site-alias included on the commandline is loaded if present.
1. The local selected site is determined, if any.
1. [Dependency injection](dependency-injection.md) is done.
1. Global commandfiles are loaded. Commandfiles that ship with modules are loaded later, during `bootstrap @full`.
1. The command is dispatched via the Symfony Console component.
Bootstrapping is done from a Symfony Console command hook. The different bootstrap levels are described below.
none
-----------------------
Only run Drush _preflight_, without considering Drupal at all. Any code that operates on the Drush installation, and not specifically any Drupal directory, should bootstrap to this phase. This Attribute and value may also be used on a command _class_ when it wants to load before Drupal bootstrap is started. Commands that ship inside Drupal modules always bootstrap to full, regardless of _none_ value.
root
------------------------------
Set up and test for a valid Drupal root, either through the --root options, or evaluated based on the current working directory. Any code that interacts with an entire Drupal installation, and not a specific site on the Drupal installation should use this bootstrap phase.
site
------------------------------
Set up a Drupal site directory and the correct environment variables to allow Drupal to find the configuration file. If no site is specified with the --uri options, Drush will assume the site is 'default', which mimics Drupal's behaviour. Note that it is necessary to specify a full URI, e.g. --uri=http://example.com, in order for certain Drush commands and Drupal modules to behave correctly. See the [Drush configuration](using-drush-configuration.md) for more information. Any code that needs to modify or interact with a specific Drupal site's settings.php file should bootstrap to this phase.
configuration
---------------------------------------
Load the settings from the Drupal sites directory. This phase is analogous to the DRUPAL\_BOOTSTRAP\_CONFIGURATION bootstrap phase in Drupal itself, and this is also the first step where Drupal specific code is included. This phase is commonly used for code that interacts with the Drupal install API, as both install.php and update.php start at this phase.
database
----------------------------------
Connect to the Drupal database using the database credentials loaded during the previous bootstrap phase. This phase is analogous to the DRUPAL\_BOOTSTRAP\_DATABASE bootstrap phase in Drupal. Any code that needs to interact with the Drupal database API needs to be bootstrapped to at least this phase.
full
------------------------------
Fully initialize Drupal. This is analogous to the DRUPAL\_BOOTSTRAP\_FULL bootstrap phase in Drupal. Any code that interacts with the general Drupal API should be bootstrapped to this phase.
max
---------------------
This is not an actual bootstrap phase. Commands that use the "max" bootstrap level will cause Drush to bootstrap as far as possible, and then run the command regardless of the bootstrap phase that was reached. This is useful for Drush commands that work without a bootstrapped site, but that provide additional information or capabilities in the presence of a bootstrapped site. For example, [`drush status`](commands/core_status.md) will show progressively more information the farther the site bootstraps.
+151
View File
@@ -0,0 +1,151 @@
# Creating Custom Commands
!!! tip
1. You may now use [Autowire](https://github.com/drush-ops/drush/blob/13.x/src/Commands/AutowireTrait.php) to inject Drupal and Drush dependencies. Prior approaches were using a [create() method](dependency-injection.md#create-method] and using a [drush.services.yml file](https://www.drush.org/11.x/dependency-injection/#services-files). These are now deprecated.
1. Drush 12 expects all commandfiles in the `<module-name>/src/Drush/<Commands|Generators>` directory. The `Drush` subdirectory is a new requirement.
Creating a new Drush command is easy. Follow the steps below.
1. Run `drush generate drush:command-file`.
2. Drush will prompt for the machine name of the module that should "own" the file. The module selected must already exist and be enabled. Use `drush generate module` to create a new module.
3. Drush will then report that it created a commandfile. Edit as needed.
4. Use the classes for the core Drush commands at [/src/Commands](https://github.com/drush-ops/drush/tree/12.x/src/Commands) as inspiration and documentation.
5. You may [inject dependencies](dependency-injection.md) into a command instance.
6. Write PHPUnit tests based on [Drush Test Traits](https://github.com/drush-ops/drush/blob/12.x/docs/contribute/unish.md#drush-test-traits).
## Attributes or Annotations
The following are both valid ways to declare a command:
=== "PHP8 Attributes"
```php
use Drush\Attributes as CLI;
/**
* Retrieve and display xkcd cartoons (attribute variant).
*/
#[CLI\Command(name: 'xkcd:fetch-attributes', aliases: ['xkcd-attributes'])]
#[CLI\Argument(name: 'search', description: 'Optional argument to retrieve the cartoons matching an index, keyword, or "random".')]
#[CLI\Option(name: 'image-viewer', description: 'Command to use to view images (e.g. xv, firefox).', suggestedValues: ['open', 'xv', 'firefox'])]
#[CLI\Option(name: 'google-custom-search-api-key', description: 'Google Custom Search API Key')]
#[CLI\Usage(name: 'drush xkcd', description: 'Retrieve and display the latest cartoon')]
#[CLI\Usage(name: 'drush xkcd sandwich', description: 'Retrieve and display cartoons about sandwiches.')]
public function fetch($search = null, $options = ['image-viewer' => 'open', 'google-custom-search-api-key' => 'AIza']) {
$this->doFetch($search, $options);
}
```
=== "Annotations"
```php
/**
* @command xkcd:fetch
* @param $search Optional argument to retrieve the cartoons matching an index number, keyword, or "random".
* @option image-viewer Command to use to view images (e.g. xv, firefox).
* @option google-custom-search-api-key Google Custom Search API Key.
* @usage drush xkcd
* Retrieve and display the latest cartoon.
* @usage drush xkcd sandwich
* Retrieve and display cartoons about sandwiches.
* @aliases xkcd
*/
public function fetch($search = null, $options = ['image-viewer' => 'open', 'google-custom-search-api-key' => 'AIza']) {
$this->doFetch($search, $options);
}
```
- A commandfile that will only be used on PHP8+ should [use PHP Attributes](https://github.com/drush-ops/drush/pull/4821) instead of Annotations.
- [See Attributes provided by Drush core](https://www.drush.org/api/Drush/Attributes.html). Custom code can add additional attributes.
## Altering Command Info
Drush command info (annotations/attributes) can be altered from other modules. This is done by creating and registering _command info alterers_. Alterers are classes that are able to intercept and manipulate an existing command annotation.
In the module that wants to alter a command info, add a class that:
1. The generator class namespace, relative to base namespace, should be `Drupal\<module-name>\Drush\CommandInfoAlterers` and the class file should be located under the `src/Drush/CommandInfoAlterers` directory.
1. The filename must have a name like FooCommandInfoAlterer.php. The prefix `Foo` can be whatever string you want. The file must end in `CommandInfoAlterer.php`.
1. The class must implement the `\Consolidation\AnnotatedCommand\CommandInfoAltererInterface`.
1. Implement the alteration logic in the `alterCommandInfo()` method.
1. Along with the alter code, it's strongly recommended to log a debug message explaining what exactly was altered. This makes things easier on others who may need to debug the interaction of the alter code with other modules. Also it's a good practice to inject the the logger in the class constructor.
For an example, see [WootCommandInfoAlterer](https://github.com/drush-ops/drush/blob/12.x/sut/modules/unish/woot/src/Drush/CommandInfoAlterers/WootCommandInfoAlterer.php) provided by the testing 'woot' module.
## Symfony Console Commands
Drush lists and runs Symfony Console commands, in addition to more typical annotated commands. See [this test](https://github.com/drush-ops/drush/blob/eed106ae4510d5a2df89f8e7fd54b41ffb0aa5fa/tests/integration/AnnotatedCommandCase.php#L178-L180) and this [commandfile](https://github.com/drush-ops/drush/blob/12.x/sut/modules/unish/woot/src/Commands/GreetCommand.php).
## Auto-discovered commands (PSR4)
Such commands are auto-discovered by their class PSR4 namespace and class/file name suffix. Drush will auto-discover commands if:
* The commands class is PSR4 auto-loadable.
* The commands class namespace, relative to base namespace, is `Drush\Commands`. For instance, if a Drush command provider third party library maps this PSR4 autoload entry:
```json
"autoload": {
"psr-4": {
"My\\Custom\\Library\\": "src"
}
}
```
then the Drush global commands class namespace should be `My\Custom\Library\Drush\Commands` and the class file should be located under the `src/Drush/Commands` directory.
* The class and file name ends with `*DrushCommands`, e.g. `FooDrushCommands`.
Auto-discovered commandfiles should declare their Drush version compatibility via a `conflict` directive. For example, a Composer-managed site-wide command that works with both Drush 11 and Drush 12 might contain something similar to the following in its composer.json file:
```json
"conflict": {
"drush/drush": "<11.0",
}
```
Using `require` in place of `conflict` is not recommended.
!!! warning "Symlinked packages"
While it is good practice to make your custom commands into a Composer package, please beware that symlinked packages (by using the composer repository type [Path](https://getcomposer.org/doc/05-repositories.md#path)) will **not** be discovered by Drush. When in development, it is recommended to [specify your package's](https://github.com/drush-ops/drush/blob/12.x/examples/example.drush.yml#L52-L67) path in your `drush.yml` to have quick access to your commands.
## Site-wide Commands
Commandfiles that are installed in a Drupal site and are not bundled inside a Drupal module are called _site-wide_ commandfiles. Site-wide commands may either be added directly to the Drupal site's repository (e.g. for site-specific policy files), or via `composer require`. See the [examples/Commands](https://github.com/drush-ops/drush/tree/12.x/examples/Commands) folder for examples. In general, it's preferable to use modules to carry your Drush commands.
Here are some examples of valid commandfile names and namespaces:
1. Simple
- Filename: $PROJECT_ROOT/drush/Commands/ExampleCommands.php
- Namespace: Drush\Commands
1. Nested in a subdirectory committed to the site's repository
- Filename: $PROJECT_ROOT/drush/Commands/example/ExampleCommands.php
- Namespace: Drush\Commands\example
1. Nested in a subdirectory installed via a Composer package
- Filename: $PROJECT_ROOT/drush/Commands/contrib/dev_modules/ExampleCommands.php
- Namespace: Drush\Commands\dev_modules
Note: Make sure you do _not_ include `src` in the path to your command. Your command may not be discovered and have additional problems.
If a commandfile is added via a Composer package, then it may declare any dependencies that it may need in its composer.json file. Site-wide commandfiles that are committed directly to a site's repository only have access to the dependencies already available in the site.
A site-wide commandfile should have tests that run with each (major) version of Drush that is supported. You may model your test suite after the [example drush extension](https://github.com/drush-ops/example-drush-extension) project.
## Global commands discovered by configuration
!!! warning "Deprecation"
Configuration discovery has been deprecated and will be removed in a future version of Drush. It is recommended that you avoid global Drush commands, and favor site-wide or PSR4 discovered commandfiles instead. If you really need commands that are not part of any Drupal site, consider making a stand-alone script or custom .phar instead. See [ahoy](https://github.com/ahoy-cli/ahoy), [Robo](https://github.com/consolidation/robo) and [g1a/starter](https://github.com/g1a/starter) as potential starting points.
Global commandfiles discoverable by configuration are not supported by default; in order to enable them, you must configure your `drush.yml` configuration file to add an `include` search location.
For example:
```yaml
drush:
paths:
include:
- '${env.home}/.drush/commands'
```
With this configuration in place, global commands may be placed as described in the Site-Wide Drush Commands section above. Global commandfiles may not declare any dependencies of their own; they may only use those dependencies already available via the autoloader.
!!! tip
1. The filename must be have a name like Commands/ExampleCommands.php
1. The prefix `Example` can be whatever string you want.
1. The file must end in `Commands.php`
1. The directory above `Commands` must be one of:
1. A Folder listed in the 'include' option. Include may be provided via [config](#global-drush-commands) or via CLI.
1. ../drush, /drush or /sites/all/drush. These paths are relative to Drupal root.
+26
View File
@@ -0,0 +1,26 @@
# Exporting and Importing Configuration
Drush provides commands to [export](commands/config_export.md), [pull](commands/config_pull.md), and [import](commands/config_import.md) Drupal configuration files.
## Simple - value changes
It is not necessary to alter configuration values to
make simple value changes to configuration variables, as this may be
done by the [configuration override system](https://www.drupal.org/node/1928898).
The configuration override system allows you to change configuration
values for a given instance of a site (e.g. the development server) by
setting configuration variables in the site's settings.php file.
For example, to change the name of a local development site:
```php
$config['system.site']['name'] = 'Local Install of Awesome Widgets, Inc.';
```
Note that the configuration override system is a Drupal feature, not
a Drush feature. It should be the preferred method for changing
configuration values on a per-environment basis; however, it does not
work for some things, such as enabling and disabling modules.
## Advanced - variation by environment
- Drupal supports [excluding development modules from enabling on higher environments](https://www.drupal.org/node/3079028).
- See [Config Split](https://www.drupal.org/project/config_split) module for more advanced needs.
+1
View File
@@ -0,0 +1 @@
../../CONTRIBUTING.md
+51
View File
@@ -0,0 +1,51 @@
Drush's test suite (aka Unish) is based on [PHPUnit](http://www.phpunit.de). In order to maintain
high quality, our tests are run on every push. See [CircleCi](https://circleci.com/gh/drush-ops/drush).
## Usage
1. `git clone https://github.com/drush-ops/drush.git`
1. `cd drush`
1. `composer install`
1. Review the configuration settings in [tests/phpunit.xml.dist](https://github.com/drush-ops/drush/blob/12.x/tests/phpunit.xml.dist). If customization is needed, copy phpunit.xml.dist to phpunit.xml and edit away.
1. Run all test suites: `composer test`
## DDEV
:octicons-tag-24: 11.0+
Drush's own tests may be run within provided Docker containers via [DDEV](https://ddev.readthedocs.io/en/stable/)
- Start containers: `ddev start`
- Run a test: `ddev exec drupal composer functional -- --filter testUserRole`
- See the [DDEV's XDebug docs](https://ddev.readthedocs.io/en/stable/users/debugging-profiling/step-debugging/) for help on enabling Xdebug.
## Advanced usage
- Run only one test suite
- `composer unit`
- `composer integration`
- `composer functional`
- Run only tests matching a regex: `composer functional -- --filter testUserRole`
- Skip slow tests (usually those with network usage): `composer functional -- --exclude-group slow`
- XML results: `composer functional -- --log-junit results.xml`
- Ad-hoc testing with the SUT
- `composer sut:si`. [See composer.json for details](https://github.com/drush-ops/drush/blob/dde2793453ed96cc8b9e5bbc1b66e3d8d26be1f6/composer.json#L117).
- `UNISH_DIRTY=1 composer functional -- --filter testUserRole`
- `./drush @sut.dev status`
## About the Test Suites
- **Unit tests** operate on functions that take values and return results without creating side effects. No database connection is required to run these tests, and no Drupal site is set up.
- **Integration tests** set up a test dependency injection container and operate by calling the Symfony Application APIs directly. A Drupal site called the System Under Test is set up and used for the tests. The SUT is set up and installed only once, and then is re-used for all tests. Integration tests therefore cannot make destructive changes to the SUT database. Also, Drupal is bootstrapped only once (always using the standard Drupal kernel, never the install or update kernel). This means that all commands run at `@bootstrap full`, and it is not possible to test loading different Drush configuration files and so on. It is not possible to test argument / option parsing. The shutdown and error handlers are not installed, so PHP deprecation warnings will be evidenced in the integration tests.
- **Functional tests** operate by `exec`ing the Drush executable. All functional tests therefore run in their own separate processes. The Drupal System Under Test is set up every time it is needed by any functional test. It is therefore okay if a functional test changes the state of the SUT. The codebase is re-used, so no destructive changes should be made to the code.
## Drush Test Traits
Drush provides test traits that may be used to test your own Drush extensions. Adding the traits varies slightly depending how you package your Drush extension.
- An extension that ships inside a contributed module - [DevelCommandsTest](https://cgit.drupalcode.org/devel/tree/tests/src/Functional/DevelCommandsTest.php?h=8.x-2.x) for an example. More examples are [SchedulerDrushTest](https://git.drupalcode.org/project/scheduler/blob/8.x-1.x/tests/src/Functional/SchedulerDrushTest.php) and [Views Bulk Operations](https://git.drupalcode.org/project/views_bulk_operations/-/blob/8.x-3.x/tests/src/Functional/DrushCommandsTest.php). Remember to add `drush/drush` to your module's composer.json (`require-dev` section).
- A standalone Drush extension or one that ships outside of a module - [example drush extension](https://github.com/drush-ops/example-drush-extension)
Once you successfully have `use Drush\TestTraits\DrushTestTrait` in your test class, you are able to write simple tests that call your extension's commands and makes assertions against 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"');
}
```
+53
View File
@@ -0,0 +1,53 @@
Running Drupal cron tasks from Drush
====================================
Drupal cron tasks are often set up to be run via a wget/curl call to cron.php; this same task can also be accomplished via the [cron command](commands/core_cron.md), which circumvents the need to provide a web server interface to cron.
Quick start
----------
If you just want to get started quickly, here is a crontab entry that will run cron once every hour at ten minutes after the hour:
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 && /vendor/bin/drush --uri=your.drupalsite.org --quiet cron
You should set up crontab to run your cron tasks as the same user that runs the web server; for example, if you run your web server as the user www-data:
sudo crontab -u www-data -e
You might need to edit the crontab entry shown above slightly for your particular setup; for example, if you have installed Drush to some directory other than /usr/local/drush, then you will need to adjust the path to drush appropriately. We'll break down the meaning of each section of the crontab entry in the documentation that continues below.
Setting the schedule
--------------------
See `man 5 crontab` for information on how to format the information in a crontab entry. In the example above, the schedule for the crontab is set by the string `10 * * * *`. These fields are the minute, hour, day of month, month and day of week; `*` means essentially 'all values', so `10 * * * *` will run any time the minute == 10 (once every hour).
Setting the PATH
----------------
We use /usr/bin/env to run Drush so that we can set up some necessary environment variables that Drush needs to execute. By default, cron will run each command with an empty PATH, which would not work well with Drush. To find out what your PATH needs to be, just type:
echo $PATH
Take the value that is output and place it into your crontab entry in the place of the one shown above. You can remove any entry that is known to not be of interest to Drush (e.g. /usr/games), or is only useful in a graphic environment (e.g. /usr/X11/bin).
Setting COLUMNS
---------------
When running Drush in a terminal, the number of columns will be automatically determined by Drush by way of the tput command, which queries the active terminal to determine what the width of the screen is. When running Drush from cron, there will not be any terminal set, and the call to tput will produce an error message. Spurious error messages are undesirable, as cron is often configured to send email whenever any output is produced, so it is important to make an effort to insure that successful runs of cron complete with no output.
In some cases, Drush is smart enough to recognize that there is no terminal -- if the terminal value is empty or "dumb", for example. However, there are some "non-terminal" values that Drush does not recognize, such as "unknown." If you manually set `COLUMNS`, then Drush will respect your setting and will not attempt to call tput.
Using --quiet
-------------
By default, Drush will print a success message when the run of cron is completed. The --quiet flag will suppress these and other progress messages, again avoiding an unnecessary email message.
Specifying the Drupal site to run
---------------------------------
There are many ways to tell Drush which Drupal site to select for the active command, and any may be used here. The example uses `cd [DOCROOT]`, but you could also use the --root and --uri flags.
Avoiding Maintenance mode
---------------------------------
The call to maint:status checks to see if the site is in maintenance mode. If yes, cron will not run and the command returns a failure. It is not safe to run cron while the site is in maintenance. See https://drupal.slack.com/archives/C45SW3FLM/p1675287662331809.
+23
View File
@@ -0,0 +1,23 @@
/*https://squidfunk.github.io/mkdocs-material/setup/setting-up-navigation/#content-area-width. Looks worse IMO.*/
/*.md-grid {*/
/* max-width: 1440px;*/
/*}*/
/*https://github.com/squidfunk/mkdocs-material/issues/2574#issuecomment-821979698*/
[data-md-toggle="search"]:not(:checked) ~ .md-header .md-search__form::after {
position: absolute;
top: .3rem;
right: .3rem;
display: block;
padding: .1rem .4rem;
color: var(--md-default-bg-color);
font-weight: bold;
font-size: .8rem;
border: .05rem solid var(--md-default-bg-color--lighter);
border-radius: .1rem;
content: "/";
}
.md-typeset h1 {
margin: 0 0 0.1em;
}
+57
View File
@@ -0,0 +1,57 @@
Dependency Injection
==================
Drush command files obtain references to the resources they need through a technique called _dependency injection_. When using this programing paradigm, a class by convention will never use the `new` operator to instantiate dependencies. Instead, it will store the other objects it needs in class variables, and provide a way for other code to assign an object to that variable.
!!! tip
Drush 11 and prior required [dependency injection via a drush.services.yml file](https://www.drush.org/11.x/dependency-injection/#services-files). This approach is deprecated in Drush 12+.
Autowire
------------------
:octicons-tag-24: 12.5+
Command files may inject Drush and Drupal services by adding the [AutowireTrait](https://github.com/drush-ops/drush/blob/12.x/src/Commands/AutowireTrait.php) to the class (example: [MaintCommands](https://github.com/drush-ops/drush/blob/12.x/src/Commands/core/MaintCommands.php)). This enables your [Constructor parameter type hints determine the the injected service](https://www.drupal.org/node/3396179). When a type hint is insufficient, an [#[Autowire] Attribute](https://www.drupal.org/node/3396179) on the constructor property (with
_service:_ named argument) directs AutoWireTrait to the right service.
If your command is not found by Drush, add the `-vvv` option for debug info about any service instantiation errors. If Autowire is still insufficient, a commandfile may implement its own `create()` method (see below).
create() method
------------------
:octicons-tag-24: 11.6+
Command files not using Autowire may inject services by adding a create() method to the commandfile. The passed in Container is a [League container](https://container.thephpleague.com/) with a delegate to the Drupal container. Note that the type hint should be to `Psr\Container\ContanierInterface` not `Symfony\Component\DependencyInjection\ContainerInterface`. A create() method and constructor will look something like this:
```php
class WootStaticFactoryCommands extends DrushCommands
{
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'));
}
```
See the [Drupal Documentation](https://www.drupal.org/docs/drupal-apis/services-and-dependency-injection/services-and-dependency-injection-in-drupal-8#s-injecting-dependencies-into-controllers-forms-and-blocks) for details on how to inject Drupal services into your command file. This approach mimics Drupal's blocks, forms, and controllers.
createEarly() method
------------------
:octicons-tag-24: 12.0+
The `createEarly()` method was deprecated in Drush 12.5. Instead put a `#[CLI\Bootstrap(DrupalBootLevels::NONE)]` Attribute on the command class and inject dependencies via the usual `__construct` with [AutowireTrait](https://github.com/drush-ops/drush/blob/13.x/src/Commands/AutowireTrait.php).
Note also that Drush commands packaged with Drupal modules are not discovered
until after Drupal bootstraps, and therefore cannot use `createEarly()`. This
mechanism is only usable by PSR-4 discovered commands packaged with Composer
projects that are *not* Drupal modules.
Inflection
-----------------
A command class may implement the following interfaces. When doing so, implement the corresponding trait to satisfy the interface.
- [CustomEventAwareInterface](https://github.com/consolidation/annotated-command/blob/4.x/src/Events/CustomEventAwareInterface.php): Allows command files to [define and fire custom events](hooks.md) that other command files can hook. Example: [CacheCommands](https://github.com/drush-ops/drush/blob/13.x/src/Commands/core/CacheCommands.php)
- [StdinAwareInterface](https://github.com/consolidation/annotated-command/blob/4.x/src/Input/StdinAwareInterface.php): Read from standard input. This class contains facilities to redirect stdin to instead read from a file, e.g. in response to an option or argument value. Example: [CacheCommands](https://github.com/drush-ops/drush/blob/13.x/src/Commands/core/CacheCommands.php)
+28
View File
@@ -0,0 +1,28 @@
# Deploy
:octicons-tag-24: 10.3+
The [deploy command](commands/deploy.md) standardizes how Drupal deployments work. The intent is your
deployment script updates the codebase for the target site and then this command
performs the following:
```shell
drush updatedb --no-cache-clear
drush cache:rebuild
drush config:import
drush cache:rebuild
drush deploy:hook
```
## Authoring update functions
Below are the 3 types of update functions run by this command, in order. Choose the most appropriate for your need.
| Function | Drupal API | Purpose |
| --- | --- | --- |
| [HOOK_update_n()](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Extension!module.api.php/function/hook_update_N) | Not allowed | Low level changes. |
| [HOOK_post_update_NAME()](https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Extension!module.api.php/function/hook_post_update_NAME) | Allowed | Runs *before* config is imported. |
| [HOOK_deploy_NAME()](https://github.com/drush-ops/drush/tree/HEAD/drush.api.php) | Allowed | Runs *after* config is imported. |
## Configuration
If you need to customize this command, you should use Drush configuration for the
subcommands listed above (e.g. [updatedb](commands/updatedb.md), [config:import](commands/config_import.md), etc.).
+1
View File
@@ -0,0 +1 @@
../drush_logo-black.png
+7
View File
@@ -0,0 +1,7 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/Commands/ArtCommands.php
---
```php
--8<-- "examples/Commands/ArtCommands.php"
```
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/Commands/PolicyCommands.php
---
```php
--8<-- "examples/Commands/PolicyCommands.php"
```
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/Commands/SiteAliasAlterCommands.php
---
```php
--8<-- "examples/Commands/SiteAliasAlterCommands.php"
```
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/Commands/SyncViaHttpCommands.php
---
```php
--8<-- "examples/Commands/SyncViaHttpCommands.php"
```
+6
View File
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/Commands/XkcdCommands.php
---
```php
--8<-- "examples/Commands/XkcdCommands.php"
```
+6
View File
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/example.drush.yml
---
```yaml
--8<-- "examples/example.drush.yml"
```
+6
View File
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/example.prompt.sh
---
```shell
--8<-- "examples/example.prompt.sh"
```
+6
View File
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/example.site.yml
---
```yaml
--8<-- "examples/example.site.yml"
```
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/git-bisect.example.sh
---
```shell
--8<-- "examples/git-bisect.example.sh"
```
+6
View File
@@ -0,0 +1,6 @@
---
edit_url: https://github.com/drush-ops/drush/blob/12.x/examples/helloworld.script
---
```php
--8<-- "examples/helloworld.script"
```
+39
View File
@@ -0,0 +1,39 @@
# Overview
!!! tip
Drush 11 and prior required generators to define a [drush.services.yml file](https://www.drush.org/11.x/dependency-injection/#services-files). This is no longer used with Drush 12+ generators. See [docs](dependency-injection.md) for injecting dependencies..
Generators jump start your coding by building all the boring boilerplate code for you. After running the [generate command](commands/generate.md), you have a guide for where to insert your custom logic.
Drush's generators reuse classes provided by the excellent [Drupal Code Generator](https://github.com/Chi-teck/drupal-code-generator) project. See its [Commands directory](https://github.com/Chi-teck/drupal-code-generator/tree/3.x/src/Command) for inspiration.
## Writing Custom Generators
Drupal modules may supply their own Generators, just like they can supply Commands.
See [Woot module](https://github.com/drush-ops/drush/tree/12.x/sut/modules/unish/woot/src/Drush/Generators), which Drush uses for testing. Specifically,
1. Write a class similar to [ExampleGenerator](https://github.com/drush-ops/drush/tree/12.x/sut/modules/unish/woot/src/Drush/Generators). Implement your custom logic in the generate() method. Typically this class is placed under the src/Drush/Generators directory.
2. Add a .twig file to the same directory. This template specifies what gets output from the generator.
## Auto-discovered Generators (PSR4)
Generators that don't ship inside Drupal modules are called *global* generators. For example see [CustomDrushGenerator](https://github.com/drush-ops/drush/blob/12.x/tests/fixtures/lib/Drush/Generators/CustomGenerator.php). In general, it is better to use modules to carry your generators. If you still prefer using a global generator, please note:
1. The generator class should be PSR4 auto-loadable.
1. The generator class namespace, relative to base namespace, should be `Drush\Generators`. For instance, if a Drush generator provider third party library maps this PSR4 autoload entry:
```json
"autoload": {
"psr-4": {
"My\\Custom\\Library\\": "src"
}
}
```
then the Drush global generator class namespace should be `My\Custom\Library\Drush\Generators` and the class file should be located under the `src/Drush/Generators` directory.
1. The filename must have a name like FooGenerator.php. The prefix `Foo` can be whatever string you want. The file must end in `Generator.php`.
## Site-wide Generators
Sitewide generators (as opposed to auto-discovered PSR4) have a namespace that starts with `\Drush\Generators`, the directory above Generators must be one of:
1. A Folder listed in the *--include* option. include may be provided via config or via CLI.
1. `../drush`, `/drush` or `/sites/all/drush`. These paths are relative to Drupal root.
+59
View File
@@ -0,0 +1,59 @@
## Core Hooks
All commandfiles may implement methods that are called by Drush at various times in the request cycle. To implement one, add a `#[CLI\Hook(type: HookManager::ARGUMENT_VALIDATOR, target: 'pm:install')]` (for example) to the top of your method. The class constants for hooks are located in [HookManager](https://github.com/consolidation/annotated-command/blob/e01152f698eff4cb5df3ebfe5e097ef335dbd3c9/src/Hooks/HookManager.php#L30-L57).
- [Documentation about available hooks](https://github.com/consolidation/annotated-command#hooks).
- To see how core commands implement a hook, you can [search the Drush source code](https://github.com/drush-ops/drush/search?q="%40#[CLI\Hook]"&type=Code&utf8=%E2%9C%93).
## Custom Hooks
Drush commands can define custom events that other command files can hook. You can find examples in [CacheCommands](https://github.com/drush-ops/drush/blob/12.x/src/Commands/core/CacheCommands.php) and [SanitizeCommands](https://github.com/drush-ops/drush/blob/12.x/src/Drupal/Commands/sql/SanitizeCommands.php)
First, the command must implement CustomEventAwareInterface and use CustomEventAwareTrait, as described in the [dependency injection](dependency-injection.md#inflection) documentation.
Then, the command may ask the provided hook manager to return a list of handlers with a certain attribute. In the example below, the `my-event` label is used:
```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);
}
```
Other commandfiles may provide implementations via a PHP8 Attribute or an Annotation.
=== "PHP8 Attributes"
```php
/**
* #[CLI\Hook(type: HookManager::ON_EVENT, target: 'my-event')]
*/
public function hookOne()
{
return 'one';
}
```
=== "Annotations"
```php
/**
* @hook on-event my-event
*/
public function hookOne()
{
return 'one';
}
```
+1
View File
@@ -0,0 +1 @@
../../misc/favicon.ico
+41
View File
@@ -0,0 +1,41 @@
Drush is a command line shell and Unix scripting interface for Drupal. Drush core ships with lots of [useful commands](commands/all.md) and [generators](generators/all.md). Similarly, it runs update.php, executes SQL queries, runs content migrations, and misc utilities like cron or cache rebuild. Drush can be extended by [3rd party commandfiles](https://www.drupal.org/project/project_module?f[2]=im_vid_3%3A4654).
[![Latest Stable Version](https://poser.pugx.org/drush/drush/v/stable.png)](https://packagist.org/packages/drush/drush) [![Total Downloads](https://poser.pugx.org/drush/drush/downloads.png)](https://packagist.org/packages/drush/drush) [![License](https://poser.pugx.org/drush/drush/license.png)](https://packagist.org/packages/drush/drush) <a href="https://circleci.com/gh/drush-ops/drush"><img src="https://circleci.com/gh/drush-ops/drush.svg?style=shield"></a> [![Twitter](https://img.shields.io/badge/Twitter-%40DrushCli-blue.svg)](https://twitter.com/intent/user?screen_name=DrushCli)
Resources
-----------
* [Installing and Upgrading](install.md)
* [Commands](commands/all.md) and [Generators](generators/all.md)
* [API Documentation](https://www.drush.org/api)
* [Drush packages available via Composer](https://packagist.org/search/?type=drupal-drush)
* [A list of modules that include Drush integration](https://www.drupal.org/project/project_module?f[2]=im_vid_3%3A4654&solrsort=ds_project_latest_release+desc)
* Drush expects all participants to abide by the [Drupal Code of Conduct](https://www.drupal.org/dcoc).
* Drush 8 is no longer recommended, but [here are its docs](https://docs.drush.org/en/8.x/install/).
Support
-----------
* Post support requests to [Drupal Answers](http://drupal.stackexchange.com/questions/tagged/drush). Tag question with _drush_.
* Report bugs and request features in the [GitHub Drush Issue Queue](https://github.com/drush-ops/drush/issues).
* Use pull requests (PRs) to contribute to Drush. [Guidelines](contribute/CONTRIBUTING.md).
FAQ
------
#### What does *Drush* stand for?
A: The Drupal Shell.
#### How do I pronounce Drush?
Some people pronounce the *dru* with a long 'u' like Dr*u*pal. Fidelity points
go to them, but they are in the minority. Most pronounce Drush so that it
rhymes with hush, rush, flush, etc. This is the preferred pronunciation.
Credits
-----------
* Maintained by [Moshe Weitzman](http://drupal.org/moshe) with much help from the folks listed at https://github.com/orgs/drush-ops/people.
* Originally developed by [Arto Bendiken](http://bendiken.net) for Drupal 4.7.
* Redesigned by [Franz Heinzmann](http://unbiskant.org) in May 2007 for Drupal 5.
* Thanks to [JetBrains](https://www.jetbrains.com) for [supporting this project and open source software](https://www.jetbrains.com/buy/opensource/).
![Drush Logo](drush_logo-black.png)
[![PhpStorm Logo](misc/icon_PhpStorm.png)](https://www.jetbrains.com/phpstorm/)
+105
View File
@@ -0,0 +1,105 @@
!!! tip
Drush only supports one install method. It requires that your Drupal site be built with Composer and Drush be listed as a dependency.
See the [Drush 8](http://docs.drush.org/en/8.x) or [Drush 9](https://docs.drush.org/en/9.x) docs for installing prior versions of Drush.
1. **Composer**. It is required that Drupal sites be built using Composer, with Drush listed as a dependency. See [recommended-project](https://www.drupal.org/docs/develop/using-composer/using-composer-to-install-drupal-and-manage-dependencies) (Drush must be added). If your Composer project doesn't yet depend on Drush, run `composer require drush/drush` to add it.
1. **Execution**. Change to the project root, and call Drush via `vendor/bin/drush`. To simplify things, add `./vendor/bin` to your `$PATH`, allowing you to call Drush via `drush` from the project root. If you have only one Drupal codebase on your system, you may put `/path/to/vendor/bin` in your `$PATH`; now you can call Drush from everywhere, without having to change to project root.
1. **Completion**. Optional. Append to .bashrc or equivalent for ZSH or [Fish shell](https://fishshell.com/). Run `drush completion --help` for more details.
1. **Multiple Codebases**. Optional. If using the bash shell, consider installing the [fd](https://github.com/g1a/fd) project, a small set of scripts that make it easier to switch between different project directories quickly, with type completion.
!!! note
- See [Usage](usage.md) for details on using Drush.
- To use a non-default PHP, [edit ~/.bashrc so that the desired PHP is in front of your $PATH](http://stackoverflow.com/questions/4145667/how-to-override-the-path-of-php-to-use-the-mamp-path/10653443#10653443). If that is not desirable, you can change your PATH for just one request: `PATH=/path/to/php:$PATH` drush status ...`
- To use a custom php.ini for Drush requests, [see this comment](https://github.com/drush-ops/drush/issues/3294#issuecomment-370201342).
- See our [guide on porting commandfiles](https://weitzman.github.io/blog/port-to-drush9) from Drush 8 to later versions. Also note that alias and config files use a new .yml format in Drush 10+.
Drupal Compatibility
-----------------
<table>
<tr>
<th rowspan="2"> Drush Version </th>
<th rowspan="2"> PHP Version</th>
<th rowspan="2"> End Of Life </th>
<th colspan="5"> Drupal versions </th>
</tr>
<th>7</th> <th>8</th> <th>9</th> <th>10</th> <th>11</th>
</tr>
<tr>
<td> Drush 13 </td>
<td> 8.3+ </td>
<td> TBD </td>
<td></td> <td></td> <td></td> <td><b>✓</b></td> <td><b>✅</b></td>
</tr>
<tr>
<td> Drush 12 </td>
<td> 8.1+ </td>
<!-- Released Jun 2023 -->
<td> TBD </td>
<td></td> <td></td> <td></td> <td><b>✅</b></td> <td></td>
</tr>
<tr>
<td> Drush 11 </td>
<td> 7.4+ </td>
<!-- TBD -->
<td> Nov 2023 </td>
<td></td> <td></td> <td><b>✓</b></td> <td><b>✓</b></td> <td></td>
</tr>
<tr>
<td> Drush 10 </td>
<td> 7.1+ (not 8) </td>
<!-- Released Oct 2019 -->
<td> Jan 2022 </td>
<td></td> <td>✓</td> <td><b>✓</b></td> <td></td> <td></td>
</tr>
<tr>
<td> Drush 9 </td>
<td> 5.6+ </td>
<!-- Released Jan 2018 -->
<td> May 2020 </td>
<td></td> <td>✓</td> <td></td> <td></td> <td></td>
</tr>
<tr>
<td> Drush 8 </td>
<td> 5.4.5+ </td>
<!-- Released Nov 2015 -->
<td> Jan 2025 </td>
<td>✅</td> <td><b>✓️</b></td> <td></td> <td></td> <td></td>
</tr>
<tr>
<td> Drush 7 </td>
<td> 5.3.0+ </td>
<!-- Released May 2015 -->
<td> Jul 2017 </td>
<td>✓</td> <td></td> <td></td> <td></td> <td></td>
</tr>
<tr>
<td> Drush 6 </td>
<td> 5.3.0+ </td>
<!-- Released Aug 2013 -->
<td> Dec 2015 </td>
<td>✓</td> <td></td> <td></td> <td></td> <td></td>
</tr>
<tr>
<td> Drush 5 </td>
<td> 5.2.0+ </td>
<!-- Released March 2012 -->
<td> May 2015 </td>
<td>✓</td> <td></td> <td></td> <td></td> <td></td>
</tr>
</table>
<table>
<tr>
<th colspan="2">Legend</th>
</tr>
<tr>
<td>✅</td> <td>Supported and recommended</td>
</tr>
<tr>
<td>✓</td> <td>Compatible but no longer supported</td>
</tr>
</table>
+12
View File
@@ -0,0 +1,12 @@
# Input / Output
- The Input object holds information about the request such option and argument values. You may need to this information when coding a hook implementation. You don't need this object in your command callback method since these values are passed as parameters.
- The Output object is rarely needed. Instead, return an object that gets formatted via the Output Formatter system. If you want to send additional output, use the io system (see below).
## The io() system
- If you need to ask the user a question, or print non-object content, use the io() system.
- A command callback gets access via `$this->io()`.
- The main methods for gathering user input are `$this->io()->choice()` and `$this->io()->confirm()`.
- You may use any of the methods described in the [Symfony Style docs](https://symfony.com/doc/current/console/style.html).
+27
View File
@@ -0,0 +1,27 @@
Defining and running migrations
===============================
:octicons-tag-24: 10.4+
The Migrate API delivers services for migrating data from a source system to Drupal. This API is provided by the core `migrate` module. In order to migrate data to Drupal, you'll need to create migrations for each type of destination data.
These commands are an alternative to https://www.drupal.org/project/migrate_tools. Don't use that module if you use these commands.
Defining migrations
-------------------
Learn how to create migrations from the Drupal official documentation:
* Migrate API overview: https://www.drupal.org/docs/8/api/migrate-api/migrate-api-overview
* Drupal API: https://api.drupal.org/api/drupal/core%21modules%21migrate%21migrate.api.php/group/migration
Running migrations
------------------
Drush provides a set of commands that allows to run migration operations such as importing, [checking the current status of migrations](commands/migrate_status.md), [rolling-back migrations](commands/migrate_rollback.md
), [stopping an ongoing migration](commands/migrate_stop.md), etc. Such commands are available *only* when the `migrate` module is enabled. In order the get a full list of migrate commands, type:
drush --filter=migrate
To get help on each command run drush with the command name as parameter and the `--help` option. For example next command will show details about the [migrate:import](commands/migrate_import.md) Drush command:
drush migrate:import --help
+1
View File
@@ -0,0 +1 @@
../../misc/icon_PhpStorm.png
+146
View File
@@ -0,0 +1,146 @@
# Output Formats, Fields and Filters
Drush utilizes a powerful formatting and filtering system that provides the user with a lot of control over how output from various commands is rendered.
* Output formats may be used to select the data type used to print the output. For example, many commands allow the user to select between a human-readable table, or various machine-parsable formats such as yaml and json.
* Output fields may be used to select and order the data columns.
* Output filters may be used to limit which data rows are printed based on logical expressions.
## Output Formats
The `--format` option may be used to select the data format used to print the output of a command. Most commands that produce informative output about some object or system can transform their data into different formats. For example, the [version command](commands/version.md) may be printed in a human-readable table (the default), or in a json array:
```shell
$ drush version
Drush version : 10.3.1
$ drush version --format=json
{
"drush-version": "10.3.1"
}
```
The available output formats are shown in the `help` for each command:
```shell
$ drush help version
Show drush version.
Options:
--format=<json> Select output format. Available: json, string, var_export, yaml. Default is key-value.
```
## Output Fields
If you wish to limit the number of columns produced by a command, use the `--fields` option. List the field names in the order they should be displayed:
```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 |
+-------------------+----------+
```
The available field names are shown in the `help` text:
```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"]
```
Fields may be named either using their human-readable name, or via their machine name.
Note also that some commands do not display all of their available data columns by default. To show all available fields, use `--fields=*`
There is also a singular form `--field` available. If this form is used, it will also force the output format to `string`.
```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
```
## Output Filters
A number of Drush commands that output tabular data support a `--filter` option that allows rows from the output to be selected with simple logic expressions.
In its simplest form, the `--filter` option takes a string that indicates the value to filter by in the command's *default filter field*. For example, the [role:list command](commands/role_list.md) specifies `perms` as its default filter; the output of the `role:list` command may be limited to only those roles that have a specified permission:
```shell
$ drush role:list --filter='post comments'
authenticated:
label: 'Authenticated user'
perms:
- 'access comments'
- 'access content'
- 'access shortcuts'
- 'access site-wide contact form'
- 'access user contact forms'
- 'post comments'
- 'search content'
- 'skip comment approval'
- 'use text format basic_html'
```
Note that not all commands have a default filter field.
Other fields in the output may be searched by using a simple expression in the `--filter` term. For example, to list only the enabled extensions with the `pm:list` command, you could run:
```shell
$ drush pm:list --filter='status=enabled'
```
To search for fields that contain a string using the operator `*=`, or match a regular expression with the `~=` operator. For example, to find all views whose machine name contains the word *content*:
```shell
drush views:list --filter='machine-name*=content'
```
To use a regular expression to find any core requirement notice whose title contains either *php* or *gd*
```shell
drush core:requirements --filter='title~=#(php|gd)#i'
```
Finally, filter expressions may also use logical-and (`&&`) or logical-or (`||`) operations to separate multiple terms. Parenthesis are not supported. For example, to search both the `title` and `severity` fields in the `core:requirements` command:
```shell
drush core:requirements --filter='title~=#(php|gd)#i&&severity=warning'
```
The `=` and `*=` operators always use case-insensitive comparisons. The `~=` operator is case-sensitive, unless the `i` [PCRE modifier](http://php.net/manual/en/reference.pcre.pattern.modifiers.php) is used, as shown in the previous example.
## Comparison of Filters with Grep
Using the `--filter` feature is similar to using `grep`. The main difference is that the filter feature does a semantic search, which is to say that it explicitly compares against the data in specific fields. In comparison, the `grep` command does a line-based search.
Show only results where the severity is *warning*:
`#!shell drush core:requirements --filter='severity=warning'`
Show only lines that contain the string *warning* (either in the severity field, or somewhere else on the line):
`#!shell drush core:requirements | grep -i warning`
The table below compares and contrasts the two ways of searching.
| Feature | --filter | grep |
| ----------------------- | ------------------- | -------------------------- |
| Regular expressions | Yes, with `~=` | Yes |
| Word-wrapped field data | Searched correctly | Might cause false negative |
| Search just one field | Yes | Might get false positives |
| Search multiple fields | Yes, with `||`/`&&` | Yes (line-based searching) |
| Searching hides header | No | Yes (unless it matches) |
+57
View File
@@ -0,0 +1,57 @@
{% extends "base.html" %}
{% block extrahead %}
<!-- https://squidfunk.github.io/mkdocs-material/reference/meta-tags/#open-graph -->
{% set title = config.site_name %}
{% if page and page.meta and page.meta.title %}
{% set title = config.site_name ~ " - " ~ page.meta.title %}
{% elif page and page.title and not page.is_homepage %}
{% set title = config.site_name ~ " - " ~ page.title | striptags %}
{% endif %}
<meta property="og:type" content="website" />
<meta property="og:title" content="{{ title }}" />
<meta property="og:description" content="{{ config.site_description }}" />
<meta property="og:url" content="{{ page.canonical_url }}" />
<meta property="og:image" content="https://raw.githubusercontent.com/drush-ops/drush/10.x/drush_logo-black.png" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="218" />
<meta property="og:image:height" content="215" />
{% set title = config.site_name %}
{% if page and page.meta and page.meta.title %}
{% set title = config.site_name ~ " - " ~ page.meta.title %}
{% elif page and page.title and not page.is_homepage %}
{% set title = config.site_name ~ " - " ~ page.title | striptags %}
{% endif %}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@drushcli" />
<meta name="twitter:creator" content="@weitzman" />
<meta name="twitter:title" content="{{ title }}" />
<meta name="twitter:description" content="{{ config.site_description }}" />
<meta name="twitter:image" content="https://raw.githubusercontent.com/drush-ops/drush/10.x/drush_logo-black.png" />
{% endblock %}
<!-- https://timvink.github.io/mkdocs-git-authors-plugin/usage.html -->
{% block content %}
{{ super() }}
{% if git_page_authors %}
<div class="md-source-date">
<small>
Authors: {{ git_page_authors | default('enable mkdocs-git-authors-plugin') }}
</small>
</div>
{% endif %}
{% endblock %}
{% block disqus %}
<script src="https://cdn.fastcomments.com/js/embed.min.js"></script>
<div id="fastcomments-widget"></div>
<script>
window.FastCommentsUI(document.getElementById('fastcomments-widget'), {
tenantId: '7tG3defply',
urlId: '{{ page.url }}'
});
</script>
{% endblock %}
+47
View File
@@ -0,0 +1,47 @@
<!--
Copyright (c) 2016-2020 Martin Donath <martin.donath@squidfunk.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
-->
<!-- Hack: unset variable, as we're using it recursively in tabs-item.html -->
{% set class = "" %}
<!-- Navigation tabs -->
<nav
class="md-tabs"
aria-label="{{ lang.t('tabs.title') }}"
data-md-component="tabs"
>
<div class="md-tabs__inner md-grid">
<ul class="md-tabs__list">
{% for nav_item in nav %}
{% include "partials/tabs-item.html" %}
{% endfor %}
<!-- MW: Add link built outside of mkdocs -->
<!-- This can now be done in 'nav' without an override but I'd have to hard code the domain https://github.com/squidfunk/mkdocs-material/issues/2072 and https://github.com/squidfunk/mkdocs-material/issues/1884 -->
<li class="md-tabs__item">
<a href="/api" class="md-tabs__link">API</a>
</li>
<!-- End Add -->
</ul>
</div>
</nav>
+5
View File
@@ -0,0 +1,5 @@
The [php:cli command](commands/php_cli.md) is interactive PHP REPL with your bootstrapped site (remote or local). It’s a Drupal code playground. You can do quick code experimentation, grab some data, or run Drush commands. This can also help with debugging certain issues. See [this blog post](http://webcache.googleusercontent.com/search?q=cache:gwk2crTHcrcJ:blog.damiankloip.net/2015/drush-php-settings&sca_esv=559191296&hl=en&gl=us&strip=1&vwsrc=0) for an introduction. Run `help` for a list of commands.
Any global [PsySH configuration](https://github.com/bobthecow/psysh/wiki/Configuration) is loaded by Drush. If you prefer a config file that is specific to the project (and can be checked in with other source code), [set the environment variable](https://github.com/bobthecow/psysh/wiki/Configuration#specifying-a-different-config-file) `PSYSH_CONFIG=</path/to/config-file>`. This file then takes precedence over any global file.
Entity classes are available without their namespace. For example, Node::load() works instead of Drupal\Node\entity\Noad::load().
+12
View File
@@ -0,0 +1,12 @@
Site Alias Manager
==================
The [Site Alias Manager (SAM)](https://github.com/consolidation/site-alias/blob/4.0.1/src/SiteAliasManager.php) service is used to retrieve information about one or all of the site aliases for the current installation.
- An informative example is the [browse command](https://github.com/drush-ops/drush/blob/13.x/src/Commands/core/BrowseCommands.php)
- A commandfile gets usually access to the SAM via [autowire](dependency-injection.md#autowire). The type hint to use is SiteAliasManagerInterface
- If an alias was used for the current request, it is available via `$this->siteAliasManager->getself()`.
- The SAM generally deals in [SiteAlias](https://github.com/consolidation/site-alias/blob/main/src/SiteAlias.php) objects. That is how any given site alias is represented. See its methods for determining things like whether the alias points to a local host or remote host.
- [Site alias docs](site-aliases.md).
- [Dynamically alter site aliases](https://raw.githubusercontent.com/drush-ops/drush/11.x/examples/Commands/SiteAliasAlterCommands.php).
- The SAM is also available for as [a standalone Composer project](https://github.com/consolidation/site-alias). More information available in the README there.
+315
View File
@@ -0,0 +1,315 @@
# Site aliases
### Basic usage
In its most basic form, the Drush site alias feature provides a way
for teams to share short names that refer to the live and staging sites
(usually remote) for a given Drupal site.
Add an alias file called `$PROJECT/drush/sites/self.site.yml`,
where `$PROJECT` is the project root (location of composer.json file). The site alias file should be named `self.site.yml` because this name is special, and is used to define the different environments (usually remote)
of the current Drupal site.
The contents of the alias file should look something like the example below:
```yml
# 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
```
The top-level element names (`live` and `stage` in the example above) are
used to identify the different environments available for this site. These
may be used on the command line to select a different target environment
to operate on by prepending an `@` character, e.g. `@live` or `@stage`.
Following these steps, a cache:rebuild on the live environment would be:
```bash
$ drush @live cache:rebuild
```
All of the available aliases for a site's environments may be listed via:
```bash
$ drush site:alias @self
```
The elements of a site alias are:
- **host**: The fully-qualified domain name of the remote system
hosting the Drupal instance. The `host` option
must be omitted for local sites, as this option controls various
operations, such as whether or not rsync parameters are for local or
remote machines, and so on.
- **user**: The username to log in as when using ssh or docker. If each user
has to use own username, you can create an environment variable which holds
the value, and reference via ${env.PROJECT_SSH_USER} (for example). Or you may
omit the `user` item and specify a user in the `~/.ssh/config` file.
- **root**: The Drupal root; must not be specified as a relative path.
- **uri**: The value of --uri should always be the same as
when the site is being accessed from a web browser (e.g. http://example.com)
Drush typically uses ssh to run commands on remote systems; all team members should
install ssh keys on the target servers (e.g. via `ssh-add`).
### Advanced usage
It is also possible to create site alias files that reference other
sites on the same local system. Site alias files for other local sites
are usually stored in the directory `~/.drush/sites`; however, Drush does
not search this location for alias files by default. To use this location,
you must add the path in your [Drush configuration file](using-drush-configuration.md). For example,
to re-add both of the default user alias path from Drush 8, put the following
in your `~/.drush/drush.yml` configuration file:
```yml
drush:
paths:
alias-path:
- '${env.HOME}/.drush/sites'
- /etc/drush/sites
```
A canonical alias named _example_ that points to a local
Drupal site named at http://example.com like this:
```yml
# File: example.site.yml
dev:
root: /path/to/drupal
uri: http://example.com
```
Note that the first part of the filename (in this case _example_
defines the name of the site alias, and the top-level key _dev_
defines the name of the environment.
With these definitions in place, it is possible to run commands targeting
the dev environment of the target site via:
```bash
$ drush @example.dev status
```
This command is equivalent to the longer form:
```bash
$ drush --root=/path/to/drupal --uri=http://example.com status
```
See [Additional Site Alias Options](#additional-site-alias-options) for more information.
### Altering aliases:
See [examples/Commands/SiteAliasAlterCommands.php](https://www.drush.org/latest/examples/SiteAliasAlterCommands.php/)) for an example.
### Site specifications:
When a site alias name is provided on the command line, a site specification may be used instead. A site specification is a site alias that is not saved on the filesystem but instead is provided directly e.g. `drush user@server/path/to/drupal#uri core:status`. See [example site specifications](https://github.com/consolidation/site-alias/blob/ef2eb7d37e59b3d837b4556d4d8070cb345b378c/src/SiteSpecParser.php#L24-L31).
### Environment variables
Site aliases may reference environment variables, just like any Drush config
file. For example, `${env.PROJECT_SSH_USER}` will be replaced by the value
of the `PROJECT_SSH_USER` environment value.
SSH site aliases may set environment variables via the `env-vars` key.
See below.
### Additional Site Alias Options
Aliases are commonly used to define short names for
local or remote Drupal installations; however, an alias
is really nothing more than a collection of options.
- **docker**: When specified, Drush executes via `docker-compose` exec rather than `ssh`.
- **service**: the name of the container to run on.
- **exec**:
- **options**: Options for the exec subcommand.
- **kubectl** When specified, Drush executes via `kubectl` exec rather than `ssh`.
- **namespace** The namespace to execute the command in.
- **resource** The k8s object to execute the command on.
- **container** The container in the resource to execute the command on.
- **os**: The operating system of the remote server. Valid values
are _Windows_ and _Linux_. Set this value for all remote
aliases where the remote's OS differs from the local. This is especially relevant
for the [sql:sync](commands/sql_sync.md) command.
- **ssh**: Contains settings used to control how ssh commands are generated
when running remote commands.
- **options**: Contains additional commandline options for the `ssh` command
itself, e.g. `-p 100`
- **tty**: Usually, Drush will decide whether or not to create a tty (via
the `ssh --t` option) based on whether the local Drush command is running
interactively or not. To force Drush to always or never create a tty,
set the `ssh.tty` option to _true_ or _false_, respectively.
- **paths**: An array of aliases for common rsync targets. Relative aliases are always taken from the Drupal root.
- **files**: Path to _files_ directory. This will be looked up if not specified.
- **drush-script**: Path to the remote Drush command.
- **command**: These options will only be set if the alias is used with the specified command. In the advanced example below, the option `--no-dump` will be selected whenever the `@stage` alias is used in any of the following ways:
- `drush @stage sql-sync @self @live`
- `drush sql-sync @stage @live`
- `drush sql-sync @live @stage`
- **env-vars**: An array of key / value pairs that will be set as environment variables.
Complex example:
```yml
# File: remote.site.yml
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'
```
### Site Alias Files for Service Providers
There are a number of service providers that manage Drupal sites as a
service. Drush allows service providers to create collections of site alias
files to reference all of the sites available to a single user. In order
to do this, a new location must be defined in your Drush configuration
file:
```yml
drush:
paths:
alias-path:
- '${env.HOME}/.drush/sites/provider-name'
```
Site aliases stored in this directory may then be referenced by its
full alias name, including its location, e.g.:
```bash
$ drush @provider-name.example.dev
```
Such alias files may still be referenced by their shorter name, e.g.
`@example.dev`. Note that it is necessary to individually list every
location where site alias files may be stored; Drush never does recursive
(deep) directory searches for alias files.
The `site:alias` command may also be used to list all of the sites and
environments in a given location, e.g.:
```bash
$ drush site:alias @provider-name
```
Add the option `--format=list` to show only the names of each site and
environment without also showing the values in each alias record.
### Wildcard Aliases for Service Providers
Some service providers that manage Drupal sites allow customers to create
multiple "environments" for a site. It is common for these providers to
also have a feature to automatically create Drush aliases for all of a
user's sites. Rather than write one record for every environment in that
site, it is also possible to write a single _wildcard_ alias that represents
all possible environments. This is possible if the contents of each
environment alias are identical save for the name of the environment in
one or more values. The variable `${env-name}` will be substituted with the
environment name wherever it appears.
Example wildcard record:
```yml
# 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
```
With a wildcard record, any environment name may be used, and will always
match. This is not desirable in instances where the specified environment
does not exist (e.g. if the user made a typo). An alias alter hook in a
policy file may be used to catch these mistakes and report an error.
See [SiteAliasAlterCommands](https://www.drush.org/latest/examples/SiteAliasAlterCommands.php/) for an example on how to do this.
### Docker Compose
The example below shows drush calling into a Docker hosted site. See the https://github.com/consolidation/site-alias and https://github.com/consolidation/site-process projects for more developer
information about transports.
An example appears below. Edit to suit:
```yml
# 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
```
### Kubernetes
Drush provides transport for running drush commands on your Kubernetes cluster via [kubectl](https://kubernetes.io/docs/reference/kubectl/). See an example and options below.
```yml
prod:
kubectl:
namespace: 'my-drupal-namespace'
resource: 'pods/my-drupal-pod'
container: 'drupal'
```
#### Key options
* **namespace:** The namespace where your Drupal deployment resides.
* **resource:** Kubernetes resource type (usually 'pods').
* **container:** The specific container within the pod where Drupal runs.
* **kubeconfig:** The kubeconfig file to use for authentication.
* **entrypoint:** The command to use as the container entrypoint.
### Example of rsync with exclude-paths
Note that most options typically passed to rsync via `drush rsync` are
"passthrough options", which is to say they appear after the `--` separator
on the command line. Passthrough options are actually arguments, and
it is not possible to set default arguments in an alias record. The
`drush rsync` command does support two options, `--mode` and `--exclude-paths`,
which are interpreted directly by Drush. Default values for these options
may be specified in an alias record, as shown below.
```yml
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'
```
+36
View File
@@ -0,0 +1,36 @@
Drush can be run in your shell by typing `drush` from within your project root directory or anywhere within Drupal.
$ drush [options] <command> [argument1] [argument2]
Use the [help command](commands/help.md) to get a list of available options and commands:
$ drush help pm:list
For even more documentation, use the [topic command](commands/core_topic.md):
$ drush topic
Using the --uri option and --root options.
-----------
For multi-site installations, use a site alias or the --uri option to target a particular site.
$ drush --uri=http://example.com pm:install
If you are outside the Composer project and not using a site alias, you need to specify --root and --uri for Drush to locate and bootstrap the right Drupal site.
Site Aliases
------------
Drush lets you run commands on a remote server. Once defined, aliases can be referenced with the @ nomenclature, i.e.
```bash
# Run pending updates on staging site.
$ drush @staging updatedb
# Synchronize staging files to production
$ drush rsync @staging:%files/ @live:%files
# Synchronize database from production to local, excluding the cache table
$ drush sql:sync --structure-tables-key=custom @live @self
```
See [Site aliases](site-aliases.md) for more information.
+191
View File
@@ -0,0 +1,191 @@
Drush Configuration
===================
Drush configuration is useful to cut down on typing out lengthy and repetitive command line
options, and to avoid mistakes.
#### Directories and Discovery
drush.yml files are discovered as below, in order of precedence:
1. Drupal site folder (e.g. `sites/{example.com}/drush.yml`).
2. `sites/all/drush`, `WEBROOT/drush`, or `PROJECTROOT/drush`.
3. In any location, as specified by the `--config` option.
4. User's .drush folder (i.e. `~/.drush/drush.yml`).
5. System-wide configuration folder (e.g. `/etc/drush/drush.yml` or `C:\ProgramData\Drush\drush.yml`).
If a configuration file is found in any of the above locations, it will be
loaded and merged with other configuration files in the search list. Run `drush status --fields=drush-conf`
to see all discovered config files.
#### Environment variables
Your Drush config file may reference environment variables using a syntax like `${env.HOME}`.
For example see the `drush.paths` examples below.
An alternative way to populate Drush configuration is to define environment variables that
correspond to config keys. For example, to populate the `options.uri` config item,
create an environment variable `DRUSH_OPTIONS_URI=http://example.com`.
As you can see, variable names should be uppercased, prefixed with `DRUSH_`, and periods
replaced with underscores.
### Config examples
#### Specify config files to load
```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
```
- The value may be path to a file, or to a directory containing drush.yml file(s).
- View discovered config paths: `drush status --fields=drush-conf --format=yaml`
#### Specify folders to search for Drush command files.
These locations are always merged with include paths defined on the command line or
in other configuration files. On the command line, paths may be separated
by a colon `:` on Unix-based systems or a semi-colon `;` on Windows,
or multiple `--include` options may be provided. Drush 8 and earlier did
a deep search in `~/.drush` and `/usr/share/drush/commands` when loading
command files, so we mimic that here as an example.
```yml
drush:
include:
- '${env.HOME}/.drush/commands'
- /usr/share/drush/commands
```
- View all loaded commands: `drush list`
#### Specify the folders to search for Drush alias files (*.site.yml).
These locations are always merged with alias paths defined on the command line
or in other configuration files. On the command line, paths may be
separated by a colon `:` on Unix-based systems or a semi-colon `;` on
Windows, or multiple `--alias-path` options may be provided. Note that
Drush 8 and earlier did a deep search in `~/.drush` and `/etc/drush` when
loading alias files.
```yml
drush:
paths:
alias-path:
- '${env.HOME}/.drush/sites'
- /etc/drush/sites
```
- View all loaded site aliases: `drush site:alias`
#### Backup directory
Specify a folder where Drush should store backup files, including
temporary sql dump files created during [sql:sync](https://www.drush.org/latest/commands/sql_sync/). If unspecified,
defaults to `$HOME/drush-backups`.
```yml
drush:
paths:
backup-dir: /tmp/drush-backups
```
#### Global options
```yml
options:
# Specify the base_url that should be used when generating links.
uri: 'http://example.com/subdir'
# Specify your Drupal core base directory (useful if you use symlinks).
root: '/home/USER/workspace/drupal'
# Enable verbose mode.
verbose: true
```
#### Command-specific options
```yml
command:
sql:
cli:
options:
# Enable auto-complete in MySQL.
extra: "--auto-rehash"
dump:
options:
# Omit cache and similar tables (including during a sql:sync).
structure-tables-key: common
php:
script:
options:
# Additional folders to search for scripts.
script-path: 'sites/all/scripts:profiles/myprofile/scripts'
core:
rsync:
options:
# Ensure all rsync commands use verbose output.
verbose: true
site:
install:
options:
# Set a predetermined username and password when using site:install.
account-name: 'alice'
account-pass: 'secret'
```
#### Non-options
```yml
sql:
# An explicit list of tables which should be included in sql-dump and sql-sync.
tables:
common:
- user
- permissions
- role_permissions
- role
# List of tables whose *data* is skipped by the 'sql-dump' and 'sql-sync'
# commands when the "--structure-tables-key=common" option is provided.
# You may add specific tables to the existing array or add a new element.
structure-tables:
common:
- cache
- 'cache_*'
- history
- 'search_*'
- 'sessions'
- 'watchdog'
# List of tables to be omitted entirely from SQL dumps made by the 'sql-dump'
# and 'sql-sync' commands when the "--skip-tables-key=common" option is
# provided on the command line. This is useful if your database contains
# non-Drupal tables used by some other application or during a migration for
# example. You may add new tables to the existing array or add a new element.
skip-tables:
common:
- 'migration_*'
ssh:
# Specify options to pass to ssh. The default is to prohibit
# password authentication, and is included here, so you may add additional
# parameters without losing the default configuration.
options: '-o PasswordAuthentication=no'
# This string is valid for Bash shell. Override in case you need something different. See https://github.com/drush-ops/drush/issues/3816.
pipefail: 'set -o pipefail; '
notify:
# Notify when command takes more than 30 seconds.
duration: 30
# Specify a command to run. Defaults to Notification Center (OSX) or libnotify (Linux)
cmd: /path/to/program
# See https://github.com/drush-ops/drush/blob/12.x/src/Commands/core/NotifyCommands.php for more settings.
xh:
# Start profiling via xhprof/tideways and show a link to the run report.
link: http://xhprof.local
# See https://github.com/drush-ops/drush/blob/12.x/src/Commands/core/XhprofCommands.php for more settings.
profile-builtins: true
profile-cpu: false
profile-memory: false
```
### Misc
- If you are authoring a commandfile and wish to access the user's configuration, see [Command Authoring](commands.md).
- [Setting boolean options broke with Symfony 3](https://github.com/drush-ops/drush/issues/2956). This will be fixed
in a future release.
- Version-specific configuration. Limit the version of Drush that will load a configuration file by placing
the Drush major version number in the filename, e.g. `drush10.yml`.
- The Drush configuration system has been factored out of Drush and shared with the world at [https://github.com/consolidation/config](https://github.com/consolidation/config). Feel free to use it for your projects. Lots more usage information is there.
Vendored Executable
+4
View File
@@ -0,0 +1,4 @@
#!/usr/bin/env php
<?php
require __DIR__ . '/drush.php';
+46
View File
@@ -0,0 +1,46 @@
<?php
/**
* @file
* Drupal hooks provided by the Drush package.
*/
/**
* Executes a deploy function which is intended to update data, like entities,
* after config is imported during a deployment.
*
* These are a higher level alternative to hook_update_n and hook_deploy_NAME
* functions and have to be placed in a MODULE.deploy.php file.
*
* NAME can be arbitrary machine names. In contrast to hook_update_N() the
* alphanumeric naming of functions in the file is the only thing which ensures
* the execution order of those functions. If update order is mandatory,
* you should add numerical prefix to NAME or make it completely numerical.
*
* Drupal also ensures to not execute the same hook_deploy_NAME() function
* twice.
*
* @param array $sandbox
* Stores information for batch updates.
*
* @return string|null
* Optionally, hook_deploy_NAME() hooks may return a translated string
* that will be displayed to the user after the update has completed. If no
* message is returned, no message will be presented to the user.
*
* @throws \Exception
* In case of error, update hooks should throw an instance of
* \Exception with a meaningful message for the user.
*
* @ingroup update_api
*
* @see hook_update_N()
* @see hook_post_update_NAME()
*/
function hook_deploy_NAME(array &$sandbox): string {
$node = \Drupal\node\Entity\Node::load(123);
$node->setTitle('foo');
$node->save();
return t('Node %nid saved', ['%nid' => $node->id()]);
}
+5
View File
@@ -0,0 +1,5 @@
@ECHO OFF
REM Running this file is equivalent to running `php drush`
setlocal DISABLEDELAYEDEXPANSION
SET BIN_TARGET=%~dp0drush
php "%BIN_TARGET%" %*
Vendored Executable
+141
View File
@@ -0,0 +1,141 @@
<?php
use Drush\Drush;
use Drush\Config\Environment;
use Drush\Preflight\Preflight;
use Drush\Runtime\Runtime;
use Drush\Runtime\DependencyInjection;
use Symfony\Component\Filesystem\Path;
/**
* This script runs Drush.
*
* ## Responsibilities of this script ##
*
* - Include the Composer autoload file.
* - Set up the environment (record user home directory, cwd, etc.).
* - Call the Preflight object to do all necessary setup and execution.
* - Exit with status code returned
*
* It is our goal to put all $_SERVER access and other constructs that are
* difficult to test in this script to reduce the burden on the unit tests.
* This script will only be tested via the functional tests.
*
* The Drush bootstrap goes through the following steps:
*
* - (ArgsPreprocessor) Preprocess the commandline arguments, considering only:
* - The named alias `@sitealias` (removed from arguments if present)
* - The --root option (read and retained)
* - The --config option (read and retained)
* - The --alias-path option (read and retained)
* - Load the Drush configuration and alias files from the standard
* global locations (including --config and --alias-path)
* - Determine the local Drupal site targeted, if any
* - Include the Composer autoload for Drupal (if different)
* - Extend configuration and alias files to include files in target Drupal site.
* - Create the Robo DI container and Symfony Application et. al.
* - Run the Symfony Application
* - Predispatch: call a remote Drush command if applicable
* - Bootstrap Drupal via @bootstrap command hook
* - Run commands and command hooks via annotated commands library
* - Catch 'command not found' exception, bootstrap Drupal and run again
* - Return status code
*
* ## Viable Drush configurations ##
*
* As of Drush 12, only a site-local Drush will bootstrap Drupal.
* A globally installed Drush is no longer supported.
*
* The following directory layouts are supported:
*
* Drush binary in site-local configuration in recommended Drupal site: (typical)
*
* drupal
* ├── web
* │ ├── core
* │ └── index.php
* └── vendor
* ├── autoload.php
* [*1] ├── bin
* │ └── drush.php -> ../drush/drush/drush.php
* [*2] └── drush
* └── drush
* └── drush.php
*
* Drush binary in site-local configuration in a legacy Drupal site: (unusual)
*
* drupal
* ├── core
* ├── index.php
* └── vendor
* ├── autoload.php
* [*1] ├── bin
* │ └── drush.php -> ../drush/drush/drush.php
* [*2] └── drush
* └── drush
* └── drush.php
*
* Drush project: (Only used when developing Drush)
*
* [*3] drush
* ├── drush.php
* ├── sut
* │ ├── core
* │ └── index.php
* └── vendor
* └── autoload.php
*
* The possible locations that __DIR__ may point to in the supported
* configurations are indicated by [*1], [*2] and [*3] in the diagrams
* above.
*
* Note that in the case of the Drush project, the Drupal site used for
* testing during development, called the "System Under Test", or "sut",
* counts as a site-local configuration, since the `vendor` directory is
* common between Drush and Drupal. Drush uses information from the
* project root to find the Drupal root, so it does not matter what the
* 'web' directory is called.
*/
// We use PWD if available because getcwd() resolves symlinks, which could take
// us outside of the Drupal root, making it impossible to find. In addition,
// is_dir() is used as the provided path may not be recognizable by PHP. For
// instance, Cygwin adds a '/cygdrive' prefix to the path which is a virtual
// directory.
$cwd = isset($_SERVER['PWD']) && is_dir($_SERVER['PWD']) ? $_SERVER['PWD'] : getcwd();
$autoloadFile = FALSE;
// Set up autoloader
$candidates = [
$_composer_autoload_path ?? __DIR__ . '/../vendor/autoload.php', // https://getcomposer.org/doc/articles/vendor-binaries.md#finding-the-composer-autoloader-from-a-binary
dirname(__DIR__, 2) . '/autoload.php', // Needed for \Drush\TestTraits\DrushTestTrait::getPathToDrush
__DIR__ . '/vendor/autoload.php', // For development of Drush itself.
];
foreach ($candidates as $candidate) {
if (file_exists($candidate)) {
$autoloadFile = $candidate;
break;
}
}
if (!$autoloadFile) {
throw new \Exception("Could not locate autoload.php. cwd is $cwd; __DIR__ is " . __DIR__);
}
$loader = include $autoloadFile;
if (!$loader) {
throw new \Exception("Invalid autoloadfile: $autoloadFile. cwd is $cwd; __DIR__ is " . __DIR__);
}
// Set up environment
$environment = new Environment(Path::getHomeDirectory(), $cwd, $autoloadFile);
$environment->setConfigFileVariant(Drush::getMajorVersion());
$environment->setLoader($loader);
$environment->applyEnvironment();
// Preflight and run
$preflight = new Preflight($environment);
$di = new DependencyInjection();
$di->desiredHandlers(['errorHandler', 'shutdownHandler']);
$runtime = new Runtime($preflight, $di);
$status_code = $runtime->run($_SERVER['argv']);
exit($status_code);
+4
View File
@@ -0,0 +1,4 @@
#This is a Drush config file. Sites may override this config to change minimum PHP.
drush:
php:
minimum-version: 8.1.0
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

+162
View File
@@ -0,0 +1,162 @@
<?php
namespace Drush\Commands;
use Consolidation\AnnotatedCommand\AnnotationData;
use Consolidation\AnnotatedCommand\CommandData;
use Consolidation\AnnotatedCommand\Events\CustomEventAwareInterface;
use Consolidation\AnnotatedCommand\Events\CustomEventAwareTrait;
use Consolidation\AnnotatedCommand\Hooks\HookManager;
use Consolidation\OutputFormatters\StructuredData\RowsOfFields;
use Drush\Attributes as CLI;
use Drush\Style\DrushStyle;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Run these commands using the --include option - e.g. `drush --include=/path/to/drush/examples art sandwich`
*
* See [Drush Test Traits](https://github.com/drush-ops/drush/blob/12.x/docs/contribute/unish.md#about-the-test-suites) for info on testing Drush commands.
*/
class ArtCommands extends DrushCommands implements CustomEventAwareInterface
{
use CustomEventAwareTrait;
/** @var string[] */
protected ?array $arts;
/**
* Show a fabulous picture.
*/
#[CLI\Command(name: 'artwork:show', aliases: ['arts'])]
#[CLI\Argument(name: 'art', description: 'The name of the art to display')]
#[CLI\Usage(name: 'drush art sandwich', description: 'Show a marvelous picture of a sandwich with pickles.')]
public function art($art = '')
{
$data = $this->getArt();
$name = $data[$art]['name'];
$description = $data[$art]['description'];
$path = $data[$art]['path'];
$msg = dt(
'Okay. Here is {art}: {description}',
['art' => $name, 'description' => $description]
);
$this->output()->writeln("\n" . $msg . "\n");
$this->printFile($path);
}
/**
* Show a table of information about available art.
*/
#[CLI\Command(name: 'artwork:list', aliases: ['artls'])]
#[CLI\FieldLabels(labels: ['name' => 'Name', 'description' => 'Description', 'path' => 'Path'])]
#[CLI\DefaultTableFields(fields: ['name', 'description'])]
#[CLI\FilterDefaultField(field: 'name')]
public function listArt($options = ['format' => 'table']): RowsOfFields
{
$data = $this->getArt();
return new RowsOfFields($data);
}
/**
* Commandfiles may also add topics. These will appear in
* the list of topics when `drush topic` is executed.
* To view the topic below, run `drush --include=/full/path/to/examples topic`
*/
/**
* Ruminations on the true meaning and philosophy of artwork.
*/
#[CLI\Command(name: 'artwork:explain')]
#[CLI\Topics(isTopic: true, path: __DIR__ . '/art-topic.md')]
#[CLI\Help(hidden: true)]
public function ruminate(): void
{
self::printFile($this->commandData);
}
/**
* Return the available built-in art. Any Drush commandfile may provide
* more art by implementing a 'drush-art' on-event hook. This on-event
* hook is defined in the 'findArt' method below.
*/
#[CLI\Hook(type: HookManager::ON_EVENT, target: 'drush-art')]
public function builtInArt()
{
return [
'drush' => [
'name' => 'Drush',
'description' => 'The Drush logo.',
'path' => __DIR__ . '/art/drush-nocolor.txt',
],
'sandwich' => [
'name' => 'Sandwich',
'description' => 'A tasty meal with bread often consumed at lunchtime.',
'path' => __DIR__ . '/art/sandwich-nocolor.txt',
],
];
}
#[CLI\Hook(type: HookManager::INTERACT, target: 'artwork:show')]
public function interact(InputInterface $input, OutputInterface $output, AnnotationData $annotationData)
{
$io = new DrushStyle($input, $output);
// If the user did not specify any artwork, then prompt for one.
$art = $input->getArgument('art');
if (empty($art)) {
$data = $this->getArt();
$selections = $this->convertArtListToKeyValue($data);
$selection = $io->choice('Select art to display', $selections);
$input->setArgument('art', $selection);
}
}
#[CLI\Hook(type: HookManager::ARGUMENT_VALIDATOR, target: 'artwork:show')]
public function artValidate(CommandData $commandData)
{
$art = $commandData->input()->getArgument('art');
$data = $this->getArt();
if (!isset($data[$art])) {
throw new \Exception(dt('I do not have any art called "{name}".', ['name' => $art]));
}
}
/**
* Get a list of available artwork. Cache result for future fast access.
*/
protected function getArt(): array
{
if (!isset($this->arts)) {
$this->arts = $this->findArt();
}
return $this->arts;
}
/**
* Use custom defined on-event hook 'drush-art' to find available artwork.
*/
protected function findArt()
{
$arts = [];
$handlers = $this->getCustomEventHandlers('drush-art');
foreach ($handlers as $handler) {
$handlerResult = $handler();
$arts = array_merge($arts, $handlerResult);
}
return $arts;
}
/**
* Given a list of artwork, convert to a 'key' => 'Name: Description' array.
*/
protected function convertArtListToKeyValue(array $data): array
{
$result = [];
foreach ($data as $key => $item) {
$result[$key] = $item['name'] . ': ' . $item['description'];
}
return $result;
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace Drush\Commands;
use Consolidation\AnnotatedCommand\CommandData;
use Consolidation\AnnotatedCommand\Hooks\HookManager;
use Drush\Attributes as CLI;
use Drush\Commands\core\RsyncCommands;
use Drush\Commands\core\UpdateDBCommands;
use Drush\Commands\DrushCommands;
use Drush\Commands\sql\SqlSyncCommands;
use Symfony\Component\Console\Input\InputOption;
/**
* Load this commandfile using the --include option - e.g. `drush --include=/path/to/drush/examples`
*
* See [Drush Test Traits](https://github.com/drush-ops/drush/blob/12.x/docs/contribute/unish.md#about-the-test-suites) for info on testing Drush commands.
*/
class PolicyCommands extends DrushCommands
{
/**
* Prevent catastrophic braino. Note that this file has to be local to the
* machine that initiates the sql:sync command.
*
* @throws \Exception
*/
#[CLI\Hook(type: HookManager::ARGUMENT_VALIDATOR, target: SqlSyncCommands::SYNC)]
public function sqlSyncValidate(CommandData $commandData)
{
if ($commandData->input()->getArgument('target') == '@prod') {
throw new \Exception(dt('Per !file, you may never overwrite the production database.', ['!file' => __FILE__]));
}
}
/**
* Limit rsync operations to production site.
*/
#[CLI\Hook(type: HookManager::ARGUMENT_VALIDATOR, target: RsyncCommands::RSYNC)]
public function rsyncValidate(CommandData $commandData)
{
if (preg_match("/^@prod/", $commandData->input()->getArgument('target'))) {
throw new \Exception(dt('Per !file, you may never rsync to the production site.', ['!file' => __FILE__]));
}
}
/**
* Unauthorized may not execute updates.
*/
#[CLI\Hook(type: HookManager::ARGUMENT_VALIDATOR, target: UpdateDBCommands::UPDATEDB)]
public function validateUpdateDb(CommandData $commandData)
{
if (!$commandData->input()->getOption('secret') == 'mysecret') {
throw new \Exception(dt('UpdateDb command requires a secret token per site policy.'));
}
}
#[CLI\Hook(type: HookManager::OPTION_HOOK, target: UpdateDBCommands::UPDATEDB)]
#[CLI\Option(name: 'secret', description: 'A required token else user may not run updatedb command.')]
public function optionsetUpdateDb($options = ['secret' => self::REQ])
{
}
}
@@ -0,0 +1,50 @@
<?php
namespace Drush\Commands;
use Consolidation\AnnotatedCommand\AnnotationData;
use Consolidation\AnnotatedCommand\Hooks\HookManager;
use Consolidation\SiteAlias\SiteAliasManagerAwareInterface;
use Consolidation\SiteAlias\SiteAliasManagerAwareTrait;
use Drush\Attributes as CLI;
use Symfony\Component\Console\Input\InputInterface;
/**
* Load this example by using the --include option - e.g. `drush --include=/path/to/drush/examples`
*/
class SiteAliasAlterCommands extends DrushCommands implements SiteAliasManagerAwareInterface
{
use SiteAliasManagerAwareTrait;
/**
* A few example alterations to site aliases.
*/
#[CLI\Hook(type: HookManager::PRE_INITIALIZE, target: '*')]
public function alter(InputInterface $input, AnnotationData $annotationData)
{
$self = $this->siteAliasManager()->getSelf();
if ($self->isRemote()) {
// Always pass along ssh keys.
if (!$self->has('ssh.options')) {
// Don't edit the alias - edit the general config service instead.
$this->getConfig()->set('ssh.options', '-o ForwardAgent=yes');
}
// Change the SSH user.
$input->setOption('remote-user', 'mw2');
// Test to see if specific environment really exists in wildcard
// aliases, but only if the target is a specific host.
$host = $self->get('host');
if (preg_match('#\.myserver.com$#', $host)) {
$ip = gethostbyname($host);
// If the return value of gethostbyname equals its input parameter,
// that indicates failure.
if ($host == $ip) {
$aliasName = $self->name();
throw new \Exception("The alias $aliasName refers to an environment that does not exist.");
}
}
}
}
}
@@ -0,0 +1,103 @@
<?php
namespace Drush\Commands;
use Consolidation\AnnotatedCommand\CommandData;
use Consolidation\AnnotatedCommand\Hooks\HookManager;
use Drush\Attributes as CLI;
use Drush\Commands\DrushCommands;
use Drush\Commands\sql\SqlSyncCommands;
use Drush\Drush;
use Drush\Exec\ExecTrait;
use Symfony\Component\Filesystem\Filesystem;
/**
* Load this commandfile using the --include option - e.g. `drush --include=/path/to/drush/examples`
*/
class SyncViaHttpCommands extends DrushCommands
{
/**
* When a hook extends a command with additional options, it must
* implement declare those option(s) in a @hook option like this one. Doing so will add
* the option to the help text for the modified command, and will also
* allow the new option to be specified on the command line. Without
* this, Drush will fail with an error when a user attempts to use
* an unknown option.
*/
#[CLI\Hook(type: HookManager::OPTION_HOOK, target: SqlSyncCommands::SYNC)]
#[CLI\Option(name: 'http-sync', description: 'Copy the database via http instead of rsync. Value is the url that the existing database dump can be found at.')]
#[CLI\Option(name: 'http-sync-user', description: 'Username for the protected directory containing the sql dump.')]
#[CLI\Option(name: 'http-sync-password', description: 'Password for the same directory.')]
public function optionsetSqlSync()
{
}
/**
* During the pre hook, determine if the http-sync option has been
* specified. If it has been, then disable the normal ssh + rsync
* dump-and-transfer that sql-sync usually does, and transfer the
* database dump via an http download.
*/
#[CLI\Hook(type: HookManager::PRE_COMMAND_HOOK, target: SqlSyncCommands::SYNC)]
public function preSqlSync(CommandData $commandData)
{
$sql_dump_download_url = $commandData->input()->getOption('http-sync');
if (!empty($sql_dump_download_url)) {
$user = $commandData->input()->getOption('http-sync-user');
$password = $commandData->input()->getOption('http-sync-password');
$source_dump_file = $this->downloadFile($sql_dump_download_url, $user, $password);
$commandData->input()->setOption('target-dump', $source_dump_file);
$commandData->input()->setOption('no-dump', true);
$commandData->input()->setOption('no-sync', true);
}
}
/**
* Downloads a file.
*
* Optionally uses user authentication, using either wget or curl, as available.
*/
protected function downloadFile($url, $user = false, $password = false, $destination = false, $overwrite = true)
{
static $use_wget;
if ($use_wget === null) {
$use_wget = ExecTrait::programExists('wget');
}
$destination_tmp = drush_tempnam('download_file');
if ($use_wget) {
$args = ['wget', '-q', '--timeout=30'];
if ($user && $password) {
$args = array_merge($args, ["--user=$user", "--password=$password", '-O', $destination_tmp, $url]);
} else {
$args = array_merge($args, ['-O', $destination_tmp, $url]);
}
} else {
$args = ['curl', '-s', '-L', '--connect-timeout 30'];
if ($user && $password) {
$args = array_merge($args, ['--user', "$user:$password", '-o', $destination_tmp, $url]);
} else {
$args = array_merge($args, ['-o', $destination_tmp, $url]);
}
}
$process = Drush::process($args);
$process->mustRun();
if (!Drush::simulate()) {
if (!drush_file_not_empty($destination_tmp) && $file = @file_get_contents($url)) {
@file_put_contents($destination_tmp, $file);
}
if (!drush_file_not_empty($destination_tmp)) {
// Download failed.
throw new \Exception(dt("The URL !url could not be downloaded.", ['!url' => $url]));
}
}
if ($destination) {
$fs = new Filesystem();
$fs->rename($destination_tmp, $destination, $overwrite);
return $destination;
}
return $destination_tmp;
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace Drush\Commands;
use Drush\Attributes as CLI;
use Drush\Exec\ExecTrait;
/**
* Run these commands using the --include option - e.g. `drush --include=/path/to/drush/examples xkcd`
*
* For an example of a Drush extension with tests for Drush:
* - https://github.com/drush-ops/example-drush-extension
*/
class XkcdCommands extends DrushCommands
{
use ExecTrait;
/**
* Retrieve and display xkcd cartoons.
*/
#[CLI\Command(name: 'xkcd:fetch', aliases: ['xkcd'])]
#[CLI\Option(name: 'search', description: 'Optional argument to retrieve the cartoons matching an index number, keyword search or "random". If omitted the latest cartoon will be retrieved.')]
#[CLI\Option(name: 'image-viewer', description: 'Command to use to view images (e.g. xv, firefox). Defaults to "display" (from ImageMagick).')]
#[CLI\Option(name: 'google-custom-search-api-key', description: 'Google Custom Search API Key, available from https://code.google.com/apis/console/. Default key limited to 100 queries/day globally.')]
#[CLI\Usage(name: 'drush xkcd', description: 'Retrieve and display the latest cartoon.')]
#[CLI\Usage(name: 'drush xkcd sandwich', description: 'Retrieve and display cartoons about sandwiches.')]
#[CLI\Usage(name: 'drush xkcd 123 --image-viewer=eog', description: 'Retrieve and display cartoon #123 in eog.')]
#[CLI\Usage(name: 'drush xkcd random --image-viewer=firefox', description: 'Retrieve and display a random cartoon in Firefox.')]
public function fetch($search = null, $options = ['image-viewer' => 'open', 'google-custom-search-api-key' => 'AIzaSyDpE01VDNNT73s6CEeJRdSg5jukoG244ek'])
{
$this->doFetch($search, $options);
}
/**
* @param $search
* @param array $options
* @throws \Exception
*/
protected function doFetch($search, array $options): void
{
if (empty($search)) {
$this->startBrowser('http://xkcd.com');
} elseif (is_numeric($search)) {
$this->startBrowser('http://xkcd.com/' . $search);
} elseif ($search == 'random') {
$xkcd_response = @json_decode(file_get_contents('http://xkcd.com/info.0.json'));
if (!empty($xkcd_response->num)) {
$this->startBrowser('http://xkcd.com/' . rand(1, $xkcd_response->num));
}
} else {
// This uses an API key with a limited number of searches per.
$search_response = @json_decode(file_get_contents('https://www.googleapis.com/customsearch/v1?key=' . $options['google-custom-search-api-key'] . '&cx=012652707207066138651:zudjtuwe28q&q=' . $search));
if (!empty($search_response->items)) {
foreach ($search_response->items as $item) {
$this->startBrowser($item->link);
}
} else {
throw new \Exception(dt('The search failed or produced no results.'));
}
}
}
}
+6
View File
@@ -0,0 +1,6 @@
I have discovered a truly marvelous proof that it is impossible to
separate a piece of art into two cubes, or four pieces of art into two
fourth of a piece of art, or in general, any artwork larger than the
second into two like artistic expressions.
This text file is too narrow to contain it.
@@ -0,0 +1,73 @@
.`
`++++++++++
,'',+++#####++
;;,,,,++#######+
',,,,,++#######+
',,,,,++#######+:
;,,,,:+########++
:,,,,'+########++ .
.,,,,,++########++ ,'''';+++.
,'+++. ;,,,,,++#########+ `',,,,,++#++:
',++++++ ',,,,,++#########+; :;,,,,;++###++;
',+++##+++` ';''++++#########+++++,,,,,+++#####++;
',+++#####++'`'',;++++##############++++,,+++#######++.
',;++#######+++,:+++'##################+++++##########++
',,++#########'++++'#######################+###########++
';'+++###########++####################################++
':::++#################################################+;
':::++###############################################++
::::;++#############################################++
':::+++############################################+'
':::++###########################################++
`;:::++##########################################+`
':::;++#########################################++
''''++##########################################+:
,,,,'+###########################################++
',,.++############################################+,
`:,,;+#############################################++
',,,++##############################################+
',,,++##############################################++;.
:,,,'+###############################################+++++++++:
`;';,,++#####################################################++++'
.'';,,,,,+++########################################################++
;';,,,,;++++++#########################################################++
;,;++++++++#############################################################+
,,,+++#################################################################++
.,,++###################################################################+
.,,++#################################################################@#+
.:,++############################,` .##################################++
`:,++########################## ################ #######+++++++
;,++########################: .############ ###++++++.
',++#######################; ########## ###+:
'++++##################### :###### :##+
:++++++++++#############` ###: .#++
,+++++############ :#++
',,;+############ ##+,
;,,++########### `###, ##+
'::++########### ######' #++
;:;+########### ########## ##+`
'::++########### :###' `#### #++
.':;+############ .#### #### ###++
',':++############; ###### ##### #####.,#####+,
',,,:'++####################### ######.###########@++
:,,,,,++#########################################@@@++
',,,,,'+#########################################@@@@#+;
:,,,,,,++################### `########+ #######@@@@@@++`
',,,,,++##################### #######@@@@@@@@++
',,,,,'+#######################+ ;######+#@@@@@@@@@++
',,,,++####################################+++++@@@@@@@++
',,++####################################++;:'++#@@@@#+;
''+###########+++#####################+++ '':+++@@#++
++#########+++:++++###############++++ ,'+++#++
.++#######+++ ,++++++##########+++ `'+++
.++#####++: ':;++++#########+; .
`++###++ ;::::,++#######@+,
+++++ ::::,++#####@@#+
++' ;:::,++##@@@@@#+
'::::;+@@@@@@@++
'::::,+#@@@@@@++
,'::,+#@@@@@@++
':,++@@@@@@+;
':++@##++++.
@@ -0,0 +1,34 @@
::::::::::::::::::::::::::::::::::MMMMMMMMMMMM:::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::MMMMMMMM:::::::::::MM:::::::::::::::::::::::::::::::::
:::::::::::::::::::MMMMM::::::::::::::::::::MMMM:::::::::::::::::::::::::::::::
::::::::::::::MMMMM:::::::::M::::::::M::::::::::MMMM:::::::::::::::::::::::::::
::::::::::MMMM::M:::::::::::::::::::::::::::::::::::MMMM:::::::::::::::::::::::
:::::::MMM::::::::::::::::::::::::::::::::::::::::::::::MMMM:::::::::::::::::::
:::::MM:::::::::::::::::::::::::::::::::::::::::::::::::::::MMMM:::::::::::::::
:::::M::::::::::::::::::::::::::::::::::::::::::::::::::::::::::MMM::::::::::::
:::::MMM$MM::::::::::::::::::::::::::::::::::::::::::::::::::::::::MMM:::::::::
:::::M$$$$$MM:::::::::::::::::::::::::::::::::::::::::::::M::::::::::MMM:::::::
::MMMMM$M$$$$MM:::::::::M:::::::::::::::::::::::::::::::::::::::::::MMMMM::::::
::MIIIMMMM$M$$$MM:::::::::::::::::::::::::::::::::::::::::::MMMMMMM$$$$M:::::::
:::MIIIIIIMM$$$$$MM::::::::::::::M:::::::::::::::::::MMMMMMM$$$$$$$$$$$$:::::::
:MMIIIIIIIIMM$$$$$$MMM::::::::::::::::::::::::MMMMMM$$$$$$$$$$$$$$$$$$$$M::::::
MIIMMMMMIIIIIMMM$$$$$$MM:::::::::::::::MMMMMM$$$$$$$$$$$$$$$$$$$$$$$$$$$M::::::
MMM:MM:MMMMIIIIMMM$$$$$$MM:::::::MMMMMMM$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$MMMMM::
::M::::MM::IIIIIIMM$$$$$$$$MMMMM$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$MMMMMMMMMIIM:::
::MM:::M::MIIMMIIIIIM$M$$$$M$$$$$$$$$$$$$$$$$$$$$$$$$$$$MMMMMMMIIIIIMMMMMMM::::
::::MM::MMMMM:MIIIIIIMM$M$$M$$$$$$$$$$$$$$$$$$$$$$MMMMMMMIIIIIIIIIIIM::MMM:::::
::::::$MM:::::MIIIMMIIIMM$M$$$$$$$$$$$$$$$$MMMMMMIMMMIIIIM:::MMMIIIIM:::::MM:::
::::::$$$MM:::::M::MIIIMMMM$M$$$$$$$MMMMMMIIIIIIMMM:MMMMM:::::::::::::MMMMMM:::
::::::M$$$$MM:MMM::MMM:::MIMMMMMMMMMMIIMMIIIIIIIMM+M:::::MMMM::::MMMMM$M:::::::
::::::MM$M$$$M+$$M::::::MIIIIIIIMIIIIM::::MIIIIIM:MM::::M$$M+MM$$$$$$$$::::::::
:::::::MMM$$$$$$$M:::::::MIIIIIM::MMM:::::::MMMM::::::::M$$M$$$$$$$$$$$M:::::::
::::::::::MM$$$$$$$MM::::MMMMMM:::::::::::::::::::MMMMMMM$$$$$$$$$$$$$$M:::::::
::::::::::::MM$M$$$$$MM:MM$$$$M::::::::::MMMMMMM$$$$$$$$$$$$$$$$$$MMMMM::::::::
::::::::::::::MMM$M$$$$MM$$$$$M:MMMMMMM$$$$$$$$$$$$$$$$$$$$$MMMMMM:::::::::::::
:::::::::::::::::MMM$M$M$$$$$$MMM$$$$$$$$$$$$$$$$$$$$$$MMMMM:M:M:::::::::::::::
:::::::::::::::::::MMMM$$M$$$$$$M$$$$$$$$$$$$$$$$$MMMMMM::::::M::::::::::::::::
::::::::::::::::::::::MMMMM$$$$$M$$$$$$$$$$$$$MMMMM::::::::::::::::::::::::::::
:::::::::::::::::::::::::MMMM$M$M$$$$$$$$$MMMMM::::::::::::::::::::::::::::::::
::::::::::::::::::::::::::::MMMMM$$$$MMMM::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::MMMMM:::::::::::::::::::::::::::::::::::::::::::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
+24
View File
@@ -0,0 +1,24 @@
 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
 . . . . . . . . . . .:8 ;t;;t;;;;:..:;%SX888@X%t;.. . . . 
 . . .. . . . . . .%t%;%@%%%%%%%%%%X@8888XS%t;...:;ttt%X. .
 . . . . . . . . .X:8%X%%%XS%%%%%%%XS%%%%%@%%%%X%%%@%S88 . 
 . . . . . . . . X@ @%%%X8X%%%88%%%8X%%%%%%%%%XXt@8@88@. .
 . . . . . . . .t@tS;%%8XSX%@XSX%@XSS%8@@88X@888X8SS S;S. 
 . . . . . . .@%XS%%%%%S8@X%@8%XXSSXX%S@SSSX888.;@ 888@ . . 
 . . . . . :.8:S%%%XS8X@@X%S@SSSS8SXSXXX%X88X:;@8@:S  88S. .
 . . . .8%S8%%%%%%8@SSSXXXSXSXSXSXSSS8S888 :@%:%XX:%8%:X: 
 . . .:8 %%%%@%%8@S%%XXSXSSSS8S@X%XSXX88 ;@X;SX88X8;%X88t. 
 . . 88S%S%%%%8XSSXSX@@S@%XS8@SS%@S%888 88@S:8. .;.@%X:@8;. 
 . .  88.8888888@XX 888888%X%@XX 88SS8@@;S@8.%;8@S%%:8  .
 . .  S%:8 @SSSS8 @@8@8 8 88888888@%S:8:S8 @..%S SXX8888;. .
 . . %:8S8888@88SXS S S::X@.8.8 X%S%8X:X88..% @@.S.%% .;. . 
 . .XX8@8;;%%t;;;;:@X@888888@888888.88S;8:8  ... . . .
 . . 8.;;@8@8:%%%%%t.8@%ttX@8@@@S8%8 X8S;X:@; :... . . . . .
 . tS:8@;88.;:8888X8S:.tX88888X88  S8tStS88 :.. . . . . . . 
 .:X;;:t%;tt%888S@8XS888@8.:tt@;88.tXXX8:::... . . . . . . .
 .:X8St:8SXS XS8@X 8.8%888%X8@@X88tXS8t; . . . . . . . . . 
 . :8888.88888888X@@X @ X X%S%;88;8t .. . . . . . . . .
 ... ..: . .@@888%St @ @ 8SS 8:; . . . . . . . . . . .
 . . . ..::. ..:;;::::. ... . . . . . . . . . . . .
 .. . . . . .. . . . . .. . . . . . . . . . . . . . 
+39
View File
@@ -0,0 +1,39 @@
#
# A minimalist Drush config file.
# See https://www.drush.org/latest/using-drush-configuration/ for lots more documentation.
#
# Preflight configuration.
drush:
include:
- '${env.HOME}/.drush/commands'
- /usr/share/drush/commands
paths:
config:
# Load additional config files. Is silently skipped if not found. Filename must be drush.yml
- ${env.HOME}/.drush/config/drush.yml
alias-path:
- '${env.HOME}/.drush/sites'
- /etc/drush/sites
# Global options.
options:
# Specify the base_url that should be used when generating links.
# uri: 'http://example.com/subdir'
# Command-specific options.
command:
sql:
dump:
options:
# Uncomment to omit cache and similar tables (including during a sql:sync).
# structure-tables-key: common
# Non-options.
ssh:
# Specify options to pass to ssh. The default is to prohibit
# password authentication, and is included here, so you may add additional
# parameters without losing the default configuration.
options: '-o PasswordAuthentication=no'
# This string is valid for Bash shell. Override in case you need something different. See https://github.com/drush-ops/drush/issues/3816.
pipefail: 'set -o pipefail; '
+107
View File
@@ -0,0 +1,107 @@
# -*- mode: shell-script; mode: flyspell-prog; ispell-local-dictionary: "american" -*-
#
# Example PS1 prompt.
#
# Note: This file does a lot, and is designed for Bash. If you want to show the
# currently set alias in your prompt, use the first 2 values below as an example.
# This section can be used for the POWERLEVEL9K theme for Oh My Zsh.
#FILE="${TMPDIR:-/tmp/}/drush-env-${USER}/drush-drupal-site-$$"
#POWERLEVEL9K_CUSTOM_DRUSH="[ -r $FILE ] && cat $FILE"
#POWERLEVEL9K_CUSTOM_DRUSH_BACKGROUND="green"
#POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(context dir vcs custom_drush)
#
# Note that your Bash session must already have the __git_ps1 function available.
# Typically this is provided by git-prompt.sh, see instructions for downloading
# and including this file here:
# https://github.com/git/git/blob/10.x/contrib/completion/git-prompt.sh
#
# Features:
#
# Displays Git repository and Drush alias status in your prompt.
__drush_ps1() {
f="${TMPDIR:-/tmp/}/drush-env-${USER}/drush-drupal-site-$$"
if [ -f $f ]
then
__DRUPAL_SITE=$(cat "$f")
else
__DRUPAL_SITE="$DRUPAL_SITE"
fi
# Set DRUSH_PS1_SHOWCOLORHINTS to a non-empty value and define a
# __drush_ps1_colorize_alias() function for color hints in your Drush PS1
# prompt. See example.prompt.sh for an example implementation.
if [ -n "${__DRUPAL_SITE-}" ] && [ -n "${DRUSH_PS1_SHOWCOLORHINTS-}" ]; then
__drush_ps1_colorize_alias
fi
[[ -n "$__DRUPAL_SITE" ]] && printf "${1:- (%s)}" "$__DRUPAL_SITE"
}
if [ -n "$(type -t __git_ps1)" ] && [ "$(type -t __git_ps1)" = function ] && [ "$(type -t __drush_ps1)" ] && [ "$(type -t __drush_ps1)" = function ]; then
# This line enables color hints in your Drush prompt. Modify the below
# __drush_ps1_colorize_alias() to customize your color theme.
DRUSH_PS1_SHOWCOLORHINTS=true
# Git offers various prompt customization options as well as seen in
# https://github.com/git/git/blob/10.x/contrib/completion/git-prompt.sh.
# Adjust the following lines to enable the corresponding features:
#
GIT_PS1_SHOWDIRTYSTATE=true
GIT_PS1_SHOWUPSTREAM=auto
# GIT_PS1_SHOWSTASHSTATE=true
# GIT_PS1_SHOWUNTRACKEDFILES=true
GIT_PS1_SHOWCOLORHINTS=true
# The following line sets your bash prompt according to this example:
#
# username@hostname ~/working-directory (git-branch)[@drush-alias] $
#
# See http://ss64.com/bash/syntax-prompt.html for customization options.
export PROMPT_COMMAND='__git_ps1 "\u@\h \w" "$(__drush_ps1 "[%s]") \\\$ "'
# PROMPT_COMMAND is used in the example above rather than PS1 because neither
# Git nor Drush color hints are compatible with PS1. If you don't want color
# hints, however, and prefer to use PS1, you can still do so by commenting out
# the PROMPT_COMMAND line above and uncommenting the PS1 line below:
#
# export PS1='\u@\h \w$(__git_ps1 " (%s)")$(__drush_ps1 "[%s]")\$ '
__drush_ps1_colorize_alias() {
if [[ -n ${ZSH_VERSION-} ]]; then
local COLOR_BLUE='%F{blue}'
local COLOR_CYAN='%F{cyan}'
local COLOR_GREEN='%F{green}'
local COLOR_MAGENTA='%F{magenta}'
local COLOR_RED='%F{red}'
local COLOR_WHITE='%F{white}'
local COLOR_YELLOW='%F{yellow}'
local COLOR_NONE='%f'
else
# Using \[ and \] around colors is necessary to prevent issues with
# command line editing/browsing/completion.
local COLOR_BLUE='\[\e[94m\]'
local COLOR_CYAN='\[\e[36m\]'
local COLOR_GREEN='\[\e[32m\]'
local COLOR_MAGENTA='\[\e[35m\]'
local COLOR_RED='\[\e[91m\]'
local COLOR_WHITE='\[\e[37m\]'
local COLOR_YELLOW='\[\e[93m\]'
local COLOR_NONE='\[\e[0m\]'
fi
# Customize your color theme below.
case "$__DRUPAL_SITE" in
*.live|*.prod) local ENV_COLOR="$COLOR_RED" ;;
*.stage|*.test) local ENV_COLOR="$COLOR_YELLOW" ;;
*.local) local ENV_COLOR="$COLOR_GREEN" ;;
*) local ENV_COLOR="$COLOR_BLUE" ;;
esac
__DRUPAL_SITE="${ENV_COLOR}${__DRUPAL_SITE}${COLOR_NONE}"
}
fi
+27
View File
@@ -0,0 +1,27 @@
#
# A minimalist Drush site alias file.
# See https://www.drush.org/latest/site-aliases/ for lots more documentation.
#
# File: self.site.yml
live:
host: www.domain.com
user: www-admin
root: /other/path/to/drupal
uri: http://www.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'
stage:
host: stage.domain.com
user: www-admin
root: /other/path/to/drupal
uri: http://stage.example.com
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env sh
#
# Git bisect is a helpful way to discover which commit an error
# occurred in. This example file gives simple instructions for
# using git bisect with Drush to quickly find erroneous commits
# in Drush commands or Drupal modules, presuming that you can
# trigger the error condition via Drush (e.g. using `drush php-eval`).
#
# Follow these simple steps:
#
# $ git bisect start
# $ git bisect bad # Tell git that the current commit does not work
# $ git bisect good bcadd5a # Tell drush that the commithash 12345 worked fine
# $ git bisect run mytestscript.sh
#
# 'git bisect run' will continue to call 'git bisect good' and 'git bisect bad',
# based on whether the script's exit code was 0 or 1, respectively.
#
# Replace 'mytestscript.sh' in the example above with a custom script that you
# write yourself. Use the example script at the end of this document as a
# guide. Replace the example command with one that calls the Drush command
# that you would like to test, and replace the 'grep' string with a value
# that appears when the error exists in the commit, but does not appear when
# commit is okay.
#
# If you are using Drush to test Drupal or an external Drush module, use:
#
# $ git bisect run drush mycommand --strict=2
#
# This presumes that there is one or more '[warning]' or '[error]'
# messages emitted when there is a problem, and no warnings or errors
# when the commit is okay. Omit '--strict=2' to ignore warnings, and
# signal failure only when 'error' messages are emitted.
#
# If you need to test for an error condition explicitly, to find errors
# that do not return any warning or error log messages on their own, you
# can use the Drush php-eval command to force an error when `myfunction()`
# returns FALSE. Replace 'myfunction()' with the name of an appropriate
# function in your module that can be used to detect the error condition
# you are looking for.
#
# $ git bisect run drush ev 'if(!myfunction()) { return drush_set_error("ERR"); }'
#
drush mycommand --myoption 2>&1 | grep -q 'string that indicates there was a problem'
if [ $? == 0 ] ; then
exit 1
else
exit 0
fi
+25
View File
@@ -0,0 +1,25 @@
<?php
//
// This example demonstrates how to write a drush
// script. These scripts are run with the php:script command.
//
use Drush\Drush;
$this->output()->writeln("Hello world!");
$this->output()->writeln("The extra options/arguments to this command were:");
$this->output()->writeln(print_r($extra, true));
//
// We can check which site was bootstrapped via
// the '@self' alias, which is defined only if
// there is a bootstrapped site.
//
$self = Drush::aliasManager()->getSelf();;
if (!$self->hasRoot()) {
$this->output()->writeln('No bootstrapped site.');
}
else {
$this->output()->writeln('The following site is bootstrapped:');
$this->output()->writeln(print_r($self->legacyRecord(), true));
}
+378
View File
@@ -0,0 +1,378 @@
<?php
/**
* @file
* Drush batch API.
*
* This file contains a fork of the Drupal Batch API that has been drastically
* simplified and tailored to Drush's unique use case.
*
* The existing API is very targeted towards environments that are web accessible,
* and would frequently attempt to redirect the user which would result in the
* drush process being completely destroyed with no hope of recovery.
*
* While the original API does offer a 'non progressive' mode which simply
* calls each operation in sequence within the current process, in most
* implementations (D6), it would still attempt to redirect
* unless very specific conditions were met.
*
* When operating in 'non progressive' mode, Drush would experience the problems
* that the API was written to solve in the first place, specifically that processes
* would exceed the available memory and exit with an error.
*
* Each major release of Drupal has also had slightly different implementations
* of the batch API, and this provides a uniform interface to all of these
* implementations.
*/
use Drupal\Core\Database\Database;
use Drupal\Core\Database\IntegrityConstraintViolationException;
use Drush\Drush;
/**
* Process a Drupal batch by spawning multiple Drush processes.
*
* The batch system will process as many batch sets as possible until
* the entire batch has been completed or 60% of the available memory
* has been used.
*
* This function is a drop in replacement for the existing batch_process()
* function of Drupal.
*
* @param string $command
* (optional) The command to call for the back end process. By default this will be
* the 'batch-process' command, but some commands will
* have special initialization requirements, and will need to define and
* use their own command.
* @param array $args
* (optional)
* @param array $options
* (optional)
*/
function drush_backend_batch_process($command = 'batch-process', $args = [], $options = []) {
// Command line options to pass to the command.
$options['u'] = \Drupal::currentUser()->id();
return _drush_backend_batch_process($command, $args, $options);
}
/**
* Process sets from the specified batch.
*
* This function is called by the worker process that is spawned by the
* drush_backend_batch_process function.
*
* The command called needs to call this function after it's special bootstrap
* requirements have been taken care of.
*
* @param int $id
* The batch ID of the batch being processed.
*
* @return bool|array
* A results array.
*/
function drush_batch_command($id) {
include_once(DRUSH_DRUPAL_CORE . '/includes/batch.inc');
return _drush_batch_command($id);
}
/**
* Main loop for the Drush batch API.
*
* Saves a record of the batch into the database, and progressively call $command to
* process the operations.
*
* @param command
* The command to call to process the batch.
*
* @return array
* A return array. The callers only care about the finished marker and an #abort on an operation.
*
*/
function _drush_backend_batch_process($command = 'batch-process', $args = [], $options = []) {
$result = NULL;
$batch = &batch_get();
if (isset($batch)) {
$process_info = [
'current_set' => 0,
];
$batch += $process_info;
// The batch is now completely built. Allow other modules to make changes
// to the batch so that it is easier to reuse batch processes in other
// environments.
\Drupal::moduleHandler()->alter('batch', $batch);
// Assign an arbitrary id: don't rely on a serial column in the 'batch'
// table, since non-progressive batches skip database storage completely.
/** @var \Drupal\Core\Batch\BatchStorageInterface $batch_storage */
$batch_storage = \Drupal::service('batch.storage');
if (method_exists($batch_storage, 'getId')) {
try {
$batch['id'] = $batch_storage->getId();
}
catch (IntegrityConstraintViolationException) {
// @todo this is here to support the update path to deprecate
// Connection::nextId(). Remove when Drupal 10.1 and lower is no longer
// supported.
$connection = \Drupal::database();
$max_bid = (int) $connection->query('SELECT MAX([bid]) FROM {batch}')->fetchField();
$batch['id'] = $max_bid + 1;
$connection->insert('batch')
->fields([
'bid' => $batch['id'],
'timestamp' => \Drupal::time()->getRequestTime(),
'token' => '',
'batch' => NULL,
])
->execute();
}
}
else {
$batch['id'] = \Drupal::database()->nextId();
}
$args[] = $batch['id'];
$batch['progressive'] = TRUE;
// Move operations to a job queue. Non-progressive batches will use a
// memory-based queue.
foreach ($batch['sets'] as $key => $batch_set) {
_batch_populate_queue($batch, $key);
}
// Store the batch.
$batch_storage->create($batch);
$finished = FALSE;
while (!$finished) {
$process = Drush::drush(Drush::aliasManager()->getSelf(), $command, $args);
// We already re-spawn when memory is low so no need for timeout.
$process->setTimeout(null);
// Suppress printing stdout since a JSON array is returned to us here.
$process->run($process->showRealtime()->hideStdout());
$result = $process->getOutputAsJson();
$finished = !$process->isSuccessful() || (isset($result['drush_batch_process_finished']) && $result['drush_batch_process_finished'] === TRUE);
}
}
// An attempt to clear the batch is performed in "_drush_batch_finished",
// however when that is run in a separate process, static cache changes need
// to be replayed.
$batch = NULL;
return $result;
}
/**
* Initialize the batch command and call the worker function.
*
* Loads the batch record from the database and sets up the requirements
* for the worker, such as registering the shutdown function.
*
* @param id
* The batch id of the batch being processed.
*
* @return bool|array
* A results array.
*/
function _drush_batch_command($id) {
$batch = &batch_get();
$data = Database::getConnection()->select('batch', 'b')
->fields('b', ['batch'])
->condition('bid', $id)
->execute()
->fetchField();
if ($data) {
$batch = unserialize($data);
}
else {
return FALSE;
}
if (!isset($batch['running'])) {
$batch['running'] = TRUE;
}
// Register database update for end of processing.
register_shutdown_function('_drush_batch_shutdown');
if (_drush_batch_worker()) {
return _drush_batch_finished();
}
else {
return ['drush_batch_process_finished' => FALSE];
}
}
/**
* Process batch operations
*
* Using the current $batch process each of the operations until the batch
* has been completed or 60% of the available memory for the process has been
* reached.
*/
function _drush_batch_worker() {
$batch = &batch_get();
$current_set = &_batch_current_set();
$set_changed = TRUE;
if (empty($current_set['start'])) {
$current_set['start'] = microtime(TRUE);
}
$queue = _batch_queue($current_set);
while (!$current_set['success']) {
// If this is the first time we iterate this batch set in the current
// request, we check if it requires an additional file for functions
// definitions.
if ($set_changed && isset($current_set['file']) && is_file($current_set['file'])) {
include_once DRUPAL_ROOT . '/' . $current_set['file'];
}
$task_message = '';
// Assume a single pass operation and set the completion level to 1 by
// default.
$finished = 1;
if ($item = $queue->claimItem()) {
[$callback, $args] = $item->data;
// Build the 'context' array and execute the function call.
$batch_context = [
'sandbox' => &$current_set['sandbox'],
'results' => &$current_set['results'],
'finished' => &$finished,
'message' => &$task_message,
];
// Tolerate recoverable errors.
// See https://github.com/drush-ops/drush/issues/1930
$halt_on_error = \Drush\Drush::config()->get('runtime.php.halt-on-error', TRUE);
\Drush\Drush::config()->set('runtime.php.halt-on-error', FALSE);
call_user_func_array($callback, array_merge($args, [&$batch_context]));
if (!empty($task_message)) {
Drush::logger()->notice(strip_tags($task_message));
}
\Drush\Drush::config()->set('runtime.php.halt-on-error', $halt_on_error);
if ($finished >= 1) {
// Make sure this step is not counted twice when computing $current.
$finished = 0;
// Remove the processed operation and clear the sandbox.
$queue->deleteItem($item);
$current_set['count']--;
$current_set['sandbox'] = [];
}
}
// When all operations in the current batch set are completed, browse
// through the remaining sets, marking them 'successfully processed'
// along the way, until we find a set that contains operations.
// _batch_next_set() executes form submit handlers stored in 'control'
// sets (see form_execute_handlers()), which can in turn add new sets to
// the batch.
$set_changed = FALSE;
$old_set = $current_set;
while (empty($current_set['count']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
$current_set = &_batch_current_set();
$current_set['start'] = microtime(TRUE);
$set_changed = TRUE;
}
// At this point, either $current_set contains operations that need to be
// processed or all sets have been completed.
$queue = _batch_queue($current_set);
// If we are in progressive mode, break processing after 60% of memory usage
// is reached.
if (drush_memory_limit() > 0 && (memory_get_usage() * 1.6) >= drush_memory_limit()) {
Drush::logger()->notice(dt("Batch process has consumed in excess of 60% of available memory. Starting new thread"));
// Record elapsed wall clock time.
$current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
break;
}
}
// Reporting 100% progress will cause the whole batch to be considered
// processed. If processing was paused right after moving to a new set,
// we have to use the info from the new (unprocessed) set.
if ($set_changed && isset($current_set['queue'])) {
// Processing will continue with a fresh batch set.
$remaining = $current_set['count'];
$total = $current_set['total'];
$progress_message = $current_set['init_message'];
$task_message = '';
}
else {
// Processing will continue with the current batch set.
$remaining = $old_set['count'];
$total = $old_set['total'];
$progress_message = $old_set['progress_message'];
}
$current = $total - $remaining + $finished;
$percentage = _batch_api_percentage($total, $current);
return ($percentage == 100);
}
/**
* End the batch processing:
* Call the 'finished' callbacks to allow custom handling of results,
* and resolve page redirection.
*
* @return array
*/
function _drush_batch_finished() {
$results = [];
$batch = &batch_get();
// Execute the 'finished' callbacks for each batch set, if defined.
foreach ($batch['sets'] as $id => $batch_set) {
if (isset($batch_set['finished'])) {
// Check if the set requires an additional file for function definitions.
if (isset($batch_set['file']) && is_file($batch_set['file'])) {
include_once DRUPAL_ROOT . '/' . $batch_set['file'];
}
if (is_callable($batch_set['finished'])) {
$queue = _batch_queue($batch_set);
$operations = $queue->getAllItems();
$elapsed = $batch_set['elapsed'] / 1000;
$elapsed = \Drupal::service('date.formatter')->formatInterval($elapsed);
call_user_func_array($batch_set['finished'], [$batch_set['success'], $batch_set['results'], $operations, $elapsed]);
$results[$id] = $batch_set['results'];
}
}
}
// Clean up the batch table.
\Drupal::service('batch.storage')->delete($batch['id']);
foreach ($batch['sets'] as $batch_set) {
if ($queue = _batch_queue($batch_set)) {
$queue->deleteQueue();
}
}
$batch = NULL;
$results['drush_batch_process_finished'] = TRUE;
return $results;
}
/**
* Shutdown function: store the batch data for next request,
* or clear the table if the batch is finished.
*/
function _drush_batch_shutdown() {
if ($batch = batch_get()) {
/** @var \Drupal\Core\Batch\BatchStorage $batch_storage */
$batch_storage = \Drupal::service('batch.storage');
$batch_storage->update($batch);
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* @deprecated see DrupalBootLevels::NONE
*/
define('DRUSH_BOOTSTRAP_NONE', 0);
/**
* Use MAX instead of drush_bootstrap_to_phase
*
* This constant is only usable as the value of the 'bootstrap'
* item of a command object, or as the parameter to
* drush_bootstrap_to_phase. It is not a real bootstrap state.
*
* @deprecated see DrupalBootLevels::NONE
*/
define('DRUSH_BOOTSTRAP_MAX', -2);
/**
* @deprecated
*
* No longer used, but 0 remains reserved. Drush always runs preflight.
* Commands may alternatively use DRUSH_BOOTSTRAP_NONE.
*/
define('DRUSH_BOOTSTRAP_DRUSH', 0);
/**
* @deprecated see DrupalBootLevels::ROOT
*/
define('DRUSH_BOOTSTRAP_DRUPAL_ROOT', 1);
/**
* @deprecated see DrupalBootLevels::SITE
*/
define('DRUSH_BOOTSTRAP_DRUPAL_SITE', 2);
/**
* @deprecated see DrupalBootLevels::CONFIGURATION
*/
define('DRUSH_BOOTSTRAP_DRUPAL_CONFIGURATION', 3);
/**
* @deprecated see DrupalBootLevels::DATABASE
*/
define('DRUSH_BOOTSTRAP_DRUPAL_DATABASE', 4);
/**
* @deprecated see DrupalBootLevels::FULL
*/
define('DRUSH_BOOTSTRAP_DRUPAL_FULL', 5);
+97
View File
@@ -0,0 +1,97 @@
<?php
use Drush\Drush;
use Drush\Utils\StringUtils;
use Psr\Log\LogLevel;
/**
* The number of bytes in a kilobyte. Copied from Drupal.
*/
define('DRUSH_KILOBYTE', 1024);
/**
* Calls a given function, passing through all arguments unchanged.
*
* This should be used when calling possibly mutative or destructive functions
* (e.g. unlink() and other file system functions) so that can be suppressed
* if the simulation mode is enabled.
*
* @param $callable
* The name of the function. Any additional arguments are passed along.
* @return
* The return value of the function, or TRUE if simulation mode is enabled.
*
*/
function drush_op($callable) {
$args_printed = [];
$args = func_get_args();
array_shift($args); // Skip function name
foreach ($args as $arg) {
$args_printed[] = is_scalar($arg) ? $arg : (is_object($arg) ? get_class($arg) : gettype($arg));
}
if (!is_array($callable)) {
$callable_string = $callable;
}
else {
if (is_object($callable[0])) {
$callable_string = get_class($callable[0]) . '::' . $callable[1];
}
else {
$callable_string = implode('::', $callable);
}
}
if (\Drush\Drush::verbose() || \Drush\Drush::simulate()) {
Drush::logger()->debug('Calling {method}({args})', ['method' => $callable_string, 'args' => implode(", ", $args_printed)]);
}
if (\Drush\Drush::simulate()) {
return TRUE;
}
return drush_call_user_func_array($callable, $args);
}
/**
* Mimic cufa but still call function directly. See http://drupal.org/node/329012#comment-1260752
*/
function drush_call_user_func_array($function, $args = []) {
if (is_array($function)) {
// $callable is a method so always use CUFA.
return call_user_func_array($function, $args);
}
switch (count($args)) {
case 0: return $function(); break;
case 1: return $function($args[0]); break;
case 2: return $function($args[0], $args[1]); break;
case 3: return $function($args[0], $args[1], $args[2]); break;
case 4: return $function($args[0], $args[1], $args[2], $args[3]); break;
case 5: return $function($args[0], $args[1], $args[2], $args[3], $args[4]); break;
case 6: return $function($args[0], $args[1], $args[2], $args[3], $args[4], $args[5]); break;
case 7: return $function($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6]); break;
case 8: return $function($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7]); break;
case 9: return $function($args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6], $args[7], $args[8]); break;
default: return call_user_func_array($function,$args);
}
}
/**
* Get the PHP memory_limit value in bytes.
*/
function drush_memory_limit() {
$value = trim(ini_get('memory_limit'));
$last = strtolower($value[strlen($value)-1]);
$size = (int) rtrim($value, 'GgMmKk');
switch ($last) {
case 'g':
$size *= DRUSH_KILOBYTE;
case 'm':
$size *= DRUSH_KILOBYTE;
case 'k':
$size *= DRUSH_KILOBYTE;
}
return $size;
}
+242
View File
@@ -0,0 +1,242 @@
<?php
/**
* @file
* Filesystem utilities.
*/
use Drush\Drush;
use Drush\Sql\SqlBase;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;
/**
* @defgroup filesystemfunctions Filesystem convenience functions.
* @{
*/
/**
* Deletes the specified file or directory and everything inside it.
*
* Usually respects read-only files and folders. To do a forced delete use
* drush_delete_tmp_dir() or set the parameter $forced.
*
* @param string $dir
* The file or directory to delete.
* @param bool $force
* Whether or not to try everything possible to delete the directory, even if
* it's read-only. Defaults to FALSE.
* @param bool $follow_symlinks
* Whether or not to delete symlinked files. Defaults to FALSE--simply
* unlinking symbolic links.
*
* @return bool
* FALSE on failure, TRUE if everything was deleted.
*
* @deprecated Use \Symfony\Component\Filesystem\Filesystem::remove.
*/
function drush_delete_dir($dir, $force = FALSE, $follow_symlinks = FALSE) {
// Do not delete symlinked files, only unlink symbolic links
if (is_link($dir) && !$follow_symlinks) {
return unlink($dir);
}
// Allow to delete symlinks even if the target doesn't exist.
if (!is_link($dir) && !file_exists($dir)) {
return TRUE;
}
if (!is_dir($dir)) {
if ($force) {
// Force deletion of items with readonly flag.
@chmod($dir, 0777);
}
return unlink($dir);
}
if (drush_delete_dir_contents($dir, $force) === FALSE) {
return FALSE;
}
if ($force) {
// Force deletion of items with readonly flag.
@chmod($dir, 0777);
}
return rmdir($dir);
}
/**
* Deletes the contents of a directory.
*
* @param string $dir
* The directory to delete.
* @param bool $force
* Whether or not to try everything possible to delete the contents, even if
* they're read-only. Defaults to FALSE.
*
* @return bool
* FALSE on failure, TRUE if everything was deleted.
*/
function drush_delete_dir_contents($dir, $force = FALSE) {
$scandir = @scandir($dir);
if (!is_array($scandir)) {
return FALSE;
}
foreach ($scandir as $item) {
if ($item == '.' || $item == '..') {
continue;
}
if ($force) {
@chmod($dir, 0777);
}
if (!drush_delete_dir($dir . '/' . $item, $force)) {
return FALSE;
}
}
return TRUE;
}
/**
* Recursively create a directory tree.
*
* @param path
* Path to directory to create.
*
* @throws IOException On any directory creation failure
* @deprecated See \Symfony\Component\Filesystem\Filesystem::mkdir.
*/
function drush_mkdir($path) {
$fs = new Filesystem();
$fs->mkdir($path);
return true;
}
/**
* Save a string to a temporary file. Does not depend on Drupal's API.
* The temporary file will be automatically deleted when drush exits.
*
* @param string $data
* @param string $suffix
* Append string to filename. use of this parameter if is discouraged. @see
* drush_tempnam().
* @return string
* A path to the file.
*/
function drush_save_data_to_temp_file($data, $suffix = NULL) {
static $fp;
$file = drush_tempnam('drush_', NULL, $suffix);
$fp = fopen($file, "w");
fwrite($fp, $data);
$meta_data = stream_get_meta_data($fp);
$file = $meta_data['uri'];
fclose($fp);
return $file;
}
/**
* Returns the path to a temporary directory.
*
* @deprecated Use $this->getConfig()->tmp() in a ConfigAware command.
*/
function drush_find_tmp() {
return Drush::config()->tmp();
}
/**
* Creates a temporary file, and registers it so that
* it will be deleted when drush exits. Whenever possible,
* drush_save_data_to_temp_file() should be used instead
* of this function.
*
* @param string $suffix
* Append this suffix to the filename. Use of this parameter is discouraged as
* it can break the guarantee of tempname(). See http://www.php.net/manual/en/function.tempnam.php#42052.
* Originally added to support Oracle driver.
*/
function drush_tempnam($pattern, $tmp_dir = NULL, $suffix = '') {
if ($tmp_dir == NULL) {
$tmp_dir = Drush::config()->tmp();
}
$tmp_file = Path::canonicalize(tempnam($tmp_dir, $pattern));
drush_register_file_for_deletion($tmp_file);
$tmp_file_with_suffix = $tmp_file . $suffix;
drush_register_file_for_deletion($tmp_file_with_suffix);
return $tmp_file_with_suffix;
}
/**
* Creates a temporary directory and return its path.
*/
function drush_tempdir() {
$tmp_dir = Path::join(Drush::config()->tmp(), 'drush_tmp_' . uniqid(time() . '_'));
$fs = new Filesystem();
$fs->mkdir($tmp_dir);
drush_register_file_for_deletion($tmp_dir);
return $tmp_dir;
}
/**
* Any file passed in to this function will be deleted
* when drush exits.
*/
function drush_register_file_for_deletion($file = NULL) {
static $registered_files = array();
if (isset($file)) {
if (empty($registered_files)) {
register_shutdown_function('_drush_delete_registered_files');
}
$registered_files[] = $file;
}
return $registered_files;
}
/**
* Delete all of the registered temporary files.
*/
function _drush_delete_registered_files() {
$files_to_delete = drush_register_file_for_deletion();
foreach ($files_to_delete as $file) {
// We'll make sure that the file still exists, just
// in case someone came along and deleted it, even
// though they did not need to.
if (file_exists($file)) {
if (is_dir($file)) {
drush_delete_dir($file, TRUE);
}
else {
@chmod($file, 0777); // Make file writeable
unlink($file);
}
}
}
}
/**
* Test to see if a file exists and is not empty
*/
function drush_file_not_empty($file_to_test) {
if (file_exists($file_to_test)) {
clearstatcache();
$stat = stat($file_to_test);
if ($stat['size'] > 0) {
return TRUE;
}
}
return FALSE;
}
/**
* Return 'TRUE' if one directory is located anywhere inside
* the other.
*/
function drush_is_nested_directory($base_dir, $test_is_nested) {
$common = Path::getLongestCommonBasePath($test_is_nested, $base_dir);
return $common == Path::canonicalize($base_dir);
}
/**
* @} End of "defgroup filesystemfunctions".
*/
+7
View File
@@ -0,0 +1,7 @@
<?php
/**
* Temporary wrapper functions to ease usage across major Drupal versions.
*/
+56
View File
@@ -0,0 +1,56 @@
<?php
use Drupal\Core\Render\Markup;
use Drush\Utils\StringUtils;
/**
* @defgroup outputfunctions Process output text.
* @{
*/
/**
* Rudimentary translation system, akin to Drupal's t() function.
*
* @param string
* String to process, possibly with replacement item.
* @param array
* An associative array of replacement items.
*
* @return
* The processed string.
*/
function dt($string, $args = []) {
return StringUtils::interpolate($string, $args);
}
/**
* Convert html to readable text. Compatible API to
* drupal_html_to_text, but less functional. Caller
* might prefer to call drupal_html_to_text if there
* is a bootstrapped Drupal site available.
*
* @param string $html
* The html text to convert.
*
* @return string
* The plain-text representation of the input.
*/
function drush_html_to_text($html, $allowed_tags = NULL) {
$replacements = [
'<hr>' => '------------------------------------------------------------------------------',
'<li>' => ' * ',
'<h1>' => '===== ',
'</h1>' => ' =====',
'<h2>' => '---- ',
'</h2>' => ' ----',
'<h3>' => '::: ',
'</h3>' => ' :::',
'<br/>' => "\n",
];
$text = str_replace(array_keys($replacements), array_values($replacements), $html);
return html_entity_decode(preg_replace('/ *<[^>]*> */', ' ', $text));
}
/**
* @} End of "defgroup outputfunctions".
*/
+25
View File
@@ -0,0 +1,25 @@
<?php
/**
* @file
* Postflight and shutdown code.
*/
use Drush\Drush;
use Drush\Runtime\Runtime;
/**
* The main Drush function.
*
* This function is still called by drush-launcher. It is no longer used by
* Drush itself.
*/
function drush_main() {
// See https://getcomposer.org/doc/articles/vendor-binaries.md#finding-the-composer-autoloader-from-a-binary.
if (isset($_composer_bin_dir) && isset($_composer_autoload_path)) {
require dirname(__DIR__) . '/drush.php';
}
else {
throw new RuntimeException('Drush Launcher is not compatible with Drush 12+. See https://github.com/drush-ops/drush-launcher/issues/105.');
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
/**
* A sneaky implementation of hook_module_implements_alter().
*
* site:install includes this file in order to not run any cron hooks during install.
* That's a bad idea.
*
* @param $implementations
* @param $hook
*/
function system_module_implements_alter(&$implementations, $hook) {
if ($hook == 'cron') {
$implementations = [];
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
$url = parse_url($_SERVER["REQUEST_URI"]);
if (file_exists('.' . urldecode($url['path']))) {
// Serve the requested resource as-is.
return false;
}
// The built in webserver incorrectly sets $_SERVER['SCRIPT_NAME'] when URLs
// contain multiple dots (such as config entity IDs) in the path. Since this is
// a virtual resource, served by index.php set the script name explicitly.
// See https://github.com/drush-ops/drush/issues/2033 for more information.
// Work around the PHP bug. Update $_SERVER variables to point to the correct
// index-file.
$path = $url['path'];
$script = 'index.php';
if (str_contains($path, '.php')) {
// Work backwards through the path to check if a script exists. Otherwise
// fallback to index.php.
do {
$path = dirname($path);
if (preg_match('/\.php$/', $path) && is_file('.' . $path)) {
// Discovered that the path contains an existing PHP file. Use that as the
// script to include.
$script = ltrim($path, '/');
break;
}
} while ($path !== '/' && $path !== '.');
}
// Update $_SERVER variables to point to the correct index-file.
$index_file_absolute = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $script;
$index_file_relative = DIRECTORY_SEPARATOR . $script;
// SCRIPT_FILENAME will point to the router script itself, it should point to
// the full path of index.php.
$_SERVER['SCRIPT_FILENAME'] = $index_file_absolute;
// SCRIPT_NAME and PHP_SELF will either point to index.php or contain the full
// virtual path being requested depending on the URL being requested. They
// should always point to index.php relative to document root.
$_SERVER['SCRIPT_NAME'] = $index_file_relative;
$_SERVER['PHP_SELF'] = $index_file_relative;
// Require the script and let core take over.
require $_SERVER['SCRIPT_FILENAME'];
+50
View File
@@ -0,0 +1,50 @@
                             .,.                                         
                                  .cd:..                                           
                                      .xXd,,'..                                        
                                    .lXWx;;;,,..                                    
                                  .,dXWXo;;;;;,,..                             
                                 .;dKWWKx:;;;;;;;,,'..                                  
                             .;oOXNXKOo;;;;;;;;;;;;,,,'..                              
                     .:dOXWMMN0Okl;;;;;;;;;;;;;;;;,,,'..                       
                    .,lk0NMMMMMMNKOxc;;;;;;;;;;;;;;;;;;;;,,,'..                   
               .'cx0XWMMMMMMMWX0kd:;;;;;;;;;;;;;;;;;;;;;;;;;,,,..                
             .'cx0NMMMMMMMMMWX0Oxl;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'..              
         .;d0NMMMMMMMMMMWX0Oxl:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,...             
         .:kXWMMMMMMMMMWNK0kdl:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'..      
          .cONMMMMMMMMMWNX0Okoc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'.     
        .;kNMMMMMMMMWNX0Okdl:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'..      
      .oXMMMMMMWWXK0Oxdl:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'..      
    ,oKWWWWNXKK0kxoc:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'..      
   'lOO0000OOxdlc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'''.     
   .,lxkxxdolc:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,''''..  
   .,;;;::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'''''..  
  .,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'''''''.  
 .';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'''''''.. 
.',;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'''''''''..
.,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''..
',;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''''.
,,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''''''.
,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'''''''''''''''.
,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''''''''''
,;;;;;;;;;;;;;;;;;;;;;;;;;;;cldxkkOkkxxdlc;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''',''''''''
,;;;;;;;;;;;;;;;;;;;;;;;:ox0XWMMMMMMMMMWNX0kxdc;;;;;;;;;;;;;;;;,,,'''''''';cdk00Okl,''''
,;;;;;;;;;;;;;;;;;;;;;cxKWMMMMMMMMMMMMMMMMMMMWN0xl;;;;;;;;;;,,,'''''''';lkKWMMMMMMW0c'''
',;;;;;;;;;;;;;;;;;;:dKWMMMMMMMMMMMMMMMMMMMMMMMMMN0xl;;;;;,,'''''''';okXWMMMMMMMMMMM0:'.
.,;;;;;;;;;;;;;;;;;:kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0xl;''''''',:oOXWMMMMMMMMMMMMMMNd'.
.',;;;;;;;;;;;;;;;;xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0xolccoxONMMMMMMMMMMMMMMMMMMWd'.
 .,;;;;;;;;;;;;;;;oXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNWMMMMMMMMMMMMMMMMMMMMMMXl..
 .',;;;;;;;;;;;;;;xNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0OOOKNMMMMMMMMMMMMMMMMMMMM0;. 
  .',;;;;;;;;;;;;;dNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWN0xl:,''',cxXWMMMMMMMMMMMMMMMMWd.  
   .',;;;;;;;;;;;;lKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKko:,'''''''''':dKWMMMMMMMMMMMMMWk,   
   .',;;;;;;;;;;;;dXMMMMMMMMMMMMMMMMMMMMMMMMWX0xl;'''',;:::;,''''';oKWMMMMMMMMMMWO,    
   ..',,;;;;;;;;;;o0NMMMMMMMMMMMMMMMMMMN0xdo:,''',cdO0XXXXK0kl,'''';o0WMMMMMMMNd,     
    .''',,,,,,,,,,;lk0XWMMMMMMMMWNX0ko:,'''''';oONN0xdoodx0NNx,''''';lOXWWWXkc.      
      ..'''''''''''''',:lloodddoolc;'''''''''',xN0dc,'''''',oK0:''''''',:clc;..     
       ...''''''''''''''''''''''''''''''''''''':c,''''''''''';;''''''''''''..    
          ..''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''...     
            ...'''''''''''''''''''''',lxdc,'''''''''''''''''',:oxkl''''''..            
          ...''''''''''''''''''':kNMNK0OxdollcccclllodxO0XX0d;'''..               
         ..'''''''''''''''''',cxOKXXNWMMWWWWWWWWNXKOxo:'''..                  
                   ...'.'''''''''''''''',;:clooodddoollc:,'''...                   
                        ....'''''''''''''''''''''''''''.....                         
                         ....'..''''''''''''........                              
+50
View File
@@ -0,0 +1,50 @@
.,.
.cd:..
.xXd,,'..
.lXWx;;;,,..
.,dXWXo;;;;;,,..
.;dKWWKx:;;;;;;;,,'..
.;oOXNXKOo;;;;;;;;;;;;,,,'..
.:dOXWMMN0Okl;;;;;;;;;;;;;;;;,,,'..
.,lk0NMMMMMMNKOxc;;;;;;;;;;;;;;;;;;;;,,,'..
.'cx0XWMMMMMMMWX0kd:;;;;;;;;;;;;;;;;;;;;;;;;;,,,..
.'cx0NMMMMMMMMMWX0Oxl;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'..
.;d0NMMMMMMMMMMWX0Oxl:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,...
.:kXWMMMMMMMMMWNK0kdl:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'..
.cONMMMMMMMMMWNX0Okoc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'.
.;kNMMMMMMMMWNX0Okdl:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'..
.oXMMMMMMWWXK0Oxdl:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'..
,oKWWWWNXKK0kxoc:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'..
'lOO0000OOxdlc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'''.
.,lxkxxdolc:;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,''''..
.,;;;::;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'''''..
.,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,'''''''.
.';;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'''''''..
.',;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'''''''''..
.,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''..
',;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''''.
,,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''''''.
,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,'''''''''''''''.
,;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''''''''''
,;;;;;;;;;;;;;;;;;;;;;;;;;;;cldxkkOkkxxdlc;;;;;;;;;;;;;;;;;;;;;;;;,,''''''''''',''''''''
,;;;;;;;;;;;;;;;;;;;;;;;:ox0XWMMMMMMMMMWNX0kxdc;;;;;;;;;;;;;;;;,,,'''''''';cdk00Okl,''''
,;;;;;;;;;;;;;;;;;;;;;cxKWMMMMMMMMMMMMMMMMMMMWN0xl;;;;;;;;;;,,,'''''''';lkKWMMMMMMW0c'''
',;;;;;;;;;;;;;;;;;;:dKWMMMMMMMMMMMMMMMMMMMMMMMMMN0xl;;;;;,,'''''''';okXWMMMMMMMMMMM0:'.
.,;;;;;;;;;;;;;;;;;:kNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0xl;''''''',:oOXWMMMMMMMMMMMMMMNd'.
.',;;;;;;;;;;;;;;;;xWMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN0xolccoxONMMMMMMMMMMMMMMMMMMWd'.
.,;;;;;;;;;;;;;;;oXMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWNWMMMMMMMMMMMMMMMMMMMMMMXl..
.',;;;;;;;;;;;;;;xNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWX0OOOKNMMMMMMMMMMMMMMMMMMMM0;.
.',;;;;;;;;;;;;;dNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWN0xl:,''',cxXWMMMMMMMMMMMMMMMMWd.
.',;;;;;;;;;;;;lKMMMMMMMMMMMMMMMMMMMMMMMMMMMMMWKko:,'''''''''':dKWMMMMMMMMMMMMMWk,
.',;;;;;;;;;;;;dXMMMMMMMMMMMMMMMMMMMMMMMMWX0xl;'''',;:::;,''''';oKWMMMMMMMMMMWO,
..',,;;;;;;;;;;o0NMMMMMMMMMMMMMMMMMMN0xdo:,''',cdO0XXXXK0kl,'''';o0WMMMMMMMNd,
.''',,,,,,,,,,;lk0XWMMMMMMMMWNX0ko:,'''''';oONN0xdoodx0NNx,''''';lOXWWWXkc.
..'''''''''''''',:lloodddoolc;'''''''''',xN0dc,'''''',oK0:''''''',:clc;..
...''''''''''''''''''''''''''''''''''''':c,''''''''''';;''''''''''''..
..''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''...
...'''''''''''''''''''''',lxdc,'''''''''''''''''',:oxkl''''''..
...''''''''''''''''''':kNMNK0OxdollcccclllodxO0XX0d;'''..
..'''''''''''''''''',cxOKXXNWMMWWWWWWWWNXKOxo:'''..
...'.'''''''''''''''',;:clooodddoollc:,'''...
....'''''''''''''''''''''''''''.....
....'..''''''''''''........
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

+110
View File
@@ -0,0 +1,110 @@
# This file is augmented with more nav pages by drush mk:docs command.
site_name: Drush
site_author: 'Moshe Weitzman'
site_description: A command line shell and Unix scripting interface for Drupal
theme:
name: material
logo: drush_logo-black.png
favicon: img/favicon.ico
icon:
repo: fontawesome/brands/github
custom_dir: docs/overrides
palette:
scheme: preference
features:
- navigation.tabs
- navigation.tabs.sticky
- toc.integrate
- content.action.edit
- content.action.view
site_url: https://www.drush.org/latest/
repo_url: https://github.com/drush-ops/drush
#Overridden on many pages via edit_uri plugin. See front matter.
edit_uri: blob/12.x/docs
extra_css:
- css/extra.drush.css
plugins:
- edit_url
- search
- mike:
canonical_version: latest
alias_type: redirect
- git-revision-date-localized:
exclude:
- commands/*
- generators/*
- git-authors:
exclude:
- commands/*
- generators/*
extra:
version:
provider: mike
social:
- icon: fontawesome/brands/twitter
link: https://twitter.com/drushcli
- icon: fontawesome/brands/github
link: https://github.com/drush-ops/drush
- icon: fontawesome/brands/slack
link: https://drupal.slack.com/archives/C62H9CWQM
# Concerned about surveillance and spam so not enabling disqus for now.
# disqus: drush
markdown_extensions:
- toc:
permalink: true
- admonition: { }
- meta: { }
- pymdownx.magiclink: { }
- pymdownx.keys: { }
- pymdownx.snippets: { }
- pymdownx.highlight:
use_pygments: true
# https://github.com/squidfunk/mkdocs-material/issues/506#issuecomment-338007823
extend_pygments_lang:
- name: php
lang: php
options:
startinline: true
- pymdownx.inlinehilite: { }
- pymdownx.superfences: { }
- pymdownx.tabbed:
alternate_style: true
- pymdownx.emoji:
emoji_index: '!!python/name:materialx.emoji.twemoji'
emoji_generator: '!!python/name:materialx.emoji.to_svg'
nav:
- Home: index.md
- Use:
- Install: install.md
- Usage: usage.md
- Cron: cron.md
- Drush configuration: using-drush-configuration.md
- Drupal configuration: config-exporting.md
- Site aliases: site-aliases.md
- Output Formats, Fields & Filters: output-formats-filters.md
- Migrate: migrate.md
- REPL (a custom shell for Drupal): repl.md
- Deploy: deploycommand.md
- Author:
- Command Authoring: commands.md
- Hooks: hooks.md
- Dependency injection: dependency-injection.md
- Input / Output: io.md
- Generator Authoring: generators.md
- Bootstrap: bootstrap.md
- Site Alias Manager: site-alias-manager.md
- Examples:
- drush.yml: examples/example.drush.yml.md
- site.yml: examples/example.site.yml.md
- examples/helloworld.script.md
- Example drush extension: https://github.com/drush-ops/example-drush-extension
- examples/ArtCommands.php.md
- examples/PolicyCommands.php.md
- examples/SiteAliasAlterCommands.php.md
- examples/SyncViaHttpCommands.php.md
- examples/XkcdCommands.php.md
- prompt.sh: examples/example.prompt.sh.md
- git-bisect.sh: examples/git-bisect.example.sh.md
- Contribute:
- Guidelines: contribute/CONTRIBUTING.md
- Unish: contribute/unish.md
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<ruleset name="drush">
<description>Default PHP CodeSniffer configuration for Drush project.</description>
<file>src</file>
<file>examples</file>
<file>tests</file>
<rule ref="PSR12"/>
<!-- Keep us sane-->
<rule ref="Generic.ControlStructures.InlineControlStructure.NotAllowed"><severity>0</severity></rule>
<rule ref="PSR2.Methods.MethodDeclaration.Underscore"><severity>0</severity></rule>
<rule ref="PSR12.Files.FileHeader.IncorrectOrder"><severity>0</severity></rule>
<arg name="warning-severity" value="0"/>
<arg value="s" />
</ruleset>
+41
View File
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
use Rector\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector;
use Rector\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeysRector;
use Rector\CodeQuality\Rector\Identical\StrlenZeroToIdenticalEmptyStringRector;
use Rector\CodeQuality\Rector\If_\CombineIfRector;
use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector;
use Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector;
use Rector\CodeQuality\Rector\Isset_\IssetOnPropertyObjectToPropertyExistsRector;
use Rector\Config\RectorConfig;
use Rector\Php81\Rector\ClassConst\FinalizePublicClassConstantRector;
use Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector;
use Rector\Set\ValueObject\SetList;
return static function (RectorConfig $config): void {
$config->importNames();
$config->disableImportShortClasses();
$config->paths([
__DIR__ . '/src',
]);
$config->sets([
SetList::CODE_QUALITY,
SetList::PHP_81,
]);
$config->skip([
StrlenZeroToIdenticalEmptyStringRector::class,
ExplicitBoolCompareRector::class,
IssetOnPropertyObjectToPropertyExistsRector::class,
CallableThisArrayToAnonymousFunctionRector::class,
CombineIfRector::class,
UnusedForeachValueToArrayKeysRector::class,
SimplifyIfElseToTernaryRector::class,
FinalizePublicClassConstantRector::class,
NullToStrictStringFuncCallArgRector::class,
]);
};
@@ -0,0 +1,72 @@
<?php
namespace Drush\Style;
use Drush\Drush;
use Drush\Exceptions\UserAbortException;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Console\Style\SymfonyStyle;
class DrushStyle extends SymfonyStyle
{
public function confirm(string $question, bool $default = true): bool
{
// Automatically accept confirmations if the --yes argument was supplied.
if (Drush::affirmative()) {
$this->comment($question . ': yes.');
return true;
} elseif (Drush::negative()) {
// Automatically cancel confirmations if the --no argument was supplied.
$this->warning($question . ': no.');
return false;
}
return parent::confirm($question, $default);
}
public function choice(string $question, array $choices, mixed $default = null, bool $multiSelect = false): mixed
{
// Display the choices without their keys.
$choices_values = array_values($choices);
$return = parent::choice($question, $choices_values, $default, $multiSelect);
if ($multiSelect) {
return array_map(function ($value) use ($choices) {
return array_search($value, $choices);
}, $return);
}
return array_search($return, $choices);
}
public function warning(string|array $message)
{
$this->block($message, 'WARNING', 'fg=black;bg=yellow', ' ! ', true);
}
public function note(string|array $message)
{
$this->block($message, 'NOTE', 'fg=black;bg=yellow', ' ! ');
}
public function caution(string|array $message)
{
$this->block($message, 'CAUTION', 'fg=black;bg=yellow', ' ! ', true);
}
/**
* @return mixed
*/
public function askRequired($question)
{
$question = new Question($question);
$question->setValidator(function (?string $value) {
// FALSE is not considered as empty value because question helper use
// it as negative answer on confirmation questions.
if ($value === null || $value === '') {
throw new \UnexpectedValueException('This value is required.');
}
return $value;
});
return $this->askQuestion($question);
}
}
@@ -0,0 +1,51 @@
<?php
namespace Drush\Symfony;
use Symfony\Component\Console\Formatter\OutputFormatterInterface;
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
use Symfony\Component\Console\Output\ConsoleSectionOutput;
use Symfony\Component\Console\Output\OutputInterface;
/**
* BufferedConsoleOutput supports separation of the stdout and stderr streams.
*/
class BufferedConsoleOutput extends BufferedOutput implements ConsoleOutputInterface
{
protected $stderr;
private array $consoleSectionOutputs = [];
/**
* @param int $verbosity The verbosity level (one of the VERBOSITY constants in OutputInterface)
* @param bool|null $decorated Whether to decorate messages (null for auto-guessing)
* @param OutputFormatterInterface|null $formatter Output formatter instance (null to use default OutputFormatter)
*/
public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = false, OutputFormatterInterface $formatter = null)
{
parent::__construct($verbosity, $decorated, $formatter);
$this->stderr = new BufferedOutput($this->getVerbosity(), $this->isDecorated(), $this->getFormatter());
}
/**
* {@inheritdoc}
*/
public function getErrorOutput(): OutputInterface
{
return $this->stderr;
}
/**
* {@inheritdoc}
*/
public function setErrorOutput(OutputInterface $error): void
{
$this->stderr = $error;
}
public function section(): ConsoleSectionOutput
{
// @todo
}
}
@@ -0,0 +1,47 @@
<?php
namespace Drush\Symfony;
use Symfony\Component\Console\Input\InputDefinition;
use Symfony\Component\Console\Input\InputOption;
/**
* This is an InputDefinition that allows any option to be considered valid.
* Used when passing a command through to another dispatcher that will do
* the option validation.
*
* We use this instead of a LessStrictArgvInput in cases where we do not
* know in advance whether the input should be handled indiscriminately.
* In other words, an IndiscriminateInputDefinition is attached to individual
* Commands that should accept any option, whereas a LessStrictArgvInput
* should be used to make all command skip option validation.
*/
class IndiscriminateInputDefinition extends InputDefinition
{
/**
* @inheritdoc
*/
public function hasShortcut(string $name): bool
{
return true;
}
/**
* @inheritdoc
*/
public function hasOption(string $name): bool
{
return true;
}
/**
* @inheritdoc
*/
public function getOption(string $name): InputOption
{
if (parent::hasOption($name)) {
return parent::getOption($name);
}
return new InputOption($name, null, InputOption::VALUE_OPTIONAL, '', []);
}
}
@@ -0,0 +1,353 @@
<?php
namespace Drush\Symfony;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Exception\RuntimeException;
/**
* UnvalidatedArgvInput is an ArgvInput that never reports errors when
* extra options are provided.
*
* If the last argument of the command being called is not an array
* argument, then an error will be thrown if there are too many arguments.
*
* We use this instead of a IndiscriminateInputDefinition in cases where we
* know in advance that we wish to disable input validation for all commands.
* In contrast, an IndiscriminateInputDefinition is attached to individual
* Commands that should accept any option.
*/
class LessStrictArgvInput extends ArgvInput
{
private $tokens;
private $parsed;
protected $additionalOptions = [];
/**
* Constructor.
*
* @param array|null $argv An array of parameters from the CLI (in the argv format)
* @param InputDefinition|null $definition A InputDefinition instance
*/
public function __construct(array $argv = null, InputDefinition $definition = null)
{
// We have to duplicate the implementation of ArgvInput
// because of liberal use of `private`
if (null === $argv) {
$argv = $_SERVER['argv'];
}
$this->tokens = $argv;
// strip the application name
array_shift($this->tokens);
parent::__construct($argv, $definition);
}
/**
* {@inheritdoc}
*/
public function getOption(string $name): mixed
{
if (array_key_exists($name, $this->options)) {
return $this->options[$name];
}
if ($this->definition->hasOption($name)) {
return $this->definition->getOption($name)->getDefault();
}
return false;
}
protected function setTokens(array $tokens)
{
$this->tokens = $tokens;
}
/**
* {@inheritdoc}
*/
protected function parse()
{
$parseOptions = true;
$this->parsed = $this->tokens;
while (null !== $token = array_shift($this->parsed)) {
if ($parseOptions && '' == $token) {
$this->parseArgument($token);
} elseif ($parseOptions && '--' == $token) {
$parseOptions = false;
} elseif ($parseOptions && 0 === strpos($token, '--')) {
$this->parseLongOption($token);
} elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
$this->parseShortOption($token);
} else {
$this->parseArgument($token);
}
}
// Put back any options that were injected.
$this->options += $this->additionalOptions;
}
/**
* Parses a short option.
*
* @param string $token The current token
*/
private function parseShortOption($token)
{
$name = substr($token, 1);
if (strlen($name) > 1) {
if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
// an option with a value (with no space)
$this->addShortOption($name[0], substr($name, 1));
} else {
$this->parseShortOptionSet($name);
}
} else {
$this->addShortOption($name, null);
}
}
/**
* Parses a short option set.
*
* @param string $name The current token
*/
private function parseShortOptionSet(string $name)
{
$len = strlen($name);
for ($i = 0; $i < $len; ++$i) {
if (!$this->definition->hasShortcut($name[$i])) {
$this->addShortOption($name[$i]);
}
$option = $this->definition->getOptionForShortcut($name[$i]);
if ($option->acceptValue()) {
$this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
break;
} else {
$this->addLongOption($option->getName(), null);
}
}
}
/**
* Parses a long option.
*
* @param string $token The current token
*/
private function parseLongOption(string $token)
{
$name = substr($token, 2);
if (false !== $pos = strpos($name, '=')) {
if (0 === strlen($value = substr($name, $pos + 1))) {
// if no value after "=" then substr() returns "" since php7 only, false before
// see http://php.net/manual/fr/migration70.incompatible.php#119151
if (\PHP_VERSION_ID < 70000 && false === $value) {
$value = '';
}
array_unshift($this->parsed, $value);
}
$this->addLongOption(substr($name, 0, $pos), $value);
} else {
$this->addLongOption($name, null);
}
}
/**
* Parses an argument.
*
* @param string $token The current token
*
* @throws RuntimeException When too many arguments are given
*/
private function parseArgument(string $token)
{
$c = count($this->arguments);
// if input is expecting another argument, add it
if ($this->definition->hasArgument($c)) {
$arg = $this->definition->getArgument($c);
$this->arguments[$arg->getName()] = $arg->isArray() ? [$token] : $token;
// if last argument isArray(), append token to last argument
} elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
$arg = $this->definition->getArgument($c - 1);
$this->arguments[$arg->getName()][] = $token;
// unexpected argument
} else {
$all = $this->definition->getArguments();
if (count($all)) {
throw new RuntimeException(sprintf('Too many arguments, expected arguments "%s", provided arguments "%s".', implode('" "', array_keys($all)), implode('" "', array_keys($this->arguments))));
}
throw new RuntimeException(sprintf('No arguments expected, got "%s".', $token));
}
}
/**
* Adds a short option value.
*
* @param string $shortcut The short option key
* @param mixed $value The value for the option
*
* @throws RuntimeException When option given doesn't exist
*/
private function addShortOption(string $shortcut, mixed $value)
{
if (!$this->definition->hasShortcut($shortcut)) {
// Hard to know what to do with unknown short options. Maybe
// these should be added to the end of the arguments. This would only
// be a good strategy if the last argument was an array argument.
// We'll try adding as a long option for now.
$this->addLongOption($shortcut, $value);
}
$this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
}
public function injectAdditionalOptions($additionalOptions)
{
$this->additionalOptions += $additionalOptions;
$this->options += $additionalOptions;
}
/**
* Adds a long option value.
*
* @param string $name The long option key
* @param mixed $value The value for the option
*
* @throws RuntimeException When option given doesn't exist
*/
private function addLongOption(string $name, mixed $value)
{
if (!$this->definition->hasOption($name)) {
// If we don't know anything about this option, then we'll
// assume it is generic.
$this->options[$name] = $value;
return;
}
$option = $this->definition->getOption($name);
if (null !== $value && !$option->acceptValue()) {
throw new RuntimeException(sprintf('The "--%s" option does not accept a value.', $name));
}
if (in_array($value, ['', null], true) && $option->acceptValue() && count($this->parsed)) {
// if option accepts an optional or mandatory argument
// let's see if there is one provided
$next = array_shift($this->parsed);
if ((isset($next[0]) && '-' !== $next[0]) || in_array($next, ['', null], true)) {
$value = $next;
} else {
array_unshift($this->parsed, $next);
}
}
if (null === $value) {
if ($option->isValueRequired()) {
throw new RuntimeException(sprintf('The "--%s" option requires a value.', $name));
}
if (!$option->isArray() && !$option->isValueOptional()) {
$value = true;
}
}
if ($option->isArray()) {
$this->options[$name][] = $value;
} else {
$this->options[$name] = $value;
}
}
/**
* {@inheritdoc}
*/
public function getFirstArgument(): ?string
{
foreach ($this->tokens as $token) {
if ($token && '-' === $token[0]) {
continue;
}
return $token;
}
}
/**
* {@inheritdoc}
*/
public function hasParameterOption(string|array $values, bool $onlyParams = false): bool
{
$values = (array) $values;
foreach ($this->tokens as $token) {
if ($onlyParams && $token === '--') {
return false;
}
foreach ($values as $value) {
if ($token === $value || 0 === strpos($token, $value . '=')) {
return true;
}
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function getParameterOption(string|array $values, string|bool|int|float|array|null $default = false, bool $onlyParams = false): mixed
{
$values = (array) $values;
$tokens = $this->tokens;
while (0 < count($tokens)) {
$token = array_shift($tokens);
if ($onlyParams && $token === '--') {
return false;
}
foreach ($values as $value) {
if ($token === $value || 0 === strpos($token, $value . '=')) {
if (false !== $pos = strpos($token, '=')) {
return substr($token, $pos + 1);
}
return array_shift($tokens);
}
}
}
return $default;
}
/**
* Returns a stringified representation of the args passed to the command.
*
* @return string
*/
public function __toString()
{
$tokens = array_map(function ($token) {
if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
return $match[1] . $this->escapeToken($match[2]);
}
if ($token && $token[0] !== '-') {
return $this->escapeToken($token);
}
return $token;
}, $this->tokens);
return implode(' ', $tokens);
}
}
+13
View File
@@ -0,0 +1,13 @@
# This file is for unifying the coding style for different editors and IDEs
# editorconfig.org
# PHP PSR-12 Coding Standards
# http://www.php-fig.org/psr/psr-12/
[*.php]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
+357
View File
@@ -0,0 +1,357 @@
<?php
declare(strict_types=1);
namespace Drush;
use Composer\Autoload\ClassLoader;
use Consolidation\AnnotatedCommand\AnnotatedCommand;
use Consolidation\SiteAlias\SiteAliasManager;
use Drush\Boot\BootstrapManager;
use Drush\Boot\DrupalBootLevels;
use Drush\Command\RemoteCommandProxy;
use Drush\Config\ConfigAwareTrait;
use Drush\Runtime\RedispatchHook;
use Drush\Runtime\TildeExpansionHook;
use Drush\Runtime\ServiceManager;
use Psr\Log\LoggerAwareInterface;
use Psr\Log\LoggerAwareTrait;
use Robo\Contract\ConfigAwareInterface;
use Robo\Robo;
use Symfony\Component\Console\Application as SymfonyApplication;
use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Our application object
*
* Note: Implementing *AwareInterface here does NOT automatically cause
* that corresponding service to be injected into the Application. This
* is because the application object is created prior to the DI container.
* See DependencyInjection::injectApplicationServices() to add more services.
*/
class Application extends SymfonyApplication implements LoggerAwareInterface, ConfigAwareInterface
{
use LoggerAwareTrait;
use ConfigAwareTrait;
/** @var BootstrapManager */
protected $bootstrapManager;
/** @var SiteAliasManager */
protected $aliasManager;
/** @var RedispatchHook */
protected $redispatchHook;
/** @var TildeExpansionHook */
protected $tildeExpansionHook;
/** @var ServiceManager */
protected $serviceManager;
/**
* Add global options to the Application and their default values to Config.
*/
public function configureGlobalOptions()
{
// Symfony 6.1+ has a --debug option for its completion command.
if ($this->getDefinition()->hasOption('--debug')) {
$this->getDefinition()
->addOption(
new InputOption('--debug', 'd', InputOption::VALUE_NONE, 'Equivalent to -vv')
);
}
$this->getDefinition()
->addOption(
new InputOption('--yes', 'y', InputOption::VALUE_NONE, 'Auto-accept the default for all user prompts. Equivalent to --no-interaction.')
);
// Note that -n belongs to Symfony Console's --no-interaction.
$this->getDefinition()
->addOption(
new InputOption('--no', null, InputOption::VALUE_NONE, 'Cancels at any confirmation prompt.')
);
$this->getDefinition()
->addOption(
new InputOption('--root', '-r', InputOption::VALUE_REQUIRED, 'The Drupal root for this site.')
);
$this->getDefinition()
->addOption(
new InputOption('--uri', '-l', InputOption::VALUE_REQUIRED, 'A base URL for building links and selecting a multi-site. Defaults to <info>https://default</info>.')
);
$this->getDefinition()
->addOption(
new InputOption('--simulate', null, InputOption::VALUE_NONE, 'Run in simulated mode (show what would have happened).')
);
$this->getDefinition()
->addOption(
new InputOption('--define', '-D', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Define a configuration item value.', [])
);
}
public function bootstrapManager()
{
return $this->bootstrapManager;
}
public function setBootstrapManager(BootstrapManager $bootstrapManager)
{
$this->bootstrapManager = $bootstrapManager;
}
public function aliasManager()
{
return $this->aliasManager;
}
public function setAliasManager($aliasManager)
{
$this->aliasManager = $aliasManager;
}
public function setRedispatchHook(RedispatchHook $redispatchHook)
{
$this->redispatchHook = $redispatchHook;
}
public function setTildeExpansionHook(TildeExpansionHook $tildeExpansionHook)
{
$this->tildeExpansionHook = $tildeExpansionHook;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
}
/**
* Return the framework uri selected by the user.
*/
public function getUri()
{
if (!$this->bootstrapManager) {
return 'default';
}
return $this->bootstrapManager->getUri();
}
/**
* If the user did not explicitly select a site URI,
* then pick an appropriate site from the cwd.
*/
public function refineUriSelection($cwd)
{
if (!$this->bootstrapManager || !$this->aliasManager) {
return;
}
$selfSiteAlias = $this->aliasManager->getSelf();
if (!$selfSiteAlias->hasRoot() && !$this->bootstrapManager()->drupalFinder()->getDrupalRoot()) {
return;
}
$uri = $selfSiteAlias->uri();
if (empty($uri)) {
$uri = $this->selectUri($cwd);
$selfSiteAlias->setUri($uri);
$this->aliasManager->setSelf($selfSiteAlias);
}
// Update the uri in the bootstrap manager
$this->bootstrapManager->setUri($uri);
}
/**
* Select a URI to use for the site, based on directory or config.
*/
public function selectUri($cwd)
{
$uri = $this->config->get('options.uri');
if ($uri) {
return $uri;
}
return $this->bootstrapManager()->selectUri($cwd);
}
/**
* @inheritdoc
*/
public function find($name)
{
if (empty($name)) {
return;
}
$command = $this->bootstrapAndFind($name);
// Avoid exception when help is being built by https://github.com/bamarni/symfony-console-autocomplete.
// @todo Find a cleaner solution.
$argv = Drush::config()->get('runtime.argv');
if (count($argv) > 1 && $argv[1] !== 'help') {
$this->checkObsolete($command);
}
return $command;
}
/**
* Look up a command. Bootstrap further if necessary.
*/
protected function bootstrapAndFind($name)
{
try {
return parent::find($name);
} catch (CommandNotFoundException $e) {
// Is the unknown command destined for a remote site?
if ($this->aliasManager) {
$selfAlias = $this->aliasManager->getSelf();
if (!$selfAlias->isLocal()) {
$command = new RemoteCommandProxy($name, $this->redispatchHook);
$command->setApplication($this);
return $command;
}
}
// If we have no bootstrap manager, then just re-throw
// the exception.
if (!$this->bootstrapManager) {
throw $e;
}
$this->logger->debug('Bootstrap further to find {command}', ['command' => $name]);
$this->bootstrapManager->bootstrapMax();
$this->logger->debug('Done with bootstrap max in Application::bootstrapAndFind(): trying to find {command} again.', ['command' => $name]);
if (!$this->bootstrapManager()->hasBootstrapped(DrupalBootLevels::ROOT)) {
// Unable to progress in the bootstrap. Give friendly error message.
throw new CommandNotFoundException(dt('Command !command was not found. Pass --root or a @siteAlias in order to run Drupal-specific commands.', ['!command' => $name]));
}
// Try to find it again, now that we bootstrapped as far as possible.
try {
return parent::find($name);
} catch (CommandNotFoundException $e) {
if (!$this->bootstrapManager()->hasBootstrapped(DrupalBootLevels::DATABASE)) {
// Unable to bootstrap to DB. Give targetted error message.
throw new CommandNotFoundException(dt('Command !command was not found. Drush was unable to query the database. As a result, many commands are unavailable. Re-run your command with --debug to see relevant log messages.', ['!command' => $name]));
}
if (!$this->bootstrapManager()->hasBootstrapped(DrupalBootLevels::FULL)) {
// Unable to fully bootstrap. Give targetted error message.
throw new CommandNotFoundException(dt('Command !command was not found. Drush successfully connected to the database but was unable to fully bootstrap your site. As a result, many commands are unavailable. Re-run your command with --debug to see relevant log messages.', ['!command' => $name]));
} else {
// We fully bootstrapped but still could not find command. Rethrow.
throw $e;
}
}
}
}
/**
* If a command is annotated @obsolete, then we will throw an exception
* immediately; the command will not run, and no hooks will be called.
*/
protected function checkObsolete($command)
{
if (!$command instanceof AnnotatedCommand) {
return;
}
$annotationData = $command->getAnnotationData();
if (!$annotationData->has('obsolete')) {
return;
}
$obsoleteMessage = $command->getDescription();
throw new \Exception($obsoleteMessage);
}
/**
* @inheritdoc
*
* Note: This method is called twice, as we wish to configure the IO
* objects earlier than Symfony does. We could define a boolean class
* field to record when this method is called, and do nothing on the
* second call. At the moment, the work done here is trivial, so we let
* it happen twice.
*/
protected function configureIO(InputInterface $input, OutputInterface $output)
{
// Do default Symfony confguration.
parent::configureIO($input, $output);
// Process legacy Drush global options.
// Note that `getParameterOption` returns the VALUE of the option if
// it is found, or NULL if it finds an option with no value.
if ($input->getParameterOption(['--yes', '-y', '--no', '-n'], false, true) !== false) {
$input->setInteractive(false);
}
// Symfony will set these later, but we want it set upfront
if ($input->getParameterOption(['--verbose', '-v'], false, true) !== false) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
}
// We are not using "very verbose", but set this for completeness
if ($input->getParameterOption(['-vv'], false, true) !== false) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
}
// Use -vvv of --debug for even more verbose logging.
if ($input->getParameterOption(['--debug', '-d', '-vvv'], false, true) !== false) {
$output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
}
}
/**
* Configure the application object and register all of the commandfiles
* available in the search paths provided via Preflight
*/
public function configureAndRegisterCommands(InputInterface $input, OutputInterface $output, $commandfileSearchpath, ClassLoader $classLoader)
{
// Symfony will call this method for us in run() (it will be
// called again), but we want to call it up-front, here, so that
// our $input and $output objects have been appropriately
// configured in case we wish to use them (e.g. for logging) in
// any of the configuration steps we do here.
$this->configureIO($input, $output);
// Directly add the yaml-cli commands.
$this->addCommands($this->serviceManager->instantiateYamlCliCommands());
// Find the command handlers that we can instantiate without bootstrapping Drupal
$commandClasses = $this->serviceManager->discover($commandfileSearchpath, '\Drush');
// Uncomment the lines below to use Console's built in help and list commands.
// unset($commandClasses[__DIR__ . '/Commands/help/HelpCommands.php']);
// unset($commandClasses[__DIR__ . '/Commands/help/ListCommands.php']);
// Instantiate our command handler objects with the service manager
// (handles 'createEarly' static factories)
$commandInstances = $this->serviceManager->instantiateServices($commandClasses, Drush::getContainer());
// Register our commands with Robo, our application framework.
// Note that Robo::register can accept either Annotated Command
// command handlers or Symfony Console Command objects.
Robo::register($this, $commandInstances);
}
/**
* Renders a caught exception. Omits the command docs at end.
*/
public function renderException(\Exception $e, OutputInterface $output)
{
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
$this->doRenderException($e, $output);
}
/**
* Renders a caught Throwable. Omits the command docs at end.
*/
public function renderThrowable(\Throwable $e, OutputInterface $output): void
{
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
$this->doRenderThrowable($e, $output);
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Drush\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class Argument extends \Consolidation\AnnotatedCommand\Attributes\Argument
{
}
+32
View File
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Drush\Attributes;
use Attribute;
use Consolidation\AnnotatedCommand\Parser\CommandInfo;
use Drush\Boot\DrupalBootLevels;
use JetBrains\PhpStorm\ExpectedValues;
#[Attribute(Attribute::TARGET_METHOD | Attribute::TARGET_CLASS)]
class Bootstrap
{
/**
* @param $level
* The level to bootstrap to.
* @package $extra
* A maximum level when used with MAX.
*/
public function __construct(
#[ExpectedValues(valuesFromClass: DrupalBootLevels::class)] public int $level,
public ?int $max_level = null,
) {
}
public static function handle(\ReflectionAttribute $attribute, CommandInfo $commandInfo)
{
$instance = $attribute->newInstance();
$commandInfo->addAnnotation('bootstrap', $instance->level . ( isset($instance->max_level) ? " $instance->max_level" : ''));
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Drush\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD)]
class Command extends \Consolidation\AnnotatedCommand\Attributes\Command
{
}
+12
View File
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Drush\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD)]
class Complete extends \Consolidation\AnnotatedCommand\Attributes\Complete
{
}
+12
View File
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Drush\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD)]
class DefaultFields extends \Consolidation\AnnotatedCommand\Attributes\DefaultFields
{
}
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Drush\Attributes;
use Attribute;
#[Attribute(Attribute::TARGET_METHOD)]
class DefaultTableFields extends \Consolidation\AnnotatedCommand\Attributes\DefaultTableFields
{
}
Loaded 100 of 31193 files, more files were not shown because too many files have changed in this diff. Show more