Merge branch 'ta/config-add-to-empty-or-true-fix' into jch
[git/jrn.git] / copy.c
blob5cb8679f939b4dfe8e90cb80115d847bf7230f8a
1 #include "cache.h"
3 int copy_fd(int ifd, int ofd)
5 while (1) {
6 char buffer[8192];
7 char *buf = buffer;
8 ssize_t len = xread(ifd, buffer, sizeof(buffer));
9 if (!len)
10 break;
11 if (len < 0) {
12 int save_errno = errno;
13 close(ifd);
14 error("copy-fd: read returned %s",
15 strerror(save_errno));
16 errno = save_errno;
17 return -1;
19 while (len) {
20 int written = xwrite(ofd, buf, len);
21 if (written > 0) {
22 buf += written;
23 len -= written;
25 else if (!written) {
26 close(ifd);
27 error("copy-fd: write returned 0");
28 errno = EAGAIN;
29 return -1;
30 } else {
31 int save_errno = errno;
32 close(ifd);
33 error("copy-fd: write returned %s",
34 strerror(save_errno));
35 errno = save_errno;
36 return -1;
40 close(ifd);
41 return 0;
44 static int copy_times(const char *dst, const char *src)
46 struct stat st;
47 struct utimbuf times;
48 if (stat(src, &st) < 0)
49 return -1;
50 times.actime = st.st_atime;
51 times.modtime = st.st_mtime;
52 if (utime(dst, &times) < 0)
53 return -1;
54 return 0;
57 int copy_file(const char *dst, const char *src, int mode)
59 int fdi, fdo, status;
61 mode = (mode & 0111) ? 0777 : 0666;
62 if ((fdi = open(src, O_RDONLY)) < 0)
63 return fdi;
64 if ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) {
65 close(fdi);
66 return fdo;
68 status = copy_fd(fdi, fdo);
69 if (close(fdo) != 0)
70 return error("%s: close error: %s", dst, strerror(errno));
72 if (!status && adjust_shared_perm(dst))
73 return -1;
75 return status;
78 int copy_file_with_time(const char *dst, const char *src, int mode)
80 int status = copy_file(dst, src, mode);
81 if (!status)
82 return copy_times(dst, src);
83 return status;