# -*- coding: utf-8 -*-
"""
Created on Sat Mar 30 20:00:17 2019
@author: Administrator
"""
import os
import shutil
target_file = "target.mk"
new_file = "new.mk"
new2_file = "new2.mk"
target_str = "lwip_version_1.4"
#replace_str = "lwip_version_2.0"
note_str = "choice"
original_content = \
"""choice:
depend:
lwip_version_1.4
lwip_version_2.0
select lwip_version_1.4:
lwiplib += lwip_sack_1.4
select lwip_version_2.0:
lwiplib += lwip_sack_2.0
endif
"""
def replace(replace_str):
file_data = ""
with open(target_file, "r", encoding="utf-8") as f:
target_find = False
target_branch = False
for line in f:
if target_str in line:
line = line.replace(target_str,replace_str)
target_find =True
file_data += line
target_branch = False #each time find, init target branch
if target_str == replace_str:
target_branch = True
continue
if target_find == True:
if target_str != replace_str:
if "else" in line:
target_branch = True
continue
if "endif" in line:
target_find = False
target_branch = True
if target_branch == False:
continue
else:
if "else" in line:
target_branch = False
if "endif" in line:
target_find = False
target_branch = True
if target_branch == False:
continue
file_data += line
with open(new_file,"w",encoding="utf-8") as f:
f.write(file_data)
def merge(target_file):
file_data = ""
if target_file == "target.mk":
with open("new.mk", "r", encoding = "utf-8") as f:
choice_find = False
for line in f:
if note_str in line:
choice_find = True
print("find choice")
file_data += original_content
if choice_find == True:
if "endif" in line:
choice_find =False
#continue
continue
file_data += line
with open(new2_file,"w",encoding="utf-8") as f:
f.write(file_data)
pass
def delete(replace_str):
file_data = ""
with open(target_file, "r", encoding="utf-8") as f:
target_branch = False
delete_branch = False
choice_find = False
depend_find = False
for line in f:
if note_str in line:
choice_find = True
target_branch = False
delete_branch = False
depend_find = False
if choice_find == True:
if "depend" in line:
depend_find = True
file_data += line
continue
if "select" in line:
depend_find = False
if depend_find == True:
if "lwip_version_1.4" not in line and "lwip_version_2.0" not in line:
pass
elif replace_str not in line:
continue
else:
pass
if "select" in line:
if replace_str in line:
target_branch = True
else:
delete_branch = True
if delete_branch == True:
if "lwip_version_1.4" not in line and "lwip_version_2.0" not in line:
delete_branch = False
else:
pass
continue
if "endif" in line:
choice_find = False
file_data += line
with open(new_file,"w",encoding="utf-8") as f:
f.write(file_data)
if __name__=='__main__':
delete("lwip_version_2.0")
merge("target.mk")
#os.remove("new.mk")
#shutil.rmtree(path)