Easy methods to construct higher command line apps and instruments utilizing Swift?

0
3


The following tips will allow you to to create wonderful CLI instruments, utility apps, server aspect tasks or terminal scripts utilizing the Swift language.

Swift

Operating Swift recordsdata as scripts

It’s doable to run a Swift file straight from the command line in the event you add a hashbang to the start of the file. This fashion you do not have to manually compile the code utilizing the swiftc command. You’ll be able to merely give the file the executable permission flag and the system will name the Swift REPL beneath the hood, so our app could be evaluated robotically. ๐Ÿ”จ


#!/usr/bin/env swift

print("Good day, world!")


For instance this most important.swift file above could be marked as an executable file, and we are able to merely name it through the ./most important.swift command afterward (you simply have to make use of chmod just one time).


chmod +x most important.swift 
./most important.swift  


The great thing about this technique is you could quickly check your Swift command line snippets. You’ll be able to even place the completed Swift scripts beneath the /usr/native/bin/ listing with out the swift file extension to make them obtainable “globally” in your working system person. ๐Ÿ’ช




Utilizing command line arguments in Swift

The CommandLine enum makes it very straightforward to fetch the arguments handed to our Swift software or script. You’ll be able to entry each argument utilizing the arguments variable as an array of Strings, however it’s also doable to get the uncooked information utilizing the argc and unsafeArgv properties.


#!/usr/bin/env swift


let script = CommandLine.arguments[0]
print("Script:", script)


let inputArgs = CommandLine.arguments.dropFirst()
print("Variety of arguments:", inputArgs.rely)

print("Arguments:")
for arg in inputArgs {
    print("-", arg)
}


You must word that the primary argument is at all times the trail of the present script, so if you’re solely in search of the enter arguments you should utilize the dropFirst() technique to return a subset of the enter strings. Normally every argument is separated by an area character.


./most important.swift howdy world




In Xcode you possibly can add customized arguments beneath the Edit Scheme… menu merchandise while you click on on the present scheme, search for the Arguments tab and use the Arguments Handed On Launch part.



Course of information and atmosphere in Swift

Similar to we are able to entry command line arguments, it’s doable to look at the present course of together with some {hardware} data and atmosphere variables.


#!/usr/bin/env swift
import Basis

let information = ProcessInfo.processInfo

print("Course of information")
print("Course of identifier:", information.processIdentifier)
print("System uptime:", information.systemUptime)
print("Globally distinctive course of id string:", information.globallyUniqueString)
print("Course of title:", information.processName)

print("Software program information")
print("Host title:", information.hostName)
print("OS main model:", information.operatingSystemVersion.majorVersion)
print("OS model string", information.operatingSystemVersionString)

print("{Hardware} information")
print("Energetic processor rely:", information.activeProcessorCount)
print("Bodily reminiscence (bytes)", information.physicalMemory)


print("Arguments")
print(ProcessInfo.processInfo.arguments)

print("Surroundings")

print(information.atmosphere)


The atmosphere variables property is a Dictionary the place each the keys and the values can be found as strings, so that you might need to parse them if you’re in search of totally different worth sorts. You’ll be able to arrange atmosphere customized variables in Xcode identical to arguments, or you possibly can move them through the command line earlier than you execute the Swift script utilizing the export command.




Commonplace enter and output in Swift

You should utilize the print operate to put in writing textual content to the usual output, however it is best to word that the print operate has a variadic gadgets definition, so you possibly can move round a number of arguments and a customized separator & terminator parameter to show extra superior outputs.


There’s additionally a typical error stream, which is a part of the normal streams in fact, however what’s attention-grabbing about it’s you could additionally write to this channel by the FileHandle.standardError property there’s fairly a sublime resolution on a Stack Overflow thread initially created by Rob Napier, I will embody that one right here as effectively. ๐Ÿ™


One other nice function of the print operate is the to parameter, which might settle for a customized TextOutputStream so you possibly can wrap the stderr stream in a customized object or you can too create customized output handlers and separate your print statements e.g. by context in the event you want.


#!/usr/bin/env swift
import Basis


print("This", "is", "enjoyable", separator: "-", terminator: "!")


"This goes to the usual error output"
    .information(utilizing: .utf8)
    .map(FileHandle.standardError.write)


closing class StandardErrorOutputStream: TextOutputStream {
    func write(_ string: String) {
        FileHandle.standardError.write(Information(string.utf8))
    }
}

var outputStream = StandardErrorOutputStream()
print("That is additionally an error", to: &outputStream)



func clear() {
    print("u{1B}[2J")
    print("u{1B}[(1);(0)H", terminator: "")
}

