• Stars
    star
    1,197
  • Rank 39,089 (Top 0.8 %)
  • Language
    Swift
  • License
    MIT License
  • Created about 9 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Swiftline is a set of tools to help you create command line applications.

Build Status Platform Language: Swift CocoaPods Carthage GITTER: join chat GITTER: join chat

Swiftline is a set of tools to help you create command line applications. Swiftline is inspired by highline

Swiftline contains the following:

  • Colorize: Helps adding colors to strings written to the terminal
  • Ask , Choose and agree: Easily create prompt for asking the user more info
  • Run: A quick way to run an external command and read its standard output and standard error.
  • Env: Read and write environment variables ruby-flavored
  • Args: Parses command line arguments and return a hash of the passed flags

Contents

Usage Installation Examples Docs Tests

Usage

Colorize 🎨

Colorize helps styling the strings before printing them to the terminal. You can change the text color, the text background and the text style. Colorize works by extending String struct to add styling to it.

To change the text color, use either string.f or string.foreground:

print("Red String".f.Red)
print("Blue String".foreground.Blue)

To change the text background color, use either string.b or string.background:

print("I have a white background".b.White)
print("My background color is green".background.Green)

To change the text background style, use either string.s or string.style:

print("I am a bold string".s.Bold)
print("I have an underline".style.Underline)

You can compose foreground, background, and style:

print("I am an underlined red on white string".s.Underline.f.Red.b.White)

Ask, Choose, Agree ❓

Ask, Choose and Agree are used to prompt the user for more information.

Ask

Ask presents the user with a prompt and waits for the user input.

let userName = ask("Enter user name?")

userName will contain the name entered by the user

Ask can be used to ask for value of Int, Double or Float types, to ask for an integer for example:

let age = ask("How old are you?", type: Int.self)

If the user prints something thats not convertible to integer, a new prompt is displayed to him, this prompt will keep displaying until the user enters an Int:

How old are you?
None
You must enter a valid Integer.
?  Error
You must enter a valid Integer.
?  5
5

Validations are added by calling addInvalidCase on AskSettings.

let name = ask("Who are you?") { settings in
    settings.addInvalidCase("Snuffles is not allowed") { value in
        value.containsString("Snuffles")
    }
}

If the user entered Snuffles ask will keep displaying the invalid message passed to addInvalidCase

Who are you?
Snuffles
Snuffles is not allowed
?  Snuffles
Snuffles is not allowed
?  Snowball

Your name is Snowball

AskSettings.confirm will ask the user to confirm his choice after entering it

let name = ask("Who are you?") { settings in
    settings.confirm = true
}

The above will output:

Who are you?
Snuffles
Are you sure?  YES

Your name is Snuffles

Choose

Choose is used to prompt the user to select an item between several possible items.

To display a choice of programming lanaugage for example:

let choice = choose("Whats your favorite programming language? ",
    choices: "Swift", "Objective C", "Ruby", "Python", "Java :S")

This will print:

1. Swift
2. Objective C
3. Ruby
4. Python
5. Java :S
Whats your favorite programming language?

The user can either choose the numbers (1..5) or the item itself. If the user enters a wrong input. A prompt will keep showing until the user makes a correct choice

Whats your favorite programming language? JavaScript
You must choose one of [1, 2, 3, 4, 5, Swift, Objective C, Ruby, Python, Java :S].
?  BBB
You must choose one of [1, 2, 3, 4, 5, Swift, Objective C, Ruby, Python, Java :S].
?  Swift

You selected Swift, good choice!

You can customize the return value for each choice element. For example if you want to get an Int from the choice, you would do this

let choice = choose("Whats your favorite programming language? ", type: Int.self) { settings in
    settings.addChoice("Swift") { 42 }
    settings.addChoice("Objective C") { 20 }
}

The number on the left can be changed to letters, here is how you could do that:

let choice = choose("Whats your favorite programming language? ", type: String.self) { settings in
   //choice value will be set to GOOD
   settings.addChoice("Swift") { "GOOD" }

   //choice value will be set to BAD
   settings.addChoice("Java") { "BAD" }

   settings.index = .Letters
   settings.indexSuffix = " ----> "
   }

That will print:

a ----> Swift
b ----> Java
Whats your favorite programming language?

Agree

Agree is used to ask a user for a Yes/No question. It returns a boolean representing the user input.

