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