Raw
1 #include "git-compat-util.h"
2 #include "copy.h"
3 #include "path.h"
4 #include "gettext.h"
5 #include "strbuf.h"
6 #include "abspath.h"
7
8 int copy_fd(int ifd, int ofd)
9 {
10 while (1) {
11 char buffer[8192];
12 ssize_t len = xread(ifd, buffer, sizeof(buffer));
13 if (!len)
14 break;
15 if (len < 0)
16 return COPY_READ_ERROR;
17 if (write_in_full(ofd, buffer, len) < 0)
18 return COPY_WRITE_ERROR;
19 }
20 return 0;
21 }
22
23 static int copy_times(const char *dst, const char *src)
24 {
25 struct stat st;
26 struct utimbuf times;
27 if (stat(src, &st) < 0)
28 return -1;
29 times.actime = st.st_atime;
30 times.modtime = st.st_mtime;
31 if (utime(dst, &times) < 0)
32 return -1;
33 return 0;
34 }
35
36 int copy_file(struct repository *repo,
37 const char *dst, const char *src, int mode)
38 {
39 int fdi, fdo, status;
40
41 mode = (mode & 0111) ? 0777 : 0666;
42 if ((fdi = open(src, O_RDONLY)) < 0)
43 return fdi;
44 if ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) {
45 close(fdi);
46 return fdo;
47 }
48 status = copy_fd(fdi, fdo);
49 switch (status) {
50 case COPY_READ_ERROR:
51 error_errno("copy-fd: read returned");
52 break;
53 case COPY_WRITE_ERROR:
54 error_errno("copy-fd: write returned");
55 break;
56 }
57 close(fdi);
58 if (close(fdo) != 0)
59 return error_errno("%s: close error", dst);
60
61 if (!status && adjust_shared_perm(repo, dst))
62 return -1;
63
64 return status;
65 }
66
67 int copy_file_with_time(struct repository *repo,
68 const char *dst, const char *src, int mode)
69 {
70 int status = copy_file(repo, dst, src, mode);
71 if (!status)
72 return copy_times(dst, src);
73 return status;
74 }