loading...

Creating a composable command-line tool using the Swift Argument Parser

rderik profile image rderik ・2 min read

Most of us make use of command-line tools that are composable, like sed(1), grep(1), sort(1). Not all tools use the same conventions for working with input from the standard input(STDIN). But it's certainly handy when they do.

Apple announced on February 2020 the Swift Argument Parser. It provides an easy to use parsing capability, and their documentationis good. But as many examples on the Internet about building command-line tools, they focus on self-contained applications.

I thought it might be useful to show how to create a composable command-line tool. A composable command-line tool allows you to create a workflow between different tools. For example:

$ grep "Name:*" *.txt | sort

We are using two tools here grep(1)(To search for the pattern Name:* on all files with a .txt extension) and sort(1). Each of the commands can be used on their own, but when we put them together, we can create complex workflows that easily solve our problem. The idea is redirecting the Standard Output(STDOUT) of one command and use it as the Standard Input(STDIN) of the second command using a pipe |.

If we want to make our command-line tool composable, we would like to support the following cases:

  • If the tool is called without any parameters it'll try to read from the STDIN.
  • If the tool's last argument is a single dash (-) read from the STDIN.

The same way as sort(1) or other Unix command-line tools work.

we can call:

$ cat file.txt | sort

or we can call:

$ sort file.txt

If you are interested in how to build a command-line tool that is composable using the Swift Argument Parser, you might find the following post interesting:

https://rderik.com/blog/understanding-the-swift-argument-parser-and-working-with-stdin/

As always, feedback is welcomed.

Posted on by:

Discussion

markdown guide