reflog-expire: brown paper bag fix.
[git/git.git] / write_or_die.c
CommitLineData
7230e6d0
RS
1#include "cache.h"
2
93d26e4c 3int read_in_full(int fd, void *buf, size_t count)
75025ccd
SP
4{
5 char *p = buf;
93d26e4c
AW
6 ssize_t total = 0;
7 ssize_t loaded = 0;
75025ccd
SP
8
9 while (count > 0) {
10 loaded = xread(fd, p, count);
93d26e4c
AW
11 if (loaded <= 0) {
12 if (total)
13 return total;
14 else
15 return loaded;
16 }
75025ccd
SP
17 count -= loaded;
18 p += loaded;
93d26e4c 19 total += loaded;
75025ccd 20 }
93d26e4c
AW
21
22 return total;
23}
24
25void read_or_die(int fd, void *buf, size_t count)
26{
27 ssize_t loaded;
28
3b97fee2
EW
29 if (!count)
30 return;
93d26e4c
AW
31 loaded = read_in_full(fd, buf, count);
32 if (loaded == 0)
33 die("unexpected end of file");
34 else if (loaded < 0)
35 die("read error (%s)", strerror(errno));
75025ccd
SP
36}
37
93822c22 38int write_in_full(int fd, const void *buf, size_t count)
7230e6d0
RS
39{
40 const char *p = buf;
93822c22 41 ssize_t total = 0;
7230e6d0
RS
42
43 while (count > 0) {
f6aa66cb
LT
44 size_t written = xwrite(fd, p, count);
45 if (written < 0)
46 return -1;
47 if (!written) {
48 errno = ENOSPC;
49 return -1;
7230e6d0
RS
50 }
51 count -= written;
52 p += written;
93822c22 53 total += written;
7230e6d0 54 }
93822c22
AW
55
56 return total;
7230e6d0 57}
7cf67205 58
93822c22 59void write_or_die(int fd, const void *buf, size_t count)
7cf67205 60{
93822c22 61 ssize_t written;
7cf67205 62
3b97fee2
EW
63 if (!count)
64 return;
93822c22
AW
65 written = write_in_full(fd, buf, count);
66 if (written == 0)
67 die("disk full?");
68 else if (written < 0) {
69 if (errno == EPIPE)
70 exit(0);
71 die("write error (%s)", strerror(errno));
e0814056 72 }
e0814056
AW
73}
74
75int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
76{
77 ssize_t written;
78
3b97fee2
EW
79 if (!count)
80 return 1;
e0814056
AW
81 written = write_in_full(fd, buf, count);
82 if (written == 0) {
83 fprintf(stderr, "%s: disk full?\n", msg);
84 return 0;
85 }
86 else if (written < 0) {
87 if (errno == EPIPE)
88 exit(0);
89 fprintf(stderr, "%s: write error (%s)\n",
90 msg, strerror(errno));
91 return 0;
7cf67205
CC
92 }
93
94 return 1;
95}
825cee7b 96
e0814056 97int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
825cee7b 98{
825cee7b
AW
99 ssize_t written;
100
3b97fee2
EW
101 if (!count)
102 return 1;
e0814056
AW
103 written = write_in_full(fd, buf, count);
104 if (written == 0) {
105 fprintf(stderr, "%s: disk full?\n", msg);
106 return 0;
107 }
108 else if (written < 0) {
109 fprintf(stderr, "%s: write error (%s)\n",
110 msg, strerror(errno));
111 return 0;
825cee7b
AW
112 }
113
114 return 1;
115}