Debian Codegraph @

src/App/BackupPolicy.cpp

raw
1 // SPDX-License-Identifier: LGPL-2.1-or-later
2
3 /****************************************************************************
4 * Copyright (c) 2020 Werner Mayer <wmayer[at]users.sourceforge.net> *
5 * *
6 * This file is part of FreeCAD. *
7 * *
8 * FreeCAD is free software: you can redistribute it and/or modify it *
9 * under the terms of the GNU Lesser General Public License as *
10 * published by the Free Software Foundation, either version 2.1 of the *
11 * License, or (at your option) any later version. *
12 * *
13 * FreeCAD is distributed in the hope that it will be useful, but *
14 * WITHOUT ANY WARRANTY; without even the implied warranty of *
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
16 * Lesser General Public License for more details. *
17 * *
18 * You should have received a copy of the GNU Lesser General Public *
19 * License along with FreeCAD. If not, see *
20 * <https://www.gnu.org/licenses/>. *
21 * *
22 ***************************************************************************/
23
24 #include <boost/algorithm/string/replace.hpp>
25 #include <boost/regex.hpp>
26 #include <string>
27
28 #include <Base/TimeInfo.h>
29 #include <Base/Console.h>
30 #include <Base/Exception.h>
31 #include <Base/FileInfo.h>
32 #include <Base/Interpreter.h>
33 #include <Base/Tools.h>
34 #include <Base/Writer.h>
35
36 #include "BackupPolicy.h"
37
38 using namespace App;
39
40 void BackupPolicy::setPolicy(const Policy p)
41 {
42 policy = p;
43 }
44 void BackupPolicy::setNumberOfFiles(const int count)
45 {
46 numberOfFiles = count;
47 }
48 void BackupPolicy::useBackupExtension(const bool on)
49 {
50 useFCBakExtension = on;
51 }
52 void BackupPolicy::setDateFormat(const std::string& fmt)
53 {
54 saveBackupDateFormat = fmt;
55 }
56 void BackupPolicy::apply(const std::string& sourcename, const std::string& targetname)
57 {
58 switch (policy) {
59 case Standard:
60 applyStandard(sourcename, targetname);
61 break;
62 case TimeStamp:
63 applyTimeStamp(sourcename, targetname);
64 break;
65 }
66 }
67
68 void BackupPolicy::applyStandard(const std::string& sourcename, const std::string& targetname) const
69 {
70 // if saving the project data succeeded rename to the actual file name
71 if (Base::FileInfo fi(targetname); fi.exists()) {
72 if (numberOfFiles > 0) {
73 int nSuff = 0;
74 std::string fn = fi.fileName();
75 Base::FileInfo di(fi.dirPath());
76 std::vector<Base::FileInfo> backup;
77 std::vector<Base::FileInfo> files = di.getDirectoryContent();
78 for (const Base::FileInfo& it : files) {
79 if (std::string file = it.fileName(); file.substr(0, fn.length()) == fn) {
80 // starts with the same file name
81 std::string suf(file.substr(fn.length()));
82 if (!suf.empty()) {
83 std::string::size_type nPos = suf.find_first_not_of("0123456789");
84 if (nPos == std::string::npos) {
85 // store all backup files
86 backup.push_back(it);
87 nSuff =
88 std::max<int>(nSuff, static_cast<int>(std::atol(suf.c_str())));
89 }
90 }
91 }
92 }
93
94 if (!backup.empty() && static_cast<int>(backup.size()) >= numberOfFiles) {
95 // delete the oldest backup file we found
96 Base::FileInfo del = backup.front();
97 for (const Base::FileInfo& it : backup) {
98 if (it.lastModified() < del.lastModified()) {
99 del = it;
100 }
101 }
102
103 del.deleteFile();
104 fn = del.filePath();
105 }
106 else {
107 // create a new backup file
108 std::stringstream str;
109 str << fi.filePath() << (nSuff + 1);
110 fn = str.str();
111 }
112
113 if (!fi.renameFile(fn.c_str())) {
114 Base::Console().warning("Cannot rename project file to backup file\n");
115 }
116 }
117 else {
118 fi.deleteFile();
119 }
120 }
121
122 if (Base::FileInfo tmp(sourcename); !tmp.renameFile(targetname.c_str())) {
123 throw Base::FileException("Cannot rename tmp save file to project file",
124 Base::FileInfo(targetname));
125 }
126 }
127
128 void BackupPolicy::applyTimeStamp(const std::string& sourcename, const std::string& targetname)
129 {
130 Base::FileInfo fi(targetname);
131
132 std::string fn = sourcename;
133 std::string ext = fi.extension();
134 std::string bn; // full path with no extension but with "."
135 std::string pbn; // base name of the project + "."
136 if (!ext.empty()) {
137 bn = fi.filePath().substr(0, fi.filePath().length() - ext.length());
138 pbn = fi.fileName().substr(0, fi.fileName().length() - ext.length());
139 }
140 else {
141 bn = fi.filePath() + ".";
142 pbn = fi.fileName() + ".";
143 }
144
145 bool backupManagementError = false; // Note error and report at the end
146 if (fi.exists()) {
147 if (numberOfFiles > 0) {
148 // replace . by - in format to avoid . between base name and extension
149 boost::replace_all(saveBackupDateFormat, ".", "-");
150 {
151 // Remove all extra backups
152 std::string filename = fi.fileName();
153 Base::FileInfo di(fi.dirPath());
154 std::vector<Base::FileInfo> backup;
155 std::vector<Base::FileInfo> files = di.getDirectoryContent();
156 for (const Base::FileInfo& it : files) {
157 if (it.isFile()) {
158 std::string file = it.fileName();
159 std::string fext = it.extension();
160 std::string fextUp = fext;
161 std::transform(fextUp.begin(),
162 fextUp.end(),
163 fextUp.begin(),
164 static_cast<int (*)(int)>(toupper));
165 // re-enforcing identification of the backup file
166
167
168 // old case : the name starts with the full name of the project and
169 // follows with numbers
170 if ((startsWith(file, filename) && (file.length() > filename.length())
171 && checkDigits(file.substr(filename.length())))
172 ||
173 // .FCBak case : The bame starts with the base name of the project +
174 // "."
175 // + complement with no "." + ".FCBak"
176 ((fextUp == "FCBAK") && startsWith(file, pbn)
177 && (checkValidComplement(file, pbn, fext)))) {
178 backup.push_back(it);
179 }
180 }
181 }
182
183 if (!backup.empty() && static_cast<int>(backup.size()) >= numberOfFiles) {
184 std::sort(backup.begin(), backup.end(), fileComparisonByDate);
185 // delete the oldest backup file we found
186 // Base::FileInfo del = backup.front();
187 int nb = 0;
188 for (Base::FileInfo& it : backup) {
189 nb++;
190 if (nb >= numberOfFiles) {
191 try {
192 if (!it.deleteFile()) {
193 backupManagementError = true;
194 Base::Console().warning("Cannot remove backup file : %s\n",
195 it.fileName().c_str());
196 }
197 }
198 catch (...) {
199 backupManagementError = true;
200 Base::Console().warning("Cannot remove backup file : %s\n",
201 it.fileName().c_str());
202 }
203 }
204 }
205 }
206 } // end remove backup
207
208 // create a new backup file
209 {
210 int ext2 = 1;
211 if (useFCBakExtension) {
212 std::stringstream str;
213 Base::TimeInfo ti = fi.lastModified();
214 time_t s = ti.getTime_t();
215 std::tm local_tm {};
216 #if defined(_WIN32)
217 localtime_s(&local_tm, &s); // Windows
218 #else
219 localtime_r(&s, &local_tm); // POSIX
220 #endif
221 constexpr size_t bufferLength = 128;
222 std::array<char, bufferLength> buffer {};
223 if (size_t bytes = std::strftime(buffer.data(),
224 bufferLength,
225 saveBackupDateFormat.c_str(),
226 &local_tm);
227 bytes == 0) {
228 // An error here is typically that we over-ran the maximum buffer length (
229 // which should be a *very* unusual condition).
230 Base::Console().error("Failed to create valid backup file name from format string:\n");
231 Base::Console().error(saveBackupDateFormat.c_str());
232 const auto knownGoodFormat {"%Y-%m-%d_%H-%M-%S"};
233 std::strftime(buffer.data(), bufferLength, knownGoodFormat, &local_tm);
234 }
235 str << bn << buffer.data();
236
237 fn = str.str();
238 bool done = false;
239
240 if ((fn.empty()) || (fn[fn.length() - 1] == ' ')
241 || (fn[fn.length() - 1] == '-')) {
242 if (fn[fn.length() - 1] == ' ') {
243 fn = fn.substr(0, fn.length() - 1);
244 }
245 }
246 else {
247 if (!renameFileNoErase(fi, fn + ".FCBak")) {
248 fn = fn + "-";
249 }
250 else {
251 done = true;
252 }
253 }
254
255 if (!done) {
256 while (ext2 < numberOfFiles + 10) {
257 if (renameFileNoErase(fi, fn + std::to_string(ext2) + ".FCBak")) {
258 break;
259 }
260 ext2++;
261 }
262 }
263 }
264 else {
265 // changed but simpler and solves also the delay sometimes introduced by
266 // google drive
267 while (ext2 < numberOfFiles + 10) {
268 // linux just replace the file if exists, and then the existence is to
269 // be tested before rename
270 if (renameFileNoErase(fi, fi.filePath() + std::to_string(ext2))) {
271 break;
272 }
273 ext2++;
274 }
275 }
276
277 if (ext2 >= numberOfFiles + 10) {
278 Base::Console().error(
279 "File not saved: Cannot rename project file to backup file\n");
280 // throw Base::FileException("File not saved: Cannot rename project file to
281 // backup file", fi);
282 }
283 }
284 }
285 else {
286 try {
287 fi.deleteFile();
288 }
289 catch (...) {
290 Base::Console().warning("Cannot remove backup file: %s\n",
291 fi.fileName().c_str());
292 backupManagementError = true;
293 }
294 }
295 }
296
297 Base::FileInfo tmp(sourcename);
298 if (!tmp.renameFile(targetname.c_str())) {
299 throw Base::FileException(
300 "Save interrupted: Cannot rename temporary file to project file",
301 tmp);
302 }
303
304 if (backupManagementError) {
305 throw Base::FileException(
306 "Warning: Save complete, but error while managing backup history.",
307 fi);
308 }
309 }
310
311 bool BackupPolicy::fileComparisonByDate(const Base::FileInfo& i, const Base::FileInfo& j)
312 {
313 return (i.lastModified() > j.lastModified());
314 }
315
316 bool BackupPolicy::startsWith(const std::string& st1, const std::string& st2) const
317 {
318 return st1.substr(0, st2.length()) == st2;
319 }
320
321 bool BackupPolicy::checkValidString(const std::string& cmpl, const boost::regex& e) const
322 {
323 boost::smatch what;
324 const bool res = boost::regex_search(cmpl, what, e);
325 return res;
326 }
327
328 bool BackupPolicy::checkValidComplement(const std::string& file,
329 const std::string& pbn,
330 const std::string& ext) const
331 {
332 const std::string cmpl =
333 file.substr(pbn.length(), file.length() - pbn.length() - ext.length() - 1);
334 const boost::regex e(R"(^[^.]*$)");
335 return checkValidString(cmpl, e);
336 }
337
338 bool BackupPolicy::checkDigits(const std::string& cmpl) const
339 {
340 const boost::regex e(R"(^[0-9]*$)");
341 return checkValidString(cmpl, e);
342 }
343
344 bool BackupPolicy::renameFileNoErase(Base::FileInfo fi, const std::string& newName)
345 {
346 // linux just replaces the file if it exists, so the existence is to be tested before rename
347 const Base::FileInfo nf(newName);
348 if (!nf.exists()) {
349 return fi.renameFile(newName.c_str());
350 }
351 return false;
352 }