Code

Consistent message encoding while reusing log from an existing commit.
[git.git] / write_or_die.c
1 #include "cache.h"
3 int read_in_full(int fd, void *buf, size_t count)
4 {
5         char *p = buf;
6         ssize_t total = 0;
8         while (count > 0) {
9                 ssize_t loaded = xread(fd, p, count);
10                 if (loaded <= 0)
11                         return total ? total : loaded;
12                 count -= loaded;
13                 p += loaded;
14                 total += loaded;
15         }
17         return total;
18 }
20 void read_or_die(int fd, void *buf, size_t count)
21 {
22         ssize_t loaded;
24         loaded = read_in_full(fd, buf, count);
25         if (loaded != count) {
26                 if (loaded < 0)
27                         die("read error (%s)", strerror(errno));
28                 die("read error: end of file");
29         }
30 }
32 int write_in_full(int fd, const void *buf, size_t count)
33 {
34         const char *p = buf;
35         ssize_t total = 0;
37         while (count > 0) {
38                 size_t written = xwrite(fd, p, count);
39                 if (written < 0)
40                         return -1;
41                 if (!written) {
42                         errno = ENOSPC;
43                         return -1;
44                 }
45                 count -= written;
46                 p += written;
47                 total += written;
48         }
50         return total;
51 }
53 void write_or_die(int fd, const void *buf, size_t count)
54 {
55         if (write_in_full(fd, buf, count) < 0) {
56                 if (errno == EPIPE)
57                         exit(0);
58                 die("write error (%s)", strerror(errno));
59         }
60 }
62 int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
63 {
64         if (write_in_full(fd, buf, count) < 0) {
65                 if (errno == EPIPE)
66                         exit(0);
67                 fprintf(stderr, "%s: write error (%s)\n",
68                         msg, strerror(errno));
69                 return 0;
70         }
72         return 1;
73 }
75 int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
76 {
77         if (write_in_full(fd, buf, count) < 0) {
78                 fprintf(stderr, "%s: write error (%s)\n",
79                         msg, strerror(errno));
80                 return 0;
81         }
83         return 1;
84 }