home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / iu < prev    next >
Encoding:
AWK Script  |  1997-08-26  |  29.0 KB  |  771 lines

  1. #!/usr/local/bin/gawk -f
  2. # @(#) iu.gawk 1.1 96/05/30
  3. # 95/08/10 john h. dubois iii
  4. # 96/05/30 Converted to gawk script.  Added h option.
  5.  
  6. # This misses empty directories, because a directory is recognized as such
  7. # by having find list files within it.
  8.  
  9. BEGIN {
  10.     Name = "iu"
  11.     Usage = "Usage: " Name " [-hs] [directory ...]"
  12.     ARGC = Opts(Name,Usage,"hs",0)
  13.     if ("h" in Options) {
  14.     printf \
  15. "%s: Report the number of files that exist in and below directories.\n"\
  16. "%s\n"\
  17. "%s scans each directory named and all of the directories under them,\n"\
  18. "or if no directories are named, the current directory and the directories\n"\
  19. "under it.  For each directory and subdirectory, the number of files found\n"\
  20. "in and below that directory (but not including the directory itself) are\n"\
  21. "listed.  Empty directories are not separately listed; they (and other\n"\
  22. "directories) are counted as a file in the parent directory.  Files and"\
  23. "empty directories given on the command line are given a count of 0 in the\n"\
  24. "output.\n"\
  25. "Options:\n"\
  26. "-h: Print this help.\n"\
  27. "-s: Print a summary for each directory named.  Subdirectories are not\n"\
  28. "    listed.\n",Name,Usage,Name
  29.     exit 0
  30.     }
  31.     if (ARGC == 1) {
  32.     ARGV[1] = "."
  33.     ARGC = 2
  34.     }
  35.     else if (ARGV[1] ~ /^-/)
  36.     ARGV[1] = "./" ARGV[1]    # so find won't take it to be an option
  37.     Summary = "s" in Options
  38.     # For -s option, and to ensure that all named files/dirs are reported on
  39.     # even if a file or empty dir
  40.     for (i = 1; i < ARGC; i++)
  41.     ReptDirs[ARGV[i]]
  42.     LastDepth = 0
  43.     Cmd = "find " QuoteArgs(ARGV,1,ARGC-1) " -depth -print"
  44.     FS = "/"
  45.     while ((Cmd | getline) == 1)
  46.     ProcFile()
  47. }
  48.  
  49. function ProcFile (  File,Depth,NumFiles) {
  50.     File = $0
  51.     Depth = NF        # number of path components
  52.     Count[Depth]++
  53.     # If we went up one level, this must be a dir
  54.     if (Depth < LastDepth) {
  55.     # Accumulate the counts for all dirs below this one into it
  56.     NumFiles = 0
  57.     for (i = LastDepth; i > Depth; i--) {
  58.         NumFiles += Count[i]
  59.         Count[i] = 0
  60.     }
  61.     Count[Depth] += NumFiles
  62.     if (!Summary || File in ReptDirs)
  63.         printf "%-3d %s\n",NumFiles,File
  64.     }
  65.     else if (File in ReptDirs)    # File or empty directory named on cmd line
  66.     printf "%-3d %s\n",0,File
  67.     LastDepth = Depth
  68. }
  69.  
  70. ### Start of ProcArgs library
  71. # @(#) ProcArgs 1.11 96/12/08
  72. # 92/02/29 john h. dubois iii (john@armory.com)
  73. # 93/07/18 Added "#" arg type
  74. # 93/09/26 Do not count -h against MinArgs
  75. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  76. #          Removed meaning of "+" or "-" by itself.
  77. # 94/03/08 Added & option and *()< option types.
  78. # 94/04/02 Added NoRCopt to Opts()
  79. # 94/06/11 Mark numeric variables as such.
  80. # 94/07/08 Opts(): Do not require any args if h option is given.
  81. # 95/01/22 Record options given more than once.  Record option num in argv.
  82. # 95/06/08 Added ExclusiveOptions().
  83. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  84. #          Expand $VARNAME at the start of its filenames.
  85. #          Let varname=0 and -option- turn off an option.
  86. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  87. #          of the vars should be searched for in the environment.
  88. #          Check for duplicate rcfiles.
  89. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  90. #          now return various negatives values on error, not just -1, and
  91. #          Opts() may set Err to various positive values, not just 1.
  92. #          Added AllowUnrecOpt.
  93. # 96/05/23 Check type given for & option
  94. # 96/06/15 Re-port to awk
  95. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  96. #          used by other functions.
  97. # 96/10/15 Added OptChars
  98. # 96/11/01 Added exOpts arg to Opts()
  99. # 96/11/16 Added ; type
  100. # 96/12/08 Added Opt2Set() & Opt2Sets()
  101. # 96/12/27 Added CmdLineOpt()
  102.  
  103. # optlist is a string which contains all of the possible command line options.
  104. # A character followed by certain characters indicates that the option takes
  105. # an argument, with type as follows:
  106. # :    String argument
  107. # ;    Non-empty string argument
  108. # *    Floating point argument
  109. # (    Non-negative floating point argument
  110. # )    Positive floating point argument
  111. # #    Integer argument
  112. # <    Non-negative integer argument
  113. # >    Positive integer argument
  114. # The only difference the type of argument makes is in the runtime argument
  115. # error checking that is done.
  116.  
  117. # The & option is a special case used to get numeric options without the
  118. # user having to give an option character.  It is shorthand for [-+.0-9].
  119. # If & is included in optlist and an option string that begins with one of
  120. # these characters is seen, the value given to "&" will include the first
  121. # char of the option.  & must be followed by a type character other than ":"
  122. # or ";".
  123. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  124.  
  125. # Strings in argv[] which begin with "-" or "+" are taken to be
  126. # strings of options, except that a string which consists solely of "-"
  127. # or "+" is taken to be a non-option string; like other non-option strings,
  128. # it stops the scanning of argv and is left in argv[].
  129. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  130. # If an option takes an argument, the argument may either immediately
  131. # follow it or be given separately.
  132. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  133. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  134. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  135. # this feature had a flaw that caused problems in some cases.  See the OptChars
  136. # parameter to explicitly set the option-specifier characters.
  137.  
  138. # If an option that does not take an argument is given,
  139. # an index with its name is created in Options and its value is set to the
  140. # number of times it occurs in argv[].
  141.  
  142. # If an option that does take an argument is given, an index with its name is
  143. # created in Options and its value is set to the value of the argument given
  144. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  145. # If an option that takes an argument is given more than once,
  146. # Options[option-name,"count"] is incremented, and the value is assigned to
  147. # the index (option-name,instance) where instance is 2 for the second occurance
  148. # of the option, etc.
  149. # In other words, the first time an option with a value is encountered, the
  150. # value is assigned to an index consisting only of its name; for any further
  151. # occurances of the option, the value index has an extra (count) dimension.
  152.  
  153. # The sequence number for each option found in argv[] is stored in
  154. # Options[option-name,"num",instance], where instance is 1 for the first
  155. # occurance of the option, etc.  The sequence number starts at 1 and is
  156. # incremented for each option, both those that have a value and those that
  157. # do not.  Options set from a config file have a value of 0 assigned to this.
  158.  
  159. # Options and their arguments are deleted from argv.
  160. # Note that this means that there may be gaps left in the indices of argv[].
  161. # If compress is nonzero, argv[] is packed by moving its elements so that
  162. # they have contiguous integer indices starting with 0.
  163. # Option processing will stop with the first unrecognized option, just as
  164. # though -- was given except that unlike -- the unrecognized option will not be
  165. # removed from ARGV[].  Normally, an error value is returned in this case.
  166. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  167. # be found, so the number of remaining arguments is returned instead.
  168. # If OptChars is not a null string, it is the set of characters that indicate
  169. # that an argument is an option string if the string begins with one of the
  170. # characters.  A string consisting solely of two of the same option-indicator
  171. # characters stops the scanning of argv[].  The default is "-+".
  172. # argv[0] is not examined.
  173. # The number of arguments left in argc is returned.
  174. # If an error occurs, the global string OptErr is set to an error message
  175. # and a negative value is returned.
  176. # Current error values:
  177. # -1: option that required an argument did not get it.
  178. # -2: argument of incorrect type supplied for an option.
  179. # -3: unrecognized (invalid) option.
  180. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  181. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  182. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  183. {
  184. # ArgNum is the index of the argument being processed.
  185. # ArgsLeft is the number of arguments left in argv.
  186. # Arg is the argument being processed.
  187. # ArgLen is the length of the argument being processed.
  188. # ArgInd is the position of the character in Arg being processed.
  189. # Option is the character in Arg being processed.
  190. # Pos is the position in OptList of the option being processed.
  191. # NumOpt is true if a numeric option may be given.
  192.     ArgsLeft = argc
  193.     NumOpt = index(OptList,"&")
  194.     OptionNum = 0
  195.     if (OptChars == "")
  196.     OptChars = "-+"
  197.     while (OptChars != "") {
  198.     c = substr(OptChars,1,1)
  199.     OptChars = substr(OptChars,2)
  200.     OptCharSet[c]
  201.     OptTerm[c c]
  202.     }
  203.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  204.     Arg = argv[ArgNum]
  205.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  206.         break    # Not an option; quit
  207.     if (Arg in OptTerm) {
  208.         delete argv[ArgNum]
  209.         ArgsLeft--
  210.         break
  211.     }
  212.     ArgLen = length(Arg)
  213.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  214.         Option = substr(Arg,ArgInd,1)
  215.         if (NumOpt && Option ~ /[-+.0-9]/) {
  216.         # If this option is a numeric option, make its flag be & and
  217.         # its option string flag position be the position of & in
  218.         # the option string.
  219.         Option = "&"
  220.         Pos = NumOpt
  221.         # Prefix Arg with a char so that ArgInd will point to the
  222.         # first char of the numeric option.
  223.         Arg = "&" Arg
  224.         ArgLen++
  225.         }
  226.         # Find position of flag in option string, to get its type (if any).
  227.         # Disallow & as literal flag.
  228.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  229.         if (AllowUnrecOpt) {
  230.             Escape = 1
  231.             break
  232.         }
  233.         else {
  234.             OptErr = "Invalid option: " specGiven Option
  235.             return -3
  236.         }
  237.         }
  238.  
  239.         # Find what the value of the option will be if it takes one.
  240.         # NeedNextOpt is true if the option specifier is the last char of
  241.         # this arg, which means that if the option requires a value it is
  242.         # the next arg.
  243.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  244.         if (GotValue = ArgNum + 1 < argc)
  245.             Value = argv[ArgNum+1]
  246.         }
  247.         else {    # Value is included with option
  248.         Value = substr(Arg,ArgInd + 1)
  249.         GotValue = 1
  250.         }
  251.  
  252.         if (HadValue = AssignVal(Option,Value,Options,
  253.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  254.         specGiven)) {
  255.         if (HadValue < 0)    # error occured
  256.             return HadValue
  257.         if (HadValue == 2)
  258.             ArgInd++    # Account for the single-char value we used.
  259.         else {
  260.             if (NeedNextOpt) {    # option took next arg as value
  261.             delete argv[++ArgNum]
  262.             ArgsLeft--
  263.             }
  264.             break    # This option has been used up
  265.         }
  266.         }
  267.     }
  268.     if (Escape)
  269.         break
  270.     # Do not delete arg until after processing of it, so that if it is not
  271.     # recognized it can be left in ARGV[].
  272.     delete argv[ArgNum]
  273.     ArgsLeft--
  274.     }
  275.     if (compress != 0) {
  276.     dest = 1
  277.     src = argc - ArgsLeft + 1
  278.     for (count = ArgsLeft - 1; count; count--) {
  279.         ARGV[dest] = ARGV[src]
  280.         dest++
  281.         src++
  282.     }
  283.     }
  284.     return ArgsLeft
  285. }
  286.  
  287. # Assignment to values in Options[] occurs only in this function.
  288. # Option: Option specifier character.
  289. # Value: Value to be assigned to option, if it takes a value.
  290. # Options[]: Options array to return values in.
  291. # ArgType: Argument type specifier character.
  292. # GotValue: Whether any value is available to be assigned to this option.
  293. # Name: Name of option being processed.
  294. # OptionNum: Number of this option (starting with 1) if set in argv[],
  295. #     or 0 if it was given in a config file or in the environment.
  296. # SingleOpt: true if the value (if any) that is available for this option was
  297. #     given as part of the same command line arg as the option.  Used only for
  298. #     options from the command line.
  299. # specGiven is the option specifier character use, if any (e.g. - or +),
  300. # for use in error messages.
  301. # Global variables: OptErr
  302. # Return value: negative value on error, 0 if option did not require an
  303. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  304. # the arg.
  305. # Current error values:
  306. # -1: Option that required an argument did not get it.
  307. # -2: Value of incorrect type supplied for option.
  308. # -3: Bad type given for option &
  309. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  310. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  311.     # If option takes a value...    [
  312.     NumTypes = "*()#<>]"
  313.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  314.     OptErr = "Bad type given for & option"
  315.     return -3
  316.     }
  317.  
  318.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  319.     if (!GotValue) {
  320.         if (Name != "")
  321.         OptErr = "Variable requires a value -- " Name
  322.         else
  323.         OptErr = "option requires an argument -- " Option
  324.         return -1
  325.     }
  326.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  327.         OptErr = Err
  328.         return -2
  329.     }
  330.     # Mark this as a numeric variable; will be propogated to Options[] val.
  331.     if (ArgType != ":" && ArgType != ";")
  332.         Value += 0
  333.     if ((Instance = ++Options[Option,"count"]) > 1)
  334.         Options[Option,Instance] = Value
  335.     else
  336.         Options[Option] = Value
  337.     }
  338.     # If this is an environ or rcfile assignment & it was given a value...
  339.     else if (!OptionNum && Value != "") {
  340.     UsedValue = 1
  341.     # If the value is "0" or "-" and this is the first instance of it,
  342.     # do not set Options[Option]; this allows an assignment in an rcfile to
  343.     # turn off an option (for the simple "Option in Options" test) in such
  344.     # a way that it cannot be turned on in a later file.
  345.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  346.         Instance = 1
  347.     else
  348.         Instance = ++Options[Option]
  349.     # Save the value even though this is a flag
  350.     Options[Option,Instance] = Value
  351.     }
  352.     # If this is a command line flag and has a - following it in the same arg,
  353.     # it is being turned off.
  354.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  355.     UsedValue = 2
  356.     if (Option in Options)
  357.         Instance = ++Options[Option]
  358.     else
  359.         Instance = 1
  360.     Options[Option,Instance]
  361.     }
  362.     # If this is a flag assignment without a value, increment the count for the
  363.     # flag unless it was turned off.  The indicator for a flag being turned off
  364.     # is that the flag index has not been set in Options[] but it has an
  365.     # instance count.
  366.     else if (Option in Options || !((Option,1) in Options))
  367.     # Increment number of times this flag seen; will inc null value to 1
  368.     Instance = ++Options[Option]
  369.     Options[Option,"num",Instance] = OptionNum
  370.     return UsedValue
  371. }
  372.  
  373. # Option is the option letter
  374. # Value is the value being assigned
  375. # Name is the var name of the option, if any
  376. # ArgType is one of:
  377. # :    String argument
  378. # ;    Non-null string argument
  379. # *    Floating point argument
  380. # (    Non-negative floating point argument
  381. # )    Positive floating point argument
  382. # #    Integer argument
  383. # <    Non-negative integer argument
  384. # >    Positive integer argument
  385. # specGiven is the option specifier character use, if any (e.g. - or +),
  386. # for use in error messages.
  387. # Returns null on success, err string on error
  388. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  389.     if (ArgType == ":")
  390.     return ""
  391.     if (ArgType == ";") {
  392.     if (Value == "")
  393.         Err = "must be a non-empty string"
  394.     }
  395.     # A number begins with optional + or -, and is followed by a string of
  396.     # digits or a decimal with digits before it, after it, or both
  397.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  398.     Err = "must be a number"
  399.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  400.     Err = "may not include a fraction"
  401.     else if (ArgType ~ "[()<>]" && Value < 0)
  402.     Err = "may not be negative"
  403.     # (
  404.     else if (ArgType ~ "[)>]" && Value == 0)
  405.     Err = "must be a positive number"
  406.     if (Err != "") {
  407.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  408.     if (Name != "")
  409.         return ErrStr "variable " substr(Name,1,1) " " Err
  410.     else {
  411.         if (Option == "&")
  412.         Option = Value
  413.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  414.     }
  415.     }
  416.     else
  417.     return ""
  418. }
  419.  
  420. # Note: only the above functions are needed by ProcArgs.
  421. # The rest of these functions call ProcArgs() and also do other
  422. # option-processing stuff.
  423.  
  424. # Opts: Process command line arguments.
  425. # Opts processes command line arguments using ProcArgs()
  426. # and checks for errors.  If an error occurs, a message is printed
  427. # and the program is exited.
  428. #
  429. # Input variables:
  430. # Name is the name of the program, for error messages.
  431. # Usage is a usage message, for error messages.
  432. # OptList the option description string, as used by ProcArgs().
  433. # MinArgs is the minimum number of non-option arguments that this
  434. # program should have, non including ARGV[0] and +h.
  435. # If the program does not require any non-option arguments,
  436. # MinArgs should be omitted or given as 0.
  437. # rcFiles, if given, is a colon-seprated list of filenames to read for
  438. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  439. # by the value of the environment variable HOME.  If a filename begins with
  440. # $, the part from the character after the $ up until (but not including)
  441. # the first character not in [a-zA-Z0-9_] will be searched for in the
  442. # environment; if found its value will be substituted, if not the filename will
  443. # be discarded.
  444. # rcfiles are read in the order given.
  445. # Values given in them will not override values given on the command line,
  446. # and values given in later files will not override those set in earlier
  447. # files, because AssignVal() will store each with a different instance index.
  448. # The first instance of each variable, either on the command line or in an
  449. # rcfile, will be stored with no instance index, and this is the value
  450. # normally used by programs that call this function.
  451. # VarNames is a comma-separated list of variable names to map to options,
  452. # in the same order as the options are given in OptList.
  453. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  454. # searched for in the environment.  If set to -1, all values will be searched
  455. # for in the environment.  Values given in the environment will override
  456. # those given in the rcfiles but not those given on the command line.
  457. # NoRCopt, if given, is an additional letter option that if given on the
  458. # command line prevents the rcfiles from being read.
  459. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  460. # ExclusiveOptions() for a description of exOpts.
  461. # Special options:
  462. # If x is made an option and is given, some debugging info is output.
  463. # h is assumed to be the help option.
  464.  
  465. # Global variables:
  466. # The command line arguments are taken from ARGV[].
  467. # The arguments that are option specifiers and values are removed from
  468. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  469. # The number of elements in ARGV[] should be in ARGC.
  470. # After processing, ARGC is set to the number of elements left in ARGV[].
  471. # The option values are put in Options[].
  472. # On error, Err is set to a positive integer value so it can be checked for in
  473. # an END block.
  474. # Return value: The number of elements left in ARGV is returned.
  475. # Must keep OptErr global since it may be set by InitOpts().
  476. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  477. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  478.     if (MinArgs == "")
  479.     MinArgs = 0
  480.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  481.     optChars)
  482.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  483.     if (ArgsLeft >= 0) {
  484.         OptErr = "Not enough arguments"
  485.         Err = 4
  486.     }
  487.     else
  488.         Err = -ArgsLeft
  489.     printf "%s: %s.\nUse -h for help.\n%s\n",
  490.     Name,OptErr,Usage > "/dev/stderr"
  491.     exit 1
  492.     }
  493.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  494.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  495.     {
  496.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  497.     Err = -e
  498.     exit 1
  499.     }
  500.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  501.     {
  502.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  503.     Err = 1
  504.     exit 1
  505.     }
  506.     return ArgsLeft
  507. }
  508.  
  509. # ReadConfFile(): Read a file containing var/value assignments, in the form
  510. # <variable-name><assignment-char><value>.
  511. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  512. # line and whitespace between the variable name and the assignment character) 
  513. # is stripped.  Lines that do not contain an assignment operator or which
  514. # contain a null variable name are ignored, other than possibly being noted in
  515. # the return value.  If more than one assignment is made to a variable, the
  516. # first assignment is used.
  517. # Input variables:
  518. # File is the file to read.
  519. # Comment is the line-comment character.  If it is found as the first non-
  520. #     whitespace character on a line, the line is ignored.
  521. # Assign is the assignment string.  The first instance of Assign on a line
  522. #     separates the variable name from its value.
  523. # If StripWhite is true, whitespace around the value (whitespace between the
  524. #     assignment char and trailing whitespace on the line) is stripped.
  525. # VarPat is a pattern that variable names must match.  
  526. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  527. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  528. #     a line; no assignment operator is needed.  These variables are set in
  529. #     the output array with a null value.  Lines containing nothing but
  530. #     whitespace are still ignored.
  531. # Output variables:
  532. # Values[] contains the assignments, with the indexes being the variable names
  533. #     and the values being the assigned values.
  534. # Lines[] contains the line number that each variable occured on.  A flag set
  535. #     is record by giving it an index in Lines[] but not in Values[].
  536. # Return value:
  537. # If any errors occur, a string consisting of descriptions of the errors
  538. # separated by newlines is returned.  In no case will the string start with a
  539. # numeric value.  If no errors occur,  the number of lines read is returned.
  540. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  541. FlagsOK,
  542. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  543.     if (Comment != "")
  544.     Comment = "^" Comment
  545.     AssignLen = length(Assign)
  546.     if (VarPat == "")
  547.     VarPat = "."    # null varname not allowed
  548.     while ((Status = (getline Line < File)) == 1) {
  549.     LineNum++
  550.     sub("^[ \t]+","",Line)
  551.     if (Line == "")        # blank line
  552.         continue
  553.     if (Comment != "" && Line ~ Comment)
  554.         continue
  555.     if (Pos = index(Line,Assign)) {
  556.         Var = substr(Line,1,Pos-1)
  557.         Val = substr(Line,Pos+AssignLen)
  558.         if (StripWhite) {
  559.         sub("^[ \t]+","",Val)
  560.         sub("[ \t]+$","",Val)
  561.         }
  562.     }
  563.     else {
  564.         Var = Line    # If no value, var is entire line
  565.         Val = ""
  566.     }
  567.     if (!FlagsOK && Val == "") {
  568.         Errs = Errs \
  569.         sprintf("\nBad assignment on line %d of file %s: %s",
  570.         LineNum,File,Line)
  571.         continue
  572.     }
  573.     sub("[ \t]+$","",Var)
  574.     if (Var !~ VarPat) {
  575.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  576.         LineNum,File,Var)
  577.         continue
  578.     }
  579.     if (!(Var in Lines)) {
  580.         Lines[Var] = LineNum
  581.         if (Pos)
  582.         Values[Var] = Val
  583.     }
  584.     }
  585.     if (Status)
  586.     Errs = Errs "\nCould not read file " File
  587.     close(File)
  588.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  589. }
  590.  
  591. # Variables:
  592. # Data is stored in Options[].
  593. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  594. # Global vars:
  595. # Sets OptErr.  Uses ENVIRON[].
  596. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  597. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  598. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  599. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  600.     split("",filesRead,"")    # make awk know this is an array
  601.     NumVars = split(VarNames,Vars,",")
  602.     TypesInd = Ret = 0
  603.     if (EnvSearch == -1)
  604.     EnvSearch = NumVars
  605.     for (i = 1; i <= NumVars; i++) {
  606.     Var = Vars[i]
  607.     CharOpt = substr(OptList,++TypesInd,1)
  608.     if (CharOpt ~ "^[:;*()#<>&]$")
  609.         CharOpt = substr(OptList,++TypesInd,1)
  610.     Map[Var] = CharOpt
  611.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  612.     # Do not overwrite entries from environment
  613.     if (i <= EnvSearch && Var in ENVIRON &&
  614.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  615.         return Err
  616.     }
  617.  
  618.     numrcFiles = split(rcFiles,fNames,":")
  619.     for (i = 1; i <= numrcFiles; i++) {
  620.     rcFile = fNames[i]
  621.     if (rcFile ~ "^~/")
  622.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  623.     else if (rcFile ~ /^\$/) {
  624.         rcFile = substr(rcFile,2)
  625.         match(rcFile,"^[a-zA-Z0-9_]*")
  626.         envvar = substr(rcFile,1,RLENGTH)
  627.         if (envvar in ENVIRON)
  628.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  629.         else
  630.         continue
  631.     }
  632.     if (rcFile in filesRead)
  633.         continue
  634.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  635.     # may be the same
  636.     filesRead[rcFile]
  637.     if ("x" in Options)
  638.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  639.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  640.     if (retStr > 0)
  641.         READ_RCFILE = 1
  642.     else if (ret != "") {
  643.         OptErr = retStr
  644.         Ret = -1
  645.     }
  646.     for (Var in Lines)
  647.         if (Var in Map) {
  648.         if ((Err = AssignVal(Map[Var],
  649.         Var in Values ? Values[Var] : "",Options,Types[Var],
  650.         Var in Values,Var,0)) < 0)
  651.             return Err
  652.         }
  653.         else {
  654.         OptErr = sprintf(\
  655.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  656.         Lines[Var],rcFile)
  657.         Ret = -1
  658.         }
  659.     }
  660.  
  661.     if ("x" in Options)
  662.     for (Var in Map)
  663.         if (Map[Var] in Options)
  664.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  665.         "/dev/stderr"
  666.         else
  667.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  668.     return Ret
  669. }
  670.  
  671. # OptSets is a semicolon-separated list of sets of option sets.
  672. # Within a list of option sets, the option sets are separated by commas.  For
  673. # each set of sets, if any option in one of the sets is in Options[] AND any
  674. # option in one of the other sets is in Options[], an error string is returned.
  675. # If no conflicts are found, nothing is returned.
  676. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  677. # the exclusions presented by the first set of sets (ab,def,g) if:
  678. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  679. # (a or b is in Options[]) AND (g is in Options) OR
  680. # (d, e, or f is in Options[]) AND (g is in Options)
  681. # An error will be returned due to the exclusions presented by the second set
  682. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  683. # todo: make options given on command line unset options given in config file
  684. # todo: that they conflict with.
  685. function ExclusiveOptions(OptSets,Options,
  686. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  687. SetNum,OSetNum) {
  688.     NumSetSets = split(OptSets,SetSets,";")
  689.     # For each set of sets...
  690.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  691.     # NumSets is the number of sets in this set of sets.
  692.     NumSets = split(SetSets[SetSet],Sets,",")
  693.     # For each set in a set of sets except the last...
  694.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  695.         s1 = Sets[SetNum]
  696.         L1 = length(s1)
  697.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  698.         # If any of the options in this set was given, check whether
  699.         # any of the options in the other sets was given.  Only check
  700.         # later sets since earlier sets will have already been checked
  701.         # against this set.
  702.         if ((c1 = substr(s1,Pos1,1)) in Options)
  703.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  704.             s2 = Sets[OSetNum]
  705.             L2 = length(s2)
  706.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  707.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  708.                 ErrStr = ErrStr "\n"\
  709.                 sprintf("Cannot give both %s and %s options.",
  710.                 c1,c2)
  711.             }
  712.     }
  713.     }
  714.     if (ErrStr != "")
  715.     return substr(ErrStr,2)
  716.     return ""
  717. }
  718.  
  719. # The value of each instance of option Opt that occurs in Options[] is made an
  720. # index of Set[].
  721. # The return value is the number of instances of Opt in Options.
  722. function Opt2Set(Options,Opt,Set,  count) {
  723.     if (!(Opt in Options))
  724.     return 0
  725.     Set[Options[Opt]]
  726.     count = Options[Opt,"count"]
  727.     for (; count > 1; count--)
  728.     Set[Options[Opt,count]]
  729.     return count
  730. }
  731.  
  732. # The value of each instance of option Opt that occurs in Options[] that
  733. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  734. # Other values are made indexes of Set[].
  735. # The return value is the number of instances of Opt in Options.
  736. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  737.     ret = Opt2Set(Options,Opt,aSet)
  738.     for (value in aSet)
  739.     if (substr(value,1,1) == "!")
  740.         nSet[substr(value,2)]
  741.     else
  742.         Set[value]
  743.     return ret
  744. }
  745.  
  746. # Returns true if option Opt was given on the command line.
  747. function CmdLineOpt(Options,Opt,  i) {
  748.     for (i = 1; (Opt,"num",i) in Options; i++)
  749.     if (Options[Opt,"num",i] != 0)
  750.         return 1
  751.     return 0
  752. }
  753. ### End of ProcArgs library
  754.  
  755. # jhdiii 96/05/14
  756. # Converts all of the elements of Arr with integer indices from Min to Max
  757. # to a string of arguments individually quoted so that when passed to the
  758. # shell as a command line to execute they will remain individual arguments and
  759. # will not undergo any type of substitution.  Equivalent to "$@" in sh.
  760. function QuoteArgs(Arr,Min,Max,  i,S,Arg) {
  761.     for (i = Min; i <= Max; i++) {
  762.     Arg = Arr[i]
  763.     # Args are quoted with single-quotes.  To deal with single-quotes in
  764.     # the arg, whereever one occurs, close the single-quotes, add a
  765.     # backslash-escaped single quote, then re-open the single quotes.
  766.     gsub("'","'\\''",Arg)
  767.     S = S " '" Arg "'"
  768.     }
  769.     return substr(S,2)    # Lose initial space
  770. }
  771.