# 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](/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](/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](/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](/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](/go/docs/packages#commands)도 명령어를 추가할 수 있습니다. 직접 만든 명령어와 패키지 명령어의 이름이 같으면 직접 만든 명령어가 패키지 명령어를 대체합니다. Laravel 명령어나 다른 자체 명령어와 이름 또는 별칭이 같으면 애플리케이션이 시작되지 않고 오류에 중복 명령어 이름이 표시됩니다.


콘솔 명령어를 정기적으로 실행하려면 [task scheduler](/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.")
```


일반 텍스트 한 줄을 쓰려면 `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`를 최대 세 번 반복하세요.

```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`는 답변의 용도 같은 설명을 질문 아래 한 줄로 표시합니다.

```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`는 화살표 키로 하나를 선택하도록 하고 선택한 값을 반환합니다. `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`에서 최소 하나를 선택해야 합니다.


자체 환경 상수나 이름 옆의 레코드 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` 같은 명령어 메시지는 그 위에 나타납니다. 시작하기 전에 질문을 모두 마치고 한 번에 하나씩 표시하세요. 로그 파일처럼 출력 대상이 터미널이 아니면 진행률 표시줄은 종료 메시지만 표시합니다.

<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`은 오류를 반환합니다.


각각 별도의 고루틴에서 실행되는 작업처럼 하나의 제목 아래에 여러 진행률 표시줄과 스피너를 함께 표시하려면 `c.ProgressGroup`이 반환하는 `*console.ProgressGroup`에서 시작하세요. 그런 다음 `Finish`로 그룹을 종료하세요.

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

## Handling signals


사용자가 Ctrl+C를 누르거나 프로세스 관리자가 `SIGTERM`을 보내면 운영체제는 명령어에 시그널을 보냅니다. 기본적으로 Laravel은 이때 `Run`이 받은 컨텍스트를 종료하여 진행 중인 쿼리가 실패합니다. 명령어가 컨텍스트 오류를 감싼 오류를 반환하면 추가 출력 없이 상태 130으로 종료합니다. 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:
		}
	}
}
```


시그널 포착 자체로는 명령어가 멈추거나 종료 상태가 바뀌지 않으며 두 번째 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은 명령어의 전체 수명 동안 하나의 [trace](/go/docs/tracing) 스팬 안에서 명령어를 실행합니다. 종료되지 않는 명령어에서는 스팬이 계속 열려 있고 모든 작업이 하나의 미완료 트레이스로 묶입니다. `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](/go/docs/scheduling)을 사용하세요. 그러면 명령어를 계속 실행하기 위한 프로세스 관리자가 필요하지 않습니다.


데이터베이스로 내보낼 카운터처럼 장기 실행 명령어가 주기적으로 관리해야 하는 상태를 메모리에 보관한다면, `true`를 반환하는 `WithTicks` 메서드를 추가하여 해당 명령어에서 애플리케이션의 [ticks](/go/docs/tasks#ticks)를 활성화하세요.

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


이 틱 안에서 `laravel.CurrentHost(ctx)`는 `Command`가 `"feeds:watch"`로 설정된 `HostCommand`를 반환합니다. `RunOnShutdown`이 설정된 틱은 명령어가 종료될 때 마지막으로 한 번 실행됩니다.

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

## Background work


핸들러에서 `r.Background`를 호출하듯, 콘솔 명령어와 [scheduled tasks](/go/docs/scheduling)는 `ctx`를 `laravel.Background`에 전달하여 [background work](/go/docs/context#background-work)를 시작할 수 있습니다. 명령어가 반환되면 Laravel은 백그라운드 작업이 끝날 때까지 기다린 뒤 프로세스를 종료합니다. 예를 들어 다음 명령어는 백그라운드에서 웹훅으로 게시물을 알립니다.

```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`](/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`는 명령줄을 공백으로 나누며 따옴표로 묶은 단어들을 하나의 인수로 취급합니다. 정확한 인수 문자열을 전달하려면 `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](/go/docs/testing#making-requests)로 테스트하세요.