softwarecontainer  0.18.0-739e8d7 2017-05-04
recursivecopy.cpp
1 /*
2  * Copyright (C) 2016-2017 Pelagicore AB
3  *
4  * Permission to use, copy, modify, and/or distribute this software for
5  * any purpose with or without fee is hereby granted, provided that the
6  * above copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
9  * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
10  * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
11  * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
12  * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
13  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
14  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
15  * SOFTWARE.
16  *
17  * For further information see LICENSE
18  */
19 
20 #include "recursivecopy.h"
21 
22 #include <ftw.h>
23 #include <fstream>
24 #include <iostream>
25 #include <string>
26 
27 #include <glibmm.h>
28 
29 namespace softwarecontainer {
30 
31 std::string dstRoot;
32 std::string srcRoot;
33 
34 extern "C" int copyFile(const char*, const struct stat, int);
35 
49 int copyFile(const char* srcPath, const struct stat* sb, int typeflag)
50 {
51  std::string dstPath;
52  std::string src(srcPath);
53 
54  if (src.find(srcRoot) != std::string::npos) {
55  dstPath = buildPath(dstRoot, src.erase(0, srcRoot.length()));
56  } else {
57  dstPath = buildPath(dstRoot, src);
58  }
59 
60  switch(typeflag) {
61  case FTW_D:
62  mkdir(dstPath.c_str(), sb->st_mode);
63  break;
64  case FTW_F:
65  std::ifstream src(srcPath, std::ios::binary);
66  std::ofstream dst(dstPath, std::ios::binary);
67  dst << src.rdbuf();
68  }
69  return 0;
70 }
71 
73 {
74  static RecursiveCopy instance;
75  return instance;
76 }
77 
78 bool RecursiveCopy::copy(std::string src, std::string dst)
79 {
80  bool retval = true;
81  m_copyLock.lock();
82  dstRoot.assign(dst);
83  srcRoot.assign(src);
84  if (ftw(src.c_str(), copyFile, 20) != 0) {
85  log_error() << "Failed to recursively copy " << src << " to " << dst;
86  retval = false;
87  }
88  m_copyLock.unlock();
89 
90  return retval;
91 }
92 
93 RecursiveCopy::RecursiveCopy() {}
94 RecursiveCopy::~RecursiveCopy() {}
95 
96 } // namespace softwarecontainer
The RecursiveCopy class is a singleton class used to copy files recursively from a source to a destin...
Definition: recursivecopy.h:29
static RecursiveCopy & getInstance()
getInstance Gets the RecursiveCopy instance.
bool copy(std::string src, std::string dst)
copy Copy files from src to dst
Developers guide to adding a config item: