Bug #211949 - As suggested by vapier, tighten the variable filter to also
[portage.git] / bin / filter-bash-environment.py
1 #!/usr/bin/env python
2 # Copyright 1999-2007 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
4 # $Id$
5
6 import os, re, sys
7
8 egrep_compat_map = {
9         "[:alnum:]" : r'\w',
10         "[:digit:]" : r'\d',
11         "[:space:]" : r'\s',
12 }
13
14 here_doc_re = re.compile(r'.*\s<<[-]?(\w+)$')
15
16 def compile_egrep_pattern(s):
17         for k, v in egrep_compat_map.iteritems():
18                 s = s.replace(k, v)
19         return re.compile(s)
20
21 def filter_bash_environment(pattern, file_in, file_out):
22         here_doc_delim = None
23         for line in file_in:
24                 if here_doc_delim is not None:
25                         if here_doc_delim.match(line):
26                                 here_doc_delim = None
27                         file_out.write(line)
28                         continue
29                 here_doc = here_doc_re.match(line)
30                 if here_doc is not None:
31                         here_doc_delim = re.compile("^%s$" % here_doc.group(1))
32                         file_out.write(line)
33                         continue
34                 if pattern.match(line) is None:
35                         file_out.write(line)
36
37 if __name__ == "__main__":
38         description = "Filter out any lines that match a given PATTERN " + \
39                 "while leaving bash here-documents intact. The PATTERN should " + \
40                 "use python regular expression syntax but [:space:] and " + \
41                 "[:alnum:] character classes will be automatically translated " + \
42                 "for compatibility with egrep syntax."
43         usage = "usage: %s PATTERN" % os.path.basename(sys.argv[0])
44         from optparse import OptionParser
45         parser = OptionParser(description=description, usage=usage)
46         options, args = parser.parse_args(sys.argv[1:])
47         if len(args) != 1:
48                 parser.error("Missing required PATTERN argument.")
49         file_in = sys.stdin
50         file_out = sys.stdout
51         filter_bash_environment(
52                 compile_egrep_pattern(args[0]), file_in, file_out)
53         file_out.flush()