chiark / gitweb /
lint: catch links at the beginning too
[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 argparse import ArgumentParser
21 import re
22 import common
23 import metadata
24 import sys
25 from sets import Set
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('gitlab.com'),
38     enforce_https('bitbucket.org'),
39     enforce_https('apache.org'),
40     enforce_https('google.com'),
41     enforce_https('svn.code.sf.net'),
42 ]
43
44
45 def forbid_shortener(domain):
46     return (re.compile(r'https?://[^/]*' + re.escape(domain) + r'/.*'),
47             "URL shorteners should not be used")
48
49 http_url_shorteners = [
50     forbid_shortener('goo.gl'),
51     forbid_shortener('t.co'),
52     forbid_shortener('ur1.ca'),
53 ]
54
55 http_checks = https_enforcings + http_url_shorteners + [
56     (re.compile(r'.*github\.com/[^/]+/[^/]+\.git'),
57      "Appending .git is not necessary"),
58     (re.compile(r'(.*/blob/master/|.*raw\.github.com/[^/]*/[^/]*/master/|.*/raw/master/)'),
59      "Use /HEAD/ instead of /master/ to point at a file in the default branch"),
60 ]
61
62 regex_checks = {
63     'Web Site': http_checks,
64     'Source Code': http_checks,
65     'Repo': https_enforcings,
66     'Issue Tracker': http_checks + [
67         (re.compile(r'.*github\.com/[^/]+/[^/]+[/]*$'),
68          "/issues is missing"),
69     ],
70     'Donate': http_checks + [
71         (re.compile(r'.*flattr\.com'),
72          "Flattr donation methods belong in the FlattrID flag"),
73     ],
74     'Changelog': http_checks,
75     'License': [
76         (re.compile(r'^(|None|Unknown)$'),
77          "No license specified"),
78     ],
79     'Summary': [
80         (re.compile(r'^$'),
81          "Summary yet to be filled"),
82         (re.compile(r'.*\b(free software|open source)\b.*', re.IGNORECASE),
83          "No need to specify that the app is Free Software"),
84         (re.compile(r'.*((your|for).*android|android.*(app|device|client|port|version))', re.IGNORECASE),
85          "No need to specify that the app is for Android"),
86         (re.compile(r'.*[a-z0-9][.!?]( |$)'),
87          "Punctuation should be avoided"),
88     ],
89     'Description': [
90         (re.compile(r'^No description available$'),
91          "Description yet to be filled"),
92         (re.compile(r'\s*[*#][^ .]'),
93          "Invalid bulleted list"),
94         (re.compile(r'^\s'),
95          "Unnecessary leading space"),
96         (re.compile(r'.*\s$'),
97          "Unnecessary trailing space"),
98         (re.compile(r'.*([^[]|^)\[[^:[\]]+( |\]|$)'),
99          "Invalid link - use [http://foo.bar Link title] or [http://foo.bar]"),
100         (re.compile(r'(^|.* )https?://[^ ]+'),
101          "Unlinkified link - use [http://foo.bar Link title] or [http://foo.bar]"),
102     ],
103 }
104
105
106 def check_regexes(app):
107     for f, checks in regex_checks.iteritems():
108         for m, r in checks:
109             v = app[f]
110             if type(v) == str:
111                 if v is None:
112                     continue
113                 if m.match(v):
114                     yield "%s '%s': %s" % (f, v, r)
115             elif type(v) == list:
116                 for l in v:
117                     if m.match(l):
118                         yield "%s at line '%s': %s" % (f, l, r)
119
120
121 def get_lastbuild(builds):
122     lowest_vercode = -1
123     lastbuild = None
124     for build in builds:
125         if not build['disable']:
126             vercode = int(build['vercode'])
127             if lowest_vercode == -1 or vercode < lowest_vercode:
128                 lowest_vercode = vercode
129         if not lastbuild or int(build['vercode']) > int(lastbuild['vercode']):
130             lastbuild = build
131     return lastbuild
132
133
134 def check_ucm_tags(app):
135     lastbuild = get_lastbuild(app['builds'])
136     if (lastbuild is not None
137             and lastbuild['commit']
138             and app['Update Check Mode'] == 'RepoManifest'
139             and not lastbuild['commit'].startswith('unknown')
140             and lastbuild['vercode'] == app['Current Version Code']
141             and not lastbuild['forcevercode']
142             and any(s in lastbuild['commit'] for s in '.,_-/')):
143         yield "Last used commit '%s' looks like a tag, but Update Check Mode is '%s'" % (
144             lastbuild['commit'], app['Update Check Mode'])
145
146
147 def check_char_limits(app):
148     limits = config['char_limits']
149
150     summ_chars = len(app['Summary'])
151     if summ_chars > limits['Summary']:
152         yield "Summary of length %s is over the %i char limit" % (
153             summ_chars, limits['Summary'])
154
155     desc_charcount = sum(len(l) for l in app['Description'])
156     if desc_charcount > limits['Description']:
157         yield "Description of length %s is over the %i char limit" % (
158             desc_charcount, limits['Description'])
159
160
161 def check_old_links(app):
162     usual_sites = [
163         'github.com',
164         'gitlab.com',
165         'bitbucket.org',
166     ]
167     old_sites = [
168         'gitorious.org',
169         'code.google.com',
170     ]
171     if any(s in app['Repo'] for s in usual_sites):
172         for f in ['Web Site', 'Source Code', 'Issue Tracker', 'Changelog']:
173             if any(s in app[f] for s in old_sites):
174                 yield "App is in '%s' but has a link to '%s'" % (app['Repo'], app[f])
175
176
177 def check_useless_fields(app):
178     if app['Update Check Name'] == app['id']:
179         yield "Update Check Name is set to the known app id - it can be removed"
180
181 filling_ucms = re.compile(r'^(Tags.*|RepoManifest.*)')
182
183
184 def check_checkupdates_ran(app):
185     if filling_ucms.match(app['Update Check Mode']):
186         if all(app[f] == metadata.app_defaults[f] for f in [
187                 'Auto Name',
188                 'Current Version',
189                 'Current Version Code',
190                 ]):
191             yield "UCM is set but it looks like checkupdates hasn't been run yet"
192
193
194 def check_empty_fields(app):
195     if not app['Categories']:
196         yield "Categories are not set"
197
198 all_categories = Set([
199     "Connectivity",
200     "Development",
201     "Games",
202     "Graphics",
203     "Internet",
204     "Money",
205     "Multimedia",
206     "Navigation",
207     "Phone & SMS",
208     "Reading",
209     "Science & Education",
210     "Security",
211     "Sports & Health",
212     "System",
213     "Theming",
214     "Time",
215     "Writing",
216 ])
217
218
219 def check_categories(app):
220     for categ in app['Categories']:
221         if categ not in all_categories:
222             yield "Category '%s' is not valid" % categ
223
224
225 def check_duplicates(app):
226     if app['Name'] and app['Name'] == app['Auto Name']:
227         yield "Name '%s' is just the auto name - remove it" % app['Name']
228
229     links_seen = set()
230     for f in ['Source Code', 'Web Site', 'Issue Tracker', 'Changelog']:
231         if not app[f]:
232             continue
233         v = app[f].lower()
234         if v in links_seen:
235             yield "Duplicate link in '%s': %s" % (f, v)
236         else:
237             links_seen.add(v)
238
239     name = app['Name'] or app['Auto Name']
240     if app['Summary'] and name:
241         if app['Summary'].lower() == name.lower():
242             yield "Summary '%s' is just the app's name" % app['Summary']
243
244     desc = app['Description']
245     if app['Summary'] and desc and len(desc) == 1:
246         if app['Summary'].lower() == desc[0].lower():
247             yield "Description '%s' is just the app's summary" % app['Summary']
248
249     seenlines = set()
250     for l in app['Description']:
251         if len(l) < 1:
252             continue
253         if l in seenlines:
254             yield "Description has a duplicate line"
255         seenlines.add(l)
256
257
258 desc_url = re.compile(r'(^|[^[])\[([^ ]+)( |\]|$)')
259
260
261 def check_mediawiki_links(app):
262     wholedesc = ' '.join(app['Description'])
263     for um in desc_url.finditer(wholedesc):
264         url = um.group(1)
265         for m, r in http_checks:
266             if m.match(url):
267                 yield "URL '%s' in Description: %s" % (url, r)
268
269
270 def check_bulleted_lists(app):
271     validchars = ['*', '#']
272     lchar = ''
273     lcount = 0
274     for l in app['Description']:
275         if len(l) < 1:
276             lcount = 0
277             continue
278
279         if l[0] == lchar and l[1] == ' ':
280             lcount += 1
281             if lcount > 2 and lchar not in validchars:
282                 yield "Description has a list (%s) but it isn't bulleted (*) nor numbered (#)" % lchar
283                 break
284         else:
285             lchar = l[0]
286             lcount = 1
287
288
289 def check_builds(app):
290     for build in app['builds']:
291         if build['disable']:
292             continue
293         for s in ['master', 'origin', 'HEAD', 'default', 'trunk']:
294             if build['commit'] and build['commit'].startswith(s):
295                 yield "Branch '%s' used as commit in build '%s'" % (s, build['version'])
296             for srclib in build['srclibs']:
297                 ref = srclib.split('@')[1].split('/')[0]
298                 if ref.startswith(s):
299                     yield "Branch '%s' used as commit in srclib '%s'" % (s, srclib)
300
301
302 def main():
303
304     global config, options
305
306     anywarns = False
307
308     # Parse command line...
309     parser = ArgumentParser(usage="%(prog)s [options] [APPID [APPID ...]]")
310     common.setup_global_opts(parser)
311     parser.add_argument("appid", nargs='*', help="app-id in the form APPID")
312     options = parser.parse_args()
313
314     config = common.read_config(options)
315
316     # Get all apps...
317     allapps = metadata.read_metadata(xref=True)
318     apps = common.read_app_args(options.appid, allapps, False)
319
320     for appid, app in apps.iteritems():
321         if app['Disabled']:
322             continue
323
324         warns = []
325
326         for check_func in [
327                 check_regexes,
328                 check_ucm_tags,
329                 check_char_limits,
330                 check_old_links,
331                 check_checkupdates_ran,
332                 check_useless_fields,
333                 check_empty_fields,
334                 check_categories,
335                 check_duplicates,
336                 check_mediawiki_links,
337                 check_bulleted_lists,
338                 check_builds,
339                 ]:
340             warns += check_func(app)
341
342         if warns:
343             anywarns = True
344             for warn in warns:
345                 print "%s: %s" % (appid, warn)
346
347     if anywarns:
348         sys.exit(1)
349
350
351 if __name__ == "__main__":
352     main()