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/>.
29 # use libyaml if it is available
31 from yaml import CLoader
34 from yaml import Loader
37 import fdroidserver.common
38 from fdroidserver import _
39 from fdroidserver.exception import MetaDataException, FDroidException
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)
52 logging.warning(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]
185 'Description': TYPE_MULTILINE,
186 'MaintainerNotes': TYPE_MULTILINE,
187 'Categories': TYPE_LIST,
188 'AntiFeatures': TYPE_LIST,
189 'BuildVersion': TYPE_BUILD,
190 'Build': TYPE_BUILD_V2,
191 'UseBuilt': TYPE_OBSOLETE,
196 name = name.replace(' ', '')
197 if name in fieldtypes:
198 return fieldtypes[name]
202 # In the order in which they are laid out on files
203 build_flags_order = [
238 # old .txt format has version name/code inline in the 'Build:' line
239 # but YAML and JSON have a explicit key for them
240 build_flags = ['versionName', 'versionCode'] + build_flags_order
245 def __init__(self, copydict=None):
250 self.submodules = False
257 self.buildozer = False
260 self.oldsdkloc = False
262 self.forceversion = False
263 self.forcevercode = False
267 self.androidupdate = []
274 self.preassemble = []
275 self.gradleprops = []
276 self.antcommands = []
277 self.novcheck = False
278 self.antifeatures = []
280 super().__init__(copydict)
283 def __getattr__(self, name):
287 raise AttributeError("No such attribute: " + name)
289 def __setattr__(self, name, value):
292 def __delattr__(self, name):
296 raise AttributeError("No such attribute: " + name)
298 def build_method(self):
299 for f in ['maven', 'gradle', 'kivy', 'buildozer']:
306 # like build_method, but prioritize output=
307 def output_method(self):
310 for f in ['maven', 'gradle', 'kivy', 'buildozer']:
318 version = 'r12b' # falls back to latest
319 paths = fdroidserver.common.config['ndk_paths']
320 if version not in paths:
322 return paths[version]
326 'versionCode': TYPE_INT,
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,
341 'prebuild': TYPE_SCRIPT,
342 'build': TYPE_SCRIPT,
343 'submodules': TYPE_BOOL,
344 'oldsdkloc': TYPE_BOOL,
345 'forceversion': TYPE_BOOL,
346 'forcevercode': TYPE_BOOL,
347 'novcheck': TYPE_BOOL,
348 'antifeatures': TYPE_LIST,
353 if name in flagtypes:
354 return flagtypes[name]
358 class FieldValidator():
360 Designates App metadata field types and checks that it matches
362 'name' - The long name of the field type
363 'matching' - List of possible values or regex expression
364 'sep' - Separator to use if value may be a list
365 'fields' - Metadata fields (Field:Value) of this type
368 def __init__(self, name, matching, fields):
370 self.matching = matching
371 self.compiled = re.compile(matching)
374 def check(self, v, appid):
382 if not self.compiled.match(v):
383 warn_or_exception("'%s' is not a valid %s in %s. Regex pattern: %s"
384 % (v, self.name, appid, self.matching))
387 # Generic value types
389 FieldValidator("Flattr ID",
393 FieldValidator("HTTP link",
395 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"]),
397 FieldValidator("Email",
398 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
401 FieldValidator("Bitcoin address",
402 r'^[a-zA-Z0-9]{27,34}$',
405 FieldValidator("Litecoin address",
406 r'^L[a-zA-Z0-9]{33}$',
409 FieldValidator("Repo Type",
410 r'^(git|git-svn|svn|hg|bzr|srclib)$',
413 FieldValidator("Binaries",
417 FieldValidator("Archive Policy",
418 r'^[0-9]+ versions$',
421 FieldValidator("Anti-Feature",
422 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets|KnownVuln|ApplicationDebuggable)$',
425 FieldValidator("Auto Update Mode",
426 r"^(Version .+|None)$",
429 FieldValidator("Update Check Mode",
430 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
435 # Check an app's metadata information for integrity errors
436 def check_metadata(app):
439 v.check(app[k], app.id)
442 # Formatter for descriptions. Create an instance, and call parseline() with
443 # each line of the description source from the metadata. At the end, call
444 # end() and then text_txt and text_html will contain the result.
445 class DescriptionFormatter:
452 def __init__(self, linkres):
455 self.state = self.stNONE
456 self.laststate = self.stNONE
459 self.html = io.StringIO()
460 self.text = io.StringIO()
462 self.linkResolver = None
463 self.linkResolver = linkres
465 def endcur(self, notstates=None):
466 if notstates and self.state in notstates:
468 if self.state == self.stPARA:
470 elif self.state == self.stUL:
472 elif self.state == self.stOL:
476 self.laststate = self.state
477 self.state = self.stNONE
478 whole_para = ' '.join(self.para_lines)
479 self.addtext(whole_para)
480 wrapped = textwrap.fill(whole_para, 80,
481 break_long_words=False,
482 break_on_hyphens=False)
483 self.text.write(wrapped)
484 self.html.write('</p>')
485 del self.para_lines[:]
488 self.html.write('</ul>')
489 self.laststate = self.state
490 self.state = self.stNONE
493 self.html.write('</ol>')
494 self.laststate = self.state
495 self.state = self.stNONE
497 def formatted(self, txt, htmlbody):
500 txt = html.escape(txt, quote=False)
502 index = txt.find("''")
507 if txt.startswith("'''"):
513 self.bold = not self.bold
521 self.ital = not self.ital
524 def linkify(self, txt):
528 index = txt.find("[")
530 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
531 res_plain += self.formatted(txt[:index], False)
532 res_html += self.formatted(txt[:index], True)
534 if txt.startswith("[["):
535 index = txt.find("]]")
537 warn_or_exception("Unterminated ]]")
539 if self.linkResolver:
540 url, urltext = self.linkResolver(url)
543 res_html += '<a href="' + url + '">' + html.escape(urltext, quote=False) + '</a>'
545 txt = txt[index + 2:]
547 index = txt.find("]")
549 warn_or_exception("Unterminated ]")
551 index2 = url.find(' ')
555 urltxt = url[index2 + 1:]
558 warn_or_exception("Url title is just the URL - use [url]")
559 res_html += '<a href="' + url + '">' + html.escape(urltxt, quote=False) + '</a>'
562 res_plain += ' (' + url + ')'
563 txt = txt[index + 1:]
565 def addtext(self, txt):
566 p, h = self.linkify(txt)
569 def parseline(self, line):
572 elif line.startswith('* '):
573 self.endcur([self.stUL])
574 if self.state != self.stUL:
575 self.html.write('<ul>')
576 self.state = self.stUL
577 if self.laststate != self.stNONE:
578 self.text.write('\n\n')
580 self.text.write('\n')
581 self.text.write(line)
582 self.html.write('<li>')
583 self.addtext(line[1:])
584 self.html.write('</li>')
585 elif line.startswith('# '):
586 self.endcur([self.stOL])
587 if self.state != self.stOL:
588 self.html.write('<ol>')
589 self.state = self.stOL
590 if self.laststate != self.stNONE:
591 self.text.write('\n\n')
593 self.text.write('\n')
594 self.text.write(line)
595 self.html.write('<li>')
596 self.addtext(line[1:])
597 self.html.write('</li>')
599 self.para_lines.append(line)
600 self.endcur([self.stPARA])
601 if self.state == self.stNONE:
602 self.state = self.stPARA
603 if self.laststate != self.stNONE:
604 self.text.write('\n\n')
605 self.html.write('<p>')
609 self.text_txt = self.text.getvalue()
610 self.text_html = self.html.getvalue()
615 # Parse multiple lines of description as written in a metadata file, returning
616 # a single string in text format and wrapped to 80 columns.
617 def description_txt(s):
618 ps = DescriptionFormatter(None)
619 for line in s.splitlines():
625 # Parse multiple lines of description as written in a metadata file, returning
626 # a single string in wiki format. Used for the Maintainer Notes field as well,
627 # because it's the same format.
628 def description_wiki(s):
632 # Parse multiple lines of description as written in a metadata file, returning
633 # a single string in HTML format.
634 def description_html(s, linkres):
635 ps = DescriptionFormatter(linkres)
636 for line in s.splitlines():
642 def parse_srclib(metadatapath):
646 # Defaults for fields that come from metadata
647 thisinfo['Repo Type'] = ''
648 thisinfo['Repo'] = ''
649 thisinfo['Subdir'] = None
650 thisinfo['Prepare'] = None
652 if not os.path.exists(metadatapath):
655 metafile = open(metadatapath, "r", encoding='utf-8')
658 for line in metafile:
660 line = line.rstrip('\r\n')
661 if not line or line.startswith("#"):
665 f, v = line.split(':', 1)
667 warn_or_exception("Invalid metadata in %s:%d" % (line, n))
670 thisinfo[f] = v.split(',')
680 """Read all srclib metadata.
682 The information read will be accessible as metadata.srclibs, which is a
683 dictionary, keyed on srclib name, with the values each being a dictionary
684 in the same format as that returned by the parse_srclib function.
686 A MetaDataException is raised if there are any problems with the srclib
691 # They were already loaded
692 if srclibs is not None:
698 if not os.path.exists(srcdir):
701 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
702 srclibname = os.path.basename(metadatapath[:-4])
703 srclibs[srclibname] = parse_srclib(metadatapath)
706 def read_metadata(xref=True, check_vcs=[]):
708 Read all metadata. Returns a list of 'app' objects (which are dictionaries as
709 returned by the parse_txt_metadata function.
711 check_vcs is the list of packageNames to check for .fdroid.yml in source
714 # Always read the srclibs before the apps, since they can use a srlib as
715 # their source repository.
720 for basedir in ('metadata', 'tmp'):
721 if not os.path.exists(basedir):
724 # If there are multiple metadata files for a single appid, then the first
725 # file that is parsed wins over all the others, and the rest throw an
726 # exception. So the original .txt format is parsed first, at least until
727 # newer formats stabilize.
729 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
730 + glob.glob(os.path.join('metadata', '*.json'))
731 + glob.glob(os.path.join('metadata', '*.yml'))
732 + glob.glob('.fdroid.txt')
733 + glob.glob('.fdroid.json')
734 + glob.glob('.fdroid.yml')):
735 packageName, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
736 if packageName in apps:
737 warn_or_exception("Found multiple metadata files for " + packageName)
738 app = parse_metadata(metadatapath, packageName in check_vcs)
743 # Parse all descriptions at load time, just to ensure cross-referencing
744 # errors are caught early rather than when they hit the build server.
747 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
748 warn_or_exception("Cannot resolve app id " + appid)
750 for appid, app in apps.items():
752 description_html(app.Description, linkres)
753 except MetaDataException as e:
754 warn_or_exception("Problem with description of " + appid +
760 # Port legacy ';' separators
761 list_sep = re.compile(r'[,;]')
764 def split_list_values(s):
766 for v in re.split(list_sep, s):
776 def get_default_app_info(metadatapath=None):
777 if metadatapath is None:
780 appid, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
782 if appid == '.fdroid': # we have local metadata in the app's source
783 if os.path.exists('AndroidManifest.xml'):
784 manifestroot = fdroidserver.common.parse_xml('AndroidManifest.xml')
786 pattern = re.compile(""".*manifest\.srcFile\s+'AndroidManifest\.xml'.*""")
787 for root, dirs, files in os.walk(os.getcwd()):
788 if 'build.gradle' in files:
789 p = os.path.join(root, 'build.gradle')
790 with open(p, 'rb') as f:
792 m = pattern.search(data)
794 logging.debug('Using: ' + os.path.join(root, 'AndroidManifest.xml'))
795 manifestroot = fdroidserver.common.parse_xml(os.path.join(root, 'AndroidManifest.xml'))
797 if manifestroot is None:
798 warn_or_exception("Cannot find a packageName for {0}!".format(metadatapath))
799 appid = manifestroot.attrib['package']
802 app.metadatapath = metadatapath
803 if appid is not None:
809 def sorted_builds(builds):
810 return sorted(builds, key=lambda build: int(build.versionCode))
813 esc_newlines = re.compile(r'\\( |\n)')
816 def post_metadata_parse(app):
817 # TODO keep native types, convert only for .txt metadata
818 for k, v in app.items():
819 if type(v) in (float, int):
823 app['builds'] = app.pop('Builds')
825 if 'flavours' in app and app['flavours'] == [True]:
826 app['flavours'] = 'yes'
828 if isinstance(app.Categories, str):
829 app.Categories = [app.Categories]
830 elif app.Categories is None:
831 app.Categories = ['None']
833 app.Categories = [str(i) for i in app.Categories]
835 def _yaml_bool_unmapable(v):
836 return v in (True, False, [True], [False])
838 def _yaml_bool_unmap(v):
848 _bool_allowed = ('disable', 'kivy', 'maven', 'buildozer')
852 for build in app['builds']:
853 if not isinstance(build, Build):
855 for k, v in build.items():
857 if flagtype(k) == TYPE_LIST:
858 if _yaml_bool_unmapable(v):
859 build[k] = _yaml_bool_unmap(v)
861 if isinstance(v, str):
863 elif isinstance(v, bool):
868 elif flagtype(k) is TYPE_INT:
870 elif flagtype(k) is TYPE_STRING:
871 if isinstance(v, bool) and k in _bool_allowed:
874 if _yaml_bool_unmapable(v):
875 build[k] = _yaml_bool_unmap(v)
880 app.builds = sorted_builds(builds)
883 # Parse metadata for a single application.
885 # 'metadatapath' - the filename to read. The package id for the application comes
886 # from this filename. Pass None to get a blank entry.
888 # Returns a dictionary containing all the details of the application. There are
889 # two major kinds of information in the dictionary. Keys beginning with capital
890 # letters correspond directory to identically named keys in the metadata file.
891 # Keys beginning with lower case letters are generated in one way or another,
892 # and are not found verbatim in the metadata.
894 # Known keys not originating from the metadata are:
896 # 'builds' - a list of dictionaries containing build information
897 # for each defined build
898 # 'comments' - a list of comments from the metadata file. Each is
899 # a list of the form [field, comment] where field is
900 # the name of the field it preceded in the metadata
901 # file. Where field is None, the comment goes at the
902 # end of the file. Alternatively, 'build:version' is
903 # for a comment before a particular build version.
904 # 'descriptionlines' - original lines of description as formatted in the
909 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
910 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
914 if bool_true.match(s):
916 if bool_false.match(s):
918 warn_or_exception("Invalid bool '%s'" % s)
921 def parse_metadata(metadatapath, check_vcs=False):
922 '''parse metadata file, optionally checking the git repo for metadata first'''
924 _, ext = fdroidserver.common.get_extension(metadatapath)
925 accepted = fdroidserver.common.config['accepted_formats']
926 if ext not in accepted:
927 warn_or_exception('"%s" is not an accepted format, convert to: %s' % (
928 metadatapath, ', '.join(accepted)))
931 app.metadatapath = metadatapath
932 name, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
933 if name == '.fdroid':
938 with open(metadatapath, 'r', encoding='utf-8') as mf:
940 parse_txt_metadata(mf, app)
942 parse_json_metadata(mf, app)
944 parse_yaml_metadata(mf, app)
946 warn_or_exception('Unknown metadata format: %s' % metadatapath)
948 if check_vcs and app.Repo:
949 build_dir = fdroidserver.common.get_build_dir(app)
950 metadata_in_repo = os.path.join(build_dir, '.fdroid.yml')
951 if not os.path.isfile(metadata_in_repo):
952 vcs, build_dir = fdroidserver.common.setup_vcs(app)
953 if isinstance(vcs, fdroidserver.common.vcs_git):
954 vcs.gotorevision('HEAD') # HEAD since we can't know where else to go
955 if os.path.isfile(metadata_in_repo):
956 logging.debug('Including metadata from ' + metadata_in_repo)
957 # do not include fields already provided by main metadata file
958 app_in_repo = parse_metadata(metadata_in_repo)
959 for k, v in app_in_repo.items():
963 post_metadata_parse(app)
967 build = app.builds[-1]
969 root_dir = build.subdir
972 paths = fdroidserver.common.manifest_paths(root_dir, build.gradle)
973 _, _, app.id = fdroidserver.common.parse_androidmanifests(paths, app)
978 def parse_json_metadata(mf, app):
980 # fdroid metadata is only strings and booleans, no floats or ints.
981 # TODO create schema using https://pypi.python.org/pypi/jsonschema
982 jsoninfo = json.load(mf, parse_int=lambda s: s,
983 parse_float=lambda s: s)
985 for f in ['Description', 'Maintainer Notes']:
988 app[f] = '\n'.join(v)
992 def parse_yaml_metadata(mf, app):
993 yamldata = yaml.load(mf, Loader=YamlLoader)
999 def write_yaml(mf, app):
1001 # import rumael.yaml and check version
1004 except ImportError as e:
1005 raise FDroidException('ruamel.yaml not instlled, can not write metadata.') from e
1006 if not ruamel.yaml.__version__:
1007 raise FDroidException('ruamel.yaml.__version__ not accessible. Please make sure a ruamel.yaml >= 0.13 is installed..')
1008 m = re.match('(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.(?P<patch>[0-9]+)(-.+)?',
1009 ruamel.yaml.__version__)
1011 raise FDroidException('ruamel.yaml version malfored, please install an upstream version of ruamel.yaml')
1012 if int(m.group('major')) < 0 or int(m.group('minor')) < 13:
1013 raise FDroidException('currently installed version of ruamel.yaml ({}) is too old, >= 1.13 required.'.format(ruamel.yaml.__version__))
1014 # suiteable version ruamel.yaml imported successfully
1016 _yaml_bools_true = ('y', 'Y', 'yes', 'Yes', 'YES',
1017 'true', 'True', 'TRUE',
1019 _yaml_bools_false = ('n', 'N', 'no', 'No', 'NO',
1020 'false', 'False', 'FALSE',
1021 'off', 'Off', 'OFF')
1022 _yaml_bools_plus_lists = []
1023 _yaml_bools_plus_lists.extend(_yaml_bools_true)
1024 _yaml_bools_plus_lists.extend([[x] for x in _yaml_bools_true])
1025 _yaml_bools_plus_lists.extend(_yaml_bools_false)
1026 _yaml_bools_plus_lists.extend([[x] for x in _yaml_bools_false])
1028 def _class_as_dict_representer(dumper, data):
1029 '''Creates a YAML representation of a App/Build instance'''
1030 return dumper.represent_dict(data)
1032 def _field_to_yaml(typ, value):
1033 if typ is TYPE_STRING:
1034 if value in _yaml_bools_plus_lists:
1035 return ruamel.yaml.scalarstring.SingleQuotedScalarString(str(value))
1037 elif typ is TYPE_INT:
1039 elif typ is TYPE_MULTILINE:
1041 return ruamel.yaml.scalarstring.preserve_literal(str(value))
1044 elif typ is TYPE_SCRIPT:
1046 return ruamel.yaml.scalarstring.preserve_literal(value)
1052 def _app_to_yaml(app):
1053 cm = ruamel.yaml.comments.CommentedMap()
1054 insert_newline = False
1055 for field in yaml_app_field_order:
1057 # next iteration will need to insert a newline
1058 insert_newline = True
1060 if app.get(field) or field is 'Builds':
1061 # .txt calls it 'builds' internally, everywhere else its 'Builds'
1062 if field is 'Builds':
1063 if app.get('builds'):
1064 cm.update({field: _builds_to_yaml(app)})
1065 elif field is 'CurrentVersionCode':
1066 cm.update({field: _field_to_yaml(TYPE_INT, getattr(app, field))})
1068 cm.update({field: _field_to_yaml(fieldtype(field), getattr(app, field))})
1071 # we need to prepend a newline in front of this field
1072 insert_newline = False
1073 # inserting empty lines is not supported so we add a
1074 # bogus comment and over-write its value
1075 cm.yaml_set_comment_before_after_key(field, 'bogus')
1076 cm.ca.items[field][1][-1].value = '\n'
1079 def _builds_to_yaml(app):
1080 fields = ['versionName', 'versionCode']
1081 fields.extend(build_flags_order)
1082 builds = ruamel.yaml.comments.CommentedSeq()
1083 for build in app.builds:
1084 b = ruamel.yaml.comments.CommentedMap()
1085 for field in fields:
1086 if hasattr(build, field) and getattr(build, field):
1087 value = getattr(build, field)
1088 if field == 'gradle' and value == ['off']:
1089 value = [ruamel.yaml.scalarstring.SingleQuotedScalarString('off')]
1090 if field in ('disable', 'kivy', 'maven', 'buildozer'):
1093 elif value == 'yes':
1095 b.update({field: _field_to_yaml(flagtype(field), value)})
1098 # insert extra empty lines between build entries
1099 for i in range(1, len(builds)):
1100 builds.yaml_set_comment_before_after_key(i, 'bogus')
1101 builds.ca.items[i][1][-1].value = '\n'
1105 yaml_app_field_order = [
1141 'UpdateCheckIgnore',
1146 'CurrentVersionCode',
1151 yaml_app = _app_to_yaml(app)
1152 ruamel.yaml.round_trip_dump(yaml_app, mf, indent=4, block_seq_indent=2)
1155 build_line_sep = re.compile(r'(?<!\\),')
1156 build_cont = re.compile(r'^[ \t]')
1159 def parse_txt_metadata(mf, app):
1163 def add_buildflag(p, build):
1165 warn_or_exception("Empty build flag at {1}"
1166 .format(buildlines[0], linedesc))
1167 bv = p.split('=', 1)
1169 warn_or_exception("Invalid build flag at {0} in {1}"
1170 .format(buildlines[0], linedesc))
1175 pk = 'androidupdate' # avoid conflicting with Build(dict).update()
1178 pv = split_list_values(pv)
1180 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1182 elif t == TYPE_BOOL:
1183 build[pk] = _decode_bool(pv)
1185 def parse_buildline(lines):
1187 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1189 warn_or_exception("Invalid build format: " + v + " in " + mf.name)
1191 build.versionName = parts[0]
1192 build.versionCode = parts[1]
1193 check_versionCode(build.versionCode)
1195 if parts[2].startswith('!'):
1196 # For backwards compatibility, handle old-style disabling,
1197 # including attempting to extract the commit from the message
1198 build.disable = parts[2][1:]
1199 commit = 'unknown - see disabled'
1200 index = parts[2].rfind('at ')
1202 commit = parts[2][index + 3:]
1203 if commit.endswith(')'):
1204 commit = commit[:-1]
1205 build.commit = commit
1207 build.commit = parts[2]
1209 add_buildflag(p, build)
1213 def check_versionCode(versionCode):
1217 warn_or_exception('Invalid versionCode: "' + versionCode + '" is not an integer!')
1219 def add_comments(key):
1222 app.comments[key] = list(curcomments)
1227 multiline_lines = []
1237 linedesc = "%s:%d" % (mf.name, c)
1238 line = line.rstrip('\r\n')
1240 if build_cont.match(line):
1241 if line.endswith('\\'):
1242 buildlines.append(line[:-1].lstrip())
1244 buildlines.append(line.lstrip())
1245 bl = ''.join(buildlines)
1246 add_buildflag(bl, build)
1249 if not build.commit and not build.disable:
1250 warn_or_exception("No commit specified for {0} in {1}"
1251 .format(build.versionName, linedesc))
1253 app.builds.append(build)
1254 add_comments('build:' + build.versionCode)
1260 if line.startswith("#"):
1261 curcomments.append(line[1:].strip())
1264 f, v = line.split(':', 1)
1266 warn_or_exception("Invalid metadata in " + linedesc)
1268 if f not in app_fields:
1269 warn_or_exception('Unrecognised app field: ' + f)
1271 # Translate obsolete fields...
1272 if f == 'Market Version':
1273 f = 'Current Version'
1274 if f == 'Market Version Code':
1275 f = 'Current Version Code'
1277 f = f.replace(' ', '')
1279 ftype = fieldtype(f)
1280 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1282 if ftype == TYPE_MULTILINE:
1285 warn_or_exception("Unexpected text on same line as "
1286 + f + " in " + linedesc)
1287 elif ftype == TYPE_STRING:
1289 elif ftype == TYPE_LIST:
1290 app[f] = split_list_values(v)
1291 elif ftype == TYPE_BUILD:
1292 if v.endswith("\\"):
1295 buildlines.append(v[:-1])
1297 build = parse_buildline([v])
1298 app.builds.append(build)
1299 add_comments('build:' + app.builds[-1].versionCode)
1300 elif ftype == TYPE_BUILD_V2:
1303 warn_or_exception('Build should have comma-separated',
1304 'versionName and versionCode,',
1305 'not "{0}", in {1}'.format(v, linedesc))
1307 build.versionName = vv[0]
1308 build.versionCode = vv[1]
1309 check_versionCode(build.versionCode)
1311 if build.versionCode in vc_seen:
1312 warn_or_exception('Duplicate build recipe found for versionCode %s in %s'
1313 % (build.versionCode, linedesc))
1314 vc_seen.add(build.versionCode)
1317 elif ftype == TYPE_OBSOLETE:
1318 pass # Just throw it away!
1320 warn_or_exception("Unrecognised field '" + f + "' in " + linedesc)
1321 elif mode == 1: # Multiline field
1324 app[f] = '\n'.join(multiline_lines)
1325 del multiline_lines[:]
1327 multiline_lines.append(line)
1328 elif mode == 2: # Line continuation mode in Build Version
1329 if line.endswith("\\"):
1330 buildlines.append(line[:-1])
1332 buildlines.append(line)
1333 build = parse_buildline(buildlines)
1334 app.builds.append(build)
1335 add_comments('build:' + app.builds[-1].versionCode)
1339 # Mode at end of file should always be 0
1341 warn_or_exception(f + " not terminated in " + mf.name)
1343 warn_or_exception("Unterminated continuation in " + mf.name)
1345 warn_or_exception("Unterminated build in " + mf.name)
1350 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1352 def field_to_attr(f):
1354 Translates human-readable field names to attribute names, e.g.
1355 'Auto Name' to 'AutoName'
1357 return f.replace(' ', '')
1359 def attr_to_field(k):
1361 Translates attribute names to human-readable field names, e.g.
1362 'AutoName' to 'Auto Name'
1366 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
1369 def w_comments(key):
1370 if key not in app.comments:
1372 for line in app.comments[key]:
1375 def w_field_always(f, v=None):
1376 key = field_to_attr(f)
1382 def w_field_nonempty(f, v=None):
1383 key = field_to_attr(f)
1390 w_field_nonempty('Disabled')
1391 w_field_nonempty('AntiFeatures')
1392 w_field_nonempty('Provides')
1393 w_field_always('Categories')
1394 w_field_always('License')
1395 w_field_nonempty('Author Name')
1396 w_field_nonempty('Author Email')
1397 w_field_nonempty('Author Web Site')
1398 w_field_always('Web Site')
1399 w_field_always('Source Code')
1400 w_field_always('Issue Tracker')
1401 w_field_nonempty('Changelog')
1402 w_field_nonempty('Donate')
1403 w_field_nonempty('FlattrID')
1404 w_field_nonempty('Bitcoin')
1405 w_field_nonempty('Litecoin')
1407 w_field_nonempty('Name')
1408 w_field_nonempty('Auto Name')
1409 w_field_nonempty('Summary')
1410 w_field_nonempty('Description', description_txt(app.Description))
1412 if app.RequiresRoot:
1413 w_field_always('Requires Root', 'yes')
1416 w_field_always('Repo Type')
1417 w_field_always('Repo')
1419 w_field_always('Binaries')
1422 for build in app.builds:
1424 if build.versionName == "Ignore":
1427 w_comments('build:%s' % build.versionCode)
1431 if app.MaintainerNotes:
1432 w_field_always('Maintainer Notes', app.MaintainerNotes)
1435 w_field_nonempty('Archive Policy')
1436 w_field_always('Auto Update Mode')
1437 w_field_always('Update Check Mode')
1438 w_field_nonempty('Update Check Ignore')
1439 w_field_nonempty('Vercode Operation')
1440 w_field_nonempty('Update Check Name')
1441 w_field_nonempty('Update Check Data')
1442 if app.CurrentVersion:
1443 w_field_always('Current Version')
1444 w_field_always('Current Version Code')
1445 if app.NoSourceSince:
1447 w_field_always('No Source Since')
1451 # Write a metadata file in txt format.
1453 # 'mf' - Writer interface (file, StringIO, ...)
1454 # 'app' - The app data
1455 def write_txt(mf, app):
1457 def w_comment(line):
1458 mf.write("# %s\n" % line)
1464 elif t == TYPE_MULTILINE:
1465 v = '\n' + v + '\n.'
1466 mf.write("%s:%s\n" % (f, v))
1469 mf.write("Build:%s,%s\n" % (build.versionName, build.versionCode))
1471 for f in build_flags_order:
1477 if f == 'androidupdate':
1478 f = 'update' # avoid conflicting with Build(dict).update()
1479 mf.write(' %s=' % f)
1480 if t == TYPE_STRING:
1482 elif t == TYPE_BOOL:
1484 elif t == TYPE_SCRIPT:
1486 for s in v.split(' && '):
1490 mf.write(' && \\\n ')
1492 elif t == TYPE_LIST:
1493 mf.write(','.join(v))
1497 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1500 def write_metadata(metadatapath, app):
1501 _, ext = fdroidserver.common.get_extension(metadatapath)
1502 accepted = fdroidserver.common.config['accepted_formats']
1503 if ext not in accepted:
1504 warn_or_exception('Cannot write "%s", not an accepted format, use: %s'
1505 % (metadatapath, ', '.join(accepted)))
1508 with open(metadatapath, 'w', encoding='utf8') as mf:
1510 return write_txt(mf, app)
1512 return write_yaml(mf, app)
1513 except FDroidException as e:
1514 os.remove(metadatapath)
1517 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1520 def add_metadata_arguments(parser):
1521 '''add common command line flags related to metadata processing'''
1522 parser.add_argument("-W", default='error',
1523 help=_("force errors to be warnings, or ignore"))