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
39 from fdroidserver.exception import MetaDataException
42 warnings_action = None
45 def warn_or_exception(value):
46 '''output warning or Exception depending on -W'''
47 if warnings_action == 'ignore':
49 elif warnings_action == 'error':
50 raise MetaDataException(value)
55 # To filter which ones should be written to the metadata files if
86 'Update Check Ignore',
91 'Current Version Code',
95 'comments', # For formats that don't do inline comments
96 'builds', # For formats that do builds as a list
102 def __init__(self, copydict=None):
104 super().__init__(copydict)
109 self.AntiFeatures = []
111 self.Categories = ['None']
112 self.License = 'Unknown'
113 self.AuthorName = None
114 self.AuthorEmail = None
115 self.AuthorWebSite = 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
151 def __getattr__(self, name):
155 raise AttributeError("No such attribute: " + name)
157 def __setattr__(self, name, value):
160 def __delattr__(self, name):
164 raise AttributeError("No such attribute: " + name)
166 def get_last_build(self):
167 if len(self.builds) > 0:
168 return self.builds[-1]
184 'Description': TYPE_MULTILINE,
185 'MaintainerNotes': TYPE_MULTILINE,
186 'Categories': TYPE_LIST,
187 'AntiFeatures': TYPE_LIST,
188 'BuildVersion': TYPE_BUILD,
189 'Build': TYPE_BUILD_V2,
190 'UseBuilt': TYPE_OBSOLETE,
195 name = name.replace(' ', '')
196 if name in fieldtypes:
197 return fieldtypes[name]
201 # In the order in which they are laid out on files
202 build_flags_order = [
235 # old .txt format has version name/code inline in the 'Build:' line
236 # but YAML and JSON have a explicit key for them
237 build_flags = ['versionName', 'versionCode'] + build_flags_order
242 def __init__(self, copydict=None):
247 self.submodules = False
253 self.buildozer = False
256 self.oldsdkloc = False
258 self.forceversion = False
259 self.forcevercode = False
263 self.androidupdate = []
270 self.preassemble = []
271 self.gradleprops = []
272 self.antcommands = []
273 self.novcheck = False
275 super().__init__(copydict)
278 def __getattr__(self, name):
282 raise AttributeError("No such attribute: " + name)
284 def __setattr__(self, name, value):
287 def __delattr__(self, name):
291 raise AttributeError("No such attribute: " + name)
293 def build_method(self):
294 for f in ['maven', 'gradle', 'kivy', 'buildozer']:
301 # like build_method, but prioritize output=
302 def output_method(self):
305 for f in ['maven', 'gradle', 'kivy', 'buildozer']:
313 version = 'r12b' # falls back to latest
314 paths = fdroidserver.common.config['ndk_paths']
315 if version not in paths:
317 return paths[version]
321 'extlibs': TYPE_LIST,
322 'srclibs': TYPE_LIST,
325 'buildjni': TYPE_LIST,
326 'preassemble': TYPE_LIST,
327 'androidupdate': TYPE_LIST,
328 'scanignore': TYPE_LIST,
329 'scandelete': TYPE_LIST,
331 'antcommands': TYPE_LIST,
332 'gradleprops': TYPE_LIST,
334 'prebuild': TYPE_SCRIPT,
335 'build': TYPE_SCRIPT,
336 'submodules': TYPE_BOOL,
337 'oldsdkloc': TYPE_BOOL,
338 'forceversion': TYPE_BOOL,
339 'forcevercode': TYPE_BOOL,
340 'novcheck': TYPE_BOOL,
345 if name in flagtypes:
346 return flagtypes[name]
350 class FieldValidator():
352 Designates App metadata field types and checks that it matches
354 'name' - The long name of the field type
355 'matching' - List of possible values or regex expression
356 'sep' - Separator to use if value may be a list
357 'fields' - Metadata fields (Field:Value) of this type
360 def __init__(self, name, matching, fields):
362 self.matching = matching
363 self.compiled = re.compile(matching)
366 def check(self, v, appid):
374 if not self.compiled.match(v):
375 warn_or_exception("'%s' is not a valid %s in %s. Regex pattern: %s"
376 % (v, self.name, appid, self.matching))
379 # Generic value types
381 FieldValidator("Hexadecimal",
385 FieldValidator("HTTP link",
387 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"]),
389 FieldValidator("Email",
390 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
393 FieldValidator("Bitcoin address",
394 r'^[a-zA-Z0-9]{27,34}$',
397 FieldValidator("Litecoin address",
398 r'^L[a-zA-Z0-9]{33}$',
401 FieldValidator("Repo Type",
402 r'^(git|git-svn|svn|hg|bzr|srclib)$',
405 FieldValidator("Binaries",
409 FieldValidator("Archive Policy",
410 r'^[0-9]+ versions$',
413 FieldValidator("Anti-Feature",
414 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets|KnownVuln)$',
417 FieldValidator("Auto Update Mode",
418 r"^(Version .+|None)$",
421 FieldValidator("Update Check Mode",
422 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
427 # Check an app's metadata information for integrity errors
428 def check_metadata(app):
431 v.check(app[k], app.id)
434 # Formatter for descriptions. Create an instance, and call parseline() with
435 # each line of the description source from the metadata. At the end, call
436 # end() and then text_txt and text_html will contain the result.
437 class DescriptionFormatter:
444 def __init__(self, linkres):
447 self.state = self.stNONE
448 self.laststate = self.stNONE
451 self.html = io.StringIO()
452 self.text = io.StringIO()
454 self.linkResolver = None
455 self.linkResolver = linkres
457 def endcur(self, notstates=None):
458 if notstates and self.state in notstates:
460 if self.state == self.stPARA:
462 elif self.state == self.stUL:
464 elif self.state == self.stOL:
468 self.laststate = self.state
469 self.state = self.stNONE
470 whole_para = ' '.join(self.para_lines)
471 self.addtext(whole_para)
472 wrapped = textwrap.fill(whole_para, 80,
473 break_long_words=False,
474 break_on_hyphens=False)
475 self.text.write(wrapped)
476 self.html.write('</p>')
477 del self.para_lines[:]
480 self.html.write('</ul>')
481 self.laststate = self.state
482 self.state = self.stNONE
485 self.html.write('</ol>')
486 self.laststate = self.state
487 self.state = self.stNONE
489 def formatted(self, txt, htmlbody):
492 txt = html.escape(txt, quote=False)
494 index = txt.find("''")
499 if txt.startswith("'''"):
505 self.bold = not self.bold
513 self.ital = not self.ital
516 def linkify(self, txt):
520 index = txt.find("[")
522 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
523 res_plain += self.formatted(txt[:index], False)
524 res_html += self.formatted(txt[:index], True)
526 if txt.startswith("[["):
527 index = txt.find("]]")
529 warn_or_exception("Unterminated ]]")
531 if self.linkResolver:
532 url, urltext = self.linkResolver(url)
535 res_html += '<a href="' + url + '">' + html.escape(urltext, quote=False) + '</a>'
537 txt = txt[index + 2:]
539 index = txt.find("]")
541 warn_or_exception("Unterminated ]")
543 index2 = url.find(' ')
547 urltxt = url[index2 + 1:]
550 warn_or_exception("Url title is just the URL - use [url]")
551 res_html += '<a href="' + url + '">' + html.escape(urltxt, quote=False) + '</a>'
554 res_plain += ' (' + url + ')'
555 txt = txt[index + 1:]
557 def addtext(self, txt):
558 p, h = self.linkify(txt)
561 def parseline(self, line):
564 elif line.startswith('* '):
565 self.endcur([self.stUL])
566 if self.state != self.stUL:
567 self.html.write('<ul>')
568 self.state = self.stUL
569 if self.laststate != self.stNONE:
570 self.text.write('\n\n')
572 self.text.write('\n')
573 self.text.write(line)
574 self.html.write('<li>')
575 self.addtext(line[1:])
576 self.html.write('</li>')
577 elif line.startswith('# '):
578 self.endcur([self.stOL])
579 if self.state != self.stOL:
580 self.html.write('<ol>')
581 self.state = self.stOL
582 if self.laststate != self.stNONE:
583 self.text.write('\n\n')
585 self.text.write('\n')
586 self.text.write(line)
587 self.html.write('<li>')
588 self.addtext(line[1:])
589 self.html.write('</li>')
591 self.para_lines.append(line)
592 self.endcur([self.stPARA])
593 if self.state == self.stNONE:
594 self.state = self.stPARA
595 if self.laststate != self.stNONE:
596 self.text.write('\n\n')
597 self.html.write('<p>')
601 self.text_txt = self.text.getvalue()
602 self.text_html = self.html.getvalue()
607 # Parse multiple lines of description as written in a metadata file, returning
608 # a single string in text format and wrapped to 80 columns.
609 def description_txt(s):
610 ps = DescriptionFormatter(None)
611 for line in s.splitlines():
617 # Parse multiple lines of description as written in a metadata file, returning
618 # a single string in wiki format. Used for the Maintainer Notes field as well,
619 # because it's the same format.
620 def description_wiki(s):
624 # Parse multiple lines of description as written in a metadata file, returning
625 # a single string in HTML format.
626 def description_html(s, linkres):
627 ps = DescriptionFormatter(linkres)
628 for line in s.splitlines():
634 def parse_srclib(metadatapath):
638 # Defaults for fields that come from metadata
639 thisinfo['Repo Type'] = ''
640 thisinfo['Repo'] = ''
641 thisinfo['Subdir'] = None
642 thisinfo['Prepare'] = None
644 if not os.path.exists(metadatapath):
647 metafile = open(metadatapath, "r", encoding='utf-8')
650 for line in metafile:
652 line = line.rstrip('\r\n')
653 if not line or line.startswith("#"):
657 f, v = line.split(':', 1)
659 warn_or_exception("Invalid metadata in %s:%d" % (line, n))
662 thisinfo[f] = v.split(',')
672 """Read all srclib metadata.
674 The information read will be accessible as metadata.srclibs, which is a
675 dictionary, keyed on srclib name, with the values each being a dictionary
676 in the same format as that returned by the parse_srclib function.
678 A MetaDataException is raised if there are any problems with the srclib
683 # They were already loaded
684 if srclibs is not None:
690 if not os.path.exists(srcdir):
693 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
694 srclibname = os.path.basename(metadatapath[:-4])
695 srclibs[srclibname] = parse_srclib(metadatapath)
698 def read_metadata(xref=True, check_vcs=[]):
700 Read all metadata. Returns a list of 'app' objects (which are dictionaries as
701 returned by the parse_txt_metadata function.
703 check_vcs is the list of packageNames to check for .fdroid.yml in source
706 # Always read the srclibs before the apps, since they can use a srlib as
707 # their source repository.
712 for basedir in ('metadata', 'tmp'):
713 if not os.path.exists(basedir):
716 # If there are multiple metadata files for a single appid, then the first
717 # file that is parsed wins over all the others, and the rest throw an
718 # exception. So the original .txt format is parsed first, at least until
719 # newer formats stabilize.
721 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
722 + glob.glob(os.path.join('metadata', '*.json'))
723 + glob.glob(os.path.join('metadata', '*.yml'))
724 + glob.glob('.fdroid.json')
725 + glob.glob('.fdroid.yml')):
726 packageName, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
727 if packageName in apps:
728 warn_or_exception("Found multiple metadata files for " + packageName)
729 app = parse_metadata(metadatapath, packageName in check_vcs)
734 # Parse all descriptions at load time, just to ensure cross-referencing
735 # errors are caught early rather than when they hit the build server.
738 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
739 warn_or_exception("Cannot resolve app id " + appid)
741 for appid, app in apps.items():
743 description_html(app.Description, linkres)
744 except MetaDataException as e:
745 warn_or_exception("Problem with description of " + appid +
751 # Port legacy ';' separators
752 list_sep = re.compile(r'[,;]')
755 def split_list_values(s):
757 for v in re.split(list_sep, s):
767 def get_default_app_info(metadatapath=None):
768 if metadatapath is None:
771 appid, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
773 if appid == '.fdroid': # we have local metadata in the app's source
774 if os.path.exists('AndroidManifest.xml'):
775 manifestroot = fdroidserver.common.parse_xml('AndroidManifest.xml')
777 pattern = re.compile(""".*manifest\.srcFile\s+'AndroidManifest\.xml'.*""")
778 for root, dirs, files in os.walk(os.getcwd()):
779 if 'build.gradle' in files:
780 p = os.path.join(root, 'build.gradle')
781 with open(p, 'rb') as f:
783 m = pattern.search(data)
785 logging.debug('Using: ' + os.path.join(root, 'AndroidManifest.xml'))
786 manifestroot = fdroidserver.common.parse_xml(os.path.join(root, 'AndroidManifest.xml'))
788 if manifestroot is None:
789 warn_or_exception("Cannot find a packageName for {0}!".format(metadatapath))
790 appid = manifestroot.attrib['package']
793 app.metadatapath = metadatapath
794 if appid is not None:
800 def sorted_builds(builds):
801 return sorted(builds, key=lambda build: int(build.versionCode))
804 esc_newlines = re.compile(r'\\( |\n)')
807 def post_metadata_parse(app):
808 # TODO keep native types, convert only for .txt metadata
809 for k, v in app.items():
810 if type(v) in (float, int):
813 if isinstance(app.Categories, str):
814 app.Categories = [app.Categories]
815 elif app.Categories is None:
816 app.Categories = ['None']
818 app.Categories = [str(i) for i in app.Categories]
822 for build in app['builds']:
823 if not isinstance(build, Build):
825 for k, v in build.items():
826 if flagtype(k) == TYPE_LIST:
827 if isinstance(v, str):
829 elif isinstance(v, bool):
834 elif flagtype(k) == TYPE_STRING and type(v) in (float, int):
838 app.builds = sorted_builds(builds)
841 # Parse metadata for a single application.
843 # 'metadatapath' - the filename to read. The package id for the application comes
844 # from this filename. Pass None to get a blank entry.
846 # Returns a dictionary containing all the details of the application. There are
847 # two major kinds of information in the dictionary. Keys beginning with capital
848 # letters correspond directory to identically named keys in the metadata file.
849 # Keys beginning with lower case letters are generated in one way or another,
850 # and are not found verbatim in the metadata.
852 # Known keys not originating from the metadata are:
854 # 'builds' - a list of dictionaries containing build information
855 # for each defined build
856 # 'comments' - a list of comments from the metadata file. Each is
857 # a list of the form [field, comment] where field is
858 # the name of the field it preceded in the metadata
859 # file. Where field is None, the comment goes at the
860 # end of the file. Alternatively, 'build:version' is
861 # for a comment before a particular build version.
862 # 'descriptionlines' - original lines of description as formatted in the
867 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
868 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
872 if bool_true.match(s):
874 if bool_false.match(s):
876 warn_or_exception("Invalid bool '%s'" % s)
879 def parse_metadata(metadatapath, check_vcs=False):
880 '''parse metadata file, optionally checking the git repo for metadata first'''
882 _, ext = fdroidserver.common.get_extension(metadatapath)
883 accepted = fdroidserver.common.config['accepted_formats']
884 if ext not in accepted:
885 warn_or_exception('"%s" is not an accepted format, convert to: %s' % (
886 metadatapath, ', '.join(accepted)))
889 app.metadatapath = metadatapath
890 name, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
891 if name == '.fdroid':
896 with open(metadatapath, 'r', encoding='utf-8') as mf:
898 parse_txt_metadata(mf, app)
900 parse_json_metadata(mf, app)
902 parse_yaml_metadata(mf, app)
904 warn_or_exception('Unknown metadata format: %s' % metadatapath)
906 if check_vcs and app.Repo:
907 build_dir = fdroidserver.common.get_build_dir(app)
908 metadata_in_repo = os.path.join(build_dir, '.fdroid.yml')
909 if not os.path.isfile(metadata_in_repo):
910 vcs, build_dir = fdroidserver.common.setup_vcs(app)
911 if isinstance(vcs, fdroidserver.common.vcs_git):
912 vcs.gotorevision('HEAD') # HEAD since we can't know where else to go
913 if os.path.isfile(metadata_in_repo):
914 logging.debug('Including metadata from ' + metadata_in_repo)
915 # do not include fields already provided by main metadata file
916 app_in_repo = parse_metadata(metadata_in_repo)
917 for k, v in app_in_repo.items():
921 post_metadata_parse(app)
925 build = app.builds[-1]
927 root_dir = build.subdir
930 paths = fdroidserver.common.manifest_paths(root_dir, build.gradle)
931 _, _, app.id = fdroidserver.common.parse_androidmanifests(paths, app)
936 def parse_json_metadata(mf, app):
938 # fdroid metadata is only strings and booleans, no floats or ints.
939 # TODO create schema using https://pypi.python.org/pypi/jsonschema
940 jsoninfo = json.load(mf, parse_int=lambda s: s,
941 parse_float=lambda s: s)
943 for f in ['Description', 'Maintainer Notes']:
946 app[f] = '\n'.join(v)
950 def parse_yaml_metadata(mf, app):
952 yamlinfo = yaml.load(mf, Loader=YamlLoader)
957 def write_yaml(mf, app):
959 def _class_as_dict_representer(dumper, data):
960 '''Creates a YAML representation of a App/Build instance'''
961 return dumper.represent_dict(data)
963 empty_keys = [k for k, v in app.items() if not v]
967 for k in ['added', 'lastUpdated', 'id', 'metadatapath']:
971 # yaml.add_representer(fdroidserver.metadata.App, _class_as_dict_representer)
972 ruamel.yaml.add_representer(fdroidserver.metadata.Build, _class_as_dict_representer)
973 # yaml.dump(app.asOrderedDict(), mf, default_flow_style=False, Dumper=yamlordereddictloader.Dumper)
975 yaml_app_field_order = [
994 'Current Version Code',
997 preformated = ruamel.yaml.comments.CommentedMap()
998 insert_newline = False
999 for field in yaml_app_field_order:
1001 insert_newline = True
1003 f = field.replace(' ', '')
1004 if hasattr(app, f) and getattr(app, f):
1005 if f in ['Description']:
1006 preformated.update({f: ruamel.yaml.scalarstring.preserve_literal(getattr(app, f))})
1008 preformated.update({f: getattr(app, f)})
1010 insert_newline = False
1011 # inserting empty lines is not supported so we add a
1012 # bogus comment and over-write its value
1013 preformated.yaml_set_comment_before_after_key(f, 'bogus')
1014 preformated.ca.items[f][1][0].value = '\n'
1016 ruamel.yaml.round_trip_dump(preformated, mf, indent=4, block_seq_indent=2)
1019 build_line_sep = re.compile(r'(?<!\\),')
1020 build_cont = re.compile(r'^[ \t]')
1023 def parse_txt_metadata(mf, app):
1027 def add_buildflag(p, build):
1029 warn_or_exception("Empty build flag at {1}"
1030 .format(buildlines[0], linedesc))
1031 bv = p.split('=', 1)
1033 warn_or_exception("Invalid build flag at {0} in {1}"
1034 .format(buildlines[0], linedesc))
1039 pk = 'androidupdate' # avoid conflicting with Build(dict).update()
1042 pv = split_list_values(pv)
1044 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1046 elif t == TYPE_BOOL:
1047 build[pk] = _decode_bool(pv)
1049 def parse_buildline(lines):
1051 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1053 warn_or_exception("Invalid build format: " + v + " in " + mf.name)
1055 build.versionName = parts[0]
1056 build.versionCode = parts[1]
1057 check_versionCode(build.versionCode)
1059 if parts[2].startswith('!'):
1060 # For backwards compatibility, handle old-style disabling,
1061 # including attempting to extract the commit from the message
1062 build.disable = parts[2][1:]
1063 commit = 'unknown - see disabled'
1064 index = parts[2].rfind('at ')
1066 commit = parts[2][index + 3:]
1067 if commit.endswith(')'):
1068 commit = commit[:-1]
1069 build.commit = commit
1071 build.commit = parts[2]
1073 add_buildflag(p, build)
1077 def check_versionCode(versionCode):
1081 warn_or_exception('Invalid versionCode: "' + versionCode + '" is not an integer!')
1083 def add_comments(key):
1086 app.comments[key] = list(curcomments)
1091 multiline_lines = []
1101 linedesc = "%s:%d" % (mf.name, c)
1102 line = line.rstrip('\r\n')
1104 if build_cont.match(line):
1105 if line.endswith('\\'):
1106 buildlines.append(line[:-1].lstrip())
1108 buildlines.append(line.lstrip())
1109 bl = ''.join(buildlines)
1110 add_buildflag(bl, build)
1113 if not build.commit and not build.disable:
1114 warn_or_exception("No commit specified for {0} in {1}"
1115 .format(build.versionName, linedesc))
1117 app.builds.append(build)
1118 add_comments('build:' + build.versionCode)
1124 if line.startswith("#"):
1125 curcomments.append(line[1:].strip())
1128 f, v = line.split(':', 1)
1130 warn_or_exception("Invalid metadata in " + linedesc)
1132 if f not in app_fields:
1133 warn_or_exception('Unrecognised app field: ' + f)
1135 # Translate obsolete fields...
1136 if f == 'Market Version':
1137 f = 'Current Version'
1138 if f == 'Market Version Code':
1139 f = 'Current Version Code'
1141 f = f.replace(' ', '')
1143 ftype = fieldtype(f)
1144 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1146 if ftype == TYPE_MULTILINE:
1149 warn_or_exception("Unexpected text on same line as "
1150 + f + " in " + linedesc)
1151 elif ftype == TYPE_STRING:
1153 elif ftype == TYPE_LIST:
1154 app[f] = split_list_values(v)
1155 elif ftype == TYPE_BUILD:
1156 if v.endswith("\\"):
1159 buildlines.append(v[:-1])
1161 build = parse_buildline([v])
1162 app.builds.append(build)
1163 add_comments('build:' + app.builds[-1].versionCode)
1164 elif ftype == TYPE_BUILD_V2:
1167 warn_or_exception('Build should have comma-separated',
1168 'versionName and versionCode,',
1169 'not "{0}", in {1}'.format(v, linedesc))
1171 build.versionName = vv[0]
1172 build.versionCode = vv[1]
1173 check_versionCode(build.versionCode)
1175 if build.versionCode in vc_seen:
1176 warn_or_exception('Duplicate build recipe found for versionCode %s in %s'
1177 % (build.versionCode, linedesc))
1178 vc_seen.add(build.versionCode)
1181 elif ftype == TYPE_OBSOLETE:
1182 pass # Just throw it away!
1184 warn_or_exception("Unrecognised field '" + f + "' in " + linedesc)
1185 elif mode == 1: # Multiline field
1188 app[f] = '\n'.join(multiline_lines)
1189 del multiline_lines[:]
1191 multiline_lines.append(line)
1192 elif mode == 2: # Line continuation mode in Build Version
1193 if line.endswith("\\"):
1194 buildlines.append(line[:-1])
1196 buildlines.append(line)
1197 build = parse_buildline(buildlines)
1198 app.builds.append(build)
1199 add_comments('build:' + app.builds[-1].versionCode)
1203 # Mode at end of file should always be 0
1205 warn_or_exception(f + " not terminated in " + mf.name)
1207 warn_or_exception("Unterminated continuation in " + mf.name)
1209 warn_or_exception("Unterminated build in " + mf.name)
1214 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1216 def field_to_attr(f):
1218 Translates human-readable field names to attribute names, e.g.
1219 'Auto Name' to 'AutoName'
1221 return f.replace(' ', '')
1223 def attr_to_field(k):
1225 Translates attribute names to human-readable field names, e.g.
1226 'AutoName' to 'Auto Name'
1230 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
1233 def w_comments(key):
1234 if key not in app.comments:
1236 for line in app.comments[key]:
1239 def w_field_always(f, v=None):
1240 key = field_to_attr(f)
1246 def w_field_nonempty(f, v=None):
1247 key = field_to_attr(f)
1254 w_field_nonempty('Disabled')
1255 w_field_nonempty('AntiFeatures')
1256 w_field_nonempty('Provides')
1257 w_field_always('Categories')
1258 w_field_always('License')
1259 w_field_nonempty('Author Name')
1260 w_field_nonempty('Author Email')
1261 w_field_nonempty('Author Web Site')
1262 w_field_always('Web Site')
1263 w_field_always('Source Code')
1264 w_field_always('Issue Tracker')
1265 w_field_nonempty('Changelog')
1266 w_field_nonempty('Donate')
1267 w_field_nonempty('FlattrID')
1268 w_field_nonempty('Bitcoin')
1269 w_field_nonempty('Litecoin')
1271 w_field_nonempty('Name')
1272 w_field_nonempty('Auto Name')
1273 w_field_nonempty('Summary')
1274 w_field_nonempty('Description', description_txt(app.Description))
1276 if app.RequiresRoot:
1277 w_field_always('Requires Root', 'yes')
1280 w_field_always('Repo Type')
1281 w_field_always('Repo')
1283 w_field_always('Binaries')
1286 for build in app.builds:
1288 if build.versionName == "Ignore":
1291 w_comments('build:%s' % build.versionCode)
1295 if app.MaintainerNotes:
1296 w_field_always('Maintainer Notes', app.MaintainerNotes)
1299 w_field_nonempty('Archive Policy')
1300 w_field_always('Auto Update Mode')
1301 w_field_always('Update Check Mode')
1302 w_field_nonempty('Update Check Ignore')
1303 w_field_nonempty('Vercode Operation')
1304 w_field_nonempty('Update Check Name')
1305 w_field_nonempty('Update Check Data')
1306 if app.CurrentVersion:
1307 w_field_always('Current Version')
1308 w_field_always('Current Version Code')
1309 if app.NoSourceSince:
1311 w_field_always('No Source Since')
1315 # Write a metadata file in txt format.
1317 # 'mf' - Writer interface (file, StringIO, ...)
1318 # 'app' - The app data
1319 def write_txt(mf, app):
1321 def w_comment(line):
1322 mf.write("# %s\n" % line)
1328 elif t == TYPE_MULTILINE:
1329 v = '\n' + v + '\n.'
1330 mf.write("%s:%s\n" % (f, v))
1333 mf.write("Build:%s,%s\n" % (build.versionName, build.versionCode))
1335 for f in build_flags_order:
1341 if f == 'androidupdate':
1342 f = 'update' # avoid conflicting with Build(dict).update()
1343 mf.write(' %s=' % f)
1344 if t == TYPE_STRING:
1346 elif t == TYPE_BOOL:
1348 elif t == TYPE_SCRIPT:
1350 for s in v.split(' && '):
1354 mf.write(' && \\\n ')
1356 elif t == TYPE_LIST:
1357 mf.write(','.join(v))
1361 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1364 def write_metadata(metadatapath, app):
1365 _, ext = fdroidserver.common.get_extension(metadatapath)
1366 accepted = fdroidserver.common.config['accepted_formats']
1367 if ext not in accepted:
1368 warn_or_exception('Cannot write "%s", not an accepted format, use: %s'
1369 % (metadatapath, ', '.join(accepted)))
1371 with open(metadatapath, 'w', encoding='utf8') as mf:
1373 return write_txt(mf, app)
1375 return write_yaml(mf, app)
1376 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1379 def add_metadata_arguments(parser):
1380 '''add common command line flags related to metadata processing'''
1381 parser.add_argument("-W", default='error',
1382 help="force errors to be warnings, or ignore")