blob: a3d5784cec94230d18747612bfe59e8db8248ff9 [file] [log] [blame]
Rene Scharfe7230e6d2006-08-21 20:43:43 +02001#include "cache.h"
Eric Wong412e4ca2021-10-29 00:15:52 +00002#include "config.h"
Jeff King96588462016-02-24 02:40:16 -05003#include "run-command.h"
Rene Scharfe7230e6d2006-08-21 20:43:43 +02004
Theodore Ts'o06f59e92007-06-29 13:40:46 -04005/*
6 * Some cases use stdio, but want to flush after the write
7 * to get error handling (and to get better interactive
8 * behaviour - not buffering excessively).
9 *
10 * Of course, if the flush happened within the write itself,
11 * we've already lost the error code, and cannot report it any
12 * more. So we just ignore that case instead (and hope we get
13 * the right error code on the flush).
14 *
15 * If the file handle is stdout, and stdout is a file, then skip the
16 * flush entirely since it's not needed.
17 */
18void maybe_flush_or_die(FILE *f, const char *desc)
19{
20 static int skip_stdout_flush = -1;
21 struct stat st;
22 char *cp;
23
24 if (f == stdout) {
25 if (skip_stdout_flush < 0) {
26 cp = getenv("GIT_FLUSH");
27 if (cp)
28 skip_stdout_flush = (atoi(cp) == 0);
29 else if ((fstat(fileno(stdout), &st) == 0) &&
30 S_ISREG(st.st_mode))
31 skip_stdout_flush = 1;
32 else
33 skip_stdout_flush = 0;
34 }
35 if (skip_stdout_flush && !ferror(f))
36 return;
37 }
38 if (fflush(f)) {
Jeff King756e6762013-02-20 15:01:36 -050039 check_pipe(errno);
Thomas Rastd824cbb2009-06-27 17:58:46 +020040 die_errno("write failure on '%s'", desc);
Theodore Ts'o06f59e92007-06-29 13:40:46 -040041 }
42}
43
Jeff King9540ce52014-09-10 06:03:52 -040044void fprintf_or_die(FILE *f, const char *fmt, ...)
45{
46 va_list ap;
47 int ret;
48
49 va_start(ap, fmt);
50 ret = vfprintf(f, fmt, ap);
51 va_end(ap);
52
53 if (ret < 0) {
54 check_pipe(errno);
55 die_errno("write error");
56 }
57}
58
Linus Torvalds4c81b032008-05-30 08:42:16 -070059void fsync_or_die(int fd, const char *msg)
60{
Eric Wong412e4ca2021-10-29 00:15:52 +000061 if (use_fsync < 0)
62 use_fsync = git_env_bool("GIT_TEST_FSYNC", 1);
63 if (!use_fsync)
64 return;
Junio C Hamanocccdfd22021-06-04 10:36:11 +090065 while (fsync(fd) < 0) {
66 if (errno != EINTR)
67 die_errno("fsync error on '%s'", msg);
Linus Torvalds4c81b032008-05-30 08:42:16 -070068 }
69}
70
Andy Whitcroft93822c22007-01-08 15:58:23 +000071void write_or_die(int fd, const void *buf, size_t count)
72{
Linus Torvaldsd34cf192007-01-11 20:23:00 -080073 if (write_in_full(fd, buf, count) < 0) {
Jeff King756e6762013-02-20 15:01:36 -050074 check_pipe(errno);
Thomas Rastd824cbb2009-06-27 17:58:46 +020075 die_errno("write error");
Andy Whitcroft93822c22007-01-08 15:58:23 +000076 }
Andy Whitcrofte0814052007-01-08 15:57:52 +000077}
Jacob Vosmaer96328392021-09-01 14:54:41 +020078
79void fwrite_or_die(FILE *f, const void *buf, size_t count)
80{
81 if (fwrite(buf, 1, count, f) != count)
82 die_errno("fwrite error");
83}
84
85void fflush_or_die(FILE *f)
86{
87 if (fflush(f))
88 die_errno("fflush error");
89}