1#!/usr/bin/env python2 2 3# This script replaces prefixes of files, and symbols in that file. 4# Useful for creating different versions of the codebase that don't 5# conflict at compile time. 6# 7# example: 8# $ ./scripts/prefix.py lfs2 9 10import os 11import os.path 12import re 13import glob 14import itertools 15import tempfile 16import shutil 17import subprocess 18 19DEFAULT_PREFIX = "lfs" 20 21def subn(from_prefix, to_prefix, name): 22 name, count1 = re.subn('\\b'+from_prefix, to_prefix, name) 23 name, count2 = re.subn('\\b'+from_prefix.upper(), to_prefix.upper(), name) 24 name, count3 = re.subn('\\B-D'+from_prefix.upper(), 25 '-D'+to_prefix.upper(), name) 26 return name, count1+count2+count3 27 28def main(from_prefix, to_prefix=None, files=None): 29 if not to_prefix: 30 from_prefix, to_prefix = DEFAULT_PREFIX, from_prefix 31 32 if not files: 33 files = subprocess.check_output([ 34 'git', 'ls-tree', '-r', '--name-only', 'HEAD']).split() 35 36 for oldname in files: 37 # Rename any matching file names 38 newname, namecount = subn(from_prefix, to_prefix, oldname) 39 if namecount: 40 subprocess.check_call(['git', 'mv', oldname, newname]) 41 42 # Rename any prefixes in file 43 count = 0 44 with open(newname+'~', 'w') as tempf: 45 with open(newname) as newf: 46 for line in newf: 47 line, n = subn(from_prefix, to_prefix, line) 48 count += n 49 tempf.write(line) 50 shutil.copystat(newname, newname+'~') 51 os.rename(newname+'~', newname) 52 subprocess.check_call(['git', 'add', newname]) 53 54 # Summary 55 print '%s: %d replacements' % ( 56 '%s -> %s' % (oldname, newname) if namecount else oldname, 57 count) 58 59if __name__ == "__main__": 60 import sys 61 sys.exit(main(*sys.argv[1:])) 62