SlideShare une entreprise Scribd logo
1  sur  35
Télécharger pour lire hors ligne
Let's build macOS CLI Utilities
...using Swift!
Diego Freniche | Realm Developer Advocate | @dfreniche
Why CLI tools in Swift?
● small scripts to scratch an itch
● to automate things
● because they look cool
Demo Time!
● based on Cowsay
● brew install cowsay
● for extra dramatism try cowsay
Hello, World && say "Hello,
World"
Demo Time!
The quick & dirty Just-One-File approach
#!/usr/bin/swift
func fibonacci(_ n: Int) -> Int {
if n <= 2 {
return 1
} else {
return fibonacci(n - 1) + fibonacci(n - 2)
}
}
print(fibonacci(10))
$ swift fibonacci.swift
lib/swift -module-name fibonacci -target-sdk-version 12.0.0
55
Running it!
$ swift -v fibonacci.swift
Apple Swift version 5.5 (swiftlang-1300.0.27.6 clang-1300.0.27.2)
Target: x86_64-apple-macosx11.0
/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchai
n/usr/bin/swift-frontend -frontend -interpret fibonacci.swift -enable-objc-interop
-stack-check -sdk
/Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Develope
r/SDKs/MacOSX12.0.sdk -color-diagnostics -new-driver-path
/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchai
n/usr/bin/swift-driver -resource-dir
/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchai
n/usr/lib/swift -module-name fibonacci -target-sdk-version 12.0.0
● only one file per script
● no include other .swift file
● no easy way to add 3rd party code
● We need to launch it using a bash script most likely *
* Hint: we don’t want bash, that’s the whole point of this talk!
⚠ Limitations of Swift Scripts
Command line tools 🛠 are software. Structuring their code in
massive files that read like bash scripts is missing an opportunity to
leverage the abstractions of the programming language and
platform to have a codebase that is easier to reason about. *
* https://twitter.com/pedropbuendia/status/1230414793191890950?s=20
🙏Always write good code
Create a Xcode project!
● New Project
● Mac > Command Line Tool
● put code in main.swift
● hit Cmd + R
● watch for output in Xcode's
Terminal
● Starting point:
main.swift
CLI tool new project: Apple Template
Program Starting point, a better way
// We can call this file whatever we want, just not main.swift
// also, no code can be in main.swift
import Foundation
@main
struct MainChiquitoSay {
static func main() {
print("Tea duck queen?")
}
}
🙈 No tests!
● Yes, we can create a Test Target
● Problem: no way to reach our code (no module defined)
🙈 No tests!
● “Solution”: add each file to the Test target’s (🙈 x 2)
We need a better way!
Modularize the code!
How to add tests? Modules!
● Create a Framework and use it from the CLI app.
● BUT
○ We need to install that Framework in our system
(dynamically linked)
● We can do the same with a Static Library
The Static Library route
● Add a Library target
● Static library
● Move all code there
● Add a test target for your library
🥇 Best way to modularize?
● SPM!
○ For 3rd party dependencies
○ For our own code (local packages)
Managing 3rd party dependencies
Go to Project > Swift Packages
1. Add new packages
2. See list of packages
3. Change versions, etc.
File > Packages: bunch of interesting options
My default Pack Of Packages 🎁
● swift-argument-parser:
○ CLI arguments parsing, help, etc.
○ https://github.com/apple/swift-argument-parser
● ANSITerminal:
○ Prints ANSI escape sequences, easy
○ https://github.com/pakLebah/ANSITerminal
● Files:
○ Makes using Files and Folders easy
○ https://github.com/johnsundell/files
● SwiftFigletKit:
○ https://github.com/dfreniche/SwiftFiglet
Main pieces of the CLI puzzle 🧩
🖥 Printing/reading to/from console
🎨 Nice ANSI colors
🔍 Argument Parsing
🗂 Working with Files and Folders
🚀 Launching other Processes
󰝊 Background Jobs
🖥 Printing to Console
● just use good old print
● use print(message, separator: "", terminator: "") if you don't
want CR + LF before your message
● 🎨 Nice ANSI colors if possible
○ 🎁 https://github.com/pakLebah/ANSITerminal
○ print("ChiquitoSay starting".green)
🖥 Reading from Console
● readLine(), readLine(strippingNewline: true)
● returns String?, so better do readLine() && ""
● readLine does not work in Playgrounds 🙈
https://developer.apple.com/documentation/swift/1641199-readline
🔍 Argument parsing
ARGUMENTS:
<image-url> URL with the image to show
<message> The message to print
OPTIONS:
--print-banner Print a text banner instead of image
--say-text Say text aloud
-h, --help Show help information.
🔍 Argument parsing
● 🎁 https://github.com/apple/swift-argument-parser
● make our main struct conform to ParsableCommand
import ArgumentParser
@main
struct MainChiquitoSay: ParsableCommand {
...
🔍 Argument parsing
import ArgumentParser
@main
struct MainChiquitoSay: ParsableCommand {
@Flag(help: "Print a text banner instead of image")
var printBanner = false
@Argument(help: "URL with the image to show")
var imageURL: String
Passing arguments from Xcode
🗂 Working with Files and Folders
SPM: https://github.com/JohnSundell/Files
extension Folder {
public static func cd(path: String) -> Folder {
do {
let parent = try Folder.init(path: path)
return parent
} catch {
return Folder.current
}
}
}
🚀 Launching other processes
/// - command: full path to the program we want to launch
/// - arguments: Array of arguments passed to that program
static func launch(command: String, arguments:[String] = []) {
let url = URL(fileURLWithPath: command)
do {
try Process.run(url, arguments: arguments) { (process) in
print("ndidFinish: (!process.isRunning)")
}
} catch {
print("Error opening file (error)")
}
}
󰝊Background Jobs
󰝊Background Jobs
● we can't use GCD here
● If we launch a background process it will be killed: our app will continue and finish
before the BG process finishes
● So we need a way to wait
● we'll use Semaphores
more info on GCD + CLI here:
https://stackoverflow.com/questions/8366195/using-grand-central-dispatch-outsi
de-of-an-application-or-runloop
󰝊Background Jobs
let sema = DispatchSemaphore( value: 0)
// define a background task
let task = URLSession.shared.dataTask(with: imageURL) { (data, response, error) in
sema.wait() // decrement semaphore, no more operations at the time
// do something that takes time
sema.signal()
end = true // signals the process to continue
};
task.resume() // launch the task in a new thread
“Continuous Integration” LOL
If you want more...
https://github.com/migueldeicaza/TermKit
https://github.com/migueldeicaza/TurboSwift
...and more
● fdir:
○ Lists directory contents adding comments to files
○ https://github.com/dfreniche/fdir
● ChiquitoSay:
○ A meme creator
○ https://github.com/dfreniche/chiquitosay
● Memo:
○ A really minimalistic memo app that stores messages in a local
Realm DB
○ https://github.com/dfreniche/memo
Thank you!
That’s all folks
Diego Freniche | Realm Mobile Developer Advocate | @dfreniche

Contenu connexe

Tendances

Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScriptTroy Miles
 
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)Tim Bunce
 
Clojure in real life 17.10.2014
Clojure in real life 17.10.2014Clojure in real life 17.10.2014
Clojure in real life 17.10.2014Metosin Oy
 
PSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend ExpressivePSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend ExpressiveMilad Arabi
 
DanNotes 2013: OpenNTF Domino API
DanNotes 2013: OpenNTF Domino APIDanNotes 2013: OpenNTF Domino API
DanNotes 2013: OpenNTF Domino APIPaul Withers
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyAerospike
 
Deploying Perl apps on dotCloud
Deploying Perl apps on dotCloudDeploying Perl apps on dotCloud
Deploying Perl apps on dotClouddaoswald
 
Wonders of Golang
Wonders of GolangWonders of Golang
Wonders of GolangKartik Sura
 
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)Robert Nelson
 
