+ часть работы xml перенесена в отдельный файл + фикс бага с записыванием в xml полных путей, вместо относительных + фикс бага при поиске
79 lines
2.5 KiB
Python
79 lines
2.5 KiB
Python
import os
|
||
import xml.etree.ElementTree as ET
|
||
|
||
def make_absolute_path(path, base_path):
|
||
if not os.path.isabs(path) and os.path.isdir(base_path):
|
||
try:
|
||
return os.path.abspath(os.path.join(base_path, path))
|
||
except Exception:
|
||
pass # На случай сбоя в os.path.join или abspath
|
||
elif os.path.isabs(path):
|
||
return os.path.abspath(path)
|
||
else:
|
||
return path
|
||
|
||
|
||
def make_relative_path(abs_path, base_path):
|
||
abs_path = os.path.abspath(abs_path)
|
||
base_path = os.path.abspath(base_path)
|
||
|
||
# Разбиваем на списки директорий
|
||
abs_parts = abs_path.split(os.sep)
|
||
base_parts = base_path.split(os.sep)
|
||
|
||
# Проверяем, является ли base_path настоящим префиксом пути (по папкам)
|
||
if abs_parts[:len(base_parts)] == base_parts:
|
||
rel_parts = abs_parts[len(base_parts):]
|
||
return "/".join(rel_parts)
|
||
|
||
# Иначе пробуем relpath
|
||
try:
|
||
return os.path.relpath(abs_path, base_path).replace("\\", "/")
|
||
except Exception:
|
||
return abs_path.replace("\\", "/")
|
||
|
||
def indent_xml(elem, level=0):
|
||
indent = " "
|
||
i = "\n" + level * indent
|
||
if len(elem):
|
||
if not elem.text or not elem.text.strip():
|
||
elem.text = i + indent
|
||
for child in elem:
|
||
indent_xml(child, level + 1)
|
||
if not elem.tail or not elem.tail.strip():
|
||
elem.tail = i
|
||
else:
|
||
if level and (not elem.tail or not elem.tail.strip()):
|
||
elem.tail = i
|
||
|
||
|
||
def fwrite(root, xml_full_path):
|
||
indent_xml(root)
|
||
ET.ElementTree(root).write(xml_full_path, encoding="utf-8", xml_declaration=True)
|
||
|
||
|
||
def safe_parse_xml(xml_path):
|
||
"""
|
||
Безопасно парсит XML-файл.
|
||
|
||
Возвращает кортеж (root, tree) или (None, None) при ошибках.
|
||
"""
|
||
if not xml_path or not os.path.isfile(xml_path):
|
||
print(f"Файл '{xml_path}' не найден или путь пустой")
|
||
return None, None
|
||
|
||
try:
|
||
if os.path.getsize(xml_path) == 0:
|
||
return None, None
|
||
|
||
tree = ET.parse(xml_path)
|
||
root = tree.getroot()
|
||
return root, tree
|
||
|
||
except ET.ParseError as e:
|
||
print(f"Ошибка парсинга XML файла '{xml_path}': {e}")
|
||
return None, None
|
||
except Exception as e:
|
||
print(f"Неожиданная ошибка при чтении XML файла '{xml_path}': {e}")
|
||
return None, None
|