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