1 # -*- coding: utf-8 -*-
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>
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.
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.
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/>.
28 from cStringIO import StringIO
30 from StringIO import StringIO
33 # use libyaml if it is available
35 from yaml import CLoader
38 from yaml import Loader
41 # use the C implementation when available
42 import xml.etree.cElementTree as ElementTree
49 class MetaDataException(Exception):
51 def __init__(self, value):
57 # To filter which ones should be written to the metadata files if
85 'Update Check Ignore',
90 'Current Version Code',
93 'comments', # For formats that don't do inline comments
94 'builds', # For formats that do builds as a list
102 self.AntiFeatures = []
104 self.Categories = ['None']
105 self.License = 'Unknown'
108 self.IssueTracker = ''
117 self.Description = ''
118 self.RequiresRoot = False
122 self.MaintainerNotes = ''
123 self.ArchivePolicy = None
124 self.AutoUpdateMode = 'None'
125 self.UpdateCheckMode = 'None'
126 self.UpdateCheckIgnore = None
127 self.VercodeOperation = None
128 self.UpdateCheckName = None
129 self.UpdateCheckData = None
130 self.CurrentVersion = ''
131 self.CurrentVersionCode = '0'
132 self.NoSourceSince = ''
135 self.metadatapath = None
139 self.lastupdated = None
141 # Translates human-readable field names to attribute names, e.g.
142 # 'Auto Name' to 'AutoName'
144 def field_to_attr(cls, f):
145 return f.replace(' ', '')
147 # Translates attribute names to human-readable field names, e.g.
148 # 'AutoName' to 'Auto Name'
150 def attr_to_field(cls, k):
153 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
156 # Constructs an old-fashioned dict with the human-readable field
157 # names. Should only be used for tests.
158 def field_dict(self):
160 for k, v in self.__dict__.iteritems():
164 d['builds'].append(build.__dict__)
166 k = App.attr_to_field(k)
170 # Gets the value associated to a field name, e.g. 'Auto Name'
171 def get_field(self, f):
172 if f not in app_fields:
173 raise MetaDataException('Unrecognised app field: ' + f)
174 k = App.field_to_attr(f)
175 return getattr(self, k)
177 # Sets the value associated to a field name, e.g. 'Auto Name'
178 def set_field(self, f, v):
179 if f not in app_fields:
180 raise MetaDataException('Unrecognised app field: ' + f)
181 k = App.field_to_attr(f)
184 # Appends to the value associated to a field name, e.g. 'Auto Name'
185 def append_field(self, f, v):
186 if f not in app_fields:
187 raise MetaDataException('Unrecognised app field: ' + f)
188 k = App.field_to_attr(f)
189 if k not in self.__dict__:
190 self.__dict__[k] = [v]
192 self.__dict__[k].append(v)
194 # Like dict.update(), but using human-readable field names
195 def update_fields(self, d):
196 for f, v in d.iteritems():
200 build.update_flags(b)
201 self.builds.append(build)
206 def metafieldtype(name):
207 if name in ['Description', 'Maintainer Notes']:
209 if name in ['Categories', 'AntiFeatures']:
211 if name == 'Build Version':
215 if name == 'Use Built':
217 if name in app_fields:
222 # In the order in which they are laid out on files
223 build_flags_order = [
256 build_flags = set(build_flags_order + ['version', 'vercode'])
265 self.submodules = False
273 self.oldsdkloc = False
275 self.forceversion = False
276 self.forcevercode = False
287 self.preassemble = []
288 self.gradleprops = []
289 self.antcommands = None
290 self.novcheck = False
292 def get_flag(self, f):
293 if f not in build_flags:
294 raise MetaDataException('Unrecognised build flag: ' + f)
295 return getattr(self, f)
297 def set_flag(self, f, v):
298 if f == 'versionName':
300 if f == 'versionCode':
302 if f not in build_flags:
303 raise MetaDataException('Unrecognised build flag: ' + f)
306 def append_flag(self, f, v):
307 if f not in build_flags:
308 raise MetaDataException('Unrecognised build flag: ' + f)
309 if f not in self.__dict__:
310 self.__dict__[f] = [v]
312 self.__dict__[f].append(v)
315 for f in ['maven', 'gradle', 'kivy']:
325 version = 'r10e' # falls back to latest
326 paths = common.config['ndk_paths']
327 if version not in paths:
329 return paths[version]
331 def update_flags(self, d):
332 for f, v in d.iteritems():
335 list_flags = set(['extlibs', 'srclibs', 'patch', 'rm', 'buildjni', 'preassemble',
336 'update', 'scanignore', 'scandelete', 'gradle', 'antcommands',
338 script_flags = set(['init', 'prebuild', 'build'])
339 bool_flags = set(['submodules', 'oldsdkloc', 'forceversion', 'forcevercode',
344 if name in list_flags:
346 if name in script_flags:
348 if name in bool_flags:
353 # Designates a metadata field type and checks that it matches
355 # 'name' - The long name of the field type
356 # 'matching' - List of possible values or regex expression
357 # 'sep' - Separator to use if value may be a list
358 # 'fields' - Metadata fields (Field:Value) of this type
359 # 'flags' - Build flags (flag=value) of this type
361 class FieldValidator():
363 def __init__(self, name, matching, sep, fields, flags):
365 self.matching = matching
366 if type(matching) is str:
367 self.compiled = re.compile(matching)
372 def _assert_regex(self, values, appid):
374 if not self.compiled.match(v):
375 raise MetaDataException("'%s' is not a valid %s in %s. "
376 % (v, self.name, appid) +
377 "Regex pattern: %s" % (self.matching))
379 def _assert_list(self, values, appid):
381 if v not in self.matching:
382 raise MetaDataException("'%s' is not a valid %s in %s. "
383 % (v, self.name, appid) +
384 "Possible values: %s" % (", ".join(self.matching)))
386 def check(self, v, appid):
387 if type(v) is not str or not v:
389 if self.sep is not None:
390 values = v.split(self.sep)
393 if type(self.matching) is list:
394 self._assert_list(values, appid)
396 self._assert_regex(values, appid)
399 # Generic value types
401 FieldValidator("Integer",
402 r'^[1-9][0-9]*$', None,
406 FieldValidator("Hexadecimal",
407 r'^[0-9a-f]+$', None,
411 FieldValidator("HTTP link",
412 r'^http[s]?://', None,
413 ["Web Site", "Source Code", "Issue Tracker", "Changelog", "Donate"], []),
415 FieldValidator("Bitcoin address",
416 r'^[a-zA-Z0-9]{27,34}$', None,
420 FieldValidator("Litecoin address",
421 r'^L[a-zA-Z0-9]{33}$', None,
425 FieldValidator("bool",
426 r'([Yy]es|[Nn]o|[Tt]rue|[Ff]alse)', None,
428 ['submodules', 'oldsdkloc', 'forceversion', 'forcevercode',
431 FieldValidator("Repo Type",
432 ['git', 'git-svn', 'svn', 'hg', 'bzr', 'srclib'], None,
436 FieldValidator("Binaries",
437 r'^http[s]?://', None,
441 FieldValidator("Archive Policy",
442 r'^[0-9]+ versions$', None,
446 FieldValidator("Anti-Feature",
447 ["Ads", "Tracking", "NonFreeNet", "NonFreeDep", "NonFreeAdd", "UpstreamNonFree"], ',',
451 FieldValidator("Auto Update Mode",
452 r"^(Version .+|None)$", None,
453 ["Auto Update Mode"],
456 FieldValidator("Update Check Mode",
457 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$", None,
458 ["Update Check Mode"],
463 # Check an app's metadata information for integrity errors
464 def check_metadata(app):
467 v.check(app.get_field(f), app.id)
468 for build in app.builds:
470 v.check(build.get_flag(f), app.id)
473 # Formatter for descriptions. Create an instance, and call parseline() with
474 # each line of the description source from the metadata. At the end, call
475 # end() and then text_txt and text_html will contain the result.
476 class DescriptionFormatter:
483 def __init__(self, linkres):
486 self.state = self.stNONE
489 self.html = StringIO()
490 self.text = StringIO()
492 self.linkResolver = None
493 self.linkResolver = linkres
495 def endcur(self, notstates=None):
496 if notstates and self.state in notstates:
498 if self.state == self.stPARA:
500 elif self.state == self.stUL:
502 elif self.state == self.stOL:
506 self.state = self.stNONE
507 whole_para = ' '.join(self.para_lines)
508 self.addtext(whole_para)
509 self.text.write(textwrap.fill(whole_para, 80,
510 break_long_words=False,
511 break_on_hyphens=False))
512 self.text.write('\n\n')
513 self.html.write('</p>')
514 del self.para_lines[:]
517 self.html.write('</ul>')
518 self.text.write('\n')
519 self.state = self.stNONE
522 self.html.write('</ol>')
523 self.text.write('\n')
524 self.state = self.stNONE
526 def formatted(self, txt, html):
529 txt = cgi.escape(txt)
531 index = txt.find("''")
536 if txt.startswith("'''"):
542 self.bold = not self.bold
550 self.ital = not self.ital
553 def linkify(self, txt):
557 index = txt.find("[")
559 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
560 res_plain += self.formatted(txt[:index], False)
561 res_html += self.formatted(txt[:index], True)
563 if txt.startswith("[["):
564 index = txt.find("]]")
566 raise MetaDataException("Unterminated ]]")
568 if self.linkResolver:
569 url, urltext = self.linkResolver(url)
572 res_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
574 txt = txt[index + 2:]
576 index = txt.find("]")
578 raise MetaDataException("Unterminated ]")
580 index2 = url.find(' ')
584 urltxt = url[index2 + 1:]
587 raise MetaDataException("Url title is just the URL - use [url]")
588 res_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
591 res_plain += ' (' + url + ')'
592 txt = txt[index + 1:]
594 def addtext(self, txt):
595 p, h = self.linkify(txt)
598 def parseline(self, line):
601 elif line.startswith('* '):
602 self.endcur([self.stUL])
603 self.text.write(line)
604 self.text.write('\n')
605 if self.state != self.stUL:
606 self.html.write('<ul>')
607 self.state = self.stUL
608 self.html.write('<li>')
609 self.addtext(line[1:])
610 self.html.write('</li>')
611 elif line.startswith('# '):
612 self.endcur([self.stOL])
613 self.text.write(line)
614 self.text.write('\n')
615 if self.state != self.stOL:
616 self.html.write('<ol>')
617 self.state = self.stOL
618 self.html.write('<li>')
619 self.addtext(line[1:])
620 self.html.write('</li>')
622 self.para_lines.append(line)
623 self.endcur([self.stPARA])
624 if self.state == self.stNONE:
625 self.html.write('<p>')
626 self.state = self.stPARA
630 self.text_txt = self.text.getvalue().rstrip()
631 self.text_html = self.html.getvalue()
636 # Parse multiple lines of description as written in a metadata file, returning
637 # a single string in text format and wrapped to 80 columns.
638 def description_txt(s):
639 ps = DescriptionFormatter(None)
640 for line in s.splitlines():
646 # Parse multiple lines of description as written in a metadata file, returning
647 # a single string in wiki format. Used for the Maintainer Notes field as well,
648 # because it's the same format.
649 def description_wiki(s):
653 # Parse multiple lines of description as written in a metadata file, returning
654 # a single string in HTML format.
655 def description_html(s, linkres):
656 ps = DescriptionFormatter(linkres)
657 for line in s.splitlines():
663 def parse_srclib(metadatapath):
667 # Defaults for fields that come from metadata
668 thisinfo['Repo Type'] = ''
669 thisinfo['Repo'] = ''
670 thisinfo['Subdir'] = None
671 thisinfo['Prepare'] = None
673 if not os.path.exists(metadatapath):
676 metafile = open(metadatapath, "r")
679 for line in metafile:
681 line = line.rstrip('\r\n')
682 if not line or line.startswith("#"):
686 f, v = line.split(':', 1)
688 raise MetaDataException("Invalid metadata in %s:%d" % (line, n))
691 thisinfo[f] = v.split(',')
701 """Read all srclib metadata.
703 The information read will be accessible as metadata.srclibs, which is a
704 dictionary, keyed on srclib name, with the values each being a dictionary
705 in the same format as that returned by the parse_srclib function.
707 A MetaDataException is raised if there are any problems with the srclib
712 # They were already loaded
713 if srclibs is not None:
719 if not os.path.exists(srcdir):
722 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
723 srclibname = os.path.basename(metadatapath[:-4])
724 srclibs[srclibname] = parse_srclib(metadatapath)
727 # Read all metadata. Returns a list of 'app' objects (which are dictionaries as
728 # returned by the parse_txt_metadata function.
729 def read_metadata(xref=True):
731 # Always read the srclibs before the apps, since they can use a srlib as
732 # their source repository.
737 for basedir in ('metadata', 'tmp'):
738 if not os.path.exists(basedir):
741 # If there are multiple metadata files for a single appid, then the first
742 # file that is parsed wins over all the others, and the rest throw an
743 # exception. So the original .txt format is parsed first, at least until
744 # newer formats stabilize.
746 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
747 + glob.glob(os.path.join('metadata', '*.json'))
748 + glob.glob(os.path.join('metadata', '*.xml'))
749 + glob.glob(os.path.join('metadata', '*.yaml'))):
750 app = parse_metadata(metadatapath)
752 raise MetaDataException("Found multiple metadata files for " + app.id)
757 # Parse all descriptions at load time, just to ensure cross-referencing
758 # errors are caught early rather than when they hit the build server.
761 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
762 raise MetaDataException("Cannot resolve app id " + appid)
764 for appid, app in apps.iteritems():
766 description_html(app.Description, linkres)
767 except MetaDataException, e:
768 raise MetaDataException("Problem with description of " + appid +
773 # Port legacy ';' separators
774 list_sep = re.compile(r'[,;]')
777 def split_list_values(s):
779 for v in re.split(list_sep, s):
789 def get_default_app_info(metadatapath=None):
790 if metadatapath is None:
793 appid, _ = common.get_extension(os.path.basename(metadatapath))
796 app.metadatapath = metadatapath
797 if appid is not None:
803 def sorted_builds(builds):
804 return sorted(builds, key=lambda build: int(build.vercode))
807 esc_newlines = re.compile(r'\\( |\n)')
810 # This function uses __dict__ to be faster
811 def post_metadata_parse(app):
813 for k, v in app.__dict__.iteritems():
814 if type(v) in (float, int):
815 app.__dict__[k] = str(v)
817 for build in app.builds:
818 for k, v in build.__dict__.iteritems():
820 if type(v) in (float, int):
821 build.__dict__[k] = str(v)
825 if ftype == 'script':
826 build.__dict__[k] = re.sub(esc_newlines, '', v).lstrip().rstrip()
827 elif ftype == 'bool':
828 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
829 if isinstance(v, basestring) and v == 'true':
830 build.__dict__[k] = True
831 elif ftype == 'string':
832 if isinstance(v, bool) and v:
833 build.__dict__[k] = 'yes'
835 if not app.Description:
836 app.Description = 'No description available'
838 app.builds = sorted_builds(app.builds)
841 # Parse metadata for a single application.
843 # 'metadatapath' - the filename to read. The package id for the application comes
844 # from this filename. Pass None to get a blank entry.
846 # Returns a dictionary containing all the details of the application. There are
847 # two major kinds of information in the dictionary. Keys beginning with capital
848 # letters correspond directory to identically named keys in the metadata file.
849 # Keys beginning with lower case letters are generated in one way or another,
850 # and are not found verbatim in the metadata.
852 # Known keys not originating from the metadata are:
854 # 'builds' - a list of dictionaries containing build information
855 # for each defined build
856 # 'comments' - a list of comments from the metadata file. Each is
857 # a list of the form [field, comment] where field is
858 # the name of the field it preceded in the metadata
859 # file. Where field is None, the comment goes at the
860 # end of the file. Alternatively, 'build:version' is
861 # for a comment before a particular build version.
862 # 'descriptionlines' - original lines of description as formatted in the
867 def _decode_list(data):
868 '''convert items in a list from unicode to basestring'''
871 if isinstance(item, unicode):
872 item = item.encode('utf-8')
873 elif isinstance(item, list):
874 item = _decode_list(item)
875 elif isinstance(item, dict):
876 item = _decode_dict(item)
881 def _decode_dict(data):
882 '''convert items in a dict from unicode to basestring'''
884 for k, v in data.iteritems():
885 if isinstance(k, unicode):
886 k = k.encode('utf-8')
887 if isinstance(v, unicode):
888 v = v.encode('utf-8')
889 elif isinstance(v, list):
891 elif isinstance(v, dict):
897 def parse_metadata(metadatapath):
898 _, ext = common.get_extension(metadatapath)
899 accepted = common.config['accepted_formats']
900 if ext not in accepted:
901 raise MetaDataException('"%s" is not an accepted format, convert to: %s' % (
902 metadatapath, ', '.join(accepted)))
906 app = parse_txt_metadata(metadatapath)
908 app = parse_json_metadata(metadatapath)
910 app = parse_xml_metadata(metadatapath)
912 app = parse_yaml_metadata(metadatapath)
914 raise MetaDataException('Unknown metadata format: %s' % metadatapath)
916 post_metadata_parse(app)
920 def parse_json_metadata(metadatapath):
922 app = get_default_app_info(metadatapath)
924 # fdroid metadata is only strings and booleans, no floats or ints. And
925 # json returns unicode, and fdroidserver still uses plain python strings
926 # TODO create schema using https://pypi.python.org/pypi/jsonschema
928 with open(metadatapath, 'r') as f:
929 jsoninfo = json.load(f, object_hook=_decode_dict,
930 parse_int=lambda s: s,
931 parse_float=lambda s: s)
932 app.update_fields(jsoninfo)
933 for f in ['Description', 'Maintainer Notes']:
935 app.set_field(f, '\n'.join(v))
939 def parse_xml_metadata(metadatapath):
941 app = get_default_app_info(metadatapath)
943 tree = ElementTree.ElementTree(file=metadatapath)
944 root = tree.getroot()
946 if root.tag != 'resources':
947 raise MetaDataException('%s does not have root as <resources></resources>!' % metadatapath)
950 if child.tag != 'builds':
951 # builds does not have name="" attrib
952 name = child.attrib['name']
954 if child.tag == 'string':
955 app.set_field(name, child.text)
956 elif child.tag == 'string-array':
958 app.append_field(name, item.text)
959 elif child.tag == 'builds':
963 build.set_flag(key.tag, key.text)
964 app.builds.append(build)
966 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
967 if not isinstance(app.RequiresRoot, bool):
968 if app.RequiresRoot == 'true':
969 app.RequiresRoot = True
971 app.RequiresRoot = False
976 def parse_yaml_metadata(metadatapath):
978 app = get_default_app_info(metadatapath)
981 with open(metadatapath, 'r') as f:
982 yamlinfo = yaml.load(f, Loader=YamlLoader)
983 app.update_fields(yamlinfo)
987 build_line_sep = re.compile(r'(?<!\\),')
988 build_cont = re.compile(r'^[ \t]')
991 def parse_txt_metadata(metadatapath):
995 def add_buildflag(p, build):
997 raise MetaDataException("Empty build flag at {1}"
998 .format(buildlines[0], linedesc))
1001 raise MetaDataException("Invalid build flag at {0} in {1}"
1002 .format(buildlines[0], linedesc))
1008 pv = split_list_values(pv)
1009 build.set_flag(pk, pv)
1010 elif t == 'string' or t == 'script':
1011 build.set_flag(pk, pv)
1014 build.set_flag(pk, True)
1016 def parse_buildline(lines):
1018 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1020 raise MetaDataException("Invalid build format: " + v + " in " + metafile.name)
1022 build.origlines = lines
1023 build.version = parts[0]
1024 build.vercode = parts[1]
1025 if parts[2].startswith('!'):
1026 # For backwards compatibility, handle old-style disabling,
1027 # including attempting to extract the commit from the message
1028 build.disable = parts[2][1:]
1029 commit = 'unknown - see disabled'
1030 index = parts[2].rfind('at ')
1032 commit = parts[2][index + 3:]
1033 if commit.endswith(')'):
1034 commit = commit[:-1]
1035 build.commit = commit
1037 build.commit = parts[2]
1039 add_buildflag(p, build)
1043 def add_comments(key):
1046 app.comments[key] = list(curcomments)
1049 app = get_default_app_info(metadatapath)
1050 metafile = open(metadatapath, "r")
1054 multiline_lines = []
1060 for line in metafile:
1062 linedesc = "%s:%d" % (metafile.name, c)
1063 line = line.rstrip('\r\n')
1065 if build_cont.match(line):
1066 if line.endswith('\\'):
1067 buildlines.append(line[:-1].lstrip())
1069 buildlines.append(line.lstrip())
1070 bl = ''.join(buildlines)
1071 add_buildflag(bl, build)
1074 if not build.commit and not build.disable:
1075 raise MetaDataException("No commit specified for {0} in {1}"
1076 .format(build.version, linedesc))
1078 app.builds.append(build)
1079 add_comments('build:' + build.vercode)
1085 if line.startswith("#"):
1086 curcomments.append(line[1:].strip())
1089 f, v = line.split(':', 1)
1091 raise MetaDataException("Invalid metadata in " + linedesc)
1092 if f != f.strip() or v != v.strip():
1093 raise MetaDataException("Extra spacing found in " + linedesc)
1095 # Translate obsolete fields...
1096 if f == 'Market Version':
1097 f = 'Current Version'
1098 if f == 'Market Version Code':
1099 f = 'Current Version Code'
1101 ftype = metafieldtype(f)
1102 if ftype not in ['build', 'buildv2']:
1104 if ftype == 'multiline':
1107 raise MetaDataException("Unexpected text on same line as " + f + " in " + linedesc)
1108 elif ftype == 'string':
1110 elif ftype == 'list':
1111 app.set_field(f, split_list_values(v))
1112 elif ftype == 'build':
1113 if v.endswith("\\"):
1116 buildlines.append(v[:-1])
1118 build = parse_buildline([v])
1119 app.builds.append(build)
1120 add_comments('build:' + app.builds[-1].vercode)
1121 elif ftype == 'buildv2':
1125 raise MetaDataException('Build should have comma-separated version and vercode, not "{0}", in {1}'
1126 .format(v, linedesc))
1127 build.version = vv[0]
1128 build.vercode = vv[1]
1129 if build.vercode in vc_seen:
1130 raise MetaDataException('Duplicate build recipe found for vercode %s in %s' % (
1131 build.vercode, linedesc))
1132 vc_seen[build.vercode] = True
1135 elif ftype == 'obsolete':
1136 pass # Just throw it away!
1138 raise MetaDataException("Unrecognised field type for " + f + " in " + linedesc)
1139 elif mode == 1: # Multiline field
1142 app.set_field(f, '\n'.join(multiline_lines))
1143 del multiline_lines[:]
1145 multiline_lines.append(line)
1146 elif mode == 2: # Line continuation mode in Build Version
1147 if line.endswith("\\"):
1148 buildlines.append(line[:-1])
1150 buildlines.append(line)
1151 build = parse_buildline(buildlines)
1152 app.builds.append(build)
1153 add_comments('build:' + app.builds[-1].vercode)
1158 # Mode at end of file should always be 0
1160 raise MetaDataException(f + " not terminated in " + metafile.name)
1162 raise MetaDataException("Unterminated continuation in " + metafile.name)
1164 raise MetaDataException("Unterminated build in " + metafile.name)
1169 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1171 def w_comments(key):
1172 if key not in app.comments:
1174 for line in app.comments[key]:
1177 def w_field_always(f, v=None):
1179 v = app.get_field(f)
1183 def w_field_nonempty(f, v=None):
1185 v = app.get_field(f)
1190 w_field_nonempty('Disabled')
1191 if app.AntiFeatures:
1192 w_field_always('AntiFeatures')
1193 w_field_nonempty('Provides')
1194 w_field_always('Categories')
1195 w_field_always('License')
1196 w_field_always('Web Site')
1197 w_field_always('Source Code')
1198 w_field_always('Issue Tracker')
1199 w_field_nonempty('Changelog')
1200 w_field_nonempty('Donate')
1201 w_field_nonempty('FlattrID')
1202 w_field_nonempty('Bitcoin')
1203 w_field_nonempty('Litecoin')
1205 w_field_nonempty('Name')
1206 w_field_nonempty('Auto Name')
1207 w_field_always('Summary')
1208 w_field_always('Description', description_txt(app.Description))
1210 if app.RequiresRoot:
1211 w_field_always('Requires Root', 'yes')
1214 w_field_always('Repo Type')
1215 w_field_always('Repo')
1217 w_field_always('Binaries')
1220 for build in sorted_builds(app.builds):
1222 if build.version == "Ignore":
1225 w_comments('build:' + build.vercode)
1229 if app.MaintainerNotes:
1230 w_field_always('Maintainer Notes', app.MaintainerNotes)
1233 w_field_nonempty('Archive Policy')
1234 w_field_always('Auto Update Mode')
1235 w_field_always('Update Check Mode')
1236 w_field_nonempty('Update Check Ignore')
1237 w_field_nonempty('Vercode Operation')
1238 w_field_nonempty('Update Check Name')
1239 w_field_nonempty('Update Check Data')
1240 if app.CurrentVersion:
1241 w_field_always('Current Version')
1242 w_field_always('Current Version Code')
1243 if app.NoSourceSince:
1245 w_field_always('No Source Since')
1249 # Write a metadata file in txt format.
1251 # 'mf' - Writer interface (file, StringIO, ...)
1252 # 'app' - The app data
1253 def write_txt_metadata(mf, app):
1255 def w_comment(line):
1256 mf.write("# %s\n" % line)
1259 t = metafieldtype(f)
1262 elif t == 'multiline':
1263 v = '\n' + v + '\n.'
1264 mf.write("%s:%s\n" % (f, v))
1267 mf.write("Build:%s,%s\n" % (build.version, build.vercode))
1269 for f in build_flags_order:
1270 v = build.get_flag(f)
1281 out += '&& \\\n '.join([s.lstrip() for s in v.split('&& ')])
1283 out += ','.join(v) if type(v) == list else v
1288 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1291 def write_yaml_metadata(mf, app):
1293 def w_comment(line):
1294 mf.write("# %s\n" % line)
1299 if any(c in v for c in [': ', '%', '@', '*']):
1300 return "'" + v.replace("'", "''") + "'"
1303 def w_field(f, v, prefix='', t=None):
1305 t = metafieldtype(f)
1310 v += prefix + ' - ' + escape(e) + '\n'
1311 elif t == 'multiline':
1313 for l in v.splitlines():
1315 v += prefix + ' ' + l + '\n'
1321 cmds = [s + '&& \\' for s in v.split('&& ')]
1323 cmds[-1] = cmds[-1][:-len('&& \\')]
1324 w_field(f, cmds, prefix, 'multiline')
1327 v = ' ' + escape(v) + '\n'
1340 mf.write("builds:\n")
1343 w_field('versionName', build.version, ' - ', 'string')
1344 w_field('versionCode', build.vercode, ' ', 'strsng')
1345 for f in build_flags_order:
1346 v = build.get_flag(f)
1350 w_field(f, v, ' ', flagtype(f))
1352 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1355 def write_metadata(fmt, mf, app):
1357 return write_txt_metadata(mf, app)
1359 return write_yaml_metadata(mf, app)
1360 raise MetaDataException("Unknown metadata format given")