Wolf Bytes

On annoyances, interests, and general thoughts that may or may not be of interest to the general public.

Monday, August 22, 2005

Take Command

Occasionally, all developers have to write a command line tool. I've had the need to write several in my career, and the part that is always the worst, is parsing the command line. I can't stand that part. It seems like it should be easier.

But time and again, I wrote it because I didn't have the time to come up with a better way.

Well, now there is one.

I ran across this on my latest foray into command line tools. I started my search for code (as I always do) at SourceForge. Here is what I ran across:

http://sourceforge.net/projects/cmdlineparser

This dandy little tool makes command line parsing easy. All you have to do is write a class that has public properties (or for you Java folks out there, Accessors and Mutators) around private member variables. For instance:


class ApplicationSettings
{
private bool help = false;

public bool Help
{
get
{
return this.help;
}

set
{
this.help = value;
}
}
}

Then, you just attribute the property like this:

[CommandLineSwitch("help", "Show usage information", @"h", @"\?")]

Basically, this says that there should be a command line switch named "help" that has two aliases named "h" and "?". It's description is "Show usage information."

So far, so good. Then in your main program, you do this:

private ApplicationSettings Options = new ApplicationSettings();
CommandLineParser commandLineParser = new CommandLineParser(this.Options);
commandLineParser.Parse(System.Environment.GetCommandLineArgs());

This will populate the ApplicationSettings object with the switches that were entered into the command line. It even casts them correctly. You can then just check your object for the switches.

This tools can even output usage information automatically by doing this:

Console.Write(commandLineParser.Usage);

Pretty cool, huh?

This little gem cut my command line tool development at least in half and also removed the most boring part of the development.

Enjoy!!!


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home