Getting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::CGetting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::Cdaoswald
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with GoSteven Francia
 
HHVM and Hack: A quick introduction
HHVM and Hack: A quick introductionHHVM and Hack: A quick introduction
HHVM and Hack: A quick introductionKuan Yen Heng
 
Writing Custom Puppet Types and Providers to Manage Web-Based Applications
Writing Custom Puppet Types and Providers to Manage Web-Based ApplicationsWriting Custom Puppet Types and Providers to Manage Web-Based Applications
Writing Custom Puppet Types and Providers to Manage Web-Based ApplicationsTim Cinel
 
30 Minutes To CPAN
30 Minutes To CPAN30 Minutes To CPAN
30 Minutes To CPANdaoswald
 
Automating Your Daily Tasks with Scripting - RubyConf 2015 Taiwan
Automating Your Daily Tasks with Scripting - RubyConf 2015 TaiwanAutomating Your Daily Tasks with Scripting - RubyConf 2015 Taiwan
Automating Your Daily Tasks with Scripting - RubyConf 2015 TaiwanAdler Hsieh
 
Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7Yuji Otani
 
Engage 2014 OpenNTF Domino API Slides
Engage 2014 OpenNTF Domino API SlidesEngage 2014 OpenNTF Domino API Slides
Engage 2014 OpenNTF Domino API SlidesPaul Withers
 

