Skip to content

Commit 7b4de74

Browse files
mirucamgitster
authored andcommitted
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 <[email protected]> Mentored-by: Johannes Schindelin <[email protected]> Signed-off-by: Miriam Rubio <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 3027676 commit 7b4de74

File tree

1 file changed

+36
-7
lines changed

1 file changed

+36
-7
lines changed

builtin/bisect--helper.c

Lines changed: 36 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,40 @@ static int one_of(const char *term, ...)
7474
return res;
7575
}
7676

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+
77111
static int check_term_format(const char *term, const char *orig_term)
78112
{
79113
int res;
@@ -104,7 +138,6 @@ static int check_term_format(const char *term, const char *orig_term)
104138

105139
static int write_terms(const char *bad, const char *good)
106140
{
107-
FILE *fp = NULL;
108141
int res;
109142

110143
if (!strcmp(bad, good))
@@ -113,13 +146,9 @@ static int write_terms(const char *bad, const char *good)
113146
if (check_term_format(bad, "bad") || check_term_format(good, "good"))
114147
return -1;
115148

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);
119150

120-
res = fprintf(fp, "%s\n%s\n", bad, good);
121-
res |= fclose(fp);
122-
return (res < 0) ? -1 : 0;
151+
return res;
123152
}
124153

125154
static int is_expected_rev(const char *expected_hex)

0 commit comments

Comments
 (0)