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