Command Line Subcommands in Julia

Here’s the translation of the Go code to Julia, formatted in Markdown suitable for Hugo:

Our first program demonstrates how to use command-line subcommands with their own set of flags. This is similar to tools like git where different subcommands (e.g., git commit, git push) have their own specific flags.

using ArgParse

function parse_commandline()
    s = ArgParseSettings()
    @add_arg_table! s begin
        "foo"
            help = "foo subcommand"
            action = :command
        "bar"
            help = "bar subcommand"
            action = :command
    end

    @add_arg_table! s["foo"] begin
        "--enable"
            help = "enable flag for foo"
            action = :store_true
        "--name"
            help = "name for foo"
            default = ""
    end

    @add_arg_table! s["bar"] begin
        "--level"
            help = "level for bar"
            arg_type = Int
            default = 0
    end

    return parse_args(s)
end

function main()
    parsed_args = parse_commandline()

    if parsed_args["%COMMAND%"] == "foo"
        println("subcommand 'foo'")
        println("  enable: ", parsed_args["foo"]["enable"])
        println("  name: ", parsed_args["foo"]["name"])
        println("  tail: ", join(parsed_args["foo"]["%REMAINDER%"], " "))
    elseif parsed_args["%COMMAND%"] == "bar"
        println("subcommand 'bar'")
        println("  level: ", parsed_args["bar"]["level"])
        println("  tail: ", join(parsed_args["bar"]["%REMAINDER%"], " "))
    else
        println("expected 'foo' or 'bar' subcommands")
        exit(1)
    end
end

main()

In this Julia version, we use the ArgParse package to handle command-line argument parsing, which provides similar functionality to Go’s flag package.

We define a function parse_commandline() that sets up the argument parsing structure. We define two subcommands, “foo” and “bar”, each with their own set of flags.

In the main() function, we parse the command-line arguments and then check which subcommand was invoked. Depending on the subcommand, we print out the relevant information.

To run this program, save it as command_line_subcommands.jl and use it like this:

$ julia command_line_subcommands.jl foo --enable --name=joe a1 a2
subcommand 'foo'
  enable: true
  name: joe
  tail: a1 a2

$ julia command_line_subcommands.jl bar --level 8 a1
subcommand 'bar'
  level: 8
  tail: a1

If you try to use a flag that doesn’t belong to a subcommand, you’ll get an error:

$ julia command_line_subcommands.jl bar --enable a1
error: unknown option "--enable"

This example demonstrates how to create a command-line tool with subcommands in Julia, each with its own set of flags. This pattern is useful for creating complex command-line applications with multiple functionalities.