Vapor(七)工具篇

  1. Terminal
  2. Command
  3. Crypto

搬最后一篇关于Vapor的砖,介绍一下Vapor中可选用的工具,包括Command、Console、Crypto。

Terminal

Terminal和Console二选一使用,两者只是创建方式不一样

import Vapor

let terminal = Terminal()
print(terminal is Console) // true
terminal.print("Hello")

let console = try req.make(Console.self)
console.print("Hello")

无论是使用 print(_ :) 还是 warning(_ :),实质都是调用强大的output(_:)实现

/// Prints "Hello, world", but the word 'world' is blue.
console.output("Hello, " + "world".consoleText(color: .blue))

也可以使用Log,实现Logger协议来自定义输出的信息,默认有效的是PrintLogger

let logger = try req.make(Logger.self)
logger.info("Logger created!")

输入

/// Accepts input from the terminal until the first newline.
let input = console.input()
console.print("You wrote: \(input)")

/// Outputs the prompt then requests input.
let name = console.ask("What is your name?")
console.print("You said: \(name)")

/// Prompts the user for yes / no input.
if console.confirm("Are you sure?") {
    // they are sure
} else {
    // don't do it!
}

SPM

let package = Package(
    name: "Project",
    dependencies: [
        ...
        /// 💻 APIs for creating interactive CLI tools.
        .package(url: "https://github.com/vapor/console.git", from: "3.0.0"),
    ],
    targets: [
      .target(name: "Project", dependencies: ["Console","Logging", ... ])
    ]
)

Command

命令行工具

/// Generates ASCII picture of a cow with a message.
struct CowsayCommand: Command {
    var arguments: [CommandArgument] {
        return [.argument(name: "message")]
    }

	var options: [CommandOption] {
        return [
            .value(name: "eyes", short: "e", default: "oo", help: ["Change cow's eyes"]),
            .value(name: "tongue", short: "t", default: " ", help: ["Change cow's tongue"]),
        ]
    }

	var help: [String] {
        return ["Generates ASCII picture of a cow with a message."]
    }

    /// See `Command`.
    func run(using context: CommandContext) throws -> Future<Void> {
        let message = try context.argument("message")
        /// We can use requireOption here since both options have default values
        let eyes = try context.requireOption("eyes")
        let tongue = try context.requireOption("tongue")
        let padding = String(repeating: "-", count: message.count)
        let text: String = """
          \(padding)
        < \(message) >
          \(padding)
                  \\   ^__^
                   \\  (\(eyes)\\_______
                      (__)\\       )\\/\\
                        \(tongue)  ||----w |
                           ||     ||
        """
        context.console.print(text)
        return .done(on: context.container)
    }
}

//in configure.swift
/// Create a `CommandConfig` with default commands.
var commandConfig = CommandConfig.default()
/// Add the `CowsayCommand`.
commandConfig.use(CowsayCommand(), as: "cowsay")
/// Register this `CommandConfig` to services.
services.register(commandConfig)
$ swift run Run xxx --help
$ swift run Run cowsay 'Good job!' -e ^^ -t U

SPM

let package = Package(
    name: "Project",
    dependencies: [
        ...
        /// 💻 APIs for creating interactive CLI tools.
        .package(url: "https://github.com/vapor/console.git", from: "3.0.0"),
    ],
    targets: [
      .target(name: "Project", dependencies: ["Command", ... ])
    ]
)

Crypto

待完成。


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 mingfungliu@gmail.com

文章标题:Vapor(七)工具篇

文章字数:552

本文作者:Mingfung

发布时间:2018-08-21, 23:02:00

最后更新:2018-08-28, 22:26:38

原始链接:http://blog.ifungfay.com/后端/Vapor(七)工具篇/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏

宝贝回家