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 
00072 #ifdef  CCXX_NAMESPACES
00073 using namespace std;
00074 using namespace ost;
00075 #endif  
00076 
00077 //
00078 // The following definition of options all use the list header
00079 // defaultCommandOptionList (which is specified as the value of the
00080 // default parameter in the constructor.  This convention would
00081 // allow other object files to link into the same list and add parameters
00082 // to the command line of this executable.
00083 
00084 CommandOptionArg        test_option1(
00085         "test_option1", "p", "This option takes an argument", true
00086 );
00087 
00088 CommandOptionNoArg      test_noarg(
00089         "test_noarg", "b", "This option does not take an argument"
00090 );
00091 
00092 CommandOptionNoArg      helparg(
00093         "help", "?", "Print help usage"
00094 );
00095 
00096 CommandOptionCollect    restoargs(
00097         0, 0, "Collect all the parameters", true
00098 );
00099 
00100 
00101 //
00102 // Normally this would me the regular main().  In this example
00103 // this processes the first command option list.
00104 //
00105 int Example_main( int argc, char ** argv )
00106 {
00107 
00108         // Create a CommandOptionParse object.  This takes the
00109         // defaultCommandOptionList and parses the command line arguments.
00110         // 
00111         CommandOptionParse * args = makeCommandOptionParse(
00112                 argc, argv,
00113                 "CommonC++ command like option interface.  This is example\n"
00114                 "       code only."
00115         );
00116 
00117         // If the user requested help then suppress all the usage error
00118         // messages.
00119         if ( helparg.numSet ) {
00120                 cerr << args->printUsage();
00121                 ::exit(0);
00122         }
00123 
00124         // Print usage your way.
00125         if ( args->argsHaveError() ) {
00126                 cerr << args->printErrors();
00127                 cerr << args->printUsage();
00128                 ::exit(1);
00129         }
00130 
00131         // Go off and run any option specific task
00132         args->performTask();
00133 
00134         // print all the -p options
00135         for ( int i = 0; i < test_option1.numValue; i ++ ) {
00136                 cerr << "test_option1 = " << test_option1.values[ i ] << endl;
00137         }
00138 
00139         // print all the other options.
00140         for ( int i = 0; i < restoargs.numValue; i ++ ) {
00141                 cerr << "restoargs " << i << " : " << restoargs.values[ i ] << endl;
00142         }
00143 
00144         delete args;
00145 
00146         return 0;
00147 }
00148 
00149 
00150 // 
00151 // This shows how to build a second option list.  The example is similar to
00152 // the first as well as it shows how to derive a new command object.
00153 //
00154 
00155 CommandOption * TestList = 0;
00156 
00157 extern CommandOptionRest        test_restoargs;
00158 
00159 
00160 #include <unistd.h>
00161 #include <sys/types.h>
00162 #include <sys/stat.h>
00163 #include <fcntl.h>
00164 #include <strstream>
00165 #include <errno.h>
00166 #include <string.h>
00167 #include <stdlib.h>
00168 #include <sys/wait.h>
00169 
00170 
00171 //
00172 // This is a parameter class derived from CommandOptionArg that takes
00173 // a file name parameter and detects wether the file is accessible
00174 // flagging an error if the file is inaccessible to read.
00175 //
00176 class file_option : public CommandOptionArg {
00177 public:
00178 
00179         // the constructor calls the regular CommandOptionArg constructor
00180         // and all should be well.
00181         file_option(
00182                 const char      * in_option_name,
00183                 const char      * in_option_letter,
00184                 const char      * in_description,
00185                 bool              in_required = false,
00186                 CommandOption  ** pp_next = & defaultCommandOptionList
00187         )
00188                 : CommandOptionArg(
00189                         in_option_name,
00190                         in_option_letter,
00191                         in_description,
00192                         in_required,
00193                         pp_next
00194                 )
00195         {
00196         }
00197 
00198         //
00199         // When parsing is done check if the file is accessible and register
00200         // an error with the CommandOptionParse object to let it know so.
00201         virtual void parseDone( CommandOptionParse * cop )
00202         {
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         {
00219                 // Should put in way more error handling here ...
00220                 return ::open( values[ numValue - 1 ], O_RDONLY );
00221         }
00222 
00223         //
00224         // The most elaborate way to spit the contents of a file
00225         // to standard output.
00226         pid_t   pid;
00227         virtual void performTask( CommandOptionParse * cop )
00228         {
00229                 pid = ::fork();
00230 
00231                 if ( pid ) {
00232                         return;
00233                 }
00234                 
00235                 int fd = OpenFile();
00236                 if ( fd < 0 ) {
00237                         int errno_s = errno;
00238                         cerr
00239                                 << "Error:  '"
00240                                 << values[ numValue - 1 ]
00241                                 << "' : "
00242                                 << ::strerror( errno_s )
00243                         ;
00244 
00245                         ::exit( 1 );
00246                 }
00247                 dup2(fd, 0);
00248                 ::execvp( test_restoargs.values[0], (char**) test_restoargs.values );
00249                 ::exit(1);
00250         }
00251 
00252         ~file_option()
00253         {
00254                 if ( pid <= 0 ) return;
00255                 int status;
00256 		::wait(&status);
00257         }
00258 };
00259 
00260 
00261 //
00262 // This is the linked list head for the options in the second example.
00263 // Note that the first example used the default value defined in the
00264 // method.  Here it is explicitly specified as TestList in all the following
00265 // CommandOption constructors.
00266 
00267 file_option     test_file(
00268         "test_file", "f", "Filename to read from", true, &TestList
00269 );
00270 
00271 CommandOptionNoArg      test_xnoarg(
00272         "test_xnoarg", "b", "This option does not take an argument", false, &TestList
00273 );
00274 
00275 CommandOptionNoArg      test_helparg(
00276         "help", "?", "Print help usage", false, &TestList
00277 );
00278 
00279 CommandOptionRest       test_restoargs(
00280         0, 0, "Command to be executed", true, &TestList
00281 );
00282 
00283 //
00284 // in most apps this would be the regular "main" function.
00285 int Test_main( int argc, char ** argv )
00286 {
00287         CommandOptionParse * args = makeCommandOptionParse(
00288                 argc, argv,
00289                 "Command line parser X test.\n"
00290                 "       This example is executed when the command ends in 'x'\n"
00291                 "       It shows how the -f parameter can be specialized.\n",
00292                 TestList
00293         );
00294 
00295         // If the user requested help then suppress all the usage error
00296         // messages.
00297         if ( test_helparg.numSet ) {
00298                 cerr << args->printUsage();
00299                 ::exit(0);
00300         }
00301 
00302         // Print usage your way.
00303         if ( args->argsHaveError() ) {
00304                 cerr << args->printErrors();
00305                 cerr << "Get help by --help\n";
00306                 ::exit(1);
00307         }
00308 
00309         // Go off and run any option specific task
00310         args->performTask();
00311 
00312         for ( int i = 0; i < test_file.numValue; i ++ ) {
00313                 cerr << "test_file = " << test_file.values[ i ] << endl;
00314         }
00315         
00316         for ( int i = 0; i < test_restoargs.numValue; i ++ ) {
00317                 cerr << "test_restoargs " << i << " : " << test_restoargs.values[ i ] << endl;
00318         }
00319 
00320         delete args;
00321 
00322         return 0;
00323 }
00324 
00325 
00326 //
00327 // This switches behaviour of this executable depending of wether it is
00328 // invoked with a command ending in "x".  This is mimicking for example
00329 // the behaviour of bunzip2 and bzip2.  These executables are THE SAME
00330 // file i.e.
00331 //   0 lrwxrwxrwx    1 root     root    5 Oct 11 14:04 /usr/bin/bunzip2 -> bzip2*
00332 // and the behaviour is determined by the executable name.
00333 //
00334 // This example is way more complex than the way most people will end up
00335 // using feature.
00336 
00337 int main( int argc, char ** argv )
00338 {
00339 
00340         int i = ::strlen( argv[ 0 ] );
00341 
00342         // determine which real "main" function do I call
00343         if ( argv[ 0 ][ i - 1 ] == 'x' ) {
00344                 return Test_main( argc, argv );
00345         } else {
00346                 return Example_main( argc, argv );
00347         }
00348 
00349 }

Generated on Thu Nov 24 14:09:08 2005 for GNU CommonC++ by  doxygen 1.4.5