@matheusbsbs / matheus-bagliano / commits / 7b4de74b5d
Fork 0

bisect--helper: introduce new `write_in_file()` function

Let's refactor code adding a new `write_in_file()` function that opens a file for writing a message and closes it and a wrapper for writing mode. This helper will be used in later steps and makes the code simpler and easier to understand. Mentored-by: Christian Couder <chriscool@tuxfamily.org> Mentored-by: Johannes Schindelin <Johannes.Schindelin@gmx.de> Signed-off-by: Miriam Rubio <mirucam@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Miriam Rubio committed Aug 28, 2020 at 14:46 UTC 7b4de74b5de5c1ceb035d33168d482ad213b4137
1 file changed +36 -7
builtin/bisect--helper.c
+36 -7
@@ -74,6 +74,40 @@ static int one_of(const char *term, ...)
74 return res;
75 }
76
77 +static int write_in_file(const char *path, const char *mode, const char *format, va_list args)
78 +{
79 + FILE *fp = NULL;
80 + int res = 0;
81 +
82 + if (strcmp(mode, "w"))
83 + BUG("write-in-file does not support '%s' mode", mode);
84 + fp = fopen(path, mode);
85 + if (!fp)
86 + return error_errno(_("cannot open file '%s' in mode '%s'"), path, mode);
87 + res = vfprintf(fp, format, args);
88 +
89 + if (res < 0) {
90 + int saved_errno = errno;
91 + fclose(fp);
92 + errno = saved_errno;
93 + return error_errno(_("could not write to file '%s'"), path);
94 + }
95 +
96 + return fclose(fp);
97 +}
98 +
99 +static int write_to_file(const char *path, const char *format, ...)
100 +{
101 + int res;
102 + va_list args;
103 +
104 + va_start(args, format);
105 + res = write_in_file(path, "w", format, args);
106 + va_end(args);
107 +
108 + return res;
109 +}
110 +
111 static int check_term_format(const char *term, const char *orig_term)
112 {
113 int res;
@@ -104,7 +138,6 @@ static int check_term_format(const char *term, const char *orig_term)
138
139 static int write_terms(const char *bad, const char *good)
140 {
107 - FILE *fp = NULL;
141 int res;
142
143 if (!strcmp(bad, good))
@@ -113,13 +146,9 @@ static int write_terms(const char *bad, const char *good)
146 if (check_term_format(bad, "bad") || check_term_format(good, "good"))
147 return -1;
148
116 - fp = fopen(git_path_bisect_terms(), "w");
117 - if (!fp)
118 - return error_errno(_("could not open the file BISECT_TERMS"));
149 + res = write_to_file(git_path_bisect_terms(), "%s\n%s\n", bad, good);
150
120 - res = fprintf(fp, "%s\n%s\n", bad, good);
121 - res |= fclose(fp);
122 - return (res < 0) ? -1 : 0;
151 + return res;
152 }
153
154 static int is_expected_rev(const char *expected_hex)