1#!/usr/bin/env python3 2 3import os 4from os.path import join, splitext 5 6from trailing_space_clean_config import PATHS 7 8SOURCE_EXT = ( 9 # C/C++ 10 ".c", ".h", ".cpp", ".hpp", ".cc", ".hh", ".cxx", ".hxx", ".inl", 11 # Objective C 12 ".m", ".mm", 13 # GLSL 14 ".glsl", 15 # Python 16 ".py", 17 # Text (also CMake) 18 ".txt", ".cmake", ".rst", 19) 20 21 22def is_source(filename): 23 return filename.endswith(SOURCE_EXT) 24 25 26def path_iter(path, filename_check=None): 27 for dirpath, dirnames, filenames in os.walk(path): 28 # skip ".git" 29 dirnames[:] = [d for d in dirnames if not d.startswith(".")] 30 31 for filename in filenames: 32 if filename.startswith("."): 33 continue 34 filepath = join(dirpath, filename) 35 if filename_check is None or filename_check(filepath): 36 yield filepath 37 38 39def path_expand(paths, filename_check=None): 40 for f in paths: 41 if not os.path.exists(f): 42 print("Missing:", f) 43 elif os.path.isdir(f): 44 yield from path_iter(f, filename_check) 45 else: 46 yield f 47 48 49def rstrip_file(filename): 50 with open(filename, "r", encoding="utf-8") as fh: 51 data_src = fh.read() 52 53 data_dst = [] 54 for l in data_src.rstrip().splitlines(True): 55 data_dst.append(l.rstrip() + "\n") 56 57 data_dst = "".join(data_dst) 58 len_strip = len(data_src) - len(data_dst) 59 if len_strip != 0: 60 with open(filename, "w", encoding="utf-8") as fh: 61 fh.write(data_dst) 62 return len_strip 63 64 65def main(): 66 for f in path_expand(PATHS, is_source): 67 len_strip = rstrip_file(f) 68 if len_strip != 0: 69 print(f"Strip ({len_strip}): {f}") 70 71 72if __name__ == "__main__": 73 main() 74