myplc@master
[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_arch = ['i386', 'i686', 'x86_64']
39 default_fcdistro = 'f29'
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', 'f20', 'f21', 'f22', 'f23', 'f24',
44     # these ones are still relevant
45     'f25', 'f27', 'f29',
46     # scientific linux
47     'sl6',
48     # debians
49     'wheezy', 'jessie',
50     # ubuntus
51     'trusty',  # 14.04 LTS
52     'xenial',  # 16.04 LTS
53     'bionic',  # 18.04 LTS
54 ]
55 default_pldistro = 'onelab'
56
57 known_keywords = [
58     'group', 'groupname', 'groupdesc',
59      'package', 'pip', 'gem',
60     'nodeyumexclude', 'plcyumexclude', 'yumexclude',
61     'precious', 'junk', 'mirror',
62 ]
63
64
65 m_fcdistro_cutter = re.compile('([a-z]+)([0-9]+)')
66 re_ident = '[a-z]+'
67
68 class PkgsParser:
69
70     def __init__(self, arch, fcdistro, pldistro, keyword, inputs, options):
71         self.arch = arch
72         self.fcdistro = fcdistro
73         self.pldistro = pldistro
74         self.keyword = keyword
75         self.inputs = inputs
76         # for verbose, new_line, and the like
77         self.options = options
78         ok = False
79         for known in known_fcdistros:
80             if fcdistro == known:
81                 try:
82                     (distro, version) = m_fcdistro_cutter.match(fcdistro).groups()
83                 # debian-like names can't use numbering
84                 except:
85                     distro = fcdistro
86                     version = 0
87                 ok = True
88         if ok:
89             self.distro = distro
90             self.version = int(version)
91         else:
92             print('unrecognized fcdistro', fcdistro, file=stderr)
93             sys.exit(1)
94
95     # qualifier is either '>=','<=', or '='
96     def match(self, qualifier, version):
97         if qualifier == '=':
98             return self.version == version
99         elif qualifier == '>=':
100             return self.version >= version
101         elif qualifier == '<=':
102             return self.version <= version
103         else:
104             raise Exception(
105                 'Internal error - unexpected qualifier {}'.format(qualifier))
106
107     m_comment = re.compile(r'\A\s*#')
108     m_blank = re.compile(r'\A\s*\Z')
109
110     m_ident = re.compile(r'\A'+re_ident+r'\Z')
111     re_qualified = r'\s*'
112     re_qualified += r'(?P<plus_minus>[+-]?)'
113     re_qualified += r'\s*'
114     re_qualified += r'(?P<keyword>{re_ident})'.format(re_ident=re_ident)
115     re_qualified += r'\s*'
116     re_qualified += r'(?P<qualifier>>=|<=|=)'
117     re_qualified += r'\s*'
118     re_qualified += r'(?P<fcdistro>{re_ident}[0-9]+)'.format(re_ident=re_ident)
119     re_qualified += r'\s*'
120     m_qualified = re.compile(r'\A{}\Z'.format(re_qualified))
121
122     re_old = '[a-z]+[+-][a-z]+[0-9]+'
123     m_old = re.compile(r'\A{}\Z'.format(re_old))
124
125     # returns a tuple (included, excluded)
126     def parse(self, filename):
127         ok = True
128         included = []
129         excluded = []
130         try:
131             with open(filename) as feed:
132                 for lineno, line in enumerate(feed, 1):
133                     line = line.strip()
134                     if self.m_comment.match(line) or self.m_blank.match(line):
135                         continue
136                     try:
137                         lefts, rights = line.split(':', 1)
138                         for left in lefts.split():
139                             ########## single ident
140                             if self.m_ident.match(left):
141                                 if left not in known_keywords:
142                                     raise Exception("Unknown keyword {left}".format(**locals()))
143                                 elif left == self.keyword:
144                                     included += rights.split()
145                             else:
146                                 m = self.m_qualified.match(left)
147                                 if m:
148                                     (plus_minus, kw, qual, fcdistro) = m.groups()
149                                     if kw not in known_keywords:
150                                         raise Exception("Unknown keyword in {left}".format(**locals()))
151                                     if fcdistro not in known_fcdistros:
152                                         raise Exception('Unknown fcdistro {fcdistro}'.format(**locals()))
153                                     # skip if another keyword
154                                     if kw != self.keyword: continue
155                                     # does this fcdistro match ?
156                                     (distro, version) = m_fcdistro_cutter.match(fcdistro).groups()
157                                     version = int (version)
158                                     # skip if another distro family
159                                     if distro != self.distro: continue
160                                     # skip if the qualifier does not fit
161                                     if not self.match (qual, version):
162                                         if self.options.verbose:
163                                             print('{filename}:{lineno}:qualifer {left} does not apply'
164                                                   .format(**locals()), file=stderr)
165                                         continue
166                                     # we're in, let's add (default) or remove (if plus_minus is minus)
167                                     if plus_minus == '-':
168                                         if self.options.verbose:
169                                             print('{filename}:{lineno}: from {left}, excluding {rights}'
170                                                   .format(**locals()), file=stderr)
171                                         excluded += rights.split()
172                                     else:
173                                         if self.options.verbose:
174                                             print('{filename}:{lineno}: from {left}, including {rights}'\
175                                                   .format(**locals()), file=stderr)
176                                         included += rights.split()
177                                 elif self.m_old.match(left):
178                                     raise Exception('Old-fashioned syntax not supported anymore {left}'.\
179                                                     format(**locals()))
180                                 else:
181                                     raise Exception('error in left expression {left}'.format(**locals()))
182
183                     except Exception as e:
184                         ok = False
185                         print("{filename}:{lineno}:syntax error: {e}".format(**locals()), file=stderr)
186         except Exception as exc:
187             ok = False
188             print('Could not parse file', filename, exc, file=stderr)
189         return (ok, included, excluded)
190
191     def run (self):
192         ok = True
193         included = []
194         excluded = []
195         for input in self.inputs:
196             (o, i, e) = self.parse (input)
197             included += i
198             excluded += e
199             ok = ok and o
200         # avoid set operations that would not preserve order
201         results = [x for x in included if x not in excluded]
202
203         results = [x.replace('@arch@', self.arch)
204                    .replace('@fcdistro@', self.fcdistro)
205                    .replace('@pldistro@', self.pldistro) for x in results]
206         if self.options.sort_results:
207             results.sort()
208         # default is space-separated
209         if not self.options.new_line:
210             print(" ".join(results))
211         # but for tests results are printed each on a line
212         else:
213             for result in results:
214                 print(result)
215         return ok
216
217 def main ():
218     usage = "Usage: %prog [options] keyword input[...]"
219     parser = OptionParser(usage=usage)
220     parser.add_option(
221         '-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(
224         '-f', '--fcdistro', dest='fcdistro', action='store', default=default_fcdistro,
225         help='fcdistro, e.g. f12 or centos5')
226     parser.add_option(
227         '-d', '--pldistro', dest='pldistro', action='store', default=default_pldistro,
228         help='pldistro, e.g. onelab or planetlab')
229     parser.add_option(
230         '-v', '--verbose', dest='verbose', action='store_true', default=False,
231         help='verbose when using qualifiers')
232     parser.add_option(
233         '-n', '--new-line', dest='new_line', action='store_true', default=False,
234         help='print outputs separated with newlines rather than with a space')
235     parser.add_option(
236         '-u', '--no-sort', dest='sort_results', default=True, action='store_false',
237         help='keep results in the same order as in the inputs')
238     (options, args) = parser.parse_args()
239
240     if len(args) <= 1:
241         parser.print_help(file=stderr)
242         sys.exit(1)
243     keyword = args[0]
244     inputs = args[1:]
245     if not options.arch in known_arch:
246         print('Unsupported arch', options.arch, file=stderr)
247         parser.print_help(file=stderr)
248         sys.exit(1)
249     if options.arch == 'i686':
250         options.arch = 'i386'
251     if not options.fcdistro in known_fcdistros:
252         print('Unsupported fcdistro', options.fcdistro, file=stderr)
253         parser.print_help(file=stderr)
254         sys.exit(1)
255
256     pkgs = PkgsParser(options.arch, options.fcdistro, options.pldistro,
257                       keyword, inputs, options)
258
259     if pkgs.run():
260         sys.exit(0)
261     else:
262         sys.exit(1)
263
264 if __name__ == '__main__':
265     if main():
266         sys.exit(0)
267     else:
268         sys.exit(1)