1 /* Cumulus: Efficient Filesystem Backup to the Cloud
2 * Copyright (C) 2012 The Cumulus Developers
3 * See the AUTHORS file for a list of contributors.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 /* Implementation of Cumulus include/exclude rules for selecting files to be
26 #include <sys/types.h>
37 FilePattern::FilePattern(const string& pattern, const string& basedir)
38 : refcount(1), orig_pattern(pattern), valid(false)
40 string pattern_as_regex = pattern_to_regex(pattern, basedir);
41 int status = regcomp(®ex, pattern_as_regex.c_str(),
42 REG_EXTENDED|REG_NOSUB);
45 regerror(status, ®ex, errbuf, sizeof(errbuf));
47 "Pattern %s: failed to compile as regular expression %s: %s\n",
48 pattern.c_str(), pattern_as_regex.c_str(), errbuf);
55 FilePattern::~FilePattern()
61 bool FilePattern::matches(const std::string& path) const
66 return regexec(®ex, path.c_str(), 0, NULL, 0) == 0;
69 string FilePattern::pattern_to_regex(const string& pattern,
70 const string& basedir)
72 /* Matches are always anchored to cover the entire string; we insert
73 * wildcards where needed if we only need to match a suffix of the path. */
76 size_t len = pattern.size();
78 /* Special case: an empty pattern matches all files. */
82 /* For a non-empty basedir, the match must ensure that the file actually
83 * falls within basedir. */
84 if (!basedir.empty() && basedir != ".") {
85 result += regex_quote(basedir) + "/";
88 /* A leading slash indicates a pattern that must match the entire path. If
89 * there is no leading slash, match any number of leading directory
91 if (pattern[0] == '/') {
99 /* Characters that must be quoted in a regular expression that are not
100 * otherwise part of the Cumulus pattern language. */
114 result += pattern[i];
118 /* Any character except a directory separator. */
123 if (i + 1 < len && pattern[i + 1] == '*') {
124 /* Any number of characters, including slashes. */
128 /* Zero or more characters (but no directory separators). */
134 /* A character matched literally that does not require quoting. */
135 result += pattern[i];
141 /* A trailing slash should match only a directory. No trailing slash means
142 * match any type of file. Callers should include a slash at the end of a
143 * path that is a directory; if there is no trailing slash in the pattern
144 * match either a trailing slash or none. */
145 if (pattern[len - 1] != '/') {
154 string FilePattern::regex_quote(const string& pattern)
157 for (size_t i = 0; i < pattern.length(); i++) {
158 switch (pattern[i]) {
159 /* Characters that must be quoted in a regular expression. */
178 result += pattern[i];
185 PathFilterList::PathFilterList()
187 /* Invariant: pattern_stack is always non-empty (except when the destructor
188 * runs). Thus, reading pattern_stack.front() is always safe. */
189 pattern_stack.push_back(make_pair(1, new PatternList));
192 PathFilterList::~PathFilterList()
194 /* Pops all items off the saved rule stack. As an optimization, rather
195 * than repeatedly popping items which have a repeat count, just set the
196 * repeat count to one. */
197 while (!pattern_stack.empty()) {
198 pattern_stack.front().first = 1;
203 /* save() operates lazily: simply increment the repeat count on the rule set at
204 * the head of the list. If modifications are made, mutable_patterns() will
205 * create a copy of the rules. */
206 void PathFilterList::save()
208 pattern_stack.front().first++;
211 void PathFilterList::restore()
213 if (--pattern_stack.front().first == 0) {
214 PatternList *old_patterns = pattern_stack.front().second;
215 pattern_stack.pop_front();
216 for (PatternList::iterator i = old_patterns->begin();
217 i != old_patterns->end(); ++i) {
224 void PathFilterList::add_pattern(PatternType type, const string& pattern,
225 const string& basedir)
227 FilePattern *pat = new FilePattern(pattern, basedir);
228 mutable_patterns()->push_back(make_pair(type, pat));
231 bool PathFilterList::is_included(const std::string& path,
232 bool is_directory) const
236 full_path = path + "/";
241 PatternList::const_iterator i;
242 for (i = patterns().begin(); i != patterns().end(); ++i) {
243 if (i->second->matches(full_path)) {
250 /* Merge rules are ignored for the purposes of selecting
251 * whether a file is included or not. */
257 /* Default is include if no rule matches. */
261 bool PathFilterList::is_mergefile(const std::string& path) const
263 PatternList::const_iterator i;
264 for (i = patterns().begin(); i != patterns().end(); ++i) {
265 if (i->first == DIRMERGE && i->second->matches(path))
271 /* Parses the specified contents of a per-directory rule merge file. The rules
272 * are first parsed into a temporary PatternList, which is then spliced into
273 * the rule set just before the DIRMERGE rule. Thus, if a dir-merge rule
274 * matches multiple times (in successive sub-directories), deeper rules take
275 * precedence over earlier rules. */
276 void PathFilterList::merge_patterns(const string& path,
277 const string& basedir,
278 const string& contents)
280 PatternList *rules = mutable_patterns();
281 PatternList::iterator i;
282 for (PatternList::iterator i = rules->begin(); i != rules->end(); ++i) {
283 /* Try to locate where the rules should be inserted by looking for the
284 * DIRMERGE rule which matches the path to the rule file. */
285 if (i->first == DIRMERGE && i->second->matches(path)) {
286 PatternList *new_rules = parse_rules(basedir, contents);
287 rules->splice(i, *new_rules);
294 PathFilterList::PatternList *PathFilterList::parse_rules(const string& basedir,
297 PatternList *patterns = new PatternList;
298 std::stringstream rules(data, std::stringstream::in);
299 while (!rules.eof()) {
301 std::getline(rules, rule);
302 /* Ignore blank lines and lines starting with "#". */
303 if (rule.empty() || rule[0] == '#')
305 if (rule.length() > 2 && rule[1] == ' ') {
306 if (rule[0] == '+' || rule[0] == '-' || rule[0] == ':') {
307 FilePattern *pat = new FilePattern(rule.substr(2), basedir);
310 patterns->push_back(make_pair(INCLUDE, pat));
313 patterns->push_back(make_pair(EXCLUDE, pat));
316 patterns->push_back(make_pair(DIRMERGE, pat));
323 fprintf(stderr, "Invalid rule: %s\n", rule.c_str());
329 PathFilterList::PatternList *PathFilterList::mutable_patterns()
331 PatternList *old_list = pattern_stack.front().second;
332 if (pattern_stack.front().first == 1)
335 PatternList *new_list = new PatternList;
336 for (PatternList::iterator i = old_list->begin();
337 i != old_list->end(); ++i) {
339 new_list->push_back(*i);
341 pattern_stack.front().first--;
342 pattern_stack.push_front(make_pair(1, new_list));
347 /*****************************************************************************
348 * Unit tests for pattern matching. These are not compiled in by default, but
349 * exclude.cc can be compiled to a standalone binary with -DRUN_TESTS to run
351 *****************************************************************************/
354 /* Tests of pattern matching rules. test_pattern takes a pattern, a base
355 * directory, and a path to match, and prints out whether the rule matches.
356 * expect_match is the expected result; if this doesn't equal the actual result
357 * print a warning message. */
358 static void test_pattern(const string& pattern, const string& basedir,
359 const string& path, bool expect_match)
361 FilePattern pat(pattern, basedir);
362 bool result = pat.matches(path);
363 printf("%3s %c %c %-30s %-30s\n",
364 result == expect_match ? "" : "ERR",
366 expect_match ? '+' : '-',
371 int main(int argc, char *argv[])
373 printf("Act/Exp Pattern Path\n");
374 test_pattern("*.o", "", "a/b/c.txt", false);
375 test_pattern("*.o", "", "a/b/c.o", true);
376 test_pattern("*.git/", "", "repo/project.git/", true);
377 test_pattern("/.cache", "", ".cache", true);
378 test_pattern("/.cache", "", "home/user/.cache", false);
379 test_pattern("/*/.cache", "", "home/user/.cache", false);
380 test_pattern("/*/*/.cache", "", "home/user/.cache", true);
381 test_pattern("/**/.cache", "", "home/user/.cache", true);
382 test_pattern(".cache", "", "home/user/.cache", true);
383 test_pattern("?.o", "", "home/user/a.o", true);
384 test_pattern("?.o", "", "home/user/a/o", false);
385 test_pattern("*.o", "", "a/b/\n.o", true);
386 test_pattern("/**/.cache", "", "home/new\nline/.cache", true);
387 test_pattern("/*/.cache", "home", "home/user/.cache", true);
388 test_pattern(".cache", "home", "home/user/.cache", true);
389 test_pattern("user/.cache", "home", "home/user/.cache", true);
390 test_pattern("user/.cache", "home/user", "home/user/.cache", false);
393 pfl.add_pattern(PathFilterList::DIRMERGE, ".cumulus-filter", "");
395 pfl.merge_patterns("dir/.cumulus-filter", "dir",