Parcourir la source

Add ctk::copyDirRecursively

* Note that a class names ctkTemporaryDir could probably be created to
easily delete directories created within the test. The directory would
basically be recursively deleted when the object would go out of scope.
Jean-Christophe Fillion-Robin il y a 13 ans
Parent
commit
c98fede305

+ 2 - 0
Libs/Core/Testing/Cpp/CMakeLists.txt

@@ -38,6 +38,7 @@ set(KITTests_SRCS
   ctkModelTesterTest1.cpp
   ctkModelTesterTest2.cpp
   ctkUtilsClosestPowerOfTenTest1.cpp
+  ctkUtilsCopyDirRecursivelyTest1.cpp
   ctkUtilsOrderOfMagnitudeTest1.cpp
   ctkUtilsQtHandleToStringTest1.cpp
   ctkUtilsSignificantDecimalsTest1.cpp
@@ -153,6 +154,7 @@ SIMPLE_TEST( ctkTransferFunctionTest1 )
 SIMPLE_TEST( ctkTransferFunctionRepresentationTest1 )
 SIMPLE_TEST( ctkTransferFunctionRepresentationTest2 )
 SIMPLE_TEST( ctkUtilsClosestPowerOfTenTest1 )
+SIMPLE_TEST( ctkUtilsCopyDirRecursivelyTest1 )
 SIMPLE_TEST( ctkUtilsOrderOfMagnitudeTest1 )
 SIMPLE_TEST( ctkUtilsQtHandleToStringTest1 )
 SIMPLE_TEST( ctkUtilsSignificantDecimalsTest1 )

+ 142 - 0
Libs/Core/Testing/Cpp/ctkUtilsCopyDirRecursivelyTest1.cpp

@@ -0,0 +1,142 @@
+/*=========================================================================
+
+  Library:   CTK
+
+  Copyright (c) Kitware Inc.
+
+  Licensed under the Apache License, Version 2.0 (the "License");
+  you may not use this file except in compliance with the License.
+  You may obtain a copy of the License at
+
+      http://www.commontk.org/LICENSE
+
+  Unless required by applicable law or agreed to in writing, software
+  distributed under the License is distributed on an "AS IS" BASIS,
+  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  See the License for the specific language governing permissions and
+  limitations under the License.
+
+=========================================================================*/
+
+// Qt includes
+#include <QDebug>
+#include <QDir>
+#include <QTextStream>
+#include <QTime>
+
+// CTK includes
+#include "ctkUtils.h"
+
+// STD includes
+#include <cstdlib>
+#include <iostream>
+
+namespace
+{
+//-----------------------------------------------------------------------------
+bool createFile(int line, const QDir& dir, const QString& relativePath, const QString& fileName)
+{
+  QDir newDir(dir);
+  newDir.mkpath(relativePath);
+  newDir.cd(relativePath);
+  QString filePath = QFileInfo(newDir, fileName).filePath();
+  QFile file(filePath);
+  file.open(QIODevice::Text | QIODevice::WriteOnly);
+  QTextStream out(&file);
+  out << "Generated by ctkUtilsCopyDirRecursivelyTest1" << endl;
+  file.close();
+
+  if (!QFile::exists(filePath))
+    {
+    std::cerr << "Line " << line << " - Failed to create file" << qPrintable(filePath) << std::endl;
+    return false;
+    }
+
+  return true;
+}
+
+} // end of anonymous namespace
+
+
+//-----------------------------------------------------------------------------
+int ctkUtilsCopyDirRecursivelyTest1(int argc, char * argv [] )
+{
+  Q_UNUSED(argc);
+  Q_UNUSED(argv);
+
+  // --------------------------------------------------------------------------
+  // Test copyDirRecursively(const QString &srcPath, const QString &dstPath);
+  // --------------------------------------------------------------------------
+
+  QDir tmp = QDir::temp();
+  QString temporaryDirName =
+      QString("ctkUtilsCopyDirRecursivelyTest1.%1").arg(QTime::currentTime().toString("hhmmsszzz"));
+
+  {
+  // Attempt to copy nonexistent relative directory
+  QString nonexistentRelativeDirPath = temporaryDirName;
+  if (ctk::copyDirRecursively(nonexistentRelativeDirPath, tmp.absolutePath()))
+    {
+    std::cerr << "Line " << __LINE__ << " - Problem with ctk::copyDirRecursively() !"
+              << " - It should fail to copy nonexistent directory: " <<
+              qPrintable(nonexistentRelativeDirPath)<< std::endl;
+    return EXIT_FAILURE;
+    }
+  }
+
+  {
+  // Attempt to copy nonexistent absolute directory
+  QString nonexistentAbsoluteDirPath = tmp.absolutePath() + "/" + temporaryDirName;
+  if (ctk::copyDirRecursively(nonexistentAbsoluteDirPath, tmp.absolutePath()))
+    {
+    std::cerr << "Line " << __LINE__ << " - Problem with ctk::copyDirRecursively() !"
+              << " - It should fail to delete nonexistent directory: " <<
+              qPrintable(nonexistentAbsoluteDirPath)<< std::endl;
+    return EXIT_FAILURE;
+    }
+  }
+
+  // Create a directory structure
+  tmp.mkdir(temporaryDirName);
+  tmp.cd(temporaryDirName);
+  if (!createFile(__LINE__, tmp, "foo", "a.txt"))
+    {
+    return EXIT_FAILURE;
+    }
+  if (!createFile(__LINE__, tmp, "foo/bar", "b.txt"))
+    {
+    return EXIT_FAILURE;
+    }
+  if (!createFile(__LINE__, tmp, "foo/zoo", "c.txt"))
+    {
+    return EXIT_FAILURE;
+    }
+
+  {
+  QString srcPath(tmp.path() + "/foo");
+  QString destPath(tmp.path() + "/dest");
+  if (!ctk::copyDirRecursively(srcPath, destPath))
+    {
+    std::cerr << "Line " << __LINE__ << " - Problem with ctk::copyDirRecursively()"
+              << " - Failed to copy directory: " << qPrintable(srcPath)
+              << "into" << qPrintable(destPath) << std::endl;
+    return EXIT_FAILURE;
+    }
+  }
+
+  {
+  // Atempt to copy a directory into itself
+  QString srcPath(tmp.path());
+  QString destPath(tmp.path() + "/dest");
+  if (ctk::copyDirRecursively(srcPath, destPath))
+    {
+    std::cerr << "Line " << __LINE__ << " - Problem with ctk::copyDirRecursively()"
+              << " - Copy of directory: " << qPrintable(srcPath)
+              << "into itself " << qPrintable(destPath)
+              << " should fail !" << std::endl;
+    return EXIT_FAILURE;
+    }
+  }
+
+  return EXIT_SUCCESS;
+}

+ 52 - 0
Libs/Core/ctkUtils.cpp

@@ -307,6 +307,58 @@ bool ctk::removeDirRecursively(const QString & dirName)
 }
 
 //-----------------------------------------------------------------------------
