summaryrefslogtreecommitdiff
path: root/utils/lint/common_lint.py
blob: e08c93cb17011337d0a33a7224a2b7be4d2d52cf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#!/usr/bin/python
#
# Common lint functions applicable to multiple types of files.

import re

def VerifyLineLength(filename, lines, max_length):
  """Checkes to make sure the file has no lines with lines exceeding the length
  limit.

  Args:
    filename: the file under consideration as string
    lines: contents of the file as string array
    max_length: maximum acceptable line length as number
  """
  line_num = 1
  for line in lines:
    length = len(line.rstrip('\n'))
    if length > max_length:
      print '%s:%d:Line exceeds %d chars (%d)' % (filename, line_num,
                                                  max_length, length)
    line_num += 1


def VerifyTrailingWhitespace(filename, lines):
  """Checkes to make sure the file has no lines with trailing whitespace.

  Args:
    filename: the file under consideration as string
    lines: contents of the file as string array
  """
  trailing_whitespace_re = re.compile(r'\s+$')
  line_num = 1
  for line in lines:
    if trailing_whitespace_re.match(line.rstrip('\n')):
      print '%s:%d:Trailing whitespace' % (filename, line_num)
    line_num += 1


class BaseLint:
  def RunOnFile(filename, lines):
    raise Exception('RunOnFile() unimplemented')


def RunLintOverAllFiles(lint, filenames):
  """Runs linter over the contents of all files.

  Args:
    lint: subclass of BaseLint, implementing RunOnFile()
    filenames: list of all files whose contents will be linted
  """
  for filename in filenames:
    file = open(filename, 'r')
    if not file:
      print 'Cound not open %s' % filename
      continue
    lines = file.readlines()
    lint.RunOnFile(filename, lines)