chronaxis.configuration.initialization
源码基线:8904c2f744951857659abd40aaa3535d57faf53c
1"""把已校验的随包合成场景写入新目录,不改写已有文件。"""2from pathlib import Path34from .template_catalog import available_templates, template_files567def initialize_configuration(scene, output, *, style='annotated'):8 """生成独立场景。参数: 场景名、新目录及风格。返回: 入口绝对路径。异常: ValueError/IO/取消。910 先读取全部包资源再独占创建目录,入口最后写出。写入失败仅删除本次创建的文件和目录;11 清理失败附注原错误并保留残余,不删除其他进程写入的文件,不以成功掩盖部分写入。12 """13 contents=template_files(scene,style=style)14 template=next(t for t in available_templates() if t.name==scene)15 target=Path(output).absolute()16 # mkdir的独占失败发生在清理区之前,已有目录(包括空目录、链接)不属于本次操作。17 target.mkdir()18 created_files=[];created_directories=[target]19 try:20 # 将主入口放在最后,使中途产物不能被误认为完整场景。21 for relative,content in sorted(contents,key=lambda item:item[0]==template.entrypoint):22 path=target/relative23 missing=[];parent=path.parent24 while parent!=target and not parent.exists():missing.append(parent);parent=parent.parent25 for directory in reversed(missing):directory.mkdir();created_directories.append(directory)26 with path.open('xb') as stream:27 created_files.append(path);stream.write(content)28 return target/template.entrypoint29 except BaseException as error:30 for path in reversed(created_files):31 try:path.unlink()32 except OSError as cleanup:error.add_note('未能清理本次文件 '+str(path)+': '+str(cleanup))33 for directory in reversed(created_directories):34 try:directory.rmdir()35 except OSError as cleanup:error.add_note('未能清理本次空目录 '+str(directory)+': '+str(cleanup))36 raise37