fix issue about name for csv refactoring to use only one file and one directory

This commit is contained in:
edo-neo 2025-09-04 16:20:48 +02:00
parent 7f0b9c1d04
commit 53fbeda6d9

View File

@ -482,20 +482,38 @@ def export_recipes(config, csv_path=None, logger=None):
def backup_current_recipes(config, logger=None):
"""
Back up current recipes to a timestamped CSV file in the predefined backup directory.
Back up current recipes to a CSV file in a single common folder. The file name equals the
[machine]/description from the active machine config (sanitized). Saving overwrites any
previous backup with the same machine description.
"""
# Get the machine's hostname to use for the directory name
machine_name = socket.gethostname()
# Define the backup directory and file name
backup_dir = os.path.join('config', 'csv_import', 'backup_csv', machine_name)
timestamp = datetime.now().strftime("%d%m%y%H%M%S")
backup_file = f"backup_{timestamp}.csv"
backup_path = os.path.join(backup_dir, backup_file)
# Get machine description from config; fall back to hostname if missing
machine_desc = None
try:
machine_desc = (config.get("machine", {}) or {}).get("description")
except Exception:
machine_desc = None
if not machine_desc:
machine_desc = socket.gethostname()
# Sanitize description to be safe as a file name
safe_name = str(machine_desc).strip()
# Replace path separators and common forbidden characters on Windows/Unix
for ch in ['\\', '/', ':', '*', '?', '"', '<', '>', '|']:
safe_name = safe_name.replace(ch, '_')
# Also collapse consecutive spaces
safe_name = ' '.join(safe_name.split())
# Ensure .csv extension
if not safe_name.lower().endswith('.csv'):
safe_name = f"{safe_name}.csv"
# Define the single backup directory and file path
backup_dir = os.path.join('config', 'csv_import', 'backup_csv')
backup_path = os.path.join(backup_dir, safe_name)
# Ensure the backup directory exists
os.makedirs(backup_dir, exist_ok=True)
# Export current recipes to the backup path
# Export current recipes to the backup path (export_recipes overwrites the file)
export_recipes(config=config, csv_path=backup_path, logger=logger)
if logger: