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                 if ( numValue ) {
00203                         if ( ::access( values[ numValue - 1 ], R_OK ) ) {
00204                                 int     errno_s = errno;
00205                                 strstream msg;
00206                                 msg << "Error: " << optionName << " '" << values[ numValue - 1 ];
00207                                 msg << "' : " << ::strerror( errno_s );
00208 
00209                                 cop->registerError( msg.str() );
00210                         }
00211                 }
00212         }
00213 
00214         //
00215         // Open said file.  Do some operations on things - like open the file.
00216         int OpenFile() {
00217                 // Should put in way more error handling here ...
00218                 return ::open( values[ numValue - 1 ], O_RDONLY );
00219         }
00220 
00221         //
00222         // The most elaborate way to spit the contents of a file
00223         // to standard output.
00224         pid_t   pid;
00225         virtual void performTask( CommandOptionParse * cop ) {
00226                 pid = ::fork();
00227 
00228                 if ( pid ) {
00229                         return;
00230                 }
00231 
00232                 int fd = OpenFile();
00233                 if ( fd < 0 ) {
00234                         int errno_s = errno;
00235                         cerr
00236                                 << "Error:  '"
00237                                 << values[ numValue - 1 ]
00238                                 << "' : "
00239                                 << ::strerror( errno_s )
00240                         ;
00241 
00242                         ::exit( 1 );
00243                 }
00244                 dup2(fd, 0);
00245                 ::execvp( test_restoargs.values[0], (char**) test_restoargs.values );
00246                 ::exit(1);
00247         }
00248 
00249         ~file_option() {
00250                 if ( pid <= 0 ) return;
00251                 int status;
00252 		::wait(&status);
00253         }
00254 };
00255 
00256 
00257 //
00258 // This is the linked list head for the options in the second example.
00259 // Note that the first example used the default value defined in the
00260 // method.  Here it is explicitly specified as TestList in all the following
00261 // CommandOption constructors.
00262 
00263 file_option     test_file(
00264         "test_file", "f", "Filename to read from", true, &TestList
00265 );
00266 
00267 CommandOptionNoArg      test_xnoarg(
00268         "test_xnoarg", "b", "This option does not take an argument", false, &TestList
00269 );
00270 
00271 CommandOptionNoArg      test_helparg(
00272         "help", "?", "Print help usage", false, &TestList
00273 );
00274 
00275 CommandOptionRest       test_restoargs(
00276         0, 0, "Command to be executed", true, &TestList
00277 );
00278 
00279 //
00280 // in most apps this would be the regular "main" function.
00281 int Test_main( int argc, char ** argv )
00282 {
00283         CommandOptionParse * args = makeCommandOptionParse(
00284                 argc, argv,
00285                 "Command line parser X test.\n"
00286                 "       This example is executed when the command ends in 'x'\n"
00287                 "       It shows how the -f parameter can be specialized.\n",
00288                 TestList
00289         );
00290 
00291         // If the user requested help then suppress all the usage error
00292         // messages.
00293         if ( test_helparg.numSet ) {
00294                 cerr << args->printUsage();
00295                 ::exit(0);
00296         }
00297 
00298         // Print usage your way.
00299         if ( args->argsHaveError() ) {
00300                 cerr << args->printErrors();
00301                 cerr << "Get help by --help\n";
00302                 ::exit(1);
00303         }
00304 
00305         // Go off and run any option specific task
00306         args->performTask();
00307 
00308         for ( int i = 0; i < test_file.numValue; i ++ ) {
00309                 cerr << "test_file = " << test_file.values[ i ] << endl;
00310         }
00311 
00312         for ( int i = 0; i < test_restoargs.numValue; i ++ ) {
00313                 cerr << "test_restoargs " << i << " : " << test_restoargs.values[ i ] << endl;
00314         }
00315 
00316         delete args;
00317 
00318         return 0;
00319 }
00320 
00321 
00322 //
00323 // This switches behaviour of this executable depending of wether it is
00324 // invoked with a command ending in "x".  This is mimicking for example
00325 // the behaviour of bunzip2 and bzip2.  These executables are THE SAME
00326 // file i.e.
00327 //   0 lrwxrwxrwx    1 root     root    5 Oct 11 14:04 /usr/bin/bunzip2 -> bzip2*
00328 // and the behaviour is determined by the executable name.
00329 //
00330 // This example is way more complex than the way most people will end up
00331 // using feature.
00332 
00333 int main( int argc, char ** argv )
00334 {
00335 
00336         int i = ::strlen( argv[ 0 ] );
00337 
00338         // determine which real "main" function do I call
00339         if ( argv[ 0 ][ i - 1 ] == 'x' ) {
00340                 return Test_main( argc, argv );
00341         } else {
00342                 return Example_main( argc, argv );
00343         }
00344 
00345 }

Generated on Fri Apr 27 09:44:59 2007 for GNU CommonC++ by  doxygen 1.4.7