]> git.tdb.fi Git - builder.git/blob - source/copy.cpp
f7dab415920d09b2bf41374d7e9de6b7ef730588
[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
14 using namespace std;
15 using namespace Msp;
16
17 Copy::Copy(Builder &b):
18         Tool(b, "CP")
19 { }
20
21 Target *Copy::create_target(const vector<Target *> &sources, const string &arg)
22 {
23         FileTarget &file_tgt = dynamic_cast<FileTarget &>(*sources.front());
24         InstalledFile *inst = new InstalledFile(builder, *file_tgt.get_package(), file_tgt, arg);
25         inst->set_tool(*this);
26         return inst;
27 }
28
29 Task *Copy::run(const Target &target) const
30 {
31         const InstalledFile &install = dynamic_cast<const InstalledFile &>(target);
32         Worker *worker = new Worker(install);
33         InternalTask *task = new InternalTask(worker);
34         task->add_file(install.get_path());
35         task->set_unlink();
36         return task;
37 }
38
39
40 Copy::Worker::Worker(const InstalledFile &t):
41         target(t)
42 { }
43
44 void Copy::Worker::main()
45 {
46         const FileTarget &source = target.get_source();
47         const FS::Path &src_path = source.get_path();
48         const FS::Path &dst_path = target.get_path();
49
50         try
51         {
52                 IO::File in(src_path.str());
53                 IO::File out(dst_path.str(), IO::M_WRITE);
54
55                 // Actual transfer loop
56                 char buf[16384];
57                 while(!in.eof())
58                 {
59                         unsigned len = in.read(buf, sizeof(buf));
60                         out.write(buf, len);
61                 }
62         }
63         catch(const exception &e)
64         {
65                 IO::print(IO::cerr, "%s\n", e.what());
66                 status = Task::ERROR;
67                 return;
68         }
69
70 #ifndef _WIN32
71         // Preserve file permissions
72         struct stat st;
73         if(stat(src_path.str().c_str(), &st)==0)
74                 chmod(dst_path.str().c_str(), st.st_mode&0777);
75
76         const FS::Path &link = target.get_symlink();
77         if(!link.empty())
78         {
79                 FS::Path relpath = FS::relative(dst_path, FS::dirname(link));
80                 if(FS::exists(link))
81                         FS::unlink(link);
82                 symlink(relpath.str().c_str(), link.str().c_str());
83         }
84 #endif
85
86         status = Task::SUCCESS;
87 }