chiark / gitweb /
rename Build fields: version -> versionName, vercode -> versionCode
[fdroidserver.git] / fdroidserver / lint.py
1 #!/usr/bin/env python3
2 #
3 # lint.py - part of the FDroid server tool
4 # Copyright (C) 2013-2014 Daniel Martí <mvdan@mvdan.cc>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Affero General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See th
14 # GNU Affero General Public License for more details.
15 #
16 # You should have received a copy of the GNU Affero General Public Licen
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18
19 from argparse import ArgumentParser
20 import os
21 import re
22 import sys
23
24 from . import common
25 from . import metadata
26 from . import rewritemeta
27
28 config = None
29 options = None
30
31
32 def enforce_https(domain):
33     return (re.compile(r'.*[^sS]://[^/]*' + re.escape(domain) + r'(/.*)?'),
34             domain + " URLs should always use https://")
35
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
52 http_url_shorteners = [
53     forbid_shortener('goo.gl'),
54     forbid_shortener('t.co'),
55     forbid_shortener('ur1.ca'),
56 ]
57
58 http_checks = https_enforcings + http_url_shorteners + [
59     (re.compile(r'.*github\.com/[^/]+/[^/]+\.git'),
60      "Appending .git is not necessary"),
61     (re.compile(r'.*://[^/]*(github|gitlab|bitbucket|rawgit)[^/]*/([^/]+/){1,3}master'),
62      "Use /HEAD instead of /master to point at a file in the default branch"),
63 ]
64
65 regex_checks = {
66     'WebSite': http_checks,
67     'SourceCode': http_checks,
68     'Repo': https_enforcings,
69     'IssueTracker': http_checks + [
70         (re.compile(r'.*github\.com/[^/]+/[^/]+/*$'),
71          "/issues is missing"),
72         (re.compile(r'.*gitlab\.com/[^/]+/[^/]+/*$'),
73          "/issues is missing"),
74     ],
75     'Donate': http_checks + [
76         (re.compile(r'.*flattr\.com'),
77          "Flattr donation methods belong in the FlattrID flag"),
78     ],
79     'Changelog': http_checks,
80     'Author Name': [
81         (re.compile(r'^\s'),
82          "Unnecessary leading space"),
83         (re.compile(r'.*\s$'),
84          "Unnecessary trailing space"),
85     ],
86     'License': [
87         (re.compile(r'^(|None|Unknown)$'),
88          "No license specified"),
89     ],
90     'Summary': [
91         (re.compile(r'^$'),
92          "Summary yet to be filled"),
93         (re.compile(r'.*\b(free software|open source)\b.*', re.IGNORECASE),
94          "No need to specify that the app is Free Software"),
95         (re.compile(r'.*((your|for).*android|android.*(app|device|client|port|version))', re.IGNORECASE),
96          "No need to specify that the app is for Android"),
97         (re.compile(r'.*[a-z0-9][.!?]( |$)'),
98          "Punctuation should be avoided"),
99         (re.compile(r'^\s'),
100          "Unnecessary leading space"),
101         (re.compile(r'.*\s$'),
102          "Unnecessary trailing space"),
103     ],
104     'Description': [
105         (re.compile(r'^No description available$'),
106          "Description yet to be filled"),
107         (re.compile(r'\s*[*#][^ .]'),
108          "Invalid bulleted list"),
109         (re.compile(r'^\s'),
110          "Unnecessary leading space"),
111         (re.compile(r'.*\s$'),
112          "Unnecessary trailing space"),
113         (re.compile(r'.*([^[]|^)\[[^:[\]]+( |\]|$)'),
114          "Invalid link - use [http://foo.bar Link title] or [http://foo.bar]"),
115         (re.compile(r'(^|.* )https?://[^ ]+'),
116          "Unlinkified link - use [http://foo.bar Link title] or [http://foo.bar]"),
117     ],
118 }
119
120
121 def check_regexes(app):
122     for f, checks in regex_checks.items():
123         for m, r in checks:
124             v = app.get(f)
125             t = metadata.fieldtype(f)
126             if t == metadata.TYPE_MULTILINE:
127                 for l in v.splitlines():
128                     if m.match(l):
129                         yield "%s at line '%s': %s" % (f, l, r)
130             else:
131                 if v is None:
132                     continue
133                 if m.match(v):
134                     yield "%s '%s': %s" % (f, v, r)
135
136
137 def get_lastbuild(builds):
138     lowest_vercode = -1
139     lastbuild = None
140     for build in builds:
141         if not build.disable:
142             vercode = int(build.versionCode)
143             if lowest_vercode == -1 or vercode < lowest_vercode:
144                 lowest_vercode = vercode
145         if not lastbuild or int(build.versionCode) > int(lastbuild.versionCode):
146             lastbuild = build
147     return lastbuild
148
149
150 def check_ucm_tags(app):
151     lastbuild = get_lastbuild(app.builds)
152     if (lastbuild is not None
153             and lastbuild.commit
154             and app.UpdateCheckMode == 'RepoManifest'
155             and not lastbuild.commit.startswith('unknown')
156             and lastbuild.versionCode == app.CurrentVersionCode
157             and not lastbuild.forcevercode
158             and any(s in lastbuild.commit for s in '.,_-/')):
159         yield "Last used commit '%s' looks like a tag, but Update Check Mode is '%s'" % (
160             lastbuild.commit, app.UpdateCheckMode)
161
162
163 def check_char_limits(app):
164     limits = config['char_limits']
165
166     if len(app.Summary) > limits['Summary']:
167         yield "Summary of length %s is over the %i char limit" % (
168             len(app.Summary), limits['Summary'])
169
170     if len(app.Description) > limits['Description']:
171         yield "Description of length %s is over the %i char limit" % (
172             len(app.Description), limits['Description'])
173
174
175 def check_old_links(app):
176     usual_sites = [
177         'github.com',
178         'gitlab.com',
179         'bitbucket.org',
180     ]
181     old_sites = [
182         'gitorious.org',
183         'code.google.com',
184     ]
185     if any(s in app.Repo for s in usual_sites):
186         for f in ['WebSite', 'SourceCode', 'IssueTracker', 'Changelog']:
187             v = app.get(f)
188             if any(s in v for s in old_sites):
189                 yield "App is in '%s' but has a link to '%s'" % (app.Repo, v)
190
191
192 def check_useless_fields(app):
193     if app.UpdateCheckName == app.id:
194         yield "Update Check Name is set to the known app id - it can be removed"
195
196
197 filling_ucms = re.compile(r'^(Tags.*|RepoManifest.*)')
198
199
200 def check_checkupdates_ran(app):
201     if filling_ucms.match(app.UpdateCheckMode):
202         if not app.AutoName and not app.CurrentVersion and app.CurrentVersionCode == '0':
203             yield "UCM is set but it looks like checkupdates hasn't been run yet"
204
205
206 def check_empty_fields(app):
207     if not app.Categories:
208         yield "Categories are not set"
209
210
211 all_categories = set([
212     "Connectivity",
213     "Development",
214     "Games",
215     "Graphics",
216     "Internet",
217     "Money",
218     "Multimedia",
219     "Navigation",
220     "Phone & SMS",
221     "Reading",
222     "Science & Education",
223     "Security",
224     "Sports & Health",
225     "System",
226     "Theming",
227     "Time",
228     "Writing",
229 ])
230
231
232 def check_categories(app):
233     for categ in app.Categories:
234         if categ not in all_categories:
235             yield "Category '%s' is not valid" % categ
236
237
238 def check_duplicates(app):
239     if app.Name and app.Name == app.AutoName:
240         yield "Name '%s' is just the auto name - remove it" % app.Name
241
242     links_seen = set()
243     for f in ['Source Code', 'Web Site', 'Issue Tracker', 'Changelog']:
244         v = app.get(f)
245         if not v:
246             continue
247         v = v.lower()
248         if v in links_seen:
249             yield "Duplicate link in '%s': %s" % (f, v)
250         else:
251             links_seen.add(v)
252
253     name = app.Name or app.AutoName
254     if app.Summary and name:
255         if app.Summary.lower() == name.lower():
256             yield "Summary '%s' is just the app's name" % app.Summary
257
258     if app.Summary and app.Description and len(app.Description) == 1:
259         if app.Summary.lower() == app.Description[0].lower():
260             yield "Description '%s' is just the app's summary" % app.Summary
261
262     seenlines = set()
263     for l in app.Description.splitlines():
264         if len(l) < 1:
265             continue
266         if l in seenlines:
267             yield "Description has a duplicate line"
268         seenlines.add(l)
269
270
271 desc_url = re.compile(r'(^|[^[])\[([^ ]+)( |\]|$)')
272
273
274 def check_mediawiki_links(app):
275     wholedesc = ' '.join(app.Description)
276     for um in desc_url.finditer(wholedesc):
277         url = um.group(1)
278         for m, r in http_checks:
279             if m.match(url):
280                 yield "URL '%s' in Description: %s" % (url, r)
281
282
283 def check_bulleted_lists(app):
284     validchars = ['*', '#']
285     lchar = ''
286     lcount = 0
287     for l in app.Description.splitlines():
288         if len(l) < 1:
289             lcount = 0
290             continue
291
292         if l[0] == lchar and l[1] == ' ':
293             lcount += 1
294             if lcount > 2 and lchar not in validchars:
295                 yield "Description has a list (%s) but it isn't bulleted (*) nor numbered (#)" % lchar
296                 break
297         else:
298             lchar = l[0]
299             lcount = 1
300
301
302 def check_builds(app):
303     for build in app.builds:
304         if build.disable:
305             if build.disable.startswith('Generated by import.py'):
306                 yield "Build generated by `fdroid import` - remove disable line once ready"
307             continue
308         for s in ['master', 'origin', 'HEAD', 'default', 'trunk']:
309             if build.commit and build.commit.startswith(s):
310                 yield "Branch '%s' used as commit in build '%s'" % (s, build.versionName)
311             for srclib in build.srclibs:
312                 ref = srclib.split('@')[1].split('/')[0]
313                 if ref.startswith(s):
314                     yield "Branch '%s' used as commit in srclib '%s'" % (s, srclib)
315
316
317 def check_files_dir(app):
318     dir_path = os.path.join('metadata', app.id)
319     if not os.path.isdir(dir_path):
320         return
321     files = set()
322     for name in os.listdir(dir_path):
323         path = os.path.join(dir_path, name)
324         if not os.path.isfile(path):
325             yield "Found non-file at %s" % path
326             continue
327         files.add(name)
328
329     used = set()
330     for build in app.builds:
331         for fname in build.patch:
332             if fname not in files:
333                 yield "Unknown file %s in build '%s'" % (fname, build.versionName)
334             else:
335                 used.add(fname)
336
337     for name in files.difference(used):
338         yield "Unused file at %s" % os.path.join(dir_path, name)
339
340
341 def check_format(app):
342     if options.format and not rewritemeta.proper_format(app):
343         yield "Run rewritemeta to fix formatting"
344
345
346 def check_extlib_dir(apps):
347     dir_path = os.path.join('build', 'extlib')
348     files = set()
349     for root, dirs, names in os.walk(dir_path):
350         for name in names:
351             files.add(os.path.join(root, name)[len(dir_path) + 1:])
352
353     used = set()
354     for app in apps:
355         for build in app.builds:
356             for path in build.extlibs:
357                 if path not in files:
358                     yield "%s: Unknown extlib %s in build '%s'" % (app.id, path, build.versionName)
359                 else:
360                     used.add(path)
361
362     for path in files.difference(used):
363         if any(path.endswith(s) for s in [
364                 '.gitignore',
365                 'source.txt', 'origin.txt', 'md5.txt',
366                 'LICENSE', 'LICENSE.txt',
367                 'COPYING', 'COPYING.txt',
368                 'NOTICE', 'NOTICE.txt',
369                 ]):
370             continue
371         yield "Unused extlib at %s" % os.path.join(dir_path, path)
372
373
374 def main():
375
376     global config, options
377
378     # Parse command line...
379     parser = ArgumentParser(usage="%(prog)s [options] [APPID [APPID ...]]")
380     common.setup_global_opts(parser)
381     parser.add_argument("-f", "--format", action="store_true", default=False,
382                         help="Also warn about formatting issues, like rewritemeta -l")
383     parser.add_argument("appid", nargs='*', help="app-id in the form APPID")
384     metadata.add_metadata_arguments(parser)
385     options = parser.parse_args()
386     metadata.warnings_action = options.W
387
388     config = common.read_config(options)
389
390     # Get all apps...
391     allapps = metadata.read_metadata(xref=True)
392     apps = common.read_app_args(options.appid, allapps, False)
393
394     anywarns = False
395
396     apps_check_funcs = []
397     if len(options.appid) == 0:
398         # otherwise it finds tons of unused extlibs
399         apps_check_funcs.append(check_extlib_dir)
400     for check_func in apps_check_funcs:
401         for warn in check_func(apps.values()):
402             anywarns = True
403             print(warn)
404
405     for appid, app in apps.items():
406         if app.Disabled:
407             continue
408
409         app_check_funcs = [
410             check_regexes,
411             check_ucm_tags,
412             check_char_limits,
413             check_old_links,
414             check_checkupdates_ran,
415             check_useless_fields,
416             check_empty_fields,
417             check_categories,
418             check_duplicates,
419             check_mediawiki_links,
420             check_bulleted_lists,
421             check_builds,
422             check_files_dir,
423             check_format,
424         ]
425
426         for check_func in app_check_funcs:
427             for warn in check_func(app):
428                 anywarns = True
429                 print("%s: %s" % (appid, warn))
430
431     if anywarns:
432         sys.exit(1)
433
434
435 if __name__ == "__main__":
436     main()