Skip to content

Usage Examples

Jan Michelfeit edited this page Feb 2, 2016 · 1 revision

Examples of EasyOpt usage

On this page you can see how all EasyOpt features can be used in several annotated examples.

time

This example shows how EasyOpt could be used to parse selected options of Unix command time.

The usage of this sample program is:

 time [options] command [arguments...]

    -o, --output=FILE
        Do not send the results to stderr, but overwrite the specified file.

    -a, --append
        (Used together with -o.) Do not overwrite but append

    -f, --format=FORMAT
        Specify output format, possibly overriding the format specified in the
        environment variable TIME.

    --help
        Print a usage message on standard output and exit successfully.

    -p, --portability
        Use the portable output format

    -v, --verbose
        Give very verbose output about all the program knows about.

    --quiet
        Do not report the status of the program even if it is different

    -V, --version
        Print version information on standard output, then exit successfully.

Program source code (download):

static void Main(string[] args) {
  // Create a parser instance
  EasyOpt parser = new EasyOpt();
 
  // Create a new string parameter.
  var outputParam = new StringParameter(true, "FILE");
  // Create an option with the string parameter
  var output = OptionFactory.Create(
    false, // The option is not required
    "Do not send the results to stderr, but overwrite the specified file.", // Description for usage text
    outputParam // Option parameter
  );
  // Register to the parser. The option will have a short name -o and a long name --output
  parser.AddOption(output, 'o', "output");
 
  // Create a new option without a parameter
  var append = OptionFactory.Create(false, "(Used together with -o.) Do not overwrite but append");
  parser.AddOption(append, 'a', "append");
 
  // Create a new string parameter. The third argument defines its default value.
  var formatParam = new StringParameter(true, "FORMAT", "real %f\nuser %f\nsys %f\n");
  var format = OptionFactory.Create(
      false,
      "Specify output format, possibly overriding the format specified in the environment variable TIME.",
      formatParam
  );
  parser.AddOption(format, 'f', "format");
 
  var help = OptionFactory.Create(false, "Print a usage message on standard output and exit successfully.");
  parser.AddOption(help, "help");
 
  var portability = OptionFactory.Create(false, "Use the portable output format");
  parser.AddOption(portability, 'p', "portability");
 
  var verbose = OptionFactory.Create(false, "Give very verbose output about all the program knows about.");
  parser.AddOption(verbose, 'v', "verbose");
 
  var quiet = OptionFactory.Create(false, "Do not report the status of the program even if it is different");
  parser.AddOption(quiet, "quiet");
 
  var version = OptionFactory.Create(false, "Print version information on standard output, then exit successfully.");
  parser.AddOption(version, 'V', "version");
 
  // Description displayed in the usage text
  parser.UsageDescription = " time [options] command [arguments...]";
 
  try {
    // The actual argument parsing
    parser.Parse(args);
  }
  catch (EasyOptException) {
    // Some options were invalid, print usage text and exit
    Console.Write( parser.GetUsage() );
    return;
  }
 
  // Find out whether --output option was defined
  bool isOutputPresent = output.IsPresent;
  // Retrieve value of the string parameter of --output option
  String outputValue = output.Value;
 
  // Find out whether --append option was defined
  bool appendValue = append.IsPresent;
  // Alternatively, for options without a parameter, you can equivalently use the following
  appendValue = append.Value;
 
  // Retrieve --format option parameter; if the option is not defined, retrieves the default value
  String formatValue = format.Value;
 
  // Values of other options can be retrieved in the same way
  bool helpValue = help.Value;
  bool portabilityValue = portability.Value;
  bool verboseValue = verbose.Value;
  bool quietValue = quiet.Value;
  bool versionValue = version.Value;
 
  // Get list of non-option arguments
  String[] arguments = parser.GetArguments();
}

ls

This example shows how EasyOpt could be used to parse selected options of Unix command ls. In this example you can see use of the powerful parameter type EnumParameter<T>, several predefined constraints and how a custom parameter type can be defined. For purposes of this example ls --block-size option is simplified.

