fetch: use strbuf to format FETCH_HEAD updates

This commit refactors `append_fetch_head()` to use a `struct strbuf` for formatting the update which we're about to append to the FETCH_HEAD file. While the refactoring doesn't have much of a benefit right now, it serves as a preparatory step to implement atomic fetches where we need to buffer all updates to FETCH_HEAD and only flush them out if all reference updates succeeded. No change in behaviour is expected from this commit. Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Patrick Steinhardt committed Jan 12, 2021 at 13:27 UTC 929d044575ed4f9657074f098e3a9be410d511ef
1 file changed +11 -5
builtin/fetch.c
+11 -5
@@ -899,6 +899,7 @@ static int iterate_ref_map(void *cb_data, struct object_id *oid)
899
900 struct fetch_head {
901 FILE *fp;
902 + struct strbuf buf;
903 };
904
905 static int open_fetch_head(struct fetch_head *fetch_head)
@@ -909,6 +910,7 @@ static int open_fetch_head(struct fetch_head *fetch_head)
910 fetch_head->fp = fopen(filename, "a");
911 if (!fetch_head->fp)
912 return error_errno(_("cannot open %s"), filename);
913 + strbuf_init(&fetch_head->buf, 0);
914 } else {
915 fetch_head->fp = NULL;
916 }
@@ -941,14 +943,17 @@ static void append_fetch_head(struct fetch_head *fetch_head,
943 return;
944 }
945
944 - fprintf(fetch_head->fp, "%s\t%s\t%s",
945 - oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
946 + strbuf_addf(&fetch_head->buf, "%s\t%s\t%s",
947 + oid_to_hex_r(old_oid_hex, old_oid), merge_status_marker, note);
948 for (i = 0; i < url_len; ++i)
949 if ('\n' == url[i])
948 - fputs("\\n", fetch_head->fp);
950 + strbuf_addstr(&fetch_head->buf, "\\n");
951 else
950 - fputc(url[i], fetch_head->fp);
951 - fputc('\n', fetch_head->fp);
952 + strbuf_addch(&fetch_head->buf, url[i]);
953 + strbuf_addch(&fetch_head->buf, '\n');
954 +
955 + strbuf_write(&fetch_head->buf, fetch_head->fp);
956 + strbuf_reset(&fetch_head->buf);
957 }
958
959 static void commit_fetch_head(struct fetch_head *fetch_head)
@@ -962,6 +967,7 @@ static void close_fetch_head(struct fetch_head *fetch_head)
967 return;
968
969 fclose(fetch_head->fp);
970 + strbuf_release(&fetch_head->buf);
971 }
972
973 static const char warn_show_forced_updates[] =