chiark / gitweb /
e24c0081ed8b464c573a13f385ca5e2aee0448e6
[fdroidserver.git] / fdroid
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3 #
4 # fdroid.py - part of the FDroid server tools
5 # Copyright (C) 2010-2015, Ciaran Gultnieks, ciaran@ciarang.com
6 # Copyright (C) 2013-2014 Daniel Marti <mvdan@mvdan.cc>
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU Affero General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 # GNU Affero General Public License for more details.
17 #
18 # You should have received a copy of the GNU Affero General Public License
19 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
20
21 import sys
22 import logging
23
24 import fdroidserver.common
25 import fdroidserver.metadata
26 from argparse import ArgumentError
27
28 commands = {
29     "build": "Build a package from source",
30     "init": "Quickly start a new repository",
31     "publish": "Sign and place packages in the repo",
32     "gpgsign": "Add gpg signatures for packages in repo",
33     "update": "Update repo information for new packages",
34     "verify": "Verify the integrity of downloaded packages",
35     "checkupdates": "Check for updates to applications",
36     "import": "Add a new application from its source code",
37     "install": "Install built packages on devices",
38     "readmeta": "Read all the metadata files and exit",
39     "rewritemeta": "Rewrite all the metadata files",
40     "lint": "Warn about possible metadata errors",
41     "scanner": "Scan the source code of a package",
42     "stats": "Update the stats of the repo",
43     "server": "Interact with the repo HTTP server",
44     "signindex": "Sign indexes created using update --nosign",
45 }
46
47
48 def print_help():
49     print("usage: fdroid [-h|--help|--version] <command> [<args>]")
50     print("")
51     print("Valid commands are:")
52     for cmd, summary in commands.items():
53         print("   " + cmd + ' ' * (15 - len(cmd)) + summary)
54     print("")
55
56
57 def main():
58
59     if len(sys.argv) <= 1:
60         print_help()
61         sys.exit(0)
62
63     command = sys.argv[1]
64     if command not in commands:
65         if command in ('-h', '--help'):
66             print_help()
67             sys.exit(0)
68         elif command == '--version':
69             import os.path
70             output = 'no version info found!'
71             cmddir = os.path.realpath(os.path.dirname(__file__))
72             moduledir = os.path.realpath(os.path.dirname(fdroidserver.common.__file__) + '/..')
73             if cmddir == moduledir:
74                 # running from git
75                 os.chdir(cmddir)
76                 if os.path.isdir('.git'):
77                     import subprocess
78                     try:
79                         output = subprocess.check_output(['git', 'describe'],
80                                                          stderr=subprocess.STDOUT)
81                     except subprocess.CalledProcessError:
82                         output = 'git commit ' + subprocess.check_output(['git', 'rev-parse', 'HEAD'])
83                 elif os.path.exists('setup.py'):
84                     import re
85                     m = re.search(r'''.*[\s,\(]+version\s*=\s*["']([0-9a-z.]+)["'].*''',
86                                   open('setup.py').read(), flags=re.MULTILINE)
87                     if m:
88                         output = m.group(1) + '\n'
89             else:
90                 from pkg_resources import get_distribution
91                 output = get_distribution('fdroidserver').version + '\n'
92             print(output),
93             sys.exit(0)
94         else:
95             print("Command '%s' not recognised.\n" % command)
96             print_help()
97             sys.exit(1)
98
99     verbose = any(s in sys.argv for s in ['-v', '--verbose'])
100     quiet = any(s in sys.argv for s in ['-q', '--quiet'])
101
102     # Helpful to differentiate warnings from errors even when on quiet
103     logformat = '%(levelname)s: %(message)s'
104     loglevel = logging.INFO
105     if verbose:
106         loglevel = logging.DEBUG
107     elif quiet:
108         loglevel = logging.WARN
109
110     logging.basicConfig(format=logformat, level=loglevel)
111
112     if verbose and quiet:
113         logging.critical("Specifying --verbose and --quiet and the same time is silly")
114         sys.exit(1)
115
116     # Trick optparse into displaying the right usage when --help is used.
117     sys.argv[0] += ' ' + command
118
119     del sys.argv[1]
120     mod = __import__('fdroidserver.' + command, None, None, [command])
121
122     try:
123         mod.main()
124     # These are ours, contain a proper message and are "expected"
125     except (fdroidserver.common.FDroidException,
126             fdroidserver.metadata.MetaDataException) as e:
127         if verbose:
128             raise
129         else:
130             logging.critical(str(e))
131         sys.exit(1)
132     except ArgumentError as e:
133         logging.critical(str(e))
134         sys.exit(1)
135     except KeyboardInterrupt:
136         print('')
137         sys.exit(1)
138     # These should only be unexpected crashes due to bugs in the code
139     # str(e) often doesn't contain a reason, so just show the backtrace
140     except Exception as e:
141         logging.critical("Unknown exception found!")
142         raise
143     sys.exit(0)
144
145 if __name__ == "__main__":
146     main()