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
87 'Update Check Ignore',
92 'Current Version Code',
95 'comments', # For formats that don't do inline comments
96 'builds', # For formats that do builds as a list
104 self.AntiFeatures = []
106 self.Categories = ['None']
107 self.License = 'Unknown'
108 self.AuthorName = None
109 self.AuthorEmail = None
112 self.IssueTracker = ''
121 self.Description = ''
122 self.RequiresRoot = False
126 self.MaintainerNotes = ''
127 self.ArchivePolicy = None
128 self.AutoUpdateMode = 'None'
129 self.UpdateCheckMode = 'None'
130 self.UpdateCheckIgnore = None
131 self.VercodeOperation = None
132 self.UpdateCheckName = None
133 self.UpdateCheckData = None
134 self.CurrentVersion = ''
135 self.CurrentVersionCode = '0'
136 self.NoSourceSince = ''
139 self.metadatapath = None
143 self.lastupdated = None
144 self._modified = set()
146 # Translates human-readable field names to attribute names, e.g.
147 # 'Auto Name' to 'AutoName'
149 def field_to_attr(cls, f):
150 return f.replace(' ', '')
152 # Translates attribute names to human-readable field names, e.g.
153 # 'AutoName' to 'Auto Name'
155 def attr_to_field(cls, k):
158 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
161 # Constructs an old-fashioned dict with the human-readable field
162 # names. Should only be used for tests.
163 def field_dict(self):
165 for k, v in self.__dict__.iteritems():
169 b = {k: v for k, v in build.__dict__.iteritems() if not k.startswith('_')}
170 d['builds'].append(b)
171 elif not k.startswith('_'):
172 f = App.attr_to_field(k)
176 # Gets the value associated to a field name, e.g. 'Auto Name'
177 def get_field(self, f):
178 if f not in app_fields:
179 raise MetaDataException('Unrecognised app field: ' + f)
180 k = App.field_to_attr(f)
181 return getattr(self, k)
183 # Sets the value associated to a field name, e.g. 'Auto Name'
184 def set_field(self, f, v):
185 if f not in app_fields:
186 raise MetaDataException('Unrecognised app field: ' + f)
187 k = App.field_to_attr(f)
189 self._modified.add(k)
191 # Appends to the value associated to a field name, e.g. 'Auto Name'
192 def append_field(self, f, v):
193 if f not in app_fields:
194 raise MetaDataException('Unrecognised app field: ' + f)
195 k = App.field_to_attr(f)
196 if k not in self.__dict__:
197 self.__dict__[k] = [v]
199 self.__dict__[k].append(v)
201 # Like dict.update(), but using human-readable field names
202 def update_fields(self, d):
203 for f, v in d.iteritems():
207 build.update_flags(b)
208 self.builds.append(build)
223 'Description': TYPE_MULTILINE,
224 'Maintainer Notes': TYPE_MULTILINE,
225 'Categories': TYPE_LIST,
226 'AntiFeatures': TYPE_LIST,
227 'Build Version': TYPE_BUILD,
228 'Build': TYPE_BUILD_V2,
229 'Use Built': TYPE_OBSOLETE,
234 if name in fieldtypes:
235 return fieldtypes[name]
239 # In the order in which they are laid out on files
240 build_flags_order = [
273 build_flags = set(build_flags_order + ['version', 'vercode'])
282 self.submodules = False
290 self.oldsdkloc = False
292 self.forceversion = False
293 self.forcevercode = False
304 self.preassemble = []
305 self.gradleprops = []
306 self.antcommands = []
307 self.novcheck = False
309 self._modified = set()
311 def get_flag(self, f):
312 if f not in build_flags:
313 raise MetaDataException('Unrecognised build flag: ' + f)
314 return getattr(self, f)
316 def set_flag(self, f, v):
317 if f == 'versionName':
319 if f == 'versionCode':
321 if f not in build_flags:
322 raise MetaDataException('Unrecognised build flag: ' + f)
324 self._modified.add(f)
326 def append_flag(self, f, v):
327 if f not in build_flags:
328 raise MetaDataException('Unrecognised build flag: ' + f)
329 if f not in self.__dict__:
330 self.__dict__[f] = [v]
332 self.__dict__[f].append(v)
335 for f in ['maven', 'gradle', 'kivy']:
345 version = 'r10e' # falls back to latest
346 paths = common.config['ndk_paths']
347 if version not in paths:
349 return paths[version]
351 def update_flags(self, d):
352 for f, v in d.iteritems():
356 'extlibs': TYPE_LIST,
357 'srclibs': TYPE_LIST,
360 'buildjni': TYPE_LIST,
361 'preassemble': TYPE_LIST,
363 'scanignore': TYPE_LIST,
364 'scandelete': TYPE_LIST,
366 'antcommands': TYPE_LIST,
367 'gradleprops': TYPE_LIST,
369 'prebuild': TYPE_SCRIPT,
370 'build': TYPE_SCRIPT,
371 'submodules': TYPE_BOOL,
372 'oldsdkloc': TYPE_BOOL,
373 'forceversion': TYPE_BOOL,
374 'forcevercode': TYPE_BOOL,
375 'novcheck': TYPE_BOOL,
380 if name in flagtypes:
381 return flagtypes[name]
385 # Designates a metadata field type and checks that it matches
387 # 'name' - The long name of the field type
388 # 'matching' - List of possible values or regex expression
389 # 'sep' - Separator to use if value may be a list
390 # 'fields' - Metadata fields (Field:Value) of this type
391 # 'flags' - Build flags (flag=value) of this type
393 class FieldValidator():
395 def __init__(self, name, matching, fields, flags):
397 self.matching = matching
398 self.compiled = re.compile(matching)
402 def check(self, v, appid):
410 if not self.compiled.match(v):
411 raise MetaDataException("'%s' is not a valid %s in %s. Regex pattern: %s"
412 % (v, self.name, appid, self.matching))
414 # Generic value types
416 FieldValidator("Integer",
421 FieldValidator("Hexadecimal",
426 FieldValidator("HTTP link",
428 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"], []),
430 FieldValidator("Email",
431 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
432 ["AuthorEmail"], []),
434 FieldValidator("Bitcoin address",
435 r'^[a-zA-Z0-9]{27,34}$',
439 FieldValidator("Litecoin address",
440 r'^L[a-zA-Z0-9]{33}$',
444 FieldValidator("Repo Type",
445 r'^(git|git-svn|svn|hg|bzr|srclib)$',
449 FieldValidator("Binaries",
454 FieldValidator("Archive Policy",
455 r'^[0-9]+ versions$',
459 FieldValidator("Anti-Feature",
460 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets)$',
464 FieldValidator("Auto Update Mode",
465 r"^(Version .+|None)$",
469 FieldValidator("Update Check Mode",
470 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
476 # Check an app's metadata information for integrity errors
477 def check_metadata(app):
480 if k not in app._modified:
482 v.check(app.__dict__[k], app.id)
483 for build in app.builds:
485 if k not in build._modified:
487 v.check(build.__dict__[k], app.id)
490 # Formatter for descriptions. Create an instance, and call parseline() with
491 # each line of the description source from the metadata. At the end, call
492 # end() and then text_txt and text_html will contain the result.
493 class DescriptionFormatter:
500 def __init__(self, linkres):
503 self.state = self.stNONE
504 self.laststate = self.stNONE
507 self.html = StringIO()
508 self.text = StringIO()
510 self.linkResolver = None
511 self.linkResolver = linkres
513 def endcur(self, notstates=None):
514 if notstates and self.state in notstates:
516 if self.state == self.stPARA:
518 elif self.state == self.stUL:
520 elif self.state == self.stOL:
524 self.laststate = self.state
525 self.state = self.stNONE
526 whole_para = ' '.join(self.para_lines)
527 self.addtext(whole_para)
528 wrapped = textwrap.fill(whole_para.decode('utf-8'), 80,
529 break_long_words=False,
530 break_on_hyphens=False)
531 self.text.write(wrapped.encode('utf-8'))
532 self.html.write('</p>')
533 del self.para_lines[:]
536 self.html.write('</ul>')
537 self.laststate = self.state
538 self.state = self.stNONE
541 self.html.write('</ol>')
542 self.laststate = self.state
543 self.state = self.stNONE
545 def formatted(self, txt, html):
548 txt = cgi.escape(txt)
550 index = txt.find("''")
555 if txt.startswith("'''"):
561 self.bold = not self.bold
569 self.ital = not self.ital
572 def linkify(self, txt):
576 index = txt.find("[")
578 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
579 res_plain += self.formatted(txt[:index], False)
580 res_html += self.formatted(txt[:index], True)
582 if txt.startswith("[["):
583 index = txt.find("]]")
585 raise MetaDataException("Unterminated ]]")
587 if self.linkResolver:
588 url, urltext = self.linkResolver(url)
591 res_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
593 txt = txt[index + 2:]
595 index = txt.find("]")
597 raise MetaDataException("Unterminated ]")
599 index2 = url.find(' ')
603 urltxt = url[index2 + 1:]
606 raise MetaDataException("Url title is just the URL - use [url]")
607 res_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
610 res_plain += ' (' + url + ')'
611 txt = txt[index + 1:]
613 def addtext(self, txt):
614 p, h = self.linkify(txt)
617 def parseline(self, line):
620 elif line.startswith('* '):
621 self.endcur([self.stUL])
622 if self.state != self.stUL:
623 self.html.write('<ul>')
624 self.state = self.stUL
625 if self.laststate != self.stNONE:
626 self.text.write('\n\n')
628 self.text.write('\n')
629 self.text.write(line)
630 self.html.write('<li>')
631 self.addtext(line[1:])
632 self.html.write('</li>')
633 elif line.startswith('# '):
634 self.endcur([self.stOL])
635 if self.state != self.stOL:
636 self.html.write('<ol>')
637 self.state = self.stOL
638 if self.laststate != self.stNONE:
639 self.text.write('\n\n')
641 self.text.write('\n')
642 self.text.write(line)
643 self.html.write('<li>')
644 self.addtext(line[1:])
645 self.html.write('</li>')
647 self.para_lines.append(line)
648 self.endcur([self.stPARA])
649 if self.state == self.stNONE:
650 self.state = self.stPARA
651 if self.laststate != self.stNONE:
652 self.text.write('\n\n')
653 self.html.write('<p>')
657 self.text_txt = self.text.getvalue()
658 self.text_html = self.html.getvalue()
663 # Parse multiple lines of description as written in a metadata file, returning
664 # a single string in text format and wrapped to 80 columns.
665 def description_txt(s):
666 ps = DescriptionFormatter(None)
667 for line in s.splitlines():
673 # Parse multiple lines of description as written in a metadata file, returning
674 # a single string in wiki format. Used for the Maintainer Notes field as well,
675 # because it's the same format.
676 def description_wiki(s):
680 # Parse multiple lines of description as written in a metadata file, returning
681 # a single string in HTML format.
682 def description_html(s, linkres):
683 ps = DescriptionFormatter(linkres)
684 for line in s.splitlines():
690 def parse_srclib(metadatapath):
694 # Defaults for fields that come from metadata
695 thisinfo['Repo Type'] = ''
696 thisinfo['Repo'] = ''
697 thisinfo['Subdir'] = None
698 thisinfo['Prepare'] = None
700 if not os.path.exists(metadatapath):
703 metafile = open(metadatapath, "r")
706 for line in metafile:
708 line = line.rstrip('\r\n')
709 if not line or line.startswith("#"):
713 f, v = line.split(':', 1)
715 raise MetaDataException("Invalid metadata in %s:%d" % (line, n))
718 thisinfo[f] = v.split(',')
728 """Read all srclib metadata.
730 The information read will be accessible as metadata.srclibs, which is a
731 dictionary, keyed on srclib name, with the values each being a dictionary
732 in the same format as that returned by the parse_srclib function.
734 A MetaDataException is raised if there are any problems with the srclib
739 # They were already loaded
740 if srclibs is not None:
746 if not os.path.exists(srcdir):
749 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
750 srclibname = os.path.basename(metadatapath[:-4])
751 srclibs[srclibname] = parse_srclib(metadatapath)
754 # Read all metadata. Returns a list of 'app' objects (which are dictionaries as
755 # returned by the parse_txt_metadata function.
756 def read_metadata(xref=True):
758 # Always read the srclibs before the apps, since they can use a srlib as
759 # their source repository.
764 for basedir in ('metadata', 'tmp'):
765 if not os.path.exists(basedir):
768 # If there are multiple metadata files for a single appid, then the first
769 # file that is parsed wins over all the others, and the rest throw an
770 # exception. So the original .txt format is parsed first, at least until
771 # newer formats stabilize.
773 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
774 + glob.glob(os.path.join('metadata', '*.json'))
775 + glob.glob(os.path.join('metadata', '*.xml'))
776 + glob.glob(os.path.join('metadata', '*.yaml'))):
777 app = parse_metadata(metadatapath)
779 raise MetaDataException("Found multiple metadata files for " + app.id)
784 # Parse all descriptions at load time, just to ensure cross-referencing
785 # errors are caught early rather than when they hit the build server.
788 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
789 raise MetaDataException("Cannot resolve app id " + appid)
791 for appid, app in apps.iteritems():
793 description_html(app.Description, linkres)
794 except MetaDataException as e:
795 raise MetaDataException("Problem with description of " + appid +
800 # Port legacy ';' separators
801 list_sep = re.compile(r'[,;]')
804 def split_list_values(s):
806 for v in re.split(list_sep, s):
816 def get_default_app_info(metadatapath=None):
817 if metadatapath is None:
820 appid, _ = common.get_extension(os.path.basename(metadatapath))
823 app.metadatapath = metadatapath
824 if appid is not None:
830 def sorted_builds(builds):
831 return sorted(builds, key=lambda build: int(build.vercode))
834 esc_newlines = re.compile(r'\\( |\n)')
837 # This function uses __dict__ to be faster
838 def post_metadata_parse(app):
840 for k, v in app.__dict__.iteritems():
841 if k not in app._modified:
843 if type(v) in (float, int):
844 app.__dict__[k] = str(v)
846 for build in app.builds:
847 for k, v in build.__dict__.iteritems():
849 if k not in build._modified:
851 if type(v) in (float, int):
852 build.__dict__[k] = str(v)
856 if ftype == TYPE_SCRIPT:
857 build.__dict__[k] = re.sub(esc_newlines, '', v).lstrip().rstrip()
858 elif ftype == TYPE_BOOL:
859 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
860 if isinstance(v, basestring):
861 build.__dict__[k] = _decode_bool(v)
862 elif ftype == TYPE_STRING:
863 if isinstance(v, bool) and v:
864 build.__dict__[k] = 'yes'
866 if not app.Description:
867 app.Description = 'No description available'
869 app.builds = sorted_builds(app.builds)
872 # Parse metadata for a single application.
874 # 'metadatapath' - the filename to read. The package id for the application comes
875 # from this filename. Pass None to get a blank entry.
877 # Returns a dictionary containing all the details of the application. There are
878 # two major kinds of information in the dictionary. Keys beginning with capital
879 # letters correspond directory to identically named keys in the metadata file.
880 # Keys beginning with lower case letters are generated in one way or another,
881 # and are not found verbatim in the metadata.
883 # Known keys not originating from the metadata are:
885 # 'builds' - a list of dictionaries containing build information
886 # for each defined build
887 # 'comments' - a list of comments from the metadata file. Each is
888 # a list of the form [field, comment] where field is
889 # the name of the field it preceded in the metadata
890 # file. Where field is None, the comment goes at the
891 # end of the file. Alternatively, 'build:version' is
892 # for a comment before a particular build version.
893 # 'descriptionlines' - original lines of description as formatted in the
898 def _decode_list(data):
899 '''convert items in a list from unicode to basestring'''
902 if isinstance(item, unicode):
903 item = item.encode('utf-8')
904 elif isinstance(item, list):
905 item = _decode_list(item)
906 elif isinstance(item, dict):
907 item = _decode_dict(item)
912 def _decode_dict(data):
913 '''convert items in a dict from unicode to basestring'''
915 for k, v in data.iteritems():
916 if isinstance(k, unicode):
917 k = k.encode('utf-8')
918 if isinstance(v, unicode):
919 v = v.encode('utf-8')
920 elif isinstance(v, list):
922 elif isinstance(v, dict):
928 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
929 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
933 if bool_true.match(s):
935 if bool_false.match(s):
937 raise MetaDataException("Invalid bool '%s'" % s)
940 def parse_metadata(metadatapath):
941 _, ext = common.get_extension(metadatapath)
942 accepted = common.config['accepted_formats']
943 if ext not in accepted:
944 raise MetaDataException('"%s" is not an accepted format, convert to: %s' % (
945 metadatapath, ', '.join(accepted)))
948 app.metadatapath = metadatapath
949 app.id, _ = common.get_extension(os.path.basename(metadatapath))
951 with open(metadatapath, 'r') as mf:
953 parse_txt_metadata(mf, app)
955 parse_json_metadata(mf, app)
957 parse_xml_metadata(mf, app)
959 parse_yaml_metadata(mf, app)
961 raise MetaDataException('Unknown metadata format: %s' % metadatapath)
963 post_metadata_parse(app)
967 def parse_json_metadata(mf, app):
969 # fdroid metadata is only strings and booleans, no floats or ints. And
970 # json returns unicode, and fdroidserver still uses plain python strings
971 # TODO create schema using https://pypi.python.org/pypi/jsonschema
972 jsoninfo = json.load(mf, object_hook=_decode_dict,
973 parse_int=lambda s: s,
974 parse_float=lambda s: s)
975 app.update_fields(jsoninfo)
976 for f in ['Description', 'Maintainer Notes']:
978 app.set_field(f, '\n'.join(v))
982 def parse_xml_metadata(mf, app):
984 tree = ElementTree.ElementTree(file=mf)
985 root = tree.getroot()
987 if root.tag != 'resources':
988 raise MetaDataException('resources file does not have root element <resources/>')
991 if child.tag != 'builds':
992 # builds does not have name="" attrib
993 name = child.attrib['name']
995 if child.tag == 'string':
996 app.set_field(name, child.text)
997 elif child.tag == 'string-array':
999 app.append_field(name, item.text)
1000 elif child.tag == 'builds':
1004 build.set_flag(key.tag, key.text)
1005 app.builds.append(build)
1007 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
1008 if not isinstance(app.RequiresRoot, bool):
1009 app.RequiresRoot = app.RequiresRoot == 'true'
1014 def parse_yaml_metadata(mf, app):
1016 yamlinfo = yaml.load(mf, Loader=YamlLoader)
1017 app.update_fields(yamlinfo)
1021 build_line_sep = re.compile(r'(?<!\\),')
1022 build_cont = re.compile(r'^[ \t]')
1025 def parse_txt_metadata(mf, app):
1029 def add_buildflag(p, build):
1031 raise MetaDataException("Empty build flag at {1}"
1032 .format(buildlines[0], linedesc))
1033 bv = p.split('=', 1)
1035 raise MetaDataException("Invalid build flag at {0} in {1}"
1036 .format(buildlines[0], linedesc))
1042 pv = split_list_values(pv)
1043 build.set_flag(pk, pv)
1044 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1045 build.set_flag(pk, pv)
1046 elif t == TYPE_BOOL:
1047 build.set_flag(pk, _decode_bool(pv))
1049 def parse_buildline(lines):
1051 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1053 raise MetaDataException("Invalid build format: " + v + " in " + mf.name)
1055 build.version = parts[0]
1056 build.vercode = parts[1]
1057 if parts[2].startswith('!'):
1058 # For backwards compatibility, handle old-style disabling,
1059 # including attempting to extract the commit from the message
1060 build.disable = parts[2][1:]
1061 commit = 'unknown - see disabled'
1062 index = parts[2].rfind('at ')
1064 commit = parts[2][index + 3:]
1065 if commit.endswith(')'):
1066 commit = commit[:-1]
1067 build.commit = commit
1069 build.commit = parts[2]
1071 add_buildflag(p, build)
1075 def add_comments(key):
1078 app.comments[key] = list(curcomments)
1083 multiline_lines = []
1091 linedesc = "%s:%d" % (mf.name, c)
1092 line = line.rstrip('\r\n')
1094 if build_cont.match(line):
1095 if line.endswith('\\'):
1096 buildlines.append(line[:-1].lstrip())
1098 buildlines.append(line.lstrip())
1099 bl = ''.join(buildlines)
1100 add_buildflag(bl, build)
1103 if not build.commit and not build.disable:
1104 raise MetaDataException("No commit specified for {0} in {1}"
1105 .format(build.version, linedesc))
1107 app.builds.append(build)
1108 add_comments('build:' + build.vercode)
1114 if line.startswith("#"):
1115 curcomments.append(line[1:].strip())
1118 f, v = line.split(':', 1)
1120 raise MetaDataException("Invalid metadata in " + linedesc)
1122 # Translate obsolete fields...
1123 if f == 'Market Version':
1124 f = 'Current Version'
1125 if f == 'Market Version Code':
1126 f = 'Current Version Code'
1128 ftype = fieldtype(f)
1129 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1131 if ftype == TYPE_MULTILINE:
1134 raise MetaDataException("Unexpected text on same line as " + f + " in " + linedesc)
1135 elif ftype == TYPE_STRING:
1137 elif ftype == TYPE_LIST:
1138 app.set_field(f, split_list_values(v))
1139 elif ftype == TYPE_BUILD:
1140 if v.endswith("\\"):
1143 buildlines.append(v[:-1])
1145 build = parse_buildline([v])
1146 app.builds.append(build)
1147 add_comments('build:' + app.builds[-1].vercode)
1148 elif ftype == TYPE_BUILD_V2:
1151 raise MetaDataException('Build should have comma-separated version and vercode, not "{0}", in {1}'
1152 .format(v, linedesc))
1154 build.version = vv[0]
1155 build.vercode = vv[1]
1156 if build.vercode in vc_seen:
1157 raise MetaDataException('Duplicate build recipe found for vercode %s in %s' % (
1158 build.vercode, linedesc))
1159 vc_seen.add(build.vercode)
1162 elif ftype == TYPE_OBSOLETE:
1163 pass # Just throw it away!
1165 raise MetaDataException("Unrecognised field '" + f + "' in " + linedesc)
1166 elif mode == 1: # Multiline field
1169 app.set_field(f, '\n'.join(multiline_lines))
1170 del multiline_lines[:]
1172 multiline_lines.append(line)
1173 elif mode == 2: # Line continuation mode in Build Version
1174 if line.endswith("\\"):
1175 buildlines.append(line[:-1])
1177 buildlines.append(line)
1178 build = parse_buildline(buildlines)
1179 app.builds.append(build)
1180 add_comments('build:' + app.builds[-1].vercode)
1184 # Mode at end of file should always be 0
1186 raise MetaDataException(f + " not terminated in " + mf.name)
1188 raise MetaDataException("Unterminated continuation in " + mf.name)
1190 raise MetaDataException("Unterminated build in " + mf.name)
1195 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1197 def w_comments(key):
1198 if key not in app.comments:
1200 for line in app.comments[key]:
1203 def w_field_always(f, v=None):
1205 v = app.get_field(f)
1209 def w_field_nonempty(f, v=None):
1211 v = app.get_field(f)
1216 w_field_nonempty('Disabled')
1217 w_field_nonempty('AntiFeatures')
1218 w_field_nonempty('Provides')
1219 w_field_always('Categories')
1220 w_field_always('License')
1221 w_field_nonempty('Author Name')
1222 w_field_nonempty('Author Email')
1223 w_field_always('Web Site')
1224 w_field_always('Source Code')
1225 w_field_always('Issue Tracker')
1226 w_field_nonempty('Changelog')
1227 w_field_nonempty('Donate')
1228 w_field_nonempty('FlattrID')
1229 w_field_nonempty('Bitcoin')
1230 w_field_nonempty('Litecoin')
1232 w_field_nonempty('Name')
1233 w_field_nonempty('Auto Name')
1234 w_field_always('Summary')
1235 w_field_always('Description', description_txt(app.Description))
1237 if app.RequiresRoot:
1238 w_field_always('Requires Root', 'yes')
1241 w_field_always('Repo Type')
1242 w_field_always('Repo')
1244 w_field_always('Binaries')
1247 for build in sorted_builds(app.builds):
1249 if build.version == "Ignore":
1252 w_comments('build:' + build.vercode)
1256 if app.MaintainerNotes:
1257 w_field_always('Maintainer Notes', app.MaintainerNotes)
1260 w_field_nonempty('Archive Policy')
1261 w_field_always('Auto Update Mode')
1262 w_field_always('Update Check Mode')
1263 w_field_nonempty('Update Check Ignore')
1264 w_field_nonempty('Vercode Operation')
1265 w_field_nonempty('Update Check Name')
1266 w_field_nonempty('Update Check Data')
1267 if app.CurrentVersion:
1268 w_field_always('Current Version')
1269 w_field_always('Current Version Code')
1270 if app.NoSourceSince:
1272 w_field_always('No Source Since')
1276 # Write a metadata file in txt format.
1278 # 'mf' - Writer interface (file, StringIO, ...)
1279 # 'app' - The app data
1280 def write_txt_metadata(mf, app):
1282 def w_comment(line):
1283 mf.write("# %s\n" % line)
1289 elif t == TYPE_MULTILINE:
1290 v = '\n' + v + '\n.'
1291 mf.write("%s:%s\n" % (f, v))
1294 mf.write("Build:%s,%s\n" % (build.version, build.vercode))
1296 for f in build_flags_order:
1297 v = build.get_flag(f)
1302 mf.write(' %s=' % f)
1303 if t == TYPE_STRING:
1305 elif t == TYPE_BOOL:
1307 elif t == TYPE_SCRIPT:
1309 for s in v.split(' && '):
1313 mf.write(' && \\\n ')
1315 elif t == TYPE_LIST:
1316 mf.write(','.join(v))
1320 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1323 def write_yaml_metadata(mf, app):
1325 def w_comment(line):
1326 mf.write("# %s\n" % line)
1331 if any(c in v for c in [': ', '%', '@', '*']):
1332 return "'" + v.replace("'", "''") + "'"
1335 def w_field(f, v, prefix='', t=None):
1342 v += prefix + ' - ' + escape(e) + '\n'
1343 elif t == TYPE_MULTILINE:
1345 for l in v.splitlines():
1347 v += prefix + ' ' + l + '\n'
1350 elif t == TYPE_BOOL:
1352 elif t == TYPE_SCRIPT:
1353 cmds = [s + '&& \\' for s in v.split('&& ')]
1355 cmds[-1] = cmds[-1][:-len('&& \\')]
1356 w_field(f, cmds, prefix, 'multiline')
1359 v = ' ' + escape(v) + '\n'
1372 mf.write("builds:\n")
1375 w_field('versionName', build.version, ' - ', TYPE_STRING)
1376 w_field('versionCode', build.vercode, ' ', TYPE_STRING)
1377 for f in build_flags_order:
1378 v = build.get_flag(f)
1382 w_field(f, v, ' ', flagtype(f))
1384 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1387 def write_metadata(fmt, mf, app):
1389 return write_txt_metadata(mf, app)
1391 return write_yaml_metadata(mf, app)
1392 raise MetaDataException("Unknown metadata format given")