xref: /titanic_51/usr/src/tools/scripts/git-pbchk.py (revision 75d94465dbafa487b716482dc36d5150a4ec9853)
1#!/usr/bin/python2.6
2#
3#  This program is free software; you can redistribute it and/or modify
4#  it under the terms of the GNU General Public License version 2
5#  as published by the Free Software Foundation.
6#
7#  This program is distributed in the hope that it will be useful,
8#  but WITHOUT ANY WARRANTY; without even the implied warranty of
9#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10#  GNU General Public License for more details.
11#
12#  You should have received a copy of the GNU General Public License
13#  along with this program; if not, write to the Free Software
14#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
15#
16
17#
18# Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
19# Copyright 2008, 2012 Richard Lowe
20# Copyright 2014 Garrett D'Amore <garrett@damore.org>
21#
22
23import getopt
24import os
25import re
26import subprocess
27import sys
28import tempfile
29
30from cStringIO import StringIO
31
32# This is necessary because, in a fit of pique, we used hg-format ignore lists
33# for NOT files.
34from mercurial import ignore
35
36#
37# Adjust the load path based on our location and the version of python into
38# which it is being loaded.  This assumes the normal onbld directory
39# structure, where we are in bin/ and the modules are in
40# lib/python(version)?/onbld/Scm/.  If that changes so too must this.
41#
42sys.path.insert(1, os.path.join(os.path.dirname(__file__), "..", "lib",
43                                "python%d.%d" % sys.version_info[:2]))
44
45#
46# Add the relative path to usr/src/tools to the load path, such that when run
47# from the source tree we use the modules also within the source tree.
48#
49sys.path.insert(2, os.path.join(os.path.dirname(__file__), ".."))
50
51from onbld.Checks import Comments, Copyright, CStyle, HdrChk
52from onbld.Checks import JStyle, Keywords, ManLint, Mapfile
53
54
55class GitError(Exception):
56    pass
57
58def git(command):
59    """Run a command and return a stream containing its stdout (and write its
60    stderr to its stdout)"""
61
62    if type(command) != list:
63        command = command.split()
64
65    command = ["git"] + command
66
67    try:
68        tmpfile = tempfile.TemporaryFile(prefix="git-nits")
69    except EnvironmentError, e:
70        raise GitError("Could not create temporary file: %s\n" % e)
71
72    try:
73        p = subprocess.Popen(command,
74                             stdout=tmpfile,
75                             stderr=subprocess.STDOUT)
76    except OSError, e:
77        raise GitError("could not execute %s: %s\n" (command, e))
78
79    err = p.wait()
80    if err != 0:
81        raise GitError(p.stdout.read())
82
83    tmpfile.seek(0)
84    return tmpfile
85
86
87def git_root():
88    """Return the root of the current git workspace"""
89
90    p = git('rev-parse --git-dir')
91
92    if not p:
93        sys.stderr.write("Failed finding git workspace\n")
94        sys.exit(err)
95
96    return os.path.abspath(os.path.join(p.readlines()[0],
97                                        os.path.pardir))
98
99
100def git_branch():
101    """Return the current git branch"""
102
103    p = git('branch')
104
105    if not p:
106        sys.stderr.write("Failed finding git branch\n")
107        sys.exit(err)
108
109    for elt in p:
110        if elt[0] == '*':
111            if elt.endswith('(no branch)'):
112                return None
113            return elt.split()[1]
114
115
116def git_parent_branch(branch):
117    """Return the parent of the current git branch.
118
119    If this branch tracks a remote branch, return the remote branch which is
120    tracked.  If not, default to origin/master."""
121
122    if not branch:
123        return None
124
125    p = git("for-each-ref --format=%(refname:short) %(upstream:short) " +
126            "refs/heads/")
127
128    if not p:
129        sys.stderr.write("Failed finding git parent branch\n")
130        sys.exit(err)
131
132    for line in p:
133        # Git 1.7 will leave a ' ' trailing any non-tracking branch
134        if ' ' in line and not line.endswith(' \n'):
135            local, remote = line.split()
136            if local == branch:
137                return remote
138    return 'origin/master'
139
140
141def git_comments(parent):
142    """Return a list of any checkin comments on this git branch"""
143
144    p = git('log --pretty=tformat:%%B:SEP: %s..' % parent)
145
146    if not p:
147        sys.stderr.write("Failed getting git comments\n")
148        sys.exit(err)
149
150    return [x.strip() for x in p.readlines() if x != ':SEP:\n']
151
152
153def git_file_list(parent, paths=None):
154    """Return the set of files which have ever changed on this branch.
155
156    NB: This includes files which no longer exist, or no longer actually
157    differ."""
158
159    p = git("log --name-only --pretty=format: %s.. %s" %
160             (parent, ' '.join(paths)))
161
162    if not p:
163        sys.stderr.write("Failed building file-list from git\n")
164        sys.exit(err)
165
166    ret = set()
167    for fname in p:
168        if fname and not fname.isspace() and fname not in ret:
169            ret.add(fname.strip())
170
171    return ret
172
173
174def not_check(root, cmd):
175    """Return a function which returns True if a file given as an argument
176    should be excluded from the check named by 'cmd'"""
177
178    ignorefiles = filter(os.path.exists,
179                         [os.path.join(root, ".git", "%s.NOT" % cmd),
180                          os.path.join(root, "exception_lists", cmd)])
181    if len(ignorefiles) > 0:
182        return ignore.ignore(root, ignorefiles, sys.stderr.write)
183    else:
184        return lambda x: False
185
186
187def gen_files(root, parent, paths, exclude):
188    """Return a function producing file names, relative to the current
189    directory, of any file changed on this branch (limited to 'paths' if
190    requested), and excluding files for which exclude returns a true value """
191
192    # Taken entirely from Python 2.6's os.path.relpath which we would use if we
193    # could.
194    def relpath(path, here):
195        c = os.path.abspath(os.path.join(root, path)).split(os.path.sep)
196        s = os.path.abspath(here).split(os.path.sep)
197        l = len(os.path.commonprefix((s, c)))
198        return os.path.join(*[os.path.pardir] * (len(s)-l) + c[l:])
199
200    def ret(select=None):
201        if not select:
202            select = lambda x: True
203
204        for f in git_file_list(parent, paths):
205            f = relpath(f, '.')
206            if (os.path.exists(f) and select(f) and not exclude(f)):
207                yield f
208    return ret
209
210
211def comchk(root, parent, flist, output):
212    output.write("Comments:\n")
213
214    return Comments.comchk(git_comments(parent), check_db=True,
215                           output=output)
216
217
218def mapfilechk(root, parent, flist, output):
219    ret = 0
220
221    # We are interested in examining any file that has the following
222    # in its final path segment:
223    #    - Contains the word 'mapfile'
224    #    - Begins with 'map.'
225    #    - Ends with '.map'
226    # We don't want to match unless these things occur in final path segment
227    # because directory names with these strings don't indicate a mapfile.
228    # We also ignore files with suffixes that tell us that the files
229    # are not mapfiles.
230    MapfileRE = re.compile(r'.*((mapfile[^/]*)|(/map\.+[^/]*)|(\.map))$',
231        re.IGNORECASE)
232    NotMapSuffixRE = re.compile(r'.*\.[ch]$', re.IGNORECASE)
233
234    output.write("Mapfile comments:\n")
235
236    for f in flist(lambda x: MapfileRE.match(x) and not
237                   NotMapSuffixRE.match(x)):
238        fh = open(f, 'r')
239        ret |= Mapfile.mapfilechk(fh, output=output)
240        fh.close()
241    return ret
242
243
244def copyright(root, parent, flist, output):
245    ret = 0
246    output.write("Copyrights:\n")
247    for f in flist():
248        fh = open(f, 'r')
249        ret |= Copyright.copyright(fh, output=output)
250        fh.close()
251    return ret
252
253
254def hdrchk(root, parent, flist, output):
255    ret = 0
256    output.write("Header format:\n")
257    for f in flist(lambda x: x.endswith('.h')):
258        fh = open(f, 'r')
259        ret |= HdrChk.hdrchk(fh, lenient=True, output=output)
260        fh.close()
261    return ret
262
263
264def cstyle(root, parent, flist, output):
265    ret = 0
266    output.write("C style:\n")
267    for f in flist(lambda x: x.endswith('.c') or x.endswith('.h')):
268        fh = open(f, 'r')
269        ret |= CStyle.cstyle(fh, output=output, picky=True,
270                             check_posix_types=True,
271                             check_continuation=True)
272        fh.close()
273    return ret
274
275
276def jstyle(root, parent, flist, output):
277    ret = 0
278    output.write("Java style:\n")
279    for f in flist(lambda x: x.endswith('.java')):
280        fh = open(f, 'r')
281        ret |= JStyle.jstyle(fh, output=output, picky=True)
282        fh.close()
283    return ret
284
285
286def manlint(root, parent, flist, output):
287    ret = 0
288    output.write("Man page format:\n")
289    ManfileRE = re.compile(r'.*\.[0-9][a-z]*$', re.IGNORECASE)
290    for f in flist(lambda x: ManfileRE.match(x)):
291        fh = open(f, 'r')
292        ret |= ManLint.manlint(fh, output=output, picky=True)
293	fh.close()
294    return ret
295
296def keywords(root, parent, flist, output):
297    ret = 0
298    output.write("SCCS Keywords:\n")
299    for f in flist():
300        fh = open(f, 'r')
301        ret |= Keywords.keywords(fh, output=output)
302        fh.close()
303    return ret
304
305
306def run_checks(root, parent, cmds, paths='', opts={}):
307    """Run the checks given in 'cmds', expected to have well-known signatures,
308    and report results for any which fail.
309
310    Return failure if any of them did.
311
312    NB: the function name of the commands passed in is used to name the NOT
313    file which excepts files from them."""
314
315    ret = 0
316
317    for cmd in cmds:
318        s = StringIO()
319
320        exclude = not_check(root, cmd.func_name)
321        result = cmd(root, parent, gen_files(root, parent, paths, exclude),
322                     output=s)
323        ret |= result
324
325        if result != 0:
326            print s.getvalue()
327
328    return ret
329
330
331def nits(root, parent, paths):
332    cmds = [copyright,
333            cstyle,
334            hdrchk,
335            jstyle,
336            keywords,
337	    manlint,
338            mapfilechk]
339    run_checks(root, parent, cmds, paths)
340
341
342def pbchk(root, parent, paths):
343    cmds = [comchk,
344            copyright,
345            cstyle,
346            hdrchk,
347            jstyle,
348            keywords,
349	    manlint,
350            mapfilechk]
351    run_checks(root, parent, cmds)
352
353
354def main(cmd, args):
355    parent_branch = None
356
357    try:
358        opts, args = getopt.getopt(args, 'b:')
359    except getopt.GetoptError, e:
360        sys.stderr.write(str(e) + '\n')
361        sys.stderr.write("Usage: %s [-b branch] [path...]\n" % cmd)
362        sys.exit(1)
363
364    for opt, arg in opts:
365        if opt == '-b':
366            parent_branch = arg
367
368    if not parent_branch:
369        parent_branch = git_parent_branch(git_branch())
370
371    func = nits
372    if cmd == 'git-pbchk':
373        func = pbchk
374        if args:
375            sys.stderr.write("only complete workspaces may be pbchk'd\n");
376            sys.exit(1)
377
378    func(git_root(), parent_branch, args)
379
380if __name__ == '__main__':
381    try:
382        main(os.path.basename(sys.argv[0]), sys.argv[1:])
383    except GitError, e:
384        sys.stderr.write("failed to run git:\n %s\n" % str(e))
385        sys.exit(1)
386