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 self.text.write(textwrap.fill(whole_para, 80,
529 break_long_words=False,
530 break_on_hyphens=False))
531 self.html.write('</p>')
532 del self.para_lines[:]
535 self.html.write('</ul>')
536 self.laststate = self.state
537 self.state = self.stNONE
540 self.html.write('</ol>')
541 self.laststate = self.state
542 self.state = self.stNONE
544 def formatted(self, txt, html):
547 txt = cgi.escape(txt)
549 index = txt.find("''")
554 if txt.startswith("'''"):
560 self.bold = not self.bold
568 self.ital = not self.ital
571 def linkify(self, txt):
575 index = txt.find("[")
577 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
578 res_plain += self.formatted(txt[:index], False)
579 res_html += self.formatted(txt[:index], True)
581 if txt.startswith("[["):
582 index = txt.find("]]")
584 raise MetaDataException("Unterminated ]]")
586 if self.linkResolver:
587 url, urltext = self.linkResolver(url)
590 res_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
592 txt = txt[index + 2:]
594 index = txt.find("]")
596 raise MetaDataException("Unterminated ]")
598 index2 = url.find(' ')
602 urltxt = url[index2 + 1:]
605 raise MetaDataException("Url title is just the URL - use [url]")
606 res_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
609 res_plain += ' (' + url + ')'
610 txt = txt[index + 1:]
612 def addtext(self, txt):
613 p, h = self.linkify(txt)
616 def parseline(self, line):
619 elif line.startswith('* '):
620 self.endcur([self.stUL])
621 if self.state != self.stUL:
622 self.html.write('<ul>')
623 self.state = self.stUL
624 if self.laststate != self.stNONE:
625 self.text.write('\n\n')
627 self.text.write('\n')
628 self.text.write(line)
629 self.html.write('<li>')
630 self.addtext(line[1:])
631 self.html.write('</li>')
632 elif line.startswith('# '):
633 self.endcur([self.stOL])
634 if self.state != self.stOL:
635 self.html.write('<ol>')
636 self.state = self.stOL
637 if self.laststate != self.stNONE:
638 self.text.write('\n\n')
640 self.text.write('\n')
641 self.text.write(line)
642 self.html.write('<li>')
643 self.addtext(line[1:])
644 self.html.write('</li>')
646 self.para_lines.append(line)
647 self.endcur([self.stPARA])
648 if self.state == self.stNONE:
649 self.state = self.stPARA
650 if self.laststate != self.stNONE:
651 self.text.write('\n\n')
652 self.html.write('<p>')
656 self.text_txt = self.text.getvalue()
657 self.text_html = self.html.getvalue()
662 # Parse multiple lines of description as written in a metadata file, returning
663 # a single string in text format and wrapped to 80 columns.
664 def description_txt(s):
665 ps = DescriptionFormatter(None)
666 for line in s.splitlines():
672 # Parse multiple lines of description as written in a metadata file, returning
673 # a single string in wiki format. Used for the Maintainer Notes field as well,
674 # because it's the same format.
675 def description_wiki(s):
679 # Parse multiple lines of description as written in a metadata file, returning
680 # a single string in HTML format.
681 def description_html(s, linkres):
682 ps = DescriptionFormatter(linkres)
683 for line in s.splitlines():
689 def parse_srclib(metadatapath):
693 # Defaults for fields that come from metadata
694 thisinfo['Repo Type'] = ''
695 thisinfo['Repo'] = ''
696 thisinfo['Subdir'] = None
697 thisinfo['Prepare'] = None
699 if not os.path.exists(metadatapath):
702 metafile = open(metadatapath, "r")
705 for line in metafile:
707 line = line.rstrip('\r\n')
708 if not line or line.startswith("#"):
712 f, v = line.split(':', 1)
714 raise MetaDataException("Invalid metadata in %s:%d" % (line, n))
717 thisinfo[f] = v.split(',')
727 """Read all srclib metadata.
729 The information read will be accessible as metadata.srclibs, which is a
730 dictionary, keyed on srclib name, with the values each being a dictionary
731 in the same format as that returned by the parse_srclib function.
733 A MetaDataException is raised if there are any problems with the srclib
738 # They were already loaded
739 if srclibs is not None:
745 if not os.path.exists(srcdir):
748 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
749 srclibname = os.path.basename(metadatapath[:-4])
750 srclibs[srclibname] = parse_srclib(metadatapath)
753 # Read all metadata. Returns a list of 'app' objects (which are dictionaries as
754 # returned by the parse_txt_metadata function.
755 def read_metadata(xref=True):
757 # Always read the srclibs before the apps, since they can use a srlib as
758 # their source repository.
763 for basedir in ('metadata', 'tmp'):
764 if not os.path.exists(basedir):
767 # If there are multiple metadata files for a single appid, then the first
768 # file that is parsed wins over all the others, and the rest throw an
769 # exception. So the original .txt format is parsed first, at least until
770 # newer formats stabilize.
772 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
773 + glob.glob(os.path.join('metadata', '*.json'))
774 + glob.glob(os.path.join('metadata', '*.xml'))
775 + glob.glob(os.path.join('metadata', '*.yaml'))):
776 app = parse_metadata(metadatapath)
778 raise MetaDataException("Found multiple metadata files for " + app.id)
783 # Parse all descriptions at load time, just to ensure cross-referencing
784 # errors are caught early rather than when they hit the build server.
787 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
788 raise MetaDataException("Cannot resolve app id " + appid)
790 for appid, app in apps.iteritems():
792 description_html(app.Description, linkres)
793 except MetaDataException as e:
794 raise MetaDataException("Problem with description of " + appid +
799 # Port legacy ';' separators
800 list_sep = re.compile(r'[,;]')
803 def split_list_values(s):
805 for v in re.split(list_sep, s):
815 def get_default_app_info(metadatapath=None):
816 if metadatapath is None:
819 appid, _ = common.get_extension(os.path.basename(metadatapath))
822 app.metadatapath = metadatapath
823 if appid is not None:
829 def sorted_builds(builds):
830 return sorted(builds, key=lambda build: int(build.vercode))
833 esc_newlines = re.compile(r'\\( |\n)')
836 # This function uses __dict__ to be faster
837 def post_metadata_parse(app):
839 for k, v in app.__dict__.iteritems():
840 if k not in app._modified:
842 if type(v) in (float, int):
843 app.__dict__[k] = str(v)
845 for build in app.builds:
846 for k, v in build.__dict__.iteritems():
848 if k not in build._modified:
850 if type(v) in (float, int):
851 build.__dict__[k] = str(v)
855 if ftype == TYPE_SCRIPT:
856 build.__dict__[k] = re.sub(esc_newlines, '', v).lstrip().rstrip()
857 elif ftype == TYPE_BOOL:
858 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
859 if isinstance(v, basestring):
860 build.__dict__[k] = _decode_bool(v)
861 elif ftype == TYPE_STRING:
862 if isinstance(v, bool) and v:
863 build.__dict__[k] = 'yes'
865 if not app.Description:
866 app.Description = 'No description available'
868 app.builds = sorted_builds(app.builds)
871 # Parse metadata for a single application.
873 # 'metadatapath' - the filename to read. The package id for the application comes
874 # from this filename. Pass None to get a blank entry.
876 # Returns a dictionary containing all the details of the application. There are
877 # two major kinds of information in the dictionary. Keys beginning with capital
878 # letters correspond directory to identically named keys in the metadata file.
879 # Keys beginning with lower case letters are generated in one way or another,
880 # and are not found verbatim in the metadata.
882 # Known keys not originating from the metadata are:
884 # 'builds' - a list of dictionaries containing build information
885 # for each defined build
886 # 'comments' - a list of comments from the metadata file. Each is
887 # a list of the form [field, comment] where field is
888 # the name of the field it preceded in the metadata
889 # file. Where field is None, the comment goes at the
890 # end of the file. Alternatively, 'build:version' is
891 # for a comment before a particular build version.
892 # 'descriptionlines' - original lines of description as formatted in the
897 def _decode_list(data):
898 '''convert items in a list from unicode to basestring'''
901 if isinstance(item, unicode):
902 item = item.encode('utf-8')
903 elif isinstance(item, list):
904 item = _decode_list(item)
905 elif isinstance(item, dict):
906 item = _decode_dict(item)
911 def _decode_dict(data):
912 '''convert items in a dict from unicode to basestring'''
914 for k, v in data.iteritems():
915 if isinstance(k, unicode):
916 k = k.encode('utf-8')
917 if isinstance(v, unicode):
918 v = v.encode('utf-8')
919 elif isinstance(v, list):
921 elif isinstance(v, dict):
927 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
928 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
932 if bool_true.match(s):
934 if bool_false.match(s):
936 raise MetaDataException("Invalid bool '%s'" % s)
939 def parse_metadata(metadatapath):
940 _, ext = common.get_extension(metadatapath)
941 accepted = common.config['accepted_formats']
942 if ext not in accepted:
943 raise MetaDataException('"%s" is not an accepted format, convert to: %s' % (
944 metadatapath, ', '.join(accepted)))
947 app.metadatapath = metadatapath
948 app.id, _ = common.get_extension(os.path.basename(metadatapath))
950 with open(metadatapath, 'r') as mf:
952 parse_txt_metadata(mf, app)
954 parse_json_metadata(mf, app)
956 parse_xml_metadata(mf, app)
958 parse_yaml_metadata(mf, app)
960 raise MetaDataException('Unknown metadata format: %s' % metadatapath)
962 post_metadata_parse(app)
966 def parse_json_metadata(mf, app):
968 # fdroid metadata is only strings and booleans, no floats or ints. And
969 # json returns unicode, and fdroidserver still uses plain python strings
970 # TODO create schema using https://pypi.python.org/pypi/jsonschema
971 jsoninfo = json.load(mf, object_hook=_decode_dict,
972 parse_int=lambda s: s,
973 parse_float=lambda s: s)
974 app.update_fields(jsoninfo)
975 for f in ['Description', 'Maintainer Notes']:
977 app.set_field(f, '\n'.join(v))
981 def parse_xml_metadata(mf, app):
983 tree = ElementTree.ElementTree(file=mf)
984 root = tree.getroot()
986 if root.tag != 'resources':
987 raise MetaDataException('resources file does not have root element <resources/>')
990 if child.tag != 'builds':
991 # builds does not have name="" attrib
992 name = child.attrib['name']
994 if child.tag == 'string':
995 app.set_field(name, child.text)
996 elif child.tag == 'string-array':
998 app.append_field(name, item.text)
999 elif child.tag == 'builds':
1003 build.set_flag(key.tag, key.text)
1004 app.builds.append(build)
1006 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
1007 if not isinstance(app.RequiresRoot, bool):
1008 app.RequiresRoot = app.RequiresRoot == 'true'
1013 def parse_yaml_metadata(mf, app):
1015 yamlinfo = yaml.load(mf, Loader=YamlLoader)
1016 app.update_fields(yamlinfo)
1020 build_line_sep = re.compile(r'(?<!\\),')
1021 build_cont = re.compile(r'^[ \t]')
1024 def parse_txt_metadata(mf, app):
1028 def add_buildflag(p, build):
1030 raise MetaDataException("Empty build flag at {1}"
1031 .format(buildlines[0], linedesc))
1032 bv = p.split('=', 1)
1034 raise MetaDataException("Invalid build flag at {0} in {1}"
1035 .format(buildlines[0], linedesc))
1041 pv = split_list_values(pv)
1042 build.set_flag(pk, pv)
1043 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1044 build.set_flag(pk, pv)
1045 elif t == TYPE_BOOL:
1046 build.set_flag(pk, _decode_bool(pv))
1048 def parse_buildline(lines):
1050 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1052 raise MetaDataException("Invalid build format: " + v + " in " + mf.name)
1054 build.version = parts[0]
1055 build.vercode = parts[1]
1056 if parts[2].startswith('!'):
1057 # For backwards compatibility, handle old-style disabling,
1058 # including attempting to extract the commit from the message
1059 build.disable = parts[2][1:]
1060 commit = 'unknown - see disabled'
1061 index = parts[2].rfind('at ')
1063 commit = parts[2][index + 3:]
1064 if commit.endswith(')'):
1065 commit = commit[:-1]
1066 build.commit = commit
1068 build.commit = parts[2]
1070 add_buildflag(p, build)
1074 def add_comments(key):
1077 app.comments[key] = list(curcomments)
1082 multiline_lines = []
1090 linedesc = "%s:%d" % (mf.name, c)
1091 line = line.rstrip('\r\n')
1093 if build_cont.match(line):
1094 if line.endswith('\\'):
1095 buildlines.append(line[:-1].lstrip())
1097 buildlines.append(line.lstrip())
1098 bl = ''.join(buildlines)
1099 add_buildflag(bl, build)
1102 if not build.commit and not build.disable:
1103 raise MetaDataException("No commit specified for {0} in {1}"
1104 .format(build.version, linedesc))
1106 app.builds.append(build)
1107 add_comments('build:' + build.vercode)
1113 if line.startswith("#"):
1114 curcomments.append(line[1:].strip())
1117 f, v = line.split(':', 1)
1119 raise MetaDataException("Invalid metadata in " + linedesc)
1121 # Translate obsolete fields...
1122 if f == 'Market Version':
1123 f = 'Current Version'
1124 if f == 'Market Version Code':
1125 f = 'Current Version Code'
1127 ftype = fieldtype(f)
1128 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1130 if ftype == TYPE_MULTILINE:
1133 raise MetaDataException("Unexpected text on same line as " + f + " in " + linedesc)
1134 elif ftype == TYPE_STRING:
1136 elif ftype == TYPE_LIST:
1137 app.set_field(f, split_list_values(v))
1138 elif ftype == TYPE_BUILD:
1139 if v.endswith("\\"):
1142 buildlines.append(v[:-1])
1144 build = parse_buildline([v])
1145 app.builds.append(build)
1146 add_comments('build:' + app.builds[-1].vercode)
1147 elif ftype == TYPE_BUILD_V2:
1150 raise MetaDataException('Build should have comma-separated version and vercode, not "{0}", in {1}'
1151 .format(v, linedesc))
1153 build.version = vv[0]
1154 build.vercode = vv[1]
1155 if build.vercode in vc_seen:
1156 raise MetaDataException('Duplicate build recipe found for vercode %s in %s' % (
1157 build.vercode, linedesc))
1158 vc_seen.add(build.vercode)
1161 elif ftype == TYPE_OBSOLETE:
1162 pass # Just throw it away!
1164 raise MetaDataException("Unrecognised field '" + f + "' in " + linedesc)
1165 elif mode == 1: # Multiline field
1168 app.set_field(f, '\n'.join(multiline_lines))
1169 del multiline_lines[:]
1171 multiline_lines.append(line)
1172 elif mode == 2: # Line continuation mode in Build Version
1173 if line.endswith("\\"):
1174 buildlines.append(line[:-1])
1176 buildlines.append(line)
1177 build = parse_buildline(buildlines)
1178 app.builds.append(build)
1179 add_comments('build:' + app.builds[-1].vercode)
1183 # Mode at end of file should always be 0
1185 raise MetaDataException(f + " not terminated in " + mf.name)
1187 raise MetaDataException("Unterminated continuation in " + mf.name)
1189 raise MetaDataException("Unterminated build in " + mf.name)
1194 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1196 def w_comments(key):
1197 if key not in app.comments:
1199 for line in app.comments[key]:
1202 def w_field_always(f, v=None):
1204 v = app.get_field(f)
1208 def w_field_nonempty(f, v=None):
1210 v = app.get_field(f)
1215 w_field_nonempty('Disabled')
1216 w_field_nonempty('AntiFeatures')
1217 w_field_nonempty('Provides')
1218 w_field_always('Categories')
1219 w_field_always('License')
1220 w_field_nonempty('Author Name')
1221 w_field_nonempty('Author Email')
1222 w_field_always('Web Site')
1223 w_field_always('Source Code')
1224 w_field_always('Issue Tracker')
1225 w_field_nonempty('Changelog')
1226 w_field_nonempty('Donate')
1227 w_field_nonempty('FlattrID')
1228 w_field_nonempty('Bitcoin')
1229 w_field_nonempty('Litecoin')
1231 w_field_nonempty('Name')
1232 w_field_nonempty('Auto Name')
1233 w_field_always('Summary')
1234 w_field_always('Description', description_txt(app.Description))
1236 if app.RequiresRoot:
1237 w_field_always('Requires Root', 'yes')
1240 w_field_always('Repo Type')
1241 w_field_always('Repo')
1243 w_field_always('Binaries')
1246 for build in sorted_builds(app.builds):
1248 if build.version == "Ignore":
1251 w_comments('build:' + build.vercode)
1255 if app.MaintainerNotes:
1256 w_field_always('Maintainer Notes', app.MaintainerNotes)
1259 w_field_nonempty('Archive Policy')
1260 w_field_always('Auto Update Mode')
1261 w_field_always('Update Check Mode')
1262 w_field_nonempty('Update Check Ignore')
1263 w_field_nonempty('Vercode Operation')
1264 w_field_nonempty('Update Check Name')
1265 w_field_nonempty('Update Check Data')
1266 if app.CurrentVersion:
1267 w_field_always('Current Version')
1268 w_field_always('Current Version Code')
1269 if app.NoSourceSince:
1271 w_field_always('No Source Since')
1275 # Write a metadata file in txt format.
1277 # 'mf' - Writer interface (file, StringIO, ...)
1278 # 'app' - The app data
1279 def write_txt_metadata(mf, app):
1281 def w_comment(line):
1282 mf.write("# %s\n" % line)
1288 elif t == TYPE_MULTILINE:
1289 v = '\n' + v + '\n.'
1290 mf.write("%s:%s\n" % (f, v))
1293 mf.write("Build:%s,%s\n" % (build.version, build.vercode))
1295 for f in build_flags_order:
1296 v = build.get_flag(f)
1301 mf.write(' %s=' % f)
1302 if t == TYPE_STRING:
1304 elif t == TYPE_BOOL:
1306 elif t == TYPE_SCRIPT:
1308 for s in v.split(' && '):
1312 mf.write(' && \\\n ')
1314 elif t == TYPE_LIST:
1315 mf.write(','.join(v))
1319 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1322 def write_yaml_metadata(mf, app):
1324 def w_comment(line):
1325 mf.write("# %s\n" % line)
1330 if any(c in v for c in [': ', '%', '@', '*']):
1331 return "'" + v.replace("'", "''") + "'"
1334 def w_field(f, v, prefix='', t=None):
1341 v += prefix + ' - ' + escape(e) + '\n'
1342 elif t == TYPE_MULTILINE:
1344 for l in v.splitlines():
1346 v += prefix + ' ' + l + '\n'
1349 elif t == TYPE_BOOL:
1351 elif t == TYPE_SCRIPT:
1352 cmds = [s + '&& \\' for s in v.split('&& ')]
1354 cmds[-1] = cmds[-1][:-len('&& \\')]
1355 w_field(f, cmds, prefix, 'multiline')
1358 v = ' ' + escape(v) + '\n'
1371 mf.write("builds:\n")
1374 w_field('versionName', build.version, ' - ', TYPE_STRING)
1375 w_field('versionCode', build.vercode, ' ', TYPE_STRING)
1376 for f in build_flags_order:
1377 v = build.get_flag(f)
1381 w_field(f, v, ' ', flagtype(f))
1383 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1386 def write_metadata(fmt, mf, app):
1388 return write_txt_metadata(mf, app)
1390 return write_yaml_metadata(mf, app)
1391 raise MetaDataException("Unknown metadata format given")