Sunday, March 26, 2023
Learning Code
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#
No Result
View All Result
Learning Code
No Result
View All Result
Home Swift

How to write Swift scripts using the new Command API in Vapor 4?

learningcode_x1mckf by learningcode_x1mckf
September 24, 2022
in Swift
0
How to write Swift scripts using the new Command API in Vapor 4?
74
SHARES
1.2k
VIEWS
Share on FacebookShare on Twitter


2020/03/03

Shell scripts are necessities on the server aspect. Learn to construct Swift scripts in your backend apps utilizing property wrappers.

Vapor

Swift Argument Parser vs Vapor Instructions

Apple open-sourced a brand new library that may assist you numerous if you wish to construct scripts that written in Swift. The Swift Argument Parser was beforehand a part of the Swift Package deal Supervisor instruments, however now it’s even highly effective & has it is personal life (I imply repository). 😉

Then again Vapor already had a considerably related method to construct scripts, however in Vapor 4 the Command API is healthier than ever. Property Wrappers (obtainable from Swift 5.1) are utilized in each instances to deal with arguments, flags & choices. Personally I like this method loads.

Let me present you a easy howdy command:


import ArgumentParser

struct HelloCommand: ParsableCommand 
    @Argument(assist: "The title to say howdy")
    var title: String

    func run() throws 
        print("Hey (self.title)!")
    

HelloCommand.most important()

Now I will present you learn how to implement an analogous command using Vapor:


import Vapor

last class HelloCommand: Command 
    
    let assist = "This command will say howdy to a given title."

    struct Signature: CommandSignature 
        @Argument(title: "title", assist: "The title to say howdy")
        var title: String
    

    func run(utilizing context: CommandContext, signature: Signature) throws 
        print("Hey (signature.title)!")
    


public func configure(_ app: Software) throws 
    app.instructions.use(HelloCommand(), as: "howdy")


As you possibly can see they virtually seem like the identical.


For those who love scripting, it is best to positively verify swift-sh and Brisk


The Swift Argument Parser library is a light-weight resolution if you’re solely in search of a easy Swift script. A very good instance is a instrument that manipulates recordsdata on the system or one thing related. It is only one little dependency, however it removes a lot boilerplate out of your scripts. It lets you deal with the script itself, as an alternative of parsing the command line inputs. Yow will discover extra detailed examples and an in depth documentation contained in the GitHub repository. 🙏


Vapor’s Command API is helpful if you wish to carry out extra sophisticated duties together with your scripts. Something that is a part of your Vapor software could be triggered from a command, so you possibly can simply create a backend instrument that reads (or writes) data from the database using Fluent 4. That is the principle benefit of utilizing a Vapor command, as an alternative a stanadlone Swift script.




Arguments, choices, flags

Let’s lengthen the howdy command with a brand new possibility and a flag. The primary distinction between an possibility and a flag is that an possibility has an related worth, however a flag is simply one thing that you simply give to the command or not. Each choices and flags begin with a single - or a double sprint --, often the only dashed model makes use of a brief title for a similar factor. 🤓

Arguments are consumer supplied values learn so as (eg.: ./howdy joe bob john).

Now that the essential definitions, right here is the instance:

last class HelloCommand: Command 
        
    struct Signature: CommandSignature 

        @Argument(title: "title", assist: "The title to say howdy")
        var title: String

        @Possibility(title: "greeting", brief: "g", assist: "Greeting used")
        var greeting: String?

        @Flag(title: "capitalize", brief: "c", assist: "Capitalizes the title")
        var capitalize: Bool
    

    let assist = "This command will say howdy to a given title."

    func run(utilizing context: CommandContext, signature: Signature) throws 
        let greeting = signature.greeting ?? "Hey"
        var title = signature.title
        if signature.capitalize 
            title = title.capitalized
        
        print("(greeting) (title)!")
    

Arguments are required by default, choices and flags are optionals. You may have a customized title (brief and lengthy) for the whole lot, plus you possibly can customise the assistance message for each element.

swift run Run howdy john


swift run Run howdy john --greeting Hello


swift run Run howdy john --greeting Hello --capitalized


swift run Run howdy john -g Szia -c

You may name the command utilizing a number of kinds. Be at liberty to select a most popular model. ⭐️



Subcommands

When command-line applications develop bigger, it may be helpful to divide them into a bunch of smaller applications, offering an interface via subcommands. Utilities resembling git and the Swift bundle supervisor are capable of present different interfaces for every of their sub-functions by implementing subcommands resembling git department or swift bundle init.

Vapor can deal with command teams in a extremely cool means. I will add an additional static property to call our instructions, since I do not prefer to repeat myself or bloat the code with pointless strings:

last class HelloCommand: Command 
    
    static var title = "howdy"
        
    


struct WelcomeCommandGroup: CommandGroup 
    
    static var title = "welcome"

    let assist: String
    let instructions: [String: AnyCommand]
    
    var defaultCommand: AnyCommand? 
        self.instructions[HelloCommand.name]
    

    init() 
        self.assist = "search engine optimisation command group assist"

        self.instructions = [
            HelloCommand.name: HelloCommand(),
        ]
    


public func configure(_ app: Software) throws 

    app.instructions.use(WelcomeCommandGroup(), as: WelcomeCommandGroup.title)


That is it, we simply moved our howdy command beneath the welcome namespace.

