Swift utilities for running commands.

Overview

Swift Commands

SPM CocoaPods CI Status License Platform

Swift utilities for running commands.

The Commands module allows you to take a system command as a string and return the standard output.

API documentation can be found here.

Usage

import Commands

Bash

Execute shell commands.

let result = Commands.Task.run("bash -c ls")

Or

let result = Commands.Task.run(["bash", "-c", "ls"])

Or

let result = Commands.Bash.run("ls")

Python

Execute python scripts.

let result = Commands.Task.run("python main.py")

Execute python commands.

let result = Commands.Task.run("python -c import base64; print(base64.b64encode('qiuzhifei').decode('ascii'))")

Or

let result = Commands.Python.run("import base64; print(base64.b64encode('qiuzhifei').decode('ascii'))")

Ruby

Execute ruby scripts.

let result = Commands.Task.run("ruby main.rb")

Execute ruby commands.

let result = Commands.Task.run("ruby -e require 'base64'; puts Base64.encode64('qiuzhifei')")

Or

let result = Commands.Ruby.run("require 'base64'; puts Base64.encode64('qiuzhifei')")

Alias

Create a shortcut name for a command.

let node = Commands.Alias("/usr/local/bin/node", dashc: "-e")
let result = node.run("console.log('qiuzhifei')")

Setting global environment variables

Commands.ENV.global["http_proxy"] = "http://127.0.0.1:7890"
Commands.ENV.global.add(PATH: "/Users/zhifeiqiu/.rvm/bin")

Making Commands

let request: Commands.Request = "ruby -v"

Or

let request: Commands.Request = ["ruby", "-v"]

Or

let request = Commands.Request(executableURL: "ruby", arguments: "-v")

Change environment variables

var request: Commands.Request = "ruby -v"
request.environment?.add(PATH: "/usr/local/bin")
request.environment?["http_proxy"] = "http://127.0.0.1:7890"
request.environment?["https_proxy"] = "http://127.0.0.1:7890"
request.environment?["all_proxy"] = "socks5://127.0.0.1:7890"

let result = Commands.Task.run(request)

Result Handler

Returns the Commands.Result of running cmd in a subprocess.

let result = Commands.Task.run("ruby -v")
switch result {
case .Success(let request, let response):
  debugPrint("command: \(request.absoluteCommand), success output: \(response.output)")
case .Failure(let request, let response):
  debugPrint("command: \(request.absoluteCommand), failure output: \(response.errorOutput)")
}

Adding Commands as a Dependency

To use the Commands library in a SwiftPM project, add the following line to the dependencies in your Package.swift file:

let package = Package(
    // name, platforms, products, etc.
    dependencies: [
        .package(url: "https://github.com/qiuzhifei/swift-commands", from: "0.6.0"),
        // other dependencies
    ],
    targets: [
        .target(name: "<command-line-tool>", dependencies: [
            .product(name: "Commands", package: "swift-commands"),
        ]),
        // other targets
    ]
)

CocoaPods (OS X 10.9+)

You can use CocoaPods to install Commands by adding it to your Podfile:

pod 'Commands',        '~> 0.6.0'

QuickStart

git clone https://github.com/QiuZhiFei/swift-commands
cd swift-commands && open Package.swift

References

Comments
  • 多个命令怎么组合?

    多个命令怎么组合?

    Commands.Task.run("cd \(path)")
    let result = Commands.Task.run("pod install")
    switch result {
        case .Success( let request, let response):    
                print( "command: \(request.absoluteCommand), Success output: \(response.errorOutput)")
        case .Failure(let request, let response):
                 print( "command: \(request.absoluteCommand), failure output: \(response.errorOutput)")
    }
    

    报错:command: pod install, failure output: The file “pod” doesn’t exist. 似乎是cd的操作独立于pod install导致的,请问这个要怎么处理?

    opened by vitasapple 4
  • java可以么?

    java可以么?

    好像拿不到结果

     let result = Commands.Task.run("java -version")
                switch result {
                case .Success(let request, let response):
                  debugPrint("command: \(request.absoluteCommand), success output: \(response.output)")
                case .Failure(let request, let response):
                  debugPrint("command: \(request.absoluteCommand), failure output: \(response.errorOutput)")
                }
    
    opened by qingweiSun 3
  • Process() not in scope issue

    Process() not in scope issue

    Hi @QiuZhiFei , I was trying to use this package so that I can run some command line stuff via swift to capture logs from an iPhone. But seems like there is an issue wherein it cannot find Process() in scope

    image

    Note: Swift Language Version is set to 5 in Build settings.

    Am I missing something here in terms of the usage? Any help would be appreciated. Thanks

    opened by gkvappium 1
  • mac应用执行pod相关命令报错

    mac应用执行pod相关命令报错

    下面是我的测试代码,我用rvm管理的ruby版本

    import Foundation
    import Commands
    
    Commands.ENV.global.add(PATH: "/Users/jensen/.rvm/gems/ruby-2.7.0/bin")
    var result = Commands.Task.run(["pod", "--version"])
    print("\(result.statusCode)")
    print("\(result.output)")
    print("\(result.errorOutput)")
    

    在命令行应用中可以正常执行,在我新建的mac app中报The file “pod” doesn’t exist. image

    帮忙看一下这是因为什么,感谢!

    opened by Zhangyanshen 1
  • Cannot run command from /usr/local/bin

    Cannot run command from /usr/local/bin

    When you install mysql with homebrew you have access to mysql.server command, start, stop ...

    but I cannot call it.

    default installation is /usr/local/bin/mysql.server

       let request = Commands.Request("mysql.server start")
                    //debugPrint(request)
                    request.environment?.add(PATH: "${PATH}:/usr/local/bin")
                     
                    let result = Commands.Task.run(request)
    
    //"command: mysql.server start, failure output: The file “mysql.server” doesn’t exist."
    
    

    with Commands.Bash..run(request) same.

    opened by flakerimi 1
