chiark / gitweb /
lint: Remove duplicate code.google.com TODO
[fdroidserver.git] / fdroidserver / lint.py
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3 #
4 # lint.py - part of the FDroid server tool
5 # Copyright (C) 2013-2014 Daniel Martí <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 th
15 # GNU Affero General Public License for more details.
16 #
17 # You should have received a copy of the GNU Affero General Public Licen
18 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20 from optparse import OptionParser
21 import re
22 import logging
23 import common
24 import metadata
25 from collections import Counter
26
27 config = None
28 options = None
29
30
31 def enforce_https(domain):
32     return (re.compile(r'.*[^sS]://[^/]*' + re.escape(domain) + r'/.*'),
33             domain + " URLs should always use https://")
34
35 https_enforcings = [
36     enforce_https('github.com'),
37     enforce_https('gitorious.org'),
38     enforce_https('apache.org'),
39     enforce_https('google.com'),
40     enforce_https('svn.code.sf.net'),
41     enforce_https('googlecode.com'),
42 ]
43
44 http_warnings = https_enforcings + [
45     (re.compile(r'.*/$'),
46      "HTTP links shouldn't end with a slash"),
47     (re.compile(r'.*github\.com/[^/]+/[^/]+\.git'),
48      "Appending .git is not necessary"),
49     # TODO enable in August 2015, when Google Code goes read-only
50     # (re.compile(r'.*://code\.google\.com/.*'),
51     #  "code.google.com will be soon switching down, perhaps the project moved to github.com?"),
52 ]
53
54 regex_warnings = {
55     'Web Site': http_warnings + [
56     ],
57     'Source Code': http_warnings + [
58     ],
59     'Repo': https_enforcings + [
60     ],
61     'Issue Tracker': http_warnings + [
62         (re.compile(r'.*github\.com/[^/]+/[^/]+[/]*$'),
63          "/issues is missing"),
64     ],
65     'Changelog': http_warnings + [
66     ],
67     'License': [
68         (re.compile(r'^(|None|Unknown)$'),
69          "No license specified"),
70     ],
71     'Summary': [
72         (re.compile(r'^$'),
73          "Summary yet to be filled"),
74         (re.compile(r'.*\b(free software|open source)\b.*', re.IGNORECASE),
75          "No need to specify that the app is Free Software"),
76         (re.compile(r'.*((your|for).*android|android.*(app|device|client|port|version))', re.IGNORECASE),
77          "No need to specify that the app is for Android"),
78         (re.compile(r'.*[a-z0-9][.!?]( |$)'),
79          "Punctuation should be avoided"),
80     ],
81     'Description': [
82         (re.compile(r'^No description available$'),
83          "Description yet to be filled"),
84         (re.compile(r'\s*[*#][^ .]'),
85          "Invalid bulleted list"),
86         (re.compile(r'^\s'),
87          "Unnecessary leading space"),
88         (re.compile(r'.*\s$'),
89          "Unnecessary trailing space"),
90     ],
91 }
92
93 regex_pedantic = {
94     'Issue Tracker': [
95         (re.compile(r'.*github\.com/[^/]+/[^/]+/issues/.*'),
96          "/issues is often enough on its own"),
97     ],
98 }
99
100
101 def main():
102
103     global config, options, curid, count
104     curid = None
105
106     count = Counter()
107
108     def warn(message):
109         global curid, count
110         if curid:
111             print "%s:" % curid
112             curid = None
113             count['app'] += 1
114         print '    %s' % message
115         count['warn'] += 1
116
117     def pwarn(message):
118         if options.pedantic:
119             warn(message)
120
121     # Parse command line...
122     parser = OptionParser(usage="Usage: %prog [options] [APPID [APPID ...]]")
123     parser.add_option("-v", "--verbose", action="store_true", default=False,
124                       help="Spew out even more information than normal")
125     parser.add_option("-q", "--quiet", action="store_true", default=False,
126                       help="Restrict output to warnings and errors")
127     parser.add_option("-p", "--pedantic", action="store_true", default=False,
128                       help="Show pedantic warnings that might give false positives")
129     (options, args) = parser.parse_args()
130
131     config = common.read_config(options)
132
133     # Get all apps...
134     allapps = metadata.read_metadata(xref=False)
135     apps = common.read_app_args(args, allapps, False)
136
137     for appid, app in apps.iteritems():
138         if app['Disabled']:
139             continue
140
141         curid = appid
142         count['app_total'] += 1
143
144         curbuild = None
145         for build in app['builds']:
146             if not curbuild or int(build['vercode']) > int(curbuild['vercode']):
147                 curbuild = build
148
149         # Potentially incorrect UCM
150         if (curbuild and curbuild['commit']
151                 and app['Update Check Mode'] == 'RepoManifest'
152                 and curbuild['commit'] != 'unknown - see disabled'
153                 and any(s in curbuild['commit'] for s in '.,_-/')):
154             pwarn("Last used commit '%s' looks like a tag, but Update Check Mode is '%s'" % (
155                 curbuild['commit'], app['Update Check Mode']))
156
157         # Dangerous auto updates
158         if curbuild and app['Auto Update Mode'] != 'None':
159             for flag in ['target', 'srclibs', 'scanignore']:
160                 if curbuild[flag]:
161                     pwarn("Auto Update Mode is enabled but '%s' is manually set at '%s'" % (flag, curbuild[flag]))
162
163         # Summary size limit
164         summ_chars = len(app['Summary'])
165         if summ_chars > config['char_limits']['Summary']:
166             warn("Summary of length %s is over the %i char limit" % (
167                 summ_chars, config['char_limits']['Summary']))
168
169         # Redundant info
170         if app['Web Site'] and app['Source Code']:
171             if app['Web Site'].lower() == app['Source Code'].lower():
172                 warn("Website '%s' is just the app's source code link" % app['Web Site'])
173
174         # "None" still a category
175         if 'None' in app['Categories']:
176             warn("Category 'None' is is still present")
177         elif not app['Categories']:
178             warn("Categories are not set")
179
180         name = app['Name'] or app['Auto Name']
181         if app['Summary'] and name:
182             if app['Summary'].lower() == name.lower():
183                 warn("Summary '%s' is just the app's name" % app['Summary'])
184
185         desc = app['Description']
186         if app['Summary'] and desc and len(desc) == 1:
187             if app['Summary'].lower() == desc[0].lower():
188                 warn("Description '%s' is just the app's summary" % app['Summary'])
189
190         # Description size limit
191         desc_charcount = sum(len(l) for l in desc)
192         if desc_charcount > config['char_limits']['Description']:
193             warn("Description of length %s is over the %i char limit" % (
194                 desc_charcount, config['char_limits']['Description']))
195
196         if (not desc[0] or not desc[-1]
197                 or any(not desc[l - 1] and not desc[l] for l in range(1, len(desc)))):
198             warn("Description has an extra empty line")
199
200         # Regex checks in all kinds of fields
201         for f in regex_warnings:
202             for m, r in regex_warnings[f]:
203                 t = metadata.metafieldtype(f)
204                 if t == 'string':
205                     if m.match(app[f]):
206                         warn("%s '%s': %s" % (f, app[f], r))
207                 elif t == 'multiline':
208                     for l in app[f]:
209                         if m.match(l):
210                             warn("%s at line '%s': %s" % (f, l, r))
211
212         # Regex pedantic checks in all kinds of fields
213         if options.pedantic:
214             for f in regex_pedantic:
215                 for m, r in regex_pedantic[f]:
216                     if m.match(app[f]):
217                         warn("%s '%s': %s" % (f, app[f], r))
218
219         # Build warnings
220         for build in app['builds']:
221             if build['disable']:
222                 continue
223             for s in ['master', 'origin', 'HEAD', 'default', 'trunk']:
224                 if build['commit'] and build['commit'].startswith(s):
225                     warn("Branch '%s' used as commit in build '%s'" % (
226                         s, build['version']))
227                 for srclib in build['srclibs']:
228                     ref = srclib.split('@')[1].split('/')[0]
229                     if ref.startswith(s):
230                         warn("Branch '%s' used as commit in srclib '%s'" % (
231                             s, srclib))
232             for s in ['git clone', 'git svn clone', 'svn checkout', 'svn co', 'hg clone']:
233                 for flag in ['init', 'prebuild', 'build']:
234                     if not build[flag]:
235                         continue
236                     if s in build[flag]:
237                         # TODO: This should not be pedantic!
238                         pwarn("'%s' used in %s '%s'" % (s, flag, build[flag]))
239
240         if not curid:
241             print
242
243     logging.info("Found a total of %i warnings in %i apps out of %i total." % (
244         count['warn'], count['app'], count['app_total']))
245
246 if __name__ == "__main__":
247     main()