let choice = agree("Are you sure you want to `rm -rf /` ?")

If the user enters any invalid input, agree will keep prompting him for a Yes/No question

Are you sure you want to `rm -rf /` ?  What!
Please enter "yes" or "no".
Are you sure you want to `rm -rf /` ?  Wait
Please enter "yes" or "no".
Are you sure you want to `rm -rf /` ?  No

You entered false

Run 🏃

Run provides a quick, concise way to run an external command and read its standard output and standard error.

To execute a simple command you would do:

let result = run("ls -all")
print(result.stdout)

result type is RunResults, it contains:

  • exitStatus: The command exit status
  • stdout: The standard output for the command executed
  • stderr: The standard error for the command executed

While run("command") can split the arguments by spaces. Some times argument splitting is not trivial. If you have multiple argument to pass to the command to execute, you should use run(command: String, args: String...). The above translates to:

let result = run("ls", args: "-all")

To customize the run function, you can pass in a customization block:

let result = run("ls -all") { settings in
    settings.dryRun = true
    settings.echo = [.Stdout, .Stderr, .Command]
    settings.interactive = false
}

settings is an instance of RunSettings, which contains the following variables:

  • settings.dryRun: defaults to false. If false, the command is actually run. If true, the command is logged to the stdout paramter of result
  • settings.echo: Customize the message printed to stdout, echo can contain any of the following:
    • EchoSettings.Stdout: The stdout returned from running the command will be printed to the terminal
    • EchoSettings.Stderr: The stderr returned from running the command will be printed to the terminal
    • EchoSettings.Command: The command executed will be printed to the terminal
  • settings.interactive: defaults to false. If set to true the command will be executed using system kernel function and only the exit status will be captured. If set to false, the command will be executed using NSTask and both stdout and stderr will be captured. Set interactive to true if you expect the launched command to ask input from the user through the stdin.

runWithoutCapture("command") is a quick way to run a command in interactive mode. The return value is the exit code of that command.

Env

Env is used to read and write the environment variables passed to the script

// Set enviroment variable
Env.set("key1", "value1")

// Get environment variable
Env.get("SomeKey")

// Clear all variables
Env.clear()

// Get all keys and values
Env.keys()
Env.values()

Args

Returns the arguments passed to the script. For example when calling script -f1 val1 -f2 val2 -- val3 val4

