File: check_trailing_whitespaces.py

package info (click to toggle)
corsix-th 0.62-2
  • links: PTS, VCS
  • area: contrib
  • in suites: buster
  • size: 16,012 kB
  • sloc: cpp: 19,118; java: 8,419; ansic: 3,531; objc: 248; python: 210; lex: 82; yacc: 44; makefile: 26; xml: 26; sh: 14
file content (46 lines) | stat: -rwxr-xr-x 1,260 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/python

"""
  Usage: check_trailing_whitespaces.py [root]
  This script will check the presence of trailing whitespaces in any file
  below |root|. It will return 0 if none is found. Otherwise, it will print the
  path of the violating file and return an error code.
  If root is not specified, it will use the current directory.
"""

import fileinput
import os
import re
import sys

def has_trailing_whitespaces(path):
  """ Returns whether |path| has trailing whitespaces. """
  handle = open(path, 'r')
  for line in handle:
    for idx in range(-1, -len(line) - 1, -1):
      if line[idx] in ('\n', '\r'):
        continue
      if line[idx] in (' ', '\t'):
        handle.close()
        return True
      break
  handle.close()
  return False

if (len(sys.argv) > 2):
  sys.exit('Usage: ' + sys.argv[0] + ' [root]')

top = os.getcwd()
if len(sys.argv) == 2:
  top += '/' + sys.argv[1]

for root, dirs, files in os.walk(top):
  for f in files:
    if f.endswith('.py') or f.endswith('.lua') or f.endswith('.h') or \
       f.endswith('.cpp') or f.endswith('.cc') or f.endswith('.c'):
         path = root + '/' + f
         if has_trailing_whitespaces(path):
           sys.exit('Found a file with trailing whitespaces: ' + path)

sys.exit(0)