Generic Command Line Parser for Delphi 10.3.x

You know the feeling. You need a specific input from your command line, but you can’t find something lightweight that does the job. Hence, the FDC.CommandLine was born.

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

You can use – / or + as a switch, and use : or = as a flag for parameters.

You can use single and double quotes to be able to parse parameters that contain spaces and quotes.
/quoteoftheday:”This is a ‘quoted’ parameter”

It also supports lists of parameters.
/inputfiles:(file1.txt , “file with space.txt”)

Take a look at the TestFDCCommandLine.dpr for more examples of how it works.

Breaking down the classes gives you three basic elements

The TOptionParser contains TOption elements, and each TOption can contain one or more TParam elements. TOption<T> gives us generic typed option parameters TParam<T>, and it supports strings, ints, floats and enumerated types.

By default, any “anonymous” option that you parse and look up by name will be of the type TOption<String> and hence will contains strings as parameters.

You can however create typed instances in your parser descendant that allow you to use the actual names of enumerated type elements.

  TMyColors = (Red, White, Blue);

  TMyParser = class(TOptionParser)
    Color: TOption<TMyColors>;
    constructor Create;

constructor TMyParser.Create;
  Color := Declare<TMyColors>('Color', White);

  MyParser: TMyParser;

In this example, White is set as the default color, but since the options string contains the color blue, you can refer to MyParser.Color.Value and see that it indeed equals TMyColors.Blue after parsing.

Note that DefaultValue can also be changed after declaration, and it will be used if parsing a parameter value fails to resolve to one of the enumerated values of the type.

Finally, we have the TCommandLine descendant from TOptionParser which basically just concatenates all the ParamStr values into one string and runs the parser on it.

My little command line project feature ballooned a bit, but I am satisfied with the result and I hope it can be of help to others as well.

For those of you that are on older version of Delphi than 10.3, I apologise for the inline variable declarations, but they are so addictive! It shouldn’t be too hard to rewrite it to use oldschool local variables, though.

You can leave your comments here, or at Delphi Praxis.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.