+bool ctk::copyDirRecursively(const QString &srcPath, const QString &dstPath)
+{
+  // See http://stackoverflow.com/questions/2536524/copy-directory-using-qt
+  if (!QFile::exists(srcPath))
+    {
+    qCritical() << "ctk::copyDirRecursively: Failed to copy nonexistent directory" << srcPath;
+    return false;
+    }
+
+  QDir srcDir(srcPath);
+  if (!srcDir.relativeFilePath(dstPath).startsWith(".."))
+    {
+    qCritical() << "ctk::copyDirRecursively: Cannot copy directory" << srcPath << "into itself" << dstPath;
+    return false;
+    }
+
+
+  QDir parentDstDir(QFileInfo(dstPath).path());
+  if (!QFile::exists(dstPath) && !parentDstDir.mkdir(QFileInfo(dstPath).fileName()))
+    {
+    qCritical() << "ctk::copyDirRecursively: Failed to create destination directory" << QFileInfo(dstPath).fileName();
+    return false;
+    }
+
+  foreach(const QFileInfo &info, srcDir.entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot))
+    {
+    QString srcItemPath = srcPath + "/" + info.fileName();
+    QString dstItemPath = dstPath + "/" + info.fileName();
+    if (info.isDir())
+      {
+      if (!ctk::copyDirRecursively(srcItemPath, dstItemPath))
+        {
+        qCritical() << "ctk::copyDirRecursively: Failed to copy files from " << srcItemPath << " into " << dstItemPath;
+        return false;
+        }
+      }
+    else if (info.isFile())
+      {
+      if (!QFile::copy(srcItemPath, dstItemPath))
+        {
+        return false;
+        }
+      }
+    else
+      {
+      qWarning() << "ctk::copyDirRecursively: Unhandled item" << info.filePath();
+      }
+    }
+  return true;
+}
+
+//-----------------------------------------------------------------------------
 QString ctk::qtHandleToString(Qt::HANDLE handle)
 {
   QString str;

+ 10 - 0
Libs/Core/ctkUtils.h

@@ -117,6 +117,16 @@ double CTK_CORE_EXPORT closestPowerOfTen(double value);
 /// \sa QDir::rmdir
 bool CTK_CORE_EXPORT removeDirRecursively(const QString & dirName);
 
+
+///
+/// \ingroup Core
+/// Copy a directory recursively
+/// \param srcPath The directory to be copied
+/// \param dstPath The directory where the file should be copied
+/// \return <code>true</code> on success, <code>false</code> otherwise.
+/// \sa QFile::copy
+bool CTK_CORE_EXPORT copyDirRecursively(const QString &srcPath, const QString &dstPath);
+
 ///
 /// \ingroup Core
 /// Convert Qt::HANDLE to string