home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1994 March / Source_Code_CD-ROM_Walnut_Creek_March_1994.iso / compsrcs / misc / volume31 / cmdline / part00 < prev    next >
Encoding:
Text File  |  1992-07-26  |  11.2 KB  |  277 lines

  1. Newsgroups: comp.sources.misc
  2. From: brad@hcx1.ssd.csd.harris.com (Brad Appleton)
  3. Subject:  v31i047:  cmdline - C++ Library for parsing command-line arguments, Part00/07
  4. Message-ID: <csm-v31i047=cmdline.205609@sparky.IMD.Sterling.COM>
  5. X-Md4-Signature: 3351d1adac625399f0fad30110439c3c
  6. Date: Mon, 27 Jul 1992 01:57:10 GMT
  7. Approved: kent@sparky.imd.sterling.com
  8.  
  9. Submitted-by: brad@hcx1.ssd.csd.harris.com (Brad Appleton)
  10. Posting-number: Volume 31, Issue 47
  11. Archive-name: cmdline/part00
  12. Environment: C++
  13.  
  14.                     An overview of CmdLine and cmdparse
  15.                     ===================================
  16.  
  17.                  by Brad Appleton <brad@ssd.csd.harris.com>
  18.  
  19.  
  20.  Introduction
  21.  ------------
  22.  CmdLine is a C++ Library for parsing command-line arguments. It is 
  23.  approximately 2000 lines of C++ code (excluding comments).
  24.  
  25.  Cmdparse is a command-line interface to CmdLine for Unix shell-scripts.
  26.  It is approximately 1200 lines of C++ code (excluding comments).
  27.  
  28.  
  29.  CmdLine(3C++)
  30.  -------------
  31.  CmdLine is a set of classes to parse command-line arguments.  Unlike
  32.  getopt() and its variants, CmdLine does more than just split up the
  33.  command-line into some canonical form.  CmdLine will actually parse
  34.  the command-line, assigning the appropriate command-line values to
  35.  the corresponding variables, and will verify the command-line syntax
  36.  (and print a usage message if necessary) all in one member function
  37.  call.  Furthermore, many features of CmdLine's parsing behavior are
  38.  configurable at run-time.  These features include the following:
  39.  
  40.      o  Prompting the user for missing arguments.
  41.      o  Allowing keywords (-count=4) and/or options (-c4).
  42.      o  Ignoring bad syntax instead of terminating.
  43.      o  Ignoring upper/lower case on the command-line.
  44.      o  Suppressing the printing of syntax error messages.
  45.      o  Controlling the verboseness of usage messages.
  46.      o  Controlling whether or not options may be processed
  47.           after positional parameters have been seen.
  48.  
  49.  CmdLine also allows for options that take an optional argument, options
  50.  that take a (possibly optional) list of one or more arguments, options
  51.  whose argument must reside in the same token as the option itself, and
  52.  options whose argument must reside in a separate token from the option
  53.  itself.
  54.  
  55.  CmdLine consists of a set of C++ classes to parse arguments from an
  56.  input source called a CmdLineArgIter (which is a base class for iterating
  57.  over arguments from an arbitrary input source).  Argument iterators are
  58.  defined for an argv[] array (with or without a corresponding argc), for
  59.  a string of tokens that are separated by a given set of delimiters, and
  60.  for an input-stream.  Users can easily extend CmdLine to parse arguments
  61.  from other input sources simply by creating their own argument iterator
  62.  classes derived from the CmdLineArgIter class defined in <cmdline.h>.
  63.  
  64.  Command-line arguments are themselves objects that contain a specific
  65.  command-line interface, and a function that performs the desired actions
  66.  when its corresponding argument is seen on the command line.  Predefined
  67.  command-line argument types (derived from the abstract class CmdArg in
  68.  <cmdline.h>) exist for boolean, integer, floating-point, character, and
  69.  string arguments, and for lists of integers, floats, and strings.  These
  70.  predefined subclasses of CmdArg may be found in <cmdargs.h>.  Users can
  71.  also create their own command-argument types on the fly by defining and
  72.  implementing an appropriate subclass of the CmdArg class.
  73.  
  74.  Using CmdLine is relatively easy - you need to construct your arguments,
  75.  your command-line, and your argument iterator.  Then all that is left to
  76.  do is call the "parse" member function of your CmdLine object.  The
  77.  following is a simple example:
  78.  
  79.     #include <stdlib.h>
  80.     #include <iostream.h>
  81.     #include <cmdargs.h>
  82.  
  83.     int  main(int argc, char * argv[])
  84.     {
  85.           // Declare arguments
  86.        CmdArgInt  count('c', "count", "number", "number of copies to print.");
  87.        CmdArgBool xflag('x', "xmode", "turn on 'x'-mode.");
  88.        CmdArgChar fdsep('s', "separator", "char", "field-separator to use.");
  89.        CmdArgStr  input("input-file",  "input file to read.");
  90.        CmdArgStrList  output("[output-file ...]",  "where to print output.");
  91.  
  92.           // Declare command object and its argument-iterator
  93.        CmdLine  cmd(*argv, &count, &xflag, &fdsep, &input, &output, NULL);
  94.        CmdArgvIter  arg_iter(--argc, ++argv);
  95.  
  96.           // Initialize arguments to appropriate default values.
  97.        count = 1;
  98.        xflag = 0;
  99.        fdsep = ',';
  100.  
  101.           // Parse arguments
  102.        cmd.parse(arg_iter);
  103.  
  104.           // Print arguments
  105.        cout << "count=" << count << endl ;
  106.        cout << "xflag=" << (xflag ? "ON" : "OFF") << endl ;
  107.        cout << "fdsep='" << (char) fdsep << "'" << endl ;
  108.        cout << "input=\"" << input << "\"" << endl ;
  109.        
  110.        for (int i = 0 ; i < output.count() ; i++) {
  111.           cout << "output[" << i << "]=" << output[i] << endl ;
  112.        }
  113.  
  114.        return  0;
  115.     }
  116.  
  117.  
  118.  The Unix command-line syntax for the above program would be as follows:
  119.  
  120.     Usage: progname [-c number] [-x] [-s char] input-file [output-file ...]
  121.  
  122.     Options/Arguments:
  123.             -c number        number of copies to print.
  124.             -x               turn on 'x'-mode.
  125.             -s char          field-separator to use.
  126.             input-file       input file to read.
  127.             output-file ...  where to print output.
  128.  
  129.  
  130.  The Unix command-line syntax using long-options (keywords) for the above
  131.  program would be as follows:
  132.  
  133.     Usage: progname [--count number] [--xmode] [--separator char]
  134.                     input-file [output-file ...]
  135.  
  136.     Options/Arguments:
  137.             --count number    number of copies to print.
  138.             --xmode           turn on 'x'-mode.
  139.             --separator char  field-separator to use.
  140.             input-file        input file to read.
  141.             output-file ...   where to print output.
  142.  
  143.  
  144.  By default, CmdLine allows both options and long-options to appear on the
  145.  command-line. You can instruct CmdLine to disallow one or the other however.
  146.  As an "extra", when options are disallowed, the "-" prefix is assumed to
  147.  denote a long-option instead of an option (hence either "-" or "--" denotes
  148.  a keyword in this case).  Using this feature, CmdLine can be used to supply
  149.  the type of long-option syntax that is now becoming quite popular in the
  150.  Unix world. Using this "new" syntax, the command-line syntax for the above
  151.  command would be the following:
  152.  
  153.     Usage: progname [-count number] [-xmode] [-separator char]
  154.                     input-file [output-file ...]
  155.  
  156.     Options/Arguments:
  157.             -count number    number of copies to print.
  158.             -xmode           turn on 'x'-mode.
  159.             -separator char  field-separator to use.
  160.             input-file       input file to read.
  161.             output-file ...  where to print output.
  162.  
  163.  
  164.  It should be mentioned that, when long-options are used, only a unique
  165.  prefix of the keyword needs to be given (and character-case is ignored).
  166.  Hence, in the above example, "-x", "-X", and "-xm" will match "-xmode".
  167.  
  168.  
  169.  cmdparse(1)
  170.  -----------
  171.  Using "cmdparse" is even easier than using CmdLine. You declare your
  172.  arguments in a string and then you invoke cmdparse with the command
  173.  line of your shell-script and cmdparse will output a script of variable
  174.  settings for you to evaluate.  The following is an example (using the
  175.  same arguments as in our sample program):
  176.  
  177.     #!/bin/sh
  178.     NAME="`/bin/basename $0`"
  179.  
  180.     ARGS='
  181.        ArgInt   count  "[c|count number]"    "number of copies to print."
  182.        ArgBool  xflag  "[x|xmode]"           "turn on x-mode."
  183.        ArgChar  fdsep  "[s|separator char]"  "field-separator to use."
  184.        ArgStr   input  "input-file"          "input file to read."
  185.        ArgStr   output "[output-file ...]"   "where to print output."
  186.     '
  187.  
  188.     if  cmdparse -shell=sh -decls="$ARGS" -- $NAME "$@" > tmp$$
  189.     then
  190.        . tmp$$
  191.        /bin/rm -f tmp$$
  192.     else
  193.        EXITVAL=$?
  194.        /bin/rm -f tmp$$
  195.        exit $EXITVAL
  196.     fi
  197.  
  198.     echo "xflag=" $xflag
  199.     echo "count=" $count
  200.     echo "fdsep=" $fdsep
  201.     echo "input=" $input
  202.     if [ "$output" ] ; then
  203.        echo "output=" $output
  204.     fi
  205.  
  206.  
  207.  Note that you declare the syntax of an argument differently for cmdparse
  208.  than for CmdLine. The syntax for a single argument for cmdparse looks like
  209.  the following:
  210.  
  211.     <arg-type>  <arg-name>  <syntax>  <description>
  212.  
  213.  Where <arg-type> is one of the following:
  214.  
  215.     ArgInt     --  an integer value (or list of values)
  216.     ArgFloat   --  a floating-point value (or list of values)
  217.     ArgChar    --  a character value (or list of values)
  218.     ArgStr     --  a string value (or list of values)
  219.     ArgBool    --  a boolean flag that is turned ON
  220.     ArgClear   --  a boolean flag that is turned OFF
  221.     ArgToggle  --  a boolean flag that is toggled
  222.     ArgUsage   --  print usage and exit
  223.     ArgDummy   -- a dummy argument
  224.  
  225.  If desired, the leading "Arg" portion may be omitted from the type-name.
  226.  
  227.  <arg-name> is simply the name of the variable in your script that you wish
  228.  to contain the resultant value from the command-line.  Any default value
  229.  must be assigned to the variable before invoking cmdparse.
  230.  
  231.  <syntax> and <description> *MUST* be enclosed in either single or double
  232.  quotes! <description> is simply that, the description of the argument.
  233.  
  234.  <syntax> is a little trickier, there are three basic forms of syntax:
  235.  
  236.    1)  "c|keyword"        -- an option the takes no value
  237.    2)  "c|keyword value"  -- an option that takes a value
  238.    3)  "value"            -- a positional parameter
  239.  
  240.  Note that the option-character MUST precede the keyword-name and that
  241.  there must be NO spaces surrounding the '|' in "c|keyword"!
  242.  
  243.  Any "optional" parts of the argument should appear inside square-brackets
  244.  ('[' and ']') and a list of values is denoted by an ellipsis (" ...").
  245.  Most options will be inside of square brackets to reflect the fact that
  246.  they are "optional".
  247.  
  248.  Some example <syntax> strings follow:
  249.  
  250.     "c|keyword"                -- a required option
  251.     "[c|keyword]"              -- an option with no value
  252.     "[c|keyword value]"        -- an option that takes a value
  253.     "[c|keyword [value]]"      -- an option that takes an optional value
  254.     "[c|keyword value ...]"    -- an option that takes 1 or more values
  255.     "[c|keyword [value ...]]"  -- an option that takes 0 or more values
  256.     "value"                    -- a required positional parameter
  257.     "[value]"                  -- an optional positional-parameter
  258.     "[c|keyword] value"        -- a required argument that may be matched
  259.                                   either positionally or by keyword!
  260.  
  261.  
  262.  Further Information
  263.  -------------------
  264.  This is just a brief overview of what the CmdLine package can do. Please
  265.  read the documentation for a more thorough explanation of this products'
  266.  capabilities and limitations!
  267.  
  268.  
  269. ______________________ "And miles to go before I sleep." ______________________
  270.  Brad Appleton                         Harris Corp., Computer Systems Division
  271.    Senior Software Engineer            2101 West Cypress Creek Road,  M/S 161 
  272.      brad@ssd.csd.harris.com           Fort Lauderdale, FL  33309-1892  USA
  273.        ...!uunet!travis!brad                 Phone: (305) 973-5190
  274. ~~~~~~~~~~~~~~~~~~~~ Disclaimer: I said it, not my company! ~~~~~~~~~~~~~~~~~~~
  275.  
  276. exit 0 # Just in case...
  277.