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.
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.
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.
18 # Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
19 # Copyright 2008, 2012 Richard Lowe
29 from cStringIO
import StringIO
31 # This is necessary because, in a fit of pique, we used hg-format ignore lists
33 from mercurial
import ignore
36 # Adjust the load path based on our location and the version of python into
37 # which it is being loaded. This assumes the normal onbld directory
38 # structure, where we are in bin/ and the modules are in
39 # lib/python(version)?/onbld/Scm/. If that changes so too must this.
41 sys
.path
.insert(1, os
.path
.join(os
.path
.dirname(__file__
), "..", "lib",
42 "python%d.%d" % sys
.version_info
[:2]))
45 # Add the relative path to usr/src/tools to the load path, such that when run
46 # from the source tree we use the modules also within the source tree.
48 sys
.path
.insert(2, os
.path
.join(os
.path
.dirname(__file__
), ".."))
50 from onbld
.Checks
import Comments
, Copyright
, CStyle
, HdrChk
51 from onbld
.Checks
import JStyle
, Keywords
, Mapfile
54 class GitError(Exception):
58 """Run a command and return a stream containing its stdout (and write its
59 stderr to its stdout)"""
61 if type(command
) != list:
62 command
= command
.split()
64 command
= ["git"] + command
67 tmpfile
= tempfile
.TemporaryFile(prefix
="git-nits")
68 except EnvironmentError, e
:
69 raise GitError("Could not create temporary file: %s\n" % e
)
72 p
= subprocess
.Popen(command
,
74 stderr
=subprocess
.STDOUT
)
76 raise GitError("could not execute %s: %s\n" (command
, e
))
80 raise GitError(p
.stdout
.read())
87 """Return the root of the current git workspace"""
89 p
= git('rev-parse --git-dir')
92 sys
.stderr
.write("Failed finding git workspace\n")
95 return os
.path
.abspath(os
.path
.join(p
.readlines()[0],
100 """Return the current git branch"""
105 sys
.stderr
.write("Failed finding git branch\n")
110 if elt
.endswith('(no branch)'):
112 return elt
.split()[1]
115 def git_parent_branch(branch
):
116 """Return the parent of the current git branch.
118 If this branch tracks a remote branch, return the remote branch which is
119 tracked. If not, default to origin/master."""
124 p
= git("for-each-ref --format=%(refname:short) %(upstream:short) " +
128 sys
.stderr
.write("Failed finding git parent branch\n")
132 # Git 1.7 will leave a ' ' trailing any non-tracking branch
133 if ' ' in line
and not line
.endswith(' \n'):
134 local
, remote
= line
.split()
137 return 'origin/master'
140 def git_comments(parent
):
141 """Return a list of any checkin comments on this git branch"""
143 p
= git('log --pretty=tformat:%%B:SEP: %s..' % parent
)
146 sys
.stderr
.write("Failed getting git comments\n")
149 return [x
.strip() for x
in p
.readlines() if x
!= ':SEP:\n']
152 def git_file_list(parent
, paths
=None):
153 """Return the set of files which have ever changed on this branch.
155 NB: This includes files which no longer exist, or no longer actually
158 p
= git("log --name-only --pretty=format: %s.. %s" %
159 (parent
, ' '.join(paths
)))
162 sys
.stderr
.write("Failed building file-list from git\n")
167 if fname
and not fname
.isspace() and fname
not in ret
:
168 ret
.add(fname
.strip())
173 def not_check(root
, cmd
):
174 """Return a function which returns True if a file given as an argument
175 should be excluded from the check named by 'cmd'"""
177 ignorefiles
= filter(os
.path
.exists
,
178 [os
.path
.join(root
, ".git", "%s.NOT" % cmd
),
179 os
.path
.join(root
, "exception_lists", cmd
)])
180 if len(ignorefiles
) > 0:
181 return ignore
.ignore(root
, ignorefiles
, sys
.stderr
.write
)
183 return lambda x
: False
186 def gen_files(root
, parent
, paths
, exclude
):
187 """Return a function producing file names, relative to the current
188 directory, of any file changed on this branch (limited to 'paths' if
189 requested), and excluding files for which exclude returns a true value """
191 # Taken entirely from Python 2.6's os.path.relpath which we would use if we
193 def relpath(path
, here
):
194 c
= os
.path
.abspath(os
.path
.join(root
, path
)).split(os
.path
.sep
)
195 s
= os
.path
.abspath(here
).split(os
.path
.sep
)
196 l
= len(os
.path
.commonprefix((s
, c
)))
197 return os
.path
.join(*[os
.path
.pardir
] * (len(s
)-l
) + c
[l
:])
199 def ret(select
=None):
201 select
= lambda x
: True
203 for f
in git_file_list(parent
, paths
):
205 if (os
.path
.exists(f
) and select(f
) and not exclude(f
)):
210 def comchk(root
, parent
, flist
, output
):
211 output
.write("Comments:\n")
213 return Comments
.comchk(git_comments(parent
), check_db
=True,
217 def mapfilechk(root
, parent
, flist
, output
):
220 # We are interested in examining any file that has the following
221 # in its final path segment:
222 # - Contains the word 'mapfile'
223 # - Begins with 'map.'
225 # We don't want to match unless these things occur in final path segment
226 # because directory names with these strings don't indicate a mapfile.
227 # We also ignore files with suffixes that tell us that the files
229 MapfileRE
= re
.compile(r
'.*((mapfile[^/]*)|(/map\.+[^/]*)|(\.map))$',
231 NotMapSuffixRE
= re
.compile(r
'.*\.[ch]$', re
.IGNORECASE
)
233 output
.write("Mapfile comments:\n")
235 for f
in flist(lambda x
: MapfileRE
.match(x
) and not
236 NotMapSuffixRE
.match(x
)):
238 ret |
= Mapfile
.mapfilechk(fh
, output
=output
)
243 def copyright(root
, parent
, flist
, output
):
245 output
.write("Copyrights:\n")
248 ret |
= Copyright
.copyright(fh
, output
=output
)
253 def hdrchk(root
, parent
, flist
, output
):
255 output
.write("Header format:\n")
256 for f
in flist(lambda x
: x
.endswith('.h')):
258 ret |
= HdrChk
.hdrchk(fh
, lenient
=True, output
=output
)
263 def cstyle(root
, parent
, flist
, output
):
265 output
.write("C style:\n")
266 for f
in flist(lambda x
: x
.endswith('.c') or x
.endswith('.h')):
268 ret |
= CStyle
.cstyle(fh
, output
=output
, picky
=True,
269 check_posix_types
=True,
270 check_continuation
=True)
275 def jstyle(root
, parent
, flist
, output
):
277 output
.write("Java style:\n")
278 for f
in flist(lambda x
: x
.endswith('.java')):
280 ret |
= JStyle
.jstyle(fh
, output
=output
, picky
=True)
285 def keywords(root
, parent
, flist
, output
):
287 output
.write("SCCS Keywords:\n")
290 ret |
= Keywords
.keywords(fh
, output
=output
)
295 def run_checks(root
, parent
, cmds
, paths
='', opts
={}):
296 """Run the checks given in 'cmds', expected to have well-known signatures,
297 and report results for any which fail.
299 Return failure if any of them did.
301 NB: the function name of the commands passed in is used to name the NOT
302 file which excepts files from them."""
309 exclude
= not_check(root
, cmd
.func_name
)
310 result
= cmd(root
, parent
, gen_files(root
, parent
, paths
, exclude
),
320 def nits(root
, parent
, paths
):
327 run_checks(root
, parent
, cmds
, paths
)
330 def pbchk(root
, parent
, paths
):
338 run_checks(root
, parent
, cmds
)
345 opts
, args
= getopt
.getopt(args
, 'b:')
346 except getopt
.GetoptError
, e
:
347 sys
.stderr
.write(str(e
) + '\n')
348 sys
.stderr
.write("Usage: %s [-b branch] [path...]\n" % cmd
)
351 for opt
, arg
in opts
:
355 if not parent_branch
:
356 parent_branch
= git_parent_branch(git_branch())
359 if cmd
== 'git-pbchk':
362 sys
.stderr
.write("only complete workspaces may be pbchk'd\n");
365 func(git_root(), parent_branch
, args
)
367 if __name__
== '__main__':
369 main(os
.path
.basename(sys
.argv
[0]), sys
.argv
[1:])
371 sys
.stderr
.write("failed to run git:\n %s\n" % str(e
))