style.py revision 8237:b83e07b4541d
1#! /usr/bin/env python
2# Copyright (c) 2006 The Regents of The University of Michigan
3# Copyright (c) 2007,2011 The Hewlett-Packard Development Company
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met: redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer;
10# redistributions in binary form must reproduce the above copyright
11# notice, this list of conditions and the following disclaimer in the
12# documentation and/or other materials provided with the distribution;
13# neither the name of the copyright holders nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28#
29# Authors: Nathan Binkert
30
31import heapq
32import os
33import re
34import sys
35
36from os.path import dirname, join as joinpath
37from itertools import count
38from mercurial import bdiff, mdiff
39
40current_dir = dirname(__file__)
41sys.path.insert(0, current_dir)
42sys.path.insert(1, joinpath(dirname(current_dir), 'src', 'python'))
43
44from m5.util import neg_inf, pos_inf, Region, Regions
45import sort_includes
46from file_types import lang_type
47
48all_regions = Region(neg_inf, pos_inf)
49
50tabsize = 8
51lead = re.compile(r'^([ \t]+)')
52trail = re.compile(r'([ \t]+)$')
53any_control = re.compile(r'\b(if|while|for)[ \t]*[(]')
54good_control = re.compile(r'\b(if|while|for) [(]')
55
56format_types = set(('C', 'C++'))
57
58def modified_regions(old_data, new_data):
59    regions = Regions()
60    beg = None
61    for pbeg, pend, fbeg, fend in bdiff.blocks(old_data, new_data):
62        if beg is not None and beg != fbeg:
63            regions.append(beg, fbeg)
64        beg = fend
65    return regions
66
67def modregions(wctx, fname):
68    fctx = wctx.filectx(fname)
69    pctx = fctx.parents()
70
71    file_data = fctx.data()
72    lines = mdiff.splitnewlines(file_data)
73    if len(pctx) in (1, 2):
74        mod_regions = modified_regions(pctx[0].data(), file_data)
75        if len(pctx) == 2:
76            m2 = modified_regions(pctx[1].data(), file_data)
77            # only the lines that are new in both
78            mod_regions &= m2
79    else:
80        mod_regions = Regions()
81        mod_regions.add(0, len(lines))
82
83    return mod_regions
84
85class UserInterface(object):
86    def __init__(self, verbose=False, auto=False):
87        self.auto = auto
88        self.verbose = verbose
89
90    def prompt(self, prompt, results, default):
91        if self.auto:
92            return self.auto
93
94        while True:
95            result = self.do_prompt(prompt, results, default)
96            if result in results:
97                return result
98
99class MercurialUI(UserInterface):
100    def __init__(self, ui, *args, **kwargs):
101        super(MercurialUI, self).__init__(*args, **kwargs)
102        self.ui = ui
103
104    def do_prompt(self, prompt, results, default):
105        return self.ui.prompt(prompt, default=default)
106
107    def write(self, string):
108        self.ui.write(string)
109
110class StdioUI(UserInterface):
111    def do_prompt(self, prompt, results, default):
112        return raw_input(prompt) or default
113
114    def write(self, string):
115        sys.stdout.write(string)
116
117class Region(object):
118    def __init__(self, asdf):
119        self.regions = Foo
120
121class Verifier(object):
122    def __init__(self, ui, repo=None):
123        self.ui = ui
124        self.repo = repo
125        if repo is None:
126            self.wctx = None
127
128    def __getattr__(self, attr):
129        if attr in ('prompt', 'write'):
130            return getattr(self.ui, attr)
131
132        if attr == 'wctx':
133            try:
134                wctx = repo.workingctx()
135            except:
136                from mercurial import context
137                wctx = context.workingctx(repo)
138            self.wctx = wctx
139            return wctx
140
141        raise AttributeError
142
143    def open(self, filename, mode):
144        if self.repo:
145            filename = self.repo.wjoin(filename)
146
147        try:
148            f = file(filename, mode)
149        except OSError, msg:
150            print 'could not open file %s: %s' % (filename, msg)
151            return None
152
153        return f
154
155    def skip(self, filename):
156        return lang_type(filename) not in self.languages
157
158    def check(self, filename, regions=all_regions):
159        f = self.open(filename, 'r')
160
161        errors = 0
162        for num,line in enumerate(f):
163            if num not in regions:
164                continue
165            if not self.check_line(line):
166                self.write("invalid %s in %s:%d\n" % \
167                               (self.test_name, filename, num + 1))
168                if self.ui.verbose:
169                    self.write(">>%s<<\n" % line[-1])
170                errors += 1
171        return errors
172
173    def fix(self, filename, regions=all_regions):
174        f = self.open(filename, 'r+')
175
176        lines = list(f)
177
178        f.seek(0)
179        f.truncate()
180
181        for i,line in enumerate(lines):
182            if i in regions:
183                line = self.fix_line(line)
184
185            f.write(line)
186        f.close()
187
188    def apply(self, filename, prompt, regions=all_regions):
189        if not self.skip(filename):
190            errors = self.check(filename, regions)
191            if errors:
192                if prompt(filename, self.fix, regions):
193                    return True
194        return False
195
196
197class Whitespace(Verifier):
198    languages = set(('C', 'C++', 'swig', 'python', 'asm', 'isa', 'scons'))
199    test_name = 'whitespace'
200    def check_line(self, line):
201        match = lead.search(line)
202        if match and match.group(1).find('\t') != -1:
203            return False
204
205        match = trail.search(line)
206        if match:
207            return False
208
209        return True
210
211    def fix_line(self, line):
212        if lead.search(line):
213            newline = ''
214            for i,c in enumerate(line):
215                if c == ' ':
216                    newline += ' '
217                elif c == '\t':
218                    newline += ' ' * (tabsize - len(newline) % tabsize)
219                else:
220                    newline += line[i:]
221                    break
222
223            line = newline
224
225        return line.rstrip() + '\n'
226
227class SortedIncludes(Verifier):
228    languages = sort_includes.default_languages
229    def __init__(self, *args, **kwargs):
230        super(SortedIncludes, self).__init__(*args, **kwargs)
231        self.sort_includes = sort_includes.SortIncludes()
232
233    def check(self, filename, regions=all_regions):
234        f = self.open(filename, 'r')
235
236        lines = [ l.rstrip('\n') for l in f.xreadlines() ]
237        old = ''.join(line + '\n' for line in lines)
238        f.close()
239
240        language = lang_type(filename, lines[0])
241        sort_lines = list(self.sort_includes(lines, filename, language))
242        new = ''.join(line + '\n' for line in sort_lines)
243
244        mod = modified_regions(old, new)
245        modified = mod & regions
246
247        if modified:
248            self.write("invalid sorting of includes\n")
249            if self.ui.verbose:
250                for start, end in modified.regions:
251                    self.write("bad region [%d, %d)\n" % (start, end))
252            return 1
253
254        return 0
255
256    def fix(self, filename, regions=all_regions):
257        f = self.open(filename, 'r+')
258
259        old = f.readlines()
260        lines = [ l.rstrip('\n') for l in old ]
261        language = lang_type(filename, lines[0])
262        sort_lines = list(self.sort_includes(lines, filename, language))
263        new = ''.join(line + '\n' for line in sort_lines)
264
265        f.seek(0)
266        f.truncate()
267
268        for i,line in enumerate(sort_lines):
269            f.write(line)
270            f.write('\n')
271        f.close()
272
273def linelen(line):
274    tabs = line.count('\t')
275    if not tabs:
276        return len(line)
277
278    count = 0
279    for c in line:
280        if c == '\t':
281            count += tabsize - count % tabsize
282        else:
283            count += 1
284
285    return count
286
287class ValidationStats(object):
288    def __init__(self):
289        self.toolong = 0
290        self.toolong80 = 0
291        self.leadtabs = 0
292        self.trailwhite = 0
293        self.badcontrol = 0
294        self.cret = 0
295
296    def dump(self):
297        print '''\
298%d violations of lines over 79 chars. %d of which are 80 chars exactly.
299%d cases of whitespace at the end of a line.
300%d cases of tabs to indent.
301%d bad parens after if/while/for.
302%d carriage returns found.
303''' % (self.toolong, self.toolong80, self.trailwhite, self.leadtabs,
304       self.badcontrol, self.cret)
305
306    def __nonzero__(self):
307        return self.toolong or self.toolong80 or self.leadtabs or \
308               self.trailwhite or self.badcontrol or self.cret
309
310def validate(filename, stats, verbose, exit_code):
311    if lang_type(filename) not in format_types:
312        return
313
314    def msg(lineno, line, message):
315        print '%s:%d>' % (filename, lineno + 1), message
316        if verbose > 2:
317            print line
318
319    def bad():
320        if exit_code is not None:
321            sys.exit(exit_code)
322
323    try:
324        f = file(filename, 'r')
325    except OSError:
326        if verbose > 0:
327            print 'could not open file %s' % filename
328        bad()
329        return
330
331    for i,line in enumerate(f):
332        line = line.rstrip('\n')
333
334        # no carriage returns
335        if line.find('\r') != -1:
336            self.cret += 1
337            if verbose > 1:
338                msg(i, line, 'carriage return found')
339            bad()
340
341        # lines max out at 79 chars
342        llen = linelen(line)
343        if llen > 79:
344            stats.toolong += 1
345            if llen == 80:
346                stats.toolong80 += 1
347            if verbose > 1:
348                msg(i, line, 'line too long (%d chars)' % llen)
349            bad()
350
351        # no tabs used to indent
352        match = lead.search(line)
353        if match and match.group(1).find('\t') != -1:
354            stats.leadtabs += 1
355            if verbose > 1:
356                msg(i, line, 'using tabs to indent')
357            bad()
358
359        # no trailing whitespace
360        if trail.search(line):
361            stats.trailwhite +=1
362            if verbose > 1:
363                msg(i, line, 'trailing whitespace')
364            bad()
365
366        # for c++, exactly one space betwen if/while/for and (
367        if cpp:
368            match = any_control.search(line)
369            if match and not good_control.search(line):
370                stats.badcontrol += 1
371                if verbose > 1:
372                    msg(i, line, 'improper spacing after %s' % match.group(1))
373                bad()
374
375def do_check_style(hgui, repo, *files, **args):
376    """check files for proper m5 style guidelines"""
377    from mercurial import mdiff, util
378
379    auto = args.get('auto', False)
380    if auto:
381        auto = 'f'
382    ui = MercurialUI(hgui, hgui.verbose, auto)
383
384    if files:
385        files = frozenset(files)
386
387    def skip(name):
388        return files and name in files
389
390    def prompt(name, func, regions=all_regions):
391        result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", 'aif', 'a')
392        if result == 'a':
393            return True
394        elif result == 'f':
395            func(repo.wjoin(name), regions)
396
397        return False
398
399    modified, added, removed, deleted, unknown, ignore, clean = repo.status()
400
401    whitespace = Whitespace(ui)
402    sorted_includes = SortedIncludes(ui)
403    for fname in added:
404        if skip(fname):
405            continue
406
407        if whitespace.apply(fname, prompt):
408            return True
409
410        if sorted_includes.apply(fname, prompt):
411            return True
412
413    try:
414        wctx = repo.workingctx()
415    except:
416        from mercurial import context
417        wctx = context.workingctx(repo)
418
419    for fname in modified:
420        if skip(fname):
421            continue
422
423        regions = modregions(wctx, fname)
424
425        if whitespace.apply(fname, prompt, regions):
426            return True
427
428        if sorted_includes.apply(fname, prompt, regions):
429            return True
430
431    return False
432
433def do_check_format(hgui, repo, **args):
434    ui = MercurialUI(hgui, hgui.verbose, auto)
435
436    modified, added, removed, deleted, unknown, ignore, clean = repo.status()
437
438    verbose = 0
439    stats = ValidationStats()
440    for f in modified + added:
441        validate(f, stats, verbose, None)
442
443    if stats:
444        stats.dump()
445        result = ui.prompt("invalid formatting\n(i)gnore or (a)bort?",
446                           'ai', 'a')
447        if result == 'a':
448            return True
449
450    return False
451
452def check_hook(hooktype):
453    if hooktype not in ('pretxncommit', 'pre-qrefresh'):
454        raise AttributeError, \
455              "This hook is not meant for %s" % hooktype
456
457def check_style(ui, repo, hooktype, **kwargs):
458    check_hook(hooktype)
459    args = {}
460
461    try:
462        return do_check_style(ui, repo, **args)
463    except Exception, e:
464        import traceback
465        traceback.print_exc()
466        return True
467
468def check_format(ui, repo, hooktype, **kwargs):
469    check_hook(hooktype)
470    args = {}
471
472    try:
473        return do_check_format(ui, repo, **args)
474    except Exception, e:
475        import traceback
476        traceback.print_exc()
477        return True
478
479try:
480    from mercurial.i18n import _
481except ImportError:
482    def _(arg):
483        return arg
484
485cmdtable = {
486    '^m5style' :
487    ( do_check_style,
488      [ ('a', 'auto', False, _("automatically fix whitespace")) ],
489      _('hg m5style [-a] [FILE]...')),
490    '^m5format' :
491    ( do_check_format,
492      [ ],
493      _('hg m5format [FILE]...')),
494}
495
496if __name__ == '__main__':
497    import getopt
498
499    progname = sys.argv[0]
500    if len(sys.argv) < 2:
501        sys.exit('usage: %s <command> [<command args>]' % progname)
502
503    fixwhite_usage = '%s fixwhite [-t <tabsize> ] <path> [...] \n' % progname
504    chkformat_usage = '%s chkformat <path> [...] \n' % progname
505    chkwhite_usage = '%s chkwhite <path> [...] \n' % progname
506
507    command = sys.argv[1]
508    if command == 'fixwhite':
509        flags = 't:'
510        usage = fixwhite_usage
511    elif command == 'chkwhite':
512        flags = 'nv'
513        usage = chkwhite_usage
514    elif command == 'chkformat':
515        flags = 'nv'
516        usage = chkformat_usage
517    else:
518        sys.exit(fixwhite_usage + chkwhite_usage + chkformat_usage)
519
520    opts, args = getopt.getopt(sys.argv[2:], flags)
521
522    code = 1
523    verbose = 1
524    for opt,arg in opts:
525        if opt == '-n':
526            code = None
527        if opt == '-t':
528            tabsize = int(arg)
529        if opt == '-v':
530            verbose += 1
531
532    if command == 'fixwhite':
533        for filename in args:
534            fixwhite(filename, tabsize)
535    elif command == 'chkwhite':
536        for filename in args:
537            for line,num in checkwhite(filename):
538                print 'invalid whitespace: %s:%d' % (filename, num)
539                if verbose:
540                    print '>>%s<<' % line[:-1]
541    elif command == 'chkformat':
542        stats = ValidationStats()
543        for filename in args:
544            validate(filename, stats=stats, verbose=verbose, exit_code=code)
545
546        if verbose > 0:
547            stats.dump()
548    else:
549        sys.exit("command '%s' not found" % command)
550