Building a Command Line Tool Using Argument Parser in Swift
Share Xcode snippets with your team
Argument Parser is a new package introduced by Apple. It makes writing a command line tool easier to automate common tasks. Argument Parser has three property wrappers: Argument, Flag, and Option.
Argument
It is a value set in our argument variable when running the script. For example, we will run swift run SnippetSharing Snippets
Snippets correspond to our argument variable. It is also our snippets folder name. It can also be something else.
Flag
Flag is mostly used for verbose for adding extra logs. For example, we can run swift run SnippetSharing Snippets --verbose
to get extra logs.
Let’s create a command line tool that shares Xcode snippets with our team members. To achieve that, we create code snippets in the command line tool folder, and the command line tool will move it to the expected folder. In our example, we will use both Argument and Flag property wrappers.
Creating Swift Package
Let’s create a folder named SnippetSharing
in the project folder:
mkdir SnippetSharing
Run it to create a Swift package:
swift package init --type executable
After that, type swift run
and open Package.swift
file created by initialization.
Adding Argument Parser as a Dependency
In Package.swift
, we need to add Argument Parser to our package. Its version is 0.0.4 because we don’t need any async operations of Argument Parser.
After these configurations, the Argument Parser package should be seen in the bottom left part of Xcode in “Package Dependencies.”
Writing command line
Let’s define a struct named SnippetSharing
that uses the ParsableCommand
.
Our struct has folderName
that corresponds to Snippet
folder that we want to share with our team members. Manager
is for finding our current directory path. snippetFolderPathXcode
is a default folder path for Xcode that we will copy all snippets to show the snippets in Xcode. Verbose is for logging.
We need a function that runs our shell commands like deleting, creating, and copy operations.
After that, we can write commands functions respectively. If you are not familiar with Shell Script, you should look some examples about it. Here’s the code:
Finally, we can update our run method and call the main function of our struct out of struct scope.
There is one step to creating a folder of an Xcode Snippet. In the package folder, create a folder named as you want. My folder name is Snippets
. It contains both IBOutlet
, IBAction
snippets. We use a lot of time both keywords.
Trying command line tool
Just run swift run SnippetSharing Snippets
As we can see, we automated Xcode Snippet sharing from one base. All team members can update the snippet folder and run the command. It can also be used for custom xctemplate for sharing. The full project is here.
Thanks for reading!