Tendances (20)

Functional Programming in JavaScript
Functional Programming in JavaScriptFunctional Programming in JavaScript
Functional Programming in JavaScript
 
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
Devel::NYTProf v3 - 200908 (OUTDATED, see 201008)
 
Clojure in real life 17.10.2014
Clojure in real life 17.10.2014Clojure in real life 17.10.2014
Clojure in real life 17.10.2014
 
PSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend ExpressivePSR-7 - Middleware - Zend Expressive
PSR-7 - Middleware - Zend Expressive
 
DanNotes 2013: OpenNTF Domino API
DanNotes 2013: OpenNTF Domino APIDanNotes 2013: OpenNTF Domino API
DanNotes 2013: OpenNTF Domino API
 
Php extensions
Php extensionsPhp extensions
Php extensions
 
Golang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war storyGolang Performance : microbenchmarks, profilers, and a war story
Golang Performance : microbenchmarks, profilers, and a war story
 
Deploying Perl apps on dotCloud
Deploying Perl apps on dotCloudDeploying Perl apps on dotCloud
Deploying Perl apps on dotCloud
 
Wonders of Golang
Wonders of GolangWonders of Golang
Wonders of Golang
 
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
Enjoying the Journey from Puppet 3.x to Puppet 4.x (PuppetConf 2016)
 
Getting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::CGetting started with Perl XS and Inline::C
Getting started with Perl XS and Inline::C
 
Getting Started with Go
Getting Started with GoGetting Started with Go
Getting Started with Go
 
HHVM and Hack: A quick introduction
HHVM and Hack: A quick introductionHHVM and Hack: A quick introduction
HHVM and Hack: A quick introduction
 
Writing Custom Puppet Types and Providers to Manage Web-Based Applications
Writing Custom Puppet Types and Providers to Manage Web-Based ApplicationsWriting Custom Puppet Types and Providers to Manage Web-Based Applications
Writing Custom Puppet Types and Providers to Manage Web-Based Applications
 
30 Minutes To CPAN
30 Minutes To CPAN30 Minutes To CPAN
30 Minutes To CPAN
 
Async await...oh wait!
Async await...oh wait!Async await...oh wait!
Async await...oh wait!
 
Composer Helpdesk
Composer HelpdeskComposer Helpdesk
Composer Helpdesk
 
Automating Your Daily Tasks with Scripting - RubyConf 2015 Taiwan
Automating Your Daily Tasks with Scripting - RubyConf 2015 TaiwanAutomating Your Daily Tasks with Scripting - RubyConf 2015 Taiwan
Automating Your Daily Tasks with Scripting - RubyConf 2015 Taiwan
 
Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7Why choose Hack/HHVM over PHP7
Why choose Hack/HHVM over PHP7
 
Engage 2014 OpenNTF Domino API Slides
Engage 2014 OpenNTF Domino API SlidesEngage 2014 OpenNTF Domino API Slides
Engage 2014 OpenNTF Domino API Slides
 

Similaire à MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift

Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Fabrice Bernhard
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersRutenis Turcinas
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software DevelopmentZeeshan MIrza
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4Max Kleiner
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014biicode
 
Fullstack workshop
Fullstack workshopFullstack workshop
Fullstack workshopAssaf Gannon
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIYoni Davidson
 
