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.exception import MetaDataException, FDroidException
41 warnings_action = None
44 def warn_or_exception(value):
45 '''output warning or Exception depending on -W'''
46 if warnings_action == 'ignore':
48 elif warnings_action == 'error':
49 raise MetaDataException(value)
51 logging.warning(value)
54 # To filter which ones should be written to the metadata files if
85 'Update Check Ignore',
90 'Current Version Code',
94 'comments', # For formats that don't do inline comments
95 'builds', # For formats that do builds as a list
101 def __init__(self, copydict=None):
103 super().__init__(copydict)
108 self.AntiFeatures = []
110 self.Categories = ['None']
111 self.License = 'Unknown'
112 self.AuthorName = None
113 self.AuthorEmail = None
114 self.AuthorWebSite = None
117 self.IssueTracker = ''
126 self.Description = ''
127 self.RequiresRoot = False
131 self.MaintainerNotes = ''
132 self.ArchivePolicy = None
133 self.AutoUpdateMode = 'None'
134 self.UpdateCheckMode = 'None'
135 self.UpdateCheckIgnore = None
136 self.VercodeOperation = None
137 self.UpdateCheckName = None
138 self.UpdateCheckData = None
139 self.CurrentVersion = ''
140 self.CurrentVersionCode = None
141 self.NoSourceSince = ''
144 self.metadatapath = None
148 self.lastUpdated = None
150 def __getattr__(self, name):
154 raise AttributeError("No such attribute: " + name)
156 def __setattr__(self, name, value):
159 def __delattr__(self, name):
163 raise AttributeError("No such attribute: " + name)
165 def get_last_build(self):
166 if len(self.builds) > 0:
167 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 = [
237 # old .txt format has version name/code inline in the 'Build:' line
238 # but YAML and JSON have a explicit key for them
239 build_flags = ['versionName', 'versionCode'] + build_flags_order
244 def __init__(self, copydict=None):
249 self.submodules = False
256 self.buildozer = 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
277 self.antifeatures = []
279 super().__init__(copydict)
282 def __getattr__(self, name):
286 raise AttributeError("No such attribute: " + name)
288 def __setattr__(self, name, value):
291 def __delattr__(self, name):
295 raise AttributeError("No such attribute: " + name)
297 def build_method(self):
298 for f in ['maven', 'gradle', 'kivy', 'buildozer']:
305 # like build_method, but prioritize output=
306 def output_method(self):
309 for f in ['maven', 'gradle', 'kivy', 'buildozer']:
317 version = 'r12b' # falls back to latest
318 paths = fdroidserver.common.config['ndk_paths']
319 if version not in paths:
321 return paths[version]
325 'versionCode': TYPE_INT,
326 'extlibs': TYPE_LIST,
327 'srclibs': TYPE_LIST,
330 'buildjni': TYPE_LIST,
331 'preassemble': TYPE_LIST,
332 'androidupdate': TYPE_LIST,
333 'scanignore': TYPE_LIST,
334 'scandelete': TYPE_LIST,
336 'antcommands': TYPE_LIST,
337 '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,
347 'antifeatures': TYPE_LIST,
352 if name in flagtypes:
353 return flagtypes[name]
357 class FieldValidator():
359 Designates App metadata field types and checks that it matches
361 'name' - The long name of the field type
362 'matching' - List of possible values or regex expression
363 'sep' - Separator to use if value may be a list
364 'fields' - Metadata fields (Field:Value) of this type
367 def __init__(self, name, matching, fields):
369 self.matching = matching
370 self.compiled = re.compile(matching)
373 def check(self, v, appid):
381 if not self.compiled.match(v):
382 warn_or_exception("'%s' is not a valid %s in %s. Regex pattern: %s"
383 % (v, self.name, appid, self.matching))
386 # Generic value types
388 FieldValidator("Flattr ID",
392 FieldValidator("HTTP link",
394 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"]),
396 FieldValidator("Email",
397 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
400 FieldValidator("Bitcoin address",
401 r'^[a-zA-Z0-9]{27,34}$',
404 FieldValidator("Litecoin address",
405 r'^L[a-zA-Z0-9]{33}$',
408 FieldValidator("Repo Type",
409 r'^(git|git-svn|svn|hg|bzr|srclib)$',
412 FieldValidator("Binaries",
416 FieldValidator("Archive Policy",
417 r'^[0-9]+ versions$',
420 FieldValidator("Anti-Feature",
421 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets|KnownVuln|ApplicationDebuggable)$',
424 FieldValidator("Auto Update Mode",
425 r"^(Version .+|None)$",
428 FieldValidator("Update Check Mode",
429 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
434 # Check an app's metadata information for integrity errors
435 def check_metadata(app):
438 v.check(app[k], app.id)
441 # Formatter for descriptions. Create an instance, and call parseline() with
442 # each line of the description source from the metadata. At the end, call
443 # end() and then text_txt and text_html will contain the result.
444 class DescriptionFormatter:
451 def __init__(self, linkres):
454 self.state = self.stNONE
455 self.laststate = self.stNONE
458 self.html = io.StringIO()
459 self.text = io.StringIO()
461 self.linkResolver = None
462 self.linkResolver = linkres
464 def endcur(self, notstates=None):
465 if notstates and self.state in notstates:
467 if self.state == self.stPARA:
469 elif self.state == self.stUL:
471 elif self.state == self.stOL:
475 self.laststate = self.state
476 self.state = self.stNONE
477 whole_para = ' '.join(self.para_lines)
478 self.addtext(whole_para)
479 wrapped = textwrap.fill(whole_para, 80,
480 break_long_words=False,
481 break_on_hyphens=False)
482 self.text.write(wrapped)
483 self.html.write('</p>')
484 del self.para_lines[:]
487 self.html.write('</ul>')
488 self.laststate = self.state
489 self.state = self.stNONE
492 self.html.write('</ol>')
493 self.laststate = self.state
494 self.state = self.stNONE
496 def formatted(self, txt, htmlbody):
499 txt = html.escape(txt, quote=False)
501 index = txt.find("''")
506 if txt.startswith("'''"):
512 self.bold = not self.bold
520 self.ital = not self.ital
523 def linkify(self, txt):
527 index = txt.find("[")
529 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
530 res_plain += self.formatted(txt[:index], False)
531 res_html += self.formatted(txt[:index], True)
533 if txt.startswith("[["):
534 index = txt.find("]]")
536 warn_or_exception("Unterminated ]]")
538 if self.linkResolver:
539 url, urltext = self.linkResolver(url)
542 res_html += '<a href="' + url + '">' + html.escape(urltext, quote=False) + '</a>'
544 txt = txt[index + 2:]
546 index = txt.find("]")
548 warn_or_exception("Unterminated ]")
550 index2 = url.find(' ')
554 urltxt = url[index2 + 1:]
557 warn_or_exception("Url title is just the URL - use [url]")
558 res_html += '<a href="' + url + '">' + html.escape(urltxt, quote=False) + '</a>'
561 res_plain += ' (' + url + ')'
562 txt = txt[index + 1:]
564 def addtext(self, txt):
565 p, h = self.linkify(txt)
568 def parseline(self, line):
571 elif line.startswith('* '):
572 self.endcur([self.stUL])
573 if self.state != self.stUL:
574 self.html.write('<ul>')
575 self.state = self.stUL
576 if self.laststate != self.stNONE:
577 self.text.write('\n\n')
579 self.text.write('\n')
580 self.text.write(line)
581 self.html.write('<li>')
582 self.addtext(line[1:])
583 self.html.write('</li>')
584 elif line.startswith('# '):
585 self.endcur([self.stOL])
586 if self.state != self.stOL:
587 self.html.write('<ol>')
588 self.state = self.stOL
589 if self.laststate != self.stNONE:
590 self.text.write('\n\n')
592 self.text.write('\n')
593 self.text.write(line)
594 self.html.write('<li>')
595 self.addtext(line[1:])
596 self.html.write('</li>')
598 self.para_lines.append(line)
599 self.endcur([self.stPARA])
600 if self.state == self.stNONE:
601 self.state = self.stPARA
602 if self.laststate != self.stNONE:
603 self.text.write('\n\n')
604 self.html.write('<p>')
608 self.text_txt = self.text.getvalue()
609 self.text_html = self.html.getvalue()
614 # Parse multiple lines of description as written in a metadata file, returning
615 # a single string in text format and wrapped to 80 columns.
616 def description_txt(s):
617 ps = DescriptionFormatter(None)
618 for line in s.splitlines():
624 # Parse multiple lines of description as written in a metadata file, returning
625 # a single string in wiki format. Used for the Maintainer Notes field as well,
626 # because it's the same format.
627 def description_wiki(s):
631 # Parse multiple lines of description as written in a metadata file, returning
632 # a single string in HTML format.
633 def description_html(s, linkres):
634 ps = DescriptionFormatter(linkres)
635 for line in s.splitlines():
641 def parse_srclib(metadatapath):
645 # Defaults for fields that come from metadata
646 thisinfo['Repo Type'] = ''
647 thisinfo['Repo'] = ''
648 thisinfo['Subdir'] = None
649 thisinfo['Prepare'] = None
651 if not os.path.exists(metadatapath):
654 metafile = open(metadatapath, "r", encoding='utf-8')
657 for line in metafile:
659 line = line.rstrip('\r\n')
660 if not line or line.startswith("#"):
664 f, v = line.split(':', 1)
666 warn_or_exception("Invalid metadata in %s:%d" % (line, n))
669 thisinfo[f] = v.split(',')
679 """Read all srclib metadata.
681 The information read will be accessible as metadata.srclibs, which is a
682 dictionary, keyed on srclib name, with the values each being a dictionary
683 in the same format as that returned by the parse_srclib function.
685 A MetaDataException is raised if there are any problems with the srclib
690 # They were already loaded
691 if srclibs is not None:
697 if not os.path.exists(srcdir):
700 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
701 srclibname = os.path.basename(metadatapath[:-4])
702 srclibs[srclibname] = parse_srclib(metadatapath)
705 def read_metadata(xref=True, check_vcs=[]):
707 Read all metadata. Returns a list of 'app' objects (which are dictionaries as
708 returned by the parse_txt_metadata function.
710 check_vcs is the list of packageNames to check for .fdroid.yml in source
713 # Always read the srclibs before the apps, since they can use a srlib as
714 # their source repository.
719 for basedir in ('metadata', 'tmp'):
720 if not os.path.exists(basedir):
723 # If there are multiple metadata files for a single appid, then the first
724 # file that is parsed wins over all the others, and the rest throw an
725 # exception. So the original .txt format is parsed first, at least until
726 # newer formats stabilize.
728 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
729 + glob.glob(os.path.join('metadata', '*.json'))
730 + glob.glob(os.path.join('metadata', '*.yml'))
731 + glob.glob('.fdroid.txt')
732 + glob.glob('.fdroid.json')
733 + glob.glob('.fdroid.yml')):
734 packageName, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
735 if packageName in apps:
736 warn_or_exception("Found multiple metadata files for " + packageName)
737 app = parse_metadata(metadatapath, packageName in check_vcs)
742 # Parse all descriptions at load time, just to ensure cross-referencing
743 # errors are caught early rather than when they hit the build server.
746 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
747 warn_or_exception("Cannot resolve app id " + appid)
749 for appid, app in apps.items():
751 description_html(app.Description, linkres)
752 except MetaDataException as e:
753 warn_or_exception("Problem with description of " + appid +
759 # Port legacy ';' separators
760 list_sep = re.compile(r'[,;]')
763 def split_list_values(s):
765 for v in re.split(list_sep, s):
775 def get_default_app_info(metadatapath=None):
776 if metadatapath is None:
779 appid, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
781 if appid == '.fdroid': # we have local metadata in the app's source
782 if os.path.exists('AndroidManifest.xml'):
783 manifestroot = fdroidserver.common.parse_xml('AndroidManifest.xml')
785 pattern = re.compile(""".*manifest\.srcFile\s+'AndroidManifest\.xml'.*""")
786 for root, dirs, files in os.walk(os.getcwd()):
787 if 'build.gradle' in files:
788 p = os.path.join(root, 'build.gradle')
789 with open(p, 'rb') as f:
791 m = pattern.search(data)
793 logging.debug('Using: ' + os.path.join(root, 'AndroidManifest.xml'))
794 manifestroot = fdroidserver.common.parse_xml(os.path.join(root, 'AndroidManifest.xml'))
796 if manifestroot is None:
797 warn_or_exception("Cannot find a packageName for {0}!".format(metadatapath))
798 appid = manifestroot.attrib['package']
801 app.metadatapath = metadatapath
802 if appid is not None:
808 def sorted_builds(builds):
809 return sorted(builds, key=lambda build: int(build.versionCode))
812 esc_newlines = re.compile(r'\\( |\n)')
815 def post_metadata_parse(app):
816 # TODO keep native types, convert only for .txt metadata
817 for k, v in app.items():
818 if type(v) in (float, int):
822 app['builds'] = app.pop('Builds')
824 if 'flavours' in app and app['flavours'] == [True]:
825 app['flavours'] = 'yes'
827 if isinstance(app.Categories, str):
828 app.Categories = [app.Categories]
829 elif app.Categories is None:
830 app.Categories = ['None']
832 app.Categories = [str(i) for i in app.Categories]
834 def _yaml_bool_unmapable(v):
835 return v in (True, False, [True], [False])
837 def _yaml_bool_unmap(v):
847 _bool_allowed = ('disable', 'kivy', 'maven', 'buildozer')
851 for build in app['builds']:
852 if not isinstance(build, Build):
854 for k, v in build.items():
856 if flagtype(k) == TYPE_LIST:
857 if _yaml_bool_unmapable(v):
858 build[k] = _yaml_bool_unmap(v)
860 if isinstance(v, str):
862 elif isinstance(v, bool):
867 elif flagtype(k) is TYPE_INT:
869 elif flagtype(k) is TYPE_STRING:
870 if isinstance(v, bool) and k in _bool_allowed:
873 if _yaml_bool_unmapable(v):
874 build[k] = _yaml_bool_unmap(v)
879 app.builds = sorted_builds(builds)
882 # Parse metadata for a single application.
884 # 'metadatapath' - the filename to read. The package id for the application comes
885 # from this filename. Pass None to get a blank entry.
887 # Returns a dictionary containing all the details of the application. There are
888 # two major kinds of information in the dictionary. Keys beginning with capital
889 # letters correspond directory to identically named keys in the metadata file.
890 # Keys beginning with lower case letters are generated in one way or another,
891 # and are not found verbatim in the metadata.
893 # Known keys not originating from the metadata are:
895 # 'builds' - a list of dictionaries containing build information
896 # for each defined build
897 # 'comments' - a list of comments from the metadata file. Each is
898 # a list of the form [field, comment] where field is
899 # the name of the field it preceded in the metadata
900 # file. Where field is None, the comment goes at the
901 # end of the file. Alternatively, 'build:version' is
902 # for a comment before a particular build version.
903 # 'descriptionlines' - original lines of description as formatted in the
908 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
909 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
913 if bool_true.match(s):
915 if bool_false.match(s):
917 warn_or_exception("Invalid bool '%s'" % s)
920 def parse_metadata(metadatapath, check_vcs=False):
921 '''parse metadata file, optionally checking the git repo for metadata first'''
923 _, ext = fdroidserver.common.get_extension(metadatapath)
924 accepted = fdroidserver.common.config['accepted_formats']
925 if ext not in accepted:
926 warn_or_exception('"%s" is not an accepted format, convert to: %s' % (
927 metadatapath, ', '.join(accepted)))
930 app.metadatapath = metadatapath
931 name, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
932 if name == '.fdroid':
937 with open(metadatapath, 'r', encoding='utf-8') as mf:
939 parse_txt_metadata(mf, app)
941 parse_json_metadata(mf, app)
943 parse_yaml_metadata(mf, app)
945 warn_or_exception('Unknown metadata format: %s' % metadatapath)
947 if check_vcs and app.Repo:
948 build_dir = fdroidserver.common.get_build_dir(app)
949 metadata_in_repo = os.path.join(build_dir, '.fdroid.yml')
950 if not os.path.isfile(metadata_in_repo):
951 vcs, build_dir = fdroidserver.common.setup_vcs(app)
952 if isinstance(vcs, fdroidserver.common.vcs_git):
953 vcs.gotorevision('HEAD') # HEAD since we can't know where else to go
954 if os.path.isfile(metadata_in_repo):
955 logging.debug('Including metadata from ' + metadata_in_repo)
956 # do not include fields already provided by main metadata file
957 app_in_repo = parse_metadata(metadata_in_repo)
958 for k, v in app_in_repo.items():
962 post_metadata_parse(app)
966 build = app.builds[-1]
968 root_dir = build.subdir
971 paths = fdroidserver.common.manifest_paths(root_dir, build.gradle)
972 _, _, app.id = fdroidserver.common.parse_androidmanifests(paths, app)
977 def parse_json_metadata(mf, app):
979 # fdroid metadata is only strings and booleans, no floats or ints.
980 # TODO create schema using https://pypi.python.org/pypi/jsonschema
981 jsoninfo = json.load(mf, parse_int=lambda s: s,
982 parse_float=lambda s: s)
984 for f in ['Description', 'Maintainer Notes']:
987 app[f] = '\n'.join(v)
991 def parse_yaml_metadata(mf, app):
992 yamldata = yaml.load(mf, Loader=YamlLoader)
998 def write_yaml(mf, app):
1000 # import rumael.yaml and check version
1003 except ImportError as e:
1004 raise FDroidException('ruamel.yaml not instlled, can not write metadata.') from e
1005 if not ruamel.yaml.__version__:
1006 raise FDroidException('ruamel.yaml.__version__ not accessible. Please make sure a ruamel.yaml >= 0.13 is installed..')
1007 m = re.match('(?P<major>[0-9]+)\.(?P<minor>[0-9]+)\.(?P<patch>[0-9]+)(-.+)?',
1008 ruamel.yaml.__version__)
1010 raise FDroidException('ruamel.yaml version malfored, please install an upstream version of ruamel.yaml')
1011 if int(m.group('major')) < 0 or int(m.group('minor')) < 13:
1012 raise FDroidException('currently installed version of ruamel.yaml ({}) is too old, >= 1.13 required.'.format(ruamel.yaml.__version__))
1013 # suiteable version ruamel.yaml imported successfully
1015 _yaml_bools_true = ('y', 'Y', 'yes', 'Yes', 'YES',
1016 'true', 'True', 'TRUE',
1018 _yaml_bools_false = ('n', 'N', 'no', 'No', 'NO',
1019 'false', 'False', 'FALSE',
1020 'off', 'Off', 'OFF')
1021 _yaml_bools_plus_lists = []
1022 _yaml_bools_plus_lists.extend(_yaml_bools_true)
1023 _yaml_bools_plus_lists.extend([[x] for x in _yaml_bools_true])
1024 _yaml_bools_plus_lists.extend(_yaml_bools_false)
1025 _yaml_bools_plus_lists.extend([[x] for x in _yaml_bools_false])
1027 def _class_as_dict_representer(dumper, data):
1028 '''Creates a YAML representation of a App/Build instance'''
1029 return dumper.represent_dict(data)
1031 def _field_to_yaml(typ, value):
1032 if typ is TYPE_STRING:
1033 if value in _yaml_bools_plus_lists:
1034 return ruamel.yaml.scalarstring.SingleQuotedScalarString(str(value))
1036 elif typ is TYPE_INT:
1038 elif typ is TYPE_MULTILINE:
1040 return ruamel.yaml.scalarstring.preserve_literal(str(value))
1043 elif typ is TYPE_SCRIPT:
1045 return ruamel.yaml.scalarstring.preserve_literal(value)
1051 def _app_to_yaml(app):
1052 cm = ruamel.yaml.comments.CommentedMap()
1053 insert_newline = False
1054 for field in yaml_app_field_order:
1056 # next iteration will need to insert a newline
1057 insert_newline = True
1059 if app.get(field) or field is 'Builds':
1060 # .txt calls it 'builds' internally, everywhere else its 'Builds'
1061 if field is 'Builds':
1062 if app.get('builds'):
1063 cm.update({field: _builds_to_yaml(app)})
1064 elif field is 'CurrentVersionCode':
1065 cm.update({field: _field_to_yaml(TYPE_INT, getattr(app, field))})
1067 cm.update({field: _field_to_yaml(fieldtype(field), getattr(app, field))})
1070 # we need to prepend a newline in front of this field
1071 insert_newline = False
1072 # inserting empty lines is not supported so we add a
1073 # bogus comment and over-write its value
1074 cm.yaml_set_comment_before_after_key(field, 'bogus')
1075 cm.ca.items[field][1][-1].value = '\n'
1078 def _builds_to_yaml(app):
1079 fields = ['versionName', 'versionCode']
1080 fields.extend(build_flags_order)
1081 builds = ruamel.yaml.comments.CommentedSeq()
1082 for build in app.builds:
1083 b = ruamel.yaml.comments.CommentedMap()
1084 for field in fields:
1085 if hasattr(build, field) and getattr(build, field):
1086 value = getattr(build, field)
1087 if field == 'gradle' and value == ['off']:
1088 value = [ruamel.yaml.scalarstring.SingleQuotedScalarString('off')]
1089 if field in ('disable', 'kivy', 'maven', 'buildozer'):
1092 elif value == 'yes':
1094 b.update({field: _field_to_yaml(flagtype(field), value)})
1097 # insert extra empty lines between build entries
1098 for i in range(1, len(builds)):
1099 builds.yaml_set_comment_before_after_key(i, 'bogus')
1100 builds.ca.items[i][1][-1].value = '\n'
1104 yaml_app_field_order = [
1140 'UpdateCheckIgnore',
1145 'CurrentVersionCode',
1150 yaml_app = _app_to_yaml(app)
1151 ruamel.yaml.round_trip_dump(yaml_app, mf, indent=4, block_seq_indent=2)
1154 build_line_sep = re.compile(r'(?<!\\),')
1155 build_cont = re.compile(r'^[ \t]')
1158 def parse_txt_metadata(mf, app):
1162 def add_buildflag(p, build):
1164 warn_or_exception("Empty build flag at {1}"
1165 .format(buildlines[0], linedesc))
1166 bv = p.split('=', 1)
1168 warn_or_exception("Invalid build flag at {0} in {1}"
1169 .format(buildlines[0], linedesc))
1174 pk = 'androidupdate' # avoid conflicting with Build(dict).update()
1177 pv = split_list_values(pv)
1179 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1181 elif t == TYPE_BOOL:
1182 build[pk] = _decode_bool(pv)
1184 def parse_buildline(lines):
1186 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1188 warn_or_exception("Invalid build format: " + v + " in " + mf.name)
1190 build.versionName = parts[0]
1191 build.versionCode = parts[1]
1192 check_versionCode(build.versionCode)
1194 if parts[2].startswith('!'):
1195 # For backwards compatibility, handle old-style disabling,
1196 # including attempting to extract the commit from the message
1197 build.disable = parts[2][1:]
1198 commit = 'unknown - see disabled'
1199 index = parts[2].rfind('at ')
1201 commit = parts[2][index + 3:]
1202 if commit.endswith(')'):
1203 commit = commit[:-1]
1204 build.commit = commit
1206 build.commit = parts[2]
1208 add_buildflag(p, build)
1212 def check_versionCode(versionCode):
1216 warn_or_exception('Invalid versionCode: "' + versionCode + '" is not an integer!')
1218 def add_comments(key):
1221 app.comments[key] = list(curcomments)
1226 multiline_lines = []
1236 linedesc = "%s:%d" % (mf.name, c)
1237 line = line.rstrip('\r\n')
1239 if build_cont.match(line):
1240 if line.endswith('\\'):
1241 buildlines.append(line[:-1].lstrip())
1243 buildlines.append(line.lstrip())
1244 bl = ''.join(buildlines)
1245 add_buildflag(bl, build)
1248 if not build.commit and not build.disable:
1249 warn_or_exception("No commit specified for {0} in {1}"
1250 .format(build.versionName, linedesc))
1252 app.builds.append(build)
1253 add_comments('build:' + build.versionCode)
1259 if line.startswith("#"):
1260 curcomments.append(line[1:].strip())
1263 f, v = line.split(':', 1)
1265 warn_or_exception("Invalid metadata in " + linedesc)
1267 if f not in app_fields:
1268 warn_or_exception('Unrecognised app field: ' + f)
1270 # Translate obsolete fields...
1271 if f == 'Market Version':
1272 f = 'Current Version'
1273 if f == 'Market Version Code':
1274 f = 'Current Version Code'
1276 f = f.replace(' ', '')
1278 ftype = fieldtype(f)
1279 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1281 if ftype == TYPE_MULTILINE:
1284 warn_or_exception("Unexpected text on same line as "
1285 + f + " in " + linedesc)
1286 elif ftype == TYPE_STRING:
1288 elif ftype == TYPE_LIST:
1289 app[f] = split_list_values(v)
1290 elif ftype == TYPE_BUILD:
1291 if v.endswith("\\"):
1294 buildlines.append(v[:-1])
1296 build = parse_buildline([v])
1297 app.builds.append(build)
1298 add_comments('build:' + app.builds[-1].versionCode)
1299 elif ftype == TYPE_BUILD_V2:
1302 warn_or_exception('Build should have comma-separated',
1303 'versionName and versionCode,',
1304 'not "{0}", in {1}'.format(v, linedesc))
1306 build.versionName = vv[0]
1307 build.versionCode = vv[1]
1308 check_versionCode(build.versionCode)
1310 if build.versionCode in vc_seen:
1311 warn_or_exception('Duplicate build recipe found for versionCode %s in %s'
1312 % (build.versionCode, linedesc))
1313 vc_seen.add(build.versionCode)
1316 elif ftype == TYPE_OBSOLETE:
1317 pass # Just throw it away!
1319 warn_or_exception("Unrecognised field '" + f + "' in " + linedesc)
1320 elif mode == 1: # Multiline field
1323 app[f] = '\n'.join(multiline_lines)
1324 del multiline_lines[:]
1326 multiline_lines.append(line)
1327 elif mode == 2: # Line continuation mode in Build Version
1328 if line.endswith("\\"):
1329 buildlines.append(line[:-1])
1331 buildlines.append(line)
1332 build = parse_buildline(buildlines)
1333 app.builds.append(build)
1334 add_comments('build:' + app.builds[-1].versionCode)
1338 # Mode at end of file should always be 0
1340 warn_or_exception(f + " not terminated in " + mf.name)
1342 warn_or_exception("Unterminated continuation in " + mf.name)
1344 warn_or_exception("Unterminated build in " + mf.name)
1349 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1351 def field_to_attr(f):
1353 Translates human-readable field names to attribute names, e.g.
1354 'Auto Name' to 'AutoName'
1356 return f.replace(' ', '')
1358 def attr_to_field(k):
1360 Translates attribute names to human-readable field names, e.g.
1361 'AutoName' to 'Auto Name'
1365 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
1368 def w_comments(key):
1369 if key not in app.comments:
1371 for line in app.comments[key]:
1374 def w_field_always(f, v=None):
1375 key = field_to_attr(f)
1381 def w_field_nonempty(f, v=None):
1382 key = field_to_attr(f)
1389 w_field_nonempty('Disabled')
1390 w_field_nonempty('AntiFeatures')
1391 w_field_nonempty('Provides')
1392 w_field_always('Categories')
1393 w_field_always('License')
1394 w_field_nonempty('Author Name')
1395 w_field_nonempty('Author Email')
1396 w_field_nonempty('Author Web Site')
1397 w_field_always('Web Site')
1398 w_field_always('Source Code')
1399 w_field_always('Issue Tracker')
1400 w_field_nonempty('Changelog')
1401 w_field_nonempty('Donate')
1402 w_field_nonempty('FlattrID')
1403 w_field_nonempty('Bitcoin')
1404 w_field_nonempty('Litecoin')
1406 w_field_nonempty('Name')
1407 w_field_nonempty('Auto Name')
1408 w_field_nonempty('Summary')
1409 w_field_nonempty('Description', description_txt(app.Description))
1411 if app.RequiresRoot:
1412 w_field_always('Requires Root', 'yes')
1415 w_field_always('Repo Type')
1416 w_field_always('Repo')
1418 w_field_always('Binaries')
1421 for build in app.builds:
1423 if build.versionName == "Ignore":
1426 w_comments('build:%s' % build.versionCode)
1430 if app.MaintainerNotes:
1431 w_field_always('Maintainer Notes', app.MaintainerNotes)
1434 w_field_nonempty('Archive Policy')
1435 w_field_always('Auto Update Mode')
1436 w_field_always('Update Check Mode')
1437 w_field_nonempty('Update Check Ignore')
1438 w_field_nonempty('Vercode Operation')
1439 w_field_nonempty('Update Check Name')
1440 w_field_nonempty('Update Check Data')
1441 if app.CurrentVersion:
1442 w_field_always('Current Version')
1443 w_field_always('Current Version Code')
1444 if app.NoSourceSince:
1446 w_field_always('No Source Since')
1450 # Write a metadata file in txt format.
1452 # 'mf' - Writer interface (file, StringIO, ...)
1453 # 'app' - The app data
1454 def write_txt(mf, app):
1456 def w_comment(line):
1457 mf.write("# %s\n" % line)
1463 elif t == TYPE_MULTILINE:
1464 v = '\n' + v + '\n.'
1465 mf.write("%s:%s\n" % (f, v))
1468 mf.write("Build:%s,%s\n" % (build.versionName, build.versionCode))
1470 for f in build_flags_order:
1476 if f == 'androidupdate':
1477 f = 'update' # avoid conflicting with Build(dict).update()
1478 mf.write(' %s=' % f)
1479 if t == TYPE_STRING:
1481 elif t == TYPE_BOOL:
1483 elif t == TYPE_SCRIPT:
1485 for s in v.split(' && '):
1489 mf.write(' && \\\n ')
1491 elif t == TYPE_LIST:
1492 mf.write(','.join(v))
1496 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1499 def write_metadata(metadatapath, app):
1500 _, ext = fdroidserver.common.get_extension(metadatapath)
1501 accepted = fdroidserver.common.config['accepted_formats']
1502 if ext not in accepted:
1503 warn_or_exception('Cannot write "%s", not an accepted format, use: %s'
1504 % (metadatapath, ', '.join(accepted)))
1507 with open(metadatapath, 'w', encoding='utf8') as mf:
1509 return write_txt(mf, app)
1511 return write_yaml(mf, app)
1512 except FDroidException as e:
1513 os.remove(metadatapath)
1516 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1519 def add_metadata_arguments(parser):
1520 '''add common command line flags related to metadata processing'''
1521 parser.add_argument("-W", default='error',
1522 help="force errors to be warnings, or ignore")