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',
102 'comments', # For formats that don't do inline comments
103 'builds', # For formats that do builds as a list
109 def __init__(self, copydict=None):
111 super().__init__(copydict)
116 self.AntiFeatures = []
118 self.Categories = ['None']
119 self.License = 'Unknown'
120 self.AuthorName = None
121 self.AuthorEmail = None
124 self.IssueTracker = ''
133 self.Description = ''
134 self.RequiresRoot = False
138 self.MaintainerNotes = ''
139 self.ArchivePolicy = None
140 self.AutoUpdateMode = 'None'
141 self.UpdateCheckMode = 'None'
142 self.UpdateCheckIgnore = None
143 self.VercodeOperation = None
144 self.UpdateCheckName = None
145 self.UpdateCheckData = None
146 self.CurrentVersion = ''
147 self.CurrentVersionCode = None
148 self.NoSourceSince = ''
151 self.metadatapath = None
155 self.lastUpdated = None
157 def __getattr__(self, name):
161 raise AttributeError("No such attribute: " + name)
163 def __setattr__(self, name, value):
166 def __delattr__(self, name):
170 raise AttributeError("No such attribute: " + name)
172 def get_last_build(self):
173 if len(self.builds) > 0:
174 return self.builds[-1]
190 'Description': TYPE_MULTILINE,
191 'MaintainerNotes': TYPE_MULTILINE,
192 'Categories': TYPE_LIST,
193 'AntiFeatures': TYPE_LIST,
194 'BuildVersion': TYPE_BUILD,
195 'Build': TYPE_BUILD_V2,
196 'UseBuilt': TYPE_OBSOLETE,
201 name = name.replace(' ', '')
202 if name in fieldtypes:
203 return fieldtypes[name]
207 # In the order in which they are laid out on files
208 build_flags_order = [
241 build_flags = set(build_flags_order + ['versionName', 'versionCode'])
246 def __init__(self, copydict=None):
251 self.submodules = False
259 self.oldsdkloc = False
261 self.forceversion = False
262 self.forcevercode = False
266 self.androidupdate = []
273 self.preassemble = []
274 self.gradleprops = []
275 self.antcommands = []
276 self.novcheck = False
278 super().__init__(copydict)
281 def __getattr__(self, name):
285 raise AttributeError("No such attribute: " + name)
287 def __setattr__(self, name, value):
290 def __delattr__(self, name):
294 raise AttributeError("No such attribute: " + name)
296 def build_method(self):
297 for f in ['maven', 'gradle', 'kivy']:
304 # like build_method, but prioritize output=
305 def output_method(self):
308 for f in ['maven', 'gradle', 'kivy']:
316 version = 'r12b' # falls back to latest
317 paths = fdroidserver.common.config['ndk_paths']
318 if version not in paths:
320 return paths[version]
324 'extlibs': TYPE_LIST,
325 'srclibs': TYPE_LIST,
328 'buildjni': TYPE_LIST,
329 'preassemble': TYPE_LIST,
330 'androidupdate': TYPE_LIST,
331 'scanignore': TYPE_LIST,
332 'scandelete': TYPE_LIST,
334 'antcommands': TYPE_LIST,
335 'gradleprops': TYPE_LIST,
337 'prebuild': TYPE_SCRIPT,
338 'build': TYPE_SCRIPT,
339 'submodules': TYPE_BOOL,
340 'oldsdkloc': TYPE_BOOL,
341 'forceversion': TYPE_BOOL,
342 'forcevercode': TYPE_BOOL,
343 'novcheck': TYPE_BOOL,
348 if name in flagtypes:
349 return flagtypes[name]
353 class FieldValidator():
355 Designates App metadata field types and checks that it matches
357 'name' - The long name of the field type
358 'matching' - List of possible values or regex expression
359 'sep' - Separator to use if value may be a list
360 'fields' - Metadata fields (Field:Value) of this type
363 def __init__(self, name, matching, fields):
365 self.matching = matching
366 self.compiled = re.compile(matching)
369 def check(self, v, appid):
377 if not self.compiled.match(v):
378 warn_or_exception("'%s' is not a valid %s in %s. Regex pattern: %s"
379 % (v, self.name, appid, self.matching))
382 # Generic value types
384 FieldValidator("Hexadecimal",
388 FieldValidator("HTTP link",
390 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"]),
392 FieldValidator("Email",
393 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
396 FieldValidator("Bitcoin address",
397 r'^[a-zA-Z0-9]{27,34}$',
400 FieldValidator("Litecoin address",
401 r'^L[a-zA-Z0-9]{33}$',
404 FieldValidator("Repo Type",
405 r'^(git|git-svn|svn|hg|bzr|srclib)$',
408 FieldValidator("Binaries",
412 FieldValidator("Archive Policy",
413 r'^[0-9]+ versions$',
416 FieldValidator("Anti-Feature",
417 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets|KnownVuln)$',
420 FieldValidator("Auto Update Mode",
421 r"^(Version .+|None)$",
424 FieldValidator("Update Check Mode",
425 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
430 # Check an app's metadata information for integrity errors
431 def check_metadata(app):
434 v.check(app[k], app.id)
437 # Formatter for descriptions. Create an instance, and call parseline() with
438 # each line of the description source from the metadata. At the end, call
439 # end() and then text_txt and text_html will contain the result.
440 class DescriptionFormatter:
447 def __init__(self, linkres):
450 self.state = self.stNONE
451 self.laststate = self.stNONE
454 self.html = io.StringIO()
455 self.text = io.StringIO()
457 self.linkResolver = None
458 self.linkResolver = linkres
460 def endcur(self, notstates=None):
461 if notstates and self.state in notstates:
463 if self.state == self.stPARA:
465 elif self.state == self.stUL:
467 elif self.state == self.stOL:
471 self.laststate = self.state
472 self.state = self.stNONE
473 whole_para = ' '.join(self.para_lines)
474 self.addtext(whole_para)
475 wrapped = textwrap.fill(whole_para, 80,
476 break_long_words=False,
477 break_on_hyphens=False)
478 self.text.write(wrapped)
479 self.html.write('</p>')
480 del self.para_lines[:]
483 self.html.write('</ul>')
484 self.laststate = self.state
485 self.state = self.stNONE
488 self.html.write('</ol>')
489 self.laststate = self.state
490 self.state = self.stNONE
492 def formatted(self, txt, html):
495 txt = cgi.escape(txt)
497 index = txt.find("''")
502 if txt.startswith("'''"):
508 self.bold = not self.bold
516 self.ital = not self.ital
519 def linkify(self, txt):
523 index = txt.find("[")
525 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
526 res_plain += self.formatted(txt[:index], False)
527 res_html += self.formatted(txt[:index], True)
529 if txt.startswith("[["):
530 index = txt.find("]]")
532 warn_or_exception("Unterminated ]]")
534 if self.linkResolver:
535 url, urltext = self.linkResolver(url)
538 res_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
540 txt = txt[index + 2:]
542 index = txt.find("]")
544 warn_or_exception("Unterminated ]")
546 index2 = url.find(' ')
550 urltxt = url[index2 + 1:]
553 warn_or_exception("Url title is just the URL - use [url]")
554 res_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
557 res_plain += ' (' + url + ')'
558 txt = txt[index + 1:]
560 def addtext(self, txt):
561 p, h = self.linkify(txt)
564 def parseline(self, line):
567 elif line.startswith('* '):
568 self.endcur([self.stUL])
569 if self.state != self.stUL:
570 self.html.write('<ul>')
571 self.state = self.stUL
572 if self.laststate != self.stNONE:
573 self.text.write('\n\n')
575 self.text.write('\n')
576 self.text.write(line)
577 self.html.write('<li>')
578 self.addtext(line[1:])
579 self.html.write('</li>')
580 elif line.startswith('# '):
581 self.endcur([self.stOL])
582 if self.state != self.stOL:
583 self.html.write('<ol>')
584 self.state = self.stOL
585 if self.laststate != self.stNONE:
586 self.text.write('\n\n')
588 self.text.write('\n')
589 self.text.write(line)
590 self.html.write('<li>')
591 self.addtext(line[1:])
592 self.html.write('</li>')
594 self.para_lines.append(line)
595 self.endcur([self.stPARA])
596 if self.state == self.stNONE:
597 self.state = self.stPARA
598 if self.laststate != self.stNONE:
599 self.text.write('\n\n')
600 self.html.write('<p>')
604 self.text_txt = self.text.getvalue()
605 self.text_html = self.html.getvalue()
610 # Parse multiple lines of description as written in a metadata file, returning
611 # a single string in text format and wrapped to 80 columns.
612 def description_txt(s):
613 ps = DescriptionFormatter(None)
614 for line in s.splitlines():
620 # Parse multiple lines of description as written in a metadata file, returning
621 # a single string in wiki format. Used for the Maintainer Notes field as well,
622 # because it's the same format.
623 def description_wiki(s):
627 # Parse multiple lines of description as written in a metadata file, returning
628 # a single string in HTML format.
629 def description_html(s, linkres):
630 ps = DescriptionFormatter(linkres)
631 for line in s.splitlines():
637 def parse_srclib(metadatapath):
641 # Defaults for fields that come from metadata
642 thisinfo['Repo Type'] = ''
643 thisinfo['Repo'] = ''
644 thisinfo['Subdir'] = None
645 thisinfo['Prepare'] = None
647 if not os.path.exists(metadatapath):
650 metafile = open(metadatapath, "r", encoding='utf-8')
653 for line in metafile:
655 line = line.rstrip('\r\n')
656 if not line or line.startswith("#"):
660 f, v = line.split(':', 1)
662 warn_or_exception("Invalid metadata in %s:%d" % (line, n))
665 thisinfo[f] = v.split(',')
675 """Read all srclib metadata.
677 The information read will be accessible as metadata.srclibs, which is a
678 dictionary, keyed on srclib name, with the values each being a dictionary
679 in the same format as that returned by the parse_srclib function.
681 A MetaDataException is raised if there are any problems with the srclib
686 # They were already loaded
687 if srclibs is not None:
693 if not os.path.exists(srcdir):
696 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
697 srclibname = os.path.basename(metadatapath[:-4])
698 srclibs[srclibname] = parse_srclib(metadatapath)
701 def read_metadata(xref=True, check_vcs=[]):
703 Read all metadata. Returns a list of 'app' objects (which are dictionaries as
704 returned by the parse_txt_metadata function.
706 check_vcs is the list of packageNames to check for .fdroid.yml in source
709 # Always read the srclibs before the apps, since they can use a srlib as
710 # their source repository.
715 for basedir in ('metadata', 'tmp'):
716 if not os.path.exists(basedir):
719 # If there are multiple metadata files for a single appid, then the first
720 # file that is parsed wins over all the others, and the rest throw an
721 # exception. So the original .txt format is parsed first, at least until
722 # newer formats stabilize.
724 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
725 + glob.glob(os.path.join('metadata', '*.json'))
726 + glob.glob(os.path.join('metadata', '*.yml'))
727 + glob.glob('.fdroid.json')
728 + glob.glob('.fdroid.yml')):
729 packageName, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
730 if packageName in apps:
731 warn_or_exception("Found multiple metadata files for " + packageName)
732 app = parse_metadata(metadatapath, packageName in check_vcs)
737 # Parse all descriptions at load time, just to ensure cross-referencing
738 # errors are caught early rather than when they hit the build server.
741 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
742 warn_or_exception("Cannot resolve app id " + appid)
744 for appid, app in apps.items():
746 description_html(app.Description, linkres)
747 except MetaDataException as e:
748 warn_or_exception("Problem with description of " + appid +
754 # Port legacy ';' separators
755 list_sep = re.compile(r'[,;]')
758 def split_list_values(s):
760 for v in re.split(list_sep, s):
770 def get_default_app_info(metadatapath=None):
771 if metadatapath is None:
774 appid, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
776 if appid == '.fdroid': # we have local metadata in the app's source
777 if os.path.exists('AndroidManifest.xml'):
778 manifestroot = fdroidserver.common.parse_xml('AndroidManifest.xml')
780 pattern = re.compile(""".*manifest\.srcFile\s+'AndroidManifest\.xml'.*""")
781 for root, dirs, files in os.walk(os.getcwd()):
782 if 'build.gradle' in files:
783 p = os.path.join(root, 'build.gradle')
784 with open(p, 'rb') as f:
786 m = pattern.search(data)
788 logging.debug('Using: ' + os.path.join(root, 'AndroidManifest.xml'))
789 manifestroot = fdroidserver.common.parse_xml(os.path.join(root, 'AndroidManifest.xml'))
791 if manifestroot is None:
792 warn_or_exception("Cannot find a packageName for {0}!".format(metadatapath))
793 appid = manifestroot.attrib['package']
796 app.metadatapath = metadatapath
797 if appid is not None:
803 def sorted_builds(builds):
804 return sorted(builds, key=lambda build: int(build.versionCode))
807 esc_newlines = re.compile(r'\\( |\n)')
810 def post_metadata_parse(app):
811 # TODO keep native types, convert only for .txt metadata
812 for k, v in app.items():
813 if type(v) in (float, int):
816 if isinstance(app.Categories, str):
817 app.Categories = [app.Categories]
819 app.Categories = [str(i) for i in app.Categories]
823 for build in app['builds']:
824 if not isinstance(build, Build):
826 for k, v in build.items():
827 if flagtype(k) == TYPE_LIST:
828 if isinstance(v, str):
830 elif isinstance(v, bool):
835 elif flagtype(k) == TYPE_STRING and type(v) in (float, int):
839 app.builds = sorted_builds(builds)
842 # Parse metadata for a single application.
844 # 'metadatapath' - the filename to read. The package id for the application comes
845 # from this filename. Pass None to get a blank entry.
847 # Returns a dictionary containing all the details of the application. There are
848 # two major kinds of information in the dictionary. Keys beginning with capital
849 # letters correspond directory to identically named keys in the metadata file.
850 # Keys beginning with lower case letters are generated in one way or another,
851 # and are not found verbatim in the metadata.
853 # Known keys not originating from the metadata are:
855 # 'builds' - a list of dictionaries containing build information
856 # for each defined build
857 # 'comments' - a list of comments from the metadata file. Each is
858 # a list of the form [field, comment] where field is
859 # the name of the field it preceded in the metadata
860 # file. Where field is None, the comment goes at the
861 # end of the file. Alternatively, 'build:version' is
862 # for a comment before a particular build version.
863 # 'descriptionlines' - original lines of description as formatted in the
868 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
869 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
873 if bool_true.match(s):
875 if bool_false.match(s):
877 warn_or_exception("Invalid bool '%s'" % s)
880 def parse_metadata(metadatapath, check_vcs=False):
881 '''parse metadata file, optionally checking the git repo for metadata first'''
883 _, ext = fdroidserver.common.get_extension(metadatapath)
884 accepted = fdroidserver.common.config['accepted_formats']
885 if ext not in accepted:
886 warn_or_exception('"%s" is not an accepted format, convert to: %s' % (
887 metadatapath, ', '.join(accepted)))
890 app.metadatapath = metadatapath
891 name, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
892 if name == '.fdroid':
897 with open(metadatapath, 'r', encoding='utf-8') as mf:
899 parse_txt_metadata(mf, app)
901 parse_json_metadata(mf, app)
903 parse_yaml_metadata(mf, app)
905 warn_or_exception('Unknown metadata format: %s' % metadatapath)
907 if check_vcs and app.Repo:
908 build_dir = fdroidserver.common.get_build_dir(app)
909 metadata_in_repo = os.path.join(build_dir, '.fdroid.yml')
910 if not os.path.isfile(metadata_in_repo):
911 vcs, build_dir = fdroidserver.common.setup_vcs(app)
912 if isinstance(vcs, fdroidserver.common.vcs_git):
913 vcs.gotorevision('HEAD') # HEAD since we can't know where else to go
914 if os.path.isfile(metadata_in_repo):
915 logging.debug('Including metadata from ' + metadata_in_repo)
916 # do not include fields already provided by main metadata file
917 app_in_repo = parse_metadata(metadata_in_repo)
918 for k, v in app_in_repo.items():
922 post_metadata_parse(app)
926 build = app.builds[-1]
928 root_dir = build.subdir
931 paths = fdroidserver.common.manifest_paths(root_dir, build.gradle)
932 _, _, app.id = fdroidserver.common.parse_androidmanifests(paths, app)
937 def parse_json_metadata(mf, app):
939 # fdroid metadata is only strings and booleans, no floats or ints.
940 # TODO create schema using https://pypi.python.org/pypi/jsonschema
941 jsoninfo = json.load(mf, parse_int=lambda s: s,
942 parse_float=lambda s: s)
944 for f in ['Description', 'Maintainer Notes']:
947 app[f] = '\n'.join(v)
951 def parse_yaml_metadata(mf, app):
953 yamlinfo = yaml.load(mf, Loader=YamlLoader)
958 build_line_sep = re.compile(r'(?<!\\),')
959 build_cont = re.compile(r'^[ \t]')
962 def parse_txt_metadata(mf, app):
966 def add_buildflag(p, build):
968 warn_or_exception("Empty build flag at {1}"
969 .format(buildlines[0], linedesc))
972 warn_or_exception("Invalid build flag at {0} in {1}"
973 .format(buildlines[0], linedesc))
978 pk = 'androidupdate' # avoid conflicting with Build(dict).update()
981 pv = split_list_values(pv)
983 elif t == TYPE_STRING or t == TYPE_SCRIPT:
986 build[pk] = _decode_bool(pv)
988 def parse_buildline(lines):
990 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
992 warn_or_exception("Invalid build format: " + v + " in " + mf.name)
994 build.versionName = parts[0]
995 build.versionCode = parts[1]
996 check_versionCode(build.versionCode)
998 if parts[2].startswith('!'):
999 # For backwards compatibility, handle old-style disabling,
1000 # including attempting to extract the commit from the message
1001 build.disable = parts[2][1:]
1002 commit = 'unknown - see disabled'
1003 index = parts[2].rfind('at ')
1005 commit = parts[2][index + 3:]
1006 if commit.endswith(')'):
1007 commit = commit[:-1]
1008 build.commit = commit
1010 build.commit = parts[2]
1012 add_buildflag(p, build)
1016 def check_versionCode(versionCode):
1020 warn_or_exception('Invalid versionCode: "' + versionCode + '" is not an integer!')
1022 def add_comments(key):
1025 app.comments[key] = list(curcomments)
1030 multiline_lines = []
1040 linedesc = "%s:%d" % (mf.name, c)
1041 line = line.rstrip('\r\n')
1043 if build_cont.match(line):
1044 if line.endswith('\\'):
1045 buildlines.append(line[:-1].lstrip())
1047 buildlines.append(line.lstrip())
1048 bl = ''.join(buildlines)
1049 add_buildflag(bl, build)
1052 if not build.commit and not build.disable:
1053 warn_or_exception("No commit specified for {0} in {1}"
1054 .format(build.versionName, linedesc))
1056 app.builds.append(build)
1057 add_comments('build:' + build.versionCode)
1063 if line.startswith("#"):
1064 curcomments.append(line[1:].strip())
1067 f, v = line.split(':', 1)
1069 warn_or_exception("Invalid metadata in " + linedesc)
1071 if f not in app_fields:
1072 warn_or_exception('Unrecognised app field: ' + f)
1074 # Translate obsolete fields...
1075 if f == 'Market Version':
1076 f = 'Current Version'
1077 if f == 'Market Version Code':
1078 f = 'Current Version Code'
1080 f = f.replace(' ', '')
1082 ftype = fieldtype(f)
1083 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1085 if ftype == TYPE_MULTILINE:
1088 warn_or_exception("Unexpected text on same line as "
1089 + f + " in " + linedesc)
1090 elif ftype == TYPE_STRING:
1092 elif ftype == TYPE_LIST:
1093 app[f] = split_list_values(v)
1094 elif ftype == TYPE_BUILD:
1095 if v.endswith("\\"):
1098 buildlines.append(v[:-1])
1100 build = parse_buildline([v])
1101 app.builds.append(build)
1102 add_comments('build:' + app.builds[-1].versionCode)
1103 elif ftype == TYPE_BUILD_V2:
1106 warn_or_exception('Build should have comma-separated',
1107 'versionName and versionCode,',
1108 'not "{0}", in {1}'.format(v, linedesc))
1110 build.versionName = vv[0]
1111 build.versionCode = vv[1]
1112 check_versionCode(build.versionCode)
1114 if build.versionCode in vc_seen:
1115 warn_or_exception('Duplicate build recipe found for versionCode %s in %s'
1116 % (build.versionCode, linedesc))
1117 vc_seen.add(build.versionCode)
1120 elif ftype == TYPE_OBSOLETE:
1121 pass # Just throw it away!
1123 warn_or_exception("Unrecognised field '" + f + "' in " + linedesc)
1124 elif mode == 1: # Multiline field
1127 app[f] = '\n'.join(multiline_lines)
1128 del multiline_lines[:]
1130 multiline_lines.append(line)
1131 elif mode == 2: # Line continuation mode in Build Version
1132 if line.endswith("\\"):
1133 buildlines.append(line[:-1])
1135 buildlines.append(line)
1136 build = parse_buildline(buildlines)
1137 app.builds.append(build)
1138 add_comments('build:' + app.builds[-1].versionCode)
1142 # Mode at end of file should always be 0
1144 warn_or_exception(f + " not terminated in " + mf.name)
1146 warn_or_exception("Unterminated continuation in " + mf.name)
1148 warn_or_exception("Unterminated build in " + mf.name)
1153 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1155 def field_to_attr(f):
1157 Translates human-readable field names to attribute names, e.g.
1158 'Auto Name' to 'AutoName'
1160 return f.replace(' ', '')
1162 def attr_to_field(k):
1164 Translates attribute names to human-readable field names, e.g.
1165 'AutoName' to 'Auto Name'
1169 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
1172 def w_comments(key):
1173 if key not in app.comments:
1175 for line in app.comments[key]:
1178 def w_field_always(f, v=None):
1179 key = field_to_attr(f)
1185 def w_field_nonempty(f, v=None):
1186 key = field_to_attr(f)
1193 w_field_nonempty('Disabled')
1194 w_field_nonempty('AntiFeatures')
1195 w_field_nonempty('Provides')
1196 w_field_always('Categories')
1197 w_field_always('License')
1198 w_field_nonempty('Author Name')
1199 w_field_nonempty('Author Email')
1200 w_field_always('Web Site')
1201 w_field_always('Source Code')
1202 w_field_always('Issue Tracker')
1203 w_field_nonempty('Changelog')
1204 w_field_nonempty('Donate')
1205 w_field_nonempty('FlattrID')
1206 w_field_nonempty('Bitcoin')
1207 w_field_nonempty('Litecoin')
1209 w_field_nonempty('Name')
1210 w_field_nonempty('Auto Name')
1211 w_field_always('Summary')
1212 w_field_always('Description', description_txt(app.Description))
1214 if app.RequiresRoot:
1215 w_field_always('Requires Root', 'yes')
1218 w_field_always('Repo Type')
1219 w_field_always('Repo')
1221 w_field_always('Binaries')
1224 for build in app.builds:
1226 if build.versionName == "Ignore":
1229 w_comments('build:%s' % build.versionCode)
1233 if app.MaintainerNotes:
1234 w_field_always('Maintainer Notes', app.MaintainerNotes)
1237 w_field_nonempty('Archive Policy')
1238 w_field_always('Auto Update Mode')
1239 w_field_always('Update Check Mode')
1240 w_field_nonempty('Update Check Ignore')
1241 w_field_nonempty('Vercode Operation')
1242 w_field_nonempty('Update Check Name')
1243 w_field_nonempty('Update Check Data')
1244 if app.CurrentVersion:
1245 w_field_always('Current Version')
1246 w_field_always('Current Version Code')
1247 if app.NoSourceSince:
1249 w_field_always('No Source Since')
1253 # Write a metadata file in txt format.
1255 # 'mf' - Writer interface (file, StringIO, ...)
1256 # 'app' - The app data
1257 def write_txt(mf, app):
1259 def w_comment(line):
1260 mf.write("# %s\n" % line)
1266 elif t == TYPE_MULTILINE:
1267 v = '\n' + v + '\n.'
1268 mf.write("%s:%s\n" % (f, v))
1271 mf.write("Build:%s,%s\n" % (build.versionName, build.versionCode))
1273 for f in build_flags_order:
1279 if f == 'androidupdate':
1280 f = 'update' # avoid conflicting with Build(dict).update()
1281 mf.write(' %s=' % f)
1282 if t == TYPE_STRING:
1284 elif t == TYPE_BOOL:
1286 elif t == TYPE_SCRIPT:
1288 for s in v.split(' && '):
1292 mf.write(' && \\\n ')
1294 elif t == TYPE_LIST:
1295 mf.write(','.join(v))
1299 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1302 def write_yaml(mf, app):
1304 def w_comment(line):
1305 mf.write("# %s\n" % line)
1310 if any(c in v for c in [': ', '%', '@', '*']):
1311 return "'" + v.replace("'", "''") + "'"
1314 def w_field(f, v, prefix='', t=None):
1321 v += prefix + ' - ' + escape(e) + '\n'
1322 elif t == TYPE_MULTILINE:
1324 for l in v.splitlines():
1326 v += prefix + ' ' + l + '\n'
1329 elif t == TYPE_BOOL:
1331 elif t == TYPE_SCRIPT:
1332 cmds = [s + '&& \\' for s in v.split('&& ')]
1334 cmds[-1] = cmds[-1][:-len('&& \\')]
1335 w_field(f, cmds, prefix, 'multiline')
1338 v = ' ' + escape(v) + '\n'
1351 mf.write("builds:\n")
1354 w_field('versionName', build.versionName, ' - ', TYPE_STRING)
1355 w_field('versionCode', build.versionCode, ' ', TYPE_STRING)
1356 for f in build_flags_order:
1361 w_field(f, v, ' ', flagtype(f))
1363 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1366 def write_metadata(metadatapath, app):
1367 _, ext = fdroidserver.common.get_extension(metadatapath)
1368 accepted = fdroidserver.common.config['accepted_formats']
1369 if ext not in accepted:
1370 warn_or_exception('Cannot write "%s", not an accepted format, use: %s'
1371 % (metadatapath, ', '.join(accepted)))
1373 with open(metadatapath, 'w', encoding='utf8') as mf:
1375 return write_txt(mf, app)
1377 return write_yaml(mf, app)
1378 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1381 def add_metadata_arguments(parser):
1382 '''add common command line flags related to metadata processing'''
1383 parser.add_argument("-W", default='error',
1384 help="force errors to be warnings, or ignore")