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