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
140 self._modified = set()
142 # Translates human-readable field names to attribute names, e.g.
143 # 'Auto Name' to 'AutoName'
145 def field_to_attr(cls, f):
146 return f.replace(' ', '')
148 # Translates attribute names to human-readable field names, e.g.
149 # 'AutoName' to 'Auto Name'
151 def attr_to_field(cls, k):
154 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
157 # Constructs an old-fashioned dict with the human-readable field
158 # names. Should only be used for tests.
159 def field_dict(self):
161 for k, v in self.__dict__.iteritems():
165 d['builds'].append(build.__dict__)
167 k = App.attr_to_field(k)
171 # Gets the value associated to a field name, e.g. 'Auto Name'
172 def get_field(self, f):
173 if f not in app_fields:
174 raise MetaDataException('Unrecognised app field: ' + f)
175 k = App.field_to_attr(f)
176 return getattr(self, k)
178 # Sets the value associated to a field name, e.g. 'Auto Name'
179 def set_field(self, f, v):
180 if f not in app_fields:
181 raise MetaDataException('Unrecognised app field: ' + f)
182 k = App.field_to_attr(f)
184 self._modified.add(k)
186 # Appends to the value associated to a field name, e.g. 'Auto Name'
187 def append_field(self, f, v):
188 if f not in app_fields:
189 raise MetaDataException('Unrecognised app field: ' + f)
190 k = App.field_to_attr(f)
191 if k not in self.__dict__:
192 self.__dict__[k] = [v]
194 self.__dict__[k].append(v)
196 # Like dict.update(), but using human-readable field names
197 def update_fields(self, d):
198 for f, v in d.iteritems():
202 build.update_flags(b)
203 self.builds.append(build)
218 'Description': TYPE_MULTILINE,
219 'Maintainer Notes': TYPE_MULTILINE,
220 'Categories': TYPE_LIST,
221 'AntiFeatures': TYPE_LIST,
222 'Build Version': TYPE_BUILD,
223 'Build': TYPE_BUILD_V2,
224 'Use Built': TYPE_OBSOLETE,
229 if name in fieldtypes:
230 return fieldtypes[name]
234 # In the order in which they are laid out on files
235 build_flags_order = [
268 build_flags = set(build_flags_order + ['version', 'vercode'])
277 self.submodules = False
285 self.oldsdkloc = False
287 self.forceversion = False
288 self.forcevercode = False
299 self.preassemble = []
300 self.gradleprops = []
301 self.antcommands = None
302 self.novcheck = False
304 self._modified = set()
306 def get_flag(self, f):
307 if f not in build_flags:
308 raise MetaDataException('Unrecognised build flag: ' + f)
309 return getattr(self, f)
311 def set_flag(self, f, v):
312 if f == 'versionName':
314 if f == 'versionCode':
316 if f not in build_flags:
317 raise MetaDataException('Unrecognised build flag: ' + f)
319 self._modified.add(f)
321 def append_flag(self, f, v):
322 if f not in build_flags:
323 raise MetaDataException('Unrecognised build flag: ' + f)
324 if f not in self.__dict__:
325 self.__dict__[f] = [v]
327 self.__dict__[f].append(v)
330 for f in ['maven', 'gradle', 'kivy']:
340 version = 'r10e' # falls back to latest
341 paths = common.config['ndk_paths']
342 if version not in paths:
344 return paths[version]
346 def update_flags(self, d):
347 for f, v in d.iteritems():
351 'extlibs': TYPE_LIST,
352 'srclibs': TYPE_LIST,
355 'buildjni': TYPE_LIST,
356 'preassemble': TYPE_LIST,
358 'scanignore': TYPE_LIST,
359 'scandelete': TYPE_LIST,
361 'antcommands': TYPE_LIST,
362 'gradleprops': TYPE_LIST,
364 'prebuild': TYPE_SCRIPT,
365 'build': TYPE_SCRIPT,
366 'submodules': TYPE_BOOL,
367 'oldsdkloc': TYPE_BOOL,
368 'forceversion': TYPE_BOOL,
369 'forcevercode': TYPE_BOOL,
370 'novcheck': TYPE_BOOL,
375 if name in flagtypes:
376 return flagtypes[name]
380 # Designates a metadata field type and checks that it matches
382 # 'name' - The long name of the field type
383 # 'matching' - List of possible values or regex expression
384 # 'sep' - Separator to use if value may be a list
385 # 'fields' - Metadata fields (Field:Value) of this type
386 # 'flags' - Build flags (flag=value) of this type
388 class FieldValidator():
390 def __init__(self, name, matching, sep, fields, flags):
392 self.matching = matching
393 if type(matching) is str:
394 self.compiled = re.compile(matching)
396 self.matching = set(self.matching)
401 def _assert_regex(self, values, appid):
403 if not self.compiled.match(v):
404 raise MetaDataException("'%s' is not a valid %s in %s. Regex pattern: %s"
405 % (v, self.name, appid, self.matching))
407 def _assert_list(self, values, appid):
409 if v not in self.matching:
410 raise MetaDataException("'%s' is not a valid %s in %s. Possible values: %s"
411 % (v, self.name, appid, ', '.join(self.matching)))
413 def check(self, v, appid):
420 if type(self.matching) is set:
421 self._assert_list(values, appid)
423 self._assert_regex(values, appid)
426 # Generic value types
428 FieldValidator("Integer",
429 r'^[1-9][0-9]*$', None,
433 FieldValidator("Hexadecimal",
434 r'^[0-9a-f]+$', None,
438 FieldValidator("HTTP link",
439 r'^http[s]?://', None,
440 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"], []),
442 FieldValidator("Bitcoin address",
443 r'^[a-zA-Z0-9]{27,34}$', None,
447 FieldValidator("Litecoin address",
448 r'^L[a-zA-Z0-9]{33}$', None,
452 FieldValidator("Repo Type",
453 ['git', 'git-svn', 'svn', 'hg', 'bzr', 'srclib'], None,
457 FieldValidator("Binaries",
458 r'^http[s]?://', None,
462 FieldValidator("Archive Policy",
463 r'^[0-9]+ versions$', None,
467 FieldValidator("Anti-Feature",
468 ["Ads", "Tracking", "NonFreeNet", "NonFreeDep", "NonFreeAdd", "UpstreamNonFree"], ',',
472 FieldValidator("Auto Update Mode",
473 r"^(Version .+|None)$", None,
477 FieldValidator("Update Check Mode",
478 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$", None,
484 # Check an app's metadata information for integrity errors
485 def check_metadata(app):
488 if k not in app._modified:
490 v.check(app.__dict__[k], app.id)
491 for build in app.builds:
493 if k not in build._modified:
495 v.check(build.__dict__[k], app.id)
498 # Formatter for descriptions. Create an instance, and call parseline() with
499 # each line of the description source from the metadata. At the end, call
500 # end() and then text_txt and text_html will contain the result.
501 class DescriptionFormatter:
508 def __init__(self, linkres):
511 self.state = self.stNONE
512 self.laststate = self.stNONE
515 self.html = StringIO()
516 self.text = StringIO()
518 self.linkResolver = None
519 self.linkResolver = linkres
521 def endcur(self, notstates=None):
522 if notstates and self.state in notstates:
524 if self.state == self.stPARA:
526 elif self.state == self.stUL:
528 elif self.state == self.stOL:
532 self.laststate = self.state
533 self.state = self.stNONE
534 whole_para = ' '.join(self.para_lines)
535 self.addtext(whole_para)
536 self.text.write(textwrap.fill(whole_para, 80,
537 break_long_words=False,
538 break_on_hyphens=False))
539 self.html.write('</p>')
540 del self.para_lines[:]
543 self.html.write('</ul>')
544 self.laststate = self.state
545 self.state = self.stNONE
548 self.html.write('</ol>')
549 self.laststate = self.state
550 self.state = self.stNONE
552 def formatted(self, txt, html):
555 txt = cgi.escape(txt)
557 index = txt.find("''")
562 if txt.startswith("'''"):
568 self.bold = not self.bold
576 self.ital = not self.ital
579 def linkify(self, txt):
583 index = txt.find("[")
585 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
586 res_plain += self.formatted(txt[:index], False)
587 res_html += self.formatted(txt[:index], True)
589 if txt.startswith("[["):
590 index = txt.find("]]")
592 raise MetaDataException("Unterminated ]]")
594 if self.linkResolver:
595 url, urltext = self.linkResolver(url)
598 res_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
600 txt = txt[index + 2:]
602 index = txt.find("]")
604 raise MetaDataException("Unterminated ]")
606 index2 = url.find(' ')
610 urltxt = url[index2 + 1:]
613 raise MetaDataException("Url title is just the URL - use [url]")
614 res_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
617 res_plain += ' (' + url + ')'
618 txt = txt[index + 1:]
620 def addtext(self, txt):
621 p, h = self.linkify(txt)
624 def parseline(self, line):
627 elif line.startswith('* '):
628 self.endcur([self.stUL])
629 if self.state != self.stUL:
630 self.html.write('<ul>')
631 self.state = self.stUL
632 if self.laststate != self.stNONE:
633 self.text.write('\n\n')
635 self.text.write('\n')
636 self.text.write(line)
637 self.html.write('<li>')
638 self.addtext(line[1:])
639 self.html.write('</li>')
640 elif line.startswith('# '):
641 self.endcur([self.stOL])
642 if self.state != self.stOL:
643 self.html.write('<ol>')
644 self.state = self.stOL
645 if self.laststate != self.stNONE:
646 self.text.write('\n\n')
648 self.text.write('\n')
649 self.text.write(line)
650 self.html.write('<li>')
651 self.addtext(line[1:])
652 self.html.write('</li>')
654 self.para_lines.append(line)
655 self.endcur([self.stPARA])
656 if self.state == self.stNONE:
657 self.state = self.stPARA
658 if self.laststate != self.stNONE:
659 self.text.write('\n\n')
660 self.html.write('<p>')
664 self.text_txt = self.text.getvalue()
665 self.text_html = self.html.getvalue()
670 # Parse multiple lines of description as written in a metadata file, returning
671 # a single string in text format and wrapped to 80 columns.
672 def description_txt(s):
673 ps = DescriptionFormatter(None)
674 for line in s.splitlines():
680 # Parse multiple lines of description as written in a metadata file, returning
681 # a single string in wiki format. Used for the Maintainer Notes field as well,
682 # because it's the same format.
683 def description_wiki(s):
687 # Parse multiple lines of description as written in a metadata file, returning
688 # a single string in HTML format.
689 def description_html(s, linkres):
690 ps = DescriptionFormatter(linkres)
691 for line in s.splitlines():
697 def parse_srclib(metadatapath):
701 # Defaults for fields that come from metadata
702 thisinfo['Repo Type'] = ''
703 thisinfo['Repo'] = ''
704 thisinfo['Subdir'] = None
705 thisinfo['Prepare'] = None
707 if not os.path.exists(metadatapath):
710 metafile = open(metadatapath, "r")
713 for line in metafile:
715 line = line.rstrip('\r\n')
716 if not line or line.startswith("#"):
720 f, v = line.split(':', 1)
722 raise MetaDataException("Invalid metadata in %s:%d" % (line, n))
725 thisinfo[f] = v.split(',')
735 """Read all srclib metadata.
737 The information read will be accessible as metadata.srclibs, which is a
738 dictionary, keyed on srclib name, with the values each being a dictionary
739 in the same format as that returned by the parse_srclib function.
741 A MetaDataException is raised if there are any problems with the srclib
746 # They were already loaded
747 if srclibs is not None:
753 if not os.path.exists(srcdir):
756 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
757 srclibname = os.path.basename(metadatapath[:-4])
758 srclibs[srclibname] = parse_srclib(metadatapath)
761 # Read all metadata. Returns a list of 'app' objects (which are dictionaries as
762 # returned by the parse_txt_metadata function.
763 def read_metadata(xref=True):
765 # Always read the srclibs before the apps, since they can use a srlib as
766 # their source repository.
771 for basedir in ('metadata', 'tmp'):
772 if not os.path.exists(basedir):
775 # If there are multiple metadata files for a single appid, then the first
776 # file that is parsed wins over all the others, and the rest throw an
777 # exception. So the original .txt format is parsed first, at least until
778 # newer formats stabilize.
780 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
781 + glob.glob(os.path.join('metadata', '*.json'))
782 + glob.glob(os.path.join('metadata', '*.xml'))
783 + glob.glob(os.path.join('metadata', '*.yaml'))):
784 app = parse_metadata(metadatapath)
786 raise MetaDataException("Found multiple metadata files for " + app.id)
791 # Parse all descriptions at load time, just to ensure cross-referencing
792 # errors are caught early rather than when they hit the build server.
795 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
796 raise MetaDataException("Cannot resolve app id " + appid)
798 for appid, app in apps.iteritems():
800 description_html(app.Description, linkres)
801 except MetaDataException, e:
802 raise MetaDataException("Problem with description of " + appid +
807 # Port legacy ';' separators
808 list_sep = re.compile(r'[,;]')
811 def split_list_values(s):
813 for v in re.split(list_sep, s):
823 def get_default_app_info(metadatapath=None):
824 if metadatapath is None:
827 appid, _ = common.get_extension(os.path.basename(metadatapath))
830 app.metadatapath = metadatapath
831 if appid is not None:
837 def sorted_builds(builds):
838 return sorted(builds, key=lambda build: int(build.vercode))
841 esc_newlines = re.compile(r'\\( |\n)')
844 # This function uses __dict__ to be faster
845 def post_metadata_parse(app):
847 for k, v in app.__dict__.iteritems():
848 if k not in app._modified:
850 if type(v) in (float, int):
851 app.__dict__[k] = str(v)
853 for build in app.builds:
854 for k, v in build.__dict__.iteritems():
856 if k not in build._modified:
858 if type(v) in (float, int):
859 build.__dict__[k] = str(v)
863 if ftype == TYPE_SCRIPT:
864 build.__dict__[k] = re.sub(esc_newlines, '', v).lstrip().rstrip()
865 elif ftype == TYPE_BOOL:
866 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
867 if isinstance(v, basestring):
868 build.__dict__[k] = _decode_bool(v)
869 elif ftype == TYPE_STRING:
870 if isinstance(v, bool) and v:
871 build.__dict__[k] = 'yes'
873 if not app.Description:
874 app.Description = 'No description available'
876 app.builds = sorted_builds(app.builds)
879 # Parse metadata for a single application.
881 # 'metadatapath' - the filename to read. The package id for the application comes
882 # from this filename. Pass None to get a blank entry.
884 # Returns a dictionary containing all the details of the application. There are
885 # two major kinds of information in the dictionary. Keys beginning with capital
886 # letters correspond directory to identically named keys in the metadata file.
887 # Keys beginning with lower case letters are generated in one way or another,
888 # and are not found verbatim in the metadata.
890 # Known keys not originating from the metadata are:
892 # 'builds' - a list of dictionaries containing build information
893 # for each defined build
894 # 'comments' - a list of comments from the metadata file. Each is
895 # a list of the form [field, comment] where field is
896 # the name of the field it preceded in the metadata
897 # file. Where field is None, the comment goes at the
898 # end of the file. Alternatively, 'build:version' is
899 # for a comment before a particular build version.
900 # 'descriptionlines' - original lines of description as formatted in the
905 def _decode_list(data):
906 '''convert items in a list from unicode to basestring'''
909 if isinstance(item, unicode):
910 item = item.encode('utf-8')
911 elif isinstance(item, list):
912 item = _decode_list(item)
913 elif isinstance(item, dict):
914 item = _decode_dict(item)
919 def _decode_dict(data):
920 '''convert items in a dict from unicode to basestring'''
922 for k, v in data.iteritems():
923 if isinstance(k, unicode):
924 k = k.encode('utf-8')
925 if isinstance(v, unicode):
926 v = v.encode('utf-8')
927 elif isinstance(v, list):
929 elif isinstance(v, dict):
935 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
936 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
940 if bool_true.match(s):
942 if bool_false.match(s):
944 raise MetaDataException("Invalid bool '%s'" % s)
947 def parse_metadata(metadatapath):
948 _, ext = common.get_extension(metadatapath)
949 accepted = common.config['accepted_formats']
950 if ext not in accepted:
951 raise MetaDataException('"%s" is not an accepted format, convert to: %s' % (
952 metadatapath, ', '.join(accepted)))
956 app = parse_txt_metadata(metadatapath)
958 app = parse_json_metadata(metadatapath)
960 app = parse_xml_metadata(metadatapath)
962 app = parse_yaml_metadata(metadatapath)
964 raise MetaDataException('Unknown metadata format: %s' % metadatapath)
966 post_metadata_parse(app)
970 def parse_json_metadata(metadatapath):
972 app = get_default_app_info(metadatapath)
974 # fdroid metadata is only strings and booleans, no floats or ints. And
975 # json returns unicode, and fdroidserver still uses plain python strings
976 # TODO create schema using https://pypi.python.org/pypi/jsonschema
978 with open(metadatapath, 'r') as f:
979 jsoninfo = json.load(f, object_hook=_decode_dict,
980 parse_int=lambda s: s,
981 parse_float=lambda s: s)
982 app.update_fields(jsoninfo)
983 for f in ['Description', 'Maintainer Notes']:
985 app.set_field(f, '\n'.join(v))
989 def parse_xml_metadata(metadatapath):
991 app = get_default_app_info(metadatapath)
993 tree = ElementTree.ElementTree(file=metadatapath)
994 root = tree.getroot()
996 if root.tag != 'resources':
997 raise MetaDataException('%s does not have root as <resources></resources>!' % metadatapath)
1000 if child.tag != 'builds':
1001 # builds does not have name="" attrib
1002 name = child.attrib['name']
1004 if child.tag == 'string':
1005 app.set_field(name, child.text)
1006 elif child.tag == 'string-array':
1008 app.append_field(name, item.text)
1009 elif child.tag == 'builds':
1013 build.set_flag(key.tag, key.text)
1014 app.builds.append(build)
1016 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
1017 if not isinstance(app.RequiresRoot, bool):
1018 app.RequiresRoot = app.RequiresRoot == 'true'
1023 def parse_yaml_metadata(metadatapath):
1025 app = get_default_app_info(metadatapath)
1028 with open(metadatapath, 'r') as f:
1029 yamlinfo = yaml.load(f, Loader=YamlLoader)
1030 app.update_fields(yamlinfo)
1034 build_line_sep = re.compile(r'(?<!\\),')
1035 build_cont = re.compile(r'^[ \t]')
1038 def parse_txt_metadata(metadatapath):
1042 def add_buildflag(p, build):
1044 raise MetaDataException("Empty build flag at {1}"
1045 .format(buildlines[0], linedesc))
1046 bv = p.split('=', 1)
1048 raise MetaDataException("Invalid build flag at {0} in {1}"
1049 .format(buildlines[0], linedesc))
1055 pv = split_list_values(pv)
1056 build.set_flag(pk, pv)
1057 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1058 build.set_flag(pk, pv)
1059 elif t == TYPE_BOOL:
1060 build.set_flag(pk, _decode_bool(pv))
1062 def parse_buildline(lines):
1064 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1066 raise MetaDataException("Invalid build format: " + v + " in " + metafile.name)
1068 build.origlines = lines
1069 build.version = parts[0]
1070 build.vercode = parts[1]
1071 if parts[2].startswith('!'):
1072 # For backwards compatibility, handle old-style disabling,
1073 # including attempting to extract the commit from the message
1074 build.disable = parts[2][1:]
1075 commit = 'unknown - see disabled'
1076 index = parts[2].rfind('at ')
1078 commit = parts[2][index + 3:]
1079 if commit.endswith(')'):
1080 commit = commit[:-1]
1081 build.commit = commit
1083 build.commit = parts[2]
1085 add_buildflag(p, build)
1089 def add_comments(key):
1092 app.comments[key] = list(curcomments)
1095 app = get_default_app_info(metadatapath)
1096 metafile = open(metadatapath, "r")
1100 multiline_lines = []
1106 for line in metafile:
1108 linedesc = "%s:%d" % (metafile.name, c)
1109 line = line.rstrip('\r\n')
1111 if build_cont.match(line):
1112 if line.endswith('\\'):
1113 buildlines.append(line[:-1].lstrip())
1115 buildlines.append(line.lstrip())
1116 bl = ''.join(buildlines)
1117 add_buildflag(bl, build)
1120 if not build.commit and not build.disable:
1121 raise MetaDataException("No commit specified for {0} in {1}"
1122 .format(build.version, linedesc))
1124 app.builds.append(build)
1125 add_comments('build:' + build.vercode)
1131 if line.startswith("#"):
1132 curcomments.append(line[1:].strip())
1135 f, v = line.split(':', 1)
1137 raise MetaDataException("Invalid metadata in " + linedesc)
1139 # Translate obsolete fields...
1140 if f == 'Market Version':
1141 f = 'Current Version'
1142 if f == 'Market Version Code':
1143 f = 'Current Version Code'
1145 ftype = fieldtype(f)
1146 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1148 if ftype == TYPE_MULTILINE:
1151 raise MetaDataException("Unexpected text on same line as " + f + " in " + linedesc)
1152 elif ftype == TYPE_STRING:
1154 elif ftype == TYPE_LIST:
1155 app.set_field(f, split_list_values(v))
1156 elif ftype == TYPE_BUILD:
1157 if v.endswith("\\"):
1160 buildlines.append(v[:-1])
1162 build = parse_buildline([v])
1163 app.builds.append(build)
1164 add_comments('build:' + app.builds[-1].vercode)
1165 elif ftype == TYPE_BUILD_V2:
1168 raise MetaDataException('Build should have comma-separated version and vercode, not "{0}", in {1}'
1169 .format(v, linedesc))
1171 build.version = vv[0]
1172 build.vercode = vv[1]
1173 if build.vercode in vc_seen:
1174 raise MetaDataException('Duplicate build recipe found for vercode %s in %s' % (
1175 build.vercode, linedesc))
1176 vc_seen.add(build.vercode)
1179 elif ftype == TYPE_OBSOLETE:
1180 pass # Just throw it away!
1182 raise MetaDataException("Unrecognised field '" + f + "' in " + linedesc)
1183 elif mode == 1: # Multiline field
1186 app.set_field(f, '\n'.join(multiline_lines))
1187 del multiline_lines[:]
1189 multiline_lines.append(line)
1190 elif mode == 2: # Line continuation mode in Build Version
1191 if line.endswith("\\"):
1192 buildlines.append(line[:-1])
1194 buildlines.append(line)
1195 build = parse_buildline(buildlines)
1196 app.builds.append(build)
1197 add_comments('build:' + app.builds[-1].vercode)
1202 # Mode at end of file should always be 0
1204 raise MetaDataException(f + " not terminated in " + metafile.name)
1206 raise MetaDataException("Unterminated continuation in " + metafile.name)
1208 raise MetaDataException("Unterminated build in " + metafile.name)
1213 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1215 def w_comments(key):
1216 if key not in app.comments:
1218 for line in app.comments[key]:
1221 def w_field_always(f, v=None):
1223 v = app.get_field(f)
1227 def w_field_nonempty(f, v=None):
1229 v = app.get_field(f)
1234 w_field_nonempty('Disabled')
1235 if app.AntiFeatures:
1236 w_field_always('AntiFeatures')
1237 w_field_nonempty('Provides')
1238 w_field_always('Categories')
1239 w_field_always('License')
1240 w_field_always('Web Site')
1241 w_field_always('Source Code')
1242 w_field_always('Issue Tracker')
1243 w_field_nonempty('Changelog')
1244 w_field_nonempty('Donate')
1245 w_field_nonempty('FlattrID')
1246 w_field_nonempty('Bitcoin')
1247 w_field_nonempty('Litecoin')
1249 w_field_nonempty('Name')
1250 w_field_nonempty('Auto Name')
1251 w_field_always('Summary')
1252 w_field_always('Description', description_txt(app.Description))
1254 if app.RequiresRoot:
1255 w_field_always('Requires Root', 'yes')
1258 w_field_always('Repo Type')
1259 w_field_always('Repo')
1261 w_field_always('Binaries')
1264 for build in sorted_builds(app.builds):
1266 if build.version == "Ignore":
1269 w_comments('build:' + build.vercode)
1273 if app.MaintainerNotes:
1274 w_field_always('Maintainer Notes', app.MaintainerNotes)
1277 w_field_nonempty('Archive Policy')
1278 w_field_always('Auto Update Mode')
1279 w_field_always('Update Check Mode')
1280 w_field_nonempty('Update Check Ignore')
1281 w_field_nonempty('Vercode Operation')
1282 w_field_nonempty('Update Check Name')
1283 w_field_nonempty('Update Check Data')
1284 if app.CurrentVersion:
1285 w_field_always('Current Version')
1286 w_field_always('Current Version Code')
1287 if app.NoSourceSince:
1289 w_field_always('No Source Since')
1293 # Write a metadata file in txt format.
1295 # 'mf' - Writer interface (file, StringIO, ...)
1296 # 'app' - The app data
1297 def write_txt_metadata(mf, app):
1299 def w_comment(line):
1300 mf.write("# %s\n" % line)
1306 elif t == TYPE_MULTILINE:
1307 v = '\n' + v + '\n.'
1308 mf.write("%s:%s\n" % (f, v))
1311 mf.write("Build:%s,%s\n" % (build.version, build.vercode))
1313 for f in build_flags_order:
1314 v = build.get_flag(f)
1319 mf.write(' %s=' % f)
1320 if t == TYPE_STRING:
1322 elif t == TYPE_BOOL:
1324 elif t == TYPE_SCRIPT:
1326 for s in v.split(' && '):
1330 mf.write(' && \\\n ')
1332 elif t == TYPE_LIST:
1333 mf.write(','.join(v))
1337 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1340 def write_yaml_metadata(mf, app):
1342 def w_comment(line):
1343 mf.write("# %s\n" % line)
1348 if any(c in v for c in [': ', '%', '@', '*']):
1349 return "'" + v.replace("'", "''") + "'"
1352 def w_field(f, v, prefix='', t=None):
1359 v += prefix + ' - ' + escape(e) + '\n'
1360 elif t == TYPE_MULTILINE:
1362 for l in v.splitlines():
1364 v += prefix + ' ' + l + '\n'
1367 elif t == TYPE_BOOL:
1369 elif t == TYPE_SCRIPT:
1370 cmds = [s + '&& \\' for s in v.split('&& ')]
1372 cmds[-1] = cmds[-1][:-len('&& \\')]
1373 w_field(f, cmds, prefix, 'multiline')
1376 v = ' ' + escape(v) + '\n'
1389 mf.write("builds:\n")
1392 w_field('versionName', build.version, ' - ', TYPE_STRING)
1393 w_field('versionCode', build.vercode, ' ', TYPE_STRING)
1394 for f in build_flags_order:
1395 v = build.get_flag(f)
1399 w_field(f, v, ' ', flagtype(f))
1401 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1404 def write_metadata(fmt, mf, app):
1406 return write_txt_metadata(mf, app)
1408 return write_yaml_metadata(mf, app)
1409 raise MetaDataException("Unknown metadata format given")