sequencer: simplify memory allocation of get_message

For a commit with sha1 "1234abcd" and subject "foo", this function produces a struct with three strings: 1. "foo" 2. "1234abcd... foo" 3. "parent of 1234abcd... foo" It takes advantage of the fact that these strings are subsets of each other, and allocates only _one_ string, with pointers into the various parts. Unfortunately, this makes the string allocation complicated and hard to follow. Since we keep only one of these in memory at a time, we can afford to simply allocate three strings. This lets us build on tools like xstrfmt and avoid manual computation. While we're here, we can also drop the ad-hoc reimplementation of get_git_commit_encoding(), and simply call that function. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Feb 22, 2016 at 17:44 UTC 7b35eaf8c50609ae4899dcde7fcaa1be0df657df
1 file changed +10 -19
sequencer.c
+10 -19
@@ -124,42 +124,33 @@ static const char *action_name(const struct replay_opts *opts)
124
125 struct commit_message {
126 char *parent_label;
127 - const char *label;
128 - const char *subject;
127 + char *label;
128 + char *subject;
129 const char *message;
130 };
131
132 static int get_message(struct commit *commit, struct commit_message *out)
133 {
134 const char *abbrev, *subject;
135 - int abbrev_len, subject_len;
136 - char *q;
137 -
138 - if (!git_commit_encoding)
139 - git_commit_encoding = "UTF-8";
135 + int subject_len;
136
141 - out->message = logmsg_reencode(commit, NULL, git_commit_encoding);
137 + out->message = logmsg_reencode(commit, NULL, get_commit_output_encoding());
138 abbrev = find_unique_abbrev(commit->object.oid.hash, DEFAULT_ABBREV);
143 - abbrev_len = strlen(abbrev);
139
140 subject_len = find_commit_subject(out->message, &subject);
141
147 - out->parent_label = xmalloc(strlen("parent of ") + abbrev_len +
148 - strlen("... ") + subject_len + 1);
149 - q = out->parent_label;
150 - q = mempcpy(q, "parent of ", strlen("parent of "));
151 - out->label = q;
152 - q = mempcpy(q, abbrev, abbrev_len);
153 - q = mempcpy(q, "... ", strlen("... "));
154 - out->subject = q;
155 - q = mempcpy(q, subject, subject_len);
156 - *q = '\0';
142 + out->subject = xmemdupz(subject, subject_len);
143 + out->label = xstrfmt("%s... %s", abbrev, out->subject);
144 + out->parent_label = xstrfmt("parent of %s", out->label);
145 +
146 return 0;
147 }
148
149 static void free_message(struct commit *commit, struct commit_message *msg)
150 {
151 free(msg->parent_label);
152 + free(msg->label);
153 + free(msg->subject);
154 unuse_commit_buffer(commit, msg->message);
155 }
156