The usage message for this sample program is:

 ls [OPTION]... [FILE]...

    -a, --all
        do not ignore entries starting with .

    --author
        with -l, print the author or each file

    --block-size=SIZE
        use SIZE-byte blocks; SIZE  may  be one of following: kB1000, KB1024,
        MB1000 and so on for G, T, P, E, Z, Y.

    --color[=WHEN]
        control whether color is used to distinguish file types. WHEN may be
        'never', 'always' or 'auto'

    --format=WORD
        across  -x, commas -m, horizontal -x, long -l, single-column -1,
        verbose -l, vertical -C

    --quoting-style=WORD
        use quoting style WORD for entry names: literal, locale, shell,
        shell-always, c, escape

    -T, --tabsize=COLS
        assume tab stops at each COLS instead of 8

Program source code (download):

enum SizeUnit {
  kB, MB, GB, TB, PB, EB, ZB, YB
}
 
class Size {
  public SizeUnit Unit { get; set; }
  public int Value { get; set; }
  public Size(int value, SizeUnit unit) {
    this.Value = value;
    this.Unit = unit;
  }
}
 
// Custom parameter class that converts option parameter to type Size
class SizeParameter : Parameter<Size> {
  public SizeParameter(bool isRequired, String usageName)
      : base(isRequired, usageName, default(Size))
  { }
 
  // Custom parameter has to override this abstract method
  // It defines a conversion function from string parameter value to type Size
  protected override Size convert(string parameterValue) {
    var match = System.Text.RegularExpressions.Regex.Match(parameterValue, @"^(\w+)(\d+)$");
    if (!match.Success) {
      // In case that conversion fails, throw an exception
      throw new ParameterConversionException(parameterValue, this);
    }
    try {
      SizeUnit unit = (SizeUnit) Enum.Parse(typeof(SizeUnit), match.Groups[1].Value, true);
      int value = Int32.Parse(match.Groups[2].Value);
      return new Size(value, unit);
    }
    catch (Exception) {
      throw new ParameterConversionException(parameterValue, this);
    }
  }
}
 
// This enum type will be used in conjuction with EnumParameter
enum Color {
  Never, Always, Auto
}
 
class Program {
  static void Main(string[] args) {
    // Create a new parser instance
    EasyOpt parser = new EasyOpt();
 
    // Create options without a parameter
    var all = OptionFactory.Create(false, "do not ignore entries starting with .");
    parser.AddOption(all, 'a', "all");
 
    var author = OptionFactory.Create(false, "with -l, print the author or each file");
    parser.AddOption(author, "author");
 
    // Create a new option with the custom parameter type defined earlier
    var blockSizeParam = new SizeParameter(true, "SIZE");
    // Factory method Create() infers the proper option type Option<Size> from blockSizeParam type
    var blockSize = OptionFactory.Create(
        false,
        "use SIZE-byte blocks; SIZE  may  be one of following:"+
        " kB1000, KB1024, MB1000 and so on for G, T, P, E, Z, Y.",
        blockSizeParam
    );
    parser.AddOption(blockSize, "block-size");
 
    // With EnumParameter<T> you can easily define range of accepted values
    // and EnumParameter will convert parameter to the specified enum type.
    var colorParam = new EnumParameter<Color>(false, "WHEN", Color.Auto);
    // You can set whether the conversion is case-sensitive (default is case-insensitive)
    colorParam.IgnoreCase = true;
    var color = OptionFactory.Create(
        false,
        "control whether color is used to distinguish file types. " +
        "WHEN may be 'never', 'always' or 'auto'",
        colorParam
    );
    parser.AddOption(color, "color");
 
    // Create an option with a string parameter
    var formatParam = new StringParameter(true, "WORD");
    var format = OptionFactory.Create(
        false,
        "across  -x, commas -m, horizontal -x, long -l, single-column -1, verbose -l, vertical -C",
        formatParam
    );
    parser.AddOption(format, "format");
 
    // Create an option with a string parameter
    var quotingStyleParam = new StringParameter(true, "WORD");
    var quotingStyles = new String[] { "literal", "locale", "shell", "shell-always", "c", "escape" };
    // StringEnumerationConstraint restricts the range of parameter values to the defined list of values
    quotingStyleParam.AddConstraint(new StringEnumerationConstraint(quotingStyles, true));
    var quotingStyle = OptionFactory.Create(
        false,
        "use quoting style WORD for entry names: literal, locale, shell, shell-always, c, escape",
        quotingStyleParam
    );
    parser.AddOption(quotingStyle, "quoting-style");
 
    // Create an option with int parameter
    var tabsizeParam = new IntParameter(true, "COLS", 8);
    // Parameter value must be non-negative
    tabsizeParam.AddConstraint(new LowerBoundConstraint(0));
    var tabsize = OptionFactory.Create(false, "assume tab stops at each COLS instead of 8", tabsizeParam);
    parser.AddOption(tabsize, 'T', "tabsize");
 
    // Description displayed in the usage text
    parser.UsageDescription = " ls [OPTION]... [FILE]...";
 
    try {
      // The actual argument parsing
      parser.Parse(args);
    }
    catch (EasyOptException e) {
      // Some options were invalid (e.g. a parameter constraint or conversion failed)
      // Print usage text and exit
      Console.Write( parser.GetUsage() );
      return;
    }
 
    // Retrieve some option values
    // Retrieve whether --all option is on
    bool allValue = all.Value;
    // Retrieve --block-size parameter converted to Size
    Size blockSizeValue = blockSize.Value;
    // Retrieve --color parameter converted to Color enum type
    Color colorValue = color.Value;
    // Retrieve --quoting-style value; the value must me one of the strings in quotingStyles or default value ("")
    String quotingValue = quotingStyle.Value;
 
    // Get list of non-option arguments
    String[] arguments = parser.GetArguments();
  }
}

