Created
December 22, 2016 09:53
-
-
Save nowox/168fa2848c94206770960f29ca964dc4 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
"""Update of new names in source code after massive file rename onto a Git repository. | |
This script considers: | |
- The script is located at the root of the Git repository | |
- The head of the branch where the files were renamed is checkout | |
- This branch as a common ancestor with the master | |
- This common ancestor is used for the diff | |
""" | |
import os, git | |
from termcolor import colored | |
from shutil import copyfile | |
MASTER_BRANCH = 'master' | |
RENAME_BRANCH = 'rework/files_renaming' | |
def ls_files(tree): | |
"""List the files into a Git repository.""" | |
files = [] | |
def _recurse_tree(tree): | |
for item in tree: | |
if item.type == 'blob' and item.mime_type == 'text/plain': | |
files.append(os.path.join(tree.abspath, item.name)) | |
elif item.type == 'tree': | |
_recurse_tree(item) | |
_recurse_tree(tree) | |
return sorted(files) | |
def get_branch(repo, branch): | |
"""Get a branch by its name.""" | |
return repo.heads[{v.name:i for i,v in enumerate(repo.heads)}[branch]] | |
# Get the rename branch | |
repo = git.Repo(search_parent_directories=True) | |
rename_branch = get_branch(repo, RENAME_BRANCH) | |
# Find common ancestor between the two branches | |
for commit in get_branch(repo, MASTER_BRANCH).commit.iter_parents(): | |
if not commit in rename_branch.commit.iter_parents(): break | |
# Identify the renamed files and list the changelist | |
changes = [] | |
for diff in commit.diff(rename_branch): | |
if not diff.renamed_file: continue | |
changes.append((os.path.basename(diff.rename_from), os.path.basename(diff.rename_to))) | |
# Do rename any occurences of the change list into all the repository files | |
for f in ls_files(repo.tree()): | |
copyfile(f, f + '.bak') | |
print "Processing %s ..." % f, | |
with open(f, 'wb') as dst: | |
with open(f + '.bak', 'rb') as src: | |
content = src.read() | |
for a, b in changes: | |
content = content.replace(bytes(a), bytes(b)) | |
dst.write(content) | |
os.unlink(f + '.bak') | |
print colored(' done', 'green') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment