blob: a7f58fd905b31b2634f74580090ec664a640e279 [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];
7 char *buf = buffer;
Johan Herland8a912bc2007-05-15 14:49:22 +02008 ssize_t len = xread(ifd, buffer, sizeof(buffer));
Junio C Hamanof3123c42005-10-22 01:28:13 -07009 if (!len)
10 break;
11 if (len < 0) {
Ariel Badichi8b1f6de2008-04-23 04:05:29 +030012 int read_error = errno;
Junio C Hamanoe6c64fc2005-11-05 11:02:56 -080013 close(ifd);
Junio C Hamanof3123c42005-10-22 01:28:13 -070014 return error("copy-fd: read returned %s",
Junio C Hamanoe6c64fc2005-11-05 11:02:56 -080015 strerror(read_error));
Junio C Hamanof3123c42005-10-22 01:28:13 -070016 }
Junio C Hamano1c15afb2005-12-19 16:18:28 -080017 while (len) {
18 int written = xwrite(ofd, buf, len);
Junio C Hamanof3123c42005-10-22 01:28:13 -070019 if (written > 0) {
20 buf += written;
21 len -= written;
Junio C Hamanof3123c42005-10-22 01:28:13 -070022 }
Sam Ravnborg08337a92005-12-27 09:19:05 +010023 else if (!written) {
24 close(ifd);
Junio C Hamanof3123c42005-10-22 01:28:13 -070025 return error("copy-fd: write returned 0");
Sam Ravnborg08337a92005-12-27 09:19:05 +010026 } else {
Ariel Badichi8b1f6de2008-04-23 04:05:29 +030027 int write_error = errno;
Sam Ravnborg08337a92005-12-27 09:19:05 +010028 close(ifd);
Junio C Hamano1c15afb2005-12-19 16:18:28 -080029 return error("copy-fd: write returned %s",
Ariel Badichi8b1f6de2008-04-23 04:05:29 +030030 strerror(write_error));
Sam Ravnborg08337a92005-12-27 09:19:05 +010031 }
Junio C Hamanof3123c42005-10-22 01:28:13 -070032 }
33 }
34 close(ifd);
35 return 0;
36}
Daniel Barkalow1468bd42008-02-25 14:24:48 -050037
Clemens Buchacherf7835a22009-09-12 11:03:48 +020038static int copy_times(const char *dst, const char *src)
39{
40 struct stat st;
41 struct utimbuf times;
42 if (stat(src, &st) < 0)
43 return -1;
44 times.actime = st.st_atime;
45 times.modtime = st.st_mtime;
46 if (utime(dst, &times) < 0)
47 return -1;
48 return 0;
49}
50
Daniel Barkalow1468bd42008-02-25 14:24:48 -050051int copy_file(const char *dst, const char *src, int mode)
52{
53 int fdi, fdo, status;
54
55 mode = (mode & 0111) ? 0777 : 0666;
56 if ((fdi = open(src, O_RDONLY)) < 0)
57 return fdi;
58 if ((fdo = open(dst, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) {
59 close(fdi);
60 return fdo;
61 }
62 status = copy_fd(fdi, fdo);
63 if (close(fdo) != 0)
Ariel Badichi8b1f6de2008-04-23 04:05:29 +030064 return error("%s: close error: %s", dst, strerror(errno));
Daniel Barkalow1468bd42008-02-25 14:24:48 -050065
66 if (!status && adjust_shared_perm(dst))
67 return -1;
68
69 return status;
70}
Clemens Buchacherf7835a22009-09-12 11:03:48 +020071
72int copy_file_with_time(const char *dst, const char *src, int mode)
73{
74 int status = copy_file(dst, src, mode);
75 if (!status)
76 return copy_times(dst, src);
77 return status;
78}