refs.c: add a function to append a reflog entry to a fd

Break out the code to create the string and writing it to the file descriptor from log_ref_write and add it into a dedicated function log_ref_write_fd. It is a nice unit of work. For now this is only used from log_ref_write, but in the future it might have other callers. Signed-off-by: Ronnie Sahlberg <sahlberg@google.com> Signed-off-by: Stefan Beller <sbeller@google.com> Reviewed-by: Jonathan Nieder <jrnieder@gmail.com> Signed-off-by: Michael Haggerty <mhagger@alum.mit.edu> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Ronnie Sahlberg committed Dec 12, 2014 at 09:56 UTC 2c6207abbd6c430be06ddfef97d145d7e21446fb
1 file changed +30 -18
refs.c
+30 -18
@@ -2990,15 +2990,37 @@ int log_ref_setup(const char *refname, char *logfile, int bufsize)
2990 return 0;
2991 }
2992
2993 +static int log_ref_write_fd(int fd, const unsigned char *old_sha1,
2994 + const unsigned char *new_sha1,
2995 + const char *committer, const char *msg)
2996 +{
2997 + int msglen, written;
2998 + unsigned maxlen, len;
2999 + char *logrec;
3000 +
3001 + msglen = msg ? strlen(msg) : 0;
3002 + maxlen = strlen(committer) + msglen + 100;
3003 + logrec = xmalloc(maxlen);
3004 + len = sprintf(logrec, "%s %s %s\n",
3005 + sha1_to_hex(old_sha1),
3006 + sha1_to_hex(new_sha1),
3007 + committer);
3008 + if (msglen)
3009 + len += copy_msg(logrec + len - 1, msg) - 1;
3010 +
3011 + written = len <= maxlen ? write_in_full(fd, logrec, len) : -1;
3012 + free(logrec);
3013 + if (written != len)
3014 + return -1;
3015 +
3016 + return 0;
3017 +}
3018 +
3019 static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3020 const unsigned char *new_sha1, const char *msg)
3021 {
2996 - int logfd, result, written, oflags = O_APPEND | O_WRONLY;
2997 - unsigned maxlen, len;
2998 - int msglen;
3022 + int logfd, result, oflags = O_APPEND | O_WRONLY;
3023 char log_file[PATH_MAX];
3000 - char *logrec;
3001 - const char *committer;
3024
3025 if (log_all_ref_updates < 0)
3026 log_all_ref_updates = !is_bare_repository();
@@ -3010,19 +3032,9 @@ static int log_ref_write(const char *refname, const unsigned char *old_sha1,
3032 logfd = open(log_file, oflags);
3033 if (logfd < 0)
3034 return 0;
3013 - msglen = msg ? strlen(msg) : 0;
3014 - committer = git_committer_info(0);
3015 - maxlen = strlen(committer) + msglen + 100;
3016 - logrec = xmalloc(maxlen);
3017 - len = sprintf(logrec, "%s %s %s\n",
3018 - sha1_to_hex(old_sha1),
3019 - sha1_to_hex(new_sha1),
3020 - committer);
3021 - if (msglen)
3022 - len += copy_msg(logrec + len - 1, msg) - 1;
3023 - written = len <= maxlen ? write_in_full(logfd, logrec, len) : -1;
3024 - free(logrec);
3025 - if (written != len) {
3035 + result = log_ref_write_fd(logfd, old_sha1, new_sha1,
3036 + git_committer_info(0), msg);
3037 + if (result) {
3038 int save_errno = errno;
3039 close(logfd);
3040 error("Unable to append to %s", log_file);