Created
April 21, 2012 11:33
-
-
Save bitdewy/2436711 to your computer and use it in GitHub Desktop.
format src, mormalize new line token, remove space at end of line and expand tabs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: UTF-8 -*- | |
''' | |
format source code | |
normalize newline token, remove space at end of line and expand tabs | |
wrote in python 3k | |
@Author: bitdewy (bitdewy (at) gmail.com) | |
''' | |
import locale, os, re, stat | |
unix = '\n' | |
mac = '\r' | |
dos = '\r\n' | |
ts = 2 | |
cpp = '.*\\.(h|hpp|c|cc|cpp)$' | |
def main(path = '.', tabsize = ts, newline = unix, regex = cpp): | |
def format_file(filename, tabsize, newline): | |
encoding = locale.getpreferredencoding() | |
try: | |
f = open(filename, 'r+', 1, encoding, 'strict', newline) | |
except IOError: | |
raise | |
content = '' | |
try: | |
for line in f: | |
content += line.expandtabs(tabsize).rstrip() + newline | |
except ValueError: | |
f.close() | |
raise | |
f.truncate(0) | |
f.seek(0) | |
f.write(content) | |
f.close() | |
for item in os.listdir(path): | |
pathname = os.path.join(path, item) | |
mode = os.stat(pathname).st_mode | |
if stat.S_ISDIR(mode): | |
main(pathname) | |
elif stat.S_ISREG(mode) and re.match(regex, pathname): | |
try: | |
format_file(pathname, tabsize, newline) | |
except Exception as err: | |
print('format file error: {0} {1}'.format(pathname, err)) | |
else: | |
print('file: {0} not match'.format(pathname)) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment