2 namespace Consolidation\AnnotatedCommand;
4 use Symfony\Component\Finder\Finder;
7 * Do discovery presuming that the namespace of the command will
8 * contain the last component of the path. This is the convention
9 * that should be used when searching for command files that are
10 * bundled with the modules of a framework. The convention used
11 * is that the namespace for a module in a framework should start with
12 * the framework name followed by the module name.
14 * For example, if base namespace is "Drupal", then a command file in
15 * modules/default_content/src/CliTools/ExampleCommands.cpp
16 * will be in the namespace Drupal\default_content\CliTools.
18 * For global locations, the middle component of the namespace is
19 * omitted. For example, if the base namespace is "Drupal", then
20 * a command file in __DRUPAL_ROOT__/CliTools/ExampleCommands.cpp
21 * will be in the namespace Drupal\CliTools.
23 * To discover namespaced commands in modules:
25 * $commandFiles = $discovery->discoverNamespaced($moduleList, '\Drupal');
27 * To discover global commands:
29 * $commandFiles = $discovery->discover($drupalRoot, '\Drupal');
33 * This class is deprecated. Commandfile discovery is complicated, and does
34 * not work from within phar files. It is recommended to instead use a static
35 * list of command classes as shown in https://github.com/g1a/starter/blob/master/example
37 * For a better alternative when implementing a plugin mechanism, see
38 * https://robo.li/extending/#register-command-files-via-psr-4-autoloading
40 class CommandFileDiscovery
43 protected $excludeList;
45 protected $searchLocations;
47 protected $searchPattern = '*Commands.php';
49 protected $includeFilesAtBase = true;
51 protected $searchDepth = 2;
53 protected $followLinks = false;
55 protected $strippedNamespaces;
57 public function __construct()
59 $this->excludeList = ['Exclude'];
60 $this->searchLocations = [
62 'CliTools', // TODO: Maybe remove
67 * Specify whether to search for files at the base directory
68 * ($directoryList parameter to discover and discoverNamespaced
69 * methods), or only in the directories listed in the search paths.
71 * @param boolean $includeFilesAtBase
73 public function setIncludeFilesAtBase($includeFilesAtBase)
75 $this->includeFilesAtBase = $includeFilesAtBase;
80 * Set the list of excludes to add to the finder, replacing
81 * whatever was there before.
83 * @param array $excludeList The list of directory names to skip when
84 * searching for command files.
86 public function setExcludeList($excludeList)
88 $this->excludeList = $excludeList;
93 * Add one more location to the exclude list.
95 * @param string $exclude One directory name to skip when searching
98 public function addExclude($exclude)
100 $this->excludeList[] = $exclude;
105 * Set the search depth. By default, fills immediately in the
106 * base directory are searched, plus all of the search locations
107 * to this specified depth. If the search locations is set to
108 * an empty array, then the base directory is searched to this
111 public function setSearchDepth($searchDepth)
113 $this->searchDepth = $searchDepth;
118 * Specify that the discovery object should follow symlinks. By
119 * default, symlinks are not followed.
121 public function followLinks($followLinks = true)
123 $this->followLinks = $followLinks;
128 * Set the list of search locations to examine in each directory where
129 * command files may be found. This replaces whatever was there before.
131 * @param array $searchLocations The list of locations to search for command files.
133 public function setSearchLocations($searchLocations)
135 $this->searchLocations = $searchLocations;
140 * Set a particular namespace part to ignore. This is useful in plugin
141 * mechanisms where the plugin is placed by Composer.
143 * For example, Drush extensions are placed in `./drush/Commands`.
144 * If the Composer installer path is `"drush/Commands/contrib/{$name}": ["type:drupal-drush"]`,
145 * then Composer will place the command files in `drush/Commands/contrib`.
146 * The namespace should not be any different in this instance than if
147 * the extension were placed in `drush/Commands`, though, so Drush therefore
148 * calls `ignoreNamespacePart('contrib', 'Commands')`. This causes the
149 * `contrib` component to be removed from the namespace if it follows
150 * the namespace `Commands`. If the '$base' parameter is not specified, then
151 * the ignored portion of the namespace may appear anywhere in the path.
153 public function ignoreNamespacePart($ignore, $base = '')
155 $replacementPart = '\\';
157 $replacementPart .= $base . '\\';
159 $ignoredPart = $replacementPart . $ignore . '\\';
160 $this->strippedNamespaces[$ignoredPart] = $replacementPart;
166 * Add one more location to the search location list.
168 * @param string $location One more relative path to search
171 public function addSearchLocation($location)
173 $this->searchLocations[] = $location;
178 * Specify the pattern / regex used by the finder to search for
181 public function setSearchPattern($searchPattern)
183 $this->searchPattern = $searchPattern;
188 * Given a list of directories, e.g. Drupal modules like:
192 * modules/default_content
194 * Discover command files in any of these locations.
196 * @param string|string[] $directoryList Places to search for commands.
200 public function discoverNamespaced($directoryList, $baseNamespace = '')
202 return $this->discover($this->convertToNamespacedList((array)$directoryList), $baseNamespace);
206 * Given a simple list containing paths to directories, where
207 * the last component of the path should appear in the namespace,
208 * after the base namespace, this function will return an
209 * associative array mapping the path's basename (e.g. the module
210 * name) to the directory path.
212 * Module names must be unique.
214 * @param string[] $directoryList A list of module locations
218 public function convertToNamespacedList($directoryList)
220 $namespacedArray = [];
221 foreach ((array)$directoryList as $directory) {
222 $namespacedArray[basename($directory)] = $directory;
224 return $namespacedArray;
228 * Search for command files in the specified locations. This is the function that
229 * should be used for all locations that are NOT modules of a framework.
231 * @param string|string[] $directoryList Places to search for commands.
234 public function discover($directoryList, $baseNamespace = '')
237 foreach ((array)$directoryList as $key => $directory) {
238 $itemsNamespace = $this->joinNamespace([$baseNamespace, $key]);
239 $commandFiles = array_merge(
241 $this->discoverCommandFiles($directory, $itemsNamespace),
242 $this->discoverCommandFiles("$directory/src", $itemsNamespace)
245 return $this->fixNamespaces($commandFiles);
249 * fixNamespaces will alter the namespaces in the commandFiles
250 * result to remove the Composer placement directory, if any.
252 protected function fixNamespaces($commandFiles)
254 // Do nothing unless the client told us to remove some namespace components.
255 if (empty($this->strippedNamespaces)) {
256 return $commandFiles;
259 // Strip out any part of the namespace the client did not want.
260 // @see CommandFileDiscovery::ignoreNamespacePart
264 array_keys($this->strippedNamespaces),
265 array_values($this->strippedNamespaces),
274 * Search for command files in specific locations within a single directory.
276 * In each location, we will accept only a few places where command files
277 * can be found. This will reduce the need to search through many unrelated
280 * The default search locations include:
286 * The pattern we will look for is any file whose name ends in 'Commands.php'.
287 * A list of paths to found files will be returned.
289 protected function discoverCommandFiles($directory, $baseNamespace)
292 // In the search location itself, we will search for command files
293 // immediately inside the directory only.
294 if ($this->includeFilesAtBase) {
295 $commandFiles = $this->discoverCommandFilesInLocation(
297 $this->getBaseDirectorySearchDepth(),
302 // In the other search locations,
303 foreach ($this->searchLocations as $location) {
304 $itemsNamespace = $this->joinNamespace([$baseNamespace, $location]);
305 $commandFiles = array_merge(
307 $this->discoverCommandFilesInLocation(
308 "$directory/$location",
309 $this->getSearchDepth(),
314 return $commandFiles;
318 * Return a Finder search depth appropriate for our selected search depth.
322 protected function getSearchDepth()
324 return $this->searchDepth <= 0 ? '== 0' : '<= ' . $this->searchDepth;
328 * Return a Finder search depth for the base directory. If the
329 * searchLocations array has been populated, then we will only search
330 * for files immediately inside the base directory; no traversal into
331 * deeper directories will be done, as that would conflict with the
332 * specification provided by the search locations. If there is no
333 * search location, then we will search to whatever depth was specified
338 protected function getBaseDirectorySearchDepth()
340 if (!empty($this->searchLocations)) {
343 return $this->getSearchDepth();
347 * Search for command files in just one particular location. Returns
348 * an associative array mapping from the pathname of the file to the
349 * classname that it contains. The pathname may be ignored if the search
350 * location is included in the autoloader.
352 * @param string $directory The location to search
353 * @param string $depth How deep to search (e.g. '== 0' or '< 2')
354 * @param string $baseNamespace Namespace to prepend to each classname
358 protected function discoverCommandFilesInLocation($directory, $depth, $baseNamespace)
360 if (!is_dir($directory)) {
363 $finder = $this->createFinder($directory, $depth);
366 foreach ($finder as $file) {
367 $relativePathName = $file->getRelativePathname();
368 $relativeNamespaceAndClassname = str_replace(
373 $classname = $this->joinNamespace([$baseNamespace, $relativeNamespaceAndClassname]);
374 $commandFilePath = $this->joinPaths([$directory, $relativePathName]);
375 $commands[$commandFilePath] = $classname;
382 * Create a Finder object for use in searching a particular directory
385 * @param string $directory The location to search
386 * @param string $depth The depth limitation
390 protected function createFinder($directory, $depth)
392 $finder = new Finder();
394 ->name($this->searchPattern)
398 foreach ($this->excludeList as $item) {
399 $finder->exclude($item);
402 if ($this->followLinks) {
403 $finder->followLinks();
410 * Combine the items of the provied array into a backslash-separated
411 * namespace string. Empty and numeric items are omitted.
413 * @param array $namespaceParts List of components of a namespace
417 protected function joinNamespace(array $namespaceParts)
419 return $this->joinParts(
423 return !is_numeric($item) && !empty($item);
429 * Combine the items of the provied array into a slash-separated
430 * pathname. Empty items are omitted.
432 * @param array $pathParts List of components of a path
436 protected function joinPaths(array $pathParts)
438 $path = $this->joinParts(
442 return !empty($item);
445 return str_replace(DIRECTORY_SEPARATOR, '/', $path);
449 * Simple wrapper around implode and array_filter.
451 * @param string $delimiter
452 * @param array $parts
453 * @param callable $filterFunction
455 protected function joinParts($delimiter, $parts, $filterFunction)
458 function ($item) use ($delimiter) {
459 return rtrim($item, $delimiter);
465 array_filter($parts, $filterFunction)