53 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			Python
		
	
	
	
			
		
		
	
	
			53 lines
		
	
	
		
			1.7 KiB
		
	
	
	
		
			Python
		
	
	
	
import json
 | 
						|
import os.path
 | 
						|
import xml.etree.ElementTree as ET
 | 
						|
 | 
						|
from scripts.task import Task
 | 
						|
from utils.logger_utils import app_logger
 | 
						|
 | 
						|
 | 
						|
def batch_update_xml_resources(file_path, updates_dict):
 | 
						|
    # 解析XML文件
 | 
						|
    tree = ET.parse(file_path)
 | 
						|
    root = tree.getroot()
 | 
						|
    updated_count = 0  # 遍历字典中的每个key-value对
 | 
						|
    for key, new_value in updates_dict.items():
 | 
						|
        # 查找指定key的元素
 | 
						|
        for elem in root.findall(f".//string[@name='{key}']"):
 | 
						|
            # 修改元素内容
 | 
						|
            elem.text = new_value.replace("'", "\\'")
 | 
						|
            print(f"已更新 key: {key} 的值为: {elem.text}")
 | 
						|
            updated_count += 1
 | 
						|
            break
 | 
						|
        else:
 | 
						|
            print(f"未找到 key: {key}")
 | 
						|
 | 
						|
    # 美化并保存修改
 | 
						|
    tree.write(file_path, encoding='utf-8', xml_declaration=True)
 | 
						|
    return updated_count
 | 
						|
 | 
						|
 | 
						|
class ProjectResString(Task):
 | 
						|
 | 
						|
    def update_res(self, string_path: str, res: dict[str, str]):
 | 
						|
        if os.path.exists(string_path):
 | 
						|
            batch_update_xml_resources(string_path, res)
 | 
						|
            return
 | 
						|
 | 
						|
        app_logger().debug("路径不存,不操作了,后续可以给他创建出来:" + string_path + "\t" + json.dumps(res, indent=4))
 | 
						|
 | 
						|
    def execute(self):
 | 
						|
        if not self.context.update_code:
 | 
						|
            app_logger().info("代码没有更新,不需要处理资源")
 | 
						|
            return
 | 
						|
        for key in self.context.string.keys():
 | 
						|
            launcher = key.replace('base', '')
 | 
						|
            if launcher:
 | 
						|
                launcher = "values-" + launcher
 | 
						|
            else:
 | 
						|
                launcher = "values"
 | 
						|
 | 
						|
            path = f"launcher-game/res/{launcher}/strings.xml"
 | 
						|
            self.update_res(os.path.join(self.context.temp_project_path, path), self.context.string[key])
 | 
						|
        pass
 |