Building a Command Line Tool in Swift To Share Xcode Snippets With Your Team | by Tolga Taner | Sep, 2022

Using Argument Parser

Photo by Markus Spiske on Unsplash

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.

It is a value set in our argument variable when running the script. For example, we will runswift run SnippetSharing Snippets Snippets correspond to our argument variable. It is also our snippets folder name. It can also be something else.

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.

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.

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, it can be weird. 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!

News Credit

%d bloggers like this: