f33
[build.git] / pkgs.py
1 #!/usr/bin/env python3
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 # pylint: disable=c0111
30
31
32 import sys
33 from sys import stderr
34 from optparse import OptionParser
35 import re
36
37 default_arch = 'x86_64'
38 known_archs = ['i386', 'i686', 'x86_64']
39 default_fcdistro = 'f33'
40 known_fcdistros = [
41     'centos5', 'centos6',
42     # oldies but we have references to that in the pkgs files
43     'f8', 'f10', 'f12', 'f14', 'f16', 'f18', 
44     'f20', 'f21', 'f22', 'f23', 'f24', 'f25', 'f27', 
45     # these ones are still relevant
46     'f29', 'f31', 'f33',
47     # scientific linux
48     'sl6',
49     # debians
50     'wheezy', 'jessie',
51     # ubuntus
52     'trusty',  # 14.04 LTS
53     'xenial',  # 16.04 LTS
54     'bionic',  # 18.04 LTS
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(
106                 'Internal error - unexpected qualifier {}'.format(qualifier))
107
108     m_comment = re.compile(r'\A\s*#')
109     m_blank = re.compile(r'\A\s*\Z')
110
111     m_ident = re.compile(r'\A'+re_ident+r'\Z')
112     re_qualified = r'\s*'
113     re_qualified += r'(?P<plus_minus>[+-]?)'
114     re_qualified += r'\s*'
115     re_qualified += r'(?P<keyword>{re_ident})'.format(re_ident=re_ident)
116     re_qualified += r'\s*'
117     re_qualified += r'(?P<qualifier>>=|<=|=)'
118     re_qualified += r'\s*'
119     re_qualified += r'(?P<fcdistro>{re_ident}[0-9]+)'.format(re_ident=re_ident)
120     re_qualified += r'\s*'
121     m_qualified = re.compile(r'\A{re_qualified}\Z'.format(re_qualified=re_qualified))
122
123     re_old = '[a-z]+[+-][a-z]+[0-9]+'
124     m_old = re.compile(r'\A{}\Z'.format(re_old))
125
126     # returns a tuple (included, excluded)
127     def parse(self, filename):
128         ok = True
129         included = []
130         excluded = []
131         try:
132             with open(filename) as feed:
133                 for lineno, line in enumerate(feed, 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 exc:
188             ok = False
189             print('Could not parse file', filename, exc, 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(
222         '-a', '--arch', dest='arch', action='store', default=default_arch,
223         help='target arch, e.g. i386 or x86_64, default={}'.format(default_arch))
224     parser.add_option(
225         '-f', '--fcdistro', dest='fcdistro', action='store', default=default_fcdistro,
226         help='fcdistro, e.g. f12 or centos5')
227     parser.add_option(
228         '-d', '--pldistro', dest='pldistro', action='store', default=default_pldistro,
229         help='pldistro, e.g. onelab or planetlab')
230     parser.add_option(
231         '-v', '--verbose', dest='verbose', action='store_true', default=False,
232         help='verbose when using qualifiers')
233     parser.add_option(
234         '-n', '--new-line', dest='new_line', action='store_true', default=False,
235         help='print outputs separated with newlines rather than with a space')
236     parser.add_option(
237         '-u', '--no-sort', dest='sort_results', default=True, action='store_false',
238         help='keep results in the same order as in the inputs')
239     (options, args) = parser.parse_args()
240
241     if len(args) <= 1:
242         parser.print_help(file=stderr)
243         sys.exit(1)
244     keyword = args[0]
245     inputs = args[1:]
246     if options.arch not in known_archs:
247         print('Unsupported arch', options.arch, file=stderr)
248         parser.print_help(file=stderr)
249         sys.exit(1)
250     if options.arch == 'i686':
251         options.arch = 'i386'
252     if options.fcdistro not in known_fcdistros:
253         print('Unsupported fcdistro', options.fcdistro, file=stderr)
254         parser.print_help(file=stderr)
255         sys.exit(1)
256
257     pkgs = PkgsParser(options.arch, options.fcdistro, options.pldistro,
258                       keyword, inputs, options)
259
260     if pkgs.run():
261         sys.exit(0)
262     else:
263         sys.exit(1)
264
265 if __name__ == '__main__':
266     if main():
267         sys.exit(0)
268     else:
269         sys.exit(1)