print("foooooooooooooooooooooo")
clear()
print("Hello, world!")



print("u{1b}[31;1mu{1b}[40;1m("Hello, world!")u{1b}[m")
print("u{1b}[32;1m("Hello, world!")u{1b}[m")


print("Please enter your input:")
guard let input = readLine(strippingNewline: true) else {
    fatalError("Missing input")
}
print(input)


The second half of the snippet is full of ANSI escape codes which I like quite a lot, because it can make our terminal output quite beautiful. The only problem is that they don’t work in Xcode at all (come-on Apple, please support this…). You can clear the console or change the background / foreground color of the output by using these codes.


There are quite a lot of libraries on GitHub that you can use to print colorful output, for example ColorizeSwift, ANSITerminal, ANSIEscapeCode and many more cool ones.


The very last thing that I’d like to show you is the readLine function, which you can use to read a line from the standard input. This comes handy if you need to get user input from the command line.



Use an argument parser library


If you are looking for a type-safe argument parser written in Swift, you should definitely take a look at the Swift Argument Parser library. It is created and maintained by Apple, so it’s kind of an official solution for this particular issue, but IMHO it lacks some advanced features.


This is the main reason why I prefer the Vapor command API built on top of the ConsoleKit library. Both libraries can parse arguments, options and flags, but ConsoleKit is also capable of displaying progress indicators, it features multiple command groups, secure input, auto-completion, multiple log levels and many more.




import Foundation
import ConsoleKit

final class HelloCommand: Command {
        
    struct Signature: CommandSignature {

        @Argument(name: "name", help: "The name to say hello")
        var name: String

        @Option(name: "greeting", short: "g", help: "Greeting used")
        var greeting: String?

        @Flag(name: "capitalize", short: "c", help: "Capitalizes the name")
        var capitalize: Bool
    }

    static var name = "hello"
    let help = "This command will say hello to a given name."

    func run(using context: CommandContext, signature: Signature) throws {
        let greeting = signature.greeting ?? "Hello"
        var name = signature.name
        if signature.capitalize {
            name = name.capitalized
        }
        print("(greeting) (name)!")
        
        
        let bar = context.console.progressBar(title: "Hello")
        bar.start()
        
        bar.succeed()
        
        
        let foo = context.console.ask("What?")
        print(foo)
        
        
        let baz = context.console.ask("Secure what?", isSecure: true)
        print(baz)
        
        
        let c = context.console.choose("Make a choice", from: ["foo", "bar", "baz"])
        print(c)

        
    }
}


import Basis
import ConsoleKit

let console: Console = Terminal()
var enter = CommandInput(arguments: CommandLine.arguments)
var context = CommandContext(console: console, enter: enter)

var instructions = Instructions(enableAutocomplete: true)
instructions.use(HelloCommand(), as: HelloCommand.title, isDefault: false)

do {
    let group = instructions.group(assist: "Utilizing ConsoleKit with out Vapor.")
    strive console.run(group, enter: enter)
}
catch {
    console.error("(error)")
    exit(1)
}


You should utilize each resolution by the Swift Package deal Supervisor, the setup course of is kind of straightforward, you may discover extra tutorials concerning the Swift Argument Parser and I believe that it’s more durable to search out correct docs for ConsoleKit, so yeah… anyway, they’re nice libraries you will not remorse utilizing them. ๐Ÿ˜‰



Make the most of the Swift Package deal Supervisor

The Swift Package deal Supervisor is among the smartest thing concerning the Swift programming language. I actually find it irresistible and I exploit it nearly day-after-day. The truth that the bundle manifest file is outlined utilizing Swift itself makes it straightforward to make use of & perceive.



import PackageDescription

let bundle = Package deal(
    title: "myProject",
    platforms: [
        .macOS(.v10_15)
    ],
    dependencies: [
        .package(url: "https://github.com/vapor/console-kit", from: "4.1.0"),
    ],
    targets: [
        .executableTarget(name: "myProject",dependencies: [
            .product(name: "ConsoleKit", package: "console-kit"),
        ]),
        .testTarget(title: "myProjectTests", dependencies: ["myProject"]),
    ]
)


The bundle supervisor advanced rather a lot in the course of the previous few months, in the event you check out the Swift Evolution dashboard you possibly can monitor these adjustments, the newest replace was the introduction of customized, user-defined Package deal Collections, however if you’re in search of packages you possibly can at all times check out the Swift Package deal Index web site. ๐Ÿ‘




LEAVE A REPLY

Please enter your comment!
Please enter your name here