style.py revision 8326:8b0eee09deaf
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 = 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 Verifier(object): 118 def __init__(self, ui, repo=None): 119 self.ui = ui 120 self.repo = repo 121 if repo is None: 122 self.wctx = None 123 124 def __getattr__(self, attr): 125 if attr in ('prompt', 'write'): 126 return getattr(self.ui, attr) 127 128 if attr == 'wctx': 129 try: 130 wctx = repo.workingctx() 131 except: 132 from mercurial import context 133 wctx = context.workingctx(repo) 134 self.wctx = wctx 135 return wctx 136 137 raise AttributeError 138 139 def open(self, filename, mode): 140 if self.repo: 141 filename = self.repo.wjoin(filename) 142 143 try: 144 f = file(filename, mode) 145 except OSError, msg: 146 print 'could not open file %s: %s' % (filename, msg) 147 return None 148 149 return f 150 151 def skip(self, filename): 152 return lang_type(filename) not in self.languages 153 154 def check(self, filename, regions=all_regions): 155 f = self.open(filename, 'r') 156 157 errors = 0 158 for num,line in enumerate(f): 159 if num not in regions: 160 continue 161 if not self.check_line(line): 162 self.write("invalid %s in %s:%d\n" % \ 163 (self.test_name, filename, num + 1)) 164 if self.ui.verbose: 165 self.write(">>%s<<\n" % line[-1]) 166 errors += 1 167 return errors 168 169 def fix(self, filename, regions=all_regions): 170 f = self.open(filename, 'r+') 171 172 lines = list(f) 173 174 f.seek(0) 175 f.truncate() 176 177 for i,line in enumerate(lines): 178 if i in regions: 179 line = self.fix_line(line) 180 181 f.write(line) 182 f.close() 183 184 def apply(self, filename, prompt, regions=all_regions): 185 if not self.skip(filename): 186 errors = self.check(filename, regions) 187 if errors: 188 if prompt(filename, self.fix, regions): 189 return True 190 return False 191 192 193class Whitespace(Verifier): 194 languages = set(('C', 'C++', 'swig', 'python', 'asm', 'isa', 'scons')) 195 test_name = 'whitespace' 196 def check_line(self, line): 197 match = lead.search(line) 198 if match and match.group(1).find('\t') != -1: 199 return False 200 201 match = trail.search(line) 202 if match: 203 return False 204 205 return True 206 207 def fix_line(self, line): 208 if lead.search(line): 209 newline = '' 210 for i,c in enumerate(line): 211 if c == ' ': 212 newline += ' ' 213 elif c == '\t': 214 newline += ' ' * (tabsize - len(newline) % tabsize) 215 else: 216 newline += line[i:] 217 break 218 219 line = newline 220 221 return line.rstrip() + '\n' 222 223class SortedIncludes(Verifier): 224 languages = sort_includes.default_languages 225 def __init__(self, *args, **kwargs): 226 super(SortedIncludes, self).__init__(*args, **kwargs) 227 self.sort_includes = sort_includes.SortIncludes() 228 229 def check(self, filename, regions=all_regions): 230 f = self.open(filename, 'r') 231 232 lines = [ l.rstrip('\n') for l in f.xreadlines() ] 233 old = ''.join(line + '\n' for line in lines) 234 f.close() 235 236 language = lang_type(filename, lines[0]) 237 sort_lines = list(self.sort_includes(lines, filename, language)) 238 new = ''.join(line + '\n' for line in sort_lines) 239 240 mod = modified_regions(old, new) 241 modified = mod & regions 242 243 if modified: 244 self.write("invalid sorting of includes\n") 245 if self.ui.verbose: 246 for start, end in modified.regions: 247 self.write("bad region [%d, %d)\n" % (start, end)) 248 return 1 249 250 return 0 251 252 def fix(self, filename, regions=all_regions): 253 f = self.open(filename, 'r+') 254 255 old = f.readlines() 256 lines = [ l.rstrip('\n') for l in old ] 257 language = lang_type(filename, lines[0]) 258 sort_lines = list(self.sort_includes(lines, filename, language)) 259 new = ''.join(line + '\n' for line in sort_lines) 260 261 f.seek(0) 262 f.truncate() 263 264 for i,line in enumerate(sort_lines): 265 f.write(line) 266 f.write('\n') 267 f.close() 268 269def linelen(line): 270 tabs = line.count('\t') 271 if not tabs: 272 return len(line) 273 274 count = 0 275 for c in line: 276 if c == '\t': 277 count += tabsize - count % tabsize 278 else: 279 count += 1 280 281 return count 282 283class ValidationStats(object): 284 def __init__(self): 285 self.toolong = 0 286 self.toolong80 = 0 287 self.leadtabs = 0 288 self.trailwhite = 0 289 self.badcontrol = 0 290 self.cret = 0 291 292 def dump(self): 293 print '''\ 294%d violations of lines over 79 chars. %d of which are 80 chars exactly. 295%d cases of whitespace at the end of a line. 296%d cases of tabs to indent. 297%d bad parens after if/while/for. 298%d carriage returns found. 299''' % (self.toolong, self.toolong80, self.trailwhite, self.leadtabs, 300 self.badcontrol, self.cret) 301 302 def __nonzero__(self): 303 return self.toolong or self.toolong80 or self.leadtabs or \ 304 self.trailwhite or self.badcontrol or self.cret 305 306def validate(filename, stats, verbose, exit_code): 307 if lang_type(filename) not in format_types: 308 return 309 310 def msg(lineno, line, message): 311 print '%s:%d>' % (filename, lineno + 1), message 312 if verbose > 2: 313 print line 314 315 def bad(): 316 if exit_code is not None: 317 sys.exit(exit_code) 318 319 try: 320 f = file(filename, 'r') 321 except OSError: 322 if verbose > 0: 323 print 'could not open file %s' % filename 324 bad() 325 return 326 327 for i,line in enumerate(f): 328 line = line.rstrip('\n') 329 330 # no carriage returns 331 if line.find('\r') != -1: 332 self.cret += 1 333 if verbose > 1: 334 msg(i, line, 'carriage return found') 335 bad() 336 337 # lines max out at 79 chars 338 llen = linelen(line) 339 if llen > 79: 340 stats.toolong += 1 341 if llen == 80: 342 stats.toolong80 += 1 343 if verbose > 1: 344 msg(i, line, 'line too long (%d chars)' % llen) 345 bad() 346 347 # no tabs used to indent 348 match = lead.search(line) 349 if match and match.group(1).find('\t') != -1: 350 stats.leadtabs += 1 351 if verbose > 1: 352 msg(i, line, 'using tabs to indent') 353 bad() 354 355 # no trailing whitespace 356 if trail.search(line): 357 stats.trailwhite +=1 358 if verbose > 1: 359 msg(i, line, 'trailing whitespace') 360 bad() 361 362 # for c++, exactly one space betwen if/while/for and ( 363 if cpp: 364 match = any_control.search(line) 365 if match and not good_control.search(line): 366 stats.badcontrol += 1 367 if verbose > 1: 368 msg(i, line, 'improper spacing after %s' % match.group(1)) 369 bad() 370 371def do_check_style(hgui, repo, *files, **args): 372 """check files for proper m5 style guidelines""" 373 from mercurial import mdiff, util 374 375 auto = args.get('auto', False) 376 if auto: 377 auto = 'f' 378 ui = MercurialUI(hgui, hgui.verbose, auto) 379 380 if files: 381 files = frozenset(files) 382 383 def skip(name): 384 return files and name in files 385 386 def prompt(name, func, regions=all_regions): 387 result = ui.prompt("(a)bort, (i)gnore, or (f)ix?", 'aif', 'a') 388 if result == 'a': 389 return True 390 elif result == 'f': 391 func(repo.wjoin(name), regions) 392 393 return False 394 395 modified, added, removed, deleted, unknown, ignore, clean = repo.status() 396 397 whitespace = Whitespace(ui) 398 sorted_includes = SortedIncludes(ui) 399 for fname in added: 400 if skip(fname): 401 continue 402 403 fpath = joinpath(repo.root, fname) 404 405 if whitespace.apply(fpath, prompt): 406 return True 407 408 if sorted_includes.apply(fpath, prompt): 409 return True 410 411 try: 412 wctx = repo.workingctx() 413 except: 414 from mercurial import context 415 wctx = context.workingctx(repo) 416 417 for fname in modified: 418 if skip(fname): 419 continue 420 421 fpath = joinpath(repo.root, fname) 422 regions = modregions(wctx, fname) 423 424 if whitespace.apply(fpath, prompt, regions): 425 return True 426 427 if sorted_includes.apply(fpath, prompt, regions): 428 return True 429 430 return False 431 432def do_check_format(hgui, repo, **args): 433 ui = MercurialUI(hgui, hgui.verbose, auto) 434 435 modified, added, removed, deleted, unknown, ignore, clean = repo.status() 436 437 verbose = 0 438 stats = ValidationStats() 439 for f in modified + added: 440 validate(joinpath(repo.root, f), stats, verbose, None) 441 442 if stats: 443 stats.dump() 444 result = ui.prompt("invalid formatting\n(i)gnore or (a)bort?", 445 'ai', 'a') 446 if result == 'a': 447 return True 448 449 return False 450 451def check_hook(hooktype): 452 if hooktype not in ('pretxncommit', 'pre-qrefresh'): 453 raise AttributeError, \ 454 "This hook is not meant for %s" % hooktype 455 456def check_style(ui, repo, hooktype, **kwargs): 457 check_hook(hooktype) 458 args = {} 459 460 try: 461 return do_check_style(ui, repo, **args) 462 except Exception, e: 463 import traceback 464 traceback.print_exc() 465 return True 466 467def check_format(ui, repo, hooktype, **kwargs): 468 check_hook(hooktype) 469 args = {} 470 471 try: 472 return do_check_format(ui, repo, **args) 473 except Exception, e: 474 import traceback 475 traceback.print_exc() 476 return True 477 478try: 479 from mercurial.i18n import _ 480except ImportError: 481 def _(arg): 482 return arg 483 484cmdtable = { 485 '^m5style' : 486 ( do_check_style, 487 [ ('a', 'auto', False, _("automatically fix whitespace")) ], 488 _('hg m5style [-a] [FILE]...')), 489 '^m5format' : 490 ( do_check_format, 491 [ ], 492 _('hg m5format [FILE]...')), 493} 494 495if __name__ == '__main__': 496 import getopt 497 498 progname = sys.argv[0] 499 if len(sys.argv) < 2: 500 sys.exit('usage: %s <command> [<command args>]' % progname) 501 502 fixwhite_usage = '%s fixwhite [-t <tabsize> ] <path> [...] \n' % progname 503 chkformat_usage = '%s chkformat <path> [...] \n' % progname 504 chkwhite_usage = '%s chkwhite <path> [...] \n' % progname 505 506 command = sys.argv[1] 507 if command == 'fixwhite': 508 flags = 't:' 509 usage = fixwhite_usage 510 elif command == 'chkwhite': 511 flags = 'nv' 512 usage = chkwhite_usage 513 elif command == 'chkformat': 514 flags = 'nv' 515 usage = chkformat_usage 516 else: 517 sys.exit(fixwhite_usage + chkwhite_usage + chkformat_usage) 518 519 opts, args = getopt.getopt(sys.argv[2:], flags) 520 521 code = 1 522 verbose = 1 523 for opt,arg in opts: 524 if opt == '-n': 525 code = None 526 if opt == '-t': 527 tabsize = int(arg) 528 if opt == '-v': 529 verbose += 1 530 531 if command == 'fixwhite': 532 for filename in args: 533 fixwhite(filename, tabsize) 534 elif command == 'chkwhite': 535 for filename in args: 536 for line,num in checkwhite(filename): 537 print 'invalid whitespace: %s:%d' % (filename, num) 538 if verbose: 539 print '>>%s<<' % line[:-1] 540 elif command == 'chkformat': 541 stats = ValidationStats() 542 for filename in args: 543 validate(filename, stats=stats, verbose=verbose, exit_code=code) 544 545 if verbose > 0: 546 stats.dump() 547 else: 548 sys.exit("command '%s' not found" % command) 549