]> git.ipfire.org Git - thirdparty/git.git/blob - write-or-die.c
core.fsyncmethod: add writeout-only mode
[thirdparty/git.git] / write-or-die.c
1 #include "cache.h"
2 #include "config.h"
3 #include "run-command.h"
4
5 /*
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 */
18 void 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)) {
39 check_pipe(errno);
40 die_errno("write failure on '%s'", desc);
41 }
42 }
43
44 void 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
59 void fsync_or_die(int fd, const char *msg)
60 {
61 if (use_fsync < 0)
62 use_fsync = git_env_bool("GIT_TEST_FSYNC", 1);
63 if (!use_fsync)
64 return;
65
66 if (fsync_method == FSYNC_METHOD_WRITEOUT_ONLY &&
67 git_fsync(fd, FSYNC_WRITEOUT_ONLY) >= 0)
68 return;
69
70 if (git_fsync(fd, FSYNC_HARDWARE_FLUSH) < 0)
71 die_errno("fsync error on '%s'", msg);
72 }
73
74 void write_or_die(int fd, const void *buf, size_t count)
75 {
76 if (write_in_full(fd, buf, count) < 0) {
77 check_pipe(errno);
78 die_errno("write error");
79 }
80 }
81
82 void fwrite_or_die(FILE *f, const void *buf, size_t count)
83 {
84 if (fwrite(buf, 1, count, f) != count)
85 die_errno("fwrite error");
86 }
87
88 void fflush_or_die(FILE *f)
89 {
90 if (fflush(f))
91 die_errno("fflush error");
92 }