Update my e-mail address
[tgit.git] / write_or_die.c
blob630be4cb9414b1686a5ad86a4d5166f2828096f1
1 #include "cache.h"
3 /*
4 * Some cases use stdio, but want to flush after the write
5 * to get error handling (and to get better interactive
6 * behaviour - not buffering excessively).
8 * Of course, if the flush happened within the write itself,
9 * we've already lost the error code, and cannot report it any
10 * more. So we just ignore that case instead (and hope we get
11 * the right error code on the flush).
13 * If the file handle is stdout, and stdout is a file, then skip the
14 * flush entirely since it's not needed.
16 void maybe_flush_or_die(FILE *f, const char *desc)
18 static int skip_stdout_flush = -1;
19 struct stat st;
20 char *cp;
22 if (f == stdout) {
23 if (skip_stdout_flush < 0) {
24 cp = getenv("GIT_FLUSH");
25 if (cp)
26 skip_stdout_flush = (atoi(cp) == 0);
27 else if ((fstat(fileno(stdout), &st) == 0) &&
28 S_ISREG(st.st_mode))
29 skip_stdout_flush = 1;
30 else
31 skip_stdout_flush = 0;
33 if (skip_stdout_flush && !ferror(f))
34 return;
36 if (fflush(f)) {
37 if (errno == EPIPE)
38 exit(0);
39 die("write failure on %s: %s", desc, strerror(errno));
43 ssize_t read_in_full(int fd, void *buf, size_t count)
45 char *p = buf;
46 ssize_t total = 0;
48 while (count > 0) {
49 ssize_t loaded = xread(fd, p, count);
50 if (loaded <= 0)
51 return total ? total : loaded;
52 count -= loaded;
53 p += loaded;
54 total += loaded;
57 return total;
60 ssize_t write_in_full(int fd, const void *buf, size_t count)
62 const char *p = buf;
63 ssize_t total = 0;
65 while (count > 0) {
66 ssize_t written = xwrite(fd, p, count);
67 if (written < 0)
68 return -1;
69 if (!written) {
70 errno = ENOSPC;
71 return -1;
73 count -= written;
74 p += written;
75 total += written;
78 return total;
81 void fsync_or_die(int fd, const char *msg)
83 if (fsync(fd) < 0) {
84 die("%s: fsync error (%s)", msg, strerror(errno));
88 void write_or_die(int fd, const void *buf, size_t count)
90 if (write_in_full(fd, buf, count) < 0) {
91 if (errno == EPIPE)
92 exit(0);
93 die("write error (%s)", strerror(errno));
97 int write_or_whine_pipe(int fd, const void *buf, size_t count, const char *msg)
99 if (write_in_full(fd, buf, count) < 0) {
100 if (errno == EPIPE)
101 exit(0);
102 fprintf(stderr, "%s: write error (%s)\n",
103 msg, strerror(errno));
104 return 0;
107 return 1;
110 int write_or_whine(int fd, const void *buf, size_t count, const char *msg)
112 if (write_in_full(fd, buf, count) < 0) {
113 fprintf(stderr, "%s: write error (%s)\n",
114 msg, strerror(errno));
115 return 0;
118 return 1;