如何在Perforce触发器Python脚本中检查待提交文件内容?
问题描述
目标
我希望对用户拟提交的文件进行检查验证,阻止不符合要求的文件提交。
参考文档
我参考了Perforce官方文档,其中提到:
以下change-content触发器是一个Bourne Shell脚本,用于确保每个变更列表中的所有文件都包含当前年份的版权声明。
文档给出示例命令:
# p4 print -q //depot/src/file.c@=12345
我的代码
触发器表条目
check_hydra_json_trigger change-submit //foo/... "C:\Python38\python.exe %//foo/script.py% %changelist%"
Python脚本(script.py)
changelist_number = sys.argv[1] change = p4.run_describe(changelist_number) file_list = change[0]['depotFile'] for file_path in file_list: if file_path.endswith('.json'): output = p4.run("print", "-o", temp_file, f"{file_path}@{changelist_number}") data = None try: with open(temp_file, "r") as temp_file_contents: data = json.load(temp_file_contents) except Exception as e: print(f"Error: Failed to load json {file_path}. Is file properly formatted?") print(f"Exception: {e}")
遇到的问题
我用temp_file存储文件内容时,拿到的始终是仓库里的旧版本,不是用户待提交的新内容。换成change-content触发器也没解决这个问题。
解决方案
问题出在两个关键细节上:
p4 print的版本语法错误
你用的@{changelist_number}只会指向仓库中已存在的文件版本,而非变更列表里待提交的新内容。Perforce官方示例里的@=12345才是获取变更列表中待提交文件内容的正确语法。修改脚本中的
p4.run参数:output = p4.run("print", "-o", temp_file, f"{file_path}@={changelist_number}")触发器类型不匹配
change-submit阶段无法访问待提交的文件内容,必须使用change-content触发器才能获取变更里的新内容。更新触发器表条目:check_hydra_json_trigger change-content //foo/... "C:\Python38\python.exe %//foo/script.py% %changelist%"
完成这两处修改后,就能正确读取用户待提交的JSON文件内容,进而完成格式验证。
内容的提问来源于stack exchange,提问作者Adam Vengroff
相关产品推荐
相关产品推荐

