Implement smart file resolving for images

When resolving a relative image path, first search relative to the main YAML's path, then relative to the prepended YAML if unsuccessful.
This commit is contained in:
Daniel Rojas 2021-10-02 17:51:54 +02:00
parent d94a249176
commit 42a15f7eab
2 changed files with 28 additions and 5 deletions

View File

@ -5,7 +5,7 @@ import argparse
import os import os
from pathlib import Path from pathlib import Path
import sys import sys
from typing import Any, Tuple from typing import Any, List, Tuple
import yaml import yaml
@ -14,10 +14,10 @@ if __name__ == '__main__':
from wireviz import __version__ from wireviz import __version__
from wireviz.Harness import Harness from wireviz.Harness import Harness
from wireviz.wv_helper import expand, open_file_read from wireviz.wv_helper import expand, open_file_read, smart_file_resolve
def parse(yaml_input: str, base_path: (str, Path) = None, file_out: (str, Path) = None, return_types: (None, str, Tuple[str]) = None) -> Any: def parse(yaml_input: str, base_path: (str, Path, List) = None, file_out: (str, Path) = None, return_types: (None, str, Tuple[str]) = None) -> Any:
""" """
Parses yaml input string and does the high-level harness conversion Parses yaml input string and does the high-level harness conversion
@ -49,7 +49,7 @@ def parse(yaml_input: str, base_path: (str, Path) = None, file_out: (str, Path)
if isinstance(image, dict): if isinstance(image, dict):
image_path = image['src'] image_path = image['src']
if image_path and not Path(image_path).is_absolute(): # resolve relative image path if image_path and not Path(image_path).is_absolute(): # resolve relative image path
image['src'] = (Path(base_path) / image_path).resolve() image['src'] = smart_file_resolve(image_path, base_path)
if sec == 'connectors': if sec == 'connectors':
if not attribs.get('autogenerate', False): if not attribs.get('autogenerate', False):
@ -237,6 +237,8 @@ def main():
with open_file_read(args.input_file) as fh: with open_file_read(args.input_file) as fh:
yaml_input = fh.read() yaml_input = fh.read()
base_path = [Path(args.input_file).parent]
if args.prepend_file: if args.prepend_file:
if not os.path.exists(args.prepend_file): if not os.path.exists(args.prepend_file):
print(f'Error: prepend input file {args.prepend_file} inaccessible or does not exist, check path') print(f'Error: prepend input file {args.prepend_file} inaccessible or does not exist, check path')
@ -244,6 +246,7 @@ def main():
with open_file_read(args.prepend_file) as fh: with open_file_read(args.prepend_file) as fh:
prepend = fh.read() prepend = fh.read()
yaml_input = prepend + yaml_input yaml_input = prepend + yaml_input
base_path.append(Path(args.prepend_file).parent)
if not args.output_file: if not args.output_file:
file_out = args.input_file file_out = args.input_file
@ -253,7 +256,7 @@ def main():
file_out = args.output_file file_out = args.output_file
file_out = os.path.abspath(file_out) file_out = os.path.abspath(file_out)
parse(yaml_input, base_path=Path(args.input_file).parent, file_out=file_out) parse(yaml_input, base_path=base_path, file_out=file_out)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -1,6 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from pathlib import Path
from typing import List from typing import List
import re import re
@ -117,3 +118,22 @@ def aspect_ratio(image_src):
except Exception as error: except Exception as error:
print(f'aspect_ratio(): {type(error).__name__}: {error}') print(f'aspect_ratio(): {type(error).__name__}: {error}')
return 1 # Assume 1:1 when unable to read actual image size return 1 # Assume 1:1 when unable to read actual image size
def smart_file_resolve(filename: str, possible_paths: (str, List[str])) -> Path:
if not isinstance(possible_paths, List):
possible_paths = [possible_paths]
filename = Path(filename)
if filename.is_absolute():
if filename.exists():
return filename
else:
raise Exception(f'{filename} does not exist.')
else: # search all possible paths in decreasing order of precedence
possible_paths = [Path(path).resolve() for path in possible_paths if path is not None]
for possible_path in possible_paths:
resolved_path = (possible_path / filename).resolve()
if (resolved_path).exists():
return resolved_path
else:
raise Exception(f'{filename} was not found in any of the following locations: \n' +
'\n'.join([str(x) for x in possible_paths]))