From b789cdfed669c5393d41fd1d8583530390ba38d9 Mon Sep 17 00:00:00 2001 From: Daniel Mach Date: Thu, 4 May 2023 10:58:21 +0200 Subject: [PATCH] Backup edited messages and notify user about them when osc errors out The messages are kept in ~/.cache/osc/edited-messages for 1 day. --- osc/babysitter.py | 6 ++++++ osc/core.py | 34 +++++++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/osc/babysitter.py b/osc/babysitter.py index 7504c592..94623d17 100644 --- a/osc/babysitter.py +++ b/osc/babysitter.py @@ -19,6 +19,7 @@ import urllib3.exceptions from . import _private from . import commandline from . import conf as osc_conf +from . import core as osc_core from . import oscerr from .OscConfigParser import configparser from .oscssl import CertVerificationError @@ -196,6 +197,11 @@ def run(prg, argv=None): print(e, file=sys.stderr) except oscerr.OscBaseError as e: print('*** Error:', e, file=sys.stderr) + if osc_core.MESSAGE_BACKUPS: + print() + print("If you lost any edited commit messages due to an error, you may find them here:") + for path in osc_core.MESSAGE_BACKUPS: + print(f" - {path}") return 1 diff --git a/osc/core.py b/osc/core.py index 78cdb66d..f60383ac 100644 --- a/osc/core.py +++ b/osc/core.py @@ -4408,6 +4408,11 @@ def _editor_command(): return cmd +# list of files with message backups +# we'll show this list when osc errors out +MESSAGE_BACKUPS = [] + + def _edit_message_open_editor(filename, data, orig_mtime): editor = _editor_command() mtime = os.stat(filename).st_mtime @@ -4428,7 +4433,34 @@ def _edit_message_open_editor(filename, data, orig_mtime): run_editor(filename) else: run_editor(filename) - return os.stat(filename).st_mtime != orig_mtime + + if os.stat(filename).st_mtime != orig_mtime: + # file has changed + + cache_dir = os.path.expanduser("~/.cache/osc/edited-messages") + try: + os.makedirs(cache_dir, mode=0o700) + except FileExistsError: + pass + + # remove any stored messages older than 1 day + now = datetime.datetime.now() + epoch = datetime.datetime.timestamp(now - datetime.timedelta(days=1)) + for fn in os.listdir(cache_dir): + path = os.path.join(cache_dir, fn) + if not os.path.isfile(path): + continue + mtime = os.path.getmtime(path) + if mtime < epoch: + os.unlink(path) + + # store the current message's backup to the cache dir + message_backup_path = os.path.join(cache_dir, str(now).replace(" ", "_")) + shutil.copyfile(filename, message_backup_path) + MESSAGE_BACKUPS.append(message_backup_path) + return True + + return False def edit_message(footer='', template='', templatelen=30):