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/>.
30 # use libyaml if it is available
32 from yaml import CLoader
35 from yaml import Loader
38 # use the C implementation when available
39 import xml.etree.cElementTree as ElementTree
41 import fdroidserver.common
44 warnings_action = None
47 class MetaDataException(Exception):
49 def __init__(self, value):
56 def warn_or_exception(value):
57 '''output warning or Exception depending on -W'''
58 if warnings_action == 'ignore':
60 elif warnings_action == 'error':
61 raise MetaDataException(value)
66 # To filter which ones should be written to the metadata files if
96 'Update Check Ignore',
101 'Current Version Code',
104 'comments', # For formats that don't do inline comments
105 'builds', # For formats that do builds as a list
113 self.AntiFeatures = []
115 self.Categories = ['None']
116 self.License = 'Unknown'
117 self.AuthorName = None
118 self.AuthorEmail = None
121 self.IssueTracker = ''
130 self.Description = ''
131 self.RequiresRoot = False
135 self.MaintainerNotes = ''
136 self.ArchivePolicy = None
137 self.AutoUpdateMode = 'None'
138 self.UpdateCheckMode = 'None'
139 self.UpdateCheckIgnore = None
140 self.VercodeOperation = None
141 self.UpdateCheckName = None
142 self.UpdateCheckData = None
143 self.CurrentVersion = ''
144 self.CurrentVersionCode = None
145 self.NoSourceSince = ''
148 self.metadatapath = None
152 self.lastupdated = None
153 self._modified = set()
156 def field_to_attr(cls, f):
158 Translates human-readable field names to attribute names, e.g.
159 'Auto Name' to 'AutoName'
161 return f.replace(' ', '')
164 def attr_to_field(cls, k):
166 Translates attribute names to human-readable field names, e.g.
167 'AutoName' to 'Auto Name'
171 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
174 def field_dict(self):
176 Constructs an old-fashioned dict with the human-readable field
177 names. Should only be used for tests.
180 for k, v in self.__dict__.items():
184 b = {k: v for k, v in build.__dict__.items() if not k.startswith('_')}
185 d['builds'].append(b)
186 elif not k.startswith('_'):
187 f = App.attr_to_field(k)
191 def get_field(self, f):
192 """Gets the value associated to a field name, e.g. 'Auto Name'"""
193 if f not in app_fields:
194 warn_or_exception('Unrecognised app field: ' + f)
195 k = App.field_to_attr(f)
196 return getattr(self, k)
198 def set_field(self, f, v):
199 """Sets the value associated to a field name, e.g. 'Auto Name'"""
200 if f not in app_fields:
201 warn_or_exception('Unrecognised app field: ' + f)
202 k = App.field_to_attr(f)
204 self._modified.add(k)
206 def append_field(self, f, v):
207 """Appends to the value associated to a field name, e.g. 'Auto Name'"""
208 if f not in app_fields:
209 warn_or_exception('Unrecognised app field: ' + f)
210 k = App.field_to_attr(f)
211 if k not in self.__dict__:
212 self.__dict__[k] = [v]
214 self.__dict__[k].append(v)
216 def update_fields(self, d):
217 '''Like dict.update(), but using human-readable field names'''
218 for f, v in d.items():
222 build.update_flags(b)
223 self.builds.append(build)
228 '''Like dict.update()'''
229 for k, v in d.__dict__.items():
235 del(b.__dict__['_modified'])
236 build.update_flags(b.__dict__)
237 self.builds.append(build)
240 self._modified.add(k)
254 'Description': TYPE_MULTILINE,
255 'Maintainer Notes': TYPE_MULTILINE,
256 'Categories': TYPE_LIST,
257 'AntiFeatures': TYPE_LIST,
258 'Build Version': TYPE_BUILD,
259 'Build': TYPE_BUILD_V2,
260 'Use Built': TYPE_OBSOLETE,
265 if name in fieldtypes:
266 return fieldtypes[name]
270 # In the order in which they are laid out on files
271 build_flags_order = [
304 build_flags = set(build_flags_order + ['version', 'vercode'])
313 self.submodules = False
321 self.oldsdkloc = False
323 self.forceversion = False
324 self.forcevercode = False
335 self.preassemble = []
336 self.gradleprops = []
337 self.antcommands = []
338 self.novcheck = False
340 self._modified = set()
342 def get_flag(self, f):
343 if f not in build_flags:
344 warn_or_exception('Unrecognised build flag: ' + f)
345 return getattr(self, f)
347 def set_flag(self, f, v):
348 if f == 'versionName':
350 if f == 'versionCode':
352 if f not in build_flags:
353 warn_or_exception('Unrecognised build flag: ' + f)
355 self._modified.add(f)
357 def append_flag(self, f, v):
358 if f not in build_flags:
359 warn_or_exception('Unrecognised build flag: ' + f)
360 if f not in self.__dict__:
361 self.__dict__[f] = [v]
363 self.__dict__[f].append(v)
365 def build_method(self):
366 for f in ['maven', 'gradle', 'kivy']:
373 # like build_method, but prioritize output=
374 def output_method(self):
377 for f in ['maven', 'gradle', 'kivy']:
385 version = 'r12b' # falls back to latest
386 paths = fdroidserver.common.config['ndk_paths']
387 if version not in paths:
389 return paths[version]
391 def update_flags(self, d):
392 for f, v in d.items():
397 'extlibs': TYPE_LIST,
398 'srclibs': TYPE_LIST,
401 'buildjni': TYPE_LIST,
402 'preassemble': TYPE_LIST,
404 'scanignore': TYPE_LIST,
405 'scandelete': TYPE_LIST,
407 'antcommands': TYPE_LIST,
408 'gradleprops': TYPE_LIST,
410 'prebuild': TYPE_SCRIPT,
411 'build': TYPE_SCRIPT,
412 'submodules': TYPE_BOOL,
413 'oldsdkloc': TYPE_BOOL,
414 'forceversion': TYPE_BOOL,
415 'forcevercode': TYPE_BOOL,
416 'novcheck': TYPE_BOOL,
421 if name in flagtypes:
422 return flagtypes[name]
426 # Designates a metadata field type and checks that it matches
428 # 'name' - The long name of the field type
429 # 'matching' - List of possible values or regex expression
430 # 'sep' - Separator to use if value may be a list
431 # 'fields' - Metadata fields (Field:Value) of this type
432 # 'flags' - Build flags (flag=value) of this type
434 class FieldValidator():
436 def __init__(self, name, matching, fields, flags):
438 self.matching = matching
439 self.compiled = re.compile(matching)
443 def check(self, v, appid):
451 if not self.compiled.match(v):
452 warn_or_exception("'%s' is not a valid %s in %s. Regex pattern: %s"
453 % (v, self.name, appid, self.matching))
456 # Generic value types
458 FieldValidator("Integer",
463 FieldValidator("Hexadecimal",
468 FieldValidator("HTTP link",
470 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"], []),
472 FieldValidator("Email",
473 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
474 ["AuthorEmail"], []),
476 FieldValidator("Bitcoin address",
477 r'^[a-zA-Z0-9]{27,34}$',
481 FieldValidator("Litecoin address",
482 r'^L[a-zA-Z0-9]{33}$',
486 FieldValidator("Repo Type",
487 r'^(git|git-svn|svn|hg|bzr|srclib)$',
491 FieldValidator("Binaries",
496 FieldValidator("Archive Policy",
497 r'^[0-9]+ versions$',
501 FieldValidator("Anti-Feature",
502 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets)$',
506 FieldValidator("Auto Update Mode",
507 r"^(Version .+|None)$",
511 FieldValidator("Update Check Mode",
512 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
518 # Check an app's metadata information for integrity errors
519 def check_metadata(app):
522 if k not in app._modified:
524 v.check(app.__dict__[k], app.id)
525 for build in app.builds:
527 if k not in build._modified:
529 v.check(build.__dict__[k], app.id)
532 # Formatter for descriptions. Create an instance, and call parseline() with
533 # each line of the description source from the metadata. At the end, call
534 # end() and then text_txt and text_html will contain the result.
535 class DescriptionFormatter:
542 def __init__(self, linkres):
545 self.state = self.stNONE
546 self.laststate = self.stNONE
549 self.html = io.StringIO()
550 self.text = io.StringIO()
552 self.linkResolver = None
553 self.linkResolver = linkres
555 def endcur(self, notstates=None):
556 if notstates and self.state in notstates:
558 if self.state == self.stPARA:
560 elif self.state == self.stUL:
562 elif self.state == self.stOL:
566 self.laststate = self.state
567 self.state = self.stNONE
568 whole_para = ' '.join(self.para_lines)
569 self.addtext(whole_para)
570 wrapped = textwrap.fill(whole_para, 80,
571 break_long_words=False,
572 break_on_hyphens=False)
573 self.text.write(wrapped)
574 self.html.write('</p>')
575 del self.para_lines[:]
578 self.html.write('</ul>')
579 self.laststate = self.state
580 self.state = self.stNONE
583 self.html.write('</ol>')
584 self.laststate = self.state
585 self.state = self.stNONE
587 def formatted(self, txt, html):
590 txt = cgi.escape(txt)
592 index = txt.find("''")
597 if txt.startswith("'''"):
603 self.bold = not self.bold
611 self.ital = not self.ital
614 def linkify(self, txt):
618 index = txt.find("[")
620 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
621 res_plain += self.formatted(txt[:index], False)
622 res_html += self.formatted(txt[:index], True)
624 if txt.startswith("[["):
625 index = txt.find("]]")
627 warn_or_exception("Unterminated ]]")
629 if self.linkResolver:
630 url, urltext = self.linkResolver(url)
633 res_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
635 txt = txt[index + 2:]
637 index = txt.find("]")
639 warn_or_exception("Unterminated ]")
641 index2 = url.find(' ')
645 urltxt = url[index2 + 1:]
648 warn_or_exception("Url title is just the URL - use [url]")
649 res_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
652 res_plain += ' (' + url + ')'
653 txt = txt[index + 1:]
655 def addtext(self, txt):
656 p, h = self.linkify(txt)
659 def parseline(self, line):
662 elif line.startswith('* '):
663 self.endcur([self.stUL])
664 if self.state != self.stUL:
665 self.html.write('<ul>')
666 self.state = self.stUL
667 if self.laststate != self.stNONE:
668 self.text.write('\n\n')
670 self.text.write('\n')
671 self.text.write(line)
672 self.html.write('<li>')
673 self.addtext(line[1:])
674 self.html.write('</li>')
675 elif line.startswith('# '):
676 self.endcur([self.stOL])
677 if self.state != self.stOL:
678 self.html.write('<ol>')
679 self.state = self.stOL
680 if self.laststate != self.stNONE:
681 self.text.write('\n\n')
683 self.text.write('\n')
684 self.text.write(line)
685 self.html.write('<li>')
686 self.addtext(line[1:])
687 self.html.write('</li>')
689 self.para_lines.append(line)
690 self.endcur([self.stPARA])
691 if self.state == self.stNONE:
692 self.state = self.stPARA
693 if self.laststate != self.stNONE:
694 self.text.write('\n\n')
695 self.html.write('<p>')
699 self.text_txt = self.text.getvalue()
700 self.text_html = self.html.getvalue()
705 # Parse multiple lines of description as written in a metadata file, returning
706 # a single string in text format and wrapped to 80 columns.
707 def description_txt(s):
708 ps = DescriptionFormatter(None)
709 for line in s.splitlines():
715 # Parse multiple lines of description as written in a metadata file, returning
716 # a single string in wiki format. Used for the Maintainer Notes field as well,
717 # because it's the same format.
718 def description_wiki(s):
722 # Parse multiple lines of description as written in a metadata file, returning
723 # a single string in HTML format.
724 def description_html(s, linkres):
725 ps = DescriptionFormatter(linkres)
726 for line in s.splitlines():
732 def parse_srclib(metadatapath):
736 # Defaults for fields that come from metadata
737 thisinfo['Repo Type'] = ''
738 thisinfo['Repo'] = ''
739 thisinfo['Subdir'] = None
740 thisinfo['Prepare'] = None
742 if not os.path.exists(metadatapath):
745 metafile = open(metadatapath, "r", encoding='utf-8')
748 for line in metafile:
750 line = line.rstrip('\r\n')
751 if not line or line.startswith("#"):
755 f, v = line.split(':', 1)
757 warn_or_exception("Invalid metadata in %s:%d" % (line, n))
760 thisinfo[f] = v.split(',')
770 """Read all srclib metadata.
772 The information read will be accessible as metadata.srclibs, which is a
773 dictionary, keyed on srclib name, with the values each being a dictionary
774 in the same format as that returned by the parse_srclib function.
776 A MetaDataException is raised if there are any problems with the srclib
781 # They were already loaded
782 if srclibs is not None:
788 if not os.path.exists(srcdir):
791 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
792 srclibname = os.path.basename(metadatapath[:-4])
793 srclibs[srclibname] = parse_srclib(metadatapath)
796 def read_metadata(xref=True, check_vcs=[]):
798 Read all metadata. Returns a list of 'app' objects (which are dictionaries as
799 returned by the parse_txt_metadata function.
801 check_vcs is the list of packageNames to check for .fdroid.yml in source
804 # Always read the srclibs before the apps, since they can use a srlib as
805 # their source repository.
810 for basedir in ('metadata', 'tmp'):
811 if not os.path.exists(basedir):
814 # If there are multiple metadata files for a single appid, then the first
815 # file that is parsed wins over all the others, and the rest throw an
816 # exception. So the original .txt format is parsed first, at least until
817 # newer formats stabilize.
819 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
820 + glob.glob(os.path.join('metadata', '*.json'))
821 + glob.glob(os.path.join('metadata', '*.xml'))
822 + glob.glob(os.path.join('metadata', '*.yml'))
823 + glob.glob('.fdroid.json')
824 + glob.glob('.fdroid.xml')
825 + glob.glob('.fdroid.yml')):
826 packageName, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
827 if packageName in apps:
828 warn_or_exception("Found multiple metadata files for " + packageName)
829 app = parse_metadata(metadatapath, packageName in check_vcs)
834 # Parse all descriptions at load time, just to ensure cross-referencing
835 # errors are caught early rather than when they hit the build server.
838 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
839 warn_or_exception("Cannot resolve app id " + appid)
841 for appid, app in apps.items():
843 description_html(app.Description, linkres)
844 except MetaDataException as e:
845 warn_or_exception("Problem with description of " + appid +
851 # Port legacy ';' separators
852 list_sep = re.compile(r'[,;]')
855 def split_list_values(s):
857 for v in re.split(list_sep, s):
867 def get_default_app_info(metadatapath=None):
868 if metadatapath is None:
871 appid, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
873 if appid == '.fdroid': # we have local metadata in the app's source
874 if os.path.exists('AndroidManifest.xml'):
875 manifestroot = fdroidserver.common.parse_xml('AndroidManifest.xml')
877 pattern = re.compile(""".*manifest\.srcFile\s+'AndroidManifest\.xml'.*""")
878 for root, dirs, files in os.walk(os.getcwd()):
879 if 'build.gradle' in files:
880 p = os.path.join(root, 'build.gradle')
881 with open(p, 'rb') as f:
883 m = pattern.search(data)
885 logging.debug('Using: ' + os.path.join(root, 'AndroidManifest.xml'))
886 manifestroot = fdroidserver.common.parse_xml(os.path.join(root, 'AndroidManifest.xml'))
888 if manifestroot is None:
889 warn_or_exception("Cannot find a packageName for {0}!".format(metadatapath))
890 appid = manifestroot.attrib['package']
893 app.metadatapath = metadatapath
894 if appid is not None:
900 def sorted_builds(builds):
901 return sorted(builds, key=lambda build: int(build.vercode))
904 esc_newlines = re.compile(r'\\( |\n)')
907 # This function uses __dict__ to be faster
908 def post_metadata_parse(app):
910 for k in app._modified:
912 if type(v) in (float, int):
913 app.__dict__[k] = str(v)
915 for build in app.builds:
916 for k in build._modified:
917 v = build.__dict__[k]
918 if type(v) in (float, int):
919 build.__dict__[k] = str(v)
923 if ftype == TYPE_SCRIPT:
924 build.__dict__[k] = re.sub(esc_newlines, '', v).lstrip().rstrip()
925 elif ftype == TYPE_BOOL:
926 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
927 if isinstance(v, str):
928 build.__dict__[k] = _decode_bool(v)
929 elif ftype == TYPE_STRING:
930 if isinstance(v, bool) and v:
931 build.__dict__[k] = 'yes'
932 elif ftype == TYPE_LIST:
933 if isinstance(v, bool) and v:
934 build.__dict__[k] = ['yes']
935 elif isinstance(v, str):
936 build.__dict__[k] = [v]
938 if not app.Description:
939 app.Description = 'No description available'
941 app.builds = sorted_builds(app.builds)
944 # Parse metadata for a single application.
946 # 'metadatapath' - the filename to read. The package id for the application comes
947 # from this filename. Pass None to get a blank entry.
949 # Returns a dictionary containing all the details of the application. There are
950 # two major kinds of information in the dictionary. Keys beginning with capital
951 # letters correspond directory to identically named keys in the metadata file.
952 # Keys beginning with lower case letters are generated in one way or another,
953 # and are not found verbatim in the metadata.
955 # Known keys not originating from the metadata are:
957 # 'builds' - a list of dictionaries containing build information
958 # for each defined build
959 # 'comments' - a list of comments from the metadata file. Each is
960 # a list of the form [field, comment] where field is
961 # the name of the field it preceded in the metadata
962 # file. Where field is None, the comment goes at the
963 # end of the file. Alternatively, 'build:version' is
964 # for a comment before a particular build version.
965 # 'descriptionlines' - original lines of description as formatted in the
970 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
971 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
975 if bool_true.match(s):
977 if bool_false.match(s):
979 warn_or_exception("Invalid bool '%s'" % s)
982 def parse_metadata(metadatapath, check_vcs=False):
983 '''parse metadata file, optionally checking the git repo for metadata first'''
985 _, ext = fdroidserver.common.get_extension(metadatapath)
986 accepted = fdroidserver.common.config['accepted_formats']
987 if ext not in accepted:
988 warn_or_exception('"%s" is not an accepted format, convert to: %s' % (
989 metadatapath, ', '.join(accepted)))
992 app.metadatapath = metadatapath
993 name, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
994 if name == '.fdroid':
999 with open(metadatapath, 'r', encoding='utf-8') as mf:
1001 parse_txt_metadata(mf, app)
1003 parse_json_metadata(mf, app)
1005 parse_xml_metadata(mf, app)
1007 parse_yaml_metadata(mf, app)
1009 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1011 if check_vcs and app.Repo:
1012 build_dir = fdroidserver.common.get_build_dir(app)
1013 metadata_in_repo = os.path.join(build_dir, '.fdroid.yml')
1014 if not os.path.isfile(metadata_in_repo):
1015 vcs, build_dir = fdroidserver.common.setup_vcs(app)
1016 vcs.gotorevision('HEAD') # HEAD since we can't know where else to go
1017 if os.path.isfile(metadata_in_repo):
1018 logging.debug('Including metadata from ' + metadata_in_repo)
1019 app.update(parse_metadata(metadata_in_repo))
1021 post_metadata_parse(app)
1025 build = app.builds[-1]
1027 root_dir = build.subdir
1030 paths = fdroidserver.common.manifest_paths(root_dir, build.gradle)
1031 _, _, app.id = fdroidserver.common.parse_androidmanifests(paths, app)
1036 def parse_json_metadata(mf, app):
1038 # fdroid metadata is only strings and booleans, no floats or ints.
1039 # TODO create schema using https://pypi.python.org/pypi/jsonschema
1040 jsoninfo = json.load(mf, parse_int=lambda s: s,
1041 parse_float=lambda s: s)
1042 app.update_fields(jsoninfo)
1043 for f in ['Description', 'Maintainer Notes']:
1044 v = app.get_field(f)
1045 app.set_field(f, '\n'.join(v))
1049 def parse_xml_metadata(mf, app):
1051 tree = ElementTree.ElementTree(file=mf)
1052 root = tree.getroot()
1054 if root.tag != 'resources':
1055 warn_or_exception('resources file does not have root element <resources/>')
1058 if child.tag != 'builds':
1059 # builds does not have name="" attrib
1060 name = child.attrib['name']
1062 if child.tag == 'string':
1063 app.set_field(name, child.text)
1064 elif child.tag == 'string-array':
1066 app.append_field(name, item.text)
1067 elif child.tag == 'builds':
1071 build.set_flag(key.tag, key.text)
1072 app.builds.append(build)
1074 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
1075 if not isinstance(app.RequiresRoot, bool):
1076 app.RequiresRoot = app.RequiresRoot == 'true'
1081 def parse_yaml_metadata(mf, app):
1083 yamlinfo = yaml.load(mf, Loader=YamlLoader)
1084 app.update_fields(yamlinfo)
1088 build_line_sep = re.compile(r'(?<!\\),')
1089 build_cont = re.compile(r'^[ \t]')
1092 def parse_txt_metadata(mf, app):
1096 def add_buildflag(p, build):
1098 warn_or_exception("Empty build flag at {1}"
1099 .format(buildlines[0], linedesc))
1100 bv = p.split('=', 1)
1102 warn_or_exception("Invalid build flag at {0} in {1}"
1103 .format(buildlines[0], linedesc))
1109 pv = split_list_values(pv)
1110 build.set_flag(pk, pv)
1111 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1112 build.set_flag(pk, pv)
1113 elif t == TYPE_BOOL:
1114 build.set_flag(pk, _decode_bool(pv))
1116 def parse_buildline(lines):
1118 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1120 warn_or_exception("Invalid build format: " + v + " in " + mf.name)
1122 build.version = parts[0]
1123 build.vercode = parts[1]
1124 if parts[2].startswith('!'):
1125 # For backwards compatibility, handle old-style disabling,
1126 # including attempting to extract the commit from the message
1127 build.disable = parts[2][1:]
1128 commit = 'unknown - see disabled'
1129 index = parts[2].rfind('at ')
1131 commit = parts[2][index + 3:]
1132 if commit.endswith(')'):
1133 commit = commit[:-1]
1134 build.commit = commit
1136 build.commit = parts[2]
1138 add_buildflag(p, build)
1142 def add_comments(key):
1145 app.comments[key] = list(curcomments)
1150 multiline_lines = []
1158 linedesc = "%s:%d" % (mf.name, c)
1159 line = line.rstrip('\r\n')
1161 if build_cont.match(line):
1162 if line.endswith('\\'):
1163 buildlines.append(line[:-1].lstrip())
1165 buildlines.append(line.lstrip())
1166 bl = ''.join(buildlines)
1167 add_buildflag(bl, build)
1170 if not build.commit and not build.disable:
1171 warn_or_exception("No commit specified for {0} in {1}"
1172 .format(build.version, linedesc))
1174 app.builds.append(build)
1175 add_comments('build:' + build.vercode)
1181 if line.startswith("#"):
1182 curcomments.append(line[1:].strip())
1185 f, v = line.split(':', 1)
1187 warn_or_exception("Invalid metadata in " + linedesc)
1189 # Translate obsolete fields...
1190 if f == 'Market Version':
1191 f = 'Current Version'
1192 if f == 'Market Version Code':
1193 f = 'Current Version Code'
1195 ftype = fieldtype(f)
1196 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1198 if ftype == TYPE_MULTILINE:
1201 warn_or_exception("Unexpected text on same line as "
1202 + f + " in " + linedesc)
1203 elif ftype == TYPE_STRING:
1205 elif ftype == TYPE_LIST:
1206 app.set_field(f, split_list_values(v))
1207 elif ftype == TYPE_BUILD:
1208 if v.endswith("\\"):
1211 buildlines.append(v[:-1])
1213 build = parse_buildline([v])
1214 app.builds.append(build)
1215 add_comments('build:' + app.builds[-1].vercode)
1216 elif ftype == TYPE_BUILD_V2:
1219 warn_or_exception('Build should have comma-separated',
1220 'version and vercode,',
1221 'not "{0}", in {1}'.format(v, linedesc))
1223 build.version = vv[0]
1224 build.vercode = vv[1]
1225 if build.vercode in vc_seen:
1226 warn_or_exception('Duplicate build recipe found for vercode %s in %s'
1227 % (build.vercode, linedesc))
1228 vc_seen.add(build.vercode)
1231 elif ftype == TYPE_OBSOLETE:
1232 pass # Just throw it away!
1234 warn_or_exception("Unrecognised field '" + f + "' in " + linedesc)
1235 elif mode == 1: # Multiline field
1238 app.set_field(f, '\n'.join(multiline_lines))
1239 del multiline_lines[:]
1241 multiline_lines.append(line)
1242 elif mode == 2: # Line continuation mode in Build Version
1243 if line.endswith("\\"):
1244 buildlines.append(line[:-1])
1246 buildlines.append(line)
1247 build = parse_buildline(buildlines)
1248 app.builds.append(build)
1249 add_comments('build:' + app.builds[-1].vercode)
1253 # Mode at end of file should always be 0
1255 warn_or_exception(f + " not terminated in " + mf.name)
1257 warn_or_exception("Unterminated continuation in " + mf.name)
1259 warn_or_exception("Unterminated build in " + mf.name)
1264 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1266 def w_comments(key):
1267 if key not in app.comments:
1269 for line in app.comments[key]:
1272 def w_field_always(f, v=None):
1274 v = app.get_field(f)
1278 def w_field_nonempty(f, v=None):
1280 v = app.get_field(f)
1285 w_field_nonempty('Disabled')
1286 w_field_nonempty('AntiFeatures')
1287 w_field_nonempty('Provides')
1288 w_field_always('Categories')
1289 w_field_always('License')
1290 w_field_nonempty('Author Name')
1291 w_field_nonempty('Author Email')
1292 w_field_always('Web Site')
1293 w_field_always('Source Code')
1294 w_field_always('Issue Tracker')
1295 w_field_nonempty('Changelog')
1296 w_field_nonempty('Donate')
1297 w_field_nonempty('FlattrID')
1298 w_field_nonempty('Bitcoin')
1299 w_field_nonempty('Litecoin')
1301 w_field_nonempty('Name')
1302 w_field_nonempty('Auto Name')
1303 w_field_always('Summary')
1304 w_field_always('Description', description_txt(app.Description))
1306 if app.RequiresRoot:
1307 w_field_always('Requires Root', 'yes')
1310 w_field_always('Repo Type')
1311 w_field_always('Repo')
1313 w_field_always('Binaries')
1316 for build in app.builds:
1318 if build.version == "Ignore":
1321 w_comments('build:' + build.vercode)
1325 if app.MaintainerNotes:
1326 w_field_always('Maintainer Notes', app.MaintainerNotes)
1329 w_field_nonempty('Archive Policy')
1330 w_field_always('Auto Update Mode')
1331 w_field_always('Update Check Mode')
1332 w_field_nonempty('Update Check Ignore')
1333 w_field_nonempty('Vercode Operation')
1334 w_field_nonempty('Update Check Name')
1335 w_field_nonempty('Update Check Data')
1336 if app.CurrentVersion:
1337 w_field_always('Current Version')
1338 w_field_always('Current Version Code')
1339 if app.NoSourceSince:
1341 w_field_always('No Source Since')
1345 # Write a metadata file in txt format.
1347 # 'mf' - Writer interface (file, StringIO, ...)
1348 # 'app' - The app data
1349 def write_txt(mf, app):
1351 def w_comment(line):
1352 mf.write("# %s\n" % line)
1358 elif t == TYPE_MULTILINE:
1359 v = '\n' + v + '\n.'
1360 mf.write("%s:%s\n" % (f, v))
1363 mf.write("Build:%s,%s\n" % (build.version, build.vercode))
1365 for f in build_flags_order:
1366 v = build.get_flag(f)
1371 mf.write(' %s=' % f)
1372 if t == TYPE_STRING:
1374 elif t == TYPE_BOOL:
1376 elif t == TYPE_SCRIPT:
1378 for s in v.split(' && '):
1382 mf.write(' && \\\n ')
1384 elif t == TYPE_LIST:
1385 mf.write(','.join(v))
1389 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1392 def write_yaml(mf, app):
1394 def w_comment(line):
1395 mf.write("# %s\n" % line)
1400 if any(c in v for c in [': ', '%', '@', '*']):
1401 return "'" + v.replace("'", "''") + "'"
1404 def w_field(f, v, prefix='', t=None):
1411 v += prefix + ' - ' + escape(e) + '\n'
1412 elif t == TYPE_MULTILINE:
1414 for l in v.splitlines():
1416 v += prefix + ' ' + l + '\n'
1419 elif t == TYPE_BOOL:
1421 elif t == TYPE_SCRIPT:
1422 cmds = [s + '&& \\' for s in v.split('&& ')]
1424 cmds[-1] = cmds[-1][:-len('&& \\')]
1425 w_field(f, cmds, prefix, 'multiline')
1428 v = ' ' + escape(v) + '\n'
1441 mf.write("builds:\n")
1444 w_field('versionName', build.version, ' - ', TYPE_STRING)
1445 w_field('versionCode', build.vercode, ' ', TYPE_STRING)
1446 for f in build_flags_order:
1447 v = build.get_flag(f)
1451 w_field(f, v, ' ', flagtype(f))
1453 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1456 def write_metadata(metadatapath, app):
1457 _, ext = fdroidserver.common.get_extension(metadatapath)
1458 accepted = fdroidserver.common.config['accepted_formats']
1459 if ext not in accepted:
1460 warn_or_exception('Cannot write "%s", not an accepted format, use: %s'
1461 % (metadatapath, ', '.join(accepted)))
1463 with open(metadatapath, 'w', encoding='utf8') as mf:
1465 return write_txt(mf, app)
1467 return write_yaml(mf, app)
1468 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1471 def add_metadata_arguments(parser):
1472 '''add common command line flags related to metadata processing'''
1473 parser.add_argument("-W", default='error',
1474 help="force errors to be warnings, or ignore")