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