# Console

- [Introduction](#introduction)
- [Writing commands](#writing-commands)
    - [Arguments and options](#arguments-and-options)
    - [Exit status](#exit-status)
- [Registering commands](#registering-commands)
- [Writing output](#writing-output)
    - [Styled text](#styled-text)
    - [Quiet and verbose output](#quiet-and-verbose-output)
- [Prompting for input](#prompting-for-input)
    - [Validating answers](#validating-answers)
    - [Menus](#menus)
    - [Suggestions and multiline answers](#suggestions-and-multiline-answers)
    - [Running unattended](#running-unattended)
- [Showing progress](#showing-progress)
    - [Processing collections](#processing-collections)
    - [Running work with a spinner](#running-work-with-a-spinner)
- [Handling signals](#handling-signals)
    - [Long-running commands](#long-running-commands)
- [Background work](#background-work)
- [Testing commands](#testing-commands)

<a name="introduction"></a>

## Introduction


アプリケーションのすべての処理がHTTPリクエストで始まるわけではありません。毎晩CSVファイルを取り込んだり、古い下書きを削除したり、本番環境の数行を修正したりする場合があります。コンソールコマンドはアプリケーション自体のバイナリからこれらの処理を実行し、設定、サービス、モデルに完全にアクセスできます。


コマンドを指定せずにアプリケーションのバイナリを実行すると、アプリケーションを配信します。コマンド名を渡すと、代わりにそのコマンドを実行します。開発中は [Laravel CLI](/ja/go/docs/installation#installing-the-laravel-cli) を通して実行してください。CLIがアプリケーションをビルドし、指定したコマンドを実行します。

```shell
laravel serve                 # serve the application
laravel route:list            # run a command
laravel list                  # list every command
laravel help route:list       # show a command's help
```


本番では、`./app migrate --force` のように、ビルドしたバイナリに同じ引数を渡して実行します。


すべてのコマンドはアプリケーションを含むコンテキストを受け取るため、`config.From(ctx)`、データベースクエリ、[log channels](/ja/go/docs/logging) はハンドラと同じように動作します。受信するHTTPリクエストがないため、コマンドにはセッションもクッキーもありません。

<a name="writing-commands"></a>

## Writing commands


組み込みコマンドに加え、独自のコマンドも作成できます。新しいアプリケーションでは、`commands` パッケージ内の個別ファイルに各コマンドを配置します。新しいコマンドを作るには、実行時に入力する名前で `make:command` を実行します。

```shell
laravel make:command posts:prune
```


`make:command` は `commands/prune_posts.go` を作成し、アプリケーションが [registers](#registering-commands) する `commands/commands.go` の `All` 一覧にコマンドを追加します。コマンドは、実行時に入力する `Name`、`list` と `--help` に表示する `Description`、処理を実行する `Run` メソッドを持つ型です。たとえば次のコマンドは、しばらく誰も編集していない下書きを削除します。

```go
package commands

import (
	"context"
	"flag"

	"go.laravel.com/console"
	"go.laravel.com/date"
	"go.laravel.com/db"
)

// PrunePosts deletes stale drafts.
type PrunePosts struct {
	days int
}

func (*PrunePosts) Name() string        { return "posts:prune" }
func (*PrunePosts) Description() string { return "Delete drafts that nobody has edited in a while" }

func (p *PrunePosts) Flags(flags *flag.FlagSet) {
	flags.IntVar(&p.days, "days", 30, "Delete drafts last edited more than this many `days` ago")
}

func (p *PrunePosts) Run(ctx context.Context, c *console.Console) error {
	cutoff := date.Now(ctx).AddDate(0, 0, -p.days)

	deleted, err := db.Table("posts").
		WhereNull("published_at").
		Where("updated_at", "<", cutoff).
		Delete(ctx)
	if err != nil {
		return err
	}

	c.Successf("Deleted %d drafts.", deleted)

	return nil
}
```


コマンドを `All` 一覧に追加すると、実行したりヘルプを読んだりできます。

```shell
laravel posts:prune --days=90
laravel posts:prune --help
```


`Run` が受け取る `ctx` はハンドラの `r` と同様にアプリケーションを含むため、`ctx` で実行するクエリはアプリケーションのデータベースを使います。`services.From(ctx)` は、決済プロバイダのクライアントなど、アプリケーション独自の [services](/ja/go/docs/services) を返します。`*console.Console` の `c` は、コマンドの [output](#writing-output) を書き込み、[questions](#prompting-for-input) を尋ねます。

<a name="arguments-and-options"></a>

### Arguments and options


`Flags` メソッドは標準の `flag.FlagSet` にコマンドのオプションを宣言します。上の `--days` が `p.days` にバインドされるように、通常はコマンドのフィールドにバインドします。Laravelは `Run` を呼び出す前にオプションを解析し、`--help` に一覧表示します。各実行は宣言したデフォルト値から始まるため、ある実行で設定したオプションが次の実行に引き継がれることはありません。オプションがなければ `Flags` を省略してください。


公開する投稿のIDなど、オプションではない値が必要なコマンドもあります。Laravelはオプションの後の引数を `c.Args` に格納します。`Arguments` メソッドで説明すると、`--help` に表示され、必須引数がない場合にLaravelがステータス2で終了します。次のコマンドは受け取ったIDの投稿を公開し、公開済み投稿を再公開するための `--force` スイッチを受け付けます。

```go
package commands

import (
	"context"
	"flag"

	laravel "go.laravel.com"
	"go.laravel.com/console"
	"go.laravel.com/date"
	"go.laravel.com/db"
)

// PublishPosts publishes draft posts.
type PublishPosts struct {
	force bool
}

func (*PublishPosts) Name() string        { return "posts:publish" }
func (*PublishPosts) Description() string { return "Publish draft posts" }

func (p *PublishPosts) Flags(flags *flag.FlagSet) {
	flags.BoolVar(&p.force, "force", false, "Publish posts that are already published again")
}

func (*PublishPosts) Arguments() []laravel.Argument {
	return []laravel.Argument{
		{Name: "ID", Description: "The IDs of the posts to publish", Required: true, Many: true},
	}
}

func (p *PublishPosts) Run(ctx context.Context, c *console.Console) error {
	posts := db.Table("posts").WhereIn("id", c.Args)
	if !p.force {
		posts = posts.WhereNull("published_at")
	}

	published, err := posts.Update(ctx, db.Values{"published_at": date.Now(ctx)})
	if err != nil {
		return err
	}

	c.Successf("Published %d posts.", published)

	return nil
}
```

```shell
laravel posts:publish 3 7 12 --force
```


`Arguments` メソッドのないコマンドは引数を取らず、Laravelは渡された引数を拒否します。すべてのコマンドは [output](#quiet-and-verbose-output) 用の `-q`、`-v`、`-vv`、`-vvv`、[prompts](#running-unattended) 用の `-n`、ヘルプ用の `-h` も受け付けるため、これらの名前で独自のオプションを宣言できません。

<a name="exit-status"></a>

### Exit status


`Run` が `nil` を返すコマンドはステータス0で終了します。`Run` がエラーを返すかパニックすると、Laravelはエラーを表示し、報告フックで [reports](/ja/go/docs/errors#reporting-errors) して、ステータス1で終了します。そのため、夜間のインポートが読み取り先のサーバーに接続できない場合、エラーはcronログとエラートラッカーの両方に届き、返す前に自分で報告する必要はありません。存在しないオプションなどのコマンドラインの誤りはステータス2で終了し、コマンドの使用方法を表示します。


問題を見つけたら3で終了するチェックなど、コマンドを実行するスクリプトが独自のステータスを必要とする場合があります。ステータスを指定して `console.Exit` を返すと、Laravelは追加の表示や報告をせず、そのステータスで終了します。

```go
if len(problems) > 0 {
	c.Errorf("%d posts have broken links.", len(problems))

	return console.Exit(3)
}
```

<a name="registering-commands"></a>

## Registering commands


アプリケーションのコマンド一覧は `commands/commands.go` にあり、`make:command` が新しいコマンドを末尾に追加します。手動でコマンドを作った場合は、自分で `All` に追加してください。

```go
var All = []laravel.Command{
	&PrunePosts{},
	&PublishPosts{},
}
```


`bootstrap/app.go` は `Commands` オプションを通して一覧を登録します。

```go
func Options() laravel.Options {
	return laravel.Options{
		// ...
		Commands: commands.All,
	}
}
```


`list` コマンドは独自のコマンドをLaravelのコマンドと一緒に表示し、`posts` などコロンの前の接頭辞でグループ化します。よく使うコマンドには短い名前も付けられます。別名を列挙する `Aliases` メソッドを追加すると、コマンドのヘルプに表示されます。

```go
func (*PublishPosts) Aliases() []string { return []string{"publish"} }
```


[Packages](/ja/go/docs/packages#commands) もコマンドを追加できます。独自のコマンドがパッケージのコマンドと同名なら、独自のコマンドが置き換えます。Laravelのコマンドや別の独自コマンドと名前またはエイリアスが重複すると、アプリケーションは起動を拒否し、エラーに重複したコマンド名を表示します。


定期的にコマンドを実行するには、[task scheduler](/ja/go/docs/scheduling)に設定してください。

<a name="writing-output"></a>

## Writing output


コマンドの実行中は、実行者に現在の処理と完了した処理を知らせます。各メッセージは色付きのマーカーで始まります。メッセージは標準エラーへ、`Line` や `Table` の出力などの結果は標準出力へ送るため、出力をパイプで受け取るスクリプトには結果だけが渡ります。

```go
c.Info("Importing users...")
c.Step("Reading users.csv...")
c.Success("Imported.")

c.Warn("Skipping a duplicate.")
c.Error("Could not read users.csv.")
```


通常のテキストを1行書くには `Line`、空行には `NewLine` を使います。

```go
c.Line("Import complete.")
c.NewLine()
c.Line("Next steps...")
```


`Table` はヘッダの下に行を標準出力へ書き、端末の幅に合わせてセルを折り返します。ステータスなど値によってセルを色付けするには、`Paint` にセルとトーンを渡します。トーンには `console.Success`、`console.Warning`、`console.Error`、`console.Info`、`console.Accent`、`console.Muted` があり、列の位置は揃ったままです。

```go
c.Table([]string{"Invoice", "Status"}, [][]string{
	{"1024", c.Paint(console.Success, "Paid")},
	{"1025", c.Paint(console.Warning, "Overdue")},
})
```


各メソッドには、`fmt.Sprintf` のようにメッセージを整形する、名前が `f` で終わるバージョンがあります。

```go
c.Successf("Imported %d users.", imported)
c.Linef("%d rows skipped", skipped)
```


インストール後の次の手順など、タイトル付きのメッセージブロックを表示するには `Note` を使います。

```go
c.Note("Next steps", "Review your configuration, then run the import.")
```


`encoding/csv` のライタなど、`io.Writer` に書き込むライブラリには `c.Stdout()` を渡します。

<a name="styled-text"></a>

### Styled text


行の一部にスタイルを付けるには `Markup` を使います。タグはセミコロン区切りの `fg`、`bg`、`options` を受け付け、`</>` で閉じます。

```go
c.Markup("<fg=black;bg=cyan> Notice </> <fg=emerald-400;options=bold>Ready</>")

name, err := c.Ask(ctx, "What is your name?")
if err != nil {
	return err
}

c.Markup("<fg=sky-400>Hello, " + console.Escape(name) + ".</>")
```


色には `red` などのANSI名、`emerald-400` などの [Tailwind CSS colors](https://tailwindcss.com/docs/colors)、`#ff8800` などの16進コードを使えます。上のユーザーの回答など、自分が書いたものではないテキストは必ず `console.Escape` で包み、テキスト内の `<` がタグとして解釈されないようにしてください。出力先が端末でなければ、`Markup` はスタイルなしでテキストを書き込みます。

<a name="quiet-and-verbose-output"></a>

### Quiet and verbose output


すべてのコマンドは `--quiet`（`-q`）と `--verbose`（`-v`）を受け付けます。詳しい出力にするには `-v` を最大3回繰り返します。

```shell
laravel users:import -v
laravel users:import -vvv
laravel users:import --quiet
```


詳細出力でのみ表示する行は、`Verbose`、`VeryVerbose`、`Debug`、または名前が `f` で終わるバージョンで書きます。各行は、実行者がそのレベル以上を指定した場合にのみ表示されます。

```go
c.Info("Importing users...")
c.Verbose("Reading users.csv")
c.VeryVerbose("Checking each user record")
c.Debug("Using the CSV importer")
```

| オプション | 表示する出力 |
| --- | --- |
| `-q`, `--quiet` | `c.Error` とコマンドの失敗のみ。 |
| なし | 標準のメッセージ、結果、進捗。 |
| `-v` | `Verbose` の行を追加。 |
| `-vv` | `VeryVerbose` の行を追加。 |
| `-vvv` | `Debug` の行を追加。 |


クエリで件数を数えるなど、詳細情報の計算コストが高い場合は、先に `c.Verbosity` とレベルを比較してください。行が表示される場合だけクエリが実行されます。

```go
if c.Verbosity >= console.Verbose {
	count, err := db.Table("users").Count(ctx)
	if err != nil {
		return err
	}

	c.Verbosef("%d users before the import", count)
}
```

<a name="prompting-for-input"></a>

## Prompting for input


新しいユーザーの名前やメールアドレスなど、実行者の回答が必要な場合は質問できます。テキストには `Ask`、パスワードなど入力中に隠す値には `Secret`、はい・いいえの質問には `Confirm` を使います。

```go
package commands

import (
	"context"

	"go.laravel.com/console"
	"go.laravel.com/db"
	"go.laravel.com/hash"
)

// CreateUser creates a user.
type CreateUser struct{}

func (*CreateUser) Name() string        { return "user:create" }
func (*CreateUser) Description() string { return "Create a user" }

func (*CreateUser) Run(ctx context.Context, c *console.Console) error {
	name, err := c.Ask(ctx, "What is the user's name?", console.Required())
	if err != nil {
		return err
	}

	email, err := c.Ask(ctx, "What is their email address?", console.Required())
	if err != nil {
		return err
	}

	password, err := c.Secret(ctx, "Choose a password", console.Required())
	if err != nil {
		return err
	}

	create, err := c.Confirm(ctx, "Create the user?", true)
	if err != nil || !create {
		return err
	}

	hashed, err := hash.Make(ctx, password)
	if err != nil {
		return err
	}

	err = db.Table("users").Insert(ctx, db.Values{"name": name, "email": email, "password": hashed})
	if err != nil {
		return err
	}

	c.Success("User created.")

	return nil
}
```


`Ask` と `Secret` は `string`、`Confirm` は `bool` を返します。`Confirm` の最後の引数は、Enterを押したときに選ばれる回答です。Enterで受け入れられるデフォルト値を `Ask` に指定するには、`console.Default` を渡します。

```go
queue, err := c.Ask(ctx, "Which queue?", console.Default("default"))
```


各プロンプトはコマンドのコンテキストを受け取ります。入力中にCtrl+Cを押すと、プロンプトはコンテキストのエラーを返します。そのエラーを返すと、エラーを報告せずにコマンドがステータス130で終了します。

<a name="validating-answers"></a>

### Validating answers


`console.Required()` を渡すと空の回答を拒否します。独自のルールには、回答が無効なときにエラーを返す関数を `console.Validate` に渡します。プロンプトはエラーメッセージを表示し、有効な回答が得られるまで再度質問します。

```go
email, err := c.Ask(ctx, "What is their email address?",
	console.Placeholder("you@example.com"),
	console.Required(),
	console.Validate(func(email string) error {
		if !strings.Contains(email, "@") {
			return errors.New("Enter an email address.")
		}

		return nil
	}),
)
```


`console.Placeholder` は空の回答欄に薄い色の例文を表示しますが、それを回答にはしません。`console.Hint` は、回答の用途などを質問の下に1行表示します。

```go
email, err := c.Ask(ctx, "What is their email address?",
	console.Hint("We'll send the welcome email here."),
)
```

<a name="menus"></a>

### Menus


環境など、いくつかの値から回答を選ぶ場合はメニューを表示します。`Choice` は矢印キーで1つを選択させ、その値を返します。`MultiChoice` はスペースキーで複数選択でき、列挙した順序で選択値を返します。

```go
env, err := c.Choice(ctx, "Which environment?", []string{"production", "staging"},
	console.Default("staging"),
)
if err != nil {
	return err
}

roles, err := c.MultiChoice(ctx, "Which roles?", []string{"admin", "editor", "viewer"},
	console.Defaults("editor"),
)
```


デフォルト値は選択肢のいずれかである必要があります。`console.Defaults` は、`MultiChoice` で初めから選択する項目を指定します。どちらのメニューにも `console.Searchable()` を追加すると、入力で選択肢を絞り込めます。`console.Required()` を追加すると、`MultiChoice` で最低1つの選択が必要になります。


独自の環境定数や、名前に対応するレコードのIDなど、選択肢のラベルと戻り値を変えたい場合は、`c.Select` に `console.Item` の値を渡します。各項目には `Select` が返す `Value`、メニューに表示する `Label`、ラベルの横に薄く表示する任意の `Hint` があります。

```go
type Environment int

const (
	Production Environment = iota + 1
	Staging
)

env, err := c.Select(ctx, "Which environment?", []console.Item[Environment]{
	{Value: Production, Label: "Production", Hint: "Live customer traffic"},
	{Value: Staging, Label: "Staging", Hint: "Testing environment"},
}, console.Default(Staging))
```


`c.MultiSelect` は複数の選択肢に対して同じ処理を行い、その値を返します。デフォルト値とバリデーション関数には、ラベルではなく `Staging` などの項目の値を使います。

<a name="suggestions-and-multiline-answers"></a>

### Suggestions and multiline answers


`Ask` は入力中に回答候補を提示できます。`console.Suggest` で固定の一覧を使うか、`console.SuggestFunc` で現在までの入力を受け取る関数を使います。Tabで強調表示された候補を選べます。

```go
language, err := c.Ask(ctx, "Which language?", console.Suggest("Go", "Python", "TypeScript"))
if err != nil {
	return err
}

emails, err := db.Table("users").Pluck[string](ctx, "email")
if err != nil {
	return err
}

email, err := c.Ask(ctx, "Which user?", console.SuggestFunc(func(input string) []string {
	var matches []string
	for _, email := range emails {
		if strings.HasPrefix(email, input) {
			matches = append(matches, email)
		}
	}

	return matches
}))
```


候補は入力できる値を制限しません。回答を既知の選択肢に一致させる必要があれば、`console.Validate` を追加してください。関数はキーを押すたびに実行されます。関数内でデータベースにクエリする代わりに、このコマンドが `emails` を読み込むように、必要な情報を先に読み込んでください。


長い回答には `console.Multiline()` を追加します。Enterで改行し、Escapeで回答全体を表示します。その後Enterで送信します。

```go
description, err := c.Ask(ctx, "Describe your project", console.Multiline())
```

<a name="running-unattended"></a>

### Running unattended


デプロイスクリプトやcronジョブがコマンドを実行するときは、プロンプトに答える人がいません。`--no-interaction`（`-n`）を渡すと、各プロンプトがデフォルト値を使います。標準入力が端末でない場合もLaravelは同様に処理します。このときデフォルト値のないプロンプトは失敗し、エラーに質問が表示されます。無人で実行する可能性があるコマンドでは、各プロンプトにデフォルト値を指定するか、`migrate --force` が確認を省略するように、プロンプトを省略するオプションを設けてください。


`--quiet` だけではプロンプトが無効にならないため、完全な無人実行では両方のオプションを渡します。

```shell
laravel user:create --quiet --no-interaction
```

<a name="showing-progress"></a>

## Showing progress


コマンドが数千件のレコードを処理するとき、進捗バーで実行者に進み具合を示せます。項目の総数が分かる場合は進捗バー、分からない場合はスピナーを使います。たとえば次のコマンドは、未公開の下書きを削除しながら進捗バーを進めます。

```go
package commands

import (
	"context"

	"go.laravel.com/console"
	"go.laravel.com/model"

	"app/models"
)

// PrunePosts deletes unpublished drafts.
type PrunePosts struct{}

func (*PrunePosts) Name() string        { return "posts:prune" }
func (*PrunePosts) Description() string { return "Delete every unpublished draft" }

func (*PrunePosts) Run(ctx context.Context, c *console.Console) error {
	drafts, err := model.Query[models.Post]().WhereNull("published_at").Get(ctx)
	if err != nil {
		return err
	}

	bar := c.Progress(len(drafts), "Deleting drafts...")

	for _, draft := range drafts {
		if err := model.Delete(ctx, &draft); err != nil {
			bar.Fail("Couldn't delete the drafts.")

			return err
		}

		bar.Advance(1)
	}

	bar.Finish("Drafts deleted.")

	return nil
}
```


スピナーも総数を指定しない点以外は同じライフサイクルです。

```go
spinner := c.Spinner("Loading users...")

users, err := model.Query[models.User]().Get(ctx)
if err != nil {
	spinner.Fail("Couldn't load the users.")

	return err
}

spinner.Finish("Users loaded.")
```


表示ラベルを変えるには `Message`、その下に薄い文字を表示するには `Hint` を呼び出します。すべての進捗バーやスピナーを `Finish`、`Cancel`、`Fail` のいずれかで終了してください。これらは端末の表示だけを変えるため、コマンド自体も失敗させるには `Run` からエラーを返します。`Advance` は複数のゴルーチンから同時に呼び出せます。


進捗バーやスピナーの表示中、`c.Warn` などのメッセージはその上に表示されます。質問は開始前に済ませ、表示は一度に1つにしてください。ログファイルなど出力先が端末でない場合、進捗バーは終了時のメッセージだけを表示します。

<a name="processing-collections"></a>

### Processing collections


`c.ProgressEach` はスライスの各項目に関数を実行し、項目ごとに進捗バーを進めます。次は `ProgressEach` で記述した `posts:prune` です。

```go
drafts, err := model.Query[models.Post]().WhereNull("published_at").Get(ctx)
if err != nil {
	return err
}

return c.ProgressEach(
	"Deleting drafts...",
	drafts,
	func(draft models.Post, bar *console.Progress) error {
		bar.Message("Deleting " + draft.Title + "...")

		return model.Delete(ctx, &draft)
	},
)
```


関数がエラーを返すと、`ProgressEach` は直ちに停止し、進捗バーを失敗表示にしてエラーを返します。

<a name="running-work-with-a-spinner"></a>

### Running work with a spinner


関数の実行中にスピナーを表示し、関数の戻り値を返すには `c.Spin` を使います。

```go
users, err := c.Spin("Loading users...", func() ([]models.User, error) {
	return model.Query[models.User]().Get(ctx)
})
```


関数がエラーを返すと、スピナーが失敗を表示し、`Spin` はエラーを返します。


個別のゴルーチンで実行する処理など、1つの見出しの下に複数の進捗バーやスピナーを表示するには、`c.ProgressGroup` が返す `*console.ProgressGroup` から開始し、最後に `Finish` でグループを終了します。

<a name="handling-signals"></a>

## Handling signals


Ctrl+Cが押されるか、プロセスマネージャが `SIGTERM` を送ると、OSはコマンドにシグナルを送ります。デフォルトではLaravelが `Run` に渡したコンテキストを終了し、実行中のクエリが失敗します。コマンドがコンテキストのエラーをラップしたエラーを返すと、追加出力なしでステータス130で終了します。2回目のCtrl+Cでプロセスは直ちに終了します。


ステップの途中でコマンドを停止すべきでない場合もあります。現在の作業単位を終えてから終了するには、シグナルを捕捉します。`Signals` メソッドでシグナルを列挙すると、Laravelはコマンドのコンテキストを終了せずに `c.Signals` へ送るため、安全な区切りで停止できます。`console.ShutdownSignals()` は現在のプラットフォームの標準終了シグナル（Unixでは `os.Interrupt` と `SIGTERM`、Windowsでは `os.Interrupt`）を返します。たとえば次のコマンドは下書きを100件ずつ削除し、現在のページを完了した後に停止します。

```go
package commands

import (
	"context"
	"os"

	"go.laravel.com/console"
	"go.laravel.com/db"
)

// PrunePosts deletes unpublished drafts.
type PrunePosts struct{}

func (*PrunePosts) Name() string         { return "posts:prune" }
func (*PrunePosts) Description() string  { return "Delete every unpublished draft" }
func (*PrunePosts) Signals() []os.Signal { return console.ShutdownSignals() }

func (*PrunePosts) Run(ctx context.Context, c *console.Console) error {
	for {
		ids, err := db.Table("posts").
			WhereNull("published_at").
			OrderBy("id").
			Limit(100).
			Pluck[int64](ctx, "id")
		if err != nil || len(ids) == 0 {
			return err
		}

		if _, err := db.Table("posts").WhereIn("id", ids).Delete(ctx); err != nil {
			return err
		}

		select {
		case <-c.Signals:
			c.Info("Stopped. Run the command again to delete the rest.")

			return console.Exit(130)
		default:
		}
	}
}
```


シグナルの捕捉自体はコマンドを停止せず、終了ステータスも変更しません。2回目のCtrl+Cでもプロセスは終了しません。中断時に `console.Exit(130)` を返すと、Ctrl+Cの標準的なシェルの慣習に従い、呼び出し元のスクリプトに未完了を伝えられます。ただし、回答待ちのプロンプトはシグナルが届くと停止し、コマンドはステータス130で終了します。


`os.Interrupt` はすべてのプラットフォームでCtrl+Cを処理します。Unixでは `syscall.SIGTERM`、`syscall.SIGHUP`、`syscall.SIGQUIT`、`syscall.SIGUSR1`、`syscall.SIGUSR2` も捕捉できます。

<a name="long-running-commands"></a>

### Long-running commands


`serve`、`queue:work`、独自のフィードポーラーなどは、停止されるまで実行されます。`select` でコンテキストを待ち、終了したら戻ってください。デフォルトでは、Laravelはコマンドの全実行期間を1つの [trace](/ja/go/docs/tracing) スパン内で実行します。終了しないコマンドではスパンが永久に開いたままになり、すべての処理が1つの未完了トレースにまとめられます。`true` を返す `LongRunning` メソッドを追加すると、スパンなしで実行されます。

```go
package commands

import (
	"context"
	"time"

	"go.laravel.com/console"

	"app/feeds"
)

// WatchFeeds fetches new posts until it's stopped.
type WatchFeeds struct{}

func (*WatchFeeds) Name() string        { return "feeds:watch" }
func (*WatchFeeds) Description() string { return "Fetch new posts from every feed until stopped" }
func (*WatchFeeds) LongRunning() bool   { return true }

func (*WatchFeeds) Run(ctx context.Context, c *console.Console) error {
	ticker := time.NewTicker(5 * time.Minute)
	defer ticker.Stop()

	for {
		if err := feeds.Refresh(ctx); err != nil {
			return err
		}

		select {
		case <-ctx.Done():
			return nil
		case <-ticker.C:
		}
	}
}
```


決まった時刻だけに実行すればよい処理なら、[schedule](/ja/go/docs/scheduling) を使ってください。コマンドを常時動かすためのプロセスマネージャが不要になります。


データベースへ書き出すカウンタなど、定期的な保守が必要な状態を長時間実行するコマンドがメモリに保持する場合、`true` を返す `WithTicks` メソッドを追加して、そのコマンドの [ticks](/ja/go/docs/tasks#ticks) を有効にします。

```go
func (*WatchFeeds) LongRunning() bool { return true }
func (*WatchFeeds) WithTicks() bool   { return true }
```


これらのtick内では、`laravel.CurrentHost(ctx)` は `Command` が `"feeds:watch"` に設定された `HostCommand` を返します。`RunOnShutdown` が設定されたtickは、コマンド終了時に最後の1回を実行します。

<a name="background-work"></a>

## Background work


ハンドラが `r.Background` を呼び出すように、コンソールコマンドや [scheduled tasks](/ja/go/docs/scheduling) は `ctx` を `laravel.Background` に渡して [background work](/ja/go/docs/context#background-work) を開始できます。コマンドが戻った後、Laravelはバックグラウンド処理の完了を待ってからプロセスを終了します。たとえば次のコマンドは、バックグラウンドで投稿をWebhookへ通知します。

```go
package commands

import (
	"context"

	laravel "go.laravel.com"
	"go.laravel.com/console"
	"go.laravel.com/httpclient"
	"go.laravel.com/model"

	"app/models"
)

// AnnouncePost announces a published post.
type AnnouncePost struct{}

func (*AnnouncePost) Name() string        { return "posts:announce" }
func (*AnnouncePost) Description() string { return "Announce a post to the newsletter service" }

func (*AnnouncePost) Arguments() []laravel.Argument {
	return []laravel.Argument{
		{
			Name:        "ID",
			Description: "The ID of the post to announce",
			Required:    true,
		},
	}
}

func (*AnnouncePost) Run(ctx context.Context, c *console.Console) error {
	post, err := model.Find[models.Post](ctx, c.Args[0])
	if err != nil {
		return err
	}

	laravel.Background(ctx, func(ctx context.Context) error {
		_, err := httpclient.JSON(map[string]any{"post_id": post.ID, "title": post.Title}).
			EnsureSuccessful().
			Post(ctx, "https://example.com/webhooks/announcements")

		return err
	})

	c.Successf("Announcing %q.", post.Title)

	return nil
}
```


Laravelは最大 `SERVER_SHUTDOWN_TIMEOUT`（デフォルト20秒）待ち、その後まだ実行中の処理のコンテキストをキャンセルします。バックグラウンド処理のエラーやパニックはログに記録されますが、コマンドの終了ステータスは変えません。

<a name="testing-commands"></a>

## Testing commands


コマンドをテストするには、[`laraveltest.New`](/ja/go/docs/testing#configuring-your-tests) でテストクライアントを構築し、`Command` メソッドにコマンドライン（`laravel` の後の部分）を渡します。

```go
package feature_test

import (
	"testing"

	"go.laravel.com/date"
	"go.laravel.com/db"

	"app/tests"
)

func TestPruningDeletesOnlyStaleDrafts(t *testing.T) {
	client := tests.New(t)
	now := date.Now(client.Context())

	err := db.Table("posts").Insert(client.Context(),
		db.Values{"title": "Old draft", "updated_at": now.AddDate(0, -2, 0)},
		db.Values{"title": "Older draft", "updated_at": now.AddDate(0, -3, 0)},
		db.Values{"title": "New draft", "updated_at": now},
	)
	if err != nil {
		t.Fatal(err)
	}

	client.Command("posts:prune --days=30").
		AssertSuccessful().
		AssertErrorOutputContains("Deleted 2 drafts.")

	client.AssertDatabaseMissing("posts", db.Values{"title": "Old draft"})
	client.AssertDatabaseHas("posts", db.Values{"title": "New draft"})
}
```


コマンドはテストのプロセス内でテストクライアントのデータベースを使って実行されるため、テストが作成した行を参照できます。Laravelは標準出力と標準エラーを個別にキャプチャします。`Line` と `Table` の結果は標準出力（`AssertOutputContains`）へ、`Info`、`Success`、`Warn`、`Error` などのメッセージと `Run` が返すエラーは標準エラー（`AssertErrorOutputContains`）へ送られます。出力がないことは `AssertOutputMissing`、`AssertErrorOutputMissing`、`AssertNoOutput` で、終了ステータスは `AssertExitCode` または `AssertFailed` で確認します。


`Command` はコマンドラインを空白で分割し、引用符で囲んだ語を1つの引数にまとめます。正確な引数文字列を渡すには `CommandArgs` を使います。

```go
client.CommandArgs([]string{"posts:publish", "42", "--force"}).AssertSuccessful()
```


プロンプトをテストするには、コマンドが質問する順序で各質問に `laraveltest.Answer` を渡します。

```go
client.Command("user:create",
	laraveltest.Answer("What is the user's name?", "Taylor"),
	laraveltest.Answer("What is their email address?", "taylor@laravel.com"),
	laraveltest.Answer("Choose a password", "secret-password"),
	laraveltest.Answer("Create the user?", "yes"),
).AssertSuccessful()
```


`MultiChoice` には `"admin, editor"` のようなカンマ区切りの選択肢、`Select` や `MultiSelect` には `"Staging"` のような項目のラベル、複数行プロンプトには `\n` で結合した行で回答します。コマンドの質問が次の回答と一致しない場合や、回答を用意した質問をしない場合はテストが失敗します。回答を渡さなければ、`-n` と同様に各プロンプトがデフォルト値を使います。


シグナルの捕捉をテストするには、`laraveltest.Signal` で模擬シグナルを送ります。

```go
client.Command("posts:prune", laraveltest.Signal(os.Interrupt)).
	AssertExitCode(130).
	AssertErrorOutputContains("Stopped.")
```

> [!WARNING]
> コマンドはテストでも実際の処理を行います。たとえば、`--show` なしで `key:generate` を実行すると `.env` ファイルに書き込みます。`serve` はコンテキストが終了するまで戻らないため、ルートは [HTTP tests](/ja/go/docs/testing#making-requests) でテストしてください。