blob: b9b10f900436ffe4ae132ad87f33edf83f8f2eea [file] [log] [blame]
Michael Walsh08a66762018-02-15 17:14:02 -06001#!/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
Michael Walsh2b55f642018-02-21 16:50:22 -060060 # 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 {
Michael Walsh08a66762018-02-15 17:14:02 -060064 # 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
Michael Walsh2b55f642018-02-21 16:50:22 -060069 set _opt_rec_ [split $_opt_arg_ =]
Michael Walsh08a66762018-02-15 17:14:02 -060070 # opt_spec will include any colons that may have been specified.
Michael Walsh2b55f642018-02-21 16:50:22 -060071 set _opt_spec_ [lindex $_opt_rec_ 0]
Michael Walsh08a66762018-02-15 17:14:02 -060072 # Add the option spec to the global longoptions list.
Michael Walsh2b55f642018-02-21 16:50:22 -060073 lappend_unique longoptions $_opt_spec_
Michael Walsh08a66762018-02-15 17:14:02 -060074 # Strip the colons to get the option name.
Michael Walsh2b55f642018-02-21 16:50:22 -060075 set _opt_name_ [string trimright $_opt_spec_ ":"]
Michael Walsh08a66762018-02-15 17:14:02 -060076 # Get the option's default value, if any.
Michael Walsh2b55f642018-02-21 16:50:22 -060077 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_ == "" } {
Michael Walsh08a66762018-02-15 17:14:02 -060080 # If this parm takes no arg and no default was specified by the user,
81 # we will set the default to 0.
Michael Walsh2b55f642018-02-21 16:50:22 -060082 set _opt_default_value_ 0
Michael Walsh08a66762018-02-15 17:14:02 -060083 }
84 # Set a global variable whose name is identical to the option name. Set
85 # the default value if there is one.
Michael Walsh2b55f642018-02-21 16:50:22 -060086 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_
Michael Walsh08a66762018-02-15 17:14:02 -060092 }
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]
Michael Walsh2b55f642018-02-21 16:50:22 -0600112 # 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_ }
Michael Walsh08a66762018-02-15 17:14:02 -0600117 # 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
Michael Walsh2b55f642018-02-21 16:50:22 -0600122 set _opt_parm_rec_ [split $_opt_arg_ =]
123 if { $_opt_debug_ } { print_list _opt_parm_rec_ }
Michael Walsh08a66762018-02-15 17:14:02 -0600124 # parm_spec will include any colons that may have been specified.
Michael Walsh2b55f642018-02-21 16:50:22 -0600125 set _opt_parm_name_ [lindex $_opt_parm_rec_ 0]
126 if { $_opt_debug_ } { print_var _opt_parm_name_ }
Michael Walsh08a66762018-02-15 17:14:02 -0600127 # Add the option spec to the global pos_parms list.
Michael Walsh2b55f642018-02-21 16:50:22 -0600128 lappend pos_parms $_opt_parm_name_
Michael Walsh08a66762018-02-15 17:14:02 -0600129 # Get the option's default value, if any.
Michael Walsh2b55f642018-02-21 16:50:22 -0600130 set _opt_parm_default_value_ [lindex $_opt_parm_rec_ 1]
131 if { $_opt_debug_ } { print_var _opt_parm_default_value_ }
Michael Walsh08a66762018-02-15 17:14:02 -0600132 # Set a global variable whose name is identical to the option name. Set
133 # the default value if there is one.
Michael Walsh2b55f642018-02-21 16:50:22 -0600134 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_
Michael Walsh08a66762018-02-15 17:14:02 -0600138 }
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
Michael Walsh2b55f642018-02-21 16:50:22 -0600169 # 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
Michael Walsh08a66762018-02-15 17:14:02 -0600172
Michael Walsh2b55f642018-02-21 16:50:22 -0600173 set _opt_len_pos_parms_ [llength $pos_parms]
Michael Walsh08a66762018-02-15 17:14:02 -0600174
Michael Walsh2b55f642018-02-21 16:50:22 -0600175 if { $_opt_debug_ } {
176 print_list longoptions
177 print_list pos_parms
178 print_var _opt_len_pos_parms_
179 }
Michael Walsh08a66762018-02-15 17:14:02 -0600180
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'.
Michael Walsh2b55f642018-02-21 16:50:22 -0600193 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 ] } {
Michael Walsh08a66762018-02-15 17:14:02 -0600200 puts stderr $result
201 exit 1
202 }
203
204 set OPT_LIST [quotes_to_curly_braces $OPT_LIST]
Michael Walsh2b55f642018-02-21 16:50:22 -0600205 set _opt_cmd_buf_ "set opt_list \[list $OPT_LIST\]"
206 if { $_opt_debug_ } { pissuing $_opt_cmd_buf_ }
207 eval $_opt_cmd_buf_
Michael Walsh08a66762018-02-15 17:14:02 -0600208
Michael Walsh2b55f642018-02-21 16:50:22 -0600209 if { $_opt_debug_ } { print_list opt_list }
Michael Walsh08a66762018-02-15 17:14:02 -0600210
Michael Walsh2b55f642018-02-21 16:50:22 -0600211 set _opt_longopt_regex_ {\-[-]?[^- ]+}
Michael Walsh08a66762018-02-15 17:14:02 -0600212 global help
213 global h
214 set help 0
215 set h 0
Michael Walsh2b55f642018-02-21 16:50:22 -0600216 if { $_opt_debug_ } { printn ; print_timen "Processing opt_list." }
217 set _opt_pos_parm_ix_ 0
218 set _opt_current_longopt_ {}
Michael Walsh08a66762018-02-15 17:14:02 -0600219 foreach opt_list_entry $opt_list {
Michael Walsh2b55f642018-02-21 16:50:22 -0600220 if { $_opt_debug_ } { print_var opt_list_entry }
Michael Walsh08a66762018-02-15 17:14:02 -0600221 if { $opt_list_entry == "--" } { break; }
Michael Walsh2b55f642018-02-21 16:50:22 -0600222 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 }
Michael Walsh08a66762018-02-15 17:14:02 -0600230 continue
231 }
Michael Walsh2b55f642018-02-21 16:50:22 -0600232 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_ } {
Michael Walsh08a66762018-02-15 17:14:02 -0600236 regsub -all {^\-[-]?} $opt_list_entry {} opt_name
Michael Walsh2b55f642018-02-21 16:50:22 -0600237 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_
Michael Walsh08a66762018-02-15 17:14:02 -0600244 } else {
Michael Walsh2b55f642018-02-21 16:50:22 -0600245 set _opt_current_longopt_ [string trimleft $opt_list_entry "-"]
Michael Walsh08a66762018-02-15 17:14:02 -0600246 }
247 } else {
248 # Must be a positional parm.
Michael Walsh2b55f642018-02-21 16:50:22 -0600249 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_
Michael Walsh08a66762018-02-15 17:14:02 -0600256 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 }
Michael Walsh2b55f642018-02-21 16:50:22 -0600265 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_
Michael Walsh08a66762018-02-15 17:14:02 -0600271 }
Michael Walsh2b55f642018-02-21 16:50:22 -0600272 if { $_opt_debug_ } { printn }
Michael Walsh08a66762018-02-15 17:14:02 -0600273 }
274
275 if { $h || $help } {
276 if { [info proc help] != "" } {
277 help
278 } else {
279 puts "No help text defined for this program."
280 }
281 exit 0
282 }
283
284}
285
286
287proc print_usage {} {
288
289 # Print usage help text line.
290
291 # Example:
292 # usage: demo.tcl [OPTIONS] [USERID] [FILE_LIST]
293
294 global program_name
295 global longoptions
296 global pos_parms
297
298 append buffer "usage: $program_name"
299
300 if { $longoptions != "" } {
301 append buffer " \[OPTIONS\]"
302 }
303
304 foreach parm $pos_parms {
305 set upper_parm [string toupper $parm]
306 append buffer " \[$upper_parm\]"
307 }
308
309 puts $buffer
310
311}
312
313
314proc print_option_help { option help_text { data_desc {} } { print_default {}}\
315 { width 30 } } {
316
317 # Print help text for the given option.
318
319 # Description of argument(s):
320 # option The option for which help text should be
321 # printed. This value should include a
322 # leading "--" to indicate that this is an
323 # optional rather than a positional parm.
324 # data_desc A description of the data (e.g. "dir
325 # path", "1,0", etc.)0
326 # print_default Indicates whether the current value of the
327 # global variable representing the option is
328 # to be printed as a default value. For
329 # example, if the option value is "--parm1",
330 # global value parm1 is "no" and
331 # print_default is set, the following phrase
332 # will be appended to the help text: The
333 # default value is "no".
334 # width The width of the arguments column.
335
336 set indent 2
337
338 # Get the actual opt_name by stripping leading dashes and trailing colons.
339 regsub -all {^\-[-]?} $option {} opt_name
340 regsub -all {:[:]?$} $opt_name {} opt_name
341
342 # Set defaults for args to this procedure.
343 set longopt_regex {\-[-]?[^- ]+}
344 set is_option [regexp -expanded $longopt_regex ${option}]
345 if { $is_option } {
346 # It is an option (vs positional parm).
347 # Does it take an argument?
348 set arg_req [get_arg_req $opt_name]
349 if { $arg_req == "not_allowed" } {
350 set data_desc_default ""
351 } else {
352 set data_desc_default "{$opt_name}"
353 }
354 } else {
355 # It's a positional parm.
356 set opt_name [string tolower $opt_name]
357 set data_desc_default ""
358 }
359
360 set_var_default data_desc $data_desc_default
361 set_var_default print_default 1
362
363 if { $print_default } {
364 # Access the global variable that represents the value of the option.
365 eval global $opt_name
366 set cmd_buf "set opt_value \${${opt_name}}"
367 eval $cmd_buf
368 set default_string " The default value is \"${opt_value}\"."
369 } else {
370 set default_string ""
371 }
372
373 if { $data_desc != "" } {
374 # Remove any curly braces and put them back on.
375 set data_desc "{[string trim $data_desc {{}}]}"
376 }
377
378 print_arg_desc "$option $data_desc" "${help_text}${default_string}" 2 $width
379
380}
381
382
383# Create help text variables for stock parms like quiet, debug and test_mode.
384set test_mode_help_text "This means that ${program_name} should go through"
385append test_mode_help_text " all the motions but not actually do anything"
386append test_mode_help_text " substantial. This is mainly to be used by the"
387append test_mode_help_text " developer of ${program_name}."
388set quiet_help_text "If this parameter is set to \"1\", ${program_name} will"
389append quiet_help_text " print only essential information, i.e. it will not"
390append quiet_help_text " echo parameters, echo commands, print the total run"
391append quiet_help_text " time, etc."
392set debug_help_text "If this parameter is set to \"1\", ${program_name} will"
393append debug_help_text " print additional debug information. This is mainly to"
394append debug_help_text " be used by the developer of ${program_name}."
395
396proc gen_print_help { { width 30 } } {
397
398 # Print general help text based on user's pos_parms and longoptions.
399
400 # Note: To use this procedure, the user must create a global help_dict
401 # containing entries for each of their options and one for the program as a
402 # whole. The keys of this dictionary are the option names and the values
403 # are lists whose values map to arguments from the print_option_help
404 # procedure:
405 # - help_text
406 # - data_desc (optional)
407 # - print_default (1 or 0 - default is 1)
408
409 # Example:
410 # set help_dict [dict create\
411 # ${program_name} [list "${program_name} will demonstrate..."]\
412 # userid [list "The userid of the caller."]\
413 # file_list [list "A list of files to be processed."]\
414 # flag [list "A flag to indicate that..."]\
415 # dir_path [list "The path to the directory containing the files."]\
416 # release [list "The code release."]\
417 # ]
418
419 global program_name
420 global longoptions
421 global pos_parms
422
423 global help_dict
424 global test_mode_help_text
425 global quiet_help_text
426 global debug_help_text
427
428 # Add help text for stock options to global help_dict.
429 dict set help_dict test_mode [list $test_mode_help_text "1,0"]
430 dict set help_dict quiet [list $quiet_help_text "1,0"]
431 dict set help_dict debug [list $debug_help_text "1,0"]
432
433 puts ""
434 print_usage
435
436 # Retrieve the general program help text from the help_dict and print it.
437 set help_entry [dict get $help_dict ${program_name}]
438 puts ""
Michael Walsh8cfe9df2018-02-27 10:46:38 -0600439
440 append cmd_buf "echo '[escape_bash_quotes [lindex $help_entry 0]]' | fold"
441 append cmd_buf " --spaces --width=80"
442 set out_buf [eval exec bash -c {$cmd_buf}]
443
444 puts "$out_buf"
Michael Walsh08a66762018-02-15 17:14:02 -0600445
446 if { $pos_parms != "" } {
447 puts ""
448 puts "positional arguments:"
449 foreach option $pos_parms {
450 # Retrieve the print_option_help parm values from the help_dict and
451 # call print_option_help.
452 set help_entry [dict get $help_dict ${option}]
453 set help_text [lindex $help_entry 0]
454 set data_desc [lindex $help_entry 1]
455 set print_default [lindex $help_entry 2]
456 print_option_help [string toupper $option] $help_text $data_desc\
457 $print_default $width
458 }
459 }
460
461 if { $longoptions != "" } {
462 puts ""
463 puts "optional arguments:"
464 foreach option $longoptions {
465 set option [string trim $option ":"]
466 # Retrieve the print_option_help parm values from the help_dict and
467 # call print_option_help.
468 set help_entry [dict get $help_dict ${option}]
469 set help_text [lindex $help_entry 0]
470 set data_desc [lindex $help_entry 1]
471 set print_default [lindex $help_entry 2]
472 print_option_help "--${option}" $help_text $data_desc $print_default\
473 $width
474 }
475 }
476 puts ""
477
478}
479
480
481proc return_program_options {} {
482
483 # Return all the names of the global program options as a composite list.
484
485 global longoptions pos_parms
486
487 regsub -all {:} $longoptions {} program_options
488 eval lappend program_options $pos_parms
489
490 return $program_options
491
492}
493
494
495proc global_program_options {} {
496
497 # Make all program option global variables available to the calling function.
498 set program_options [return_program_options]
499 uplevel eval global $program_options
500
501}
502
503
504proc gen_pre_validation {} {
505
506 # Do generic post-validation processing. By "post", we mean that this is
507 # to be called from a validation function after the caller has done any
508 # validation desired. If the calling program passes exit_function and
509 # signal_handler parms, this function will register them. In other words,
510 # it will make the signal_handler functions get called for SIGINT and
511 # SIGTERM and will make the exit_function function run prior to the
512 # termination of the program.
513
514 # Make all program option global variables available to the calling function.
515 uplevel global_program_options
516
517}
518
519
520proc gen_post_validation {} {
521
522 # Do generic post-validation processing. By "post", we mean that this is
523 # to be called from a validation function after the caller has done any
524 # validation desired. If the calling program passes exit_function and
525 # signal_handler parms, this function will register them. In other words,
526 # it will make the signal_handler functions get called for SIGINT and
527 # SIGTERM and will make the exit_function function run prior to the
528 # termination of the program.
529
530 trap { exit_proc } [list SIGTERM SIGINT]
531
532}