LoginSignup
1
1

More than 5 years have passed since last update.

自作 WP-CLI コマンドでプロンプトを出す

Last updated at Posted at 2016-10-14

WP-CLI の自作コマンドで例えばファイルを生成したい時に既存のファイルを上書きする?って聞きたいことがありますよね!?

そんな時は以下のような感じの行を追加する。

$should_write_file = cli\confirm( 'Do you want to overwrite', false );

するとコマンドを実行した時に以下のような感じで YesNo かを聞いてきます。

$ wp scaffold movefile 
Warning: File already exists.
Do you want to overwrite? [y/N]

yn を入力してエンターすると、$should_write_filetrue または false が格納されます。

それを判定して以下のようにファイルを生成するなりやめるなりします。

global $wp_filesystem;
WP_Filesystem();
$wp_filesystem->put_contents( $filename, $contents )

テストのやり方

WP-CLI では、Behat というツールを使ってテストするならわしになってて、そのテストは以下のように書きます。

Feature: Test that WP-CLI loads.


  Scenario: Overwrite Movefile by prompting yes
    Given a WP install
    And a Movefile file:
      """
      Hello
      """
    And a session file:
      """
      y
      """

    When I run `wp scaffold movefile < session`
    Then the return code should be 0
    And the Movefile file should exist
    And the Movefile file should contain:
      """
      local:
      """
    And STDOUT should contain:
      """
      Success:
      """

  Scenario: Don't overwrite Movefile
    Given a WP install
    And a Movefile file:
      """
      Hello
      """
    And a session file:
      """
      n
      """

    When I run `wp scaffold movefile < session`
    Then the return code should be 0
    And the Movefile file should exist
    And the Movefile file should contain:
      """
      Hello
      """
    And STDOUT should contain:
      """
      Success:
      """

この例では、2種類のテストをやってて、ひとつはプロンプトで y と入力した場合、もう一つは n と入力した場合で、あらかじめ置いてあるファイルの中のコンテンツを確認して、期待通りになっているかを見ています。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1