chiark / gitweb /
Merge branch 'mr/update_platforms_tools' into 'master'
[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 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     "dscanner": "Dynamically scan APKs post build",
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     "btlog": "Update the binary transparency log for a URL",
46 }
47
48
49 def print_help():
50     print("usage: fdroid [-h|--help|--version] <command> [<args>]")
51     print("")
52     print("Valid commands are:")
53     for cmd, summary in commands.items():
54         print("   " + cmd + ' ' * (15 - len(cmd)) + summary)
55     print("")
56
57
58 def main():
59
60     if len(sys.argv) <= 1:
61         print_help()
62         sys.exit(0)
63
64     command = sys.argv[1]
65     if command not in commands:
66         if command in ('-h', '--help'):
67             print_help()
68             sys.exit(0)
69         elif command == '--version':
70             import os.path
71             output = 'no version info found!'
72             cmddir = os.path.realpath(os.path.dirname(__file__))
73             moduledir = os.path.realpath(os.path.dirname(fdroidserver.common.__file__) + '/..')
74             if cmddir == moduledir:
75                 # running from git
76                 os.chdir(cmddir)
77                 if os.path.isdir('.git'):
78                     import subprocess
79                     try:
80                         output = subprocess.check_output(['git', 'describe'],
81                                                          stderr=subprocess.STDOUT,
82                                                          universal_newlines=True)
83                     except subprocess.CalledProcessError:
84                         output = 'git commit ' + subprocess.check_output(['git', 'rev-parse', 'HEAD'],
85                                                                          universal_newlines=True)
86                 elif os.path.exists('setup.py'):
87                     import re
88                     m = re.search(r'''.*[\s,\(]+version\s*=\s*["']([0-9a-z.]+)["'].*''',
89                                   open('setup.py').read(), flags=re.MULTILINE)
90                     if m:
91                         output = m.group(1) + '\n'
92             else:
93                 from pkg_resources import get_distribution
94                 output = get_distribution('fdroidserver').version + '\n'
95             print(output),
96             sys.exit(0)
97         else:
98             print("Command '%s' not recognised.\n" % command)
99             print_help()
100             sys.exit(1)
101
102     verbose = any(s in sys.argv for s in ['-v', '--verbose'])
103     quiet = any(s in sys.argv for s in ['-q', '--quiet'])
104
105     # Helpful to differentiate warnings from errors even when on quiet
106     logformat = '%(levelname)s: %(message)s'
107     loglevel = logging.INFO
108     if verbose:
109         loglevel = logging.DEBUG
110     elif quiet:
111         loglevel = logging.WARN
112
113     logging.basicConfig(format=logformat, level=loglevel)
114
115     if verbose and quiet:
116         logging.critical("Specifying --verbose and --quiet and the same time is silly")
117         sys.exit(1)
118
119     # Trick optparse into displaying the right usage when --help is used.
120     sys.argv[0] += ' ' + command
121
122     del sys.argv[1]
123     mod = __import__('fdroidserver.' + command, None, None, [command])
124
125     try:
126         mod.main()
127     # These are ours, contain a proper message and are "expected"
128     except (fdroidserver.common.FDroidException,
129             fdroidserver.metadata.MetaDataException) as e:
130         if verbose:
131             raise
132         else:
133             logging.critical(str(e))
134         sys.exit(1)
135     except ArgumentError as e:
136         logging.critical(str(e))
137         sys.exit(1)
138     except KeyboardInterrupt:
139         print('')
140         sys.exit(1)
141     # These should only be unexpected crashes due to bugs in the code
142     # str(e) often doesn't contain a reason, so just show the backtrace
143     except Exception as e:
144         logging.critical("Unknown exception found!")
145         raise
146     sys.exit(0)
147
148
149 if __name__ == "__main__":
150     main()