| 117 | } |
| 118 | |
| 119 | bool BackupFiles(const std::string &filename, bool remove_file) { |
| 120 | if (filename.empty()) { |
| 121 | LOG_ERROR() << "File name is empty. Illegal use of function"; |
| 122 | return false; |
| 123 | } |
| 124 | |
| 125 | try { |
| 126 | const std::filesystem::path full(filename); |
| 127 | const std::filesystem::path parent(full.parent_path()); |
| 128 | const std::filesystem::path stem(full.stem()); |
| 129 | const std::filesystem::path ext(full.extension()); |
| 130 | if (!std::filesystem::exists(full)) { |
| 131 | return true; // No meaning to back up if original doesn't exist. |
| 132 | } |
| 133 | // shift all file xxx_N -> xxx_N-1 and last xxx -> xxx_0 |
| 134 | for (int ii = 9; ii >= 0; --ii) { |
| 135 | std::ostringstream temp1; |
| 136 | temp1 << stem.string() << "_" << ii << ext.string(); |
| 137 | |
| 138 | std::filesystem::path file1(parent); |
| 139 | file1.append(temp1.str()); |
| 140 | if (std::filesystem::exists(file1) && ii == 9) { |
| 141 | std::filesystem::remove(file1); |
| 142 | } |
| 143 | if (ii == 0) { |
| 144 | if (remove_file) { |
| 145 | std::filesystem::rename(full, file1); |
| 146 | } else { |
| 147 | std::filesystem::copy(full, file1); |
| 148 | } |
| 149 | } else { |
| 150 | std::ostringstream temp2; |
| 151 | temp2 << stem.string() << "_" << ii - 1 << ext.string(); |
| 152 | std::filesystem::path file2(parent); |
| 153 | file2.append(temp2.str()); |
| 154 | if (std::filesystem::exists(file2)) { |
| 155 | std::filesystem::rename(file2, file1); |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | } catch (const std::exception &error) { |
| 160 | LOG_ERROR() << "Backup of file failed. Error: " << error.what() |
| 161 | << ", File: " << filename; |
| 162 | return false; |
| 163 | } |
| 164 | return true; |
| 165 | } |
| 166 | |
| 167 | } // namespace util::log |
no test coverage detected