4

I'm developing a command-line tool that has many user options. Some of the options are lists of values. I'd like the program to be able to parse these listed options directly from the command line, and via a file (e.g. --opt=valA,valB and --opt=vals.txt).

Is it preferable to have two separate options for each case, or have the program interpret the arguments at runtime? I've seen programs doing it both ways but I can't decide which is the better design (if there is an objective reason).

  • If I write foo --opt=valA how will your program know whether I mean valA is a filename or valA is an option. What if I decided to name my file the same way as one of your options. – Brandin May 18 '15 at 13:23
  • @Brandin valA would need to be a valid system path. – Daniel May 18 '15 at 15:25
  • But valA could also be an option. For example suppose you implement a turbo option and call valA "turbo". But "turbo" is also a legal path. So what does --opt=turbo mean? That you want the turbo option or that you want to write/read the file called turbo? It's ambiguous. – Brandin May 18 '15 at 18:14
4

The test to apply is whether or not someone can definitively understand the intent of the arguments just by looking at them.

In your example, the interpretation of --opt=foo would vary depending on the program's surroundings. That could sow confusion or, worse, cause a security problem if there's a file named foo in the current working directory and the intent was foo as a literal. (This, by the way, is why putting . or other relative directories in the program search path is considered unsafe.)

There are two ways to make the intent clear:

  • Use different switches (e.g., --opt=foo and --opt-file=bar.txt).
  • Add a sigil to the beginning of the value to indicate that it's a file and not a literal. Some programs use @ (e.g., --opt=foo and --opt=@bar.txt). This comes at the expense of not being able to specify literals starting with that character without escaping it.

Either could easily be added to an argument parsing library or simply dealt with when you have the results.

2

You've seen programs that interpret option arguments both as a filename and as literals? Depending on what, the state of the file system? That's an insidious defect or exploit waiting to happen. Never, never, ever do this.

  • Yes, generally conditioned on the string being a valid system path. I had a feeling it was a bad idea, but haven't been able to find a convincing argument as to why... – Daniel May 18 '15 at 12:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.