Fix handling of properties files when they're in subdirs (#1082)

- File operation class methods create parent dirs if they don't exist
- Avoid stripping path from file names in several places
- Simplify prop file matching logic: check for existence of file
- Remove list_files() method which is now unused
This commit is contained in:
Daniel Markstedt 2023-01-28 14:36:07 -08:00 committed by GitHub
parent 956195d67e
commit bf53958636
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 34 deletions

View File

@ -4,7 +4,7 @@ Module for methods reading from and writing to the file system
import logging import logging
import asyncio import asyncio
from os import path, walk from os import walk
from functools import lru_cache from functools import lru_cache
from pathlib import PurePath, Path from pathlib import PurePath, Path
from zipfile import ZipFile, is_zipfile from zipfile import ZipFile, is_zipfile
@ -54,23 +54,6 @@ class FileCmds:
return self.sock_cmd.send_pb_command(command.SerializeToString()) return self.sock_cmd.send_pb_command(command.SerializeToString())
# noinspection PyMethodMayBeStatic
# pylint: disable=no-self-use
def list_files(self, file_types, dir_path):
"""
Takes a (list) or (tuple) of (str) file_types - e.g. ('hda', 'hds')
Returns (list) of (list)s files_list:
index 0 is (str) file name and index 1 is (int) size in bytes
"""
files_list = []
for file_path, _dirs, files in walk(dir_path):
# Only list selected file types
files = [file for file in files if file.lower().endswith(file_types)]
files_list.extend(
[(file, path.getsize(path.join(file_path, file))) for file in files],
)
return files_list
# noinspection PyMethodMayBeStatic # noinspection PyMethodMayBeStatic
def list_config_files(self): def list_config_files(self):
""" """
@ -99,18 +82,13 @@ class FileCmds:
result = proto.PbResult() result = proto.PbResult()
result.ParseFromString(data) result.ParseFromString(data)
# Get a list of all *.properties files in CFG_DIR
prop_data = self.list_files(PROPERTIES_SUFFIX, CFG_DIR)
prop_files = [PurePath(x[0]).stem for x in prop_data]
server_info = self.piscsi.get_server_info() server_info = self.piscsi.get_server_info()
files = [] files = []
for file in result.image_files_info.image_files: for file in result.image_files_info.image_files:
# Add properties meta data for the image, if applicable prop_file_path = Path(CFG_DIR) / f"{file.name}.{PROPERTIES_SUFFIX}"
if file.name in prop_files: # Add properties meta data for the image, if matching prop file is found
process = self.read_drive_properties( if prop_file_path.exists():
Path(CFG_DIR) / f"{file.name}.{PROPERTIES_SUFFIX}" process = self.read_drive_properties(prop_file_path)
)
prop = process["conf"] prop = process["conf"]
else: else:
prop = False prop = False
@ -189,6 +167,8 @@ class FileCmds:
Returns (dict) with (bool) status, (str) msg, (dict) parameters Returns (dict) with (bool) status, (str) msg, (dict) parameters
""" """
parameters = {"target_path": target_path} parameters = {"target_path": target_path}
if not target_path.parent.exists():
target_path.parent.mkdir(parents=True)
if target_path.parent.exists() and not target_path.exists(): if target_path.parent.exists() and not target_path.exists():
file_path.rename(target_path) file_path.rename(target_path)
return { return {
@ -211,6 +191,8 @@ class FileCmds:
Returns (dict) with (bool) status, (str) msg, (dict) parameters Returns (dict) with (bool) status, (str) msg, (dict) parameters
""" """
parameters = {"target_path": target_path} parameters = {"target_path": target_path}
if not target_path.parent.exists():
target_path.parent.mkdir(parents=True)
if target_path.parent.exists() and not target_path.exists(): if target_path.parent.exists() and not target_path.exists():
copyfile(str(file_path), str(target_path)) copyfile(str(file_path), str(target_path))
return { return {
@ -224,16 +206,18 @@ class FileCmds:
"parameters": parameters, "parameters": parameters,
} }
def create_empty_image(self, file_path, size): def create_empty_image(self, target_path, size):
""" """
Takes (Path) file_path and (int) size in bytes Takes (Path) target_path and (int) size in bytes
Creates a new empty binary file to use as image Creates a new empty binary file to use as image
Returns (dict) with (bool) status, (str) msg, (dict) parameters Returns (dict) with (bool) status, (str) msg, (dict) parameters
""" """
parameters = {"target_path": file_path} parameters = {"target_path": target_path}
if file_path.parent.exists() and not file_path.exists(): if not target_path.parent.exists():
target_path.parent.mkdir(parents=True)
if target_path.parent.exists() and not target_path.exists():
try: try:
with open(f"{file_path}", "wb") as out: with open(f"{target_path}", "wb") as out:
out.seek(size - 1) out.seek(size - 1)
out.write(b"\0") out.write(b"\0")
except OSError as error: except OSError as error:
@ -793,6 +777,8 @@ class FileCmds:
Returns (dict) with (bool) status and (str) msg Returns (dict) with (bool) status and (str) msg
""" """
file_path = Path(CFG_DIR) / file_name file_path = Path(CFG_DIR) / file_name
if not file_path.parent.exists():
file_path.parent.mkdir(parents=True)
try: try:
with open(file_path, "w") as json_file: with open(file_path, "w") as json_file:
dump(conf, json_file, indent=4) dump(conf, json_file, indent=4)

View File

@ -389,7 +389,7 @@ def drive_create():
Creates the image and properties file pair Creates the image and properties file pair
""" """
drive_name = request.form.get("drive_name") drive_name = request.form.get("drive_name")
file_name = Path(request.form.get("file_name")).name file_name = Path(request.form.get("file_name"))
properties = get_properties_by_drive_name(APP.config["PISCSI_DRIVE_PROPERTIES"], drive_name) properties = get_properties_by_drive_name(APP.config["PISCSI_DRIVE_PROPERTIES"], drive_name)
@ -432,7 +432,7 @@ def drive_cdrom():
Creates a properties file for a CD-ROM image Creates a properties file for a CD-ROM image
""" """
drive_name = request.form.get("drive_name") drive_name = request.form.get("drive_name")
file_name = Path(request.form.get("file_name")).name file_name = Path(request.form.get("file_name"))
# Creating the drive properties file # Creating the drive properties file
file_name = f"{file_name}.{PROPERTIES_SUFFIX}" file_name = f"{file_name}.{PROPERTIES_SUFFIX}"