cmdlineopt.cpp

00001 // Copyright (C) 2001 Gianni Mariani
00002 //
00003 // This program is free software; you can redistribute it and/or modify
00004 // it under the terms of the GNU General Public License as published by
00005 // the Free Software Foundation; either version 2 of the License, or
00006 // (at your option) any later version.
00007 //
00008 // This program is distributed in the hope that it will be useful,
00009 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00010 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00011 // GNU General Public License for more details.
00012 //
00013 // You should have received a copy of the GNU General Public License
00014 // along with this program; if not, write to the Free Software
00015 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
00016 //
00017 // As a special exception to the GNU General Public License, permission is
00018 // granted for additional uses of the text contained in its release
00019 // of Common C++.
00020 //
00021 // The exception is that, if you link the Common C++ library with other
00022 // files to produce an executable, this does not by itself cause the
00023 // resulting executable to be covered by the GNU General Public License.
00024 // Your use of that executable is in no way restricted on account of
00025 // linking the Common C++ library code into it.
00026 //
00027 // This exception does not however invalidate any other reasons why
00028 // the executable file might be covered by the GNU General Public License.
00029 //
00030 // This exception applies only to the code released under the
00031 // name Common C++.  If you copy code from other releases into a copy of
00032 // Common C++, as the General Public License permits, the exception does
00033 // not apply to the code that you add in this way.  To avoid misleading
00034 // anyone as to the status of such modified files, you must delete
00035 // this exception notice from them.
00036 //
00037 // If you write modifications of your own for Common C++, it is your choice
00038 // whether to permit this exception to apply to your modifications.
00039 // If you do not wish that, delete this exception notice.
00040 //
00041 
00042 
00043 //
00044 // Example for Common C++ the command line parser interface.
00045 //
00046 //
00047 // This exmaple code shows how to use the command line parser provided by
00048 // CommonC++.  The command line parser provides an interface which is
00049 // "object oriented" such that command line parameters are true "objects".
00050 //
00051 // Each command line option needs to be created.  By defining "CommandOption"s
00052 // statically, the C++ constructor is called when the objects are loaded and
00053 // before the "main" function is called.  The constructor links itself to
00054 // a list of other CommandOptionXXX in the list provided.  If no
00055 // list is specified in the constructor, a default one is used. Because of
00056 // the undefined nature as to the order in which constructors are called,
00057 // no assumption as to the order in which the CommandOptionXXX constructors
00058 // are called should be made.
00059 //
00060 // CommandOptionXXX classes can be used to derive specialized parameter
00061 // classes that are specific to applications.  The second example shows
00062 // just how this can be done.
00063 //
00064 
00065 //
00066 // Include the CommandOption definitions
00067 //
00068 #include <cc++/common.h>
00069 
00070 #include <iostream>
00071 #ifndef WIN32
00072 #include <cstdlib>
00073 #endif
00074 
00075 #ifdef  CCXX_NAMESPACES
00076 using namespace std;
00077 using namespace ost;
00078 #endif
00079 
00080 //
00081 // The following definition of options all use the list header
00082 // defaultCommandOptionList (which is specified as the value of the
00083 // default parameter in the constructor.  This convention would
00084 // allow other object files to link into the same list and add parameters
00085 // to the command line of this executable.
00086 
00087 CommandOptionArg        test_option1(
00088         "test_option1", "p", "This option takes an argument", true
00089 );
00090 
00091 CommandOptionNoArg      test_noarg(
00092         "test_noarg", "b", "This option does not take an argument"
00093 );
00094 
00095 CommandOptionNoArg      helparg(
00096         "help", "?", "Print help usage"
00097 );
00098 
00099 CommandOptionCollect    restoargs(
00100         0, 0, "Collect all the parameters", true
00101 );
00102 
00103 
00104 //
00105 // Normally this would me the regular main().  In this example
00106 // this processes the first command option list.
00107 //
00108 int Example_main( int argc, char ** argv )
00109 {
00110 
00111         // Create a CommandOptionParse object.  This takes the
00112         // defaultCommandOptionList and parses the command line arguments.
00113         //
00114         CommandOptionParse * args = makeCommandOptionParse(
00115                 argc, argv,
00116                 "CommonC++ command like option interface.  This is example\n"
00117                 "       code only."
00118         );
00119 
00120         // If the user requested help then suppress all the usage error
00121         // messages.
00122         if ( helparg.numSet ) {
00123                 cerr << args->printUsage();
00124                 ::exit(0);
00125         }
00126 
00127         // Print usage your way.
00128         if ( args->argsHaveError() ) {
00129                 cerr << args->printErrors();
00130                 cerr << args->printUsage();
00131                 ::exit(1);
00132         }
00133 
00134         // Go off and run any option specific task
00135         args->performTask();
00136 
00137         // print all the -p options
00138         for ( int i = 0; i < test_option1.numValue; i ++ ) {
00139                 cerr << "test_option1 = " << test_option1.values[ i ] << endl;
00140         }
00141 
00142         // print all the other options.
00143         for ( int i = 0; i < restoargs.numValue; i ++ ) {
00144                 cerr << "restoargs " << i << " : " << restoargs.values[ i ] << endl;
00145         }
00146 
00147         delete args;
00148 
00149         return 0;
00150 }
00151 
00152 
00153 //
00154 // This shows how to build a second option list.  The example is similar to
00155 // the first as well as it shows how to derive a new command object.
00156 //
00157 
00158 CommandOption * TestList = 0;
00159 
00160 extern CommandOptionRest        test_restoargs;
00161 
00162 #include <unistd.h>
00163 #include <sys/types.h>
00164 #include <sys/stat.h>
00165 #include <fcntl.h>
00166 #include <errno.h>
00167 #include <string.h>
00168 #include <stdlib.h>
00169 #include <sys/wait.h>
00170 #include <strstream>
00171 
00172 //
00173 // This is a parameter class derived from CommandOptionArg that takes
00174 // a file name parameter and detects wether the file is accessible
00175 // flagging an error if the file is inaccessible to read.
00176 //
00177 class file_option : public CommandOptionArg {
00178 public:
00179 
00180         // the constructor calls the regular CommandOptionArg constructor
00181         // and all should be well.
00182         file_option(
00183                 const char      * in_option_name,
00184                 const char      * in_option_letter,
00185                 const char      * in_description,
00186                 bool              in_required = false,
00187                 CommandOption  ** pp_next = & defaultCommandOptionList
00188         )
00189                 : CommandOptionArg(
00190                         in_option_name,
00191                         in_option_letter,
00192                         in_description,
00193                         in_required,
00194                         pp_next
00195                 )
00196         {
00197         }
00198 
00199         //
00200         // When parsing is done check if the file is accessible and register
00201         // an error with the CommandOptionParse object to let it know so.
00202         virtual void parseDone( CommandOptionParse * cop ) {
00203                 if ( numValue ) {
00204                         if ( ::access( values[ numValue - 1 ], R_OK ) ) {
00205                                 int     errno_s = errno;
00206                                 strstream msg;
00207                                 msg << "Error: " << optionName << " '" << values[ numValue - 1 ];
00208                                 msg << "' : " << ::strerror( errno_s );
00209 
00210                                 cop->registerError( msg.str() );
00211                         }
00212                 }
00213         }
00214 
00215         //
00216         // Open said file.  Do some operations on things - like open the file.
00217         int OpenFile() {
00218                 // Should put in way more error handling here ...
00219                 return ::open( values[ numValue - 1 ], O_RDONLY );
00220         }
00221 
00222         //
00223         // The most elaborate way to spit the contents of a file
00224         // to standard output.
00225         pid_t   pid;
00226         virtual void performTask( CommandOptionParse * cop ) {
00227                 pid = ::fork();
00228 
00229                 if ( pid ) {
00230                         return;
00231                 }
00232 
00233                 int fd = OpenFile();
00234                 if ( fd < 0 ) {
00235                         int errno_s = errno;
00236                         cerr
00237                                 << "Error:  '"
00238                                 << values[ numValue - 1 ]
00239                                 << "' : "
00240                                 << ::strerror( errno_s )
00241                         ;
00242 
00243                         ::exit( 1 );
00244                 }
00245                 dup2(fd, 0);
00246                 ::execvp( test_restoargs.values[0], (char**) test_restoargs.values );
00247                 ::exit(1);
00248         }
00249 
00250         ~file_option() {
00251                 if ( pid <= 0 ) return;
00252                 int status;
00253 		::wait(&status);
00254         }
00255 };
00256 
00257 
00258 //
00259 // This is the linked list head for the options in the second example.
00260 // Note that the first example used the default value defined in the
00261 // method.  Here it is explicitly specified as TestList in all the following
00262 // CommandOption constructors.
00263 
00264 file_option     test_file(
00265         "test_file", "f", "Filename to read from", true, &TestList
00266 );
00267 
00268 CommandOptionNoArg      test_xnoarg(
00269         "test_xnoarg", "b", "This option does not take an argument", false, &TestList
00270 );
00271 
00272 CommandOptionNoArg      test_helparg(
00273         "help", "?", "Print help usage", false, &TestList
00274 );
00275 
00276 CommandOptionRest       test_restoargs(
00277         0, 0, "Command to be executed", true, &TestList
00278 );
00279 
00280 //
00281 // in most apps this would be the regular "main" function.
00282 int Test_main( int argc, char ** argv )
00283 {
00284         CommandOptionParse * args = makeCommandOptionParse(
00285                 argc, argv,
00286                 "Command line parser X test.\n"
00287                 "       This example is executed when the command ends in 'x'\n"
00288                 "       It shows how the -f parameter can be specialized.\n",
00289                 TestList
00290         );
00291 
00292         // If the user requested help then suppress all the usage error
00293         // messages.
00294         if ( test_helparg.numSet ) {
00295                 cerr << args->printUsage();
00296                 ::exit(0);
00297         }
00298 
00299         // Print usage your way.
00300         if ( args->argsHaveError() ) {
00301                 cerr << args->printErrors();
00302                 cerr << "Get help by --help\n";
00303                 ::exit(1);
00304         }
00305 
00306         // Go off and run any option specific task
00307         args->performTask();
00308 
00309         for ( int i = 0; i < test_file.numValue; i ++ ) {
00310                 cerr << "test_file = " << test_file.values[ i ] << endl;
00311         }
00312 
00313         for ( int i = 0; i < test_restoargs.numValue; i ++ ) {
00314                 cerr << "test_restoargs " << i << " : " << test_restoargs.values[ i ] << endl;
00315         }
00316 
00317         delete args;
00318 
00319         return 0;
00320 }
00321 
00322 
00323 //
00324 // This switches behaviour of this executable depending of wether it is
00325 // invoked with a command ending in "x".  This is mimicking for example
00326 // the behaviour of bunzip2 and bzip2.  These executables are THE SAME
00327 // file i.e.
00328 //   0 lrwxrwxrwx    1 root     root    5 Oct 11 14:04 /usr/bin/bunzip2 -> bzip2*
00329 // and the behaviour is determined by the executable name.
00330 //
00331 // This example is way more complex than the way most people will end up
00332 // using feature.
00333 
00334 int main( int argc, char ** argv )
00335 {
00336 
00337         int i = ::strlen( argv[ 0 ] );
00338 
00339         // determine which real "main" function do I call
00340         if ( argv[ 0 ][ i - 1 ] == 'x' ) {
00341                 return Test_main( argc, argv );
00342         } else {
00343                 return Example_main( argc, argv );
00344         }
00345 
00346 }

Generated on Sun Mar 21 21:38:46 2010 for GNU CommonC++ by  doxygen 1.4.7