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