├── assets └── wp.gif ├── 4-practical-uses-for-custom-commands.md ├── README.md ├── 5-more-resources.md ├── 2-using-wp-cli-internal-api.md ├── 3-best-practices-designing-a-cli.md ├── 00-intro-to-command-line.md ├── 0-intro-to-wp-cli.md ├── 1-intro-to-custom-commands.md └── LICENSE /assets/wp.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/0aveRyan/learn-wp-cli/HEAD/assets/wp.gif -------------------------------------------------------------------------------- /4-practical-uses-for-custom-commands.md: -------------------------------------------------------------------------------- 1 | # Practical Uses for Custom Commands 2 | 3 | ## Installing WordPress 4 | 5 | ## Running Updates 6 | 7 | ## Common Repetitive Tasks 8 | 9 | ## Setting/Resetting Application State 10 | 11 | ## Time-Based Operations 12 | 13 | ## Batch Install 14 | 15 | ## Integrating 3rd Party HTTP APIs & 3rd Party Applications 16 | 17 | ## Custom Import & Export Commands 18 | 19 | ## Provide Catalyst to Developers 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Learn WP-CLI 2 | 3 | ## INTROS 4 | * [Intro to Command Line](00-intro-to-command-line.md) 5 | * [Intro to WP-CLI](0-intro-to-wp-cli.md) 6 | * **[Intro to Custom WP-CLI Commands](1-intro-to-custom-commands.md)** 7 | 8 | ## Building Custom WP-CLI Commands 9 | 10 | * [Using WP-CLI Internal API & Helpers](2-using-wp-cli-internal-api.md) 11 | * [Best Practices: Designing A CLI](3-best-practices-designing-a-cli.md) 12 | * [Practical Uses for Custom Commands](4-practical-uses-for-custom-commands.md) 13 | 14 | ### [Resources](5-more-resources.md) 15 | -------------------------------------------------------------------------------- /5-more-resources.md: -------------------------------------------------------------------------------- 1 | # My Resources 2 | 3 | **[0aveRyan/wp-lando](https://github.com/0aveRyan/wp-lando)** 4 | `wp lando` command for quickly installing and pre-configuring WordPress on Lando. 5 | 6 | # More Resources 7 | 8 | ### [wp-forge scaffolding tools](https://github.com/wp-forge/wp-scaffolding-tool) 9 | 10 | Building a scaffold with a customized/opinionated boilerplate has long been arduous and manual. While the Core scaffold commands are a great starting place, this tool built by @wpscholar is much more robust and can handle more dynamic things like running shell commands, adding Composer and npm packages, with a much more robust foundation and rich customization support. 11 | 12 | ### [CLImate](https://climate.thephpleague.com/) - Advanced Formatting, Interactivity and Animation 13 | 14 | WP-CLI comes with particularly useful helper functions and utilities, but I find I often need an abstract class with my own helpers for formatting and interactivity that my custom command classes extend. 15 | 16 | Enter [CLImate](https://climate.thephpleague.com/), a terrific PHP package from The League of Extraordinary Packages. CLImate does overlap some functionality provided in WP-CLI helpers and utilties, but it can be used in-lieu or alongside without issue. It also brings more advanced formatting, animation and interactive tools like CLI checkboxes and multiselects that are common in JavaScript-based CLIs. 17 | 18 | ### [An Introduction to WP-CLI](https://pascalbirchler.com/an-introduction-to-wp-cli/) 19 | 20 | Helpful guide recently published from Pascal Bircher. 21 | 22 | ### [John Blackbourn: WP-CLI: An Intro & Interesting Use-Cases](https://wordpress.tv/2019/04/14/john-blackbourn-wp-cli-an-intro-and-interesting-use-cases/) 23 | 24 | Helpful WP-CLI presentation at WordCamp Rome 2018 from WordPress Contributor John Blackbourn. 25 | 26 | ### [Alain Schlesser: Controlling WordPress Through The Command Line – Introduction to WP-CLI](https://wordpress.tv/2017/05/22/alain-schlesser-controlling-wordpress-through-the-command-line-introduction-to-wp-cli/) 27 | 28 | WP-CLI intro and valuable info from WP-CLI Contributor Alain Schlesser. 29 | 30 | ### [Chris Klosowski: Building WP-CLI Progress Bars](https://chrisk.io/adding-progress-bars-wp-cli-processes/) 31 | -------------------------------------------------------------------------------- /2-using-wp-cli-internal-api.md: -------------------------------------------------------------------------------- 1 | # Using WP-CLI's Internal API & Utility Functions 2 | 3 | ## Introduction 4 | 5 | WP-CLI isn't just a robust tool, it has robust and reusable internal utilities that greatly expedite building WP-CLI commands just as powerful as the Core commands. 6 | 7 | The official documentation is fantastic and extensive, but if it has one shortcoming it's that it's organized alphabetically instead of assigning a hiearchy of importance or grouping like items. 8 | 9 | This chapter aims to surface some of the most commonly-used functions and utilities. 10 | 11 | ## Key API Functions 12 | 13 | ### `WP_CLI::log()` and `WP_CLI::line()` 14 | 15 | Just as `echo` is used to output strings to an HTML document, it can be used to output strings in a CLI application. Both these methods can be used to output strings to a new line. 16 | 17 | In general, `WP_CLI::log()` is preferred to `WP_CLI::line()` for a few reasons. 18 | 19 | While _very_ similar methods, `WP_CLI::log()` is more resilient and will respect the `--quiet` flag. 20 | 21 | `WP_CLI::log()` also allows users to swap the default logger with a custom one, so try to use it over `WP_CLI::line()` or a simple `echo`. 22 | 23 | ### `WP_CLI::success()`, `WP_CLI::warning()` and `WP_CLI::error()` 24 | 25 | These methods are very straightforward -- they're mostly just `WP_CLI::log()` but with colored prefixes like `Success: $msg` in green, `Warning: $msg` in orange and `Error: $msg` in red. 26 | 27 | Both success and warning messages are sent to `STDOUT`, so subsequent code in your callback will be executed. However, error messages are sent to `STDERR` and it **will also stop the command from running.** 28 | 29 | Another consideration is you'll commonly use `WP_CLI::error()` during validation of arguments. If a user didn't include a required parameter, or included an invalid value, don't just say `You forgot X, stopping everything.`! Instead, help guide the user with `X parameter is required. Try "wp cmd X" with "Y" or "Z."` 30 | 31 | ### `WP_CLI::confirm()` 32 | 33 | The confirm method is also similar to `WP_CLI::log()` in that you pass a message string (a yes/no question) and it stops the callback from continuing until a user types `y`/`yes` or `n`/`no`. 34 | 35 | ##### Ex. This callback... 36 | ```php 37 | function my_command( $args, $assoc_args ) { 38 | WP_CLI::confirm( 'Are you ready to continue?' ); 39 | WP_CLI::success( 'Did it!' ); 40 | } 41 | ``` 42 | 43 | ##### Will show... 44 | ```bash 45 | $ wp my_command 46 | Are you ready to continue? [y/n]: y 47 | Success: Did it! 48 | ``` 49 | If you type `y` above, you'll see `Success: Did it!`, otherwise you'll break out of the callback and see nothing further after the question. 50 | 51 | ### `WP_CLI::colorize()` 52 | 53 | Pops of color can add clarity, branding and flair to a command. This method uses PHP CLI Tool's color tokens to style a string. 54 | 55 | When styling a string, you need a beginning token and "reset" token to return to standard output. Tokens can be used to set both a background color and a text color. A full reference of these tokens is available here. 56 | 57 | ##### Important Note 58 | Whenever you're using colors, remember that Users can customize their Terminal themes and may have a black, white or color background. If you're not careful, your text may be illegible or invisible. Because of this, I recommend using color sparingly and on non-critical text (i.e. branding of your company/product name). If you want to add color for a command you're distributing with a product or other developers will use, I recommend testing with a few Terminal themes ranging from light to dark backgrounds -- just as you'd test browsers for HTML. 59 | 60 | ### `WP_CLI::debug()` 61 | 62 | One great way to find a balance between highly verbose output and streamlined output is stuffing data into `WP_CLI::debug()`. 63 | 64 | `WP_CLI::debug()` is only shown when the `--debug` flag is used, and will write to `STDERR`. 65 | 66 | One other benefit of `WP_CLI::debug()` is that it will append the script execution time to the output. 67 | 68 | ## Advanced API Functions 69 | 70 | ### `WP_CLI::error_multi_line()` 71 | 72 | Handy error styler that can display multiple lines, wrapped in a red box. Unlike `WP_CLI::error()`, this method doesn't exit the script. 73 | 74 | ### `WP_CLI::add_hook()` and `WP_CLI::do_hook()` 75 | 76 | Just like `add_action()` and `do_action()` in WordPress Core, `WP_CLI::add_hook()` lets you register a callback to a hook string and `WP_CLI::do_hook()` executes callbacks registered to a hook string. 77 | 78 | ### `WP_CLI::runcommand()` 79 | 80 | Perhaps one of the most powerful methods in the internal API, `WP_CLI::runcommand()` can be used spawn a child process and run another WP-CLI command. Instead of `wp post list`, you drop the `wp` prefix and simply use `WP_CLI::runcommand( 'post list' )`. 81 | 82 | Keep in mind, any `WP_CLI::error()` or other issue inside the command being wrapped will break out of the command where `WP_CLI::runcommand()` is being used. 83 | 84 | _Also, remember to late-escape any variables you inject into the command string!_ 85 | ```php 86 | $format = 'csv'; 87 | WP_CLI::runcommand( sprintf( 'post list --format=%s', $format ) ); 88 | ``` 89 | ### `WP_CLI::launch()` 90 | 91 | _Work-in-progress..._ 92 | 93 | ## Key Utilitiy Functions 94 | 95 | ### `WP_CLI\Utils\format_items()` 96 | 97 | This method is incredibly useful for outputting data in a variety of formats, including a CLI table, CSV, YAML and JSON. 98 | 99 | ### `WP_CLI\Utils\get_flag_value()` 100 | 101 | Instead of accessing `$assoc_args` directly, use this method because flags can be negated with `--no-queit` or `--quiet`. 102 | 103 | ```php 104 | // bad 105 | function( $args, $assoc_args ) { 106 | $value = ! empty( $assoc_args['my-flag'] ) ? $assoc_args['my-value'] : 'default-value'; 107 | } 108 | // good 109 | function( $args, $assoc_args ) { 110 | $value = WP_CLI\Utils\get_flag_value( $assoc_args, 'my-value', 'default-value' ); 111 | } 112 | ``` 113 | 114 | ### `WP_CLI\Utils\trailingslashit()` 115 | 116 | _Work-in-progress..._ 117 | 118 | ### `WP_CLI\Utils\get_temp_dir()` 119 | 120 | _Work-in-progress..._ 121 | 122 | ### `WP_CLI\Utils\get_home_dir()` 123 | 124 | _Work-in-progress..._ 125 | 126 | ### `WP_CLI\Utils\report_batch_operation_results()` 127 | 128 | _Work-in-progress..._ 129 | 130 | ## Advanced Utility Functions 131 | 132 | ### `WP_CLI\Utils\http_request()` 133 | 134 | _Work-in-progress..._ 135 | 136 | ### `WP_CLI\Utils\launch_editor_for_input()` 137 | 138 | _Work-in-progress..._ 139 | 140 | ### `WP_CLI\Utils\make_progress_bar()` 141 | 142 | _Work-in-progress..._ 143 | 144 | ### `WP_CLI\Utils\write_csv()` 145 | 146 | _Work-in-progress..._ 147 | -------------------------------------------------------------------------------- /3-best-practices-designing-a-cli.md: -------------------------------------------------------------------------------- 1 | # Best Practices Designing A Command-Line Interface with WP-CLI 2 | 3 | When crafting WP-CLI Commands, these are some best practices to make your commands resilient, professional-grade and the best they can be. 4 | 5 | ## Commands Should Do ONE Thing 6 | 7 | Commands should aim to accomplish one task with flexability and grace. 8 | 9 | If you need to make a command that does multiple things, consider making multiple discrete commands and then a wrapper command that executes those commands. Not only are these easier to test and debug, but easier to evolve in the future. 10 | 11 | ## Commands Should Be Verbose 12 | 13 | Ideal WP-CLI commands find a balance between being overly-descriptive and too quiet. 14 | 15 | If commands overwhelm a user with unnecessary information, they're more likely to read in a quick scan (if even) and perhaps miss important information. If commands don't provide enough necessary information, users can be impatient and distrustful. 16 | 17 | Each time you introduce conditional logic or run an operation that could error-out or timeout like an API call or database query, consider adding a `WP_CLI::log()`. 18 | 19 | Writing descriptive logs is the equivalent of adding loading spinners and notifications in a GUI -- they give users clarity and confidence in the application. Logging also makes debugging a heck of a lot easier. 20 | 21 | ## Design Commands for Human & Machine Usage 22 | 23 | WP-CLI comes with helpful interactive tools like `WP_CLI::confirm()` and adding more advanced interactivity can really help your commands shine. 24 | 25 | Interactivity is great for humans, but not fun for machines or automation. 26 | 27 | Anytime you throw up an interactivity hurdle, make sure there is a way to set the value with an associative argument and set a flag to disable prompts. 28 | 29 | ## Using Consistient, Parallel Language Construction 30 | 31 | This is a linguistic concept, not a technical concept. 32 | 33 | Naming things is hard. 34 | 35 | It's fine to have a preference on `create` vs. `add` vs. `new` vs. `insert` -- just stick with your preference and it's parallel. 36 | 37 | You start, then stop (like a car). 38 | You begin, then end (like a book). 39 | You connect, then disconnect. 40 | You login, then logout. 41 | 42 | Don't intermix things like: connect + stop, start + end, etc. 43 | 44 | ## Don't Reinvent The Wheel 45 | 46 | There's lots of "prior art" out there for CLI's. Try to use commonly-used language instead of inventing your own -- it will help people learn your CLI faster! 47 | 48 | So if `clone` is a natural fit, don't name something `replicate` or `materialize-duplicate`. 49 | 50 | If `start` is a natural fit, don't name something `powerup` or `lets-get-this-party-started` -- be cute inside your command, not in the naming of it. 51 | 52 | Also consider the audience -- if your teammates are the primary audience, keep in mind other CLI tools you already share and if there's sensible command keywords to adopt. 53 | 54 | ## Brevity & Predictability Are Vital 55 | 56 | WP-CLI discourages brevity for the sake of brevity -- clarity is more important than saving a few chars ;-) 57 | 58 | Verbosity is good! Except when it's not. Brevity is good! Except when it's not. 59 | 60 | Aim for _clarity_. 61 | 62 | Aim to avoid abbrevs and words with multiple meanings like: 63 | * arr 64 | * obj 65 | * opts 66 | * str 67 | * atts 68 | * meta or metadata 69 | 70 | Also watch out for jargon-y or overly-verbose command names. 71 | * Don't include data types in command names (i.e. `wp process-billing-objects`) -- that's what type docs are for! 72 | * Don't include API names in command names (i.e. `wp optimize-billing-post-meta`) -- that's what descriptions are for! 73 | * Don't describe what the command is doing (i.e. `wp http_post_to_billing_api_and_store_processed_results`) -- that's what descriptions are for! 74 | 75 | For the above, consider alternatives like `wp billing process`, `wp invoices fetch` or `wp invoices optimize`. 76 | 77 | ## Reuse Internal Commands Where Possible 78 | 79 | Frankly, some of my favorite Custom WP-CLI Commands I've built are just callbacks using tons of `WP_CLI::runcommand()`'s without anything custom. 80 | 81 | You don't need to invent magic to create magic! 82 | 83 | Whenever possible, try to use a WP-CLI command over a WordPress Core function, so your command doesn't error out when WordPress isn't installed yet or is undergoing a fatal error. 84 | 85 | ## Prepare Responses In Multiple Data Formats 86 | 87 | Many core commands use the `--format` flag and internal helper utility to return data in a table, CSV, YAML, JSON or a list of IDs. This greatly aids in their composability. 88 | 89 | ## Flags and Associative Args Are Generally Better Than Positional Args 90 | 91 | For the same reason a single array of args is better for a WordPress Hook than defining multiple positional variables, try to stick to flags over positional args. 92 | 93 | Nothing is more frustrating than knowing keys for data you're manipulating, but not remembering the order of arguments. 94 | 95 | If you want to use a positional argument, allow for it to fail gracefully and check for an associative argument as well before falling back on a default value. 96 | 97 | ## Consider Scale Issues 98 | 99 | Make sure you test your commands on large datasets, not just a simple install with `Hello World!` and a few dozen options. 100 | 101 | * Don't use unbounded queries. 102 | * Throw up confirmation dialogs before running an operation that could lock-up a large database. 103 | * Consider whether an operation should be run immediately, tied to WordPress Cron or a true task queue system. 104 | 105 | ## Potentially Destructive Commands Default to Dry-Run 106 | 107 | Humans make mistakes. We think `deploy` and type `destroy`. We miss a semicolon and bring down all of AWS. 108 | 109 | Core WP-CLI commands have an optional `--dry-run` mode, however in my own commands I often prefer the default to use dry-run if the operation is potentially destructive or dangerous. It's kind of like "Undo Send" in Gmail. 110 | 111 | Adding a tiny bit of friction can save you from yourself. Add too much friction and you'll just `return` through everything out of habit and still end up destroying everything. 112 | 113 | So try to find a balance between being annoying and being helpful. 114 | 115 | ## Long & Short Flags 116 | 117 | While mostly a bonus, having short flags and long flags that both do the same thing is super helpful. 118 | 119 | If you're trying to skip loading Plugins, Themes and WP-CLI Packages `--skip-plugins --skip-themes --skip-packages` is a fair number of keystrokes for "skip them things." 120 | 121 | `--sp --st --spkg` or even `--skip-all` would be too much appreviation/obfuscation if they were the only args available. 122 | 123 | But if they were secondary triggers in addition to the verbose versions, it gives the best of both worlds. 124 | 125 | Not every command needs long and short variants -- muddies docs -- but keep your eyes out for opportunities where having a select few short equivalents would be helpful. 126 | -------------------------------------------------------------------------------- /00-intro-to-command-line.md: -------------------------------------------------------------------------------- 1 | # Intro to Command Line (for new WP-CLI Users) 2 | 3 | Adopting new tools can be intimidating. 4 | 5 | Whether this is your first venture into a Terminal application or it's just well outside your comfort zone, remember it takes time to get comfortable with new software -- put on your thinking cap and be patient, curious, careful and confident you can figure it out! 6 | 7 | There's a lot of lingo to learn using a CLI. Shells, streams, SSH, strange symbols and a sea of acronyms... 8 | 9 | This guide is designed to get you going with the command line so you can get going with WP-CLI. 10 | 11 | This guide is far from comprehensive -- it's designed to get you going with WP-CLI, but in reality you don't need to be a CLI expert to make great use of WP-CLI or build custom WP-CLI commands using PHP. 12 | 13 | Check out the resource section at the end to learn more about the Terminal and Command Line interfaces! 14 | 15 | This guide is meant for Linux/Unix based systems (which includes MacOS, ChromeOS, Ubuntu, etc). While it's possible to host WordPress on Windows, most WordPress servers run Unix-like operating systems. 16 | 17 | #### Note for Windows Users 18 | 19 | If you're a Windows user, this guide is likely still useful to you! Often when you're running WP-CLI, you'll be remotely-connected to an internet server or local, virtual server on your Windows machine that's running one of these Unix-like operating systems. Windows 10 also offers a system called Bash on Ubuntu on Windows (yes, a mouthful) which lets you use native Linux commands on your Windows machine. 20 | 21 | ### Why Learn The Command Line 22 | * More flexibility 23 | 24 | ### Under The Hood: `STDIN`, `STDOUT` & `STDERR` 25 | 26 | Most modern programming languages like PHP, JavaScript and Python can be used to create a CLI application -- just as these languages can be used to generate HTML documents for a web browser. 27 | 28 | In a command line, these languages wrap three underlying application streams to create the CLI: 29 | 30 | 1. **STDIN** - Standard Input 31 | 2. **STDOUT** - Standard Output 32 | 3. **STDERR** - Standard Error 33 | 34 | Think of these technologies as the conveyer belts your data is carried on -- carrying data into your application, out of your application and a special error handler that stops the other belts and tells you the error for why they stopped. 35 | 36 | When you type a command and hit `return`, you're sending that input to `STDIN`. Then, as processes are reporting progress or completion, they'll return output to `STDOUT`. If something goes wrong, your application will send errors to `STDERR` and break out of their process. 37 | 38 | _**It's not super important to understand these underlying pieces deeply to use WP-CLI or write Custom WP-CLI Commands with PHP**_. 39 | 40 | ### Users & Directories 41 | 42 | The are two critical concepts to understand while you're using a CLI in a Terminal window: 43 | 44 | In a terminal session... 45 | 1. ... **you're always using a user account** with varying permission rights to read or write to parts of the filesystem. 46 | 2. ... **you're always inside a folder (aka directory)** somewhere on the filesystem. 47 | 48 | When you open a Terminal window on a Mac or Linux machine you'll see something like this: 49 | ```bash 50 | username@hostname:directory[separator] 51 | ``` 52 | 53 | In my case, this looks like... 54 | ```bash 55 | dryan@mbp:~$ 56 | ``` 57 | 58 | * `dryan` is my system user's username (which differs from my user's display name of `David Ryan`) 59 | * `mbp` is the name of my host machine 60 | * `~` is a symbolic shorthand for my user's directory (`/Users/dryan`) 61 | * `$` is the "prompt" part of "command prompt" that separates your command from lets you know the Terminal is ready for input (`>` on Windows) and has a cursor following it. 62 | 63 | We'll get into more details below about how to navigate the filesystem, but for now know whenever you see that string, it means your terminal is awaiting input and no processes are running. 64 | 65 | ### Navigating Directories & Common Commands 66 | 67 | As mentioned above, when you first open a Terminal window you are in your user's Home Directory. 68 | 69 | * `~` is short for the user's Home Directory (i.e. `/Users/dryan`) 70 | * `.` is short for the **current** directory. 71 | * `..` is short for the directory **above** the current directory. 72 | * `/` when at the beginning of a path stands for the root directory of the entire filesystem (elsewhere it denotes the separation between directories) 73 | 74 | With paths, similar to URLs, there are **relative paths** and **absolute paths**. 75 | 76 | This is best explained by introducing the `cd` command, which is used to _change directory_. 77 | 78 | Example: Changing into a folder called `playground` in my user's directory would be: 79 | * `cd playground` but only if I'm in the root of my home directory. This relative path is relative to your current directory. 80 | * `cd /Users/dryan/playground` from anywhere (including my home directory). This absolute path can be used anywhere and doesn't take the current directory into account. 81 | 82 | As directories change, you'll see your prompt prefix change as well: 83 | ```bash 84 | dryan@mbp:~/playground$ 85 | ``` 86 | 87 | Then, if I wanted to "step up" one directory to return to my user directory, I could run... 88 | ```bash 89 | cd .. 90 | ``` 91 | 92 | Or, if I wanted to step up two directories into the `/Users` directory from `/Users/dryan/playground`, I'd run 93 | 94 | ```bash 95 | cd ../.. 96 | ``` 97 | 98 | **TIP:** For a long directory name that's inside the current directory (i.e. `my-super-long-folder-name`) you can type the first few characters `cd my-` and hit the **`TAB`** key to auto-complete the name without typing it all out. This also works with absolute paths as-you-go: 99 | * `cd /Users/dr` + **`TAB`** (to get `dryan`), and then... 100 | * `cd /Users/dryan/my-` + **`TAB`** (to get `my-super-long-folder-name`) 101 | 102 | **macOS TIP:** For a long directory path, you can type `cd ` (note the space) and then drag-and-drop a folder from Finder into the terminal window, which will insert the absolute path to that directory. It can save a ton of time over typing a path like `cd /Users/dryan/Sites/VVV/wordpress/public_html/wp-content/plugins/src/scss`. 103 | 104 | #### Common Commands & Operators 105 | * `cd` - Change directories 106 | * `ls` - List files 107 | * `touch` - Create a file 108 | * `mkdir` - Create a folder 109 | * `rm` - Remove a file or folder 110 | * `&&` - Chain commands together 111 | 112 | ##### Some examples... 113 | 114 | ###### Change into the themes directory and make a folder called custom 115 | ```bash 116 | cd wp-content/themes && mkdir custom 117 | ``` 118 | 119 | ###### Change into the plugins directory and force remove Hello Dolly, and recursively remove any subfolders and nested files inside hello 120 | ```bash 121 | cd wp-content/plugins && rm -rf hello 122 | ``` 123 | 124 | ###### Change up one level from the current directory and make an empty file called LICENSE.md 125 | ```bash 126 | cd .. && touch README.md 127 | ``` 128 | 129 | ###### Change into the public_html folder (where WordPress lives) and list files, including hidden system files/folders that begin with a period 130 | ```bash 131 | cd ~/public_html && ls -a 132 | ``` 133 | 134 | ### Understanding Remote Connections with SSH 135 | 136 | SSH stands for Secure Shell and works like a remote desktop for the Terminal. 137 | 138 | SSH lets you connect to a shell session on a remote server with credentials. The server could be elsewhere on the internet, or simply a virtual server running on your local OS like VVV or Lando. 139 | 140 | To access WP-CLI you will often need to "ssh in" to your server to begin running commands. 141 | 142 | To use SSH you'll need: 143 | 1. A **username** for a user on the remote server 144 | 2. A **hostname** for pointing your computer at the server (either an IP address or domain like something.mydomain.com) 145 | 3. A **password or key file** used to authenticate as that user. 146 | 147 | (You may also need a port number, if the default SSH port 22 is blocked) 148 | 149 | ```bash 150 | dryan@mbp:~$ ssh dave@192.168.32.145 151 | Password: ********** 152 | 153 | dave@192.168.32.145:~$ 154 | ``` 155 | 156 | If you've set a default User and key file in your ssh config, you can... 157 | ```bash 158 | dryan@mbp:~$ ssh 192.168.32.145 159 | 160 | dave@192.168.32.145:~$ 161 | ``` 162 | 163 | A few things to keep in-mind when you're SSH'd into a remote server: 164 | * You don't have access to command history from your local system. 165 | * You don't have access to any aliases in your local system's `~/.bash_profile` -- you have your remote user's `~/.bash_profile` 166 | * You only have access to software installed on the server, not on your local machine _(i.e. you may be able to `npm install` on your local machine because you installed `npm` on there, but that command may not work on your remote server unless `npm` is installed there.)_ 167 | -------------------------------------------------------------------------------- /0-intro-to-wp-cli.md: -------------------------------------------------------------------------------- 1 | # Introduction to WP-CLI 2 | 3 | The WordPress Command Line interface is a robust tool for interacting with WordPress sites. 4 | 5 | WP-CLI uses a text-based syntax of commands (combinations of words, numbers, abbreviations and punctuation) to interact with a WordPress site instead of the visual WP Admin interface in a web browser. 6 | 7 | Using a Terminal app (a.k.a "shell") you... 8 | 1. Change directories (`cd`) the folder where your WordPress site is installed 9 | 2. Type a command using WP-CLI's syntax _(i.e. `wp maintenance-mode activate` )_ 10 | 3. Hit `return` 11 | 4. When the command is done running, WP-CLI will show a written response explaining what operations it ran or errors it encountered. 12 | 13 | This interaction is kind of like sending a text message to your favorite restaurant... **`subscribe`** to receive coupons (receiving an text back saying _"Great! We'll send you discounts. Type STOP to unsubscribe."_) or **`stop`** (receiving _"Okay, you've unsubscribed from sweet discounts."_). The system on the other end is designed to run operations based on receiving specific commands.. 14 | 15 | In WP-CLI, instead of SMS commands you'd text to a restaurant like `subscribe`, `stop`, `hours` or `reservation`, commands map to different features of WordPress like `post`, `option`, `maintenance-mode` and `user` -- there are 44 commands that come with WP-CLI out-of-the-box, many with subcommands and flexible options. 16 | 17 | At the end of the day, WP-CLI is just a virtual assistant -- kinda like Slackbot or Siri -- you can direct message with to manage WordPress sites. 18 | 19 | ## Getting Started with WP-CLI 20 | 21 | ### WP-CLI is likely already installed on your web host 22 | 23 | The [vast majority of WordPress hosts](https://make.wordpress.org/cli/handbook/hosting-companies/) pre-install WP-CLI on their servers, so it's ready-to-use whenever you're ready. It's also bundled with popular local development tools like VVV, DesktopServer, Lando and Local by Flywheel. _(Using MAMP? Here are [some good instructions](https://tommcfarlin.com/installing-wp-cli-with-mamp/) for installing WP-CLI). 24 | 25 | ### Checking for WP-CLI and where to start 26 | 27 | To start using WP-CLI, you'll likely need to connect to your webserver or virtual server using SSH. 28 | 29 | 1. Sign-in to your server. 30 | 2. `cd` into the WordPress root directory _(the folder with `/wp-admin`, `/wp-content`, etc)_. 31 | 3. Type **`wp`** and press **`return`** on your keyboard. 32 | 4. If WP-CLI is installed correctly, you should see the help guide with a list of the available commands on the server. 33 | 5. Type **`q`** to quit the help documentation. 34 | 35 | ![example of WP-CLI help readout](assets/wp.gif) 36 | 37 | ## Commands & Subcommands 38 | 39 | At the center of WP-CLI are **Commands**. 40 | 41 | At time of writing, there are 44 top-level commands included with WP-CLI to run operations on data in a WordPress database, generate WordPress starter code and more! 42 | 43 | Commands are pretty easy to identify -- they're the first word following `wp` in a command string, such as `wp `**`post`**. 44 | 45 | When commands are registered with WP-CLI, this keyword string is mapped to a callback to execute when that command is used. This mapping is similar to an automated phone tree, such as the one from your bank: 46 | 47 | > Press `2` for account information, press `3` to file a claim, press `0` to speak to an operator... 48 | 49 | Where WP-CLI is more like... 50 | 51 | > Type `wp post` to work with Posts, type `wp option` to work with WordPress Options and type `wp help` to learn about available commands... 52 | 53 | **Subcommands** are registered beneath a primary command, such as `wp post `**`delete`**. Subcommands are commands that aren't top-level (top-level commands are immediately right-adjacent to the `wp` keyword), but otherwise have all the same potential features as a top-level command. 54 | 55 | It's not a hard rule, but in general the primary command is a _thing_ (post, user, cron, config etc) while subcommands are _operations_ that run on that thing (create, delete, start, install, etc). 56 | 57 | It's also important to note that while `wp post create` and `wp user create` both have a `create` subcommand, these are two _distinct_ subcommands with different arguments and functionality. 58 | 59 | ## Positional Arguments, Associative Arguments and Flags 60 | 61 | Many WP-CLI commands have required or optional arguments that change how the commands work, scope what the operation will modify and how the command will return a response. 62 | 63 | ### Positional Arguments 64 | 65 | Positional arguments are values that immediately follow the command/subcommand keyword, separated by a space. The order of positional arguments matters, hence the name positional. 66 | 67 | _Ex. `wp post delete `**`100`** -- `100` is the **first** positional argument following the `delete` subcommand. In a simple, top-level command like `wp do-something `**`my-plugin-name`**, `my-plugin-name` isn't a subcommand, it's the first positional argument.`wp do-something-else subcommand arg1 arg2 arg3` is an example of multiple positional arguments on a subcommand._ 68 | 69 | ### Flags 70 | 71 | Flags are similar to checkboxes in a visual interface -- they're used to denote true/false and are used to enable or disable part of a command's functionality. They're called flags because their syntax looks like a flag pole the word is "flying from" with two preceeding dashes. 72 | 73 | _Ex. In `wp post delete 100 `**`--force`**`, --force` is the flag._ 74 | 75 | ### Associative Arguments 76 | 77 | Associative arguments are values that are associated with a string key. These key-value pairs that start with a flag syntax, but an `=` is used to set a value. Unlike positional args, associative args are always optional and can be used in any order. Associative is often abbreviated `assoc` in code. 78 | 79 | _Ex. `wp post delete 100 --method=via-sql-query`_ 80 | 81 | ## Global Arguments 82 | 83 | At writing, there are 13 global arguments that can be used with any command included in WP-CLI or a Custom Command. 84 | 85 | All global arguments are associative args, as they're all optional. 86 | 87 | Two critical clobal arguments to be aware of, that greatly expedite learning and use of WP-CLI are: 88 | 89 | * `--prompt` - Creates an interactive prompt that asks a user for values for each positional argument, associative argument and flag, meaning **you don't need to memorize argument keys OR the order of arguments**. Hitting `return` with an empty value in `--prompt` will fallback to the default value for the argument, as if you didn't type it. 90 | * `--help` - Will return the documentation for any command or subcommand. `wp post --help`, `wp post list --help` and `wp maintenance-mode --help` will all return different help responses. **No need to go search the web for information about commands!** 91 | 92 | ## Remote Management & WordPress Multisite 93 | 94 | ### Using WP-CLI's built-in Remote Management Features 95 | 96 | Ready for inception? You can use one install of WP-CLI to remotely control another! 97 | 98 | This means you can use WP-CLI running on your local development environment to control your remote production and staging environments -- so long as WP-CLI is installed on both remote servers. This can be done using the `--ssh` or `--http` global arguments, or better yet using a `wp-cli.yml` configuration file where you identify an environment with an alias. 99 | 100 | A common use case is mapping aliases for staging and production environments to a local development environment where WP-CLI is installed. 101 | 102 | Another practical use is for a developer or agency that manages dozens or hundreds of sites. Creating a YAML config file on a local environment that points to all the remote servers for clients can make things like updating plugins for all clients a breeze. The config allows an alias to be set like "client1" or "candy-store". Note that "all" is a reserved alias -- using @all will run the command against the current environment and all remotes registered in the config file. 103 | 104 | 105 | ```bash 106 | wp @candy-store plugin update --all 107 | ``` 108 | 109 | ```bash 110 | wp @staging plugin update --all && wp @production plugin update --all 111 | ``` 112 | 113 | ```bash 114 | wp @all plugin update --all 115 | ``` 116 | 117 | ### Working with WordPress Multisite 118 | 119 | By default, all WP-CLI commands on a Multisite installation are run against the *first* site in the network. 120 | 121 | To run a command against another site, the global argument `--url` must be set -- i.e. `wp post delete 100 --url=https://site2.com` -- otherwise WP-CLI will try to delete Post ID 100 from the primary site in the network, so please use extra caution when running commands for Multisite installs. 122 | 123 | **NOTE:** This must be the _fully-qualified Site URL_, not the numerical Site ID. 124 | 125 | ## Chaining Commands Together 126 | 127 | Commands don't run in parallel, so they can be chained together and expected to run sequentially. 128 | 129 | ```bash 130 | # Update All The Things 131 | wp cli update && wp core update && wp theme update --all && wp plugin update --all 132 | ``` 133 | 134 | One risk of running commands in a sequence like this, is that if one command errors-out, subsequent commands are never run. So if you set a cron job to "update all the things" each day, but each day the WP-CLI update command fails... none of the other commands will run... so when chaining commands that aren't related like above, consider the order of importance and put the most stable/reliable commands first. 135 | 136 | ## Composing Commands Together 137 | 138 | Some of the real power of WP-CLI is composing commands together in a sequence where subsequent commands use the dynamic response(s) from preceeding commands. 139 | 140 | By making commands that focus on doing one thing, the results of one command can be passed into arguments for another command, making them much more versitile and composible. 141 | 142 | There are two primary ways to compose commands together: 143 | 1. Using a subshell to use the results of a command inside another 144 | 1. Using `xargs` to pass response items to the second command. 145 | 146 | In general, I find the `xargs` syntax easier on the eyes, but there isn't a right way to do it, and sometimes there are benefits to subshells and loops. 147 | 148 | ### Scenario: Delete All Drafts For a Specific User 149 | 150 | The WordPress Admin is a fairly powerful interface, but it does have limitations. Using the filters on the All Posts screen, it's possible to get a list of all draft posts or posts by a specific author, but not a list of all drafts by a specific author. 151 | 152 | On a news website, a user might have thousands of posts and hundreds of drafts, which would make cleaning drafts out for that user an exhaustively manual task in the WordPress Admin. 153 | 154 | Enter WP-CLI! 155 | 156 | ##### Using a subshell 157 | ```bash 158 | wp post delete --force $(wp post list --post_status=draft --post_author=1 --format=ids) 159 | ``` 160 | 161 | ##### Using `xargs` 162 | ```bash 163 | wp post list --post_status=draft --post_author=1 --field=ID | xargs -n1 -I % wp post delete % --force 164 | ``` 165 | 166 | ### Scenario: Add User Privileges to All Sites In a Multisite 167 | 168 | Management of a WordPress Multisite is one area where WP-CLI really shines. Where WP-CLI will often save minutes on a task for a single site, it can save hours for a task that needs to happen in a large Multisite. 169 | 170 | When I worked in publishing, one frequent task would be granting a new editor privileges on each site within a Multisite that contained hundreds of sites (or de-escalating their privileges when they left the company). Unlike a super-admin user, an editor-level user needs to get opt-in access to each site from an administrator. 171 | 172 | In this example, we're looping over all sites in a multisite, and setting user "1" as an editor, with a custom capability called `custom_homepage_builder`. 173 | 174 | ##### Using For Loop 175 | _(Here we use a for loop instad of using a subshell so we can echo-out the name of the site before setting user privleges, so the output can be copied and saved for reference.)_ 176 | ```bash 177 | for url in $(wp site list --format=csv --fields=url | tail -n +2); do echo "$url: "; wp user set-role 1 editor --url=$url; wp user add-cap 1 custom_homepage_builder --url=$url; done 178 | ``` 179 | 180 | ##### Using `xargs` 181 | ```bash 182 | wp site list --fields=url | xargs -n1 -I % wp user set-role 1 editor --url=% && wp user add-cap 1 custom_homepage_builder --url=% 183 | ``` 184 | -------------------------------------------------------------------------------- /1-intro-to-custom-commands.md: -------------------------------------------------------------------------------- 1 | # Introduction to WP-CLI Custom Commands 2 | 3 | > Any sufficiently advanced technology is indistinguishable from magic. - Arthur C. Clarke 4 | 5 | For a long time, I used WP-CLI and thought "the core commands are _so powerful_, they must be _so challenging_ to create. 6 | 7 | In reality, working on WP-CLI commands is more like creating an electrical circuit than a rocket engine. Which isn't to say it's always "quick" or "easy," but if you think it's magic you may be surprised... and it could very well be quicker and easier than you expect. 8 | 9 | However, even with the knowledge that building commands isn't rocket science, it's easy to psyche yourself out: _I don't have a genius idea for a custom command to change the world, my products or even my workflow..._ 10 | 11 | ### Some benefits of creating Custom WP-CLI Commands: 12 | * A set of tools accessible from anywhere and easily shared with others. 13 | * Create powerful tools without the overhead and distraction of designing and maintaining GUIs. 14 | * Aim to mitigate human error. Chaining and composing commands can be super powerful -- also super dangerous. A typo can have disasterous consequences, particularly in production. Putting long chains and compound commands inside a custom commands can give you the confidence to run otherwise dangerous operations or sequences with extra validation and shorter strings to type. 15 | * Add technical value for your technical customers. 16 | 17 | ### Some ideas for when to make custom WP-CLI commands: 18 | * Setup WordPress with baseline dependencies and settings (local, staging or production environments). 19 | * Custom import/export tool for a product. 20 | * Custom diagnostic tool that scans for errors 21 | * Custom tools to connects your data/files with an internet service or API. 22 | * A custom scaffolding tool for creating Plugins, Themes, Blocks or WP-CLI Packages from standardized templates. 23 | * CRUD operations for interacting with a product. 24 | * Setting WordPress/an extending product to a specific state, perhaps with dummy content or to step 5 of 12 in a complex flow. 25 | * Flows for common issues that fill your help desk system. 26 | * A simple wrapper around a `wp option update` command, so users don't need to remember the option key, run a `wp option list` and scan a large list of options to find the key and so you can run validation prior to injecting an value. (i.e. `wp my-coming-soon disable` could run `wp option update my_cs_is_enabled 0`) 27 | 28 | ## Custom Commands Can Live in Plugins or WP-CLI Packages 29 | 30 | Custom WP-CLI Commands can be registered in three locations: 31 | * A traditional WordPress Plugin 32 | * A must-use WordPress Plugin 33 | * A WP-CLI Package 34 | 35 | WP-CLI Packages are effectively a WP-CLI-only plugin that can be installed from a Git repo or an the official WP-CLI package repository (that official repository is now closed to submissions). 36 | 37 | Packages are nice because WP-CLI uses Composer to autoload and handle code updates! 38 | 39 | #### Both Plugins and Packages have Pros & Cons 40 | 41 | Plugins are great because custom commands can be updated by pushing a Plugin update, so they're often the best option if you're trying to distribute a CLI with a custom Plugin or Theme to environments you don't control. 42 | 43 | Packages require `wp package update` to be run for updates to deploy. If you control your environments, you can run this as-needed or on a system cron job. 44 | 45 | But Packages are great because they don't clutter your Plugins screen, prevent users from disabling unless they have permission to use WP-CLI and commands in packages can be run without WordPress already installed (so long as they don't require the WordPress database and Core functions). 46 | 47 | ## Registering A Custom Command 48 | 49 | Before you name and register a new command, it's important to consider a few things: 50 | 1. Command name strings are a global namespace -- make sure your name string is unique. 51 | 1. Run `wp` on your system and see what Core/Custom commands are used (your host may add their own commands). 52 | 2. Particularly if you're distributing a product with custom commands, check [this list](https://make.wordpress.org/cli/handbook/tools/) **_(not exhaustive!)_** and search the web for "wp-cli wp [name]" to try to avoid collision. 53 | 2. Do you need an entirely new namespace? If you're building a generic custom command, say to scaffold a React-based UI for the WordPress Admin, it may make sense to register a new subcommand under `wp scaffold` -- instead of `wp scaffold-react-admin` you could put under `wp scaffold react-admin`. 54 | 55 | Now, it's time to get building! 56 | 57 | ### WP_CLI::add_command() 58 | 59 | Using a static method on the `WP_CLI` class called `add_command()` you can register new top-level commands and subcommands. 60 | 61 | When using `WP_CLI::add_command()`, you first need to check if the `WP_CLI` class is available, otherwise you can get some nasty errors. 62 | 63 | You can either check the class is available before using the static method or hook your code to load on `cli_init` action, so it only instantiates if WP-CLI is available. 64 | 65 | ```php 66 | // used anywhere 67 | if ( ! class_exists('WP_CLI' ) ) { 68 | return; 69 | } 70 | 71 | WP_CLI::add_command() 72 | ``` 73 | 74 | ```php 75 | // safe to directly use `WP_CLI` without checking if the class exists 76 | add_action( 'cli_init', 'my_custom_command' ); 77 | function my_custom_command() { 78 | WP_CLI::add_command(); 79 | } 80 | ``` 81 | 82 | `WP_CLI::add_command()` has two required arguments and a third, optional argument that accepts a configuration array. 83 | 84 | ```php 85 | WP_CLI::add_command( $name, $callable, $args = array() ); 86 | ``` 87 | 88 | ##### $name _(string)_ 89 | This argument is where the keyword name is set used to trigger your command. 90 | 91 | ```php 92 | /** 93 | * You can register one callback that handles subcommands, register each subcommand separately or hook into an existing core command. 94 | */ 95 | WP_CLI::add_command( 'magic', $callback_handles_start_and_stop ); 96 | // OR 97 | WP_CLI::add_command( 'magic start', $callback_handles_start ); 98 | WP_CLI::add_command( 'magic stop', $callback_handles_stop ); 99 | // OR EXTEND CORE COMMANDS LIKE 'scaffold' 100 | WP_CLI::add_command( 'scaffold magic', $scaffold_magic ); 101 | ``` 102 | 103 | ##### $callable _(callable)_ 104 | This argument can be a function, a closure function or a class. 105 | 106 | ##### $args _(array)_ 107 | This optional arguments array can be used to define a WP-CLI Hook to execute on, trigger code to invoke before/after the command fires and has string description fields as an alternative to PHPDoc to populate the `help` command results. 108 | 109 | * _(callable)_ $before_invoke Callback to execute before invoking the command. 110 | * _(callable)_ $after_invoke Callback to execute after invoking the command. 111 | * _(string)_ $shortdesc Short description (80 char or less) for the command. 112 | * _(string)_ $longdesc Description of arbitrary length for examples, etc. 113 | * _(string)_ $synopsis The synopsis for the command (string or array). 114 | * _(string)_ $when Execute callback on a named WP-CLI hook (e.g. before_wp_load). 115 | * _(bool)_ $is_deferred Whether the command addition had already been deferred. 116 | 117 | 118 | ### Writing Command Callbacks 119 | 120 | In the next few chapters I go into more detail about _what_ to do in your callback and WP_CLI's internal API and helper functions, but first we need to talk about what happens to `$callable` from above. 121 | 122 | No matter whether you're passing a function name, qualified class name or closure, in the end you'll end up with a function that's passed two arguments -- both arrays that default to empty. 123 | 124 | ```php 125 | /** 126 | * 127 | * @param array $args - Positional Arguments 128 | * @param array $assoc_args - Flags & Associative Arguments 129 | */ 130 | function( $args, $assoc_args ) { 131 | // doing command stuff 132 | } 133 | ``` 134 | 135 | #### $args 136 | These are your **Positional Args** -- if you have any. The first positional argument would be `$args[0]`, the second would be `$args[1]`, etc. 137 | 138 | _Remember to use good code hygene and use `isset()` or `! empty()` to check for a value before trying to access it._ 139 | 140 | #### $assoc_args 141 | These are your **Associative Args** -- if you have any. The flag `--bam=pow` would be `$assoc_args['bam'] = 'pow'`. _Note that you don't need the double-dash in the key string._ 142 | 143 | However, instead of running an `isset()` or `! empty()` check and accessing directly, I recommend using the utility function to extract associative args, because they can be negated using `--no-quiet`. 144 | 145 | ```php 146 | // to use, pass the entire array of $assoc_args and use $flag to set your key 147 | WP_CLI\Utils\get_flag_value( $assoc_args, $flag, $default = null) 148 | 149 | // example - If 'bam' is set to 'pow', $flag = 'pow'. If not set $flag = 'smack'. 150 | $flag = WP_CLI\Utils\get_flag_value( $assoc_args, 'bam', 'smack' ); 151 | ``` 152 | 153 | ### Notes on Code Structure 154 | 155 | I prefer the flexibility that PHP classes offer over functions. 156 | 157 | When a qualified class name is passed for `$callable`, any `public function` in the class immediately becomes a subcommand. 158 | 159 | ```php 160 | WP_CLI::add_command( 'cool', 'My_Cool_Command' ); 161 | 162 | class My_Cool_Command { 163 | public function start( $args, $assoc_args ) { 164 | // 'wp cool start' will execute this method 165 | $this->helper(); 166 | } 167 | public function stop( $args, $assoc_args ) { 168 | // 'wp cool stop' will execute this method 169 | $this->helper(); 170 | } 171 | protected function helper() { 172 | // this method isn't registered as a command 173 | } 174 | } 175 | ``` 176 | 177 | Another benefit of using classes is that its easier to reuse code, map multiple subcommands to the same callback and organize code in general. 178 | ```php 179 | WP_CLI::add_command( 'cool', 'My_Cool_Command' ); 180 | 181 | class My_Cool_Command { 182 | /** 183 | * Note use of __invoke(). __construct() won't work! 184 | */ 185 | public function __invoke( $args, $assoc_args ) { 186 | $subcommand = ! empty( $args[0] ) ? $args[0] : ''; 187 | switch( $subcommand ) { 188 | case 'start': 189 | case 'begin': 190 | $this->start( $args, $assoc_args ); 191 | break; 192 | case 'stop': 193 | case 'end': 194 | $this->stop( $args, $assoc_args ); 195 | break; 196 | default: 197 | WP_CLI::warning( '' ); 198 | break; 199 | } 200 | 201 | } 202 | protected function start( $args, $assoc_args ) { 203 | /** 204 | * wp cool start OR wp cool begin 205 | */ 206 | $this->helper( $assoc_args ); 207 | // now do start stuff 208 | } 209 | protected function stop( $args, $assoc_args ) { 210 | /** 211 | * wp cool stop OR wp cool end 212 | */ 213 | $this->helper( $assoc_args ); 214 | // now do stop stuff 215 | } 216 | protected function helper( $assoc_args ) { 217 | // this method is shared by the command functions above 218 | // it's not registered because it's 'protected' 219 | } 220 | } 221 | ``` 222 | 223 | If you're developing multiple commands, you may want to re-use helper methods across multiple classes, another place where using classes over functions really shines. 224 | 225 | ```php 226 | class My_CLI_Commands { 227 | function my_helper( $input ) { 228 | // do stuff to $input 229 | return $input 230 | } 231 | } 232 | 233 | class Cool_Command extends My_CLI_Commands { 234 | public function start( $args ) { 235 | $my_input = ! empty( $args[0] ) ? $args[0] : 'default-value'; 236 | $parsed = $this->my_helper( $my_input ); 237 | // do stuff 238 | } 239 | } 240 | ``` 241 | 242 | ## Understanding WP-CLI Hooks 243 | 244 | WP-CLI hooks are quite similar to WordPress Action Hooks. 245 | 246 | Hooks control when the code is executed: 247 | * Before/After a specific command. 248 | * Before/After WordPress is loaded (Ex. you cannot use `wp core download` inside a custom command unless you use `before_wp_load`). 249 | * Before/After the wp-config.php is loaded. 250 | 251 | Defining a Hook for a command is done during `WP_CLI::add_command()` registration by specifying the `when` parameter in the $args array. 252 | 253 | ```php 254 | WP_CLI::add_command( 255 | 'magic', 256 | function() { 257 | WP_CLI::success( "It's magic!" ); 258 | }, 259 | array( 260 | 'when' => 'before_wp_load' 261 | ) 262 | ); 263 | ``` 264 | 265 | ### Available WP-CLI Hooks 266 | * before_add_command: – Before the command is added. 267 | * after_add_command: – After the command was added. 268 | * before_invoke: – Just before a command is invoked. 269 | * after_invoke: – Just after a command is invoked. 270 | * find_command_to_run_pre – Just before WP-CLI finds the command to run. 271 | * before_wp_load – Just before the WP load process begins. 272 | * before_wp_config_load – After wp-config.php has been located. 273 | * after_wp_config_load – After wp-config.php has been loaded into scope. 274 | * after_wp_load – Just after the WP load process has completed. 275 | * before_run_command – Just before the command is executed. 276 | 277 | ## Using PHPDoc to Register In-CLI Help Documentation 278 | 279 | Perhaps the most magical feature of WP-CLI is how it slurps PHPdoc comments above classes and functions to magically build the `help` results for commands. 280 | 281 | No one likes going to code to check arguments -- so add simple PHPdoc comments. 282 | 283 | The best artists steal, so I recommend copying + pasting an existing PHPdoc **(just make sure to edit/cut it down properly!)**. 284 | 285 | There's great boilerplates on the [WP-CLI Documentation Standards](https://make.wordpress.org/cli/handbook/documentation-standards/) page. 286 | 287 | ## Why a custom command when I can use a shell script/alias or the WP-Admin? 288 | 289 | ### Advantages over `my-awesome-script.sh` & shell aliases 290 | * Shareable with others and accessible no matter the machine you're using. 291 | * Remotely installable with `wp plugin install` and `wp package install` 292 | * Easier to write defensive checks in PHP than in Bash -- so more likely you'll do it and write safer, more resiliant code. 293 | * Commands are less-likely to run into file permission/executable issues. 294 | * More likely commands are in Git AND versioned than a random cowboy or config file. 295 | * Easier to execute both PHP and shell commands together. 296 | * Execute on a hook, to properly time the execution of your code with something happening elsewhere in WordPress. 297 | 298 | ### Advantages over WP-Admin Interface 299 | * Expectation of a certain level of technical know-how from user consuming code. 300 | * Less worry about scoping user privleges, nonces, etc. 301 | * No need to write and maintain HTML, CSS or JavaScript. 302 | * No obsessing over design decisions and browser inconsistiencies when the goal is a technical feature. 303 | * No waiting for page refreshes. 304 | * Reuse other powerful WP-CLI commands within your command that go beyond WordPress Core functions. 305 | * Command is composable with other commands during execution. 306 | 307 | ### Multiple Ways To Do The Same Thing 308 | 309 | One of the great things about WP-CLI is there is often a few ways to do the same thing. 310 | 311 | ##### Example: Updating a database option 312 | 313 | * `wp option update blogdescription "WP-CLI is awesome!"` 314 | * `wp eval 'update_option( "blogdescription", "WP-CLI is awesome!" );'` 315 | * `wp db query 'UPDATE wp_options SET option_value="WP-CLI is awesome!" WHERE option_name="blogdescription";'` 316 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------