swift run Run welcome howdy john --greeting "Hello" --capitalize

For those who learn the Swift Argument Parser docs, you possibly can obtain the very same habits via a customized CommandConfiguration. Personally, I favor Vapor’s method right here… 🤷‍♂️



Ready for async duties

Vapor builds on high of SwiftNIO together with EventLoops, Futures & Guarantees. Many of the API is asynchronous, however within the CLI world you need to await the async operations to complete.

last class TodoCommand: Command 
    
    static let title = "todo"

    struct Signature: CommandSignature  
        
    let assist = "This command will create a dummy Todo merchandise"

    func run(utilizing context: CommandContext, signature: Signature) throws 
        let app = context.software
        app.logger.discover("Creating todos...")
        
        let todo = Todo(title: "Look ahead to async duties...")
        attempt todo.create(on: app.db).wait()
        
        app.logger.discover("Todo is prepared.")
    

There’s a throwing wait() methodology that you may make the most of to “keep within the loop” till the whole lot is completed. You can even get a pointer for the appliance object through the use of the present context. The app has the database connection, so you possibly can inform Fluent to create a new model. Additionally you should utilize the built-in logger to print data to the console whereas the consumer waits. ⏳




Utilizing ConsoleKit with out Vapor

Let’s discuss overheads. Vapor comes with this neat instructions API, but additionally bundles numerous different core issues. What if I simply need the goodies for my Swift scripts? No drawback. You should use the underlying ConsoleKit by including it as a dependency.


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: [
        .target(name: "myProject", dependencies: [
            .product(name: "ConsoleKit", package: "console-kit"),
        ])
    ]
)

You continue to must do some extra work in your most important.swift file, however nothing critical:

import ConsoleKit
import Basis

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.")
    attempt console.run(group, enter: enter)

catch 
    console.error("(error)")
    exit(1)

This manner you possibly can eliminate many of the community associated core packages (which are included by default when you use Vapor). This method solely fetches swift-log as a 3rd social gathering dependency. 😍




Abstract

ConsoleKit in Vapor is a good way to write down CLI instruments and small scripts. The brand new Swift Argument Parser is a extra light-weight resolution for a similar drawback. In case your plan is to take care of databases via scripts otherwise you carry out numerous networking or asynchronous operations it could be higher to go along with Vapor, since you possibly can at all times develop by importing a brand new element from the ecosystem.




Source link

You might also like

Introducing – AI Utils for macOS

Encoding and decoding data using the Hummingbird framework

Hummingbird routing and requests – The.Swift.Dev.

Share30Tweet19
learningcode_x1mckf

learningcode_x1mckf

Recommended For You

Introducing – AI Utils for macOS

by learningcode_x1mckf
March 24, 2023
0
Introducing – AI Utils for macOS

⚠️ REQUIRES a FREE OpenAI API key. You will get one utilizing this hyperlink. ⚠️ Improve your productiveness with our AI powered utility application. - accessible...

Read more

Encoding and decoding data using the Hummingbird framework

by learningcode_x1mckf
March 22, 2023
0
Encoding and decoding data using the Hummingbird framework

HTTP is all about sending and receiving information over the community. Initially it was solely utilized to switch HTML paperwork, however these days we use HTTP to switch...

Read more

Hummingbird routing and requests – The.Swift.Dev.

by learningcode_x1mckf
March 17, 2023
0
Hummingbird routing and requests – The.Swift.Dev.

Routing on the server facet means the server goes to ship a response primarily based on the URL path that the consumer referred to as when firing up...

Read more

Building a Scrollable Custom Tab Bar in SwiftUI

by learningcode_x1mckf
March 10, 2023
0
Building a Scrollable Custom Tab Bar in SwiftUI

Whether or not you’re making a social media app or a productiveness device, the tab bar interface can improve the consumer expertise by making it extra intuitive and...

Read more

Beginner’s guide to server-side Swift using the Hummingbird framework

by learningcode_x1mckf
March 8, 2023
0
Beginner’s guide to server-side Swift using the Hummingbird framework

Swift on the Server in 2023 Three years in the past I began to focus on Vapor, the preferred web-framework written in Swift, which served me very...

Read more
Next Post
Middleware enterprise functionality comes to JavaScript, thanks to Vercel

Middleware enterprise functionality comes to JavaScript, thanks to Vercel

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Related News

How to Determine Which Element Has Focus in JavaScript

How JavaScript Works Behind the Scenes

October 3, 2022
The future of Leaf and Tau

The future of Leaf and Tau

September 17, 2022
Explaining Access Control Using Python & Cautiously Handling Pickles – The Real Python Podcast

Explaining Access Control Using Python & Cautiously Handling Pickles – The Real Python Podcast

September 30, 2022

Browse by Category

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

RECENT POSTS

  • 2023 Java roadmap for developers – TheServerSide.com
  • YS Jagan launches Ragi Java in Jagananna Gorumudda, says focused on intellectual development of students – The Hans India
  • Disadvantages of Java – TheServerSide.com

CATEGORIES

  • C#
  • C++
  • Java
  • JavaScript
  • Python
  • Swift

© 2022 Copyright Learning Code

No Result
View All Result
  • Home
  • JavaScript
  • Java
  • Python
  • Swift
  • C++
  • C#

© 2022 Copyright Learning Code

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?