]> git.tdb.fi Git - builder.git/blob - source/copy.cpp
eea40fcdae6eda6f63dc30f09988736fa88a7fbc
[builder.git] / source / copy.cpp
1 /* $Id$
2
3 This file is part of builder
4 Copyright © 2006-2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #include <errno.h>
9 #include <fstream>
10 #include <iostream>
11 #include <msp/path/utils.h>
12 #include "builder.h"
13 #include "copy.h"
14 #include "package.h"
15
16 using namespace std;
17 using namespace Msp;
18
19 Copy::Copy(Builder &b, const Package &pkg, const Path::Path &s, const Path::Path &d):
20         InternalAction(b),
21         src(s),
22         dest(d)
23 {
24         announce(pkg.get_name(), "COPY", dest[-1]);
25         if(builder.get_verbose()>=2)
26                 cout<<s<<" -> "<<d<<'\n';
27
28         if(!builder.get_dry_run())
29                 worker=new Worker(*this);
30 }
31
32
33 Copy::Worker::Worker(Copy &c):
34         copy(c)
35 {
36         launch();
37 }
38
39 void Copy::Worker::main()
40 {
41         Path::mkpath(copy.dest.subpath(0, copy.dest.size()-1), 0755);
42
43         // Remove old file.  Not doing this would cause Bad Stuff when installing libraries.
44         if(unlink(copy.dest.str().c_str())<0 && errno!=ENOENT)
45         {
46                 int err=errno;
47                 cerr<<"Can't unlink "<<copy.dest<<": "<<strerror(err)<<'\n';
48                 done=error=true;
49                 return;
50         }
51
52         ifstream in(copy.src.str().c_str());
53         if(!in)
54         {
55                 cerr<<"Can't open "<<copy.src<<" for reading\n";
56                 done=error=true;
57                 return;
58         }
59
60         ofstream out(copy.dest.str().c_str());
61         if(!out)
62         {
63                 cerr<<"Can't open "<<copy.dest<<" for writing\n";
64                 done=error=true;
65                 return;
66         }
67
68         // Actual transfer loop
69         char buf[16384];
70         while(!in.eof())
71         {
72                 in.read(buf, sizeof(buf));
73                 out.write(buf, in.gcount());
74         }
75
76         // Preserve file permissions
77         struct stat st;
78         Path::stat(copy.src, st);
79         chmod(copy.dest.str().c_str(), st.st_mode&0777);
80
81         done=true;
82 }