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