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