summaryrefslogtreecommitdiffstats
path: root/mdk-stage1/dietlibc/libshell/fnmatch.c
blob: ef43735f64ebcf2104dcad8c1bd712b26ce7d536 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <ctype.h>
#include <fnmatch.h>
#include <string.h>

#define NOTFIRST 128

static int match(char c,char d,int flags) {
  if (flags&FNM_CASEFOLD)
    return (tolower(c)==tolower(d));
  else
    return (c==d);
}

int fnmatch(const char *pattern, const char *string, int flags) {
  /*printf("fnmatch(\"%s\",\"%s\")\n",pattern,string);*/
  if (*string==0) {
    while (*pattern=='*') ++pattern;
    return (!!*pattern);
  }
  if (*string=='.' && *pattern!='.' && (flags&FNM_PERIOD)) {
    /* don't match if FNM_PERIOD and this is the first char */
    if ((flags&FNM_PERIOD) && (!(flags&NOTFIRST)))
      return FNM_NOMATCH;
    /* don't match if FNM_PERIOD and FNM_FILE_NAME and previous was '/' */
    if ((flags&(FNM_FILE_NAME|FNM_PERIOD)) && string[-1]=='/')
      return FNM_NOMATCH;
  }
  flags|=NOTFIRST;
  switch (*pattern) {
  case '[':
    {
      int neg=0;
      ++pattern;
      if (*string=='/' && flags&FNM_PATHNAME) return FNM_NOMATCH;
      if (*pattern=='^') { neg=1; ++pattern; }
      while (*pattern && *pattern!=']') {
	int res=0;
	if (pattern[1]=='-') {
	  if (*string>=*pattern && *string<=pattern[2]) res=1;
	  if (flags&FNM_CASEFOLD) {
	    if (tolower(*string)>=tolower(*pattern) && tolower(*string)<=tolower(pattern[2])) res=1;
	  }
	  pattern+=3;
	} else {
	  res=match(*pattern,*string,flags);
	  ++pattern;
	}
	if (res ^ neg) {
	  while (*pattern && *pattern!=']') ++pattern;
	  return fnmatch(pattern+1,string+1,flags);
	}
      }
    }
    break;
  case '\\':
    if (flags&FNM_NOESCAPE) {
      if (*string=='\\')
	return fnmatch(pattern+1,string+1,flags);
    } else {
      if (*string==pattern[1])
	return fnmatch(pattern+2,string+1,flags);
    }
    break;
  case '*':
    if ((*string=='/' && flags&FNM_PATHNAME) || fnmatch(pattern,string+1,flags))
      return fnmatch(pattern+1,string,flags);
    return 0;
  case 0:
    if (*string==0 || (*string=='/' && (flags&FNM_LEADING_DIR)))
      return 0;
    break;
  default:
    if (match(*pattern,*string,flags))
      return fnmatch(pattern+1,string+1,flags);
    break;
  }
  return FNM_NOMATCH;
}