DevOps(4) : Ansible(2) - (MOSG)
DevOps(4) : Ansible(2) - (MOSG)DevOps(4) : Ansible(2) - (MOSG)
DevOps(4) : Ansible(2) - (MOSG)Soshi Nemoto
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Max Kleiner
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache FlexGert Poppe
 
Where's the source, Luke? : How to find and debug the code behind Plone
Where's the source, Luke? : How to find and debug the code behind PloneWhere's the source, Luke? : How to find and debug the code behind Plone
Where's the source, Luke? : How to find and debug the code behind PloneVincenzo Barone
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache FlexGert Poppe
 
Makefile for python projects
Makefile for python projectsMakefile for python projects
Makefile for python projectsMpho Mphego
 
Python Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IPython Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IDUSPviz
 
Dependent things dependency management for apple sw - slideshare
Dependent things   dependency management for apple sw - slideshareDependent things   dependency management for apple sw - slideshare
Dependent things dependency management for apple sw - slideshareCavelle Benjamin
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with pythonroskakori
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Henry Schreiner
 
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)Bastian Feder
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James NelsonGWTcon
 

Similaire à MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift (20)

Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
Adopt DevOps philosophy on your Symfony projects (Symfony Live 2011)
 
TypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack DevelopersTypeScript - Silver Bullet for the Full-stack Developers
TypeScript - Silver Bullet for the Full-stack Developers
 
Introduction to Software Development
Introduction to Software DevelopmentIntroduction to Software Development
Introduction to Software Development
 
EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4EKON 25 Python4Delphi_mX4
EKON 25 Python4Delphi_mX4
 
Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014Dependencies Managers in C/C++. Using stdcpp 2014
Dependencies Managers in C/C++. Using stdcpp 2014
 
Fullstack workshop
Fullstack workshopFullstack workshop
Fullstack workshop
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-API
 
DevOps(4) : Ansible(2) - (MOSG)
DevOps(4) : Ansible(2) - (MOSG)DevOps(4) : Ansible(2) - (MOSG)
DevOps(4) : Ansible(2) - (MOSG)
 
Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475Ekon 25 Python4Delphi_MX475
Ekon 25 Python4Delphi_MX475
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
 
Where's the source, Luke? : How to find and debug the code behind Plone
Where's the source, Luke? : How to find and debug the code behind PloneWhere's the source, Luke? : How to find and debug the code behind Plone
Where's the source, Luke? : How to find and debug the code behind Plone
 
Automated User Tests with Apache Flex
Automated User Tests with Apache FlexAutomated User Tests with Apache Flex
Automated User Tests with Apache Flex
 
Makefile for python projects
Makefile for python projectsMakefile for python projects
Makefile for python projects
 
Python Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part IPython Programming for ArcGIS: Part I
Python Programming for ArcGIS: Part I
 
Dependent things dependency management for apple sw - slideshare
Dependent things   dependency management for apple sw - slideshareDependent things   dependency management for apple sw - slideshare
Dependent things dependency management for apple sw - slideshare
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with python
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024
 
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
Advanced Eclipse Workshop (held at IPC2010 -spring edition-)
 
"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson"Xapi-lang For declarative code generation" By James Nelson
"Xapi-lang For declarative code generation" By James Nelson
 

Plus de Diego Freniche Brito

Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfLos mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfDiego Freniche Brito
 
From Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmFrom Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmDiego Freniche Brito
 
Cocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesCocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesDiego Freniche Brito
 
Swift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkSwift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkDiego Freniche Brito
 
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickCharla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickDiego Freniche Brito
 
Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Diego Freniche Brito
 
Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013Diego Freniche Brito
 
Core data basic Workshop slides NSSpain 2013
Core data basic Workshop slides NSSpain 2013Core data basic Workshop slides NSSpain 2013
Core data basic Workshop slides NSSpain 2013Diego Freniche Brito
 

Plus de Diego Freniche Brito (8)

Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdfLos mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
Los mejores consejos para migrar de RDBMS a MongoDB.pptx.pdf
 
From Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using RealmFrom Mobile to MongoDB: Store your app's data using Realm
From Mobile to MongoDB: Store your app's data using Realm
 
Cocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your librariesCocoa pods iOSDevUK 14 talk: managing your libraries
Cocoa pods iOSDevUK 14 talk: managing your libraries
 
