Commit 94dfd0ea authored by guest's avatar guest

提交脚本

parent ed360823
This diff is collapsed.
...@@ -983,8 +983,8 @@ def deal_code(): ...@@ -983,8 +983,8 @@ def deal_code():
if os.path.isdir(os.path.join(new_path, i)): if os.path.isdir(os.path.join(new_path, i)):
continue continue
result_path.append(os.path.join(new_path, i)) result_path.append(os.path.join(new_path, i))
add_import(applicationId + '.R', result_path) # add_import(applicationId + '.R', result_path)
add_import(applicationId + '.BuildConfig', result_path) # add_import(applicationId + '.BuildConfig', result_path)
# 类名 # 类名
print("类名 start") print("类名 start")
...@@ -1064,7 +1064,18 @@ def deal_res_type(res_type): ...@@ -1064,7 +1064,18 @@ def deal_res_type(res_type):
name = j.rsplit('.', 1)[0] name = j.rsplit('.', 1)[0]
path = os.path.join(path_join, j) path = os.path.join(path_join, j)
if '.DS_Store' not in path: if '.DS_Store' not in path:
shutil.move(path, path.replace(name, type_mapping[name])) # shutil.move(path, path.replace(name, type_mapping[name]))
# 仅替换文件名部分
dir_path, file_name = os.path.split(path)
new_file_name = file_name.replace(name, type_mapping[name])
new_path = os.path.join(dir_path, new_file_name)
# 打印路径调试信息
print(f"源路径: {path}")
print(f"目标路径: {new_path}")
# 移动文件
shutil.move(path, new_path)
sub_map = {} sub_map = {}
for i in type_mapping: for i in type_mapping:
...@@ -1540,7 +1551,130 @@ def main(): ...@@ -1540,7 +1551,130 @@ def main():
deal_code() deal_code()
def load_mapping(file_path):
"""加载 mapping.json 文件并打印内容."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
print("Loaded Mapping:")
print(json.dumps(data, indent=4, ensure_ascii=False)) # 打印映射内容
return data.get("view_ids", {})
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Error loading mapping file: {e}")
return {}
def replace_identifiers_in_file(file_path, mapping, replacements_log):
"""替换单个文件中的标识符,并存储替换的内容到 JSON 日志."""
with open(file_path, 'r', encoding='utf-8') as f:
original_text = f.read()
print(f"\nProcessing File: {file_path}")
print("Original Content:")
print(original_text) # 打印文件原始内容
modified_text = original_text
replacements = []
# 替换所有绑定相关的引用
def replace_binding_references(match):
identifier = match.group(2) or match.group(3)
return f"{match.group(1)}.{mapping.get(identifier, identifier)}"
# 替换类似 `binding.tvTest1` 和 `it.tvTest1` 的结构
modified_text = re.sub(
r'\b(binding|it)\.([a-zA-Z_0-9]+)\b',
replace_binding_references,
modified_text
)
# 替换无前缀的变量名,如 `tvTest1` 和 `tvTest2`,根据 mapping 文件中的 view_ids 替换
def replace_variable_names(match):
identifier = match.group(1)
# 使用 mapping 中的 view_ids 替换变量名
new_identifier = mapping.get(identifier, identifier)
if new_identifier != identifier:
replacements.append({"original": identifier, "modified": new_identifier})
return new_identifier
# 先提取所有引号中的内容
quoted_texts = re.findall(r'"([^"]*)"', modified_text)
# 将引号中的内容临时替换为占位符
placeholders = [f"__PLACEHOLDER_{i}__" for i in range(len(quoted_texts))]
for i, quoted in enumerate(quoted_texts):
modified_text = modified_text.replace(f'"{quoted}"', placeholders[i])
# 过滤掉方法调用中的标识符(例如 taichiPref.edit() 不替换 edit)
def is_function_call(match):
# 检查匹配的标识符后是否跟着 `()`
return f"{match.group(1)}()" if match.group(2) else None
# 替换变量名,排除函数调用
modified_text = re.sub(
r'\b(' + '|'.join(mapping.keys()) + r')\b(?!\()',
replace_variable_names,
modified_text
)
# 将占位符替换回原始引号内容
for i, quoted in enumerate(quoted_texts):
modified_text = modified_text.replace(placeholders[i], f'"{quoted}"')
# 过滤重复的替换项:根据 (original, modified) 进行去重
seen_replacements = set()
unique_replacements = []
for replacement in replacements:
replacement_tuple = (replacement["original"], replacement["modified"])
if replacement_tuple not in seen_replacements:
unique_replacements.append(replacement)
seen_replacements.add(replacement_tuple)
if unique_replacements:
replacements_log[file_path] = unique_replacements
# 写入修改后的内容
with open(file_path, 'w', encoding='utf-8') as f:
f.write(modified_text)
else:
print("No replacements made.")
def process_files_in_directory(directory, mapping, replacements_log):
"""处理目录下的所有文件并打印文件路径."""
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".kt"): # 仅处理 Kotlin 文件
file_path = os.path.join(root, file)
replace_identifiers_in_file(file_path, mapping, replacements_log)
def solve_runapplyalso():
# 配置路径
mapping_file = "mapping.json"
src_directory = "./src/main/java"
log_file = "replacement_log.json"
# 加载映射表
mapping = load_mapping(mapping_file)
# 检查路径
if not os.path.exists(src_directory):
print(f"Source directory not found: {src_directory}")
elif not mapping:
print("Mapping file is empty or not found.")
else:
# 存储替换日志
replacements_log = {}
# 开始处理文件
process_files_in_directory(src_directory, mapping, replacements_log)
# 将替换日志保存为 JSON 文件
with open(log_file, 'w', encoding='utf-8') as log:
json.dump(replacements_log, log, ensure_ascii=False, indent=4)
print(f"\nReplacement completed. Log saved to {log_file}.")
if __name__ == '__main__': if __name__ == '__main__':
if os.path.exists('build.gradle'): if os.path.exists('build.gradle'):
gradle_path = 'build.gradle' gradle_path = 'build.gradle'
...@@ -1548,8 +1682,7 @@ if __name__ == '__main__': ...@@ -1548,8 +1682,7 @@ if __name__ == '__main__':
gradle_path = 'build.gradle.kts' gradle_path = 'build.gradle.kts'
else: else:
exit('找不到 build.gradle 文件') exit('找不到 build.gradle 文件')
#获取build.gradle.kts里的namespace,以此确定混淆目录和包名
applicationId = re.search('namespace .*?["\'](.*?)["\']', open(gradle_path, 'r', encoding='utf-8').read())[1] applicationId = re.search('namespace .*?["\'](.*?)["\']', open(gradle_path, 'r', encoding='utf-8').read())[1]
print(applicationId) print(applicationId)
main() main()
# solve_runapplyalso()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment