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 import fdroidserver.common
41 warnings_action = None
44 class MetaDataException(Exception):
46 def __init__(self, value):
53 def warn_or_exception(value):
54 '''output warning or Exception depending on -W'''
55 if warnings_action == 'ignore':
57 elif warnings_action == 'error':
58 raise MetaDataException(value)
63 # To filter which ones should be written to the metadata files if
93 'Update Check Ignore',
98 'Current Version Code',
101 'comments', # For formats that don't do inline comments
102 'builds', # For formats that do builds as a list
110 self.AntiFeatures = []
112 self.Categories = ['None']
113 self.License = 'Unknown'
114 self.AuthorName = None
115 self.AuthorEmail = None
118 self.IssueTracker = ''
127 self.Description = ''
128 self.RequiresRoot = False
132 self.MaintainerNotes = ''
133 self.ArchivePolicy = None
134 self.AutoUpdateMode = 'None'
135 self.UpdateCheckMode = 'None'
136 self.UpdateCheckIgnore = None
137 self.VercodeOperation = None
138 self.UpdateCheckName = None
139 self.UpdateCheckData = None
140 self.CurrentVersion = ''
141 self.CurrentVersionCode = None
142 self.NoSourceSince = ''
145 self.metadatapath = None
149 self.lastupdated = None
150 self._modified = set()
153 def field_to_attr(cls, f):
155 Translates human-readable field names to attribute names, e.g.
156 'Auto Name' to 'AutoName'
158 return f.replace(' ', '')
161 def attr_to_field(cls, k):
163 Translates attribute names to human-readable field names, e.g.
164 'AutoName' to 'Auto Name'
168 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
171 def field_dict(self):
173 Constructs an old-fashioned dict with the human-readable field
174 names. Should only be used for tests.
177 for k, v in self.__dict__.items():
181 b = {k: v for k, v in build.__dict__.items() if not k.startswith('_')}
182 d['builds'].append(b)
183 elif not k.startswith('_'):
184 f = App.attr_to_field(k)
188 def get_field(self, f):
189 """Gets the value associated to a field name, e.g. 'Auto Name'"""
190 if f not in app_fields:
191 warn_or_exception('Unrecognised app field: ' + f)
192 k = App.field_to_attr(f)
193 return getattr(self, k)
195 def set_field(self, f, v):
196 """Sets the value associated to a field name, e.g. 'Auto Name'"""
197 if f not in app_fields:
198 warn_or_exception('Unrecognised app field: ' + f)
199 k = App.field_to_attr(f)
201 self._modified.add(k)
203 def append_field(self, f, v):
204 """Appends to the value associated to a field name, e.g. 'Auto Name'"""
205 if f not in app_fields:
206 warn_or_exception('Unrecognised app field: ' + f)
207 k = App.field_to_attr(f)
208 if k not in self.__dict__:
209 self.__dict__[k] = [v]
211 self.__dict__[k].append(v)
213 def update_fields(self, d):
214 '''Like dict.update(), but using human-readable field names'''
215 for f, v in d.items():
219 build.update_flags(b)
220 self.builds.append(build)
225 '''Like dict.update()'''
226 for k, v in d.__dict__.items():
232 del(b.__dict__['_modified'])
233 build.update_flags(b.__dict__)
234 self.builds.append(build)
237 self._modified.add(k)
239 def get_last_build(self):
240 if len(self.builds) > 0:
241 return self.builds[-1]
257 'Description': TYPE_MULTILINE,
258 'Maintainer Notes': TYPE_MULTILINE,
259 'Categories': TYPE_LIST,
260 'AntiFeatures': TYPE_LIST,
261 'Build Version': TYPE_BUILD,
262 'Build': TYPE_BUILD_V2,
263 'Use Built': TYPE_OBSOLETE,
268 if name in fieldtypes:
269 return fieldtypes[name]
273 # In the order in which they are laid out on files
274 build_flags_order = [
307 build_flags = set(build_flags_order + ['version', 'vercode'])
316 self.submodules = False
324 self.oldsdkloc = False
326 self.forceversion = False
327 self.forcevercode = False
338 self.preassemble = []
339 self.gradleprops = []
340 self.antcommands = []
341 self.novcheck = False
343 self._modified = set()
345 def get_flag(self, f):
346 if f not in build_flags:
347 warn_or_exception('Unrecognised build flag: ' + f)
348 return getattr(self, f)
350 def set_flag(self, f, v):
351 if f == 'versionName':
353 if f == 'versionCode':
355 if f not in build_flags:
356 warn_or_exception('Unrecognised build flag: ' + f)
358 self._modified.add(f)
360 def append_flag(self, f, v):
361 if f not in build_flags:
362 warn_or_exception('Unrecognised build flag: ' + f)
363 if f not in self.__dict__:
364 self.__dict__[f] = [v]
366 self.__dict__[f].append(v)
368 def build_method(self):
369 for f in ['maven', 'gradle', 'kivy']:
376 # like build_method, but prioritize output=
377 def output_method(self):
380 for f in ['maven', 'gradle', 'kivy']:
388 version = 'r12b' # falls back to latest
389 paths = fdroidserver.common.config['ndk_paths']
390 if version not in paths:
392 return paths[version]
394 def update_flags(self, d):
395 for f, v in d.items():
400 'extlibs': TYPE_LIST,
401 'srclibs': TYPE_LIST,
404 'buildjni': TYPE_LIST,
405 'preassemble': TYPE_LIST,
407 'scanignore': TYPE_LIST,
408 'scandelete': TYPE_LIST,
410 'antcommands': TYPE_LIST,
411 'gradleprops': TYPE_LIST,
413 'prebuild': TYPE_SCRIPT,
414 'build': TYPE_SCRIPT,
415 'submodules': TYPE_BOOL,
416 'oldsdkloc': TYPE_BOOL,
417 'forceversion': TYPE_BOOL,
418 'forcevercode': TYPE_BOOL,
419 'novcheck': TYPE_BOOL,
424 if name in flagtypes:
425 return flagtypes[name]
429 class FieldValidator():
431 Designates App metadata field types and checks that it matches
433 'name' - The long name of the field type
434 'matching' - List of possible values or regex expression
435 'sep' - Separator to use if value may be a list
436 'fields' - Metadata fields (Field:Value) of this type
439 def __init__(self, name, matching, fields):
441 self.matching = matching
442 self.compiled = re.compile(matching)
445 def check(self, v, appid):
453 if not self.compiled.match(v):
454 warn_or_exception("'%s' is not a valid %s in %s. Regex pattern: %s"
455 % (v, self.name, appid, self.matching))
458 # Generic value types
460 FieldValidator("Hexadecimal",
464 FieldValidator("HTTP link",
466 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"]),
468 FieldValidator("Email",
469 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
472 FieldValidator("Bitcoin address",
473 r'^[a-zA-Z0-9]{27,34}$',
476 FieldValidator("Litecoin address",
477 r'^L[a-zA-Z0-9]{33}$',
480 FieldValidator("Repo Type",
481 r'^(git|git-svn|svn|hg|bzr|srclib)$',
484 FieldValidator("Binaries",
488 FieldValidator("Archive Policy",
489 r'^[0-9]+ versions$',
492 FieldValidator("Anti-Feature",
493 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets|KnownVuln)$',
496 FieldValidator("Auto Update Mode",
497 r"^(Version .+|None)$",
500 FieldValidator("Update Check Mode",
501 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
506 # Check an app's metadata information for integrity errors
507 def check_metadata(app):
510 if k not in app._modified:
512 v.check(app.__dict__[k], app.id)
515 # Formatter for descriptions. Create an instance, and call parseline() with
516 # each line of the description source from the metadata. At the end, call
517 # end() and then text_txt and text_html will contain the result.
518 class DescriptionFormatter:
525 def __init__(self, linkres):
528 self.state = self.stNONE
529 self.laststate = self.stNONE
532 self.html = io.StringIO()
533 self.text = io.StringIO()
535 self.linkResolver = None
536 self.linkResolver = linkres
538 def endcur(self, notstates=None):
539 if notstates and self.state in notstates:
541 if self.state == self.stPARA:
543 elif self.state == self.stUL:
545 elif self.state == self.stOL:
549 self.laststate = self.state
550 self.state = self.stNONE
551 whole_para = ' '.join(self.para_lines)
552 self.addtext(whole_para)
553 wrapped = textwrap.fill(whole_para, 80,
554 break_long_words=False,
555 break_on_hyphens=False)
556 self.text.write(wrapped)
557 self.html.write('</p>')
558 del self.para_lines[:]
561 self.html.write('</ul>')
562 self.laststate = self.state
563 self.state = self.stNONE
566 self.html.write('</ol>')
567 self.laststate = self.state
568 self.state = self.stNONE
570 def formatted(self, txt, html):
573 txt = cgi.escape(txt)
575 index = txt.find("''")
580 if txt.startswith("'''"):
586 self.bold = not self.bold
594 self.ital = not self.ital
597 def linkify(self, txt):
601 index = txt.find("[")
603 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
604 res_plain += self.formatted(txt[:index], False)
605 res_html += self.formatted(txt[:index], True)
607 if txt.startswith("[["):
608 index = txt.find("]]")
610 warn_or_exception("Unterminated ]]")
612 if self.linkResolver:
613 url, urltext = self.linkResolver(url)
616 res_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
618 txt = txt[index + 2:]
620 index = txt.find("]")
622 warn_or_exception("Unterminated ]")
624 index2 = url.find(' ')
628 urltxt = url[index2 + 1:]
631 warn_or_exception("Url title is just the URL - use [url]")
632 res_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
635 res_plain += ' (' + url + ')'
636 txt = txt[index + 1:]
638 def addtext(self, txt):
639 p, h = self.linkify(txt)
642 def parseline(self, line):
645 elif line.startswith('* '):
646 self.endcur([self.stUL])
647 if self.state != self.stUL:
648 self.html.write('<ul>')
649 self.state = self.stUL
650 if self.laststate != self.stNONE:
651 self.text.write('\n\n')
653 self.text.write('\n')
654 self.text.write(line)
655 self.html.write('<li>')
656 self.addtext(line[1:])
657 self.html.write('</li>')
658 elif line.startswith('# '):
659 self.endcur([self.stOL])
660 if self.state != self.stOL:
661 self.html.write('<ol>')
662 self.state = self.stOL
663 if self.laststate != self.stNONE:
664 self.text.write('\n\n')
666 self.text.write('\n')
667 self.text.write(line)
668 self.html.write('<li>')
669 self.addtext(line[1:])
670 self.html.write('</li>')
672 self.para_lines.append(line)
673 self.endcur([self.stPARA])
674 if self.state == self.stNONE:
675 self.state = self.stPARA
676 if self.laststate != self.stNONE:
677 self.text.write('\n\n')
678 self.html.write('<p>')
682 self.text_txt = self.text.getvalue()
683 self.text_html = self.html.getvalue()
688 # Parse multiple lines of description as written in a metadata file, returning
689 # a single string in text format and wrapped to 80 columns.
690 def description_txt(s):
691 ps = DescriptionFormatter(None)
692 for line in s.splitlines():
698 # Parse multiple lines of description as written in a metadata file, returning
699 # a single string in wiki format. Used for the Maintainer Notes field as well,
700 # because it's the same format.
701 def description_wiki(s):
705 # Parse multiple lines of description as written in a metadata file, returning
706 # a single string in HTML format.
707 def description_html(s, linkres):
708 ps = DescriptionFormatter(linkres)
709 for line in s.splitlines():
715 def parse_srclib(metadatapath):
719 # Defaults for fields that come from metadata
720 thisinfo['Repo Type'] = ''
721 thisinfo['Repo'] = ''
722 thisinfo['Subdir'] = None
723 thisinfo['Prepare'] = None
725 if not os.path.exists(metadatapath):
728 metafile = open(metadatapath, "r", encoding='utf-8')
731 for line in metafile:
733 line = line.rstrip('\r\n')
734 if not line or line.startswith("#"):
738 f, v = line.split(':', 1)
740 warn_or_exception("Invalid metadata in %s:%d" % (line, n))
743 thisinfo[f] = v.split(',')
753 """Read all srclib metadata.
755 The information read will be accessible as metadata.srclibs, which is a
756 dictionary, keyed on srclib name, with the values each being a dictionary
757 in the same format as that returned by the parse_srclib function.
759 A MetaDataException is raised if there are any problems with the srclib
764 # They were already loaded
765 if srclibs is not None:
771 if not os.path.exists(srcdir):
774 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
775 srclibname = os.path.basename(metadatapath[:-4])
776 srclibs[srclibname] = parse_srclib(metadatapath)
779 def read_metadata(xref=True, check_vcs=[]):
781 Read all metadata. Returns a list of 'app' objects (which are dictionaries as
782 returned by the parse_txt_metadata function.
784 check_vcs is the list of packageNames to check for .fdroid.yml in source
787 # Always read the srclibs before the apps, since they can use a srlib as
788 # their source repository.
793 for basedir in ('metadata', 'tmp'):
794 if not os.path.exists(basedir):
797 # If there are multiple metadata files for a single appid, then the first
798 # file that is parsed wins over all the others, and the rest throw an
799 # exception. So the original .txt format is parsed first, at least until
800 # newer formats stabilize.
802 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
803 + glob.glob(os.path.join('metadata', '*.json'))
804 + glob.glob(os.path.join('metadata', '*.yml'))
805 + glob.glob('.fdroid.json')
806 + glob.glob('.fdroid.yml')):
807 packageName, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
808 if packageName in apps:
809 warn_or_exception("Found multiple metadata files for " + packageName)
810 app = parse_metadata(metadatapath, packageName in check_vcs)
815 # Parse all descriptions at load time, just to ensure cross-referencing
816 # errors are caught early rather than when they hit the build server.
819 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
820 warn_or_exception("Cannot resolve app id " + appid)
822 for appid, app in apps.items():
824 description_html(app.Description, linkres)
825 except MetaDataException as e:
826 warn_or_exception("Problem with description of " + appid +
832 # Port legacy ';' separators
833 list_sep = re.compile(r'[,;]')
836 def split_list_values(s):
838 for v in re.split(list_sep, s):
848 def get_default_app_info(metadatapath=None):
849 if metadatapath is None:
852 appid, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
854 if appid == '.fdroid': # we have local metadata in the app's source
855 if os.path.exists('AndroidManifest.xml'):
856 manifestroot = fdroidserver.common.parse_xml('AndroidManifest.xml')
858 pattern = re.compile(""".*manifest\.srcFile\s+'AndroidManifest\.xml'.*""")
859 for root, dirs, files in os.walk(os.getcwd()):
860 if 'build.gradle' in files:
861 p = os.path.join(root, 'build.gradle')
862 with open(p, 'rb') as f:
864 m = pattern.search(data)
866 logging.debug('Using: ' + os.path.join(root, 'AndroidManifest.xml'))
867 manifestroot = fdroidserver.common.parse_xml(os.path.join(root, 'AndroidManifest.xml'))
869 if manifestroot is None:
870 warn_or_exception("Cannot find a packageName for {0}!".format(metadatapath))
871 appid = manifestroot.attrib['package']
874 app.metadatapath = metadatapath
875 if appid is not None:
881 def sorted_builds(builds):
882 return sorted(builds, key=lambda build: int(build.vercode))
885 esc_newlines = re.compile(r'\\( |\n)')
888 # This function uses __dict__ to be faster
889 def post_metadata_parse(app):
891 for k in app._modified:
893 if type(v) in (float, int):
894 app.__dict__[k] = str(v)
896 for build in app.builds:
897 for k in build._modified:
898 v = build.__dict__[k]
899 if type(v) in (float, int):
900 build.__dict__[k] = str(v)
904 if ftype == TYPE_SCRIPT:
905 build.__dict__[k] = re.sub(esc_newlines, '', v).lstrip().rstrip()
906 elif ftype == TYPE_BOOL:
907 # TODO handle this using <xsd:element type="xsd:boolean> in a schema
908 if isinstance(v, str):
909 build.__dict__[k] = _decode_bool(v)
910 elif ftype == TYPE_STRING:
911 if isinstance(v, bool) and v:
912 build.__dict__[k] = 'yes'
913 elif ftype == TYPE_LIST:
914 if isinstance(v, bool) and v:
915 build.__dict__[k] = ['yes']
916 elif isinstance(v, str):
917 build.__dict__[k] = [v]
919 if not app.Description:
920 app.Description = 'No description available'
922 app.builds = sorted_builds(app.builds)
925 # Parse metadata for a single application.
927 # 'metadatapath' - the filename to read. The package id for the application comes
928 # from this filename. Pass None to get a blank entry.
930 # Returns a dictionary containing all the details of the application. There are
931 # two major kinds of information in the dictionary. Keys beginning with capital
932 # letters correspond directory to identically named keys in the metadata file.
933 # Keys beginning with lower case letters are generated in one way or another,
934 # and are not found verbatim in the metadata.
936 # Known keys not originating from the metadata are:
938 # 'builds' - a list of dictionaries containing build information
939 # for each defined build
940 # 'comments' - a list of comments from the metadata file. Each is
941 # a list of the form [field, comment] where field is
942 # the name of the field it preceded in the metadata
943 # file. Where field is None, the comment goes at the
944 # end of the file. Alternatively, 'build:version' is
945 # for a comment before a particular build version.
946 # 'descriptionlines' - original lines of description as formatted in the
951 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
952 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
956 if bool_true.match(s):
958 if bool_false.match(s):
960 warn_or_exception("Invalid bool '%s'" % s)
963 def parse_metadata(metadatapath, check_vcs=False):
964 '''parse metadata file, optionally checking the git repo for metadata first'''
966 _, ext = fdroidserver.common.get_extension(metadatapath)
967 accepted = fdroidserver.common.config['accepted_formats']
968 if ext not in accepted:
969 warn_or_exception('"%s" is not an accepted format, convert to: %s' % (
970 metadatapath, ', '.join(accepted)))
973 app.metadatapath = metadatapath
974 name, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
975 if name == '.fdroid':
980 with open(metadatapath, 'r', encoding='utf-8') as mf:
982 parse_txt_metadata(mf, app)
984 parse_json_metadata(mf, app)
986 parse_yaml_metadata(mf, app)
988 warn_or_exception('Unknown metadata format: %s' % metadatapath)
990 if check_vcs and app.Repo:
991 build_dir = fdroidserver.common.get_build_dir(app)
992 metadata_in_repo = os.path.join(build_dir, '.fdroid.yml')
993 if not os.path.isfile(metadata_in_repo):
994 vcs, build_dir = fdroidserver.common.setup_vcs(app)
995 vcs.gotorevision('HEAD') # HEAD since we can't know where else to go
996 if os.path.isfile(metadata_in_repo):
997 logging.debug('Including metadata from ' + metadata_in_repo)
998 app.update(parse_metadata(metadata_in_repo))
1000 post_metadata_parse(app)
1004 build = app.builds[-1]
1006 root_dir = build.subdir
1009 paths = fdroidserver.common.manifest_paths(root_dir, build.gradle)
1010 _, _, app.id = fdroidserver.common.parse_androidmanifests(paths, app)
1015 def parse_json_metadata(mf, app):
1017 # fdroid metadata is only strings and booleans, no floats or ints.
1018 # TODO create schema using https://pypi.python.org/pypi/jsonschema
1019 jsoninfo = json.load(mf, parse_int=lambda s: s,
1020 parse_float=lambda s: s)
1021 app.update_fields(jsoninfo)
1022 for f in ['Description', 'Maintainer Notes']:
1023 v = app.get_field(f)
1024 app.set_field(f, '\n'.join(v))
1028 def parse_yaml_metadata(mf, app):
1030 yamlinfo = yaml.load(mf, Loader=YamlLoader)
1031 app.update_fields(yamlinfo)
1035 build_line_sep = re.compile(r'(?<!\\),')
1036 build_cont = re.compile(r'^[ \t]')
1039 def parse_txt_metadata(mf, app):
1043 def add_buildflag(p, build):
1045 warn_or_exception("Empty build flag at {1}"
1046 .format(buildlines[0], linedesc))
1047 bv = p.split('=', 1)
1049 warn_or_exception("Invalid build flag at {0} in {1}"
1050 .format(buildlines[0], linedesc))
1056 pv = split_list_values(pv)
1057 build.set_flag(pk, pv)
1058 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1059 build.set_flag(pk, pv)
1060 elif t == TYPE_BOOL:
1061 build.set_flag(pk, _decode_bool(pv))
1063 def parse_buildline(lines):
1065 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1067 warn_or_exception("Invalid build format: " + v + " in " + mf.name)
1069 build.version = parts[0]
1070 build.vercode = parts[1]
1071 check_versionCode(build.vercode)
1073 if parts[2].startswith('!'):
1074 # For backwards compatibility, handle old-style disabling,
1075 # including attempting to extract the commit from the message
1076 build.disable = parts[2][1:]
1077 commit = 'unknown - see disabled'
1078 index = parts[2].rfind('at ')
1080 commit = parts[2][index + 3:]
1081 if commit.endswith(')'):
1082 commit = commit[:-1]
1083 build.commit = commit
1085 build.commit = parts[2]
1087 add_buildflag(p, build)
1091 def check_versionCode(versionCode):
1095 warn_or_exception('Invalid versionCode: "' + versionCode + '" is not an integer!')
1097 def add_comments(key):
1100 app.comments[key] = list(curcomments)
1105 multiline_lines = []
1113 linedesc = "%s:%d" % (mf.name, c)
1114 line = line.rstrip('\r\n')
1116 if build_cont.match(line):
1117 if line.endswith('\\'):
1118 buildlines.append(line[:-1].lstrip())
1120 buildlines.append(line.lstrip())
1121 bl = ''.join(buildlines)
1122 add_buildflag(bl, build)
1125 if not build.commit and not build.disable:
1126 warn_or_exception("No commit specified for {0} in {1}"
1127 .format(build.version, linedesc))
1129 app.builds.append(build)
1130 add_comments('build:' + build.vercode)
1136 if line.startswith("#"):
1137 curcomments.append(line[1:].strip())
1140 f, v = line.split(':', 1)
1142 warn_or_exception("Invalid metadata in " + linedesc)
1144 # Translate obsolete fields...
1145 if f == 'Market Version':
1146 f = 'Current Version'
1147 if f == 'Market Version Code':
1148 f = 'Current Version Code'
1150 ftype = fieldtype(f)
1151 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1153 if ftype == TYPE_MULTILINE:
1156 warn_or_exception("Unexpected text on same line as "
1157 + f + " in " + linedesc)
1158 elif ftype == TYPE_STRING:
1160 elif ftype == TYPE_LIST:
1161 app.set_field(f, split_list_values(v))
1162 elif ftype == TYPE_BUILD:
1163 if v.endswith("\\"):
1166 buildlines.append(v[:-1])
1168 build = parse_buildline([v])
1169 app.builds.append(build)
1170 add_comments('build:' + app.builds[-1].vercode)
1171 elif ftype == TYPE_BUILD_V2:
1174 warn_or_exception('Build should have comma-separated',
1175 'version and vercode,',
1176 'not "{0}", in {1}'.format(v, linedesc))
1178 build.version = vv[0]
1179 build.vercode = vv[1]
1180 check_versionCode(build.vercode)
1181 if build.vercode in vc_seen:
1182 warn_or_exception('Duplicate build recipe found for vercode %s in %s'
1183 % (build.vercode, linedesc))
1184 vc_seen.add(build.vercode)
1187 elif ftype == TYPE_OBSOLETE:
1188 pass # Just throw it away!
1190 warn_or_exception("Unrecognised field '" + f + "' in " + linedesc)
1191 elif mode == 1: # Multiline field
1194 app.set_field(f, '\n'.join(multiline_lines))
1195 del multiline_lines[:]
1197 multiline_lines.append(line)
1198 elif mode == 2: # Line continuation mode in Build Version
1199 if line.endswith("\\"):
1200 buildlines.append(line[:-1])
1202 buildlines.append(line)
1203 build = parse_buildline(buildlines)
1204 app.builds.append(build)
1205 add_comments('build:' + app.builds[-1].vercode)
1209 # Mode at end of file should always be 0
1211 warn_or_exception(f + " not terminated in " + mf.name)
1213 warn_or_exception("Unterminated continuation in " + mf.name)
1215 warn_or_exception("Unterminated build in " + mf.name)
1220 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1222 def w_comments(key):
1223 if key not in app.comments:
1225 for line in app.comments[key]:
1228 def w_field_always(f, v=None):
1230 v = app.get_field(f)
1234 def w_field_nonempty(f, v=None):
1236 v = app.get_field(f)
1241 w_field_nonempty('Disabled')
1242 w_field_nonempty('AntiFeatures')
1243 w_field_nonempty('Provides')
1244 w_field_always('Categories')
1245 w_field_always('License')
1246 w_field_nonempty('Author Name')
1247 w_field_nonempty('Author Email')
1248 w_field_always('Web Site')
1249 w_field_always('Source Code')
1250 w_field_always('Issue Tracker')
1251 w_field_nonempty('Changelog')
1252 w_field_nonempty('Donate')
1253 w_field_nonempty('FlattrID')
1254 w_field_nonempty('Bitcoin')
1255 w_field_nonempty('Litecoin')
1257 w_field_nonempty('Name')
1258 w_field_nonempty('Auto Name')
1259 w_field_always('Summary')
1260 w_field_always('Description', description_txt(app.Description))
1262 if app.RequiresRoot:
1263 w_field_always('Requires Root', 'yes')
1266 w_field_always('Repo Type')
1267 w_field_always('Repo')
1269 w_field_always('Binaries')
1272 for build in app.builds:
1274 if build.version == "Ignore":
1277 w_comments('build:' + build.vercode)
1281 if app.MaintainerNotes:
1282 w_field_always('Maintainer Notes', app.MaintainerNotes)
1285 w_field_nonempty('Archive Policy')
1286 w_field_always('Auto Update Mode')
1287 w_field_always('Update Check Mode')
1288 w_field_nonempty('Update Check Ignore')
1289 w_field_nonempty('Vercode Operation')
1290 w_field_nonempty('Update Check Name')
1291 w_field_nonempty('Update Check Data')
1292 if app.CurrentVersion:
1293 w_field_always('Current Version')
1294 w_field_always('Current Version Code')
1295 if app.NoSourceSince:
1297 w_field_always('No Source Since')
1301 # Write a metadata file in txt format.
1303 # 'mf' - Writer interface (file, StringIO, ...)
1304 # 'app' - The app data
1305 def write_txt(mf, app):
1307 def w_comment(line):
1308 mf.write("# %s\n" % line)
1314 elif t == TYPE_MULTILINE:
1315 v = '\n' + v + '\n.'
1316 mf.write("%s:%s\n" % (f, v))
1319 mf.write("Build:%s,%s\n" % (build.version, build.vercode))
1321 for f in build_flags_order:
1322 v = build.get_flag(f)
1327 mf.write(' %s=' % f)
1328 if t == TYPE_STRING:
1330 elif t == TYPE_BOOL:
1332 elif t == TYPE_SCRIPT:
1334 for s in v.split(' && '):
1338 mf.write(' && \\\n ')
1340 elif t == TYPE_LIST:
1341 mf.write(','.join(v))
1345 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1348 def write_yaml(mf, app):
1350 def w_comment(line):
1351 mf.write("# %s\n" % line)
1356 if any(c in v for c in [': ', '%', '@', '*']):
1357 return "'" + v.replace("'", "''") + "'"
1360 def w_field(f, v, prefix='', t=None):
1367 v += prefix + ' - ' + escape(e) + '\n'
1368 elif t == TYPE_MULTILINE:
1370 for l in v.splitlines():
1372 v += prefix + ' ' + l + '\n'
1375 elif t == TYPE_BOOL:
1377 elif t == TYPE_SCRIPT:
1378 cmds = [s + '&& \\' for s in v.split('&& ')]
1380 cmds[-1] = cmds[-1][:-len('&& \\')]
1381 w_field(f, cmds, prefix, 'multiline')
1384 v = ' ' + escape(v) + '\n'
1397 mf.write("builds:\n")
1400 w_field('versionName', build.version, ' - ', TYPE_STRING)
1401 w_field('versionCode', build.vercode, ' ', TYPE_STRING)
1402 for f in build_flags_order:
1403 v = build.get_flag(f)
1407 w_field(f, v, ' ', flagtype(f))
1409 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1412 def write_metadata(metadatapath, app):
1413 _, ext = fdroidserver.common.get_extension(metadatapath)
1414 accepted = fdroidserver.common.config['accepted_formats']
1415 if ext not in accepted:
1416 warn_or_exception('Cannot write "%s", not an accepted format, use: %s'
1417 % (metadatapath, ', '.join(accepted)))
1419 with open(metadatapath, 'w', encoding='utf8') as mf:
1421 return write_txt(mf, app)
1423 return write_yaml(mf, app)
1424 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1427 def add_metadata_arguments(parser):
1428 '''add common command line flags related to metadata processing'''
1429 parser.add_argument("-W", default='error',
1430 help="force errors to be warnings, or ignore")