1
0

fileutils.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. #include "fileutils.h"
  2. #include <QFile>
  3. #include <QMimeDatabase>
  4. #include <QDateTime>
  5. #include <QTemporaryFile>
  6. #include <QJsonDocument>
  7. #include <core/exception.h>
  8. #include <core/global.h>
  9. #include "pathutils.h"
  10. using namespace vnotex;
  11. QByteArray FileUtils::readFile(const QString &p_filePath)
  12. {
  13. QFile file(p_filePath);
  14. if (!file.open(QIODevice::ReadOnly)) {
  15. Exception::throwOne(Exception::Type::FailToReadFile,
  16. QString("failed to read file: %1").arg(p_filePath));
  17. }
  18. return file.readAll();
  19. }
  20. QString FileUtils::readTextFile(const QString &p_filePath)
  21. {
  22. QFile file(p_filePath);
  23. if (!file.open(QIODevice::ReadOnly)) {
  24. Exception::throwOne(Exception::Type::FailToReadFile,
  25. QString("failed to read file: %1").arg(p_filePath));
  26. }
  27. // TODO: determine the encoding of the text.
  28. QString text(file.readAll());
  29. file.close();
  30. return text;
  31. }
  32. QJsonObject FileUtils::readJsonFile(const QString &p_filePath)
  33. {
  34. return QJsonDocument::fromJson(readFile(p_filePath)).object();
  35. }
  36. void FileUtils::writeFile(const QString &p_filePath, const QByteArray &p_data)
  37. {
  38. QFile file(p_filePath);
  39. if (!file.open(QIODevice::WriteOnly)) {
  40. Exception::throwOne(Exception::Type::FailToWriteFile,
  41. QString("failed to write to file: %1").arg(p_filePath));
  42. }
  43. file.write(p_data);
  44. file.close();
  45. }
  46. void FileUtils::writeFile(const QString &p_filePath, const QString &p_text)
  47. {
  48. QFile file(p_filePath);
  49. if (!file.open(QIODevice::WriteOnly)) {
  50. Exception::throwOne(Exception::Type::FailToWriteFile,
  51. QString("failed to write to file: %1").arg(p_filePath));
  52. }
  53. QTextStream stream(&file);
  54. stream << p_text;
  55. file.close();
  56. }
  57. void FileUtils::writeFile(const QString &p_filePath, const QJsonObject &p_jobj)
  58. {
  59. writeFile(p_filePath, QJsonDocument(p_jobj).toJson());
  60. }
  61. void FileUtils::renameFile(const QString &p_path, const QString &p_name)
  62. {
  63. Q_ASSERT(PathUtils::isLegalFileName(p_name));
  64. QString newFilePath(PathUtils::concatenateFilePath(PathUtils::parentDirPath(p_path), p_name));
  65. QFile file(p_path);
  66. if (!file.exists() || !file.rename(newFilePath)) {
  67. Exception::throwOne(Exception::Type::FailToRenameFile,
  68. QString("failed to rename file: %1").arg(p_path));
  69. }
  70. }
  71. bool FileUtils::childExistsCaseInsensitive(const QString &p_dirPath, const QString &p_name)
  72. {
  73. QDir dir(p_dirPath);
  74. if (!dir.exists()) {
  75. return false;
  76. }
  77. auto name = p_name.toLower();
  78. auto children = dir.entryList(QDir::Dirs | QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot);
  79. for (const auto &child : children) {
  80. if (child.toLower() == name) {
  81. return true;
  82. }
  83. }
  84. return false;
  85. }
  86. bool FileUtils::existsCaseInsensitive(const QString &p_path)
  87. {
  88. return childExistsCaseInsensitive(PathUtils::parentDirPath(p_path), PathUtils::fileName(p_path));
  89. }
  90. void FileUtils::copyFile(const QString &p_filePath,
  91. const QString &p_destPath,
  92. bool p_move)
  93. {
  94. if (PathUtils::areSamePaths(p_filePath, p_destPath)) {
  95. return;
  96. }
  97. QDir dir;
  98. if (!dir.mkpath(PathUtils::parentDirPath(p_destPath))) {
  99. Exception::throwOne(Exception::Type::FailToCreateDir,
  100. QString("failed to create directory: %1").arg(PathUtils::parentDirPath(p_destPath)));
  101. }
  102. bool failed = false;
  103. if (p_move) {
  104. QFile file(p_filePath);
  105. if (!file.rename(p_destPath)) {
  106. failed = true;
  107. }
  108. } else {
  109. if (!QFile::copy(p_filePath, p_destPath)) {
  110. failed = true;
  111. }
  112. }
  113. if (failed) {
  114. Exception::throwOne(Exception::Type::FailToCopyFile,
  115. QString("failed to copy file: %1 %2").arg(p_filePath, p_destPath));
  116. }
  117. }
  118. void FileUtils::copyDir(const QString &p_dirPath,
  119. const QString &p_destPath,
  120. bool p_move)
  121. {
  122. if (PathUtils::areSamePaths(p_dirPath, p_destPath)) {
  123. return;
  124. }
  125. if (QFileInfo::exists(p_destPath)) {
  126. Exception::throwOne(Exception::Type::FailToCopyDir,
  127. QString("target directory %1 already exists").arg(p_destPath));
  128. }
  129. // QDir.rename() could not move directory across dirves.
  130. // Create target directory.
  131. QDir destDir(p_destPath);
  132. if (!destDir.mkpath(p_destPath)) {
  133. Exception::throwOne(Exception::Type::FailToCreateDir,
  134. QString("failed to create directory: %1").arg(p_destPath));
  135. }
  136. // Copy directory contents recursively.
  137. QDir srcDir(p_dirPath);
  138. auto nodes = srcDir.entryInfoList(QDir::Dirs
  139. | QDir::Files
  140. | QDir::Hidden
  141. | QDir::NoSymLinks
  142. | QDir::NoDotAndDotDot);
  143. for (const auto &node : nodes) {
  144. auto name = node.fileName();
  145. if (node.isDir()) {
  146. copyDir(srcDir.filePath(name), destDir.filePath(name), p_move);
  147. } else {
  148. Q_ASSERT(node.isFile());
  149. copyFile(srcDir.filePath(name), destDir.filePath(name), p_move);
  150. }
  151. }
  152. if (p_move) {
  153. if (!destDir.rmdir(p_dirPath)) {
  154. Exception::throwOne(Exception::Type::FailToRemoveDir,
  155. QString("failed to remove source directory after move: %1").arg(p_dirPath));
  156. }
  157. }
  158. }
  159. QString FileUtils::renameIfExistsCaseInsensitive(const QString &p_path)
  160. {
  161. QFileInfo fi(p_path);
  162. auto dirPath = fi.absolutePath();
  163. auto baseName = fi.completeBaseName();
  164. auto suffix = fi.suffix();
  165. auto name = fi.fileName();
  166. int idx = 1;
  167. while (childExistsCaseInsensitive(dirPath, name)) {
  168. name = QString("%1_%2").arg(baseName, QString::number(idx));
  169. if (!suffix.isEmpty()) {
  170. name += QStringLiteral(".") + suffix;
  171. }
  172. ++idx;
  173. }
  174. return PathUtils::concatenateFilePath(dirPath, name);
  175. }
  176. void FileUtils::removeFile(const QString &p_filePath)
  177. {
  178. Q_ASSERT(!QFileInfo::exists(p_filePath) || QFileInfo(p_filePath).isFile());
  179. QFile file(p_filePath);
  180. if (!file.remove()) {
  181. Exception::throwOne(Exception::Type::FailToRemoveFile,
  182. QString("failed to remove file: %1").arg(p_filePath));
  183. }
  184. }
  185. bool FileUtils::removeDirIfEmpty(const QString &p_dirPath)
  186. {
  187. QDir dir(p_dirPath);
  188. if (!dir.isEmpty()) {
  189. return false;
  190. }
  191. if (!dir.rmdir(p_dirPath)) {
  192. Exception::throwOne(Exception::Type::FailToRemoveFile,
  193. QString("failed to remove directory: %1").arg(p_dirPath));
  194. return false;
  195. }
  196. return true;
  197. }
  198. void FileUtils::removeDir(const QString &p_dirPath)
  199. {
  200. QDir dir(p_dirPath);
  201. if (!dir.removeRecursively()) {
  202. Exception::throwOne(Exception::Type::FailToRemoveFile,
  203. QString("failed to remove directory recursively: %1").arg(p_dirPath));
  204. }
  205. }
  206. bool FileUtils::isPlatformNameCaseSensitive()
  207. {
  208. #if defined(Q_OS_WIN)
  209. return false;
  210. #else
  211. return true;
  212. #endif
  213. }
  214. bool FileUtils::isText(const QString &p_filePath)
  215. {
  216. QMimeDatabase mimeDatabase;
  217. auto mimeType = mimeDatabase.mimeTypeForFile(p_filePath);
  218. const auto name = mimeType.name();
  219. if (name.startsWith(QStringLiteral("text/")) || name == QStringLiteral("application/x-zerosize")) {
  220. return true;
  221. }
  222. return mimeType.inherits(QStringLiteral("text/plain"));
  223. }
  224. bool FileUtils::isImage(const QString &p_filePath)
  225. {
  226. QMimeDatabase mimeDatabase;
  227. auto mimeType = mimeDatabase.mimeTypeForFile(p_filePath);
  228. if (mimeType.name().startsWith(QStringLiteral("image/"))) {
  229. return true;
  230. }
  231. return false;
  232. }
  233. QImage FileUtils::imageFromFile(const QString &p_filePath)
  234. {
  235. QImage img(p_filePath);
  236. if (!img.isNull()) {
  237. return img;
  238. }
  239. // @p_filePath may has a wrong suffix which indicates a wrong image format.
  240. img.loadFromData(readFile(p_filePath));
  241. return img;
  242. }
  243. QPixmap FileUtils::pixmapFromFile(const QString &p_filePath)
  244. {
  245. QPixmap pixmap;
  246. pixmap.loadFromData(readFile(p_filePath));
  247. return pixmap;
  248. }
  249. QString FileUtils::generateUniqueFileName(const QString &p_folderPath,
  250. const QString &p_hints,
  251. const QString &p_suffix)
  252. {
  253. auto fileName = generateRandomFileName(p_hints, p_suffix);
  254. int suffixIdx = fileName.lastIndexOf(QLatin1Char('.'));
  255. auto baseName = suffixIdx == -1 ? fileName : fileName.left(suffixIdx);
  256. auto suffix = suffixIdx == -1 ? QStringLiteral("") : fileName.mid(suffixIdx);
  257. int index = 1;
  258. while (childExistsCaseInsensitive(p_folderPath, fileName)) {
  259. fileName = QString("%1_%2%3").arg(baseName, QString::number(index++), suffix);
  260. }
  261. return fileName;
  262. }
  263. QString FileUtils::generateRandomFileName(const QString &p_hints, const QString &p_suffix)
  264. {
  265. Q_UNUSED(p_hints);
  266. // Do not use toSecsSinceEpoch() here since we want a short name.
  267. const QString timeStamp(QDateTime::currentDateTime().toString(QStringLiteral("sszzzmmHHyyMMdd")));
  268. const QString baseName(QString::number(timeStamp.toLongLong() + qrand()));
  269. QString suffix;
  270. if (!p_suffix.isEmpty()) {
  271. suffix = QLatin1Char('.') + p_suffix.toLower();
  272. }
  273. return baseName + suffix;
  274. }
  275. QTemporaryFile *FileUtils::createTemporaryFile(const QString &p_suffix)
  276. {
  277. QString xx = p_suffix.isEmpty() ? QStringLiteral("XXXXXX") : QStringLiteral("XXXXXX.");
  278. return new QTemporaryFile(QDir::tempPath() + QDir::separator() + xx + p_suffix);
  279. }
  280. QString FileUtils::generateFileNameWithSequence(const QString &p_folderPath,
  281. const QString &p_baseName,
  282. const QString &p_suffix)
  283. {
  284. auto fileName = p_suffix.isEmpty() ? p_baseName : p_baseName + QLatin1Char('.') + p_suffix;
  285. auto suffix = p_suffix.isEmpty() ? QString() : QStringLiteral(".") + p_suffix;
  286. int index = 1;
  287. while (childExistsCaseInsensitive(p_folderPath, fileName)) {
  288. fileName = QString("%1_%2%3").arg(p_baseName, QString::number(index++), suffix);
  289. }
  290. return fileName;
  291. }
  292. void FileUtils::removeEmptyDir(const QString &p_dirPath)
  293. {
  294. QDir dir(p_dirPath);
  295. if (dir.isEmpty()) {
  296. return;
  297. }
  298. auto childDirs = dir.entryInfoList(QDir::AllDirs | QDir::NoDotAndDotDot | QDir::NoSymLinks);
  299. for (const auto &child : childDirs) {
  300. const auto childPath = child.absoluteFilePath();
  301. removeEmptyDir(childPath);
  302. removeDirIfEmpty(childPath);
  303. }
  304. }
  305. QStringList FileUtils::entryListRecursively(const QString &p_dirPath,
  306. const QStringList &p_nameFilters,
  307. QDir::Filters p_filters)
  308. {
  309. QStringList entries;
  310. QDir dir(p_dirPath);
  311. if (!dir.exists()) {
  312. return entries;
  313. }
  314. const auto curEntries = dir.entryList(p_nameFilters, p_filters | QDir::NoDotAndDotDot);
  315. for (const auto &e : curEntries) {
  316. entries.append(PathUtils::concatenateFilePath(p_dirPath, e));
  317. }
  318. const auto subdirs = dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot);
  319. for (const auto &subdir : subdirs) {
  320. const auto dirPath = PathUtils::concatenateFilePath(p_dirPath, subdir);
  321. entries.append(entryListRecursively(dirPath, p_nameFilters, p_filters));
  322. }
  323. return entries;
  324. }