Releases(0.6.0)
Owner
Phil
Phil
This app is a sample app that recognizes specific voice commands such as "make it red", "make it blue", "make it green", and "make it black" and change the background color of the view in the frame.

VoiceOperationSample This app is a sample app that recognizes specific voice commands such as "make it red", "make it blue", "make it green", and "mak

Takuya Aso 3 Dec 3, 2021
Util for executing shell commands, and getting the results easily(data, string, and any decodable).

ShellExecutor Util for executing shell commands, and getting the results easily(data, string, and any decodable). Requirements Xcode 14.0+ Swift 5.7+

Yozone Wang 2 Jul 30, 2022
A starting point to create CLI utilities with swift

cli tuist template A starting point to create CLI utilities with swift Installation Just create a Tuist folder and a Templates folder inside it. Creat

humdrum 6 May 3, 2022
Tool for running macOS guest virtual machines in macOS 12 host or higher on M1 arm64 Macs

macosvm macosvm is a command line tool which allows creating and running of virtual machines on macOS 12 (Monterey) using the new Virtualization frame

Simon Urbanek 89 Jan 4, 2023
Linenoise-Swift A pure Swift implementation of the Linenoise library. A minimal, zero-config readline replacement.

Linenoise-Swift A pure Swift implementation of the Linenoise library. A minimal, zero-config readline replacement. Supports Mac OS and Linux Line edit

Andy Best 114 Dec 14, 2022
Swift tool to generate Module Interfaces for Swift projects.

ModuleInterface Swift tool to generate Module Interfaces for Swift projects. What is a Module Interface A Module Interface is what we commonly get usi

Jorge Revuelta 75 Dec 21, 2022
Swift-cli - Example of building command-line tools in Swift

swift-cli Example of building command-line tools in Swift Step 1: Create CLI wit

Noah Gift 2 Jan 17, 2022
Compose beautiful command line interfaces in Swift

Commander is a small Swift framework allowing you to craft beautiful command line interfaces in a composable way. Usage Simple Hello World i

Kyle Fuller 1.5k Dec 29, 2022
CommandLineKit - A pure Swift library for creating command-line interfaces

CommandLineKit A pure Swift library for creating command-line interfaces. Note: This project is no longer maintained. It's preserved here for historic

Ben Gollmer 1.1k Dec 1, 2022
Guaka - Smart and beautiful POSIX compliant CLI framework for Swift.

Guaka - Smart and beautiful POSIX compliant CLI framework for Swift. It helps you create modern and familiar CLI apps in the vein of widely used proje

Omar Abdelhafith 1.1k Dec 24, 2022
Progress.swift ⌛ Add beautiful progress bars to your loops.

Progress.swift ⌛ Just wrap the SequenceType in your loop with the Progress SequenceType and you'll automatically get beautiful progress bars. Updating

Justus Kandzi 304 Dec 1, 2022
Straightforward, type-safe argument parsing for Swift

Swift Argument Parser Usage Begin by declaring a type that defines the information that you need to collect from the command line. Decorate each store

Apple 2.9k Jan 7, 2023
SwiftCLI - A powerful framework for developing CLIs in Swift

SwiftCLI A powerful framework for developing CLIs, from the simplest to the most complex, in Swift.

Jake Heiser 793 Jan 4, 2023
SwiftShell - A Swift framework for shell scripting.

Run shell commands | Parse command line arguments | Handle files and directories Swift 5.1 - 5.3 | Swift 4 | Swift 3 | Swift 2 SwiftShell A library fo

Kare Morstol 973 Jan 2, 2023
SwiftyTextTable - A lightweight Swift library for generating text tables

SwiftyTextTable A lightweight Swift library for generating text tables. Swift Language Support SwiftyTextTable is now Swift 4.0 compatible! The last r

Scott Hoyt 283 Dec 23, 2022
Shell scripting in Swift

Shwift Shell-scripting in Swift DISCLAIMER: Shwift depends on Swift's incoming concurrency features. As such, it requires a recent Swift toolchain, an

George Lyon 32 Sep 15, 2022
A CLI too powered by Swift to provision environments using an up.toml manifest file

tuist-up tuist up was originally a Tuist built-in command to provision environments by reading the requirements in a manifest file Setup.swift. Althou

Tuist 5 Mar 31, 2022
Terminal string styling for Swift.

Terminal string styling for Swift. Integration Swift Package Manager (SPM) You can use The Swift Package Manager to install ColorizeSwift by adding it

Michał Tynior 281 Dec 22, 2022
Simple & Elegant Command Line Interfaces in Swift

An elegant pure Swift library for building command line applications. Features Tons of class, but no classes. 100% organic pure value types. Auto gene

hypertalk 52 Nov 9, 2022