· 7 years ago · Oct 01, 2018, 03:22 PM
1# -*- coding: UTF-8 -*-
2'''
3format source code
4normalize newline token, remove space at end of line and expand tabs
5wrote in python 3k
6
7@Author: bitdewy (bitdewy (at) gmail.com)
8'''
9
10import locale, os, re, stat
11
12unix = '\n'
13mac = '\r'
14dos = '\r\n'
15ts = 2
16cpp = '.*\\.(h|hpp|c|cc|cpp)$'
17
18def main(path = '.', tabsize = ts, newline = unix, regex = cpp):
19 def format_file(filename, tabsize, newline):
20 encoding = locale.getpreferredencoding()
21 try:
22 f = open(filename, 'r+', 1, encoding, 'strict', newline)
23 except IOError:
24 raise
25 content = ''
26 try:
27 for line in f:
28 content += line.expandtabs(tabsize).rstrip() + newline
29 except ValueError:
30 f.close()
31 raise
32 f.truncate(0)
33 f.seek(0)
34 f.write(content)
35 f.close()
36
37 for item in os.listdir(path):
38 pathname = os.path.join(path, item)
39 mode = os.stat(pathname).st_mode
40 if stat.S_ISDIR(mode):
41 main(pathname)
42 elif stat.S_ISREG(mode) and re.match(regex, pathname):
43 try:
44 format_file(pathname, tabsize, newline)
45 except Exception as err:
46 print('format file error: {0} {1}'.format(pathname, err))
47 else:
48 print('file: {0} not match'.format(pathname))
49
50if __name__ == '__main__':
51 main()