touch

This example shows how EasyOpt could be used to parse selected options of Unix command touch. In this example you can see how to define custom constraints.

The usage of this sample program is:

 touch [OPTION]... [FILE]...

    -a
        change only the access time

    -c, --no-create
        do not create any files

    -d, --date=STRING
        parse STRING and use it instead of current time

    -r, --reference=FILE
        use this file's times instead of current time

    -t STAMP
        use [[CC]YY]MMDDhhmm[.ss] instead of current time

    --time=WORD
        change the specified time: WORD is access, atime, or use

    --version
        output version information and exit

Program source code (download):

// A custom constraint
class TimeConstraint : IConstraint<String> {
  public bool IsValid(String parameter) {
    var r = new System.Text.RegularExpressions.Regex(@"^((\d\d)?\d\d)?(\d){8}(\.\d\d)?$");
    return r.IsMatch(parameter);
  }
}
 
enum Time {
  Access, Atime, Use
}
 
class Program {
  static void Main(string[] args) {
    // Create a new parser instance
    EasyOpt parser = new EasyOpt();
 
    // Add some options
    var accessTime = OptionFactory.Create(false, "change only the access time");
    parser.AddOption(accessTime, 'a');
 
    var noCreate = OptionFactory.Create(false, "do not create any files");
    parser.AddOption(noCreate, 'c', "no-create");
 
    var dateParam = new StringParameter(true, "STRING");
    var date = OptionFactory.Create(false, "parse STRING and use it instead of current time", dateParam);
    parser.AddOption(date, 'd', "date");
 
    var referenceParam = new StringParameter(true, "FILE");
    // ExistingFileConstraint ensures that the parameter value is a valid path to an existing file
    referenceParam.AddConstraint(new ExistingFileConstraint());
    var reference = OptionFactory.Create(false, "use this file's times instead of current time", referenceParam);
    parser.AddOption(reference, 'r', "reference");
 
    var stampParam = new StringParameter(true, "STAMP");
    // Apply the custom constraint defined earlier to the parameter
    stampParam.AddConstraint(new TimeConstraint());
    var stamp = OptionFactory.Create(false, "use [[CC]YY]MMDDhhmm[.ss] instead of current time", stampParam);
    parser.AddOption(stamp, 't');
 
    // Use EnumParameter to restrict the range of parameter values and convert the value to Time
    var timeParam = new EnumParameter<Time>(true, "WORD");
    var time = OptionFactory.Create(false, "change the specified time: WORD is access, atime, or use", timeParam);
    parser.AddOption(time, "time");
 
    var version = OptionFactory.Create(false, "output version information and exit");
    parser.AddOption(version, "version");
 
    // Description displayed in the usage text
    parser.UsageDescription = " touch [OPTION]... [FILE]...";
 
    try {
      // The actual argument parsing
      parser.Parse(args);
    }
    catch (EasyOptException e) {
      // Some options were invalid, print usage text and exit
      Console.Write( parser.GetUsage() );
      return;
    }
 
    // Retrieve some option values
    bool accessTimeValue = accessTime.Value;
    String dateValue = date.Value;
    String referenceValue = reference.Value;
    String stampValue = stamp.Value;
    Time timeValue = time.Value;
 
    // Get list of non-option arguments
    String[] arguments = parser.GetArguments();
  }
}

Clone this wiki locally