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