chiark / gitweb /
Restore friendly error messages
[fdroidserver.git] / fdroidserver / metadata.py
1 # -*- coding: utf-8 -*-
2 #
3 # metadata.py - part of the FDroid server tools
4 # Copyright (C) 2013, Ciaran Gultnieks, ciaran@ciarang.com
5 # Copyright (C) 2013-2014 Daniel Martí <mvdan@mvdan.cc>
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Affero General Public License for more details.
16 #
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 import os
21 import re
22 import glob
23 import cgi
24 import logging
25
26 srclibs = []
27
28 class MetaDataException(Exception):
29     def __init__(self, value):
30         self.value = value
31
32     def __str__(self):
33         return self.value
34
35 app_defaults = {
36     'Name': None,
37     'Provides': None,
38     'Auto Name': '',
39     'Categories': ['None'],
40     'Description': [],
41     'Summary': '',
42     'License': 'Unknown',
43     'Web Site': '',
44     'Source Code': '',
45     'Issue Tracker': '',
46     'Donate': None,
47     'FlattrID': None,
48     'Bitcoin': None,
49     'Litecoin': None,
50     'Dogecoin': None,
51     'Disabled': None,
52     'AntiFeatures': None,
53     'Archive Policy': None,
54     'Update Check Mode': 'None',
55     'Update Check Ignore': None,
56     'Update Check Name': None,
57     'Update Check Data': None,
58     'Vercode Operation': None,
59     'Auto Update Mode': 'None',
60     'Current Version': '',
61     'Current Version Code': '0',
62     'Repo Type': '',
63     'Repo': '',
64     'Requires Root': False,
65     'No Source Since': ''
66     }
67
68
69 # This defines the preferred order for the build items - as in the
70 # manual, they're roughly in order of application.
71 ordered_flags = [
72     'disable', 'commit', 'subdir', 'submodules', 'init',
73     'gradle', 'maven', 'kivy', 'output', 'oldsdkloc', 'target',
74     'update', 'encoding', 'forceversion', 'forcevercode', 'rm',
75     'extlibs', 'srclibs', 'patch', 'prebuild', 'scanignore',
76     'scandelete', 'build', 'buildjni', 'preassemble', 'bindir',
77     'antcommand', 'novcheck'
78     ]
79
80
81 # Designates a metadata field type and checks that it matches
82 #
83 # 'name'     - The long name of the field type
84 # 'matching' - List of possible values or regex expression
85 # 'sep'      - Separator to use if value may be a list
86 # 'fields'   - Metadata fields (Field:Value) of this type
87 # 'attrs'    - Build attributes (attr=value) of this type
88 #
89 class FieldType():
90     def __init__(self, name, matching, sep, fields, attrs):
91         self.name = name
92         self.matching = matching
93         if type(matching) is str:
94             self.compiled = re.compile(matching)
95         self.sep = sep
96         self.fields = fields
97         self.attrs = attrs
98
99     def _assert_regex(self, values, appid):
100         for v in values:
101             if not self.compiled.match(v):
102                 raise MetaDataException("'%s' is not a valid %s in %s. "
103                                         % (v, self.name, appid) +
104                                         "Regex pattern: %s" % (self.matching))
105
106     def _assert_list(self, values, appid):
107         for v in values:
108             if v not in self.matching:
109                 raise MetaDataException("'%s' is not a valid %s in %s. "
110                                         % (v, self.name, appid) +
111                                         "Possible values: %s" % (", ".join(self.matching)))
112
113     def check(self, value, appid):
114         if type(value) is not str or not value:
115             return
116         if self.sep is not None:
117             values = value.split(self.sep)
118         else:
119             values = [value]
120         if type(self.matching) is list:
121             self._assert_list(values, appid)
122         else:
123             self._assert_regex(values, appid)
124
125
126 # Generic value types
127 valuetypes = {
128     'int': FieldType("Integer",
129                      r'^[1-9][0-9]*$', None,
130                      ['FlattrID'],
131                      ['vercode']),
132
133     'http': FieldType("HTTP link",
134                       r'^http[s]?://', None,
135                       ["Web Site", "Source Code", "Issue Tracker", "Donate"], []),
136
137     'bitcoin': FieldType("Bitcoin address",
138                          r'^[a-zA-Z0-9]{27,34}$', None,
139                          ["Bitcoin"],
140                          []),
141
142     'litecoin': FieldType("Litecoin address",
143                           r'^L[a-zA-Z0-9]{33}$', None,
144                           ["Litecoin"],
145                           []),
146
147     'dogecoin': FieldType("Dogecoin address",
148                           r'^D[a-zA-Z0-9]{33}$', None,
149                           ["Dogecoin"],
150                           []),
151
152     'Bool': FieldType("Boolean",
153                       ['Yes', 'No'], None,
154                       ["Requires Root"],
155                       []),
156
157     'bool': FieldType("Boolean",
158                       ['yes', 'no'], None,
159                       [],
160                       ['submodules', 'oldsdkloc', 'forceversion', 'forcevercode',
161                        'novcheck']),
162
163     'Repo Type': FieldType("Repo Type",
164                            ['git', 'git-svn', 'svn', 'hg', 'bzr', 'srclib'], None,
165                            ["Repo Type"],
166                            []),
167
168     'archive': FieldType("Archive Policy",
169                          r'^[0-9]+ versions$', None,
170                          ["Archive Policy"],
171                          []),
172
173     'antifeatures': FieldType("Anti-Feature",
174                               ["Ads", "Tracking", "NonFreeNet", "NonFreeDep", "NonFreeAdd", "UpstreamNonFree"], ',',
175                               ["AntiFeatures"],
176                               []),
177
178     'autoupdatemodes': FieldType("Auto Update Mode",
179                                  r"^(Version .+|None)$", None,
180                                  ["Auto Update Mode"],
181                                  []),
182
183     'updatecheckmodes': FieldType("Update Check Mode",
184                                   r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$", None,
185                                   ["Update Check Mode"],
186                                   [])
187     }
188
189
190 # Check an app's metadata information for integrity errors
191 def check_metadata(info):
192     for k, t in valuetypes.iteritems():
193         for field in t.fields:
194             if field in info:
195                 t.check(info[field], info['id'])
196                 if k == 'Bool':
197                     info[field] = info[field] == "Yes"
198         for build in info['builds']:
199             for attr in t.attrs:
200                 if attr in build:
201                     t.check(build[attr], info['id'])
202                     if k == 'bool':
203                         build[attr] = build[attr] == "yes"
204                 elif k == 'bool':
205                     build[attr] = False
206
207
208 # Formatter for descriptions. Create an instance, and call parseline() with
209 # each line of the description source from the metadata. At the end, call
210 # end() and then text_plain, text_wiki and text_html will contain the result.
211 class DescriptionFormatter:
212     stNONE = 0
213     stPARA = 1
214     stUL = 2
215     stOL = 3
216     bold = False
217     ital = False
218     state = stNONE
219     text_plain = ''
220     text_wiki = ''
221     text_html = ''
222     linkResolver = None
223
224     def __init__(self, linkres):
225         self.linkResolver = linkres
226
227     def endcur(self, notstates=None):
228         if notstates and self.state in notstates:
229             return
230         if self.state == self.stPARA:
231             self.endpara()
232         elif self.state == self.stUL:
233             self.endul()
234         elif self.state == self.stOL:
235             self.endol()
236
237     def endpara(self):
238         self.text_plain += '\n'
239         self.text_html += '</p>'
240         self.state = self.stNONE
241
242     def endul(self):
243         self.text_html += '</ul>'
244         self.state = self.stNONE
245
246     def endol(self):
247         self.text_html += '</ol>'
248         self.state = self.stNONE
249
250     def formatted(self, txt, html):
251         formatted = ''
252         if html:
253             txt = cgi.escape(txt)
254         while True:
255             index = txt.find("''")
256             if index == -1:
257                 return formatted + txt
258             formatted += txt[:index]
259             txt = txt[index:]
260             if txt.startswith("'''"):
261                 if html:
262                     if self.bold:
263                         formatted += '</b>'
264                     else:
265                         formatted += '<b>'
266                 self.bold = not self.bold
267                 txt = txt[3:]
268             else:
269                 if html:
270                     if self.ital:
271                         formatted += '</i>'
272                     else:
273                         formatted += '<i>'
274                 self.ital = not self.ital
275                 txt = txt[2:]
276
277     def linkify(self, txt):
278         linkified_plain = ''
279         linkified_html = ''
280         while True:
281             index = txt.find("[")
282             if index == -1:
283                 return (linkified_plain + self.formatted(txt, False), linkified_html + self.formatted(txt, True))
284             linkified_plain += self.formatted(txt[:index], False)
285             linkified_html += self.formatted(txt[:index], True)
286             txt = txt[index:]
287             if txt.startswith("[["):
288                 index = txt.find("]]")
289                 if index == -1:
290                     raise MetaDataException("Unterminated ]]")
291                 url = txt[2:index]
292                 if self.linkResolver:
293                     url, urltext = self.linkResolver(url)
294                 else:
295                     urltext = url
296                 linkified_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
297                 linkified_plain += urltext
298                 txt = txt[index + 2:]
299             else:
300                 index = txt.find("]")
301                 if index == -1:
302                     raise MetaDataException("Unterminated ]")
303                 url = txt[1:index]
304                 index2 = url.find(' ')
305                 if index2 == -1:
306                     urltxt = url
307                 else:
308                     urltxt = url[index2 + 1:]
309                     url = url[:index2]
310                 linkified_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
311                 linkified_plain += urltxt
312                 if urltxt != url:
313                     linkified_plain += ' (' + url + ')'
314                 txt = txt[index + 1:]
315
316     def addtext(self, txt):
317         p, h = self.linkify(txt)
318         self.text_plain += p
319         self.text_html += h
320
321     def parseline(self, line):
322         self.text_wiki += "%s\n" % line
323         if not line:
324             self.endcur()
325         elif line.startswith('* '):
326             self.endcur([self.stUL])
327             if self.state != self.stUL:
328                 self.text_html += '<ul>'
329                 self.state = self.stUL
330             self.text_html += '<li>'
331             self.text_plain += '* '
332             self.addtext(line[1:])
333             self.text_html += '</li>'
334         elif line.startswith('# '):
335             self.endcur([self.stOL])
336             if self.state != self.stOL:
337                 self.text_html += '<ol>'
338                 self.state = self.stOL
339             self.text_html += '<li>'
340             self.text_plain += '* '  # TODO: lazy - put the numbers in!
341             self.addtext(line[1:])
342             self.text_html += '</li>'
343         else:
344             self.endcur([self.stPARA])
345             if self.state == self.stNONE:
346                 self.text_html += '<p>'
347                 self.state = self.stPARA
348             elif self.state == self.stPARA:
349                 self.text_html += ' '
350                 self.text_plain += ' '
351             self.addtext(line)
352
353     def end(self):
354         self.endcur()
355
356
357 # Parse multiple lines of description as written in a metadata file, returning
358 # a single string in plain text format.
359 def description_plain(lines, linkres):
360     ps = DescriptionFormatter(linkres)
361     for line in lines:
362         ps.parseline(line)
363     ps.end()
364     return ps.text_plain
365
366
367 # Parse multiple lines of description as written in a metadata file, returning
368 # a single string in wiki format. Used for the Maintainer Notes field as well,
369 # because it's the same format.
370 def description_wiki(lines):
371     ps = DescriptionFormatter(None)
372     for line in lines:
373         ps.parseline(line)
374     ps.end()
375     return ps.text_wiki
376
377
378 # Parse multiple lines of description as written in a metadata file, returning
379 # a single string in HTML format.
380 def description_html(lines, linkres):
381     ps = DescriptionFormatter(linkres)
382     for line in lines:
383         ps.parseline(line)
384     ps.end()
385     return ps.text_html
386
387
388 def parse_srclib(metafile):
389
390     thisinfo = {}
391     if metafile and not isinstance(metafile, file):
392         metafile = open(metafile, "r")
393
394     # Defaults for fields that come from metadata
395     thisinfo['Repo Type'] = ''
396     thisinfo['Repo'] = ''
397     thisinfo['Subdir'] = None
398     thisinfo['Prepare'] = None
399     thisinfo['Srclibs'] = None
400
401     if metafile is None:
402         return thisinfo
403
404     n = 0
405     for line in metafile:
406         n += 1
407         line = line.rstrip('\r\n')
408         if not line or line.startswith("#"):
409             continue
410
411         try:
412             field, value = line.split(':', 1)
413         except ValueError:
414             raise MetaDataException("Invalid metadata in %s:%d" % (line, n))
415
416         if field == "Subdir":
417             thisinfo[field] = value.split(',')
418         else:
419             thisinfo[field] = value
420
421     return thisinfo
422
423
424 # Read all metadata. Returns a list of 'app' objects (which are dictionaries as
425 # returned by the parse_metadata function.
426 def read_metadata(xref=True):
427     apps = []
428
429     for basedir in ('metadata', 'tmp'):
430         if not os.path.exists(basedir):
431             os.makedirs(basedir)
432
433     for metafile in sorted(glob.glob(os.path.join('metadata', '*.txt'))):
434         appinfo = parse_metadata(metafile)
435         check_metadata(appinfo)
436         apps.append(appinfo)
437
438     if xref:
439         # Parse all descriptions at load time, just to ensure cross-referencing
440         # errors are caught early rather than when they hit the build server.
441         def linkres(link):
442             for app in apps:
443                 if app['id'] == link:
444                     return ("fdroid.app:" + link, "Dummy name - don't know yet")
445             raise MetaDataException("Cannot resolve app id " + link)
446         for app in apps:
447             try:
448                 description_html(app['Description'], linkres)
449             except Exception, e:
450                 raise MetaDataException("Problem with description of " + app['id'] +
451                                         " - " + str(e))
452
453     return apps
454
455
456 # Get the type expected for a given metadata field.
457 def metafieldtype(name):
458     if name in ['Description', 'Maintainer Notes']:
459         return 'multiline'
460     if name in ['Categories']:
461         return 'list'
462     if name == 'Build Version':
463         return 'build'
464     if name == 'Build':
465         return 'buildv2'
466     if name == 'Use Built':
467         return 'obsolete'
468     if name not in app_defaults:
469         return 'unknown'
470     return 'string'
471
472
473 def flagtype(name):
474     if name in ['extlibs', 'srclibs', 'patch', 'rm', 'buildjni',
475                 'update', 'scanignore', 'scandelete']:
476         return 'list'
477     if name in ['init', 'prebuild', 'build']:
478         return 'script'
479     return 'string'
480
481
482 # Parse metadata for a single application.
483 #
484 #  'metafile' - the filename to read. The package id for the application comes
485 #               from this filename. Pass None to get a blank entry.
486 #
487 # Returns a dictionary containing all the details of the application. There are
488 # two major kinds of information in the dictionary. Keys beginning with capital
489 # letters correspond directory to identically named keys in the metadata file.
490 # Keys beginning with lower case letters are generated in one way or another,
491 # and are not found verbatim in the metadata.
492 #
493 # Known keys not originating from the metadata are:
494 #
495 #  'id'               - the application's package ID
496 #  'builds'           - a list of dictionaries containing build information
497 #                       for each defined build
498 #  'comments'         - a list of comments from the metadata file. Each is
499 #                       a tuple of the form (field, comment) where field is
500 #                       the name of the field it preceded in the metadata
501 #                       file. Where field is None, the comment goes at the
502 #                       end of the file. Alternatively, 'build:version' is
503 #                       for a comment before a particular build version.
504 #  'descriptionlines' - original lines of description as formatted in the
505 #                       metadata file.
506 #
507 def parse_metadata(metafile):
508
509     linedesc = None
510
511     def add_buildflag(p, thisbuild):
512         bv = p.split('=', 1)
513         if len(bv) != 2:
514             raise MetaDataException("Invalid build flag at {0} in {1}"
515                                     .format(buildlines[0], linedesc))
516         pk, pv = bv
517         if pk in thisbuild:
518             raise MetaDataException("Duplicate definition on {0} in version {1} of {2}"
519                                     .format(pk, thisbuild['version'], linedesc))
520
521         pk = pk.lstrip()
522         if pk not in ordered_flags:
523             raise MetaDataException("Unrecognised build flag at {0} in {1}"
524                                     .format(p, linedesc))
525         t = flagtype(pk)
526         if t == 'list':
527             # Port legacy ';' separators
528             thisbuild[pk] = [v.strip() for v in pv.replace(';', ',').split(',')]
529         elif t == 'string':
530             thisbuild[pk] = pv
531         elif t == 'script':
532             thisbuild[pk] = pv
533         else:
534             raise MetaDataException("Unrecognised build flag type '%s' at %s in %s"
535                                     % (t, p, linedesc))
536
537     def parse_buildline(lines):
538         value = "".join(lines)
539         parts = [p.replace("\\,", ",")
540                  for p in re.split(r"(?<!\\),", value)]
541         if len(parts) < 3:
542             raise MetaDataException("Invalid build format: " + value + " in " + metafile.name)
543         thisbuild = {}
544         thisbuild['origlines'] = lines
545         thisbuild['version'] = parts[0]
546         thisbuild['vercode'] = parts[1]
547         if parts[2].startswith('!'):
548             # For backwards compatibility, handle old-style disabling,
549             # including attempting to extract the commit from the message
550             thisbuild['disable'] = parts[2][1:]
551             commit = 'unknown - see disabled'
552             index = parts[2].rfind('at ')
553             if index != -1:
554                 commit = parts[2][index + 3:]
555                 if commit.endswith(')'):
556                     commit = commit[:-1]
557             thisbuild['commit'] = commit
558         else:
559             thisbuild['commit'] = parts[2]
560         for p in parts[3:]:
561             add_buildflag(p, thisbuild)
562
563         return thisbuild
564
565     def add_comments(key):
566         if not curcomments:
567             return
568         for comment in curcomments:
569             thisinfo['comments'].append((key, comment))
570         del curcomments[:]
571
572     def get_build_type(build):
573         for t in ['maven', 'gradle', 'kivy']:
574             if build.get(t, 'no') != 'no':
575                 return t
576         if 'output' in build:
577             return 'raw'
578         return 'ant'
579
580     thisinfo = {}
581     if metafile:
582         if not isinstance(metafile, file):
583             metafile = open(metafile, "r")
584         thisinfo['id'] = metafile.name[9:-4]
585     else:
586         thisinfo['id'] = None
587
588     thisinfo.update(app_defaults)
589
590     # General defaults...
591     thisinfo['builds'] = []
592     thisinfo['comments'] = []
593
594     if metafile is None:
595         return thisinfo
596
597     mode = 0
598     buildlines = []
599     curcomments = []
600     curbuild = None
601
602     c = 0
603     for line in metafile:
604         c += 1
605         linedesc = "%s:%d" % (metafile.name, c)
606         line = line.rstrip('\r\n')
607         if mode == 3:
608             if not any(line.startswith(s) for s in (' ', '\t')):
609                 if 'commit' not in curbuild and 'disable' not in curbuild:
610                     raise MetaDataException("No commit specified for {0} in {1}"
611                                             .format(curbuild['version'], linedesc))
612                 thisinfo['builds'].append(curbuild)
613                 add_comments('build:' + curbuild['version'])
614                 mode = 0
615             else:
616                 if line.endswith('\\'):
617                     buildlines.append(line[:-1].lstrip())
618                 else:
619                     buildlines.append(line.lstrip())
620                     bl = ''.join(buildlines)
621                     add_buildflag(bl, curbuild)
622                     buildlines = []
623
624         if mode == 0:
625             if not line:
626                 continue
627             if line.startswith("#"):
628                 curcomments.append(line)
629                 continue
630             try:
631                 field, value = line.split(':', 1)
632             except ValueError:
633                 raise MetaDataException("Invalid metadata in " + linedesc)
634             if field != field.strip() or value != value.strip():
635                 raise MetaDataException("Extra spacing found in " + linedesc)
636
637             # Translate obsolete fields...
638             if field == 'Market Version':
639                 field = 'Current Version'
640             if field == 'Market Version Code':
641                 field = 'Current Version Code'
642
643             fieldtype = metafieldtype(field)
644             if fieldtype not in ['build', 'buildv2']:
645                 add_comments(field)
646             if fieldtype == 'multiline':
647                 mode = 1
648                 thisinfo[field] = []
649                 if value:
650                     raise MetaDataException("Unexpected text on same line as " + field + " in " + linedesc)
651             elif fieldtype == 'string':
652                 thisinfo[field] = value
653             elif fieldtype == 'list':
654                 thisinfo[field] = [v.strip() for v in value.replace(';', ',').split(',')]
655             elif fieldtype == 'build':
656                 if value.endswith("\\"):
657                     mode = 2
658                     buildlines = [value[:-1]]
659                 else:
660                     thisinfo['builds'].append(parse_buildline([value]))
661                     add_comments('build:' + thisinfo['builds'][-1]['version'])
662             elif fieldtype == 'buildv2':
663                 curbuild = {}
664                 vv = value.split(',')
665                 if len(vv) != 2:
666                     raise MetaDataException('Build should have comma-separated version and vercode, not "{0}", in {1}'
667                                             .format(value, linedesc))
668                 curbuild['version'] = vv[0]
669                 curbuild['vercode'] = vv[1]
670                 buildlines = []
671                 mode = 3
672             elif fieldtype == 'obsolete':
673                 pass        # Just throw it away!
674             else:
675                 raise MetaDataException("Unrecognised field type for " + field + " in " + linedesc)
676         elif mode == 1:     # Multiline field
677             if line == '.':
678                 mode = 0
679             else:
680                 thisinfo[field].append(line)
681         elif mode == 2:     # Line continuation mode in Build Version
682             if line.endswith("\\"):
683                 buildlines.append(line[:-1])
684             else:
685                 buildlines.append(line)
686                 thisinfo['builds'].append(
687                     parse_buildline(buildlines))
688                 add_comments('build:' + thisinfo['builds'][-1]['version'])
689                 mode = 0
690     add_comments(None)
691
692     # Mode at end of file should always be 0...
693     if mode == 1:
694         raise MetaDataException(field + " not terminated in " + metafile.name)
695     elif mode == 2:
696         raise MetaDataException("Unterminated continuation in " + metafile.name)
697     elif mode == 3:
698         raise MetaDataException("Unterminated build in " + metafile.name)
699
700     if not thisinfo['Description']:
701         thisinfo['Description'].append('No description available')
702
703     for build in thisinfo['builds']:
704         build['type'] = get_build_type(build)
705
706     return thisinfo
707
708
709 # Write a metadata file.
710 #
711 # 'dest'    - The path to the output file
712 # 'app'     - The app data
713 def write_metadata(dest, app):
714
715     def writecomments(key):
716         written = 0
717         for pf, comment in app['comments']:
718             if pf == key:
719                 mf.write("%s\n" % comment)
720                 written += 1
721         if written > 0:
722             logging.debug("...writing comments for " + (key if key else 'EOF'))
723
724     def writefield(field, value=None):
725         writecomments(field)
726         if value is None:
727             value = app[field]
728         t = metafieldtype(field)
729         if t == 'list':
730             value = ','.join(value)
731         mf.write("%s:%s\n" % (field, value))
732
733     mf = open(dest, 'w')
734     if app['Disabled']:
735         writefield('Disabled')
736     if app['AntiFeatures']:
737         writefield('AntiFeatures')
738     if app['Provides']:
739         writefield('Provides')
740     writefield('Categories')
741     writefield('License')
742     writefield('Web Site')
743     writefield('Source Code')
744     writefield('Issue Tracker')
745     if app['Donate']:
746         writefield('Donate')
747     if app['FlattrID']:
748         writefield('FlattrID')
749     if app['Bitcoin']:
750         writefield('Bitcoin')
751     if app['Litecoin']:
752         writefield('Litecoin')
753     if app['Dogecoin']:
754         writefield('Dogecoin')
755     mf.write('\n')
756     if app['Name']:
757         writefield('Name')
758     if app['Auto Name']:
759         writefield('Auto Name')
760     writefield('Summary')
761     writefield('Description', '')
762     for line in app['Description']:
763         mf.write("%s\n" % line)
764     mf.write('.\n')
765     mf.write('\n')
766     if app['Requires Root']:
767         writefield('Requires Root', 'Yes')
768         mf.write('\n')
769     if app['Repo Type']:
770         writefield('Repo Type')
771         writefield('Repo')
772         mf.write('\n')
773     for build in app['builds']:
774         writecomments('build:' + build['version'])
775         mf.write("Build:%s,%s\n" % (build['version'], build['vercode']))
776
777         def write_builditem(key, value):
778             if key in ['version', 'vercode', 'origlines', 'type']:
779                 return
780             if key in valuetypes['bool'].attrs:
781                 if not value:
782                     return
783                 value = 'yes'
784             t = flagtype(key)
785             logging.debug("...writing {0} : {1}".format(key, value))
786             outline = '    %s=' % key
787             if t == 'string':
788                 outline += value
789             elif t == 'script':
790                 outline += '&& \\\n        '.join([s.lstrip() for s in value.split('&& ')])
791             elif t == 'list':
792                 outline += ','.join(value) if type(value) == list else value
793             outline += '\n'
794             mf.write(outline)
795
796         for key in ordered_flags:
797             if key in build:
798                 write_builditem(key, build[key])
799         mf.write('\n')
800
801     if 'Maintainer Notes' in app:
802         writefield('Maintainer Notes', '')
803         for line in app['Maintainer Notes']:
804             mf.write("%s\n" % line)
805         mf.write('.\n')
806         mf.write('\n')
807
808     if app['Archive Policy']:
809         writefield('Archive Policy')
810     writefield('Auto Update Mode')
811     writefield('Update Check Mode')
812     if app['Update Check Ignore']:
813         writefield('Update Check Ignore')
814     if app['Vercode Operation']:
815         writefield('Vercode Operation')
816     if app['Update Check Data']:
817         writefield('Update Check Data')
818     if app['Current Version']:
819         writefield('Current Version')
820         writefield('Current Version Code')
821     mf.write('\n')
822     if app['No Source Since']:
823         writefield('No Source Since')
824         mf.write('\n')
825     writecomments(None)
826     mf.close()