IOS developer based in barcelona.

Command-line scripts in Swift - Swift Package Manager

This post is about Swift Package Manager and how you can execute command-lines in Swift. For example: creating folders, network status, git commands, etc. I have created two simple methods in order to achieve this goal.

It's super easy, the next snippet is all you need

import Foundation

extension Process {
    public func shell(command: String) -> String {
        launchPath = "/bin/bash"
        arguments = ["-c", command]
        
        let outputPipe = Pipe()
        standardOutput = outputPipe
        launch()
        
        let data = outputPipe.fileHandleForReading.readDataToEndOfFile()
        guard let outputData = String(data: data, encoding: String.Encoding.utf8) else { return "" }
        
        return outputData.characters.reduce("") { (result, value) in
            return result + String(value)
        }
    }
}


public func launch(command: String, arguments: [String]) -> String {
    let process = Process()
    let command = "\(command) \(arguments.joined(separator: " "))"
    return process.shell(command: command)
}

I've created an extension of Process and a new instance of Pipe to print the command line output. Where are we gonna add this code? Swift Package Manager to the rescue. To create your custom script with SPM you need to execute the next command:

swift package init --type executable

Automatically a bunch of  new files and folders are created. You need to create and add the first snippet in SwiftShell

and you will add the code below in Main

let currentBranch = launch(command: "git", arguments: "describe", "--contains", "--all", "HEAD")
print("current branch:\(currentBranch)")

let newFolder = launch(command: "mkdir", arguments: "MyFolder")
print("Create folder \(newFolder)")

let interface = launch(command: "ifconfig", arguments: "")
print("Interface \(interface)")

The next step is building the package and execute it! Executing this command will show any compilation error (in another post I will show how to debug the code with breakpoints)

swift build

and the next one to execute it

.build/debug/SwiftShell
 Result from executing  .build/debug/SwiftShell

Result from executing .build/debug/SwiftShell

You can find all the code on Github, and if you want to use it, the installation is super easy, you only need to add in your Package file:

.Package(url: "https://github.com/MoralAlberto/SwiftShell.git", majorVersion: 1) to your Package.swift

and update all your dependencies with:

swift package update

I'm all ears to know your feedback, thanks for reading! 😃

Interceptors in your URLRequest

Get data from Instagram's private API