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
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 = [
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 'versionCode': TYPE_INT,
322 'extlibs': TYPE_LIST,
323 'srclibs': TYPE_LIST,
326 'buildjni': TYPE_LIST,
327 'preassemble': TYPE_LIST,
328 'androidupdate': TYPE_LIST,
329 'scanignore': TYPE_LIST,
330 'scandelete': TYPE_LIST,
332 'antcommands': TYPE_LIST,
333 'gradleprops': TYPE_LIST,
335 'prebuild': TYPE_SCRIPT,
336 'build': TYPE_SCRIPT,
337 'submodules': TYPE_BOOL,
338 'oldsdkloc': TYPE_BOOL,
339 'forceversion': TYPE_BOOL,
340 'forcevercode': TYPE_BOOL,
341 'novcheck': TYPE_BOOL,
346 if name in flagtypes:
347 return flagtypes[name]
351 class FieldValidator():
353 Designates App metadata field types and checks that it matches
355 'name' - The long name of the field type
356 'matching' - List of possible values or regex expression
357 'sep' - Separator to use if value may be a list
358 'fields' - Metadata fields (Field:Value) of this type
361 def __init__(self, name, matching, fields):
363 self.matching = matching
364 self.compiled = re.compile(matching)
367 def check(self, v, appid):
375 if not self.compiled.match(v):
376 warn_or_exception("'%s' is not a valid %s in %s. Regex pattern: %s"
377 % (v, self.name, appid, self.matching))
380 # Generic value types
382 FieldValidator("Hexadecimal",
386 FieldValidator("HTTP link",
388 ["WebSite", "SourceCode", "IssueTracker", "Changelog", "Donate"]),
390 FieldValidator("Email",
391 r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
394 FieldValidator("Bitcoin address",
395 r'^[a-zA-Z0-9]{27,34}$',
398 FieldValidator("Litecoin address",
399 r'^L[a-zA-Z0-9]{33}$',
402 FieldValidator("Repo Type",
403 r'^(git|git-svn|svn|hg|bzr|srclib)$',
406 FieldValidator("Binaries",
410 FieldValidator("Archive Policy",
411 r'^[0-9]+ versions$',
414 FieldValidator("Anti-Feature",
415 r'^(Ads|Tracking|NonFreeNet|NonFreeDep|NonFreeAdd|UpstreamNonFree|NonFreeAssets|KnownVuln)$',
418 FieldValidator("Auto Update Mode",
419 r"^(Version .+|None)$",
422 FieldValidator("Update Check Mode",
423 r"^(Tags|Tags .+|RepoManifest|RepoManifest/.+|RepoTrunk|HTTP|Static|None)$",
428 # Check an app's metadata information for integrity errors
429 def check_metadata(app):
432 v.check(app[k], app.id)
435 # Formatter for descriptions. Create an instance, and call parseline() with
436 # each line of the description source from the metadata. At the end, call
437 # end() and then text_txt and text_html will contain the result.
438 class DescriptionFormatter:
445 def __init__(self, linkres):
448 self.state = self.stNONE
449 self.laststate = self.stNONE
452 self.html = io.StringIO()
453 self.text = io.StringIO()
455 self.linkResolver = None
456 self.linkResolver = linkres
458 def endcur(self, notstates=None):
459 if notstates and self.state in notstates:
461 if self.state == self.stPARA:
463 elif self.state == self.stUL:
465 elif self.state == self.stOL:
469 self.laststate = self.state
470 self.state = self.stNONE
471 whole_para = ' '.join(self.para_lines)
472 self.addtext(whole_para)
473 wrapped = textwrap.fill(whole_para, 80,
474 break_long_words=False,
475 break_on_hyphens=False)
476 self.text.write(wrapped)
477 self.html.write('</p>')
478 del self.para_lines[:]
481 self.html.write('</ul>')
482 self.laststate = self.state
483 self.state = self.stNONE
486 self.html.write('</ol>')
487 self.laststate = self.state
488 self.state = self.stNONE
490 def formatted(self, txt, htmlbody):
493 txt = html.escape(txt, quote=False)
495 index = txt.find("''")
500 if txt.startswith("'''"):
506 self.bold = not self.bold
514 self.ital = not self.ital
517 def linkify(self, txt):
521 index = txt.find("[")
523 return (res_plain + self.formatted(txt, False), res_html + self.formatted(txt, True))
524 res_plain += self.formatted(txt[:index], False)
525 res_html += self.formatted(txt[:index], True)
527 if txt.startswith("[["):
528 index = txt.find("]]")
530 warn_or_exception("Unterminated ]]")
532 if self.linkResolver:
533 url, urltext = self.linkResolver(url)
536 res_html += '<a href="' + url + '">' + html.escape(urltext, quote=False) + '</a>'
538 txt = txt[index + 2:]
540 index = txt.find("]")
542 warn_or_exception("Unterminated ]")
544 index2 = url.find(' ')
548 urltxt = url[index2 + 1:]
551 warn_or_exception("Url title is just the URL - use [url]")
552 res_html += '<a href="' + url + '">' + html.escape(urltxt, quote=False) + '</a>'
555 res_plain += ' (' + url + ')'
556 txt = txt[index + 1:]
558 def addtext(self, txt):
559 p, h = self.linkify(txt)
562 def parseline(self, line):
565 elif line.startswith('* '):
566 self.endcur([self.stUL])
567 if self.state != self.stUL:
568 self.html.write('<ul>')
569 self.state = self.stUL
570 if self.laststate != self.stNONE:
571 self.text.write('\n\n')
573 self.text.write('\n')
574 self.text.write(line)
575 self.html.write('<li>')
576 self.addtext(line[1:])
577 self.html.write('</li>')
578 elif line.startswith('# '):
579 self.endcur([self.stOL])
580 if self.state != self.stOL:
581 self.html.write('<ol>')
582 self.state = self.stOL
583 if self.laststate != self.stNONE:
584 self.text.write('\n\n')
586 self.text.write('\n')
587 self.text.write(line)
588 self.html.write('<li>')
589 self.addtext(line[1:])
590 self.html.write('</li>')
592 self.para_lines.append(line)
593 self.endcur([self.stPARA])
594 if self.state == self.stNONE:
595 self.state = self.stPARA
596 if self.laststate != self.stNONE:
597 self.text.write('\n\n')
598 self.html.write('<p>')
602 self.text_txt = self.text.getvalue()
603 self.text_html = self.html.getvalue()
608 # Parse multiple lines of description as written in a metadata file, returning
609 # a single string in text format and wrapped to 80 columns.
610 def description_txt(s):
611 ps = DescriptionFormatter(None)
612 for line in s.splitlines():
618 # Parse multiple lines of description as written in a metadata file, returning
619 # a single string in wiki format. Used for the Maintainer Notes field as well,
620 # because it's the same format.
621 def description_wiki(s):
625 # Parse multiple lines of description as written in a metadata file, returning
626 # a single string in HTML format.
627 def description_html(s, linkres):
628 ps = DescriptionFormatter(linkres)
629 for line in s.splitlines():
635 def parse_srclib(metadatapath):
639 # Defaults for fields that come from metadata
640 thisinfo['Repo Type'] = ''
641 thisinfo['Repo'] = ''
642 thisinfo['Subdir'] = None
643 thisinfo['Prepare'] = None
645 if not os.path.exists(metadatapath):
648 metafile = open(metadatapath, "r", encoding='utf-8')
651 for line in metafile:
653 line = line.rstrip('\r\n')
654 if not line or line.startswith("#"):
658 f, v = line.split(':', 1)
660 warn_or_exception("Invalid metadata in %s:%d" % (line, n))
663 thisinfo[f] = v.split(',')
673 """Read all srclib metadata.
675 The information read will be accessible as metadata.srclibs, which is a
676 dictionary, keyed on srclib name, with the values each being a dictionary
677 in the same format as that returned by the parse_srclib function.
679 A MetaDataException is raised if there are any problems with the srclib
684 # They were already loaded
685 if srclibs is not None:
691 if not os.path.exists(srcdir):
694 for metadatapath in sorted(glob.glob(os.path.join(srcdir, '*.txt'))):
695 srclibname = os.path.basename(metadatapath[:-4])
696 srclibs[srclibname] = parse_srclib(metadatapath)
699 def read_metadata(xref=True, check_vcs=[]):
701 Read all metadata. Returns a list of 'app' objects (which are dictionaries as
702 returned by the parse_txt_metadata function.
704 check_vcs is the list of packageNames to check for .fdroid.yml in source
707 # Always read the srclibs before the apps, since they can use a srlib as
708 # their source repository.
713 for basedir in ('metadata', 'tmp'):
714 if not os.path.exists(basedir):
717 # If there are multiple metadata files for a single appid, then the first
718 # file that is parsed wins over all the others, and the rest throw an
719 # exception. So the original .txt format is parsed first, at least until
720 # newer formats stabilize.
722 for metadatapath in sorted(glob.glob(os.path.join('metadata', '*.txt'))
723 + glob.glob(os.path.join('metadata', '*.json'))
724 + glob.glob(os.path.join('metadata', '*.yml'))
725 + glob.glob('.fdroid.json')
726 + glob.glob('.fdroid.yml')):
727 packageName, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
728 if packageName in apps:
729 warn_or_exception("Found multiple metadata files for " + packageName)
730 app = parse_metadata(metadatapath, packageName in check_vcs)
735 # Parse all descriptions at load time, just to ensure cross-referencing
736 # errors are caught early rather than when they hit the build server.
739 return ("fdroid.app:" + appid, "Dummy name - don't know yet")
740 warn_or_exception("Cannot resolve app id " + appid)
742 for appid, app in apps.items():
744 description_html(app.Description, linkres)
745 except MetaDataException as e:
746 warn_or_exception("Problem with description of " + appid +
752 # Port legacy ';' separators
753 list_sep = re.compile(r'[,;]')
756 def split_list_values(s):
758 for v in re.split(list_sep, s):
768 def get_default_app_info(metadatapath=None):
769 if metadatapath is None:
772 appid, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
774 if appid == '.fdroid': # we have local metadata in the app's source
775 if os.path.exists('AndroidManifest.xml'):
776 manifestroot = fdroidserver.common.parse_xml('AndroidManifest.xml')
778 pattern = re.compile(""".*manifest\.srcFile\s+'AndroidManifest\.xml'.*""")
779 for root, dirs, files in os.walk(os.getcwd()):
780 if 'build.gradle' in files:
781 p = os.path.join(root, 'build.gradle')
782 with open(p, 'rb') as f:
784 m = pattern.search(data)
786 logging.debug('Using: ' + os.path.join(root, 'AndroidManifest.xml'))
787 manifestroot = fdroidserver.common.parse_xml(os.path.join(root, 'AndroidManifest.xml'))
789 if manifestroot is None:
790 warn_or_exception("Cannot find a packageName for {0}!".format(metadatapath))
791 appid = manifestroot.attrib['package']
794 app.metadatapath = metadatapath
795 if appid is not None:
801 def sorted_builds(builds):
802 return sorted(builds, key=lambda build: int(build.versionCode))
805 esc_newlines = re.compile(r'\\( |\n)')
808 def post_metadata_parse(app):
809 # TODO keep native types, convert only for .txt metadata
810 for k, v in app.items():
811 if type(v) in (float, int):
815 app['builds'] = app.pop('Builds')
817 if 'flavours' in app and app['flavours'] == [True]:
818 app['flavours'] = 'yes'
820 if isinstance(app.Categories, str):
821 app.Categories = [app.Categories]
822 elif app.Categories is None:
823 app.Categories = ['None']
825 app.Categories = [str(i) for i in app.Categories]
827 def _yaml_bool_unmapable(v):
828 return v in (True, False, [True], [False])
830 def _yaml_bool_unmap(v):
840 _bool_allowed = ('disable', 'kivy', 'maven', 'buildozer')
844 for build in app['builds']:
845 if not isinstance(build, Build):
847 for k, v in build.items():
849 if flagtype(k) == TYPE_LIST:
850 if _yaml_bool_unmapable(v):
851 build[k] = _yaml_bool_unmap(v)
853 if isinstance(v, str):
855 elif isinstance(v, bool):
860 elif flagtype(k) is TYPE_INT:
862 elif flagtype(k) is TYPE_STRING:
863 if isinstance(v, bool) and k in _bool_allowed:
866 if _yaml_bool_unmapable(v):
867 build[k] = _yaml_bool_unmap(v)
872 app.builds = sorted_builds(builds)
875 # Parse metadata for a single application.
877 # 'metadatapath' - the filename to read. The package id for the application comes
878 # from this filename. Pass None to get a blank entry.
880 # Returns a dictionary containing all the details of the application. There are
881 # two major kinds of information in the dictionary. Keys beginning with capital
882 # letters correspond directory to identically named keys in the metadata file.
883 # Keys beginning with lower case letters are generated in one way or another,
884 # and are not found verbatim in the metadata.
886 # Known keys not originating from the metadata are:
888 # 'builds' - a list of dictionaries containing build information
889 # for each defined build
890 # 'comments' - a list of comments from the metadata file. Each is
891 # a list of the form [field, comment] where field is
892 # the name of the field it preceded in the metadata
893 # file. Where field is None, the comment goes at the
894 # end of the file. Alternatively, 'build:version' is
895 # for a comment before a particular build version.
896 # 'descriptionlines' - original lines of description as formatted in the
901 bool_true = re.compile(r'([Yy]es|[Tt]rue)')
902 bool_false = re.compile(r'([Nn]o|[Ff]alse)')
906 if bool_true.match(s):
908 if bool_false.match(s):
910 warn_or_exception("Invalid bool '%s'" % s)
913 def parse_metadata(metadatapath, check_vcs=False):
914 '''parse metadata file, optionally checking the git repo for metadata first'''
916 _, ext = fdroidserver.common.get_extension(metadatapath)
917 accepted = fdroidserver.common.config['accepted_formats']
918 if ext not in accepted:
919 warn_or_exception('"%s" is not an accepted format, convert to: %s' % (
920 metadatapath, ', '.join(accepted)))
923 app.metadatapath = metadatapath
924 name, _ = fdroidserver.common.get_extension(os.path.basename(metadatapath))
925 if name == '.fdroid':
930 with open(metadatapath, 'r', encoding='utf-8') as mf:
932 parse_txt_metadata(mf, app)
934 parse_json_metadata(mf, app)
936 parse_yaml_metadata(mf, app)
938 warn_or_exception('Unknown metadata format: %s' % metadatapath)
940 if check_vcs and app.Repo:
941 build_dir = fdroidserver.common.get_build_dir(app)
942 metadata_in_repo = os.path.join(build_dir, '.fdroid.yml')
943 if not os.path.isfile(metadata_in_repo):
944 vcs, build_dir = fdroidserver.common.setup_vcs(app)
945 if isinstance(vcs, fdroidserver.common.vcs_git):
946 vcs.gotorevision('HEAD') # HEAD since we can't know where else to go
947 if os.path.isfile(metadata_in_repo):
948 logging.debug('Including metadata from ' + metadata_in_repo)
949 # do not include fields already provided by main metadata file
950 app_in_repo = parse_metadata(metadata_in_repo)
951 for k, v in app_in_repo.items():
955 post_metadata_parse(app)
959 build = app.builds[-1]
961 root_dir = build.subdir
964 paths = fdroidserver.common.manifest_paths(root_dir, build.gradle)
965 _, _, app.id = fdroidserver.common.parse_androidmanifests(paths, app)
970 def parse_json_metadata(mf, app):
972 # fdroid metadata is only strings and booleans, no floats or ints.
973 # TODO create schema using https://pypi.python.org/pypi/jsonschema
974 jsoninfo = json.load(mf, parse_int=lambda s: s,
975 parse_float=lambda s: s)
977 for f in ['Description', 'Maintainer Notes']:
980 app[f] = '\n'.join(v)
984 def parse_yaml_metadata(mf, app):
985 yamldata = yaml.load(mf, Loader=YamlLoader)
990 def write_yaml(mf, app):
994 _yaml_bools_true = ('y', 'Y', 'yes', 'Yes', 'YES',
995 'true', 'True', 'TRUE',
997 _yaml_bools_false = ('n', 'N', 'no', 'No', 'NO',
998 'false', 'False', 'FALSE',
1000 _yaml_bools_plus_lists = []
1001 _yaml_bools_plus_lists.extend(_yaml_bools_true)
1002 _yaml_bools_plus_lists.extend([[x] for x in _yaml_bools_true])
1003 _yaml_bools_plus_lists.extend(_yaml_bools_false)
1004 _yaml_bools_plus_lists.extend([[x] for x in _yaml_bools_false])
1006 def _class_as_dict_representer(dumper, data):
1007 '''Creates a YAML representation of a App/Build instance'''
1008 return dumper.represent_dict(data)
1010 def _field_to_yaml(typ, value):
1011 if typ is TYPE_STRING:
1012 if value in _yaml_bools_plus_lists:
1013 return ruamel.yaml.scalarstring.SingleQuotedScalarString(str(value))
1015 elif typ is TYPE_INT:
1017 elif typ is TYPE_MULTILINE:
1019 return ruamel.yaml.scalarstring.preserve_literal(str(value))
1022 elif typ is TYPE_SCRIPT:
1024 return ruamel.yaml.scalarstring.preserve_literal(value)
1030 def _app_to_yaml(app):
1031 cm = ruamel.yaml.comments.CommentedMap()
1032 insert_newline = False
1033 for field in yaml_app_field_order:
1035 # next iteration will need to insert a newline
1036 insert_newline = True
1038 if (hasattr(app, field) and getattr(app, field)) or field is 'Builds':
1039 if field is 'Builds':
1040 cm.update({field: _builds_to_yaml(app)})
1041 elif field is 'CurrentVersionCode':
1042 cm.update({field: _field_to_yaml(TYPE_INT, getattr(app, field))})
1044 cm.update({field: _field_to_yaml(fieldtype(field), getattr(app, field))})
1047 # we need to prepend a newline in front of this field
1048 insert_newline = False
1049 # inserting empty lines is not supported so we add a
1050 # bogus comment and over-write its value
1051 cm.yaml_set_comment_before_after_key(field, 'bogus')
1052 cm.ca.items[field][1][-1].value = '\n'
1055 def _builds_to_yaml(app):
1056 fields = ['versionName', 'versionCode']
1057 fields.extend(build_flags_order)
1058 builds = ruamel.yaml.comments.CommentedSeq()
1059 for build in app.builds:
1060 b = ruamel.yaml.comments.CommentedMap()
1061 for field in fields:
1062 if hasattr(build, field) and getattr(build, field):
1063 value = getattr(build, field)
1064 if field == 'gradle' and value == ['off']:
1065 value = [ruamel.yaml.scalarstring.SingleQuotedScalarString('off')]
1066 if field in ('disable', 'kivy', 'maven', 'buildozer'):
1069 elif value == 'yes':
1071 b.update({field: _field_to_yaml(flagtype(field), value)})
1074 # insert extra empty lines between build entries
1075 for i in range(1, len(builds)):
1076 builds.yaml_set_comment_before_after_key(i, 'bogus')
1077 builds.ca.items[i][1][-1].value = '\n'
1081 yaml_app_field_order = [
1117 'UpdateCheckIgnore',
1122 'CurrentVersionCode',
1127 yaml_app = _app_to_yaml(app)
1128 ruamel.yaml.round_trip_dump(yaml_app, mf, indent=4, block_seq_indent=2)
1131 build_line_sep = re.compile(r'(?<!\\),')
1132 build_cont = re.compile(r'^[ \t]')
1135 def parse_txt_metadata(mf, app):
1139 def add_buildflag(p, build):
1141 warn_or_exception("Empty build flag at {1}"
1142 .format(buildlines[0], linedesc))
1143 bv = p.split('=', 1)
1145 warn_or_exception("Invalid build flag at {0} in {1}"
1146 .format(buildlines[0], linedesc))
1151 pk = 'androidupdate' # avoid conflicting with Build(dict).update()
1154 pv = split_list_values(pv)
1156 elif t == TYPE_STRING or t == TYPE_SCRIPT:
1158 elif t == TYPE_BOOL:
1159 build[pk] = _decode_bool(pv)
1161 def parse_buildline(lines):
1163 parts = [p.replace("\\,", ",") for p in re.split(build_line_sep, v)]
1165 warn_or_exception("Invalid build format: " + v + " in " + mf.name)
1167 build.versionName = parts[0]
1168 build.versionCode = parts[1]
1169 check_versionCode(build.versionCode)
1171 if parts[2].startswith('!'):
1172 # For backwards compatibility, handle old-style disabling,
1173 # including attempting to extract the commit from the message
1174 build.disable = parts[2][1:]
1175 commit = 'unknown - see disabled'
1176 index = parts[2].rfind('at ')
1178 commit = parts[2][index + 3:]
1179 if commit.endswith(')'):
1180 commit = commit[:-1]
1181 build.commit = commit
1183 build.commit = parts[2]
1185 add_buildflag(p, build)
1189 def check_versionCode(versionCode):
1193 warn_or_exception('Invalid versionCode: "' + versionCode + '" is not an integer!')
1195 def add_comments(key):
1198 app.comments[key] = list(curcomments)
1203 multiline_lines = []
1213 linedesc = "%s:%d" % (mf.name, c)
1214 line = line.rstrip('\r\n')
1216 if build_cont.match(line):
1217 if line.endswith('\\'):
1218 buildlines.append(line[:-1].lstrip())
1220 buildlines.append(line.lstrip())
1221 bl = ''.join(buildlines)
1222 add_buildflag(bl, build)
1225 if not build.commit and not build.disable:
1226 warn_or_exception("No commit specified for {0} in {1}"
1227 .format(build.versionName, linedesc))
1229 app.builds.append(build)
1230 add_comments('build:' + build.versionCode)
1236 if line.startswith("#"):
1237 curcomments.append(line[1:].strip())
1240 f, v = line.split(':', 1)
1242 warn_or_exception("Invalid metadata in " + linedesc)
1244 if f not in app_fields:
1245 warn_or_exception('Unrecognised app field: ' + f)
1247 # Translate obsolete fields...
1248 if f == 'Market Version':
1249 f = 'Current Version'
1250 if f == 'Market Version Code':
1251 f = 'Current Version Code'
1253 f = f.replace(' ', '')
1255 ftype = fieldtype(f)
1256 if ftype not in [TYPE_BUILD, TYPE_BUILD_V2]:
1258 if ftype == TYPE_MULTILINE:
1261 warn_or_exception("Unexpected text on same line as "
1262 + f + " in " + linedesc)
1263 elif ftype == TYPE_STRING:
1265 elif ftype == TYPE_LIST:
1266 app[f] = split_list_values(v)
1267 elif ftype == TYPE_BUILD:
1268 if v.endswith("\\"):
1271 buildlines.append(v[:-1])
1273 build = parse_buildline([v])
1274 app.builds.append(build)
1275 add_comments('build:' + app.builds[-1].versionCode)
1276 elif ftype == TYPE_BUILD_V2:
1279 warn_or_exception('Build should have comma-separated',
1280 'versionName and versionCode,',
1281 'not "{0}", in {1}'.format(v, linedesc))
1283 build.versionName = vv[0]
1284 build.versionCode = vv[1]
1285 check_versionCode(build.versionCode)
1287 if build.versionCode in vc_seen:
1288 warn_or_exception('Duplicate build recipe found for versionCode %s in %s'
1289 % (build.versionCode, linedesc))
1290 vc_seen.add(build.versionCode)
1293 elif ftype == TYPE_OBSOLETE:
1294 pass # Just throw it away!
1296 warn_or_exception("Unrecognised field '" + f + "' in " + linedesc)
1297 elif mode == 1: # Multiline field
1300 app[f] = '\n'.join(multiline_lines)
1301 del multiline_lines[:]
1303 multiline_lines.append(line)
1304 elif mode == 2: # Line continuation mode in Build Version
1305 if line.endswith("\\"):
1306 buildlines.append(line[:-1])
1308 buildlines.append(line)
1309 build = parse_buildline(buildlines)
1310 app.builds.append(build)
1311 add_comments('build:' + app.builds[-1].versionCode)
1315 # Mode at end of file should always be 0
1317 warn_or_exception(f + " not terminated in " + mf.name)
1319 warn_or_exception("Unterminated continuation in " + mf.name)
1321 warn_or_exception("Unterminated build in " + mf.name)
1326 def write_plaintext_metadata(mf, app, w_comment, w_field, w_build):
1328 def field_to_attr(f):
1330 Translates human-readable field names to attribute names, e.g.
1331 'Auto Name' to 'AutoName'
1333 return f.replace(' ', '')
1335 def attr_to_field(k):
1337 Translates attribute names to human-readable field names, e.g.
1338 'AutoName' to 'Auto Name'
1342 f = re.sub(r'([a-z])([A-Z])', r'\1 \2', k)
1345 def w_comments(key):
1346 if key not in app.comments:
1348 for line in app.comments[key]:
1351 def w_field_always(f, v=None):
1352 key = field_to_attr(f)
1358 def w_field_nonempty(f, v=None):
1359 key = field_to_attr(f)
1366 w_field_nonempty('Disabled')
1367 w_field_nonempty('AntiFeatures')
1368 w_field_nonempty('Provides')
1369 w_field_always('Categories')
1370 w_field_always('License')
1371 w_field_nonempty('Author Name')
1372 w_field_nonempty('Author Email')
1373 w_field_nonempty('Author Web Site')
1374 w_field_always('Web Site')
1375 w_field_always('Source Code')
1376 w_field_always('Issue Tracker')
1377 w_field_nonempty('Changelog')
1378 w_field_nonempty('Donate')
1379 w_field_nonempty('FlattrID')
1380 w_field_nonempty('Bitcoin')
1381 w_field_nonempty('Litecoin')
1383 w_field_nonempty('Name')
1384 w_field_nonempty('Auto Name')
1385 w_field_nonempty('Summary')
1386 w_field_nonempty('Description', description_txt(app.Description))
1388 if app.RequiresRoot:
1389 w_field_always('Requires Root', 'yes')
1392 w_field_always('Repo Type')
1393 w_field_always('Repo')
1395 w_field_always('Binaries')
1398 for build in app.builds:
1400 if build.versionName == "Ignore":
1403 w_comments('build:%s' % build.versionCode)
1407 if app.MaintainerNotes:
1408 w_field_always('Maintainer Notes', app.MaintainerNotes)
1411 w_field_nonempty('Archive Policy')
1412 w_field_always('Auto Update Mode')
1413 w_field_always('Update Check Mode')
1414 w_field_nonempty('Update Check Ignore')
1415 w_field_nonempty('Vercode Operation')
1416 w_field_nonempty('Update Check Name')
1417 w_field_nonempty('Update Check Data')
1418 if app.CurrentVersion:
1419 w_field_always('Current Version')
1420 w_field_always('Current Version Code')
1421 if app.NoSourceSince:
1423 w_field_always('No Source Since')
1427 # Write a metadata file in txt format.
1429 # 'mf' - Writer interface (file, StringIO, ...)
1430 # 'app' - The app data
1431 def write_txt(mf, app):
1433 def w_comment(line):
1434 mf.write("# %s\n" % line)
1440 elif t == TYPE_MULTILINE:
1441 v = '\n' + v + '\n.'
1442 mf.write("%s:%s\n" % (f, v))
1445 mf.write("Build:%s,%s\n" % (build.versionName, build.versionCode))
1447 for f in build_flags_order:
1453 if f == 'androidupdate':
1454 f = 'update' # avoid conflicting with Build(dict).update()
1455 mf.write(' %s=' % f)
1456 if t == TYPE_STRING:
1458 elif t == TYPE_BOOL:
1460 elif t == TYPE_SCRIPT:
1462 for s in v.split(' && '):
1466 mf.write(' && \\\n ')
1468 elif t == TYPE_LIST:
1469 mf.write(','.join(v))
1473 write_plaintext_metadata(mf, app, w_comment, w_field, w_build)
1476 def write_metadata(metadatapath, app):
1477 _, ext = fdroidserver.common.get_extension(metadatapath)
1478 accepted = fdroidserver.common.config['accepted_formats']
1479 if ext not in accepted:
1480 warn_or_exception('Cannot write "%s", not an accepted format, use: %s'
1481 % (metadatapath, ', '.join(accepted)))
1483 with open(metadatapath, 'w', encoding='utf8') as mf:
1485 return write_txt(mf, app)
1487 return write_yaml(mf, app)
1488 warn_or_exception('Unknown metadata format: %s' % metadatapath)
1491 def add_metadata_arguments(parser):
1492 '''add common command line flags related to metadata processing'''
1493 parser.add_argument("-W", default='error',
1494 help="force errors to be warnings, or ignore")