]> git.tdb.fi Git - builder.git/blob - source/copy.cpp
31e62100d9751d991a0bf59529dd7699973e8ac5
[builder.git] / source / copy.cpp
1 #ifndef _WIN32
2 #include <unistd.h>
3 #include <sys/stat.h>
4 #endif
5 #include <msp/fs/dir.h>
6 #include <msp/fs/stat.h>
7 #include <msp/fs/utils.h>
8 #include <msp/io/file.h>
9 #include <msp/io/print.h>
10 #include "builder.h"
11 #include "copy.h"
12 #include "installedfile.h"
13 #include "internaltask.h"
14
15 using namespace std;
16 using namespace Msp;
17
18 Target *Copy::create_target(const vector<Target *> &sources, const string &arg)
19 {
20         FileTarget &file_tgt = dynamic_cast<FileTarget &>(*sources.front());
21         InstalledFile *inst = new InstalledFile(builder, *file_tgt.get_package(), file_tgt, arg);
22         inst->set_tool(*this);
23         return inst;
24 }
25
26 Task *Copy::run(const Target &target) const
27 {
28         const InstalledFile &install = dynamic_cast<const InstalledFile &>(target);
29         InternalTask *task = new InternalTask([&install]{ return _run(install); });
30         task->add_file(install.get_path());
31         task->set_unlink();
32         return task;
33 }
34
35 bool Copy::_run(const InstalledFile &install)
36 {
37         const FileTarget &source = install.get_source();
38         const FS::Path &src_path = source.get_path();
39         const FS::Path &dst_path = install.get_path();
40
41         try
42         {
43                 IO::File in(src_path.str());
44                 IO::File out(dst_path.str(), IO::M_WRITE);
45
46                 // Actual transfer loop
47                 char buf[16384];
48                 while(!in.eof())
49                 {
50                         unsigned len = in.read(buf, sizeof(buf));
51                         out.write(buf, len);
52                 }
53         }
54         catch(const exception &e)
55         {
56                 IO::print(IO::cerr, "%s\n", e.what());
57                 return false;
58         }
59
60 #ifndef _WIN32
61         // Preserve file permissions
62         struct stat st;
63         if(stat(src_path.str().c_str(), &st)==0)
64                 chmod(dst_path.str().c_str(), st.st_mode&0777);
65
66         const FS::Path &link = install.get_symlink();
67         if(!link.empty())
68         {
69                 FS::Path relpath = FS::relative(dst_path, FS::dirname(link));
70                 if(FS::exists(link))
71                         FS::unlink(link);
72                 symlink(relpath.str().c_str(), link.str().c_str());
73         }
74 #endif
75
76         return true;
77 }