1#!/usr/bin/wish 2 3# This file provides many valuable parm and argument processing procedures 4# such as longoptions, pos_parms, gen_get_options, etc. 5 6my_source [list escape.tcl data_proc.tcl print.tcl] 7 8 9proc get_arg_req { opt_name } { 10 11 # Determine whether the given opt_name is "optional", "required" or 12 # "not_allowed" and return that result. 13 14 # Note: This procedure assumes that global list longoptions has been 15 # initialized via a call to the longoptions procedure. 16 17 # Description of argument(s): 18 # opt_name The name of the option including its 19 # requirement indicator as accepted by the 20 # bash getopt longoptions parameter: No 21 # colon means the option takes no argument, 22 # one colon means the option requires an 23 # argument and two colons indicate that an 24 # argument is optional (the value of the 25 # option will be 1 if no argument is 26 # specified. 27 28 global longoptions 29 30 if { [lsearch -exact $longoptions "${opt_name}::"] != -1 } { 31 return optional 32 } 33 if { [lsearch -exact $longoptions "${opt_name}:"] != -1 } { 34 return required 35 } 36 return not_allowed 37 38} 39 40 41proc longoptions { args } { 42 43 # Populate the global longoptions list and set global option variable 44 # defaults. 45 46 # Description of argument(s): 47 # args Each arg is comprised of 1) the name of 48 # the option 2) zero, one or 2 colons to 49 # indicate whether the corresponding 50 # argument value is a) not required, b) 51 # required or c) optional 3) Optionally, an 52 # equal sign followed by a default value for 53 # the parameter. 54 55 # Example usage: 56 # longoptions parm1 parm2: parm3:: test_mode:=0 quiet:=0 57 58 global longoptions 59 60 # Note: Because this procedure manipulates global variables, we use the 61 # "_opt_<varname>_" format to minimize the possibility of naming collisions. 62 set _opt_debug_ 0 63 foreach _opt_arg_ $args { 64 # Create an option record which is a 2-element list consisting of the 65 # option specification and a possible default value. Example:; 66 # opt_rec: 67 # opt_rec[0]: test_mode: 68 # opt_rec[1]: 0 69 set _opt_rec_ [split $_opt_arg_ =] 70 # opt_spec will include any colons that may have been specified. 71 set _opt_spec_ [lindex $_opt_rec_ 0] 72 # Add the option spec to the global longoptions list. 73 lappend_unique longoptions $_opt_spec_ 74 # Strip the colons to get the option name. 75 set _opt_name_ [string trimright $_opt_spec_ ":"] 76 # Get the option's default value, if any. 77 set _opt_default_value_ [lindex $_opt_rec_ 1] 78 set _opt_arg_req_ [get_arg_req $_opt_name_] 79 if { $_opt_arg_req_ == "not_allowed" && $_opt_default_value_ == "" } { 80 # If this parm takes no arg and no default was specified by the user, 81 # we will set the default to 0. 82 set _opt_default_value_ 0 83 } 84 # Set a global variable whose name is identical to the option name. Set 85 # the default value if there is one. 86 set _opt_cmd_buf_ "global ${_opt_name_}" 87 if { $_opt_debug_ } { print_issuing $_opt_cmd_buf_ } 88 eval $_opt_cmd_buf_ 89 set _opt_cmd_buf_ "set ${_opt_name_} {${_opt_default_value_}}" 90 if { $_opt_debug_ } { print_issuing $_opt_cmd_buf_ } 91 eval $_opt_cmd_buf_ 92 } 93 94} 95 96 97proc pos_parms { args } { 98 99 # Populate the global pos_parms list and set global option variable defaults. 100 101 # Description of argument(s): 102 # args Each arg is comprised of the name of a 103 # positional parm and a possible initial 104 # value. 105 106 # Example usage: 107 # pos_parms user_name=mike 108 109 global pos_parms 110 111 set pos_parms [list] 112 # Note: Because this procedure manipulates global variables, we use the 113 # "_opt_<varname>_" format to minimize the possibility of naming collisions. 114 set _opt_debug_ 0 115 foreach _opt_arg_ $args { 116 if { $_opt_debug_ } { print_var _opt_arg_ } 117 # Create an option record which is a 2-element list consisting of the 118 # option specification and a possible default value. Example:; 119 # opt_rec: 120 # opt_rec[0]: test_mode: 121 # opt_rec[1]: 0 122 set _opt_parm_rec_ [split $_opt_arg_ =] 123 if { $_opt_debug_ } { print_list _opt_parm_rec_ } 124 # parm_spec will include any colons that may have been specified. 125 set _opt_parm_name_ [lindex $_opt_parm_rec_ 0] 126 if { $_opt_debug_ } { print_var _opt_parm_name_ } 127 # Add the option spec to the global pos_parms list. 128 lappend pos_parms $_opt_parm_name_ 129 # Get the option's default value, if any. 130 set _opt_parm_default_value_ [lindex $_opt_parm_rec_ 1] 131 if { $_opt_debug_ } { print_var _opt_parm_default_value_ } 132 # Set a global variable whose name is identical to the option name. Set 133 # the default value if there is one. 134 set _opt_cmd_buf_ "global ${_opt_parm_name_} ; set ${_opt_parm_name_}" 135 append _opt_cmd_buf_ " {${_opt_parm_default_value_}}" 136 if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ } 137 eval $_opt_cmd_buf_ 138 } 139 140} 141 142 143proc gen_get_options { argv } { 144 145 # Get the command line options/arguments and use them to set the 146 # corresponding global option variable names. 147 148 # Note: This procedure assumes that global list longoptions has been 149 # initialized via a call to the longoptions procedure and that global 150 # pos_parms has been initialized via a call to the pos_parms procdure. 151 # These data structures indicates what options and arguments are supported 152 # by the calling program. 153 154 # Note: If the last var_name in pos_parms ends in "_list", then the caller 155 # can specify as many parms as they desire and they will all be appended to 156 # the variable in question. 157 158 # Description of argument(s): 159 # argv The argv array that is set for this 160 # program. 161 162 # Example call: 163 # gen_get_options $argv 164 165 global longoptions 166 global pos_parms 167 global program_name 168 169 # Note: Because this procedure manipulates global variables, we use the 170 # "_opt_<varname>_" format to minimize the possibility of naming collisions. 171 set _opt_debug_ 0 172 173 set _opt_len_pos_parms_ [llength $pos_parms] 174 175 if { $_opt_debug_ } { 176 print_list longoptions 177 print_list pos_parms 178 print_var _opt_len_pos_parms_ 179 } 180 181 # Rather than write the algorithm from scratch, we will call upon the bash 182 # getopt program to help us. This program has several advantages: 183 # - It will reject illegal options 184 # - It supports different posix input styles (e.g. -option <arg> vs 185 # --option=<arg>). 186 # - It allows the program's caller to abbreviate option names provided that 187 # there is no ambiguity. 188 189 # Convert curly braces to single quotes. This includes escaping existing 190 # quotes in the argv string. This will allow us to use the result in a bash 191 # command string. Example: {--parm3=Kathy's cat} will become 192 # '--parm3=Kathy'\''s cat'. 193 if { $_opt_debug_ } { print_var argv } 194 set _opt_bash_args_ [curly_braces_to_quotes $argv] 195 set _opt_cmd_buf_ "getopt --name=${program_name} -a --longoptions=\"help" 196 append _opt_cmd_buf_ " ${longoptions}\" --options=\"-h\" --" 197 append _opt_cmd_buf_ " ${_opt_bash_args_}" 198 if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ } 199 if { [ catch {set OPT_LIST [eval exec bash -c {$_opt_cmd_buf_}]} result ] } { 200 puts stderr $result 201 exit 1 202 } 203 204 set OPT_LIST [quotes_to_curly_braces $OPT_LIST] 205 set _opt_cmd_buf_ "set opt_list \[list $OPT_LIST\]" 206 if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ } 207 eval $_opt_cmd_buf_ 208 209 if { $_opt_debug_ } { print_list opt_list } 210 211 set _opt_longopt_regex_ {\-[-]?[^- ]+} 212 global help 213 global h 214 set help 0 215 set h 0 216 if { $_opt_debug_ } { printn ; print_timen "Processing opt_list." } 217 set _opt_pos_parm_ix_ 0 218 set _opt_current_longopt_ {} 219 foreach opt_list_entry $opt_list { 220 if { $_opt_debug_ } { print_var opt_list_entry } 221 if { $opt_list_entry == "--" } { break; } 222 if { $_opt_current_longopt_ != "" } { 223 if { $_opt_debug_ } { print_var _opt_current_longopt_ } 224 set _opt_cmd_buf_ "global ${_opt_current_longopt_} ; set" 225 append _opt_cmd_buf_ " ${_opt_current_longopt_} {${opt_list_entry}}" 226 if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ } 227 eval $_opt_cmd_buf_ 228 set _opt_current_longopt_ {} 229 if { $_opt_debug_ } { printn } 230 continue 231 } 232 set _opt_is_option_ [regexp -expanded $_opt_longopt_regex_\ 233 ${opt_list_entry}] 234 if { $_opt_debug_ } { print_var _opt_is_option_ } 235 if { $_opt_is_option_ } { 236 regsub -all {^\-[-]?} $opt_list_entry {} opt_name 237 if { $_opt_debug_ } { print_var opt_name } 238 set _opt_arg_req_ [get_arg_req $opt_name] 239 if { $_opt_debug_ } { print_var _opt_arg_req_ } 240 if { $_opt_arg_req_ == "not_allowed" } { 241 set _opt_cmd_buf_ "global ${opt_name} ; set ${opt_name} 1" 242 if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ } 243 eval $_opt_cmd_buf_ 244 } else { 245 set _opt_current_longopt_ [string trimleft $opt_list_entry "-"] 246 } 247 } else { 248 # Must be a positional parm. 249 if { $_opt_pos_parm_ix_ >= $_opt_len_pos_parms_ } { 250 set _opt_is_list_ [regexp -expanded "_list$" ${pos_parm_name}] 251 if { $_opt_debug_ } { print_var _opt_is_list_ } 252 if { $_opt_is_list_ } { 253 set _opt_cmd_buf_ "lappend ${pos_parm_name} {${opt_list_entry}}" 254 if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ } 255 eval $_opt_cmd_buf_ 256 continue 257 } 258 append message "The caller has specified more positional parms than" 259 append message " are allowed by the program.\n" 260 append message [sprint_varx parm_value ${opt_list_entry} 2] 261 append message [sprint_list pos_parms 2] 262 print_error_report $message 263 exit 1 264 } 265 set _opt_pos_parm_name_ [lindex $pos_parms $_opt_pos_parm_ix_] 266 set _opt_cmd_buf_ "global ${_opt_pos_parm_name_} ; set" 267 append _opt_cmd_buf_ " ${_opt_pos_parm_name_} {${opt_list_entry}}" 268 if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ } 269 eval $_opt_cmd_buf_ 270 incr _opt_pos_parm_ix_ 271 } 272 if { $_opt_debug_ } { printn } 273 } 274 275 # Automatically register any parameter whose name ends in "_password" to 276 # prevent printing of password. 277 regsub -all ":" "${longoptions} ${pos_parms}" {} parm_names 278 foreach parm_name $parm_names { 279 if { [string match *password $parm_name] } { 280 global $parm_name 281 register_passwords [set $parm_name] 282 } 283 } 284 285 if { $h || $help } { 286 if { [info proc help] != "" } { 287 help 288 } else { 289 puts "No help text defined for this program." 290 } 291 exit 0 292 } 293 294} 295 296 297proc print_usage {} { 298 299 # Print usage help text line. 300 301 # Example: 302 # usage: demo.tcl [OPTIONS] [USERID] [FILE_LIST] 303 304 global program_name 305 global longoptions 306 global pos_parms 307 308 append buffer "usage: $program_name" 309 310 if { $longoptions != "" } { 311 append buffer " \[OPTIONS\]" 312 } 313 314 foreach parm $pos_parms { 315 set upper_parm [string toupper $parm] 316 append buffer " \[$upper_parm\]" 317 } 318 319 puts $buffer 320 321} 322 323 324proc print_option_help { option help_text { data_desc {} } { print_default {}}\ 325 { width 30 } } { 326 327 # Print help text for the given option. 328 329 # Description of argument(s): 330 # option The option for which help text should be 331 # printed. This value should include a 332 # leading "--" to indicate that this is an 333 # optional rather than a positional parm. 334 # data_desc A description of the data (e.g. "dir 335 # path", "1,0", etc.)0 336 # print_default Indicates whether the current value of the 337 # global variable representing the option is 338 # to be printed as a default value. For 339 # example, if the option value is "--parm1", 340 # global value parm1 is "no" and 341 # print_default is set, the following phrase 342 # will be appended to the help text: The 343 # default value is "no". 344 # width The width of the arguments column. 345 346 set indent 2 347 348 # Get the actual opt_name by stripping leading dashes and trailing colons. 349 regsub -all {^\-[-]?} $option {} opt_name 350 regsub -all {:[:]?$} $opt_name {} opt_name 351 352 # Set defaults for args to this procedure. 353 set longopt_regex {\-[-]?[^- ]+} 354 set is_option [regexp -expanded $longopt_regex ${option}] 355 if { $is_option } { 356 # It is an option (vs positional parm). 357 # Does it take an argument? 358 set arg_req [get_arg_req $opt_name] 359 if { $arg_req == "not_allowed" } { 360 set data_desc_default "" 361 } else { 362 set data_desc_default "{$opt_name}" 363 } 364 } else { 365 # It's a positional parm. 366 set opt_name [string tolower $opt_name] 367 set data_desc_default "" 368 } 369 370 set_var_default data_desc $data_desc_default 371 set_var_default print_default 1 372 373 if { $print_default } { 374 # Access the global variable that represents the value of the option. 375 eval global $opt_name 376 set cmd_buf "set opt_value \${${opt_name}}" 377 eval $cmd_buf 378 set default_string " The default value is \"${opt_value}\"." 379 } else { 380 set default_string "" 381 } 382 383 if { $data_desc != "" } { 384 # Remove any curly braces and put them back on. 385 set data_desc "{[string trim $data_desc {{}}]}" 386 } 387 388 print_arg_desc "$option $data_desc" "${help_text}${default_string}" 2 $width 389 390} 391 392 393# Create help text variables for stock parms like quiet, debug and test_mode. 394set test_mode_help_text "This means that ${program_name} should go through" 395append test_mode_help_text " all the motions but not actually do anything" 396append test_mode_help_text " substantial. This is mainly to be used by the" 397append test_mode_help_text " developer of ${program_name}." 398set quiet_help_text "If this parameter is set to \"1\", ${program_name} will" 399append quiet_help_text " print only essential information, i.e. it will not" 400append quiet_help_text " echo parameters, echo commands, print the total run" 401append quiet_help_text " time, etc." 402set debug_help_text "If this parameter is set to \"1\", ${program_name} will" 403append debug_help_text " print additional debug information. This is mainly to" 404append debug_help_text " be used by the developer of ${program_name}." 405 406proc gen_print_help { { width 30 } } { 407 408 # Print general help text based on user's pos_parms and longoptions. 409 410 # Note: To use this procedure, the user must create a global help_dict 411 # containing entries for each of their options and one for the program as a 412 # whole. The keys of this dictionary are the option names and the values 413 # are lists whose values map to arguments from the print_option_help 414 # procedure: 415 # - help_text 416 # - data_desc (optional) 417 # - print_default (1 or 0 - default is 1) 418 419 # Example: 420 # set help_dict [dict create\ 421 # ${program_name} [list "${program_name} will demonstrate..."]\ 422 # userid [list "The userid of the caller."]\ 423 # file_list [list "A list of files to be processed."]\ 424 # flag [list "A flag to indicate that..."]\ 425 # dir_path [list "The path to the directory containing the files."]\ 426 # release [list "The code release."]\ 427 # ] 428 429 global program_name 430 global longoptions 431 global pos_parms 432 433 global help_dict 434 global test_mode_help_text 435 global quiet_help_text 436 global debug_help_text 437 438 # Add help text for stock options to global help_dict. 439 dict set help_dict test_mode [list $test_mode_help_text "1,0"] 440 dict set help_dict quiet [list $quiet_help_text "1,0"] 441 dict set help_dict debug [list $debug_help_text "1,0"] 442 443 puts "" 444 print_usage 445 446 # Retrieve the general program help text from the help_dict and print it. 447 set help_entry [dict get $help_dict ${program_name}] 448 puts "" 449 450 append cmd_buf "echo '[escape_bash_quotes [lindex $help_entry 0]]' | fold" 451 append cmd_buf " --spaces --width=80" 452 set out_buf [eval exec bash -c {$cmd_buf}] 453 454 puts "$out_buf" 455 456 if { $pos_parms != "" } { 457 puts "" 458 puts "positional arguments:" 459 foreach option $pos_parms { 460 # Retrieve the print_option_help parm values from the help_dict and 461 # call print_option_help. 462 set help_entry [dict get $help_dict ${option}] 463 set help_text [lindex $help_entry 0] 464 set data_desc [lindex $help_entry 1] 465 set print_default [lindex $help_entry 2] 466 print_option_help [string toupper $option] $help_text $data_desc\ 467 $print_default $width 468 } 469 } 470 471 if { $longoptions != "" } { 472 puts "" 473 puts "optional arguments:" 474 foreach option $longoptions { 475 set option [string trim $option ":"] 476 # Retrieve the print_option_help parm values from the help_dict and 477 # call print_option_help. 478 set help_entry [dict get $help_dict ${option}] 479 set help_text [lindex $help_entry 0] 480 set data_desc [lindex $help_entry 1] 481 set print_default [lindex $help_entry 2] 482 print_option_help "--${option}" $help_text $data_desc $print_default\ 483 $width 484 } 485 } 486 puts "" 487 488} 489 490 491proc return_program_options {} { 492 493 # Return all the names of the global program options as a composite list. 494 495 global longoptions pos_parms 496 497 regsub -all {:} $longoptions {} program_options 498 eval lappend program_options $pos_parms 499 500 return $program_options 501 502} 503 504 505proc global_program_options {} { 506 507 # Make all program option global variables available to the calling function. 508 set program_options [return_program_options] 509 uplevel eval global $program_options 510 511} 512 513 514proc gen_pre_validation {} { 515 516 # Do generic post-validation processing. By "post", we mean that this is 517 # to be called from a validation function after the caller has done any 518 # validation desired. If the calling program passes exit_function and 519 # signal_handler parms, this function will register them. In other words, 520 # it will make the signal_handler functions get called for SIGINT and 521 # SIGTERM and will make the exit_function function run prior to the 522 # termination of the program. 523 524 # Make all program option global variables available to the calling function. 525 uplevel global_program_options 526 527} 528 529 530proc gen_post_validation {} { 531 532 # Do generic post-validation processing. By "post", we mean that this is 533 # to be called from a validation function after the caller has done any 534 # validation desired. If the calling program passes exit_function and 535 # signal_handler parms, this function will register them. In other words, 536 # it will make the signal_handler functions get called for SIGINT and 537 # SIGTERM and will make the exit_function function run prior to the 538 # termination of the program. 539 540 trap { exit_proc } [list SIGTERM SIGINT] 541 542} 543 544 545proc gen_exit_proc { {ret_code 0} } { 546 547 # Call exit_proc if it is defined. Otherwise, just call exit. 548 549 if { [info procs "exit_proc"] != "" } { 550 exit_proc $ret_code 551 } else { 552 exit $ret_code 553 } 554 555} 556