Created
April 17, 2019 18:01
-
-
Save kenyee/e0090b9bfafbcbf5944d51fc20e14f2f to your computer and use it in GitHub Desktop.
Hardened Python3 script to automatically rename classpaths for the AndroidX migration...thanks to AndiMiko for the original: https://gist.github.com/AndiMiko/58ecc04a64ac4f89eb5262176ab3fc9e
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/local/bin/python3 | |
import sys, getopt | |
import glob | |
import csv | |
import os | |
dictCSV = "androidx-class-mapping.csv" | |
projectPath = os.getcwd() | |
def main(argv): | |
testrun = False | |
try: | |
opts, args = getopt.getopt(argv,"htm:p:",["mappingFile=","projectPath=","testrun"]) | |
except getopt.GetoptError: | |
print_help() | |
sys.exit(2) | |
for opt, arg in opts: | |
if opt == '-h': | |
print_help() | |
sys.exit() | |
elif opt in ("-m", "--mappingFile"): | |
global dictCSV | |
dictCSV = arg | |
elif opt in ("-p", "--projectPath"): | |
global projectPath | |
projectPath = arg | |
elif opt in ("-t", "--testrun"): | |
print("Test Run") | |
testrun = True | |
if (not os.path.isfile(dictCSV)): | |
print(dictCSV + " doesn't exist") | |
sys.exit(-1) | |
if (not os.path.isdir(projectPath)): | |
print(projectPath + " doesn't exist") | |
sys.exit(-1) | |
doReplace(testrun) | |
def print_help(): | |
print('migrateAndroidX.py -m <mappingFile> -p <projectPath> [-testrun]') | |
def find_unfixed(text, dic): | |
for i, j in dic.items(): | |
if (text.find(i) > -1): | |
return True | |
return False | |
def replace_all(text, dic): | |
for i, j in dic.items(): | |
text = text.replace(i, j) | |
return text | |
def doReplace(isTestRun): | |
fileCount = 0 | |
with open(dictCSV, mode='r') as infile: | |
reader = csv.reader(infile) | |
replaceDict = {rows[0]:rows[1] for rows in reader} | |
files = [] | |
for ext in ('/**/*.xml', '/**/*.kt', '/**/*.java'): | |
files.extend(glob.iglob(projectPath + ext, recursive=True)) | |
for filename in files: | |
try: | |
if os.path.isfile(filename): | |
with open(filename, 'r') as file : | |
filedata = file.read() | |
needsReplacing = find_unfixed(filedata, replaceDict) | |
if (needsReplacing): | |
print("Replacing in file: " + filename) | |
fileCount = fileCount + 1 | |
if (not isTestRun): | |
filedata = replace_all(filedata, replaceDict) | |
with open(filename, 'w') as file: | |
file.write(filedata) | |
except Exception as e: | |
print("Error reading/writing file. Skipping ..." + e) | |
print(str(fileCount) + " files affected") | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment