Kenji Arai / mbed-os_TYBLE16

Dependents:   TYBLE16_simple_data_logger TYBLE16_MP3_Air

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers prefix.py Source File

prefix.py

00001 #!/usr/bin/env python
00002 
00003 # This script replaces prefixes of files, and symbols in that file.
00004 # Useful for creating different versions of the codebase that don't
00005 # conflict at compile time.
00006 #
00007 # example:
00008 # $ ./scripts/prefix.py lfs2
00009 
00010 import os
00011 import os.path
00012 import re
00013 import glob
00014 import itertools
00015 import tempfile
00016 import shutil
00017 import subprocess
00018 
00019 DEFAULT_PREFIX = "lfs"
00020 
00021 def subn(from_prefix, to_prefix, name):
00022     name, count1 = re.subn('\\b'+from_prefix, to_prefix, name)
00023     name, count2 = re.subn('\\b'+from_prefix.upper(), to_prefix.upper(), name)
00024     name, count3 = re.subn('\\B-D'+from_prefix.upper(),
00025             '-D'+to_prefix.upper(), name)
00026     return name, count1+count2+count3
00027 
00028 def main(from_prefix, to_prefix=None, files=None):
00029     if not to_prefix:
00030         from_prefix, to_prefix = DEFAULT_PREFIX, from_prefix
00031 
00032     if not files:
00033         files = subprocess.check_output([
00034                 'git', 'ls-tree', '-r', '--name-only', 'HEAD']).split()
00035 
00036     for oldname in files:
00037         # Rename any matching file names
00038         newname, namecount = subn(from_prefix, to_prefix, oldname)
00039         if namecount:
00040             subprocess.check_call(['git', 'mv', oldname, newname])
00041 
00042         # Rename any prefixes in file
00043         count = 0
00044         with open(newname+'~', 'w') as tempf:
00045             with open(newname) as newf:
00046                 for line in newf:
00047                     line, n = subn(from_prefix, to_prefix, line)
00048                     count += n
00049                     tempf.write(line)
00050         shutil.copystat(newname, newname+'~')
00051         os.rename(newname+'~', newname)
00052         subprocess.check_call(['git', 'add', newname])
00053 
00054         # Summary
00055         print '%s: %d replacements' % (
00056                 '%s -> %s' % (oldname, newname) if namecount else oldname,
00057                 count)
00058 
00059 if __name__ == "__main__":
00060     import sys
00061     sys.exit(main(*sys.argv[1:]))