blob: 4de6a110f0912d81def3f2dd4ffd6ddc9bc30d2f [file] [log] [blame]
Junio C Hamanof3123c42005-10-22 01:28:13 -07001#include "cache.h"
2
3int copy_fd(int ifd, int ofd)
4{
5 while (1) {
Junio C Hamanof3123c42005-10-22 01:28:13 -07006 char buffer[8192];
Johan Herland8a912bc2007-05-15 14:49:22 +02007 ssize_t len = xread(ifd, buffer, sizeof(buffer));
Junio C Hamanof3123c42005-10-22 01:28:13 -07008 if (!len)
9 break;
Junio C Hamano00b7cbf2015-05-19 10:55:16 -070010 if (len < 0)
11 return COPY_READ_ERROR;
Steffen Prohaskab29763a2014-08-26 17:23:24 +020012 if (write_in_full(ofd, buffer, len) < 0)
Junio C Hamano00b7cbf2015-05-19 10:55:16 -070013 return COPY_WRITE_ERROR;
Junio C Hamanof3123c42005-10-22 01:28:13 -070014 }
Junio C Hamanof3123c42005-10-22 01:28:13 -070015 return 0;
16}
Daniel Barkalow1468bd42008-02-25 14:24:48 -050017
Clemens Buchacherf7835a22009-09-12 11:03:48 +020018static int copy_times(const char *dst, const char *src)
19{
20 struct stat st;
21 struct utimbuf times;
22 if (stat(src, &st) < 0)
23 return -1;
24 times.actime = st.st_atime;
25 times.modtime = st.st_mtime;
26 if (utime(dst, &times) < 0)
27 return -1;
28 return 0;
29}
30
Daniel Barkalow1468bd42008-02-25 14:24:48 -050031int copy_file(const char *dst, const char *src, int mode)
32{
33 int fdi, fdo, status;
34
35 mode = (mode & 0111) ? 0777 : 0666;
36 if ((fdi = open(src, O_RDONLY)) < 0)
37 return fdi;
38 if ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) {
39 close(fdi);
40 return fdo;
41 }
42 status = copy_fd(fdi, fdo);
Junio C Hamano00b7cbf2015-05-19 10:55:16 -070043 switch (status) {
44 case COPY_READ_ERROR:
Nguyễn Thái Ngọc Duy37653a12016-05-08 16:47:40 +070045 error_errno("copy-fd: read returned");
Junio C Hamano00b7cbf2015-05-19 10:55:16 -070046 break;
47 case COPY_WRITE_ERROR:
Nguyễn Thái Ngọc Duy37653a12016-05-08 16:47:40 +070048 error_errno("copy-fd: write returned");
Junio C Hamano00b7cbf2015-05-19 10:55:16 -070049 break;
50 }
Steffen Prohaskab29763a2014-08-26 17:23:24 +020051 close(fdi);
Daniel Barkalow1468bd42008-02-25 14:24:48 -050052 if (close(fdo) != 0)
Nguyễn Thái Ngọc Duy37653a12016-05-08 16:47:40 +070053 return error_errno("%s: close error", dst);
Daniel Barkalow1468bd42008-02-25 14:24:48 -050054
55 if (!status && adjust_shared_perm(dst))
56 return -1;
57
58 return status;
59}
Clemens Buchacherf7835a22009-09-12 11:03:48 +020060
61int copy_file_with_time(const char *dst, const char *src, int mode)
62{
63 int status = copy_file(dst, src, mode);
64 if (!status)
65 return copy_times(dst, src);
66 return status;
67}