home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Professional / OS2PRO194.ISO / os2 / prgramer / rcs / sources / glob.c < prev    next >
C/C++ Source or Header  |  1992-01-19  |  14KB  |  593 lines

  1. /* File-name wildcard pattern matching for GNU. Part 1/2
  2.    Copyright (C) 1985, 1988, 1989, 1990 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 1, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  17.  
  18. /* To whomever it may concern: I have never seen the code which most
  19.    Unix programs use to perform this function.  I wrote this from scratch
  20.    based on specifications for the pattern matching.  --RMS.  */
  21.  
  22. #include <sys/types.h>
  23.  
  24. #if    defined(STDC_HEADERS) || defined(__GNU_LIBRARY__)
  25. #include <stdlib.h>
  26. #include <string.h>
  27. #define bcopy(s, d, n) memcpy ((d), (s), (n))
  28. #define index strchr
  29. #define rindex strrchr
  30. #else
  31.  
  32. #if defined(USG) || defined(OS2)
  33. #include <string.h>
  34. #include <memory.h>
  35. #define bcopy(s, d, n) memcpy ((d), (s), (n))
  36. #define index strchr
  37. #define rindex strrchr
  38. #else /* not USG */
  39. #include <strings.h>
  40. extern void bcopy ();
  41. #endif /* not USG */
  42.  
  43. #ifdef OS2
  44. #include <malloc.h>
  45. #else
  46. extern char *malloc ();
  47. extern char *realloc ();
  48. extern void free ();
  49. #endif
  50.  
  51. #ifndef NULL
  52. #define NULL 0
  53. #endif
  54. #endif    /* Not STDC_HEADERS or __GNU_LIBRARY__.  */
  55.  
  56. #ifdef __GNUC__
  57. #define alloca __builtin_alloca
  58. #else /* Not GCC.  */
  59. #ifdef sparc
  60. #include <alloca.h>
  61. #else /* Not sparc.  */
  62. #ifndef OS2
  63. extern char *alloca ();
  64. #endif
  65. #endif /* sparc.  */
  66. #endif /* GCC.  */
  67.  
  68. #if defined(USGr3) || defined(DIRENT) || defined(__GNU_LIBRARY__)
  69. #include <dirent.h>
  70. #define direct dirent
  71. #define D_NAMLEN(d) strlen((d)->d_name)
  72. #else /* not USGr3 or DIRENT or __GNU_LIBRARY__ */
  73. #define D_NAMLEN(d) ((d)->d_namlen)
  74. #if defined(USG) && !defined(OS2)
  75. #ifdef SYSNDIR
  76. #include <sys/ndir.h>
  77. #else
  78. #include "ndir.h"        /* Get ndir.h from the Emacs distribution.  */
  79. #endif /* not SYSNDIR */
  80. #else /* not USG */
  81. #ifdef OS2
  82. #include "dir.h"
  83. #define direct dirent
  84. #else
  85. #include <sys/dir.h>
  86. #endif /* OS2 */
  87. #endif /* USG */
  88. #endif /* USGr3 */
  89.  
  90. /* Nonzero if '*' and '?' do not match an initial '.' for glob_filename.  */
  91. int noglob_dot_filenames = 1;
  92.  
  93. static int glob_match_after_star (char *pattern, char *text);
  94. int glob_pattern_p (char *pattern);
  95. int glob_match (char *pattern, char *text, int dot_special);
  96.  
  97. /* Return nonzero if PATTERN has any special globbing chars in it.  */
  98.  
  99. int glob_pattern_p (pattern)
  100.      char *pattern;
  101. {
  102.   register char *p = pattern;
  103.   register char c;
  104.  
  105.   while ((c = *p++) != '\0')
  106.     switch (c)
  107.       {
  108.       case '?':
  109.       case '[':
  110.       case '*':
  111.     return 1;
  112.  
  113.       case '\\':
  114.     if (*p++ == '\0')
  115.       return 0;
  116.       }
  117.  
  118.   return 0;
  119. }
  120.  
  121.  
  122. /* Match the pattern PATTERN against the string TEXT;
  123.    return 1 if it matches, 0 otherwise.
  124.  
  125.    A match means the entire string TEXT is used up in matching.
  126.  
  127.    In the pattern string, `*' matches any sequence of characters,
  128.    `?' matches any character, [SET] matches any character in the specified set,
  129.    [!SET] matches any character not in the specified set.
  130.  
  131.    A set is composed of characters or ranges; a range looks like
  132.    character hyphen character (as in 0-9 or A-Z).
  133.    [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
  134.    Any other character in the pattern must be matched exactly.
  135.  
  136.    To suppress the special syntactic significance of any of `[]*?!-\',
  137.    and match the character exactly, precede it with a `\'.
  138.  
  139.    If DOT_SPECIAL is nonzero,
  140.    `*' and `?' do not match `.' at the beginning of TEXT.  */
  141.  
  142. int glob_match (pattern, text, dot_special)
  143.      char *pattern, *text;
  144.      int dot_special;
  145. {
  146.   register char *p = pattern, *t = text;
  147.   register char c;
  148.  
  149.   while ((c = *p++) != '\0')
  150.     switch (c)
  151.       {
  152.       case '?':
  153.     if (*t == '\0' || (dot_special && t == text && *t == '.'))
  154.       return 0;
  155.     else
  156.       ++t;
  157.     break;
  158.  
  159.       case '\\':
  160.     if (*p++ != *t++)
  161.       return 0;
  162.     break;
  163.  
  164.       case '*':
  165.     if (dot_special && t == text && *t == '.')
  166.       return 0;
  167.     return glob_match_after_star (p, t);
  168.  
  169.       case '[':
  170.     {
  171.       register char c1 = *t++;
  172.       int invert;
  173.  
  174.       if (c1 == '\0')
  175.         return 0;
  176.  
  177.       invert = (*p == '!');
  178.  
  179.       if (invert)
  180.         p++;
  181.  
  182.       c = *p++;
  183.       while (1)
  184.         {
  185.           register char cstart = c, cend = c;
  186.  
  187.           if (c == '\\')
  188.         {
  189.           cstart = *p++;
  190.           cend = cstart;
  191.         }
  192.  
  193.           if (cstart == '\0')
  194.         return 0;    /* Missing ']'. */
  195.  
  196.           c = *p++;
  197.  
  198.           if (c == '-')
  199.         {
  200.           cend = *p++;
  201.           if (cend == '\\')
  202.             cend = *p++;
  203.           if (cend == '\0')
  204.             return 0;
  205.           c = *p++;
  206.         }
  207.           if (c1 >= cstart && c1 <= cend)
  208.         goto match;
  209.           if (c == ']')
  210.         break;
  211.         }
  212.       if (!invert)
  213.         return 0;
  214.       break;
  215.  
  216.     match:
  217.       /* Skip the rest of the [...] construct that already matched.  */
  218.       while (c != ']')
  219.         {
  220.           if (c == '\0')
  221.         return 0;
  222.           c = *p++;
  223.           if (c == '\0')
  224.         return 0;
  225.           if (c == '\\')
  226.         p++;
  227.         }
  228.       if (invert)
  229.         return 0;
  230.       break;
  231.     }
  232.  
  233.       default:
  234.     if (c != *t++)
  235.       return 0;
  236.       }
  237.  
  238.   return *t == '\0';
  239. }
  240.  
  241. /* Like glob_match, but match PATTERN against any final segment of TEXT.  */
  242.  
  243. static int glob_match_after_star (pattern, text)
  244.      char *pattern, *text;
  245. {
  246.   register char *p = pattern, *t = text;
  247.   register char c, c1;
  248.  
  249.   while ((c = *p++) == '?' || c == '*')
  250.     if (c == '?' && *t++ == '\0')
  251.       return 0;
  252.  
  253.   if (c == '\0')
  254.     return 1;
  255.  
  256.   if (c == '\\')
  257.     c1 = *p;
  258.   else
  259.     c1 = c;
  260.  
  261.   --p;
  262.   while (1)
  263.     {
  264.       if ((c == '[' || *t == c1) && glob_match (p, t, 0))
  265.     return 1;
  266.       if (*t++ == '\0')
  267.     return 0;
  268.     }
  269. }
  270.  
  271. int glob_pattern_p (char *pattern);
  272. int glob_match (char *pattern, char *text, int dot_special);
  273. static char **glob_dir_to_array (char *dir, char **array);
  274. char **glob_vector (char *pat, char *dir);
  275. char **glob_filename (char *pathname);
  276.  
  277.  
  278. /* Return a vector of names of files in directory DIR
  279.    whose names match glob pattern PAT.
  280.    The names are not in any particular order.
  281.    Wildcards at the beginning of PAT do not match an initial period
  282.    if noglob_dot_filenames is nonzero.
  283.  
  284.    The vector is terminated by an element that is a null pointer.
  285.  
  286.    To free the space allocated, first free the vector's elements,
  287.    then free the vector.
  288.  
  289.    Return NULL if cannot get enough memory to hold the pointer
  290.    and the names.
  291.  
  292.    Return -1 if cannot access directory DIR.
  293.    Look in errno for more information.  */
  294.  
  295. char **glob_vector (pat, dir)
  296.      char *pat;
  297.      char *dir;
  298. {
  299.   struct globval
  300.   {
  301.     struct globval *next;
  302.     char *name;
  303.   };
  304.  
  305.   DIR *d;
  306.   register struct direct *dp;
  307.   struct globval *lastlink;
  308.   register struct globval *nextlink;
  309.   register char *nextname;
  310.   unsigned int count;
  311.   int lose;
  312.   register char **name_vector;
  313.   register unsigned int i;
  314.  
  315.   d = opendir (dir);
  316.   if (d == NULL)
  317.     return (char **) -1;
  318.  
  319.   lastlink = NULL;
  320.   count = 0;
  321.   lose = 0;
  322.  
  323.   /* Scan the directory, finding all names that match.
  324.      For each name that matches, allocate a struct globval
  325.      on the stack and store the name in it.
  326.      Chain those structs together; lastlink is the front of the chain.  */
  327.   while (1)
  328.     {
  329.       dp = readdir (d);
  330.       if (dp == NULL)
  331.     break;
  332. #ifdef OS2
  333.       if (glob_match (pat, dp->d_name, noglob_dot_filenames))
  334. #else
  335.       if (dp->d_ino != 0
  336.       && glob_match (pat, dp->d_name, noglob_dot_filenames))
  337. #endif
  338.     {
  339.       nextlink = (struct globval *) alloca (sizeof (struct globval));
  340.       nextlink->next = lastlink;
  341.       i = D_NAMLEN (dp) + 1;
  342.       nextname = (char *) malloc (i);
  343.       if (nextname == NULL)
  344.         {
  345.           lose = 1;
  346.           break;
  347.         }
  348.       lastlink = nextlink;
  349.       nextlink->name = nextname;
  350.       bcopy (dp->d_name, nextname, i);
  351.       count++;
  352.     }
  353.     }
  354.   closedir (d);
  355.  
  356.   if (!lose)
  357.     {
  358.       name_vector = (char **) malloc ((count + 1) * sizeof (char *));
  359.       lose |= name_vector == NULL;
  360.     }
  361.  
  362.   /* Have we run out of memory?  */
  363.   if (lose)
  364.     {
  365.       /* Here free the strings we have got.  */
  366.       while (lastlink)
  367.     {
  368.       free (lastlink->name);
  369.       lastlink = lastlink->next;
  370.     }
  371.       return NULL;
  372.     }
  373.  
  374.   /* Copy the name pointers from the linked list into the vector.  */
  375.   for (i = 0; i < count; ++i)
  376.     {
  377.       name_vector[i] = lastlink->name;
  378.       lastlink = lastlink->next;
  379.     }
  380.  
  381.   name_vector[count] = NULL;
  382.   return name_vector;
  383. }
  384.  
  385. /* Return a new array, replacing ARRAY, which is the concatenation
  386.    of each string in ARRAY to DIR.
  387.    Return NULL if out of memory.  */
  388.  
  389. static char **glob_dir_to_array (dir, array)
  390.      char *dir, **array;
  391. {
  392.   register unsigned int i, l;
  393.   int add_slash = 0;
  394.   char **result;
  395.  
  396.   l = strlen (dir);
  397.   if (l == 0)
  398.     return array;
  399.  
  400.   if (dir[l - 1] != '/')
  401.     add_slash++;
  402.  
  403.   for (i = 0; array[i] != NULL; i++)
  404.     ;
  405.  
  406.   result = (char **) malloc ((i + 1) * sizeof (char *));
  407.   if (result == NULL)
  408.     return NULL;
  409.  
  410.   for (i = 0; array[i] != NULL; i++)
  411.     {
  412.       result[i] = (char *) malloc (1 + l + add_slash + strlen (array[i]));
  413.       if (result[i] == NULL)
  414.     return NULL;
  415.       strcpy (result[i], dir);
  416.       if (add_slash)
  417.     result[i][l] = '/';
  418.       strcpy (result[i] + l + add_slash, array[i]);
  419.     }
  420.   result[i] = NULL;
  421.  
  422.   /* Free the input array.  */
  423.   for (i = 0; array[i] != NULL; i++)
  424.     free (array[i]);
  425.   free ((char *) array);
  426.   return result;
  427. }
  428.  
  429. /* Do globbing on PATHNAME.  Return an array of pathnames that match,
  430.    marking the end of the array with a null-pointer as an element.
  431.    If no pathnames match, then the array is empty (first element is null).
  432.    If there isn't enough memory, then return NULL.
  433.    If a file system error occurs, return -1; `errno' has the error code.
  434.  
  435.    Wildcards at the beginning of PAT, or following a slash,
  436.    do not match an initial period if noglob_dot_filenames is nonzero.  */
  437.  
  438. char **glob_filename (pathname)
  439.      char *pathname;
  440. {
  441.   char **result;
  442.   unsigned int result_size;
  443.   char *directory_name, *filename;
  444.   unsigned int directory_len;
  445.  
  446.   result = (char **) malloc (sizeof (char *));
  447.   result_size = 1;
  448.   if (result == NULL)
  449.     return NULL;
  450.  
  451.   result[0] = NULL;
  452.  
  453.   /* Find the filename.  */
  454.   filename = rindex (pathname, '/');
  455.   if (filename == NULL)
  456.     {
  457.       filename = pathname;
  458.       directory_name = "";
  459.       directory_len = 0;
  460.     }
  461.   else
  462.     {
  463.       directory_len = (filename - pathname) + 1;
  464.       directory_name = (char *) alloca (directory_len + 1);
  465.       bcopy (pathname, directory_name, directory_len);
  466.       directory_name[directory_len] = '\0';
  467.       ++filename;
  468.     }
  469.  
  470.   /* If directory_name contains globbing characters, then we
  471.      have to expand the previous levels.  Just recurse. */
  472.   if (glob_pattern_p (directory_name))
  473.     {
  474.       char **directories;
  475.       register unsigned int i;
  476.  
  477.       if (directory_name[directory_len - 1] == '/')
  478.     directory_name[directory_len - 1] = '\0';
  479.  
  480.       directories = glob_filename (directory_name);
  481.       if (directories == NULL)
  482.     goto memory_error;
  483.       else if (directories == (char **) -1)
  484.     return (char **) -1;
  485.       else if (*directories == NULL)
  486.     {
  487.       free ((char *) directories);
  488.       return (char **) -1;
  489.     }
  490.  
  491.       /* We have successfully globbed the preceding directory name.
  492.      For each name in DIRECTORIES, call glob_vector on it and
  493.      FILENAME.  Concatenate the results together.  */
  494.       for (i = 0; directories[i] != NULL; i++)
  495.     {
  496.       char **temp_results = glob_vector (filename, directories[i]);
  497.       if (temp_results == NULL)
  498.         goto memory_error;
  499.       else if (temp_results == (char **) -1)
  500.         /* This filename is probably not a directory.  Ignore it.  */
  501.         ;
  502.       else
  503.         {
  504.           char **array = glob_dir_to_array (directories[i], temp_results);
  505.           register unsigned int l;
  506.  
  507.           l = 0;
  508.           while (array[l] != NULL)
  509.         ++l;
  510.  
  511.           result = (char **) realloc (result,
  512.                       (result_size + l) * sizeof (char *));
  513.           if (result == NULL)
  514.         goto memory_error;
  515.  
  516.           for (l = 0; array[l] != NULL; ++l)
  517.         result[result_size++ - 1] = array[l];
  518.           result[result_size - 1] = NULL;
  519.           free ((char *) array);
  520.         }
  521.     }
  522.       /* Free the directories.  */
  523.       for (i = 0; directories[i] != NULL; i++)
  524.     free (directories[i]);
  525.       free ((char *) directories);
  526.  
  527.       return result;
  528.     }
  529.  
  530.   /* If there is only a directory name, return it. */
  531.   if (*filename == '\0')
  532.     {
  533.       result = (char **) realloc ((char *) result, 2 * sizeof (char *));
  534.       if (result == NULL)
  535.     return NULL;
  536.       result[0] = (char *) malloc (directory_len + 1);
  537.       if (result[0] == NULL)
  538.     goto memory_error;
  539.       bcopy (directory_name, result[0], directory_len + 1);
  540.       result[1] = NULL;
  541.       return result;
  542.     }
  543.   else
  544.     {
  545.       /* Otherwise, just return what glob_vector
  546.      returns appended to the directory name. */
  547.       char **temp_results = glob_vector (filename,
  548.                      (directory_len == 0
  549.                       ? "." : directory_name));
  550.  
  551.       if (temp_results == NULL || temp_results == (char **) -1)
  552.     return temp_results;
  553.  
  554.       return glob_dir_to_array (directory_name, temp_results);
  555.     }
  556.  
  557. memory_error:;
  558.   if (result != NULL)
  559.     {
  560.       register unsigned int i;
  561.       for (i = 0; result[i] != NULL; ++i)
  562.     free (result[i]);
  563.       free ((char *) result);
  564.     }
  565.   return NULL;
  566. }
  567.  
  568.  
  569. #ifdef TEST
  570.  
  571. int main (argc, argv)
  572.      int argc;
  573.      char **argv;
  574. {
  575.   char **value;
  576.   int i, optind;
  577.  
  578.   for (optind = 1; optind < argc; optind++)
  579.     {
  580.       value = glob_filename (argv[optind]);
  581.       if (value == NULL)
  582.     puts ("virtual memory exhausted");
  583.       else if (value == (char **) -1)
  584.     perror (argv[optind]);
  585.       else
  586.     for (i = 0; value[i] != NULL; i++)
  587.       puts (value[i]);
  588.     }
  589.   return (0);
  590. }
  591.  
  592. #endif /* TEST */
  593.