Swift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talkSwift as a scripting language iOSDevUK14 Lightning talk
Swift as a scripting language iOSDevUK14 Lightning talk
 
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un clickCharla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
Charla XVII Beta Beers Sevilla: ¿Ágil? Como la rodilla de un click
 
Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14Core data WIPJam workshop @ MWC'14
Core data WIPJam workshop @ MWC'14
 
Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013Core data intermediate Workshop at NSSpain 2013
Core data intermediate Workshop at NSSpain 2013
 
Core data basic Workshop slides NSSpain 2013
Core data basic Workshop slides NSSpain 2013Core data basic Workshop slides NSSpain 2013
Core data basic Workshop slides NSSpain 2013
 

Dernier

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncssuser2ae721
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfme23b1001
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girlsssuser7cb4ff
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitterShivangiSharma879191
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 

Dernier (20)

Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsyncWhy does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
Why does (not) Kafka need fsync: Eliminating tail latency spikes caused by fsync
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
Electronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdfElectronically Controlled suspensions system .pdf
Electronically Controlled suspensions system .pdf
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Call Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call GirlsCall Girls Narol 7397865700 Independent Call Girls
Call Girls Narol 7397865700 Independent Call Girls
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter8251 universal synchronous asynchronous receiver transmitter
8251 universal synchronous asynchronous receiver transmitter
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 

MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift

  • 1. Let's build macOS CLI Utilities ...using Swift! Diego Freniche | Realm Developer Advocate | @dfreniche
  • 2. Why CLI tools in Swift? ● small scripts to scratch an itch ● to automate things ● because they look cool
  • 3. Demo Time! ● based on Cowsay ● brew install cowsay ● for extra dramatism try cowsay Hello, World && say "Hello, World"
  • 5. The quick & dirty Just-One-File approach #!/usr/bin/swift func fibonacci(_ n: Int) -> Int { if n <= 2 { return 1 } else { return fibonacci(n - 1) + fibonacci(n - 2) } } print(fibonacci(10))
  • 6. $ swift fibonacci.swift lib/swift -module-name fibonacci -target-sdk-version 12.0.0 55 Running it! $ swift -v fibonacci.swift Apple Swift version 5.5 (swiftlang-1300.0.27.6 clang-1300.0.27.2) Target: x86_64-apple-macosx11.0 /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchai n/usr/bin/swift-frontend -frontend -interpret fibonacci.swift -enable-objc-interop -stack-check -sdk /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Develope r/SDKs/MacOSX12.0.sdk -color-diagnostics -new-driver-path /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchai n/usr/bin/swift-driver -resource-dir /Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchai n/usr/lib/swift -module-name fibonacci -target-sdk-version 12.0.0
  • 7. ● only one file per script ● no include other .swift file ● no easy way to add 3rd party code ● We need to launch it using a bash script most likely * * Hint: we don’t want bash, that’s the whole point of this talk! ⚠ Limitations of Swift Scripts
  • 8. Command line tools 🛠 are software. Structuring their code in massive files that read like bash scripts is missing an opportunity to leverage the abstractions of the programming language and platform to have a codebase that is easier to reason about. * * https://twitter.com/pedropbuendia/status/1230414793191890950?s=20 🙏Always write good code
  • 9. Create a Xcode project! ● New Project ● Mac > Command Line Tool
  • 10. ● put code in main.swift ● hit Cmd + R ● watch for output in Xcode's Terminal ● Starting point: main.swift CLI tool new project: Apple Template
  • 11. Program Starting point, a better way // We can call this file whatever we want, just not main.swift // also, no code can be in main.swift import Foundation @main struct MainChiquitoSay { static func main() { print("Tea duck queen?") } }
  • 12. 🙈 No tests! ● Yes, we can create a Test Target ● Problem: no way to reach our code (no module defined)
  • 13. 🙈 No tests! ● “Solution”: add each file to the Test target’s (🙈 x 2)
  • 14. We need a better way! Modularize the code!
  • 15. How to add tests? Modules! ● Create a Framework and use it from the CLI app. ● BUT ○ We need to install that Framework in our system (dynamically linked) ● We can do the same with a Static Library
  • 16. The Static Library route ● Add a Library target ● Static library ● Move all code there ● Add a test target for your library
  • 17. 🥇 Best way to modularize? ● SPM! ○ For 3rd party dependencies ○ For our own code (local packages)
  • 18. Managing 3rd party dependencies Go to Project > Swift Packages 1. Add new packages 2. See list of packages 3. Change versions, etc. File > Packages: bunch of interesting options
  • 19. My default Pack Of Packages 🎁 ● swift-argument-parser: ○ CLI arguments parsing, help, etc. ○ https://github.com/apple/swift-argument-parser ● ANSITerminal: ○ Prints ANSI escape sequences, easy ○ https://github.com/pakLebah/ANSITerminal ● Files: ○ Makes using Files and Folders easy ○ https://github.com/johnsundell/files ● SwiftFigletKit: ○ https://github.com/dfreniche/SwiftFiglet
  • 20. Main pieces of the CLI puzzle 🧩 🖥 Printing/reading to/from console 🎨 Nice ANSI colors 🔍 Argument Parsing 🗂 Working with Files and Folders 🚀 Launching other Processes 󰝊 Background Jobs
  • 21. 🖥 Printing to Console ● just use good old print ● use print(message, separator: "", terminator: "") if you don't want CR + LF before your message ● 🎨 Nice ANSI colors if possible ○ 🎁 https://github.com/pakLebah/ANSITerminal ○ print("ChiquitoSay starting".green)
  • 22. 🖥 Reading from Console ● readLine(), readLine(strippingNewline: true) ● returns String?, so better do readLine() && "" ● readLine does not work in Playgrounds 🙈 https://developer.apple.com/documentation/swift/1641199-readline
  • 23. 🔍 Argument parsing ARGUMENTS: <image-url> URL with the image to show <message> The message to print OPTIONS: --print-banner Print a text banner instead of image --say-text Say text aloud -h, --help Show help information.
  • 24. 🔍 Argument parsing ● 🎁 https://github.com/apple/swift-argument-parser ● make our main struct conform to ParsableCommand import ArgumentParser @main struct MainChiquitoSay: ParsableCommand { ...
  • 25. 🔍 Argument parsing import ArgumentParser @main struct MainChiquitoSay: ParsableCommand { @Flag(help: "Print a text banner instead of image") var printBanner = false @Argument(help: "URL with the image to show") var imageURL: String
  • 27. 🗂 Working with Files and Folders SPM: https://github.com/JohnSundell/Files extension Folder { public static func cd(path: String) -> Folder { do { let parent = try Folder.init(path: path) return parent } catch { return Folder.current } } }
  • 28. 🚀 Launching other processes /// - command: full path to the program we want to launch /// - arguments: Array of arguments passed to that program static func launch(command: String, arguments:[String] = []) { let url = URL(fileURLWithPath: command) do { try Process.run(url, arguments: arguments) { (process) in print("ndidFinish: (!process.isRunning)") } } catch { print("Error opening file (error)") } }
  • 30. 󰝊Background Jobs ● we can't use GCD here ● If we launch a background process it will be killed: our app will continue and finish before the BG process finishes ● So we need a way to wait ● we'll use Semaphores more info on GCD + CLI here: https://stackoverflow.com/questions/8366195/using-grand-central-dispatch-outsi de-of-an-application-or-runloop
  • 31. 󰝊Background Jobs let sema = DispatchSemaphore( value: 0) // define a background task let task = URLSession.shared.dataTask(with: imageURL) { (data, response, error) in sema.wait() // decrement semaphore, no more operations at the time // do something that takes time sema.signal() end = true // signals the process to continue }; task.resume() // launch the task in a new thread
  • 33. If you want more... https://github.com/migueldeicaza/TermKit https://github.com/migueldeicaza/TurboSwift
  • 34. ...and more ● fdir: ○ Lists directory contents adding comments to files ○ https://github.com/dfreniche/fdir ● ChiquitoSay: ○ A meme creator ○ https://github.com/dfreniche/chiquitosay ● Memo: ○ A really minimalistic memo app that stores messages in a local Realm DB ○ https://github.com/dfreniche/memo
  • 35. Thank you! That’s all folks Diego Freniche | Realm Mobile Developer Advocate | @dfreniche