chiark / gitweb /
update: make icon extraction less dependent on aapt
[fdroidserver.git] / fdroid
1 #!/usr/bin/env python3
2 #
3 # fdroid.py - part of the FDroid server tools
4 # Copyright (C) 2010-2015, Ciaran Gultnieks, ciaran@ciarang.com
5 # Copyright (C) 2013-2014 Daniel Marti <mvdan@mvdan.cc>
6 #
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.
11 #
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.
16 #
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/>.
19
20 import sys
21 import os
22 import logging
23
24 import fdroidserver.common
25 import fdroidserver.metadata
26 from fdroidserver import _
27 from argparse import ArgumentError
28 from collections import OrderedDict
29
30
31 commands = OrderedDict([
32     ("build", _("Build a package from source")),
33     ("init", _("Quickly start a new repository")),
34     ("publish", _("Sign and place packages in the repo")),
35     ("gpgsign", _("Add PGP signatures using GnuPG for packages in repo")),
36     ("update", _("Update repo information for new packages")),
37     ("deploy", _("Interact with the repo HTTP server")),
38     ("verify", _("Verify the integrity of downloaded packages")),
39     ("checkupdates", _("Check for updates to applications")),
40     ("import", _("Add a new application from its source code")),
41     ("install", _("Install built packages on devices")),
42     ("readmeta", _("Read all the metadata files and exit")),
43     ("rewritemeta", _("Rewrite all the metadata files")),
44     ("lint", _("Warn about possible metadata errors")),
45     ("scanner", _("Scan the source code of a package")),
46     ("dscanner", _("Dynamically scan APKs post build")),
47     ("stats", _("Update the stats of the repo")),
48     ("server", _("Old, deprecated name for fdroid deploy")),
49     ("signindex", _("Sign indexes created using update --nosign")),
50     ("btlog", _("Update the binary transparency log for a URL")),
51     ("signatures", _("Extract signatures from APKs")),
52     ("nightly", _("Set up an app build for a nightly build repo")),
53     ("mirror", _("Download complete mirrors of small repos")),
54 ])
55
56
57 def print_help():
58     print(_("usage: ") + _("fdroid [<command>] [-h|--help|--version|<args>]"))
59     print("")
60     print(_("Valid commands are:"))
61     for cmd, summary in commands.items():
62         print("   " + cmd + ' ' * (15 - len(cmd)) + summary)
63     print("")
64
65
66 def main():
67
68     if len(sys.argv) <= 1:
69         print_help()
70         sys.exit(0)
71
72     command = sys.argv[1]
73     if command not in commands:
74         if command in ('-h', '--help'):
75             print_help()
76             sys.exit(0)
77         elif command == '--version':
78             output = _('no version info found!')
79             cmddir = os.path.realpath(os.path.dirname(__file__))
80             moduledir = os.path.realpath(os.path.dirname(fdroidserver.common.__file__) + '/..')
81             if cmddir == moduledir:
82                 # running from git
83                 os.chdir(cmddir)
84                 if os.path.isdir('.git'):
85                     import subprocess
86                     try:
87                         output = subprocess.check_output(['git', 'describe'],
88                                                          stderr=subprocess.STDOUT,
89                                                          universal_newlines=True)
90                     except subprocess.CalledProcessError:
91                         output = 'git commit ' + subprocess.check_output(['git', 'rev-parse', 'HEAD'],
92                                                                          universal_newlines=True)
93                 elif os.path.exists('setup.py'):
94                     import re
95                     m = re.search(r'''.*[\s,\(]+version\s*=\s*["']([0-9a-z.]+)["'].*''',
96                                   open('setup.py').read(), flags=re.MULTILINE)
97                     if m:
98                         output = m.group(1) + '\n'
99             else:
100                 from pkg_resources import get_distribution
101                 output = get_distribution('fdroidserver').version + '\n'
102             print(output),
103             sys.exit(0)
104         else:
105             print(_("Command '%s' not recognised.\n" % command))
106             print_help()
107             sys.exit(1)
108
109     verbose = any(s in sys.argv for s in ['-v', '--verbose'])
110     quiet = any(s in sys.argv for s in ['-q', '--quiet'])
111
112     # Helpful to differentiate warnings from errors even when on quiet
113     logformat = '%(levelname)s: %(message)s'
114     loglevel = logging.INFO
115     if verbose:
116         loglevel = logging.DEBUG
117     elif quiet:
118         loglevel = logging.WARN
119
120     logging.basicConfig(format=logformat, level=loglevel)
121
122     if verbose and quiet:
123         logging.critical("Specifying --verbose and --quiet and the same time is silly")
124         sys.exit(1)
125
126     # temporary workaround until server.py becomes deploy.py
127     if command == 'deploy':
128         command = 'server'
129         sys.argv.insert(1, 'update')
130
131     # Trick optparse into displaying the right usage when --help is used.
132     sys.argv[0] += ' ' + command
133
134     del sys.argv[1]
135     mod = __import__('fdroidserver.' + command, None, None, [command])
136
137     try:
138         mod.main()
139     # These are ours, contain a proper message and are "expected"
140     except (fdroidserver.common.FDroidException,
141             fdroidserver.metadata.MetaDataException) as e:
142         if verbose:
143             raise
144         else:
145             logging.critical(str(e))
146         sys.exit(1)
147     except ArgumentError as e:
148         logging.critical(str(e))
149         sys.exit(1)
150     except KeyboardInterrupt:
151         print('')
152         sys.stdout.flush()
153         sys.stderr.flush()
154         os._exit(1)
155     # These should only be unexpected crashes due to bugs in the code
156     # str(e) often doesn't contain a reason, so just show the backtrace
157     except Exception as e:
158         logging.critical(_("Unknown exception found!"))
159         raise
160     sys.exit(0)
161
162
163 if __name__ == "__main__":
164     main()