WP-CLI の自作コマンドで例えばファイルを生成したい時に既存のファイルを上書きする?って聞きたいことがありますよね!?
そんな時は以下のような感じの行を追加する。
$should_write_file = cli\confirm( 'Do you want to overwrite', false );
するとコマンドを実行した時に以下のような感じで Yes
か No
かを聞いてきます。
$ wp scaffold movefile
Warning: File already exists.
Do you want to overwrite? [y/N]
y
か n
を入力してエンターすると、$should_write_file
に true
または 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
と入力した場合で、あらかじめ置いてあるファイルの中のコンテンツを確認して、期待通りになっているかを見ています。