1#!/usr/bin/env python 2 3""" 4Scans each resource file in res/ applying various transformations 5to fix invalid resource files. 6""" 7 8import os 9import os.path 10import sys 11import tempfile 12 13from consumers.duplicates import DuplicateRemover 14from consumers.positional_arguments import PositionalArgumentFixer 15 16def do_it(res_path, consumers): 17 for file_path in enumerate_files(res_path): 18 eligible_consumers = filter(lambda c: c.matches(file_path), consumers) 19 if len(eligible_consumers) > 0: 20 print "checking {0} ...".format(file_path) 21 22 original_contents = read_contents(file_path) 23 contents = original_contents 24 for c in eligible_consumers: 25 contents = c.consume(file_path, contents) 26 if original_contents != contents: 27 write_contents(file_path, contents) 28 29def enumerate_files(res_path): 30 """Enumerates all files in the resource directory.""" 31 values_directories = os.listdir(res_path) 32 values_directories = map(lambda f: os.path.join(res_path, f), values_directories) 33 all_files = [] 34 for dir in values_directories: 35 files = os.listdir(dir) 36 files = map(lambda f: os.path.join(dir, f), files) 37 for f in files: 38 yield f 39 40def read_contents(file_path): 41 """Reads the contents of file_path without decoding.""" 42 with open(file_path) as fin: 43 return fin.read() 44 45def write_contents(file_path, contents): 46 """Writes the bytes in contents to file_path by first writing to a temporary, then 47 renaming the temporary to file_path, ensuring a consistent write. 48 """ 49 dirname, basename = os.path.split(file_path) 50 temp_name = "" 51 with tempfile.NamedTemporaryFile(prefix=basename, dir=dirname, delete=False) as temp: 52 temp_name = temp.name 53 temp.write(contents) 54 os.rename(temp.name, file_path) 55 56if __name__ == '__main__': 57 if len(sys.argv) < 2: 58 print >> sys.stderr, "please specify a path to a resource directory" 59 sys.exit(1) 60 61 res_path = os.path.abspath(sys.argv[1]) 62 print "looking in {0} ...".format(res_path) 63 do_it(res_path, [DuplicateRemover(), PositionalArgumentFixer()]) 64