From 76f6952f084cf33e01f91739c53ab2428863e508 Mon Sep 17 00:00:00 2001
From: Kubat <mael.martin31@gmail.com>
Date: Thu, 26 Aug 2021 10:46:58 +0200
Subject: [PATCH] LIB: Fix the renameWith and copyWith functions

---
 src/Lib/AbstractDocument.hh | 38 +++++++++++++++++++++++++++++--------
 1 file changed, 30 insertions(+), 8 deletions(-)

diff --git a/src/Lib/AbstractDocument.hh b/src/Lib/AbstractDocument.hh
index 9142bc4b..51d95101 100644
--- a/src/Lib/AbstractDocument.hh
+++ b/src/Lib/AbstractDocument.hh
@@ -43,11 +43,21 @@ protected:
             dirOp.mkpath(newAbsDirPath);
         }
 
-        if (QFile::copy(oldFile.absoluteFilePath(), newFile.absoluteFilePath()))
-            return success();
+        if (newFile.exists()) {
+            qWarning() << "Deleting the already existing" << newFile;
+            if (!dirOp.remove(newFile.absoluteFilePath()))
+                throw std::runtime_error("Failed to remove " +
+                                         newFile.absoluteFilePath().toStdString());
+        }
+
+        if (QFile::copy(oldFile.absoluteFilePath(), newFile.absoluteFilePath())) {
+            success();
+            save();
+        }
 
-        throw std::runtime_error("Failed to copy " + oldFile.absoluteFilePath().toStdString() +
-                                 " to " + newFile.absoluteFilePath().toStdString());
+        else
+            throw std::runtime_error("Failed to copy " + oldFile.absoluteFilePath().toStdString() +
+                                     " to " + newFile.absoluteFilePath().toStdString());
     }
 
     // Automate a part of the rename process, just need to provide a "success"
@@ -64,11 +74,23 @@ protected:
             dirOp.mkpath(newAbsDirPath);
         }
 
-        if (dirOp.rename(oldFile.absoluteFilePath(), newFile.absoluteFilePath()))
-            return success();
+        if (newFile.exists()) {
+            qWarning() << "Deleting the already existing" << newFile;
+            dirOp.remove(newFile.absoluteFilePath());
+            if (!dirOp.remove(newFile.absoluteFilePath()))
+                throw std::runtime_error("Failed to remove " +
+                                         newFile.absoluteFilePath().toStdString());
+        }
+
+        if (dirOp.rename(oldFile.absoluteFilePath(), newFile.absoluteFilePath())) {
+            success();
+            save();
+        }
 
-        throw std::runtime_error("Failed to rename " + oldFile.absoluteFilePath().toStdString() +
-                                 " to " + newFile.absoluteFilePath().toStdString());
+        else
+            throw std::runtime_error("Failed to rename " +
+                                     oldFile.absoluteFilePath().toStdString() + " to " +
+                                     newFile.absoluteFilePath().toStdString());
     }
 
     Type type;
-- 
GitLab