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
94 'Update Check Ignore',
99 'Current Version Code',
103 'comments', # For formats that don't do inline comments
104 'builds', # For formats that do builds as a list
110 def __init__(self, copydict=None):
112 super().__init__(copydict)
117 self.AntiFeatures = []
119 self.Categories = ['None']
120 self.License = 'Unknown'
121 self.AuthorName = None
122 self.AuthorEmail = None
123 self.AuthorWebSite = None
126 self.IssueTracker = ''
135 self.Description = ''
136 self.RequiresRoot = False
140 self.MaintainerNotes = ''
141 self.ArchivePolicy = None
142 self.AutoUpdateMode = 'None'
143 self.UpdateCheckMode = 'None'
144 self.UpdateCheckIgnore = None
145 self.VercodeOperation = None
146 self.UpdateCheckName = None
147 self.UpdateCheckData = None
148 self.CurrentVersion = ''
149 self.CurrentVersionCode = None
150 self.NoSourceSince = ''
153 self.metadatapath = None
157 self.lastUpdated = None
159 def __getattr__(self, name):
163 raise AttributeError("No such attribute: " + name)
165 def __setattr__(self, name, value):
168 def __delattr__(self, name):
172 raise AttributeError("No such attribute: " + name)
174 def get_last_build(self):
175 if len(self.builds) > 0:
176 return self.builds[-1]
192 'Description': TYPE_MULTILINE,
193 'MaintainerNotes': TYPE_MULTILINE,
194 'Categories': TYPE_LIST,
195 'AntiFeatures': TYPE_LIST,
196 'BuildVersion': TYPE_BUILD,
197 'Build': TYPE_BUILD_V2,
198 'UseBuilt': TYPE_OBSOLETE,
203 name = name.replace(' ', '')
204 if name in fieldtypes:
205 return fieldtypes[name]
209 # In the order in which they are laid out on files
210 build_flags_order = [
242 # old .txt format has version name/code inline in the 'Build:' line
243 # but YAML and JSON have a explicit key for them
244 build_flags = ['versionName', 'versionCode'] + build_flags_order
249 def __init__(self, copydict=None):
254 self.submodules = False
262 self.oldsdkloc = False
264 self.forceversion = False
265 self.forcevercode = False
269 self.androidupdate = []
276 self.preassemble = []
277 self.gradleprops = []
278 self.antcommands = []
279 self.novcheck = False
281 super().__init__(copydict)
284 def __getattr__(self, name):
288 raise AttributeError("No such attribute: " + name)
290 def __setattr__(self, name, value):
293 def __delattr__(self, name):
297 raise AttributeError("No such attribute: " + name)
299 def build_method(self):
300 for f in ['maven', 'gradle', 'kivy']:
307 # like build_method, but prioritize output=
308 def output_method(self):
311 for f in ['maven', 'gradle', 'kivy']:
319 version = 'r12b' # falls back to latest
320 paths = fdroidserver.common.config['ndk_paths']
321 if version not in paths:
323 return paths[version]
327 'extlibs': TYPE_LIST,
328 'srclibs': TYPE_LIST,
331 'buildjni': TYPE_LIST,
332 'preassemble': TYPE_LIST,
333 'androidupdate': TYPE_LIST,
334 'scanignore': TYPE_LIST,
335 'scandelete': TYPE_LIST,
337 'antcommands': TYPE_LIST,
338 'gradleprops': TYPE_LIST,
340 'prebuild': TYPE_SCRIPT,
341 'build': TYPE_SCRIPT,
342 'submodules': TYPE_BOOL,
343 'oldsdkloc': TYPE_BOOL,
344 'forceversion': TYPE_BOOL,
345 'forcevercode': TYPE_BOOL,
346 'novcheck': TYPE_BOOL,
351 if name in flagtypes:
352 return flagtypes[name]
356 class FieldValidator():
358 Designates App metadata field types and checks that it matches
360 'name' - The long name of the field type
361 'matching' - List of possible values or regex expression
362 'sep' - Separator to use if value may be a list
363 'fields' - Metadata fields (Field:Value) of this type
366 def __init__(self, name, matching, fields):
368 self.matching = matching
369 self.compiled = re.compile(matching)
372 def check(self, v, appid):
380 if not self.compiled.match(v):
381 warn_or_exception("'%s' is not a valid %s in %s. Regex pattern: %s"
382 % (v, self.name, appid, self.matching))
385 # Generic value types
387 FieldValidator("Hexadecimal",
391 FieldValidator("HTTP link",
393 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"]),
395 FieldValidator("Email",
396 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
399 FieldValidator("Bitcoin address",
400 r'^[a-zA-Z0-9]{27,34}$',
403 FieldValidator("Litecoin address",
404 r'^L[a-zA-Z0-9]{33}$',
407 FieldValidator("Repo Type",
408 r'^(git|git-svn|svn|hg|bzr|srclib)$',
411 FieldValidator("Binaries",
415 FieldValidator("Archive Policy",
416 r'^[0-9]+ versions$',
419 FieldValidator("Anti-Feature",
420 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets|KnownVuln)$',
423 FieldValidator("Auto Update Mode",
424 r"^(Version .+|None)$",
427 FieldValidator("Update Check Mode",
428 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
433 # Check an app's metadata information for integrity errors
434 def check_metadata(app):
437 v.check(app[k], app.id)
440 # Formatter for descriptions. Create an instance, and call parseline() with
441 # each line of the description source from the metadata. At the end, call
442 # end() and then text_txt and text_html will contain the result.
443 class DescriptionFormatter:
450 def __init__(self, linkres):
453 self.state = self.stNONE
454 self.laststate = self.stNONE
457 self.html = io.StringIO()
458 self.text = io.StringIO()
460 self.linkResolver = None
461 self.linkResolver = linkres
463 def endcur(self, notstates=None):
464 if notstates and self.state in notstates:
466 if self.state == self.stPARA:
468 elif self.state == self.stUL:
470 elif self.state == self.stOL:
474 self.laststate = self.state
475 self.state = self.stNONE
476 whole_para = ' '.join(self.para_lines)
477 self.addtext(whole_para)
478 wrapped = textwrap.fill(whole_para, 80,
479 break_long_words=False,
480 break_on_hyphens=False)
481 self.text.write(wrapped)
482 self.html.write('</p>')
483 del self.para_lines[:]
486 self.html.write('</ul>')
487 self.laststate = self.state
488 self.state = self.stNONE
491 self.html.write('</ol>')
492 self.laststate = self.state
493 self.state = self.stNONE
495 def formatted(self, txt, html):
498 txt = cgi.escape(txt)
500 index = txt.find("''")
505 if txt.startswith("'''"):
511 self.bold = not self.bold
519 self.ital = not self.ital
522 def linkify(self, txt):
526 index = txt.find("[")
528 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
529 res_plain += self.formatted(txt[:index], False)
530 res_html += self.formatted(txt[:index], True)
532 if txt.startswith("[["):
533 index = txt.find("]]")
535 warn_or_exception("Unterminated ]]")
537 if self.linkResolver:
538 url, urltext = self.linkResolver(url)
541 res_html += '<a href="' + url + '">' + cgi.escape(urltext) + '</a>'
543 txt = txt[index + 2:]
545 index = txt.find("]")
547 warn_or_exception("Unterminated ]")
549 index2 = url.find(' ')
553 urltxt = url[index2 + 1:]
556 warn_or_exception("Url title is just the URL - use [url]")
557 res_html += '<a href="' + url + '">' + cgi.escape(urltxt) + '</a>'
560 res_plain += ' (' + url + ')'
561 txt = txt[index + 1:]
563 def addtext(self, txt):
564 p, h = self.linkify(txt)
567 def parseline(self, line):
570 elif line.startswith('* '):
571 self.endcur([self.stUL])
572 if self.state != self.stUL:
573 self.html.write('<ul>')
574 self.state = self.stUL
575 if self.laststate != self.stNONE:
576 self.text.write('\n\n')
578 self.text.write('\n')
579 self.text.write(line)
580 self.html.write('<li>')
581 self.addtext(line[1:])
582 self.html.write('</li>')
583 elif line.startswith('# '):
584 self.endcur([self.stOL])
585 if self.state != self.stOL:
586 self.html.write('<ol>')
587 self.state = self.stOL
588 if self.laststate != self.stNONE:
589 self.text.write('\n\n')
591 self.text.write('\n')
592 self.text.write(line)
593 self.html.write('<li>')
594 self.addtext(line[1:])
595 self.html.write('</li>')
597 self.para_lines.append(line)
598 self.endcur([self.stPARA])
599 if self.state == self.stNONE:
600 self.state = self.stPARA
601 if self.laststate != self.stNONE:
602 self.text.write('\n\n')
603 self.html.write('<p>')
607 self.text_txt = self.text.getvalue()
608 self.text_html = self.html.getvalue()
613 # Parse multiple lines of description as written in a metadata file, returning
614 # a single string in text format and wrapped to 80 columns.
615 def description_txt(s):
616 ps = DescriptionFormatter(None)
617 for line in s.splitlines():
623 # Parse multiple lines of description as written in a metadata file, returning
624 # a single string in wiki format. Used for the Maintainer Notes field as well,
625 # because it's the same format.
626 def description_wiki(s):
630 # Parse multiple lines of description as written in a metadata file, returning
631 # a single string in HTML format.
632 def description_html(s, linkres):
633 ps = DescriptionFormatter(linkres)
634 for line in s.splitlines():
640 def parse_srclib(metadatapath):
644 # Defaults for fields that come from metadata
645 thisinfo['Repo Type'] = ''
646 thisinfo['Repo'] = ''
647 thisinfo['Subdir'] = None
648 thisinfo['Prepare'] = None
650 if not os.path.exists(metadatapath):
653 metafile = open(metadatapath, "r", encoding='utf-8')
656 for line in metafile:
658 line = line.rstrip('\r\n')
659 if not line or line.startswith("#"):
663 f, v = line.split(':', 1)
665 warn_or_exception("Invalid metadata in %s:%d" % (line, n))
668 thisinfo[f] = v.split(',')
678 """Read all srclib metadata.
680 The information read will be accessible as metadata.srclibs, which is a
681 dictionary, keyed on srclib name, with the values each being a dictionary
682 in the same format as that returned by the parse_srclib function.
684 A MetaDataException is raised if there are any problems with the srclib
689 # They were already loaded
690 if srclibs is not None:
696 if not os.path.exists(srcdir):
699 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
700 srclibname = os.path.basename(metadatapath[:-4])
701 srclibs[srclibname] = parse_srclib(metadatapath)
704 def read_metadata(xref=True, check_vcs=[]):
706 Read all metadata. Returns a list of 'app' objects (which are dictionaries as
707 returned by the parse_txt_metadata function.
709 check_vcs is the list of packageNames to check for .fdroid.yml in source
712 # Always read the srclibs before the apps, since they can use a srlib as
713 # their source repository.
718 for basedir in ('metadata', 'tmp'):
719 if not os.path.exists(basedir):
722 # If there are multiple metadata files for a single appid, then the first
723 # file that is parsed wins over all the others, and the rest throw an
724 # exception. So the original .txt format is parsed first, at least until
725 # newer formats stabilize.
727 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
728 + glob.glob(os.path.join('metadata', '*.json'))
729 + glob.glob(os.path.join('metadata', '*.yml'))
730 + glob.glob('.fdroid.json')
731 + glob.glob('.fdroid.yml')):
732 packageName, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
733 if packageName in apps:
734 warn_or_exception("Found multiple metadata files for " + packageName)
735 app = parse_metadata(metadatapath, packageName in check_vcs)
740 # Parse all descriptions at load time, just to ensure cross-referencing
741 # errors are caught early rather than when they hit the build server.
744 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
745 warn_or_exception("Cannot resolve app id " + appid)
747 for appid, app in apps.items():
749 description_html(app.Description, linkres)
750 except MetaDataException as e:
751 warn_or_exception("Problem with description of " + appid +
757 # Port legacy ';' separators
758 list_sep = re.compile(r'[,;]')
761 def split_list_values(s):
763 for v in re.split(list_sep, s):
773 def get_default_app_info(metadatapath=None):
774 if metadatapath is None:
777 appid, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
779 if appid == '.fdroid': # we have local metadata in the app's source
780 if os.path.exists('AndroidManifest.xml'):
781 manifestroot = fdroidserver.common.parse_xml('AndroidManifest.xml')
783 pattern = re.compile(""".*manifest\.srcFile\s+'AndroidManifest\.xml'.*""")
784 for root, dirs, files in os.walk(os.getcwd()):
785 if 'build.gradle' in files:
786 p = os.path.join(root, 'build.gradle')
787 with open(p, 'rb') as f:
789 m = pattern.search(data)
791 logging.debug('Using: ' + os.path.join(root, 'AndroidManifest.xml'))
792 manifestroot = fdroidserver.common.parse_xml(os.path.join(root, 'AndroidManifest.xml'))
794 if manifestroot is None:
795 warn_or_exception("Cannot find a packageName for {0}!".format(metadatapath))
796 appid = manifestroot.attrib['package']
799 app.metadatapath = metadatapath
800 if appid is not None:
806 def sorted_builds(builds):
807 return sorted(builds, key=lambda build: int(build.versionCode))
810 esc_newlines = re.compile(r'\\( |\n)')
813 def post_metadata_parse(app):
814 # TODO keep native types, convert only for .txt metadata
815 for k, v in app.items():
816 if type(v) in (float, int):
819 if isinstance(app.Categories, str):
820 app.Categories = [app.Categories]
821 elif app.Categories is None:
822 app.Categories = ['None']
824 app.Categories = [str(i) for i in app.Categories]
828 for build in app['builds']:
829 if not isinstance(build, Build):
831 for k, v in build.items():
832 if flagtype(k) == TYPE_LIST:
833 if isinstance(v, str):
835 elif isinstance(v, bool):
840 elif flagtype(k) == TYPE_STRING and type(v) in (float, int):
844 app.builds = sorted_builds(builds)
847 # Parse metadata for a single application.
849 # 'metadatapath' - the filename to read. The package id for the application comes
850 # from this filename. Pass None to get a blank entry.
852 # Returns a dictionary containing all the details of the application. There are
853 # two major kinds of information in the dictionary. Keys beginning with capital
854 # letters correspond directory to identically named keys in the metadata file.
855 # Keys beginning with lower case letters are generated in one way or another,
856 # and are not found verbatim in the metadata.
858 # Known keys not originating from the metadata are:
860 # 'builds' - a list of dictionaries containing build information
861 # for each defined build
862 # 'comments' - a list of comments from the metadata file. Each is
863 # a list of the form [field, comment] where field is
864 # the name of the field it preceded in the metadata
865 # file. Where field is None, the comment goes at the
866 # end of the file. Alternatively, 'build:version' is
867 # for a comment before a particular build version.
868 # 'descriptionlines' - original lines of description as formatted in the
873 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
874 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
878 if bool_true.match(s):
880 if bool_false.match(s):
882 warn_or_exception("Invalid bool '%s'" % s)
885 def parse_metadata(metadatapath, check_vcs=False):
886 '''parse metadata file, optionally checking the git repo for metadata first'''
888 _, ext = fdroidserver.common.get_extension(metadatapath)
889 accepted = fdroidserver.common.config['accepted_formats']
890 if ext not in accepted:
891 warn_or_exception('"%s" is not an accepted format, convert to: %s' % (
892 metadatapath, ', '.join(accepted)))
895 app.metadatapath = metadatapath
896 name, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
897 if name == '.fdroid':
902 with open(metadatapath, 'r', encoding='utf-8') as mf:
904 parse_txt_metadata(mf, app)
906 parse_json_metadata(mf, app)
908 parse_yaml_metadata(mf, app)
910 warn_or_exception('Unknown metadata format: %s' % metadatapath)
912 if check_vcs and app.Repo:
913 build_dir = fdroidserver.common.get_build_dir(app)
914 metadata_in_repo = os.path.join(build_dir, '.fdroid.yml')
915 if not os.path.isfile(metadata_in_repo):
916 vcs, build_dir = fdroidserver.common.setup_vcs(app)
917 if isinstance(vcs, fdroidserver.common.vcs_git):
918 vcs.gotorevision('HEAD') # HEAD since we can't know where else to go
919 if os.path.isfile(metadata_in_repo):
920 logging.debug('Including metadata from ' + metadata_in_repo)
921 # do not include fields already provided by main metadata file
922 app_in_repo = parse_metadata(metadata_in_repo)
923 for k, v in app_in_repo.items():
927 post_metadata_parse(app)
931 build = app.builds[-1]
933 root_dir = build.subdir
936 paths = fdroidserver.common.manifest_paths(root_dir, build.gradle)
937 _, _, app.id = fdroidserver.common.parse_androidmanifests(paths, app)
942 def parse_json_metadata(mf, app):
944 # fdroid metadata is only strings and booleans, no floats or ints.
945 # TODO create schema using https://pypi.python.org/pypi/jsonschema
946 jsoninfo = json.load(mf, parse_int=lambda s: s,
947 parse_float=lambda s: s)
949 for f in ['Description', 'Maintainer Notes']:
952 app[f] = '\n'.join(v)
956 def parse_yaml_metadata(mf, app):
958 yamlinfo = yaml.load(mf, Loader=YamlLoader)
963 def write_yaml(mf, app):
965 def _class_as_dict_representer(dumper, data):
966 '''Creates a YAML representation of a App/Build instance'''
967 return dumper.represent_dict(data)
969 empty_keys = [k for k, v in app.items() if not v]
973 for k in ['added', 'lastUpdated', 'id', 'metadatapath']:
977 yaml.add_representer(fdroidserver.metadata.App, _class_as_dict_representer)
978 yaml.add_representer(fdroidserver.metadata.Build, _class_as_dict_representer)
979 yaml.dump(app, mf, default_flow_style=False)
982 build_line_sep = re.compile(r'(?<!\\),')
983 build_cont = re.compile(r'^[ \t]')
986 def parse_txt_metadata(mf, app):
990 def add_buildflag(p, build):
992 warn_or_exception("Empty build flag at {1}"
993 .format(buildlines[0], linedesc))
996 warn_or_exception("Invalid build flag at {0} in {1}"
997 .format(buildlines[0], linedesc))
1002 pk = 'androidupdate' # avoid conflicting with Build(dict).update()
1005 pv = split_list_values(pv)
1007 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1009 elif t == TYPE_BOOL:
1010 build[pk] = _decode_bool(pv)
1012 def parse_buildline(lines):
1014 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1016 warn_or_exception("Invalid build format: " + v + " in " + mf.name)
1018 build.versionName = parts[0]
1019 build.versionCode = parts[1]
1020 check_versionCode(build.versionCode)
1022 if parts[2].startswith('!'):
1023 # For backwards compatibility, handle old-style disabling,
1024 # including attempting to extract the commit from the message
1025 build.disable = parts[2][1:]
1026 commit = 'unknown - see disabled'
1027 index = parts[2].rfind('at ')
1029 commit = parts[2][index + 3:]
1030 if commit.endswith(')'):
1031 commit = commit[:-1]
1032 build.commit = commit
1034 build.commit = parts[2]
1036 add_buildflag(p, build)
1040 def check_versionCode(versionCode):
1044 warn_or_exception('Invalid versionCode: "' + versionCode + '" is not an integer!')
1046 def add_comments(key):
1049 app.comments[key] = list(curcomments)
1054 multiline_lines = []
1064 linedesc = "%s:%d" % (mf.name, c)
1065 line = line.rstrip('\r\n')
1067 if build_cont.match(line):
1068 if line.endswith('\\'):
1069 buildlines.append(line[:-1].lstrip())
1071 buildlines.append(line.lstrip())
1072 bl = ''.join(buildlines)
1073 add_buildflag(bl, build)
1076 if not build.commit and not build.disable:
1077 warn_or_exception("No commit specified for {0} in {1}"
1078 .format(build.versionName, linedesc))
1080 app.builds.append(build)
1081 add_comments('build:' + build.versionCode)
1087 if line.startswith("#"):
1088 curcomments.append(line[1:].strip())
1091 f, v = line.split(':', 1)
1093 warn_or_exception("Invalid metadata in " + linedesc)
1095 if f not in app_fields:
1096 warn_or_exception('Unrecognised app field: ' + f)
1098 # Translate obsolete fields...
1099 if f == 'Market Version':
1100 f = 'Current Version'
1101 if f == 'Market Version Code':
1102 f = 'Current Version Code'
1104 f = f.replace(' ', '')
1106 ftype = fieldtype(f)
1107 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1109 if ftype == TYPE_MULTILINE:
1112 warn_or_exception("Unexpected text on same line as "
1113 + f + " in " + linedesc)
1114 elif ftype == TYPE_STRING:
1116 elif ftype == TYPE_LIST:
1117 app[f] = split_list_values(v)
1118 elif ftype == TYPE_BUILD:
1119 if v.endswith("\\"):
1122 buildlines.append(v[:-1])
1124 build = parse_buildline([v])
1125 app.builds.append(build)
1126 add_comments('build:' + app.builds[-1].versionCode)
1127 elif ftype == TYPE_BUILD_V2:
1130 warn_or_exception('Build should have comma-separated',
1131 'versionName and versionCode,',
1132 'not "{0}", in {1}'.format(v, linedesc))
1134 build.versionName = vv[0]
1135 build.versionCode = vv[1]
1136 check_versionCode(build.versionCode)
1138 if build.versionCode in vc_seen:
1139 warn_or_exception('Duplicate build recipe found for versionCode %s in %s'
1140 % (build.versionCode, linedesc))
1141 vc_seen.add(build.versionCode)
1144 elif ftype == TYPE_OBSOLETE:
1145 pass # Just throw it away!
1147 warn_or_exception("Unrecognised field '" + f + "' in " + linedesc)
1148 elif mode == 1: # Multiline field
1151 app[f] = '\n'.join(multiline_lines)
1152 del multiline_lines[:]
1154 multiline_lines.append(line)
1155 elif mode == 2: # Line continuation mode in Build Version
1156 if line.endswith("\\"):
1157 buildlines.append(line[:-1])
1159 buildlines.append(line)
1160 build = parse_buildline(buildlines)
1161 app.builds.append(build)
1162 add_comments('build:' + app.builds[-1].versionCode)
1166 # Mode at end of file should always be 0
1168 warn_or_exception(f + " not terminated in " + mf.name)
1170 warn_or_exception("Unterminated continuation in " + mf.name)
1172 warn_or_exception("Unterminated build in " + mf.name)
1177 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1179 def field_to_attr(f):
1181 Translates human-readable field names to attribute names, e.g.
1182 'Auto Name' to 'AutoName'
1184 return f.replace(' ', '')
1186 def attr_to_field(k):
1188 Translates attribute names to human-readable field names, e.g.
1189 'AutoName' to 'Auto Name'
1193 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
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):
1203 key = field_to_attr(f)
1209 def w_field_nonempty(f, v=None):
1210 key = field_to_attr(f)
1217 w_field_nonempty('Disabled')
1218 w_field_nonempty('AntiFeatures')
1219 w_field_nonempty('Provides')
1220 w_field_always('Categories')
1221 w_field_always('License')
1222 w_field_nonempty('Author Name')
1223 w_field_nonempty('Author Email')
1224 w_field_nonempty('Author Web Site')
1225 w_field_always('Web Site')
1226 w_field_always('Source Code')
1227 w_field_always('Issue Tracker')
1228 w_field_nonempty('Changelog')
1229 w_field_nonempty('Donate')
1230 w_field_nonempty('FlattrID')
1231 w_field_nonempty('Bitcoin')
1232 w_field_nonempty('Litecoin')
1234 w_field_nonempty('Name')
1235 w_field_nonempty('Auto Name')
1236 w_field_always('Summary')
1237 w_field_always('Description', description_txt(app.Description))
1239 if app.RequiresRoot:
1240 w_field_always('Requires Root', 'yes')
1243 w_field_always('Repo Type')
1244 w_field_always('Repo')
1246 w_field_always('Binaries')
1249 for build in app.builds:
1251 if build.versionName == "Ignore":
1254 w_comments('build:%s' % build.versionCode)
1258 if app.MaintainerNotes:
1259 w_field_always('Maintainer Notes', app.MaintainerNotes)
1262 w_field_nonempty('Archive Policy')
1263 w_field_always('Auto Update Mode')
1264 w_field_always('Update Check Mode')
1265 w_field_nonempty('Update Check Ignore')
1266 w_field_nonempty('Vercode Operation')
1267 w_field_nonempty('Update Check Name')
1268 w_field_nonempty('Update Check Data')
1269 if app.CurrentVersion:
1270 w_field_always('Current Version')
1271 w_field_always('Current Version Code')
1272 if app.NoSourceSince:
1274 w_field_always('No Source Since')
1278 # Write a metadata file in txt format.
1280 # 'mf' - Writer interface (file, StringIO, ...)
1281 # 'app' - The app data
1282 def write_txt(mf, app):
1284 def w_comment(line):
1285 mf.write("# %s\n" % line)
1291 elif t == TYPE_MULTILINE:
1292 v = '\n' + v + '\n.'
1293 mf.write("%s:%s\n" % (f, v))
1296 mf.write("Build:%s,%s\n" % (build.versionName, build.versionCode))
1298 for f in build_flags_order:
1304 if f == 'androidupdate':
1305 f = 'update' # avoid conflicting with Build(dict).update()
1306 mf.write(' %s=' % f)
1307 if t == TYPE_STRING:
1309 elif t == TYPE_BOOL:
1311 elif t == TYPE_SCRIPT:
1313 for s in v.split(' && '):
1317 mf.write(' && \\\n ')
1319 elif t == TYPE_LIST:
1320 mf.write(','.join(v))
1324 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1327 def write_metadata(metadatapath, app):
1328 _, ext = fdroidserver.common.get_extension(metadatapath)
1329 accepted = fdroidserver.common.config['accepted_formats']
1330 if ext not in accepted:
1331 warn_or_exception('Cannot write "%s", not an accepted format, use: %s'
1332 % (metadatapath, ', '.join(accepted)))
1334 with open(metadatapath, 'w', encoding='utf8') as mf:
1336 return write_txt(mf, app)
1338 return write_yaml(mf, app)
1339 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1342 def add_metadata_arguments(parser):
1343 '''add common command line flags related to metadata processing'''
1344 parser.add_argument("-W", default='error',
1345 help="force errors to be warnings, or ignore")