Optional parts in Cmd

I would like to construct a Cmd with some optional parts, depending in the caller. I got this working by collecting strings and then interpolating a vector of them, and this actually works fine (with escaping, etc) but I am curious if there is some other way.

function make_cmd(file, options)
    cmd_options = Any[]
    options.debug ≠ nothing && push!(cmd_options, "--debug=$(options.debug)")
    options.foo ≠ nothing && push!(cmd_options, "--foo=true")
    options.somepath ≠ nothing && push!(cmd_options, "--somepath=$(options.somepath)")
    `executable $(file) $(cmd_options)`
end

output:

julia> make_cmd("file.txt",
       (debug = "/debug_output.log", foo = true,
       somepath = "pathwith\"quote.txt"))
`executable file.txt --debug=/debug_output.log --foo=true '--somepath=pathwith"quote.txt'`

Cmd objects interpolate correctly into each other so this is a common pattern:

function make_cmd(file, options)
    cmd = `executable $file`
    options.debug ≠ nothing && (cmd = `$cmd --debug=$(options.debug)`)
    options.foo ≠ nothing && (cmd = `$cmd --foo=true`)
    options.somepath ≠ nothing && (cmd = `$cmd --somepath=$(options.somepath)`)
    return cmd
end

Also and empty cmd object splices into another cmd without changing it so there’s that approach too.

2 Likes

Should that be:

cmd = `$cmd --debug=$(options.debug)`

rather than:

cmd = `--debug=$(options.debug)`

?

2 Likes

Yup. Was on a phone on a bus. Fixed now.

1 Like