f29
[build.git] / pkgs.py
1 #!/usr/bin/python
2 #
3 # This is a replacement for the formerly bash-written function pl_parsePkgs ()
4 #
5 # Usage: $0  [-a arch] default_arch keyword fcdistro pldistro pkgs-file[..s]
6 # default_arch is $pl_DISTRO_ARCH, but can be overridden
7 #
8
9 #################### original language was (in this example, keyword=package)
10 ## to add to all distros
11 # package: p1 p2
12 ## to add in one distro
13 # package+f12: p1 p2
14 ## to remove in one distro
15 # package-f10: p1 p2
16 #################### replacement language
17 ## add in distro f10
18 # +package=f10: p1 p2
19 # or simply
20 # package=f10: p1 p2
21 ## add in fedora distros starting with f10
22 # +package>=f10: p1 p2
23 # or simply
24 # package>=f10: p1 p2
25 ## ditto but remove instead
26 # -package=centos5: p1 p2
27 # -package<=centos5: p1 p2
28
29 from __future__ import print_function
30
31 import sys
32 from sys import stderr
33 from optparse import OptionParser
34 import re
35
36 default_arch='x86_64'
37 known_arch = ['i386', 'i686', 'x86_64']
38 default_fcdistro = 'f29'
39 known_fcdistros = [
40     'centos5', 'centos6',
41     # oldies but we have references to that in the pkgs files
42     'f8', 'f10', 'f12', 'f16',
43     # these ones are still relevant
44     'f14', 'f18', 'f20', 'f21', 'f22', 'f23', 'f24', 'f25', 'f27', 'f29',
45     'sl6',
46     # debians
47     'wheezy','jessie',
48     # ubuntus
49     'precise', # 12.04 LTS
50     'trusty',  # 14.04 LTS
51     'utopic',  # 14.10
52     'vivid',   # 15.04
53     'wily',    # 15.10
54     'xenial',  # 16.04
55 ]
56 default_pldistro='onelab'
57
58 known_keywords = [
59     'group', 'groupname', 'groupdesc',
60      'package', 'pip', 'gem',
61     'nodeyumexclude', 'plcyumexclude', 'yumexclude',
62     'precious', 'junk', 'mirror',
63 ]
64
65
66 m_fcdistro_cutter = re.compile('([a-z]+)([0-9]+)')
67 re_ident = '[a-z]+'
68
69 class PkgsParser:
70
71     def __init__(self, arch, fcdistro, pldistro, keyword, inputs, options):
72         self.arch = arch
73         self.fcdistro = fcdistro
74         self.pldistro = pldistro
75         self.keyword = keyword
76         self.inputs = inputs
77         # for verbose, new_line, and the like
78         self.options = options
79         ok = False
80         for known in known_fcdistros:
81             if fcdistro == known:
82                 try:
83                     (distro, version) = m_fcdistro_cutter.match(fcdistro).groups()
84                 # debian-like names can't use numbering
85                 except:
86                     distro = fcdistro
87                     version = 0
88                 ok = True
89         if ok:
90             self.distro = distro
91             self.version = int(version)
92         else:
93             print('unrecognized fcdistro', fcdistro, file=stderr)
94             sys.exit(1)
95
96     # qualifier is either '>=','<=', or '='
97     def match (self, qualifier, version):
98         if qualifier == '=':
99             return self.version == version
100         elif qualifier == '>=':
101             return self.version >= version
102         elif qualifier == '<=':
103             return self.version <= version
104         else:
105             raise Exception('Internal error - unexpected qualifier {qualifier}'.format(**locals()))
106
107     m_comment = re.compile('\A\s*#')
108     m_blank = re.compile('\A\s*\Z')
109
110     m_ident = re.compile('\A'+re_ident+'\Z')
111     re_qualified = '\s*'
112     re_qualified += '(?P<plus_minus>[+-]?)'
113     re_qualified += '\s*'
114     re_qualified += '(?P<keyword>{re_ident})'.format(re_ident=re_ident)
115     re_qualified += '\s*'
116     re_qualified += '(?P<qualifier>>=|<=|=)'
117     re_qualified += '\s*'
118     re_qualified += '(?P<fcdistro>{re_ident}[0-9]+)'.format(re_ident=re_ident)
119     re_qualified += '\s*'
120     m_qualified = re.compile('\A{re_qualified}\Z'.format(**locals()))
121
122     re_old = '[a-z]+[+-][a-z]+[0-9]+'
123     m_old = re.compile('\A{re_old}\Z'.format(**locals()))
124
125     # returns a tuple (included, excluded)
126     def parse(self, filename):
127         ok = True
128         included = []
129         excluded = []
130         lineno = 0
131         try:
132             for line in file(filename).readlines():
133                 lineno += 1
134                 line = line.strip()
135                 if self.m_comment.match(line) or self.m_blank.match(line):
136                     continue
137                 try:
138                     lefts, rights = line.split(':', 1)
139                     for left in lefts.split():
140                         ########## single ident
141                         if self.m_ident.match(left):
142                             if left not in known_keywords:
143                                 raise Exception("Unknown keyword {left}".format(**locals()))
144                             elif left == self.keyword:
145                                 included += rights.split()
146                         else:
147                             m = self.m_qualified.match(left)
148                             if m:
149                                 (plus_minus, kw, qual, fcdistro) = m.groups()
150                                 if kw not in known_keywords:
151                                     raise Exception("Unknown keyword in {left}".format(**locals()))
152                                 if fcdistro not in known_fcdistros:
153                                     raise Exception('Unknown fcdistro {fcdistro}'.format(**locals()))
154                                 # skip if another keyword
155                                 if kw != self.keyword: continue
156                                 # does this fcdistro match ?
157                                 (distro, version) = m_fcdistro_cutter.match(fcdistro).groups()
158                                 version = int (version)
159                                 # skip if another distro family
160                                 if distro != self.distro: continue
161                                 # skip if the qualifier does not fit
162                                 if not self.match (qual, version):
163                                     if self.options.verbose:
164                                         print('{filename}:{lineno}:qualifer {left} does not apply'
165                                               .format(**locals()), file=stderr)
166                                     continue
167                                 # we're in, let's add (default) or remove (if plus_minus is minus)
168                                 if plus_minus == '-':
169                                     if self.options.verbose:
170                                         print('{filename}:{lineno}: from {left}, excluding {rights}'
171                                               .format(**locals()), file=stderr)
172                                     excluded += rights.split()
173                                 else:
174                                     if self.options.verbose:
175                                         print('{filename}:{lineno}: from {left}, including {rights}'\
176                                               .format(**locals()), file=stderr)
177                                     included += rights.split()
178                             elif self.m_old.match(left):
179                                 raise Exception('Old-fashioned syntax not supported anymore {left}'.\
180                                                 format(**locals()))
181                             else:
182                                 raise Exception('error in left expression {left}'.format(**locals()))
183
184                 except Exception as e:
185                     ok = False
186                     print("{filename}:{lineno}:syntax error: {e}".format(**locals()), file=stderr)
187         except Exception as e:
188             ok = False
189             print('Could not parse file', filename, e, file=stderr)
190         return (ok, included, excluded)
191
192     def run (self):
193         ok = True
194         included = []
195         excluded = []
196         for input in self.inputs:
197             (o, i, e) = self.parse (input)
198             included += i
199             excluded += e
200             ok = ok and o
201         # avoid set operations that would not preserve order
202         results = [ x for x in included if x not in excluded ]
203
204         results = [ x.replace('@arch@', self.arch).\
205                         replace('@fcdistro@', self.fcdistro).\
206                         replace('@pldistro@', self.pldistro) for x in results]
207         if self.options.sort_results:
208             results.sort()
209         # default is space-separated
210         if not self.options.new_line:
211             print(" ".join(results))
212         # but for tests results are printed each on a line
213         else:
214             for result in results:
215                 print(result)
216         return ok
217
218 def main ():
219     usage = "Usage: %prog [options] keyword input[...]"
220     parser = OptionParser (usage=usage)
221     parser.add_option ('-a', '--arch', dest='arch', action='store', default=default_arch,
222                        help='target arch, e.g. i386 or x86_64, default={}'.format(default_arch))
223     parser.add_option ('-f', '--fcdistro', dest='fcdistro', action='store', default=default_fcdistro,
224                        help='fcdistro, e.g. f12 or centos5')
225     parser.add_option ('-d', '--pldistro', dest='pldistro', action='store', default=default_pldistro,
226                        help='pldistro, e.g. onelab or planetlab')
227     parser.add_option ('-v', '--verbose', dest='verbose', action='store_true', default=False,
228                        help='verbose when using qualifiers')
229     parser.add_option ('-n', '--new-line', dest='new_line', action='store_true', default=False,
230                        help='print outputs separated with newlines rather than with a space')
231     parser.add_option ('-u', '--no-sort', dest='sort_results', default=True, action='store_false',
232                        help='keep results in the same order as in the inputs')
233     (options, args) = parser.parse_args()
234
235     if len(args) <= 1 :
236         parser.print_help(file=stderr)
237         sys.exit(1)
238     keyword = args[0]
239     inputs = args[1:]
240     if not options.arch in known_arch:
241         print('Unsupported arch', options.arch, file=stderr)
242         parser.print_help(file=stderr)
243         sys.exit(1)
244     if options.arch == 'i686':
245         options.arch='i386'
246     if not options.fcdistro in known_fcdistros:
247         print('Unsupported fcdistro', options.fcdistro, file=stderr)
248         parser.print_help(file=stderr)
249         sys.exit(1)
250
251     pkgs = PkgsParser(options.arch, options.fcdistro, options.pldistro, keyword, inputs, options)
252
253     if pkgs.run():
254         sys.exit(0)
255     else:
256         sys.exit(1)
257
258 if __name__ == '__main__':
259     if main():
260         sys.exit(0)
261     else:
262         sys.exit(1)