blob: eab8c8d0b9aab55c8435b9f451efd81e715131f8 [file] [log] [blame]
Rene Scharfe7230e6d2006-08-21 20:43:43 +02001#include "cache.h"
Jeff King96588462016-02-24 02:40:16 -05002#include "run-command.h"
Rene Scharfe7230e6d2006-08-21 20:43:43 +02003
Theodore Ts'o06f59e92007-06-29 13:40:46 -04004/*
5 * Some cases use stdio, but want to flush after the write
6 * to get error handling (and to get better interactive
7 * behaviour - not buffering excessively).
8 *
9 * Of course, if the flush happened within the write itself,
10 * we've already lost the error code, and cannot report it any
11 * more. So we just ignore that case instead (and hope we get
12 * the right error code on the flush).
13 *
14 * If the file handle is stdout, and stdout is a file, then skip the
15 * flush entirely since it's not needed.
16 */
17void maybe_flush_or_die(FILE *f, const char *desc)
18{
19 static int skip_stdout_flush = -1;
20 struct stat st;
21 char *cp;
22
23 if (f == stdout) {
24 if (skip_stdout_flush < 0) {
25 cp = getenv("GIT_FLUSH");
26 if (cp)
27 skip_stdout_flush = (atoi(cp) == 0);
28 else if ((fstat(fileno(stdout), &st) == 0) &&
29 S_ISREG(st.st_mode))
30 skip_stdout_flush = 1;
31 else
32 skip_stdout_flush = 0;
33 }
34 if (skip_stdout_flush && !ferror(f))
35 return;
36 }
37 if (fflush(f)) {
Jeff King756e6762013-02-20 15:01:36 -050038 check_pipe(errno);
Thomas Rastd824cbb2009-06-27 17:58:46 +020039 die_errno("write failure on '%s'", desc);
Theodore Ts'o06f59e92007-06-29 13:40:46 -040040 }
41}
42
Jeff King9540ce52014-09-10 06:03:52 -040043void fprintf_or_die(FILE *f, const char *fmt, ...)
44{
45 va_list ap;
46 int ret;
47
48 va_start(ap, fmt);
49 ret = vfprintf(f, fmt, ap);
50 va_end(ap);
51
52 if (ret < 0) {
53 check_pipe(errno);
54 die_errno("write error");
55 }
56}
57
Linus Torvalds4c81b032008-05-30 08:42:16 -070058void fsync_or_die(int fd, const char *msg)
59{
60 if (fsync(fd) < 0) {
Thomas Rastd824cbb2009-06-27 17:58:46 +020061 die_errno("fsync error on '%s'", msg);
Linus Torvalds4c81b032008-05-30 08:42:16 -070062 }
63}
64
Andy Whitcroft93822c22007-01-08 15:58:23 +000065void write_or_die(int fd, const void *buf, size_t count)
66{
Linus Torvaldsd34cf192007-01-11 20:23:00 -080067 if (write_in_full(fd, buf, count) < 0) {
Jeff King756e6762013-02-20 15:01:36 -050068 check_pipe(errno);
Thomas Rastd824cbb2009-06-27 17:58:46 +020069 die_errno("write error");
Andy Whitcroft93822c22007-01-08 15:58:23 +000070 }
Andy Whitcrofte0814052007-01-08 15:57:52 +000071}