These docs are for v0.12. Click to read the latest docs for v0.16.

Commands are triggered from the command line and are a good place to put your apps maintenance utilities.

Creating a Command

The following command creates test users.

struct CreateTestUser: Command {
    static let id: String = "create-test-user"

    static let signature: [Signature] = [
        Argument("name"),
        Option("repeat")
    ]

    static let help: [String] = [
        "creates test users"
    ]

    let app: Application
    init(app: Application) {
        self.app = app
    }

    func run() throws {
        guard let name = try argument("name").string else {
            throw CommandError.custom("Name wasn't string")
        }

        let amount = option("repeat").int ?? 1

        info("Creating \(amount) user(s)")

        for i in 0 ..< amount {
            let user = User(name: name)
            try user.save()
        }
    }
}

This command can be run on the command line using vapor run create-test-user John --repeat=5

You can also run it directly from the executable like .build/debug/App create-test-user John

app.commands.append(CreateTestUser)

You can then add your command to the application.

Options and Arguments

Use the static signature property to outline what arguments and options your command takes. This will be used to generate the signature in the help command. It will also be used to ensure your command receives the correct number of arguments.

let option = option("option-name") // Polymorphic?
let argument = try argument("argument-name") // Polymorphic

Although you can be sure arguments will be provided to your command, you might need to cast them to different types. Because of this, you should still provide a guard statement to ensure the correct type.

Printing

The following methods are available for printing.

print("Plain message")
info("Informational message")
warning("Warning message")
error("Error message")

Interaction

You can interact with the user and receive input using the ask() and confirm() commands.

guard let age = ask("What is your age?").int else {
    throw CommandError.custom("Age was not an integer")
}
guard confirm("Are you sure?") else {
    throw CommandError.custom("You were not sure!")
}

The confirm command will accept yes or no as well as y or n and is case-insensitive.