]> git.sesse.net Git - plocate/blob - needle.cpp
Remove dependency on non-POSIX header error.h.
[plocate] / needle.cpp
1 #include "needle.h"
2
3 #include "options.h"
4 #include "parse_trigrams.h"
5
6 #include <assert.h>
7 #include <fnmatch.h>
8 #include <stdint.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <utility>
13
14 using namespace std;
15
16 bool matches(const Needle &needle, const char *haystack)
17 {
18         if (needle.type == Needle::STRSTR) {
19                 return strstr(haystack, needle.str.c_str()) != nullptr;
20         } else if (needle.type == Needle::GLOB) {
21                 int flags = ignore_case ? FNM_CASEFOLD : 0;
22                 return fnmatch(needle.str.c_str(), haystack, flags) == 0;
23         } else {
24                 assert(needle.type == Needle::REGEX);
25                 return regexec(&needle.re, haystack, /*nmatch=*/0, /*pmatch=*/nullptr, /*flags=*/0) == 0;
26         }
27 }
28
29 string unescape_glob_to_plain_string(const string &needle)
30 {
31         string unescaped;
32         for (size_t i = 0; i < needle.size(); i += read_unigram(needle, i).second) {
33                 uint32_t ch = read_unigram(needle, i).first;
34                 assert(ch != WILDCARD_UNIGRAM);
35                 if (ch == PREMATURE_END_UNIGRAM) {
36                         fprintf(stderr, "Pattern '%s' ended prematurely\n", needle.c_str());
37                         exit(1);
38                 }
39                 unescaped.push_back(ch);
40         }
41         return unescaped;
42 }
43
44 regex_t compile_regex(const string &needle)
45 {
46         regex_t re;
47         int flags = REG_NOSUB;
48         if (ignore_case) {
49                 flags |= REG_ICASE;
50         }
51         if (use_extended_regex) {
52                 flags |= REG_EXTENDED;
53         }
54         int err = regcomp(&re, needle.c_str(), flags);
55         if (err != 0) {
56                 char errbuf[256];
57                 regerror(err, &re, errbuf, sizeof(errbuf));
58                 fprintf(stderr, "Error when compiling regex '%s': %s\n", needle.c_str(), errbuf);
59                 exit(1);
60         }
61         return re;
62 }