Read the Command-line Input From Terminal Swift 4
Swiftline is a prepare of tools to aid yous create command line applications. Swiftline is inspired by highline
Swiftline contains the following:
- Colorize: Helps adding colors to strings written to the concluding
- Enquire , Cull and agree: Easily create prompt for request 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 lot can change the text color, the text background and the text style. Colorize works past extending String
struct to add styling to information technology.
To alter the text colour, employ either string.f
or string.foreground
:
impress( "Red String" .f.Cherry) print( "Blue String" .foreground.Blueish)
To modify the text background colour, use either string.b
or string.background
:
print( "I have a white background" .b.White) print( "My groundwork color is green" .groundwork.Green)
To change the text background style, use either string.southward
or string.style
:
print( "I am a assuming string" .s.Assuming) print( "I accept an underline" .way.Underline)
Yous tin etch foreground, background, and way:
print( "I am an underlined ruddy on white string" .s.Underline.f.Cherry.b.White)
Ask, Choose, Agree ❓
Inquire, Choose and Agree are used to prompt the user for more data.
Inquire
Ask presents the user with a prompt and waits for the user input.
allow userName = ask( "Enter user name?" )
userName
will contain the proper 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 case:
let age = enquire( "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 quondam are y'all? None Yous 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 non 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 proper noun is Snowball
AskSettings.confirm
will inquire the user to confirm his choice afterward entering information technology
let name = ask( "Who are you lot?" ) { 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 detail between several possible items.
To brandish a choice of programming lanaugage for example:
let option = cull( "Whats your favorite programming language? " , choices: "Swift" , "Objective C" , "Ruby" , "Python" , "Coffee :Southward" )
This will print:
1. Swift two. Objective C three. Ruby 4. Python five. Coffee :S Whats your favorite programming language?
The user tin can either choose the numbers (1..5) or the item itself. If the user enters a wrong input. A prompt will continue showing until the user makes a correct choice
Whats your favorite programming language? JavaScript Y'all must choose one of [1, two, iii, 4, 5, Swift, Objective C, Ruby, Python, Java :South]. ? BBB Y'all must choose i of [1, two, iii, 4, 5, Swift, Objective C, Ruby, Python, Java :S]. ? Swift You selected Swift, good choice!
You can customize the render value for each option element. For example if you want to go an Int from the pick, yous would practise this
permit choice = cull( "Whats your favorite programming language? " , blazon: Int.self) { settings in settings.addChoice( "Swift" ) { 42 } settings.addChoice( "Objective C" ) { 20 } }
The number on the left tin be inverse to letters, hither is how yous could practise that:
permit choice = choose("Whats your favorite programming language? ", blazon: String.cocky) { settings in //pick value will exist ready to GOOD settings.addChoice("Swift") { "GOOD" } //choice value will exist set to BAD settings.addChoice("Java") { "BAD" } settings.alphabetize = .Letters settings.indexSuffix = " ----> " }
That will impress:
a ----> Swift b ----> Java Whats your favorite programming linguistic communication?
Concur
Agree is used to ask a user for a Yes/No question. It returns a boolean representing the user input.
permit pick = concord( "Are yous sure you lot want to `rm -rf /` ?" )
If the user enters any invalid input, agree volition keep prompting him for a Yes/No question
Are y'all sure you want to `rm -rf /` ? What! Please enter "aye" or "no". Are you sure you want to `rm -rf /` ? Wait Please enter "yes" or "no". Are y'all certain 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 exercise:
allow outcome = run( "ls -all" ) print(result.stdout)
effect
type is RunResults
, it contains:
-
exitStatus
: The command leave status -
stdout
: The standard output for the command executed -
stderr
: The standard fault for the command executed
While run("command")
tin divide the arguments by spaces. Some times statement splitting is not trivial. If you lot have multiple argument to pass to the command to execute, y'all should use run(command: String, args: String...)
. The higher up translates to:
let effect = run( "ls" , args: "-all" )
To customize the run function, you can pass in a customization block:
allow effect = run( "ls -all" ) { settings in settings.dryRun = true settings.echo = [.Stdout, .Stderr, .Command] settings.interactive = false }
settings
is an example of RunSettings, which contains the post-obit variables:
-
settings.dryRun
: defaults to imitation. If false, the command is actually run. If true, the command is logged to the stdout paramter of effect -
settings.echo
: Customize the message printed to stdout,echo
tin comprise whatsoever of the following:-
EchoSettings.Stdout
: The stdout returned from running the command will exist printed to the terminal -
EchoSettings.Stderr
: The stderr returned from running the command will be printed to the terminal -
EchoSettings.Command
: The control executed will be printed to the terminal
-
-
settings.interactive
: defaults to false. If set to true the command volition be executed usingorganisation
kernel role and only the exit status will be captured. If set to false, the command will be executed usingNSTask
and both stdout and stderr volition exist captured. Setinteractive
to true if yous expect the launched command to inquire input from the user through the stdin.
runWithoutCapture("command")
is a quick mode to run a control in interactive mode. The return value is the get out code of that control.
Env
Env is used to read and write the environment variables passed to the script
// Gear up enviroment variable Env.set( "key1" , "value1" ) // Get environment variable Env.become( "SomeKey" ) // Clear all variables Env.clear() // Go 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 instance 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
Yous can install Swiftline using CocoaPods, carthage and Swift package director
CocoaPods
use_frameworks! pod 'Swiftline'
Carthage
github 'swiftline/swiftline'
Swift Package Director
Add swiftline as dependency in your Package.swift
import PackageDescription let package = Parcel(proper name: "YourPackage", dependencies: [ .Package(url: "https://github.com/Swiftline/Swiftline.git", majorVersion: 0, pocket-size: three), ] )
CocoaPods + Rome plugin
If you want to apply swiftline in a script you tin can use Rome CocoaPods plugin. This plugin builds the framework from the pod file and identify 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 exist found hither
Tests
Tests tin be found here. They can be ordinarily run from the Xcode .
Documentation
Documentation tin can exist found here
Future Improvement
- Add get together (from highline) to inquire function
- Figure out a way to eliminate the demand of
interactive
- Add Glob handling
- Amend documentation
Credits
Daniel Beere for creating the logo @DanielBeere check out danielbeere on dribble Omar Abdelhafith current project maintainer @ifnottrue
GitHub
https://github.com/nsomar/SwiftlineSource: https://swiftobc.com/repo/nsomar-Swiftline-swift-command-line
0 Response to "Read the Command-line Input From Terminal Swift 4"
Post a Comment