Browse Source

Merge pull request #10006 from cakephp/3.next-console-fix-default-description

Merge in defaults from subcommand for the parser description.
Mark Story 9 years ago
parent
commit
e08825e595

+ 30 - 0
src/Console/ConsoleOptionParser.php

@@ -582,6 +582,9 @@ class ConsoleOptionParser
                 'parser' => null
             ];
             $options += $defaults;
+
+            $options = $this->_mergeSubcommandHelpToParserDescription($options);
+
             $command = new ConsoleInputSubcommand($options);
         }
         $this->_subcommands[$name] = $command;
@@ -591,6 +594,33 @@ class ConsoleOptionParser
     }
 
     /**
+     * @param array $options Options
+     * @return array
+     */
+    protected function _mergeSubcommandHelpToParserDescription($options)
+    {
+        if (!$options['help']) {
+            return $options;
+        }
+
+        if ($options['parser'] instanceof self) {
+            if ($options['parser']->getDescription() !== null) {
+                return $options;
+            }
+
+            $options['parser']->setDescription($options['help']);
+
+            return $options;
+        }
+
+        $options['parser'] = [
+            'description' => $options['help']
+        ] + (array)$options['parser'];
+
+        return $options;
+    }
+
+    /**
      * Remove a subcommand from the option parser.
      *
      * @param string $name The subcommand name to remove.

+ 44 - 0
tests/TestCase/Console/ConsoleOptionParserTest.php

@@ -673,6 +673,8 @@ class ConsoleOptionParserTest extends TestCase
 
         $result = $parser->help('method');
         $expected = <<<TEXT
+This is another command
+
 <info>Usage:</info>
 cake mycommand method [--connection] [-h] [-0]
 
@@ -687,6 +689,48 @@ TEXT;
     }
 
     /**
+     * test that help() with a command param shows the help for a subcommand
+     *
+     * @return void
+     */
+    public function testHelpSubcommandHelpArray()
+    {
+        $subParser = [
+            'options' => [
+                'foo' => [
+                    'short' => 'f',
+                    'help' => 'Foo.',
+                    'boolean' => true,
+                ]
+            ],
+        ];
+
+        $parser = new ConsoleOptionParser('mycommand', false);
+        $parser->addSubcommand('method', [
+            'help' => 'This is a subcommand',
+            'parser' => $subParser
+        ])
+            ->addOption('test', ['help' => 'A test option.']);
+
+        $result = $parser->help('method');
+        $expected = <<<TEXT
+This is a subcommand
+
+<info>Usage:</info>
+cake mycommand method [-f] [-h] [-q] [-v]
+
+<info>Options:</info>
+
+--foo, -f      Foo.
+--help, -h     Display this help.
+--quiet, -q    Enable quiet output.
+--verbose, -v  Enable verbose output.
+
+TEXT;
+        $this->assertTextEquals($expected, $result, 'Help is not correct.');
+    }
+
+    /**
      * test building a parser from an array.
      *
      * @return void