3
# Copyright (C) 2014 Tim Marston <tim@edm.am>
5
# This file is part of stdhome (hereafter referred to as "this program").
6
# See http://ed.am/dev/stdhome for more information.
8
# This program is free software: you can redistribute it and/or modify
9
# it under the terms of the GNU General Public License as published by
10
# the Free Software Foundation, either version 3 of the License, or
11
# (at your option) any later version.
13
# This program is distributed in the hope that it will be useful,
14
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
# GNU General Public License for more details.
18
# You should have received a copy of the GNU General Public License
19
# along with this program. If not, see <http://www.gnu.org/licenses/>.
28
def __init__( self, file, section = None ):
30
self.section = section
31
self.patterns = list()
38
file = os.path.expanduser( self.file )
40
with open( file ) as f:
43
if e.errno != errno.ENOENT: raise
47
capture = False if self.section else True
50
# clean up line and skip empty lines and comments
52
if not len( line ): continue
53
if line[ :1 ] == '#': continue
55
# if section is set, capture lines after the section heading and
56
# only until the next heading
58
if self.section and re.match( '\[', line ): break
59
self.patterns.append( self.convert_line_to_regex( line ) )
60
elif self.section and line == '[' + self.section + ']':
64
def convert_line_to_regex( self, line ):
66
# detect (and remove) quotes
68
# if line[ :1 ] == line[ -1: ] and line[ :1 ] in list( "'", '"' ):
72
# detect escaped chars
76
line = re.sub( r'\?', '.', line )
77
line = re.sub( r'\*', '.*', line )
78
line = "^%s$" % ( line )
83
def matches( self, rel_file ):
84
for pattern in self.patterns:
85
if re.search( pattern, rel_file ):
91
content = "', '".join( self.patterns )
92
if content: content = " '" + content + "' "
93
return "FileMatcher(" + content + ")"