blob: 98437658ce0b7b966132beab4535cbfe5c385f9a [file] [log] [blame]
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -05001#!/usr/bin/env python
2# encoding: utf-8
Haibo Huangb0bee822021-02-24 15:40:15 -08003# Copyright 2009 Baptiste Lepilleur and The JsonCpp Authors
4# Distributed under MIT license, or public domain if desired and
5# recognized in your jurisdiction.
6# See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -05007
8from __future__ import print_function
9from dircache import listdir
10import re
11import fnmatch
12import os.path
13
14
15# These fnmatch expressions are used by default to prune the directory tree
16# while doing the recursive traversal in the glob_impl method of glob function.
17prune_dirs = '.git .bzr .hg .svn _MTN _darcs CVS SCCS '
18
19# These fnmatch expressions are used by default to exclude files and dirs
20# while doing the recursive traversal in the glob_impl method of glob function.
21##exclude_pats = prune_pats + '*~ #*# .#* %*% ._* .gitignore .cvsignore vssver.scc .DS_Store'.split()
22
23# These ant_glob expressions are used by default to exclude files and dirs and also prune the directory tree
24# while doing the recursive traversal in the glob_impl method of glob function.
25default_excludes = '''
26**/*~
27**/#*#
28**/.#*
29**/%*%
30**/._*
31**/CVS
32**/CVS/**
33**/.cvsignore
34**/SCCS
35**/SCCS/**
36**/vssver.scc
37**/.svn
38**/.svn/**
39**/.git
40**/.git/**
41**/.gitignore
42**/.bzr
43**/.bzr/**
44**/.hg
45**/.hg/**
46**/_MTN
47**/_MTN/**
48**/_darcs
49**/_darcs/**
50**/.DS_Store '''
51
52DIR = 1
53FILE = 2
54DIR_LINK = 4
55FILE_LINK = 8
56LINKS = DIR_LINK | FILE_LINK
57ALL_NO_LINK = DIR | FILE
58ALL = DIR | FILE | LINKS
59
Haibo Huangb0bee822021-02-24 15:40:15 -080060_ANT_RE = re.compile(r'(/\*\*/)|(\*\*/)|(/\*\*)|(\*)|(/)|([^\*/]*)')
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050061
Haibo Huangb0bee822021-02-24 15:40:15 -080062def ant_pattern_to_re(ant_pattern):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050063 """Generates a regular expression from the ant pattern.
64 Matching convention:
65 **/a: match 'a', 'dir/a', 'dir1/dir2/a'
66 a/**/b: match 'a/b', 'a/c/b', 'a/d/c/b'
67 *.py: match 'script.py' but not 'a/script.py'
68 """
69 rex = ['^']
70 next_pos = 0
Haibo Huangb0bee822021-02-24 15:40:15 -080071 sep_rex = r'(?:/|%s)' % re.escape(os.path.sep)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050072## print 'Converting', ant_pattern
Haibo Huangb0bee822021-02-24 15:40:15 -080073 for match in _ANT_RE.finditer(ant_pattern):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050074## print 'Matched', match.group()
75## print match.start(0), next_pos
76 if match.start(0) != next_pos:
Haibo Huangb0bee822021-02-24 15:40:15 -080077 raise ValueError("Invalid ant pattern")
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050078 if match.group(1): # /**/
Haibo Huangb0bee822021-02-24 15:40:15 -080079 rex.append(sep_rex + '(?:.*%s)?' % sep_rex)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050080 elif match.group(2): # **/
Haibo Huangb0bee822021-02-24 15:40:15 -080081 rex.append('(?:.*%s)?' % sep_rex)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050082 elif match.group(3): # /**
Haibo Huangb0bee822021-02-24 15:40:15 -080083 rex.append(sep_rex + '.*')
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050084 elif match.group(4): # *
Haibo Huangb0bee822021-02-24 15:40:15 -080085 rex.append('[^/%s]*' % re.escape(os.path.sep))
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050086 elif match.group(5): # /
Haibo Huangb0bee822021-02-24 15:40:15 -080087 rex.append(sep_rex)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050088 else: # somepath
Haibo Huangb0bee822021-02-24 15:40:15 -080089 rex.append(re.escape(match.group(6)))
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050090 next_pos = match.end()
91 rex.append('$')
Haibo Huangb0bee822021-02-24 15:40:15 -080092 return re.compile(''.join(rex))
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050093
Haibo Huangb0bee822021-02-24 15:40:15 -080094def _as_list(l):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -050095 if isinstance(l, basestring):
96 return l.split()
97 return l
98
99def glob(dir_path,
100 includes = '**/*',
101 excludes = default_excludes,
102 entry_type = FILE,
103 prune_dirs = prune_dirs,
104 max_depth = 25):
105 include_filter = [ant_pattern_to_re(p) for p in _as_list(includes)]
106 exclude_filter = [ant_pattern_to_re(p) for p in _as_list(excludes)]
107 prune_dirs = [p.replace('/',os.path.sep) for p in _as_list(prune_dirs)]
108 dir_path = dir_path.replace('/',os.path.sep)
109 entry_type_filter = entry_type
110
Haibo Huangb0bee822021-02-24 15:40:15 -0800111 def is_pruned_dir(dir_name):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500112 for pattern in prune_dirs:
Haibo Huangb0bee822021-02-24 15:40:15 -0800113 if fnmatch.fnmatch(dir_name, pattern):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500114 return True
115 return False
116
Haibo Huangb0bee822021-02-24 15:40:15 -0800117 def apply_filter(full_path, filter_rexs):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500118 """Return True if at least one of the filter regular expression match full_path."""
119 for rex in filter_rexs:
Haibo Huangb0bee822021-02-24 15:40:15 -0800120 if rex.match(full_path):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500121 return True
122 return False
123
Haibo Huangb0bee822021-02-24 15:40:15 -0800124 def glob_impl(root_dir_path):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500125 child_dirs = [root_dir_path]
126 while child_dirs:
127 dir_path = child_dirs.pop()
Haibo Huangb0bee822021-02-24 15:40:15 -0800128 for entry in listdir(dir_path):
129 full_path = os.path.join(dir_path, entry)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500130## print 'Testing:', full_path,
Haibo Huangb0bee822021-02-24 15:40:15 -0800131 is_dir = os.path.isdir(full_path)
132 if is_dir and not is_pruned_dir(entry): # explore child directory ?
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500133## print '===> marked for recursion',
Haibo Huangb0bee822021-02-24 15:40:15 -0800134 child_dirs.append(full_path)
135 included = apply_filter(full_path, include_filter)
136 rejected = apply_filter(full_path, exclude_filter)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500137 if not included or rejected: # do not include entry ?
138## print '=> not included or rejected'
139 continue
Haibo Huangb0bee822021-02-24 15:40:15 -0800140 link = os.path.islink(full_path)
141 is_file = os.path.isfile(full_path)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500142 if not is_file and not is_dir:
143## print '=> unknown entry type'
144 continue
145 if link:
146 entry_type = is_file and FILE_LINK or DIR_LINK
147 else:
148 entry_type = is_file and FILE or DIR
149## print '=> type: %d' % entry_type,
150 if (entry_type & entry_type_filter) != 0:
151## print ' => KEEP'
Haibo Huangb0bee822021-02-24 15:40:15 -0800152 yield os.path.join(dir_path, entry)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500153## else:
154## print ' => TYPE REJECTED'
Haibo Huangb0bee822021-02-24 15:40:15 -0800155 return list(glob_impl(dir_path))
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500156
157
158if __name__ == "__main__":
159 import unittest
160
161 class AntPatternToRETest(unittest.TestCase):
Haibo Huangb0bee822021-02-24 15:40:15 -0800162## def test_conversion(self):
163## self.assertEqual('^somepath$', ant_pattern_to_re('somepath').pattern)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500164
Haibo Huangb0bee822021-02-24 15:40:15 -0800165 def test_matching(self):
166 test_cases = [ ('path',
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500167 ['path'],
Haibo Huangb0bee822021-02-24 15:40:15 -0800168 ['somepath', 'pathsuffix', '/path', '/path']),
169 ('*.py',
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500170 ['source.py', 'source.ext.py', '.py'],
Haibo Huangb0bee822021-02-24 15:40:15 -0800171 ['path/source.py', '/.py', 'dir.py/z', 'z.pyc', 'z.c']),
172 ('**/path',
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500173 ['path', '/path', '/a/path', 'c:/a/path', '/a/b/path', '//a/path', '/a/path/b/path'],
Haibo Huangb0bee822021-02-24 15:40:15 -0800174 ['path/', 'a/path/b', 'dir.py/z', 'somepath', 'pathsuffix', 'a/somepath']),
175 ('path/**',
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500176 ['path/a', 'path/path/a', 'path//'],
Haibo Huangb0bee822021-02-24 15:40:15 -0800177 ['path', 'somepath/a', 'a/path', 'a/path/a', 'pathsuffix/a']),
178 ('/**/path',
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500179 ['/path', '/a/path', '/a/b/path/path', '/path/path'],
Haibo Huangb0bee822021-02-24 15:40:15 -0800180 ['path', 'path/', 'a/path', '/pathsuffix', '/somepath']),
181 ('a/b',
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500182 ['a/b'],
Haibo Huangb0bee822021-02-24 15:40:15 -0800183 ['somea/b', 'a/bsuffix', 'a/b/c']),
184 ('**/*.py',
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500185 ['script.py', 'src/script.py', 'a/b/script.py', '/a/b/script.py'],
Haibo Huangb0bee822021-02-24 15:40:15 -0800186 ['script.pyc', 'script.pyo', 'a.py/b']),
187 ('src/**/*.py',
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500188 ['src/a.py', 'src/dir/a.py'],
Haibo Huangb0bee822021-02-24 15:40:15 -0800189 ['a/src/a.py', '/src/a.py']),
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500190 ]
191 for ant_pattern, accepted_matches, rejected_matches in list(test_cases):
Haibo Huangb0bee822021-02-24 15:40:15 -0800192 def local_path(paths):
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500193 return [ p.replace('/',os.path.sep) for p in paths ]
Haibo Huangb0bee822021-02-24 15:40:15 -0800194 test_cases.append((ant_pattern, local_path(accepted_matches), local_path(rejected_matches)))
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500195 for ant_pattern, accepted_matches, rejected_matches in test_cases:
Haibo Huangb0bee822021-02-24 15:40:15 -0800196 rex = ant_pattern_to_re(ant_pattern)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500197 print('ant_pattern:', ant_pattern, ' => ', rex.pattern)
198 for accepted_match in accepted_matches:
199 print('Accepted?:', accepted_match)
Haibo Huangb0bee822021-02-24 15:40:15 -0800200 self.assertTrue(rex.match(accepted_match) is not None)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500201 for rejected_match in rejected_matches:
202 print('Rejected?:', rejected_match)
Haibo Huangb0bee822021-02-24 15:40:15 -0800203 self.assertTrue(rex.match(rejected_match) is None)
Derek Sollenberger2eb3b4d2016-01-11 14:41:40 -0500204
205 unittest.main()