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