Args.all returns an array of all the raw arguments, in this example it will be ["-f1", "val1", "-f2", "val2", "--", "val3", "val4"

Args.parsed returns a structure that contains a parsed map of arguments and an array of arguments, for this example:

Args.parsed.parameters returns ["val3", "val4"]

Args.parsed.flags returns a dictinary of flags ["f1": "val1", "f2", "val2"]

Args.parsed.command returns the name of the executable itself "script"

Installation

You can install Swiftline using CocoaPods, carthage and Swift package manager

CocoaPods

use_frameworks!
pod 'Swiftline'

Carthage

github 'swiftline/swiftline'

Swift Package Manager

Add swiftline as dependency in your Package.swift

  import PackageDescription

  let package = Package(name: "YourPackage",
    dependencies: [
      .Package(url: "https://github.com/Swiftline/Swiftline.git", majorVersion: 0, minor: 3),
    ]
  )

CocoaPods + Rome plugin

If you want to use swiftline in a script you can use Rome CocoaPods plugin. This plugin builds the framework from the pod file and place them in a Rome directory.

platform :osx, '10.10'
plugin 'cocoapods-rome'

pod 'Swiftline'

Manual

To install Swiftline manually, add Pod/Swiftline directory to your project.

Examples

A list of examples can be found here

Tests

Tests can be found here. They can be normally run from the Xcode .

Documentation

Documentation can be found here

Future Improvement

  • Add gather (from highline) to ask function
  • Figure out a way to eliminate the need of interactive
  • Add Glob handling
  • Better documentation

Credits

Daniel Beere for creating the logo @DanielBeere check out danielbeere on dribble Omar Abdelhafith current project maintainer @ifnottrue

More Repositories

1

OAStackView

Porting UIStackView to iOS 7+
Objective-C
2,141
star
2

Guaka

The smartest and most beautiful (POSIX compliant) Command line framework for Swift 🤖
Swift
1,146
star
3

Download-Manager

iOS download manager, Download a set of files in parallel and sequential order.
Objective-C
196
star
4

mockpy

Mockpy is an open source tool to quickly create mock servers.
Python
138
star
5

OALayoutAnchor

Porting NSLayoutAnchor to iOS7 (full port)
Objective-C
83
star
6

Collection-Each

Adding ruby style each iterator to Cocoa/Cocoa touch Swift Array and Range classes, And Int.times{} to Int class
Swift
65
star
7

facebook_messenger

ExFacebookMessenger is a library that helps you create facebook messenger bots easily.
Elixir
58
star
8

OAStatusItemKit

OAStatusItemKit allows you to easily create mac status bar apps with a swifty flavour.
Swift
34
star
9

github-project-landing-page

A Github project landing page theme for Hugo.
HTML
27
star
10

exrequester

Quickly create API clients using module attributes.
Elixir
19
star
11

phoenix_facebook_echo_bot

Elixir sample facebook messenger echo bot using Phoenix framework.
Elixir
19
star
12

RangeSliderView

RangeSliderView provide an easy to use range selection view.
Swift
18
star
13

zenixir

Elixir Zendesk API Client http://developer.zendesk.com/
Elixir
17
star
14

ipa_utilities

Simple ruby gem to execute common ipa utilities, such as verify integrity, convert certificate formats, re-signs an ipa using a new provision profile and more.
Ruby
17
star
15

xserverpy

Manage Xcode server bots from the command line, without the need to open or install Xcode.
Python
16
star
16

dtracer

DTracer is part ruby gem, part iOS pod, that helps the sending and receiving of DTrace commands.
Ruby
14
star
17

IAModelBase

Json (and NSDictionary) to Objective c Model Helper
Objective-C
14
star
18

CodeImager

Generate a beautiful image from a code snippet on Mac OS.
11
star
19

phoenix_facebook_messenger

PhoenixFacebookMessenger is a library that helps you create facebook messenger bots easily with phoenix.
Elixir
10
star
20

Suas-iOS

Unidirectional data flow architecture implementation for iOS, macOS, tvOS and watchOS
Swift
8
star
21

JavaErlang

Java Erlang Integration using JInterface (OtpErlang)
Java
8
star
22

IASequenceAnimations

Perform a sequence of animations one after the other using blocks
Objective-C
8
star
23

ex_stub

ExStub provides an easy way to stub a module and record the function calls on it.
Elixir
8
star
24

OADTracer

Objective c library that facilitates the sending of DTrace commands.
Objective-C
8
star
25

Sublime-Text-Midnight

Sublime Text Midnight Theme (ported from Xcode Midnight theme)
7
star
26

IADraggableViewController

Create an apple iOS5 camera like View Controllers container
Objective-C
7
star
27

specipy

Extract spec descriptions from Kiwi
Python
7
star
28

StringScanner

A string scanner (similar to NSScanner) implementation purely implemented in swift written in swift
Swift
6
star
29

Storyboard_Layout_Translator

Storyboard Layout Translator
Ruby
5
star
30

profiles

A gem that searches local provision profiles and an ipa for a UDID
Ruby
4
star
31

IAAnimationTable

Fun with UITableView
Objective-C
4
star
32

RandomUser

Objective c iOS library for to generate random users, using https://randomuser.me/
Objective-C
3
star
33

Guaka-Generator

Guaka command line application generator app.
Swift
3
star
34

EmojiOntology

Emoji ontology project for UCD
Web Ontology Language
3
star
35

Currying-refresh-token

A swift playground containing samples on how to use swift functional currying
Swift
2
star
36

ObjcAndSwift

Objective-C and Swift in the same Dynamic Framework Target
Objective-C
2
star
37

Suas-Monitor

Cross-platform desktop app for visualizing and debugging apps built with Suas
TypeScript
1
star
38

TestTrunk

Ruby
1
star
39

Environ

Environ is a library that wrap libc environ to get all the environment variables passed to an application
Swift
1
star
40

LeftPad

Swift implementation of the famous npm left-pad (http://left-pad.io/) module
Ruby
1
star
41

homebrew-tap

Homebrew tap for mockpy
Ruby
1
star
42

elixir-algos

Some algorithm solutions in Elixir
Elixir
1
star
43

Swift-type-erasure-playground

Swift Type erasure playground
Swift
1
star