bug 1478613, expose remaining variables in matcher regex, r?stas
If we match a path, we'd like to know which variables got which
value. Say, the {locale} code in a path.
MozReview-Commit-ID: EmUO5WB2y8U
--- a/compare_locales/paths.py
+++ b/compare_locales/paths.py
@@ -46,28 +46,33 @@ class Matcher(object):
if m.group('star'):
p += '([^/]*)'
r += r'\%s' % next(backref)
else:
p += re.escape(m.group(1)) + r'(.+%s)?' % m.group(2)
r += m.group(1) + r'\%s' % next(backref) + m.group(2)
last_end = m.end()
p += re.escape(pattern[last_end:]) + '$'
+ # Now replace variable references with named group matches.
+ # The regex here matches the variable regex plus escaping.
+ p = re.sub(
+ r'\\{(?:\\ )*([\w]+)(?:\\ )*\\}',
+ lambda m: '(?P<{}>.+?)'.format(m.group(1).replace('\\', '')), p)
r += pattern[last_end:]
if last_end == 0:
prefix = pattern
self.prefix = prefix
self.regex = re.compile(p)
self.placable = r
def match(self, path):
'''
True if the given path matches the file pattern.
'''
- return self.regex.match(path) is not None
+ return self.regex.match(path)
def sub(self, other, path):
'''
Replace the wildcard matches in this pattern into the
pattern of the other Match object.
'''
if not self.match(path):
return None
--- a/compare_locales/tests/test_paths.py
+++ b/compare_locales/tests/test_paths.py
@@ -61,16 +61,34 @@ class TestMatcher(unittest.TestCase):
)
self.assertEqual(
Matcher('foo/*/bar').prefix, 'foo/'
)
self.assertEqual(
Matcher('foo/**/bar').prefix, 'foo'
)
+ def test_variables(self):
+ self.assertDictEqual(
+ Matcher('foo/bar.file').match('foo/bar.file').groupdict(),
+ {}
+ )
+ self.assertDictEqual(
+ Matcher('{path}/bar.file').match('foo/bar.file').groupdict(),
+ {
+ 'path': 'foo'
+ }
+ )
+ self.assertDictEqual(
+ Matcher('{ path }/bar.file').match('foo/bar.file').groupdict(),
+ {
+ 'path': 'foo'
+ }
+ )
+
class SetupMixin(object):
def setUp(self):
self.cfg = ProjectConfig()
self.file = File(
'/tmp/somedir/de/browser/one/two/file.ftl',
'file.ftl',
module='browser', locale='de')