ls-remote: release memory instead of UNLEAK
[git/git.git] / ref-filter.c
CommitLineData
c95b7585
KN
1#include "builtin.h"
2#include "cache.h"
3#include "parse-options.h"
4#include "refs.h"
5#include "wildmatch.h"
cbd53a21 6#include "object-store.h"
109cd76d 7#include "repository.h"
c95b7585
KN
8#include "commit.h"
9#include "remote.h"
10#include "color.h"
11#include "tag.h"
12#include "quote.h"
13#include "ref-filter.h"
35257aa0 14#include "revision.h"
ce592082 15#include "utf8.h"
90c00408
KN
16#include "git-compat-util.h"
17#include "version.h"
b1d31c89 18#include "trailer.h"
d4919bb2 19#include "wt-status.h"
a91aca44 20#include "commit-slab.h"
819807b3 21#include "commit-graph.h"
64043556 22#include "commit-reach.h"
c95b7585 23
6eac70fa
KN
24static struct ref_msg {
25 const char *gone;
26 const char *ahead;
27 const char *behind;
28 const char *ahead_behind;
29} msgs = {
30 /* Untranslated plumbing messages: */
31 "gone",
32 "ahead %d",
33 "behind %d",
34 "ahead %d, behind %d"
35};
36
37void setup_ref_filter_porcelain_msg(void)
38{
39 msgs.gone = _("gone");
40 msgs.ahead = _("ahead %d");
41 msgs.behind = _("behind %d");
42 msgs.ahead_behind = _("ahead %d, behind %d");
43}
c95b7585
KN
44
45typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
4f3e3b37 46typedef enum { COMPARE_EQUAL, COMPARE_UNEQUAL, COMPARE_NONE } cmp_status;
a8e7e385 47typedef enum { SOURCE_NONE = 0, SOURCE_OBJ, SOURCE_OTHER } info_source;
c95b7585 48
5bd881d9
KN
49struct align {
50 align_type position;
51 unsigned int width;
52};
53
c58492d4 54struct if_then_else {
4f3e3b37
KN
55 cmp_status cmp_status;
56 const char *str;
c58492d4
KN
57 unsigned int then_atom_seen : 1,
58 else_atom_seen : 1,
59 condition_satisfied : 1;
60};
61
b180e6fe 62struct refname_atom {
1a34728e
KN
63 enum { R_NORMAL, R_SHORT, R_LSTRIP, R_RSTRIP } option;
64 int lstrip, rstrip;
b180e6fe
KN
65};
66
aa46a0da
OT
67static struct expand_data {
68 struct object_id oid;
69 enum object_type type;
70 unsigned long size;
71 off_t disk_size;
72 struct object_id delta_base_oid;
73 void *content;
74
75 struct object_info info;
76} oi, oi_deref;
77
50cd83dc
KN
78/*
79 * An atom is a valid field atom listed below, possibly prefixed with
80 * a "*" to denote deref_tag().
81 *
82 * We parse given format string and sort specifiers, and make a list
83 * of properties that we need to extract out of objects. ref_array_item
84 * structure will hold an array of values extracted that can be
85 * indexed with the "atom number", which is an index into this
86 * array.
87 */
b072add7
KN
88static struct used_atom {
89 const char *name;
90 cmp_type type;
a8e7e385 91 info_source source;
fd935cc7
KN
92 union {
93 char color[COLOR_MAXLEN];
5bd881d9 94 struct align align;
7743fcca 95 struct {
cc72385f 96 enum {
9700fae5 97 RR_REF, RR_TRACK, RR_TRACKSHORT, RR_REMOTE_NAME, RR_REMOTE_REF
cc72385f 98 } option;
3ba308cb 99 struct refname_atom refname;
cc72385f 100 unsigned int nobracket : 1, push : 1, push_remote : 1;
7743fcca 101 } remote_ref;
452db397 102 struct {
b1d31c89 103 enum { C_BARE, C_BODY, C_BODY_DEP, C_LINES, C_SIG, C_SUB, C_TRAILERS } option;
67a20a00 104 struct process_trailer_options trailer_opts;
452db397
KN
105 unsigned int nlines;
106 } contents;
4f3e3b37
KN
107 struct {
108 cmp_status cmp_status;
109 const char *str;
110 } if_then_else;
42d0eb05
KN
111 struct {
112 enum { O_FULL, O_LENGTH, O_SHORT } option;
113 unsigned int length;
114 } objectname;
b180e6fe 115 struct refname_atom refname;
613a0e52 116 char *head;
fd935cc7 117 } u;
b072add7 118} *used_atom;
50cd83dc 119static int used_atom_cnt, need_tagged, need_symref;
50cd83dc 120
e2e7a245
OT
121/*
122 * Expand string, append it to strbuf *sb, then return error code ret.
123 * Allow to save few lines of code.
124 */
125static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
126{
127 va_list ap;
128 va_start(ap, fmt);
129 strbuf_vaddf(sb, fmt, ap);
130 va_end(ap);
131 return ret;
132}
133
74efea94
OT
134static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
135 const char *color_value, struct strbuf *err)
fd935cc7
KN
136{
137 if (!color_value)
74efea94 138 return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
fd935cc7 139 if (color_parse(color_value, atom->u.color) < 0)
74efea94
OT
140 return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
141 color_value);
11b087ad
JK
142 /*
143 * We check this after we've parsed the color, which lets us complain
144 * about syntactically bogus color names even if they won't be used.
145 */
146 if (!want_color(format->use_color))
147 color_parse("", atom->u.color);
74efea94 148 return 0;
fd935cc7
KN
149}
150
74efea94
OT
151static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
152 const char *name, struct strbuf *err)
5339bdad
KN
153{
154 if (!arg)
b180e6fe 155 atom->option = R_NORMAL;
5339bdad 156 else if (!strcmp(arg, "short"))
b180e6fe 157 atom->option = R_SHORT;
44a6b6ce
JH
158 else if (skip_prefix(arg, "lstrip=", &arg) ||
159 skip_prefix(arg, "strip=", &arg)) {
17938f17 160 atom->option = R_LSTRIP;
1a0ca5e3 161 if (strtol_i(arg, 10, &atom->lstrip))
74efea94 162 return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
1a34728e
KN
163 } else if (skip_prefix(arg, "rstrip=", &arg)) {
164 atom->option = R_RSTRIP;
165 if (strtol_i(arg, 10, &atom->rstrip))
74efea94 166 return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
b180e6fe 167 } else
74efea94
OT
168 return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
169 return 0;
b180e6fe
KN
170}
171
74efea94
OT
172static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
173 const char *arg, struct strbuf *err)
5339bdad 174{
7743fcca
KN
175 struct string_list params = STRING_LIST_INIT_DUP;
176 int i;
177
cc72385f
JS
178 if (!strcmp(atom->name, "push") || starts_with(atom->name, "push:"))
179 atom->u.remote_ref.push = 1;
180
7743fcca 181 if (!arg) {
3ba308cb 182 atom->u.remote_ref.option = RR_REF;
74efea94
OT
183 return refname_atom_parser_internal(&atom->u.remote_ref.refname,
184 arg, atom->name, err);
7743fcca
KN
185 }
186
187 atom->u.remote_ref.nobracket = 0;
188 string_list_split(&params, arg, ',', -1);
189
190 for (i = 0; i < params.nr; i++) {
191 const char *s = params.items[i].string;
192
3ba308cb 193 if (!strcmp(s, "track"))
7743fcca
KN
194 atom->u.remote_ref.option = RR_TRACK;
195 else if (!strcmp(s, "trackshort"))
196 atom->u.remote_ref.option = RR_TRACKSHORT;
197 else if (!strcmp(s, "nobracket"))
198 atom->u.remote_ref.nobracket = 1;
cc72385f
JS
199 else if (!strcmp(s, "remotename")) {
200 atom->u.remote_ref.option = RR_REMOTE_NAME;
201 atom->u.remote_ref.push_remote = 1;
9700fae5
W
202 } else if (!strcmp(s, "remoteref")) {
203 atom->u.remote_ref.option = RR_REMOTE_REF;
204 atom->u.remote_ref.push_remote = 1;
cc72385f 205 } else {
3ba308cb 206 atom->u.remote_ref.option = RR_REF;
74efea94
OT
207 if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
208 arg, atom->name, err)) {
209 string_list_clear(&params, 0);
210 return -1;
211 }
3ba308cb 212 }
7743fcca
KN
213 }
214
215 string_list_clear(&params, 0);
74efea94 216 return 0;
5339bdad
KN
217}
218
aa46a0da
OT
219static int objecttype_atom_parser(const struct ref_format *format, struct used_atom *atom,
220 const char *arg, struct strbuf *err)
221{
222 if (arg)
223 return strbuf_addf_ret(err, -1, _("%%(objecttype) does not take arguments"));
224 if (*atom->name == '*')
225 oi_deref.info.typep = &oi_deref.type;
226 else
227 oi.info.typep = &oi.type;
228 return 0;
229}
230
231static int objectsize_atom_parser(const struct ref_format *format, struct used_atom *atom,
232 const char *arg, struct strbuf *err)
233{
234 if (arg)
235 return strbuf_addf_ret(err, -1, _("%%(objectsize) does not take arguments"));
236 if (*atom->name == '*')
237 oi_deref.info.sizep = &oi_deref.size;
238 else
239 oi.info.sizep = &oi.size;
240 return 0;
241}
242
74efea94
OT
243static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
244 const char *arg, struct strbuf *err)
452db397
KN
245{
246 if (arg)
74efea94 247 return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
452db397 248 atom->u.contents.option = C_BODY_DEP;
74efea94 249 return 0;
452db397
KN
250}
251
74efea94
OT
252static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
253 const char *arg, struct strbuf *err)
452db397
KN
254{
255 if (arg)
74efea94 256 return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
452db397 257 atom->u.contents.option = C_SUB;
74efea94 258 return 0;
452db397
KN
259}
260
74efea94
OT
261static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
262 const char *arg, struct strbuf *err)
b1d31c89 263{
67a20a00
TB
264 struct string_list params = STRING_LIST_INIT_DUP;
265 int i;
266
e5fba5d5
JK
267 atom->u.contents.trailer_opts.no_divider = 1;
268
67a20a00
TB
269 if (arg) {
270 string_list_split(&params, arg, ',', -1);
271 for (i = 0; i < params.nr; i++) {
272 const char *s = params.items[i].string;
273 if (!strcmp(s, "unfold"))
274 atom->u.contents.trailer_opts.unfold = 1;
275 else if (!strcmp(s, "only"))
276 atom->u.contents.trailer_opts.only_trailers = 1;
74efea94
OT
277 else {
278 strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
279 string_list_clear(&params, 0);
280 return -1;
281 }
67a20a00
TB
282 }
283 }
b1d31c89 284 atom->u.contents.option = C_TRAILERS;
67a20a00 285 string_list_clear(&params, 0);
74efea94 286 return 0;
b1d31c89
JK
287}
288
74efea94
OT
289static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
290 const char *arg, struct strbuf *err)
452db397
KN
291{
292 if (!arg)
293 atom->u.contents.option = C_BARE;
294 else if (!strcmp(arg, "body"))
295 atom->u.contents.option = C_BODY;
296 else if (!strcmp(arg, "signature"))
297 atom->u.contents.option = C_SIG;
298 else if (!strcmp(arg, "subject"))
299 atom->u.contents.option = C_SUB;
7a5edbdb
TB
300 else if (skip_prefix(arg, "trailers", &arg)) {
301 skip_prefix(arg, ":", &arg);
74efea94
OT
302 if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
303 return -1;
7a5edbdb 304 } else if (skip_prefix(arg, "lines=", &arg)) {
452db397
KN
305 atom->u.contents.option = C_LINES;
306 if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
74efea94 307 return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
452db397 308 } else
74efea94
OT
309 return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
310 return 0;
452db397
KN
311}
312
74efea94
OT
313static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
314 const char *arg, struct strbuf *err)
fe63c4d1
KN
315{
316 if (!arg)
42d0eb05 317 atom->u.objectname.option = O_FULL;
fe63c4d1 318 else if (!strcmp(arg, "short"))
42d0eb05
KN
319 atom->u.objectname.option = O_SHORT;
320 else if (skip_prefix(arg, "short=", &arg)) {
321 atom->u.objectname.option = O_LENGTH;
322 if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
323 atom->u.objectname.length == 0)
74efea94 324 return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
42d0eb05
KN
325 if (atom->u.objectname.length < MINIMUM_ABBREV)
326 atom->u.objectname.length = MINIMUM_ABBREV;
327 } else
74efea94
OT
328 return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
329 return 0;
fe63c4d1
KN
330}
331
74efea94
OT
332static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
333 const char *arg, struct strbuf *err)
a7984101 334{
74efea94 335 return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
a7984101
KN
336}
337
25a8d79e
KN
338static align_type parse_align_position(const char *s)
339{
340 if (!strcmp(s, "right"))
341 return ALIGN_RIGHT;
342 else if (!strcmp(s, "middle"))
343 return ALIGN_MIDDLE;
344 else if (!strcmp(s, "left"))
345 return ALIGN_LEFT;
346 return -1;
347}
348
74efea94
OT
349static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
350 const char *arg, struct strbuf *err)
5bd881d9
KN
351{
352 struct align *align = &atom->u.align;
353 struct string_list params = STRING_LIST_INIT_DUP;
354 int i;
355 unsigned int width = ~0U;
356
357 if (!arg)
74efea94 358 return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
5bd881d9
KN
359
360 align->position = ALIGN_LEFT;
361
362 string_list_split(&params, arg, ',', -1);
363 for (i = 0; i < params.nr; i++) {
364 const char *s = params.items[i].string;
365 int position;
366
395fb8f9
KN
367 if (skip_prefix(s, "position=", &s)) {
368 position = parse_align_position(s);
74efea94
OT
369 if (position < 0) {
370 strbuf_addf(err, _("unrecognized position:%s"), s);
371 string_list_clear(&params, 0);
372 return -1;
373 }
395fb8f9
KN
374 align->position = position;
375 } else if (skip_prefix(s, "width=", &s)) {
74efea94
OT
376 if (strtoul_ui(s, 10, &width)) {
377 strbuf_addf(err, _("unrecognized width:%s"), s);
378 string_list_clear(&params, 0);
379 return -1;
380 }
395fb8f9 381 } else if (!strtoul_ui(s, 10, &width))
5bd881d9
KN
382 ;
383 else if ((position = parse_align_position(s)) >= 0)
384 align->position = position;
74efea94
OT
385 else {
386 strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
387 string_list_clear(&params, 0);
388 return -1;
389 }
5bd881d9
KN
390 }
391
74efea94
OT
392 if (width == ~0U) {
393 string_list_clear(&params, 0);
394 return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
395 }
5bd881d9
KN
396 align->width = width;
397 string_list_clear(&params, 0);
74efea94 398 return 0;
5bd881d9
KN
399}
400
74efea94
OT
401static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
402 const char *arg, struct strbuf *err)
4f3e3b37
KN
403{
404 if (!arg) {
405 atom->u.if_then_else.cmp_status = COMPARE_NONE;
74efea94 406 return 0;
4f3e3b37
KN
407 } else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
408 atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
409 } else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
410 atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
74efea94
OT
411 } else
412 return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
413 return 0;
4f3e3b37
KN
414}
415
74efea94
OT
416static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
417 const char *arg, struct strbuf *unused_err)
613a0e52 418{
efbd4fdf 419 atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
74efea94 420 return 0;
613a0e52 421}
4f3e3b37 422
c95b7585
KN
423static struct {
424 const char *name;
a8e7e385 425 info_source source;
c95b7585 426 cmp_type cmp_type;
74efea94
OT
427 int (*parser)(const struct ref_format *format, struct used_atom *atom,
428 const char *arg, struct strbuf *err);
c95b7585 429} valid_atom[] = {
a8e7e385 430 { "refname", SOURCE_NONE, FIELD_STR, refname_atom_parser },
aa46a0da
OT
431 { "objecttype", SOURCE_OTHER, FIELD_STR, objecttype_atom_parser },
432 { "objectsize", SOURCE_OTHER, FIELD_ULONG, objectsize_atom_parser },
a8e7e385
OT
433 { "objectname", SOURCE_OTHER, FIELD_STR, objectname_atom_parser },
434 { "tree", SOURCE_OBJ },
435 { "parent", SOURCE_OBJ },
436 { "numparent", SOURCE_OBJ, FIELD_ULONG },
437 { "object", SOURCE_OBJ },
438 { "type", SOURCE_OBJ },
439 { "tag", SOURCE_OBJ },
440 { "author", SOURCE_OBJ },
441 { "authorname", SOURCE_OBJ },
442 { "authoremail", SOURCE_OBJ },
443 { "authordate", SOURCE_OBJ, FIELD_TIME },
444 { "committer", SOURCE_OBJ },
445 { "committername", SOURCE_OBJ },
446 { "committeremail", SOURCE_OBJ },
447 { "committerdate", SOURCE_OBJ, FIELD_TIME },
448 { "tagger", SOURCE_OBJ },
449 { "taggername", SOURCE_OBJ },
450 { "taggeremail", SOURCE_OBJ },
451 { "taggerdate", SOURCE_OBJ, FIELD_TIME },
452 { "creator", SOURCE_OBJ },
453 { "creatordate", SOURCE_OBJ, FIELD_TIME },
454 { "subject", SOURCE_OBJ, FIELD_STR, subject_atom_parser },
455 { "body", SOURCE_OBJ, FIELD_STR, body_atom_parser },
456 { "trailers", SOURCE_OBJ, FIELD_STR, trailers_atom_parser },
457 { "contents", SOURCE_OBJ, FIELD_STR, contents_atom_parser },
458 { "upstream", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
459 { "push", SOURCE_NONE, FIELD_STR, remote_ref_atom_parser },
460 { "symref", SOURCE_NONE, FIELD_STR, refname_atom_parser },
461 { "flag", SOURCE_NONE },
462 { "HEAD", SOURCE_NONE, FIELD_STR, head_atom_parser },
463 { "color", SOURCE_NONE, FIELD_STR, color_atom_parser },
464 { "align", SOURCE_NONE, FIELD_STR, align_atom_parser },
465 { "end", SOURCE_NONE },
466 { "if", SOURCE_NONE, FIELD_STR, if_atom_parser },
467 { "then", SOURCE_NONE },
468 { "else", SOURCE_NONE },
c95b7585
KN
469};
470
574e96a2
KN
471#define REF_FORMATTING_STATE_INIT { 0, NULL }
472
473struct ref_formatting_stack {
474 struct ref_formatting_stack *prev;
475 struct strbuf output;
c58492d4 476 void (*at_end)(struct ref_formatting_stack **stack);
ce592082 477 void *at_end_data;
574e96a2
KN
478};
479
480struct ref_formatting_state {
481 int quote_style;
482 struct ref_formatting_stack *stack;
483};
484
3a25761a
KN
485struct atom_value {
486 const char *s;
3fc8439c
OT
487 int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
488 struct strbuf *err);
e467dc14 489 uintmax_t value; /* used for sorting when not FIELD_STR */
c58fc856 490 struct used_atom *atom;
3a25761a
KN
491};
492
c95b7585
KN
493/*
494 * Used to parse format string and sort specifiers
495 */
ab7ded34 496static int parse_ref_filter_atom(const struct ref_format *format,
e6ff7b3b
OT
497 const char *atom, const char *ep,
498 struct strbuf *err)
c95b7585
KN
499{
500 const char *sp;
4de707ea 501 const char *arg;
e94ce139 502 int i, at, atom_len;
c95b7585
KN
503
504 sp = atom;
505 if (*sp == '*' && sp < ep)
506 sp++; /* deref */
507 if (ep <= sp)
e6ff7b3b
OT
508 return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
509 (int)(ep-atom), atom);
c95b7585
KN
510
511 /* Do we have the atom already used elsewhere? */
512 for (i = 0; i < used_atom_cnt; i++) {
b072add7
KN
513 int len = strlen(used_atom[i].name);
514 if (len == ep - atom && !memcmp(used_atom[i].name, atom, len))
c95b7585
KN
515 return i;
516 }
517
e94ce139
SG
518 /*
519 * If the atom name has a colon, strip it and everything after
520 * it off - it specifies the format for this entry, and
521 * shouldn't be used for checking against the valid_atom
522 * table.
523 */
524 arg = memchr(sp, ':', ep - sp);
525 atom_len = (arg ? arg : ep) - sp;
526
c95b7585
KN
527 /* Is the atom a valid one? */
528 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
529 int len = strlen(valid_atom[i].name);
e94ce139 530 if (len == atom_len && !memcmp(valid_atom[i].name, sp, len))
c95b7585
KN
531 break;
532 }
533
534 if (ARRAY_SIZE(valid_atom) <= i)
e6ff7b3b
OT
535 return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
536 (int)(ep-atom), atom);
c95b7585
KN
537
538 /* Add it in, including the deref prefix */
539 at = used_atom_cnt;
540 used_atom_cnt++;
541 REALLOC_ARRAY(used_atom, used_atom_cnt);
b072add7
KN
542 used_atom[at].name = xmemdupz(atom, ep - atom);
543 used_atom[at].type = valid_atom[i].cmp_type;
a8e7e385 544 used_atom[at].source = valid_atom[i].source;
aa46a0da
OT
545 if (used_atom[at].source == SOURCE_OBJ) {
546 if (*atom == '*')
547 oi_deref.info.contentp = &oi_deref.content;
548 else
549 oi.info.contentp = &oi.content;
550 }
bea4dbea 551 if (arg) {
4de707ea 552 arg = used_atom[at].name + (arg - atom) + 1;
bea4dbea
TB
553 if (!*arg) {
554 /*
555 * Treat empty sub-arguments list as NULL (i.e.,
556 * "%(atom:)" is equivalent to "%(atom)").
557 */
558 arg = NULL;
559 }
560 }
fd935cc7 561 memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
74efea94
OT
562 if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
563 return -1;
c95b7585
KN
564 if (*atom == '*')
565 need_tagged = 1;
01f95825 566 if (!strcmp(valid_atom[i].name, "symref"))
c95b7585
KN
567 need_symref = 1;
568 return at;
569}
570
63d89fbc
KN
571static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
572{
573 switch (quote_style) {
574 case QUOTE_NONE:
575 strbuf_addstr(s, str);
576 break;
577 case QUOTE_SHELL:
578 sq_quote_buf(s, str);
579 break;
580 case QUOTE_PERL:
581 perl_quote_buf(s, str);
582 break;
583 case QUOTE_PYTHON:
584 python_quote_buf(s, str);
585 break;
586 case QUOTE_TCL:
587 tcl_quote_buf(s, str);
588 break;
589 }
590}
591
3fc8439c
OT
592static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
593 struct strbuf *unused_err)
63d89fbc 594{
ce592082
KN
595 /*
596 * Quote formatting is only done when the stack has a single
597 * element. Otherwise quote formatting is done on the
598 * element's entire output strbuf when the %(end) atom is
599 * encountered.
600 */
601 if (!state->stack->prev)
602 quote_formatting(&state->stack->output, v->s, state->quote_style);
603 else
604 strbuf_addstr(&state->stack->output, v->s);
3fc8439c 605 return 0;
63d89fbc
KN
606}
607
574e96a2
KN
608static void push_stack_element(struct ref_formatting_stack **stack)
609{
610 struct ref_formatting_stack *s = xcalloc(1, sizeof(struct ref_formatting_stack));
611
612 strbuf_init(&s->output, 0);
613 s->prev = *stack;
614 *stack = s;
615}
616
617static void pop_stack_element(struct ref_formatting_stack **stack)
618{
619 struct ref_formatting_stack *current = *stack;
620 struct ref_formatting_stack *prev = current->prev;
621
622 if (prev)
623 strbuf_addbuf(&prev->output, &current->output);
624 strbuf_release(&current->output);
625 free(current);
626 *stack = prev;
627}
628
c58492d4 629static void end_align_handler(struct ref_formatting_stack **stack)
ce592082 630{
c58492d4
KN
631 struct ref_formatting_stack *cur = *stack;
632 struct align *align = (struct align *)cur->at_end_data;
ce592082
KN
633 struct strbuf s = STRBUF_INIT;
634
c58492d4
KN
635 strbuf_utf8_align(&s, align->position, align->width, cur->output.buf);
636 strbuf_swap(&cur->output, &s);
ce592082
KN
637 strbuf_release(&s);
638}
639
3fc8439c
OT
640static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
641 struct strbuf *unused_err)
ce592082 642{
1472b5bf 643 struct ref_formatting_stack *new_stack;
ce592082
KN
644
645 push_stack_element(&state->stack);
1472b5bf
BW
646 new_stack = state->stack;
647 new_stack->at_end = end_align_handler;
648 new_stack->at_end_data = &atomv->atom->u.align;
3fc8439c 649 return 0;
ce592082
KN
650}
651
c58492d4
KN
652static void if_then_else_handler(struct ref_formatting_stack **stack)
653{
654 struct ref_formatting_stack *cur = *stack;
655 struct ref_formatting_stack *prev = cur->prev;
656 struct if_then_else *if_then_else = (struct if_then_else *)cur->at_end_data;
657
658 if (!if_then_else->then_atom_seen)
659 die(_("format: %%(if) atom used without a %%(then) atom"));
660
661 if (if_then_else->else_atom_seen) {
662 /*
663 * There is an %(else) atom: we need to drop one state from the
664 * stack, either the %(else) branch if the condition is satisfied, or
665 * the %(then) branch if it isn't.
666 */
667 if (if_then_else->condition_satisfied) {
668 strbuf_reset(&cur->output);
669 pop_stack_element(&cur);
670 } else {
671 strbuf_swap(&cur->output, &prev->output);
672 strbuf_reset(&cur->output);
673 pop_stack_element(&cur);
674 }
675 } else if (!if_then_else->condition_satisfied) {
676 /*
677 * No %(else) atom: just drop the %(then) branch if the
678 * condition is not satisfied.
679 */
680 strbuf_reset(&cur->output);
681 }
682
683 *stack = cur;
684 free(if_then_else);
685}
686
3fc8439c
OT
687static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
688 struct strbuf *unused_err)
c58492d4 689{
1472b5bf 690 struct ref_formatting_stack *new_stack;
c58492d4
KN
691 struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
692
4f3e3b37
KN
693 if_then_else->str = atomv->atom->u.if_then_else.str;
694 if_then_else->cmp_status = atomv->atom->u.if_then_else.cmp_status;
695
c58492d4 696 push_stack_element(&state->stack);
1472b5bf
BW
697 new_stack = state->stack;
698 new_stack->at_end = if_then_else_handler;
699 new_stack->at_end_data = if_then_else;
3fc8439c 700 return 0;
c58492d4
KN
701}
702
703static int is_empty(const char *s)
704{
705 while (*s != '\0') {
706 if (!isspace(*s))
707 return 0;
708 s++;
709 }
710 return 1;
711}
712
3fc8439c
OT
713static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
714 struct strbuf *err)
c58492d4
KN
715{
716 struct ref_formatting_stack *cur = state->stack;
717 struct if_then_else *if_then_else = NULL;
718
719 if (cur->at_end == if_then_else_handler)
720 if_then_else = (struct if_then_else *)cur->at_end_data;
721 if (!if_then_else)
3fc8439c 722 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
c58492d4 723 if (if_then_else->then_atom_seen)
3fc8439c 724 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
c58492d4 725 if (if_then_else->else_atom_seen)
3fc8439c 726 return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
c58492d4
KN
727 if_then_else->then_atom_seen = 1;
728 /*
4f3e3b37
KN
729 * If the 'equals' or 'notequals' attribute is used then
730 * perform the required comparison. If not, only non-empty
731 * strings satisfy the 'if' condition.
c58492d4 732 */
4f3e3b37
KN
733 if (if_then_else->cmp_status == COMPARE_EQUAL) {
734 if (!strcmp(if_then_else->str, cur->output.buf))
735 if_then_else->condition_satisfied = 1;
736 } else if (if_then_else->cmp_status == COMPARE_UNEQUAL) {
737 if (strcmp(if_then_else->str, cur->output.buf))
738 if_then_else->condition_satisfied = 1;
739 } else if (cur->output.len && !is_empty(cur->output.buf))
c58492d4
KN
740 if_then_else->condition_satisfied = 1;
741 strbuf_reset(&cur->output);
3fc8439c 742 return 0;
c58492d4
KN
743}
744
3fc8439c
OT
745static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
746 struct strbuf *err)
c58492d4
KN
747{
748 struct ref_formatting_stack *prev = state->stack;
749 struct if_then_else *if_then_else = NULL;
750
751 if (prev->at_end == if_then_else_handler)
752 if_then_else = (struct if_then_else *)prev->at_end_data;
753 if (!if_then_else)
3fc8439c 754 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
c58492d4 755 if (!if_then_else->then_atom_seen)
3fc8439c 756 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
c58492d4 757 if (if_then_else->else_atom_seen)
3fc8439c 758 return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
c58492d4
KN
759 if_then_else->else_atom_seen = 1;
760 push_stack_element(&state->stack);
761 state->stack->at_end_data = prev->at_end_data;
762 state->stack->at_end = prev->at_end;
3fc8439c 763 return 0;
ce592082
KN
764}
765
3fc8439c
OT
766static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
767 struct strbuf *err)
ce592082
KN
768{
769 struct ref_formatting_stack *current = state->stack;
770 struct strbuf s = STRBUF_INIT;
771
772 if (!current->at_end)
3fc8439c 773 return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
c58492d4
KN
774 current->at_end(&state->stack);
775
776 /* Stack may have been popped within at_end(), hence reset the current pointer */
777 current = state->stack;
ce592082
KN
778
779 /*
780 * Perform quote formatting when the stack element is that of
781 * a supporting atom. If nested then perform quote formatting
782 * only on the topmost supporting atom.
783 */
c58492d4 784 if (!current->prev->prev) {
ce592082
KN
785 quote_formatting(&s, current->output.buf, state->quote_style);
786 strbuf_swap(&current->output, &s);
787 }
788 strbuf_release(&s);
789 pop_stack_element(&state->stack);
3fc8439c 790 return 0;
ce592082
KN
791}
792
c95b7585
KN
793/*
794 * In a format string, find the next occurrence of %(atom).
795 */
796static const char *find_next(const char *cp)
797{
798 while (*cp) {
799 if (*cp == '%') {
800 /*
801 * %( is the start of an atom;
802 * %% is a quoted per-cent.
803 */
804 if (cp[1] == '(')
805 return cp;
806 else if (cp[1] == '%')
807 cp++; /* skip over two % */
808 /* otherwise this is a singleton, literal % */
809 }
810 cp++;
811 }
812 return NULL;
813}
814
815/*
816 * Make sure the format string is well formed, and parse out
817 * the used atoms.
818 */
4a68e36d 819int verify_ref_format(struct ref_format *format)
c95b7585
KN
820{
821 const char *cp, *sp;
822
bf285ae6 823 format->need_color_reset_at_eol = 0;
4a68e36d 824 for (cp = format->format; *cp && (sp = find_next(cp)); ) {
e6ff7b3b 825 struct strbuf err = STRBUF_INIT;
c95b7585
KN
826 const char *color, *ep = strchr(sp, ')');
827 int at;
828
829 if (!ep)
1823c619 830 return error(_("malformed format string %s"), sp);
c95b7585 831 /* sp points at "%(" and ep points at the closing ")" */
e6ff7b3b
OT
832 at = parse_ref_filter_atom(format, sp + 2, ep, &err);
833 if (at < 0)
834 die("%s", err.buf);
c95b7585
KN
835 cp = ep + 1;
836
b072add7 837 if (skip_prefix(used_atom[at].name, "color:", &color))
bf285ae6 838 format->need_color_reset_at_eol = !!strcmp(color, "reset");
e6ff7b3b 839 strbuf_release(&err);
c95b7585 840 }
11b087ad
JK
841 if (format->need_color_reset_at_eol && !want_color(format->use_color))
842 format->need_color_reset_at_eol = 0;
c95b7585
KN
843 return 0;
844}
845
17769795 846static int grab_objectname(const char *name, const struct object_id *oid,
fe63c4d1 847 struct atom_value *v, struct used_atom *atom)
c95b7585 848{
fe63c4d1 849 if (starts_with(name, "objectname")) {
42d0eb05 850 if (atom->u.objectname.option == O_SHORT) {
aab9583f 851 v->s = xstrdup(find_unique_abbrev(oid, DEFAULT_ABBREV));
fe63c4d1 852 return 1;
42d0eb05 853 } else if (atom->u.objectname.option == O_FULL) {
17769795 854 v->s = xstrdup(oid_to_hex(oid));
fe63c4d1 855 return 1;
42d0eb05 856 } else if (atom->u.objectname.option == O_LENGTH) {
aab9583f 857 v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
42d0eb05 858 return 1;
fe63c4d1 859 } else
033abf97 860 BUG("unknown %%(objectname) option");
c95b7585
KN
861 }
862 return 0;
863}
864
865/* See grab_values */
aa46a0da 866static void grab_common_values(struct atom_value *val, int deref, struct expand_data *oi)
c95b7585
KN
867{
868 int i;
869
870 for (i = 0; i < used_atom_cnt; i++) {
b072add7 871 const char *name = used_atom[i].name;
c95b7585
KN
872 struct atom_value *v = &val[i];
873 if (!!deref != (*name == '*'))
874 continue;
875 if (deref)
876 name++;
877 if (!strcmp(name, "objecttype"))
aa46a0da 878 v->s = type_name(oi->type);
c95b7585 879 else if (!strcmp(name, "objectsize")) {
aa46a0da
OT
880 v->value = oi->size;
881 v->s = xstrfmt("%lu", oi->size);
c95b7585
KN
882 }
883 else if (deref)
aa46a0da 884 grab_objectname(name, &oi->oid, v, &used_atom[i]);
c95b7585
KN
885 }
886}
887
888/* See grab_values */
889static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
890{
891 int i;
892 struct tag *tag = (struct tag *) obj;
893
894 for (i = 0; i < used_atom_cnt; i++) {
b072add7 895 const char *name = used_atom[i].name;
c95b7585
KN
896 struct atom_value *v = &val[i];
897 if (!!deref != (*name == '*'))
898 continue;
899 if (deref)
900 name++;
901 if (!strcmp(name, "tag"))
902 v->s = tag->tag;
903 else if (!strcmp(name, "type") && tag->tagged)
debca9d2 904 v->s = type_name(tag->tagged->type);
a5e03bf5 905 else if (!strcmp(name, "object") && tag->tagged)
f2fd0760 906 v->s = xstrdup(oid_to_hex(&tag->tagged->oid));
c95b7585
KN
907 }
908}
909
910/* See grab_values */
911static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
912{
913 int i;
914 struct commit *commit = (struct commit *) obj;
915
916 for (i = 0; i < used_atom_cnt; i++) {
b072add7 917 const char *name = used_atom[i].name;
c95b7585
KN
918 struct atom_value *v = &val[i];
919 if (!!deref != (*name == '*'))
920 continue;
921 if (deref)
922 name++;
923 if (!strcmp(name, "tree")) {
2e27bd77 924 v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
c95b7585 925 }
a5e03bf5 926 else if (!strcmp(name, "numparent")) {
e467dc14
JS
927 v->value = commit_list_count(commit->parents);
928 v->s = xstrfmt("%lu", (unsigned long)v->value);
c95b7585
KN
929 }
930 else if (!strcmp(name, "parent")) {
c95b7585 931 struct commit_list *parents;
a5e03bf5
JK
932 struct strbuf s = STRBUF_INIT;
933 for (parents = commit->parents; parents; parents = parents->next) {
c95b7585 934 struct commit *parent = parents->item;
a5e03bf5
JK
935 if (parents != commit->parents)
936 strbuf_addch(&s, ' ');
f2fd0760 937 strbuf_addstr(&s, oid_to_hex(&parent->object.oid));
c95b7585 938 }
a5e03bf5 939 v->s = strbuf_detach(&s, NULL);
c95b7585
KN
940 }
941 }
942}
943
944static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
945{
946 const char *eol;
947 while (*buf) {
948 if (!strncmp(buf, who, wholen) &&
949 buf[wholen] == ' ')
950 return buf + wholen + 1;
951 eol = strchr(buf, '\n');
952 if (!eol)
953 return "";
954 eol++;
955 if (*eol == '\n')
956 return ""; /* end of header */
957 buf = eol;
958 }
959 return "";
960}
961
962static const char *copy_line(const char *buf)
963{
964 const char *eol = strchrnul(buf, '\n');
965 return xmemdupz(buf, eol - buf);
966}
967
968static const char *copy_name(const char *buf)
969{
970 const char *cp;
971 for (cp = buf; *cp && *cp != '\n'; cp++) {
972 if (!strncmp(cp, " <", 2))
973 return xmemdupz(buf, cp - buf);
974 }
975 return "";
976}
977
978static const char *copy_email(const char *buf)
979{
980 const char *email = strchr(buf, '<');
981 const char *eoemail;
982 if (!email)
983 return "";
984 eoemail = strchr(email, '>');
985 if (!eoemail)
986 return "";
987 return xmemdupz(email, eoemail + 1 - email);
988}
989
990static char *copy_subject(const char *buf, unsigned long len)
991{
992 char *r = xmemdupz(buf, len);
993 int i;
994
995 for (i = 0; i < len; i++)
996 if (r[i] == '\n')
997 r[i] = ' ';
998
999 return r;
1000}
1001
1002static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
1003{
1004 const char *eoemail = strstr(buf, "> ");
1005 char *zone;
dddbad72 1006 timestamp_t timestamp;
c95b7585 1007 long tz;
d939af12 1008 struct date_mode date_mode = { DATE_NORMAL };
c95b7585
KN
1009 const char *formatp;
1010
1011 /*
1012 * We got here because atomname ends in "date" or "date<something>";
1013 * it's not possible that <something> is not ":<format>" because
1014 * parse_ref_filter_atom() wouldn't have allowed it, so we can assume that no
1015 * ":" means no format is specified, and use the default.
1016 */
1017 formatp = strchr(atomname, ':');
1018 if (formatp != NULL) {
1019 formatp++;
d939af12 1020 parse_date_format(formatp, &date_mode);
c95b7585
KN
1021 }
1022
1023 if (!eoemail)
1024 goto bad;
1aeb7e75 1025 timestamp = parse_timestamp(eoemail + 2, &zone, 10);
dddbad72 1026 if (timestamp == TIME_MAX)
c95b7585
KN
1027 goto bad;
1028 tz = strtol(zone, NULL, 10);
1029 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
1030 goto bad;
d939af12 1031 v->s = xstrdup(show_date(timestamp, tz, &date_mode));
e467dc14 1032 v->value = timestamp;
c95b7585
KN
1033 return;
1034 bad:
1035 v->s = "";
e467dc14 1036 v->value = 0;
c95b7585
KN
1037}
1038
1039/* See grab_values */
1040static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1041{
1042 int i;
1043 int wholen = strlen(who);
1044 const char *wholine = NULL;
1045
1046 for (i = 0; i < used_atom_cnt; i++) {
b072add7 1047 const char *name = used_atom[i].name;
c95b7585
KN
1048 struct atom_value *v = &val[i];
1049 if (!!deref != (*name == '*'))
1050 continue;
1051 if (deref)
1052 name++;
1053 if (strncmp(who, name, wholen))
1054 continue;
1055 if (name[wholen] != 0 &&
1056 strcmp(name + wholen, "name") &&
1057 strcmp(name + wholen, "email") &&
1058 !starts_with(name + wholen, "date"))
1059 continue;
1060 if (!wholine)
1061 wholine = find_wholine(who, wholen, buf, sz);
1062 if (!wholine)
1063 return; /* no point looking for it */
1064 if (name[wholen] == 0)
1065 v->s = copy_line(wholine);
1066 else if (!strcmp(name + wholen, "name"))
1067 v->s = copy_name(wholine);
1068 else if (!strcmp(name + wholen, "email"))
1069 v->s = copy_email(wholine);
1070 else if (starts_with(name + wholen, "date"))
1071 grab_date(wholine, v, name);
1072 }
1073
1074 /*
1075 * For a tag or a commit object, if "creator" or "creatordate" is
1076 * requested, do something special.
1077 */
1078 if (strcmp(who, "tagger") && strcmp(who, "committer"))
1079 return; /* "author" for commit object is not wanted */
1080 if (!wholine)
1081 wholine = find_wholine(who, wholen, buf, sz);
1082 if (!wholine)
1083 return;
1084 for (i = 0; i < used_atom_cnt; i++) {
b072add7 1085 const char *name = used_atom[i].name;
c95b7585
KN
1086 struct atom_value *v = &val[i];
1087 if (!!deref != (*name == '*'))
1088 continue;
1089 if (deref)
1090 name++;
1091
1092 if (starts_with(name, "creatordate"))
1093 grab_date(wholine, v, name);
1094 else if (!strcmp(name, "creator"))
1095 v->s = copy_line(wholine);
1096 }
1097}
1098
1099static void find_subpos(const char *buf, unsigned long sz,
1100 const char **sub, unsigned long *sublen,
1101 const char **body, unsigned long *bodylen,
1102 unsigned long *nonsiglen,
1103 const char **sig, unsigned long *siglen)
1104{
1105 const char *eol;
1106 /* skip past header until we hit empty line */
1107 while (*buf && *buf != '\n') {
1108 eol = strchrnul(buf, '\n');
1109 if (*eol)
1110 eol++;
1111 buf = eol;
1112 }
1113 /* skip any empty lines */
1114 while (*buf == '\n')
1115 buf++;
1116
1117 /* parse signature first; we might not even have a subject line */
1118 *sig = buf + parse_signature(buf, strlen(buf));
1119 *siglen = strlen(*sig);
1120
1121 /* subject is first non-empty line */
1122 *sub = buf;
1123 /* subject goes to first empty line */
1124 while (buf < *sig && *buf && *buf != '\n') {
1125 eol = strchrnul(buf, '\n');
1126 if (*eol)
1127 eol++;
1128 buf = eol;
1129 }
1130 *sublen = buf - *sub;
1131 /* drop trailing newline, if present */
1132 if (*sublen && (*sub)[*sublen - 1] == '\n')
1133 *sublen -= 1;
1134
1135 /* skip any empty lines */
1136 while (*buf == '\n')
1137 buf++;
1138 *body = buf;
1139 *bodylen = strlen(buf);
1140 *nonsiglen = *sig - buf;
1141}
1142
1bb38e5a
KN
1143/*
1144 * If 'lines' is greater than 0, append that many lines from the given
1145 * 'buf' of length 'size' to the given strbuf.
1146 */
1147static void append_lines(struct strbuf *out, const char *buf, unsigned long size, int lines)
1148{
1149 int i;
1150 const char *sp, *eol;
1151 size_t len;
1152
1153 sp = buf;
1154
1155 for (i = 0; i < lines && sp < buf + size; i++) {
1156 if (i)
1157 strbuf_addstr(out, "\n ");
1158 eol = memchr(sp, '\n', size - (sp - buf));
1159 len = eol ? eol - sp : size - (sp - buf);
1160 strbuf_add(out, sp, len);
1161 if (!eol)
1162 break;
1163 sp = eol + 1;
1164 }
1165}
1166
c95b7585
KN
1167/* See grab_values */
1168static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1169{
1170 int i;
1171 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
1172 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
1173
1174 for (i = 0; i < used_atom_cnt; i++) {
452db397
KN
1175 struct used_atom *atom = &used_atom[i];
1176 const char *name = atom->name;
c95b7585
KN
1177 struct atom_value *v = &val[i];
1178 if (!!deref != (*name == '*'))
1179 continue;
1180 if (deref)
1181 name++;
1182 if (strcmp(name, "subject") &&
1183 strcmp(name, "body") &&
67a20a00 1184 !starts_with(name, "trailers") &&
452db397 1185 !starts_with(name, "contents"))
c95b7585
KN
1186 continue;
1187 if (!subpos)
1188 find_subpos(buf, sz,
1189 &subpos, &sublen,
1190 &bodypos, &bodylen, &nonsiglen,
1191 &sigpos, &siglen);
1192
452db397 1193 if (atom->u.contents.option == C_SUB)
c95b7585 1194 v->s = copy_subject(subpos, sublen);
452db397 1195 else if (atom->u.contents.option == C_BODY_DEP)
c95b7585 1196 v->s = xmemdupz(bodypos, bodylen);
452db397 1197 else if (atom->u.contents.option == C_BODY)
c95b7585 1198 v->s = xmemdupz(bodypos, nonsiglen);
452db397 1199 else if (atom->u.contents.option == C_SIG)
c95b7585 1200 v->s = xmemdupz(sigpos, siglen);
452db397 1201 else if (atom->u.contents.option == C_LINES) {
1bb38e5a
KN
1202 struct strbuf s = STRBUF_INIT;
1203 const char *contents_end = bodylen + bodypos - siglen;
1204
1bb38e5a 1205 /* Size is the length of the message after removing the signature */
452db397 1206 append_lines(&s, subpos, contents_end - subpos, atom->u.contents.nlines);
1bb38e5a 1207 v->s = strbuf_detach(&s, NULL);
b1d31c89 1208 } else if (atom->u.contents.option == C_TRAILERS) {
67a20a00 1209 struct strbuf s = STRBUF_INIT;
b1d31c89 1210
67a20a00
TB
1211 /* Format the trailer info according to the trailer_opts given */
1212 format_trailers_from_commit(&s, subpos, &atom->u.contents.trailer_opts);
1213
1214 v->s = strbuf_detach(&s, NULL);
452db397
KN
1215 } else if (atom->u.contents.option == C_BARE)
1216 v->s = xstrdup(subpos);
c95b7585
KN
1217 }
1218}
1219
1220/*
1221 * We want to have empty print-string for field requests
1222 * that do not apply (e.g. "authordate" for a tag object)
1223 */
1224static void fill_missing_values(struct atom_value *val)
1225{
1226 int i;
1227 for (i = 0; i < used_atom_cnt; i++) {
1228 struct atom_value *v = &val[i];
1229 if (v->s == NULL)
1230 v->s = "";
1231 }
1232}
1233
1234/*
1235 * val is a list of atom_value to hold returned values. Extract
1236 * the values for atoms in used_atom array out of (obj, buf, sz).
1237 * when deref is false, (obj, buf, sz) is the object that is
1238 * pointed at by the ref itself; otherwise it is the object the
1239 * ref (which is a tag) refers to.
1240 */
1241static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
1242{
c95b7585
KN
1243 switch (obj->type) {
1244 case OBJ_TAG:
1245 grab_tag_values(val, deref, obj, buf, sz);
1246 grab_sub_body_contents(val, deref, obj, buf, sz);
1247 grab_person("tagger", val, deref, obj, buf, sz);
1248 break;
1249 case OBJ_COMMIT:
1250 grab_commit_values(val, deref, obj, buf, sz);
1251 grab_sub_body_contents(val, deref, obj, buf, sz);
1252 grab_person("author", val, deref, obj, buf, sz);
1253 grab_person("committer", val, deref, obj, buf, sz);
1254 break;
1255 case OBJ_TREE:
1256 /* grab_tree_values(val, deref, obj, buf, sz); */
1257 break;
1258 case OBJ_BLOB:
1259 /* grab_blob_values(val, deref, obj, buf, sz); */
1260 break;
1261 default:
1262 die("Eh? Object of type %d?", obj->type);
1263 }
1264}
1265
1266static inline char *copy_advance(char *dst, const char *src)
1267{
1268 while (*src)
1269 *dst++ = *src++;
1270 return dst;
1271}
1272
1a0ca5e3 1273static const char *lstrip_ref_components(const char *refname, int len)
0571979b 1274{
a7984101 1275 long remaining = len;
0571979b
JK
1276 const char *start = refname;
1277
1a0ca5e3
KN
1278 if (len < 0) {
1279 int i;
1280 const char *p = refname;
1281
1282 /* Find total no of '/' separated path-components */
1283 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1284 ;
1285 /*
1286 * The number of components we need to strip is now
1287 * the total minus the components to be left (Plus one
1288 * because we count the number of '/', but the number
1289 * of components is one more than the no of '/').
1290 */
1291 remaining = i + len + 1;
1292 }
0571979b 1293
1a0ca5e3 1294 while (remaining > 0) {
0571979b
JK
1295 switch (*start++) {
1296 case '\0':
3a42980f 1297 return "";
0571979b
JK
1298 case '/':
1299 remaining--;
1300 break;
1301 }
1302 }
1a0ca5e3 1303
0571979b
JK
1304 return start;
1305}
1306
1a34728e
KN
1307static const char *rstrip_ref_components(const char *refname, int len)
1308{
1309 long remaining = len;
1310 char *start = xstrdup(refname);
1311
1312 if (len < 0) {
1313 int i;
1314 const char *p = refname;
1315
1316 /* Find total no of '/' separated path-components */
1317 for (i = 0; p[i]; p[i] == '/' ? i++ : *p++)
1318 ;
1319 /*
1320 * The number of components we need to strip is now
1321 * the total minus the components to be left (Plus one
1322 * because we count the number of '/', but the number
1323 * of components is one more than the no of '/').
1324 */
1325 remaining = i + len + 1;
1326 }
1327
1328 while (remaining-- > 0) {
1329 char *p = strrchr(start, '/');
1330 if (p == NULL)
1331 return "";
1332 else
1333 p[0] = '\0';
1334 }
1335 return start;
1336}
1337
a7984101
KN
1338static const char *show_ref(struct refname_atom *atom, const char *refname)
1339{
1340 if (atom->option == R_SHORT)
1341 return shorten_unambiguous_ref(refname, warn_ambiguous_refs);
17938f17
KN
1342 else if (atom->option == R_LSTRIP)
1343 return lstrip_ref_components(refname, atom->lstrip);
1a34728e
KN
1344 else if (atom->option == R_RSTRIP)
1345 return rstrip_ref_components(refname, atom->rstrip);
a7984101
KN
1346 else
1347 return refname;
1348}
1349
5339bdad
KN
1350static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
1351 struct branch *branch, const char **s)
1352{
1353 int num_ours, num_theirs;
3ba308cb
KN
1354 if (atom->u.remote_ref.option == RR_REF)
1355 *s = show_ref(&atom->u.remote_ref.refname, refname);
7743fcca 1356 else if (atom->u.remote_ref.option == RR_TRACK) {
d7d1b496
JH
1357 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1358 NULL, AHEAD_BEHIND_FULL) < 0) {
6eac70fa 1359 *s = xstrdup(msgs.gone);
7743fcca 1360 } else if (!num_ours && !num_theirs)
5339bdad
KN
1361 *s = "";
1362 else if (!num_ours)
6eac70fa 1363 *s = xstrfmt(msgs.behind, num_theirs);
5339bdad 1364 else if (!num_theirs)
6eac70fa 1365 *s = xstrfmt(msgs.ahead, num_ours);
5339bdad 1366 else
6eac70fa 1367 *s = xstrfmt(msgs.ahead_behind,
5339bdad 1368 num_ours, num_theirs);
7743fcca
KN
1369 if (!atom->u.remote_ref.nobracket && *s[0]) {
1370 const char *to_free = *s;
1371 *s = xstrfmt("[%s]", *s);
1372 free((void *)to_free);
1373 }
1374 } else if (atom->u.remote_ref.option == RR_TRACKSHORT) {
d7d1b496
JH
1375 if (stat_tracking_info(branch, &num_ours, &num_theirs,
1376 NULL, AHEAD_BEHIND_FULL) < 0)
5339bdad
KN
1377 return;
1378
1379 if (!num_ours && !num_theirs)
1380 *s = "=";
1381 else if (!num_ours)
1382 *s = "<";
1383 else if (!num_theirs)
1384 *s = ">";
1385 else
1386 *s = "<>";
cc72385f
JS
1387 } else if (atom->u.remote_ref.option == RR_REMOTE_NAME) {
1388 int explicit;
1389 const char *remote = atom->u.remote_ref.push ?
1390 pushremote_for_branch(branch, &explicit) :
1391 remote_for_branch(branch, &explicit);
1392 if (explicit)
1393 *s = xstrdup(remote);
1394 else
1395 *s = "";
9700fae5
W
1396 } else if (atom->u.remote_ref.option == RR_REMOTE_REF) {
1397 int explicit;
1398 const char *merge;
1399
1400 merge = remote_ref_for_branch(branch, atom->u.remote_ref.push,
1401 &explicit);
1402 if (explicit)
1403 *s = xstrdup(merge);
1404 else
1405 *s = "";
3ba308cb 1406 } else
033abf97 1407 BUG("unhandled RR_* enum");
5339bdad
KN
1408}
1409
d4919bb2
KN
1410char *get_head_description(void)
1411{
1412 struct strbuf desc = STRBUF_INIT;
1413 struct wt_status_state state;
1414 memset(&state, 0, sizeof(state));
1415 wt_status_get_state(&state, 1);
1416 if (state.rebase_in_progress ||
a236f900
KS
1417 state.rebase_interactive_in_progress) {
1418 if (state.branch)
1419 strbuf_addf(&desc, _("(no branch, rebasing %s)"),
1420 state.branch);
1421 else
1422 strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
1423 state.detached_from);
1424 } else if (state.bisect_in_progress)
d4919bb2
KN
1425 strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
1426 state.branch);
1427 else if (state.detached_from) {
d4919bb2 1428 if (state.detached_at)
66f5f6dc
ÆAB
1429 /*
1430 * TRANSLATORS: make sure this matches "HEAD
1431 * detached at " in wt-status.c
1432 */
d4919bb2
KN
1433 strbuf_addf(&desc, _("(HEAD detached at %s)"),
1434 state.detached_from);
1435 else
66f5f6dc
ÆAB
1436 /*
1437 * TRANSLATORS: make sure this matches "HEAD
1438 * detached from " in wt-status.c
1439 */
d4919bb2
KN
1440 strbuf_addf(&desc, _("(HEAD detached from %s)"),
1441 state.detached_from);
1442 }
1443 else
1444 strbuf_addstr(&desc, _("(no branch)"));
1445 free(state.branch);
1446 free(state.onto);
1447 free(state.detached_from);
1448 return strbuf_detach(&desc, NULL);
1449}
1450
a7984101
KN
1451static const char *get_symref(struct used_atom *atom, struct ref_array_item *ref)
1452{
1453 if (!ref->symref)
1454 return "";
1455 else
1456 return show_ref(&atom->u.refname, ref->symref);
1457}
1458
1459static const char *get_refname(struct used_atom *atom, struct ref_array_item *ref)
1460{
1461 if (ref->kind & FILTER_REFS_DETACHED_HEAD)
1462 return get_head_description();
1463 return show_ref(&atom->u.refname, ref->refname);
5339bdad
KN
1464}
1465
aa46a0da
OT
1466static int get_object(struct ref_array_item *ref, int deref, struct object **obj,
1467 struct expand_data *oi, struct strbuf *err)
2bbc6e8a 1468{
04f6ee1a
OT
1469 /* parse_object_buffer() will set eaten to 0 if free() will be needed */
1470 int eaten = 1;
aa46a0da
OT
1471 if (oi->info.contentp) {
1472 /* We need to know that to use parse_object_buffer properly */
1473 oi->info.sizep = &oi->size;
1474 oi->info.typep = &oi->type;
1475 }
1476 if (oid_object_info_extended(the_repository, &oi->oid, &oi->info,
1477 OBJECT_INFO_LOOKUP_REPLACE))
1478 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1479 oid_to_hex(&oi->oid), ref->refname);
1480
1481 if (oi->info.contentp) {
c83149ac 1482 *obj = parse_object_buffer(the_repository, &oi->oid, oi->type, oi->size, oi->content, &eaten);
aa46a0da
OT
1483 if (!obj) {
1484 if (!eaten)
1485 free(oi->content);
1486 return strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
1487 oid_to_hex(&oi->oid), ref->refname);
1488 }
1489 grab_values(ref->value, deref, *obj, oi->content, oi->size);
e2255179 1490 }
aa46a0da
OT
1491
1492 grab_common_values(ref->value, deref, oi);
2bbc6e8a 1493 if (!eaten)
aa46a0da
OT
1494 free(oi->content);
1495 return 0;
2bbc6e8a
OT
1496}
1497
c95b7585
KN
1498/*
1499 * Parse the object referred by ref, and grab needed value.
1500 */
e339611b 1501static int populate_value(struct ref_array_item *ref, struct strbuf *err)
c95b7585 1502{
c95b7585 1503 struct object *obj;
2bbc6e8a 1504 int i;
aa46a0da 1505 struct object_info empty = OBJECT_INFO_INIT;
c95b7585
KN
1506
1507 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1508
1509 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
c95b7585 1510 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
efbd4fdf 1511 NULL, NULL);
c95b7585
KN
1512 if (!ref->symref)
1513 ref->symref = "";
1514 }
1515
1516 /* Fill in specials first */
1517 for (i = 0; i < used_atom_cnt; i++) {
fd935cc7 1518 struct used_atom *atom = &used_atom[i];
b072add7 1519 const char *name = used_atom[i].name;
c95b7585
KN
1520 struct atom_value *v = &ref->value[i];
1521 int deref = 0;
1522 const char *refname;
c95b7585
KN
1523 struct branch *branch = NULL;
1524
63d89fbc 1525 v->handler = append_atom;
c58fc856 1526 v->atom = atom;
63d89fbc 1527
c95b7585
KN
1528 if (*name == '*') {
1529 deref = 1;
1530 name++;
1531 }
1532
1533 if (starts_with(name, "refname"))
a7984101 1534 refname = get_refname(atom, ref);
c95b7585 1535 else if (starts_with(name, "symref"))
a7984101 1536 refname = get_symref(atom, ref);
c95b7585
KN
1537 else if (starts_with(name, "upstream")) {
1538 const char *branch_name;
20a9c156 1539 v->s = "";
c95b7585
KN
1540 /* only local branches may have an upstream */
1541 if (!skip_prefix(ref->refname, "refs/heads/",
1542 &branch_name))
1543 continue;
1544 branch = branch_get(branch_name);
1545
1546 refname = branch_get_upstream(branch, NULL);
5339bdad
KN
1547 if (refname)
1548 fill_remote_ref_details(atom, refname, branch, &v->s);
1549 continue;
cc72385f 1550 } else if (atom->u.remote_ref.push) {
c95b7585 1551 const char *branch_name;
20a9c156 1552 v->s = "";
c95b7585
KN
1553 if (!skip_prefix(ref->refname, "refs/heads/",
1554 &branch_name))
1555 continue;
1556 branch = branch_get(branch_name);
1557
cc72385f
JS
1558 if (atom->u.remote_ref.push_remote)
1559 refname = NULL;
1560 else {
1561 refname = branch_get_push(branch, NULL);
1562 if (!refname)
1563 continue;
1564 }
5339bdad
KN
1565 fill_remote_ref_details(atom, refname, branch, &v->s);
1566 continue;
fd935cc7
KN
1567 } else if (starts_with(name, "color:")) {
1568 v->s = atom->u.color;
c95b7585
KN
1569 continue;
1570 } else if (!strcmp(name, "flag")) {
1571 char buf[256], *cp = buf;
1572 if (ref->flag & REF_ISSYMREF)
1573 cp = copy_advance(cp, ",symref");
1574 if (ref->flag & REF_ISPACKED)
1575 cp = copy_advance(cp, ",packed");
1576 if (cp == buf)
1577 v->s = "";
1578 else {
1579 *cp = '\0';
1580 v->s = xstrdup(buf + 1);
1581 }
1582 continue;
17769795 1583 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
c95b7585
KN
1584 continue;
1585 } else if (!strcmp(name, "HEAD")) {
613a0e52 1586 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
c95b7585
KN
1587 v->s = "*";
1588 else
1589 v->s = " ";
1590 continue;
5bd881d9 1591 } else if (starts_with(name, "align")) {
ce592082 1592 v->handler = align_atom_handler;
20a9c156 1593 v->s = "";
ce592082
KN
1594 continue;
1595 } else if (!strcmp(name, "end")) {
1596 v->handler = end_atom_handler;
20a9c156 1597 v->s = "";
ce592082 1598 continue;
4f3e3b37
KN
1599 } else if (starts_with(name, "if")) {
1600 const char *s;
20a9c156 1601 v->s = "";
4f3e3b37
KN
1602 if (skip_prefix(name, "if:", &s))
1603 v->s = xstrdup(s);
c58492d4
KN
1604 v->handler = if_atom_handler;
1605 continue;
1606 } else if (!strcmp(name, "then")) {
1607 v->handler = then_atom_handler;
20a9c156 1608 v->s = "";
c58492d4
KN
1609 continue;
1610 } else if (!strcmp(name, "else")) {
1611 v->handler = else_atom_handler;
20a9c156 1612 v->s = "";
c58492d4 1613 continue;
c95b7585
KN
1614 } else
1615 continue;
1616
c95b7585
KN
1617 if (!deref)
1618 v->s = refname;
a5e03bf5
JK
1619 else
1620 v->s = xstrfmt("%s^{}", refname);
c95b7585
KN
1621 }
1622
1623 for (i = 0; i < used_atom_cnt; i++) {
1624 struct atom_value *v = &ref->value[i];
aa46a0da
OT
1625 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1626 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1627 oid_to_hex(&ref->objectname), ref->refname);
c95b7585 1628 }
aa46a0da
OT
1629
1630 if (need_tagged)
1631 oi.info.contentp = &oi.content;
1632 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1633 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
e339611b 1634 return 0;
c95b7585 1635
aa46a0da
OT
1636
1637 oi.oid = ref->objectname;
1638 if (get_object(ref, 0, &obj, &oi, err))
e339611b 1639 return -1;
c95b7585
KN
1640
1641 /*
1642 * If there is no atom that wants to know about tagged
1643 * object, we are done.
1644 */
1645 if (!need_tagged || (obj->type != OBJ_TAG))
e339611b 1646 return 0;
c95b7585
KN
1647
1648 /*
1649 * If it is a tag object, see if we use a value that derefs
1650 * the object, and if we do grab the object it refers to.
1651 */
aa46a0da 1652 oi_deref.oid = ((struct tag *)obj)->tagged->oid;
c95b7585
KN
1653
1654 /*
1655 * NEEDSWORK: This derefs tag only once, which
1656 * is good to deal with chains of trust, but
1657 * is not consistent with what deref_tag() does
1658 * which peels the onion to the core.
1659 */
aa46a0da 1660 return get_object(ref, 1, &obj, &oi_deref, err);
c95b7585
KN
1661}
1662
1663/*
1664 * Given a ref, return the value for the atom. This lazily gets value
1665 * out of the object by calling populate value.
1666 */
e339611b
OT
1667static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1668 struct atom_value **v, struct strbuf *err)
c95b7585
KN
1669{
1670 if (!ref->value) {
e339611b
OT
1671 if (populate_value(ref, err))
1672 return -1;
c95b7585
KN
1673 fill_missing_values(ref->value);
1674 }
1675 *v = &ref->value[atom];
e339611b 1676 return 0;
c95b7585
KN
1677}
1678
bef0e12b
KN
1679/*
1680 * Return 1 if the refname matches one of the patterns, otherwise 0.
1681 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1682 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1683 * matches "refs/heads/mas*", too).
1684 */
3bb16a8b 1685static int match_pattern(const struct ref_filter *filter, const char *refname)
bef0e12b 1686{
3bb16a8b
NTND
1687 const char **patterns = filter->name_patterns;
1688 unsigned flags = 0;
1689
1690 if (filter->ignore_case)
1691 flags |= WM_CASEFOLD;
1692
bef0e12b
KN
1693 /*
1694 * When no '--format' option is given we need to skip the prefix
1695 * for matching refs of tags and branches.
1696 */
1697 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1698 skip_prefix(refname, "refs/heads/", &refname) ||
1699 skip_prefix(refname, "refs/remotes/", &refname) ||
1700 skip_prefix(refname, "refs/", &refname));
1701
1702 for (; *patterns; patterns++) {
55d34269 1703 if (!wildmatch(*patterns, refname, flags))
bef0e12b
KN
1704 return 1;
1705 }
1706 return 0;
1707}
1708
c95b7585
KN
1709/*
1710 * Return 1 if the refname matches one of the patterns, otherwise 0.
1711 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
bef0e12b
KN
1712 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1713 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
c95b7585 1714 */
3bb16a8b 1715static int match_name_as_path(const struct ref_filter *filter, const char *refname)
c95b7585 1716{
3bb16a8b 1717 const char **pattern = filter->name_patterns;
c95b7585 1718 int namelen = strlen(refname);
3bb16a8b
NTND
1719 unsigned flags = WM_PATHNAME;
1720
1721 if (filter->ignore_case)
1722 flags |= WM_CASEFOLD;
1723
c95b7585
KN
1724 for (; *pattern; pattern++) {
1725 const char *p = *pattern;
1726 int plen = strlen(p);
1727
1728 if ((plen <= namelen) &&
1729 !strncmp(refname, p, plen) &&
1730 (refname[plen] == '\0' ||
1731 refname[plen] == '/' ||
1732 p[plen-1] == '/'))
1733 return 1;
639ab5ef 1734 if (!wildmatch(p, refname, flags))
c95b7585
KN
1735 return 1;
1736 }
1737 return 0;
1738}
1739
bef0e12b
KN
1740/* Return 1 if the refname matches one of the patterns, otherwise 0. */
1741static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1742{
1743 if (!*filter->name_patterns)
1744 return 1; /* No pattern always matches */
1745 if (filter->match_as_path)
3bb16a8b
NTND
1746 return match_name_as_path(filter, refname);
1747 return match_pattern(filter, refname);
bef0e12b
KN
1748}
1749
cfe004a5
JK
1750/*
1751 * Find the longest prefix of pattern we can pass to
1752 * `for_each_fullref_in()`, namely the part of pattern preceding the
1753 * first glob character. (Note that `for_each_fullref_in()` is
1754 * perfectly happy working with a prefix that doesn't end at a
1755 * pathname component boundary.)
1756 */
1757static void find_longest_prefix(struct strbuf *out, const char *pattern)
1758{
1759 const char *p;
1760
1761 for (p = pattern; *p && !is_glob_special(*p); p++)
1762 ;
1763
1764 strbuf_add(out, pattern, p - pattern);
1765}
1766
1767/*
1768 * This is the same as for_each_fullref_in(), but it tries to iterate
1769 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1770 * pattern match, so the callback still has to match each ref individually.
1771 */
1772static int for_each_fullref_in_pattern(struct ref_filter *filter,
1773 each_ref_fn cb,
1774 void *cb_data,
1775 int broken)
1776{
1777 struct strbuf prefix = STRBUF_INIT;
1778 int ret;
1779
1780 if (!filter->match_as_path) {
1781 /*
1782 * in this case, the patterns are applied after
1783 * prefixes like "refs/heads/" etc. are stripped off,
1784 * so we have to look at everything:
1785 */
1786 return for_each_fullref_in("", cb, cb_data, broken);
1787 }
1788
e674eb25
JK
1789 if (filter->ignore_case) {
1790 /*
1791 * we can't handle case-insensitive comparisons,
1792 * so just return everything and let the caller
1793 * sort it out.
1794 */
1795 return for_each_fullref_in("", cb, cb_data, broken);
1796 }
1797
cfe004a5
JK
1798 if (!filter->name_patterns[0]) {
1799 /* no patterns; we have to look at everything */
1800 return for_each_fullref_in("", cb, cb_data, broken);
1801 }
1802
1803 if (filter->name_patterns[1]) {
1804 /*
1805 * multiple patterns; in theory this could still work as long
1806 * as the patterns are disjoint. We'd just make multiple calls
1807 * to for_each_ref(). But if they're not disjoint, we'd end up
1808 * reporting the same ref multiple times. So let's punt on that
1809 * for now.
1810 */
1811 return for_each_fullref_in("", cb, cb_data, broken);
1812 }
1813
1814 find_longest_prefix(&prefix, filter->name_patterns[0]);
1815
1816 ret = for_each_fullref_in(prefix.buf, cb, cb_data, broken);
1817 strbuf_release(&prefix);
1818 return ret;
1819}
1820
68411046
KN
1821/*
1822 * Given a ref (sha1, refname), check if the ref belongs to the array
1823 * of sha1s. If the given ref is a tag, check if the given tag points
1824 * at one of the sha1s in the given sha1 array.
1825 * the given sha1_array.
1826 * NEEDSWORK:
1827 * 1. Only a single level of inderection is obtained, we might want to
1828 * change this to account for multiple levels (e.g. annotated tags
1829 * pointing to annotated tags pointing to a commit.)
1830 * 2. As the refs are cached we might know what refname peels to without
1831 * the need to parse the object via parse_object(). peel_ref() might be a
1832 * more efficient alternative to obtain the pointee.
1833 */
910650d2 1834static const struct object_id *match_points_at(struct oid_array *points_at,
4ce3621a 1835 const struct object_id *oid,
1836 const char *refname)
68411046 1837{
4ce3621a 1838 const struct object_id *tagged_oid = NULL;
68411046
KN
1839 struct object *obj;
1840
910650d2 1841 if (oid_array_lookup(points_at, oid) >= 0)
4ce3621a 1842 return oid;
109cd76d 1843 obj = parse_object(the_repository, oid);
68411046
KN
1844 if (!obj)
1845 die(_("malformed object at '%s'"), refname);
1846 if (obj->type == OBJ_TAG)
4ce3621a 1847 tagged_oid = &((struct tag *)obj)->tagged->oid;
910650d2 1848 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
4ce3621a 1849 return tagged_oid;
68411046
KN
1850 return NULL;
1851}
1852
0ffaa00f
JK
1853/*
1854 * Allocate space for a new ref_array_item and copy the name and oid to it.
1855 *
1856 * Callers can then fill in other struct members at their leisure.
1857 */
c95b7585 1858static struct ref_array_item *new_ref_array_item(const char *refname,
0ffaa00f 1859 const struct object_id *oid)
c95b7585 1860{
96ffc06f 1861 struct ref_array_item *ref;
0ffaa00f 1862
96ffc06f 1863 FLEX_ALLOC_STR(ref, refname, refname);
53df97a2 1864 oidcpy(&ref->objectname, oid);
c95b7585
KN
1865
1866 return ref;
1867}
1868
427cbc9d
JK
1869struct ref_array_item *ref_array_push(struct ref_array *array,
1870 const char *refname,
1871 const struct object_id *oid)
1872{
1873 struct ref_array_item *ref = new_ref_array_item(refname, oid);
1874
1875 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
1876 array->items[array->nr++] = ref;
c95b7585
KN
1877
1878 return ref;
1879}
1880
2111aa79 1881static int ref_kind_from_refname(const char *refname)
5b4f2851
KN
1882{
1883 unsigned int i;
1884
1885 static struct {
1886 const char *prefix;
1887 unsigned int kind;
1888 } ref_kind[] = {
1889 { "refs/heads/" , FILTER_REFS_BRANCHES },
1890 { "refs/remotes/" , FILTER_REFS_REMOTES },
1891 { "refs/tags/", FILTER_REFS_TAGS}
1892 };
1893
2111aa79 1894 if (!strcmp(refname, "HEAD"))
5b4f2851
KN
1895 return FILTER_REFS_DETACHED_HEAD;
1896
1897 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
1898 if (starts_with(refname, ref_kind[i].prefix))
1899 return ref_kind[i].kind;
1900 }
1901
1902 return FILTER_REFS_OTHERS;
1903}
1904
2111aa79
LP
1905static int filter_ref_kind(struct ref_filter *filter, const char *refname)
1906{
1907 if (filter->kind == FILTER_REFS_BRANCHES ||
1908 filter->kind == FILTER_REFS_REMOTES ||
1909 filter->kind == FILTER_REFS_TAGS)
1910 return filter->kind;
1911 return ref_kind_from_refname(refname);
1912}
1913
920f93ca
DS
1914struct ref_filter_cbdata {
1915 struct ref_array *array;
1916 struct ref_filter *filter;
1917 struct contains_cache contains_cache;
1918 struct contains_cache no_contains_cache;
1919};
1920
c95b7585
KN
1921/*
1922 * A call-back given to for_each_ref(). Filter refs and keep them for
1923 * later object processing.
1924 */
14de7fba 1925static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
c95b7585
KN
1926{
1927 struct ref_filter_cbdata *ref_cbdata = cb_data;
14de7fba 1928 struct ref_filter *filter = ref_cbdata->filter;
c95b7585 1929 struct ref_array_item *ref;
35257aa0 1930 struct commit *commit = NULL;
5b4f2851 1931 unsigned int kind;
c95b7585
KN
1932
1933 if (flag & REF_BAD_NAME) {
1823c619 1934 warning(_("ignoring ref with broken name %s"), refname);
c95b7585
KN
1935 return 0;
1936 }
1937
7ebc8cbe 1938 if (flag & REF_ISBROKEN) {
1823c619 1939 warning(_("ignoring broken ref %s"), refname);
7ebc8cbe
JH
1940 return 0;
1941 }
1942
5b4f2851
KN
1943 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
1944 kind = filter_ref_kind(filter, refname);
1945 if (!(kind & filter->kind))
1946 return 0;
1947
bef0e12b 1948 if (!filter_pattern_match(filter, refname))
c95b7585
KN
1949 return 0;
1950
4ce3621a 1951 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
68411046
KN
1952 return 0;
1953
35257aa0
KN
1954 /*
1955 * A merge filter is applied on refs pointing to commits. Hence
1956 * obtain the commit using the 'oid' available and discard all
1957 * non-commits early. The actual filtering is done later.
1958 */
ac3f5a34 1959 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
21e1ee8f
SB
1960 commit = lookup_commit_reference_gently(the_repository, oid,
1961 1);
35257aa0
KN
1962 if (!commit)
1963 return 0;
ac3f5a34 1964 /* We perform the filtering for the '--contains' option... */
ee2bd06b 1965 if (filter->with_commit &&
ac3f5a34
ÆAB
1966 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
1967 return 0;
1968 /* ...or for the `--no-contains' option */
1969 if (filter->no_commit &&
1970 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
ee2bd06b 1971 return 0;
35257aa0
KN
1972 }
1973
c95b7585
KN
1974 /*
1975 * We do not open the object yet; sort may only need refname
1976 * to do its job and the resulting list may yet to be pruned
1977 * by maxcount logic.
1978 */
427cbc9d 1979 ref = ref_array_push(ref_cbdata->array, refname, oid);
35257aa0 1980 ref->commit = commit;
0ffaa00f 1981 ref->flag = flag;
5b4f2851 1982 ref->kind = kind;
c95b7585 1983
c95b7585
KN
1984 return 0;
1985}
1986
1987/* Free memory allocated for a ref_array_item */
1988static void free_array_item(struct ref_array_item *item)
1989{
1990 free((char *)item->symref);
c95b7585
KN
1991 free(item);
1992}
1993
1994/* Free all memory allocated for ref_array */
1995void ref_array_clear(struct ref_array *array)
1996{
1997 int i;
1998
23941dd7
OT
1999 for (i = 0; i < used_atom_cnt; i++)
2000 free((char *)used_atom[i].name);
2001 FREE_AND_NULL(used_atom);
2002 used_atom_cnt = 0;
c95b7585
KN
2003 for (i = 0; i < array->nr; i++)
2004 free_array_item(array->items[i]);
6a83d902 2005 FREE_AND_NULL(array->items);
c95b7585
KN
2006 array->nr = array->alloc = 0;
2007}
2008
35257aa0
KN
2009static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2010{
2011 struct rev_info revs;
2012 int i, old_nr;
2013 struct ref_filter *filter = ref_cbdata->filter;
2014 struct ref_array *array = ref_cbdata->array;
2015 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2016
2017 init_revisions(&revs, NULL);
2018
2019 for (i = 0; i < array->nr; i++) {
2020 struct ref_array_item *item = array->items[i];
2021 add_pending_object(&revs, &item->commit->object, item->refname);
2022 to_clear[i] = item->commit;
2023 }
2024
2025 filter->merge_commit->object.flags |= UNINTERESTING;
2026 add_pending_object(&revs, &filter->merge_commit->object, "");
2027
2028 revs.limited = 1;
2029 if (prepare_revision_walk(&revs))
2030 die(_("revision walk setup failed"));
2031
2032 old_nr = array->nr;
2033 array->nr = 0;
2034
2035 for (i = 0; i < old_nr; i++) {
2036 struct ref_array_item *item = array->items[i];
2037 struct commit *commit = item->commit;
2038
2039 int is_merged = !!(commit->object.flags & UNINTERESTING);
2040
2041 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2042 array->items[array->nr++] = array->items[i];
2043 else
2044 free_array_item(item);
2045 }
2046
5dee6d6f 2047 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
35257aa0
KN
2048 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2049 free(to_clear);
2050}
2051
14de7fba
KN
2052/*
2053 * API for filtering a set of refs. Based on the type of refs the user
2054 * has requested, we iterate through those refs and apply filters
2055 * as per the given ref_filter structure and finally store the
2056 * filtered refs in the ref_array structure.
2057 */
2058int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2059{
2060 struct ref_filter_cbdata ref_cbdata;
35257aa0 2061 int ret = 0;
5b4f2851 2062 unsigned int broken = 0;
14de7fba
KN
2063
2064 ref_cbdata.array = array;
2065 ref_cbdata.filter = filter;
2066
5b4f2851
KN
2067 if (type & FILTER_REFS_INCLUDE_BROKEN)
2068 broken = 1;
2069 filter->kind = type & FILTER_REFS_KIND_MASK;
2070
a91aca44 2071 init_contains_cache(&ref_cbdata.contains_cache);
ac3f5a34 2072 init_contains_cache(&ref_cbdata.no_contains_cache);
a91aca44 2073
35257aa0 2074 /* Simple per-ref filtering */
5b4f2851 2075 if (!filter->kind)
14de7fba 2076 die("filter_refs: invalid type");
5b4f2851
KN
2077 else {
2078 /*
2079 * For common cases where we need only branches or remotes or tags,
2080 * we only iterate through those refs. If a mix of refs is needed,
2081 * we iterate over all refs and filter out required refs with the help
2082 * of filter_ref_kind().
2083 */
2084 if (filter->kind == FILTER_REFS_BRANCHES)
2085 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2086 else if (filter->kind == FILTER_REFS_REMOTES)
2087 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2088 else if (filter->kind == FILTER_REFS_TAGS)
2089 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2090 else if (filter->kind & FILTER_REFS_ALL)
cfe004a5 2091 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
5b4f2851
KN
2092 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2093 head_ref(ref_filter_handler, &ref_cbdata);
2094 }
2095
a91aca44 2096 clear_contains_cache(&ref_cbdata.contains_cache);
ac3f5a34 2097 clear_contains_cache(&ref_cbdata.no_contains_cache);
35257aa0
KN
2098
2099 /* Filters that need revision walking */
2100 if (filter->merge_commit)
2101 do_merge_filter(&ref_cbdata);
2102
2103 return ret;
14de7fba
KN
2104}
2105
c95b7585
KN
2106static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2107{
2108 struct atom_value *va, *vb;
2109 int cmp;
b072add7 2110 cmp_type cmp_type = used_atom[s->atom].type;
3bb16a8b 2111 int (*cmp_fn)(const char *, const char *);
e339611b 2112 struct strbuf err = STRBUF_INIT;
c95b7585 2113
e339611b
OT
2114 if (get_ref_atom_value(a, s->atom, &va, &err))
2115 die("%s", err.buf);
2116 if (get_ref_atom_value(b, s->atom, &vb, &err))
2117 die("%s", err.buf);
2118 strbuf_release(&err);
3bb16a8b 2119 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
90c00408
KN
2120 if (s->version)
2121 cmp = versioncmp(va->s, vb->s);
2122 else if (cmp_type == FIELD_STR)
3bb16a8b 2123 cmp = cmp_fn(va->s, vb->s);
90c00408 2124 else {
e467dc14 2125 if (va->value < vb->value)
c95b7585 2126 cmp = -1;
e467dc14 2127 else if (va->value == vb->value)
3bb16a8b 2128 cmp = cmp_fn(a->refname, b->refname);
c95b7585
KN
2129 else
2130 cmp = 1;
c95b7585 2131 }
90c00408 2132
c95b7585
KN
2133 return (s->reverse) ? -cmp : cmp;
2134}
2135
83fc4d64 2136static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
c95b7585
KN
2137{
2138 struct ref_array_item *a = *((struct ref_array_item **)a_);
2139 struct ref_array_item *b = *((struct ref_array_item **)b_);
2140 struct ref_sorting *s;
2141
2142 for (s = ref_sorting; s; s = s->next) {
2143 int cmp = cmp_ref_sorting(s, a, b);
2144 if (cmp)
2145 return cmp;
2146 }
2147 return 0;
2148}
2149
2150void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2151{
83fc4d64 2152 QSORT_S(array->items, array->nr, compare_refs, sorting);
c95b7585
KN
2153}
2154
574e96a2 2155static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
c95b7585 2156{
574e96a2
KN
2157 struct strbuf *s = &state->stack->output;
2158
c95b7585
KN
2159 while (*cp && (!ep || cp < ep)) {
2160 if (*cp == '%') {
2161 if (cp[1] == '%')
2162 cp++;
2163 else {
d2330973 2164 int ch = hex2chr(cp + 1);
c95b7585 2165 if (0 <= ch) {
574e96a2 2166 strbuf_addch(s, ch);
c95b7585
KN
2167 cp += 3;
2168 continue;
2169 }
2170 }
2171 }
574e96a2 2172 strbuf_addch(s, *cp);
c95b7585
KN
2173 cp++;
2174 }
2175}
2176
3019eca9 2177int format_ref_array_item(struct ref_array_item *info,
4a68e36d 2178 const struct ref_format *format,
3019eca9
OT
2179 struct strbuf *final_buf,
2180 struct strbuf *error_buf)
c95b7585
KN
2181{
2182 const char *cp, *sp, *ep;
574e96a2
KN
2183 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2184
4a68e36d 2185 state.quote_style = format->quote_style;
574e96a2 2186 push_stack_element(&state.stack);
c95b7585 2187
4a68e36d 2188 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
c95b7585 2189 struct atom_value *atomv;
e6ff7b3b 2190 int pos;
c95b7585
KN
2191
2192 ep = strchr(sp, ')');
2193 if (cp < sp)
574e96a2 2194 append_literal(cp, sp, &state);
e6ff7b3b 2195 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
e339611b
OT
2196 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2197 atomv->handler(atomv, &state, error_buf)) {
3fc8439c
OT
2198 pop_stack_element(&state.stack);
2199 return -1;
2200 }
c95b7585
KN
2201 }
2202 if (*cp) {
2203 sp = cp + strlen(cp);
574e96a2 2204 append_literal(cp, sp, &state);
c95b7585 2205 }
bf285ae6 2206 if (format->need_color_reset_at_eol) {
c95b7585 2207 struct atom_value resetv;
51331aad 2208 resetv.s = GIT_COLOR_RESET;
3fc8439c
OT
2209 if (append_atom(&resetv, &state, error_buf)) {
2210 pop_stack_element(&state.stack);
2211 return -1;
2212 }
c95b7585 2213 }
3019eca9
OT
2214 if (state.stack->prev) {
2215 pop_stack_element(&state.stack);
2216 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
c95b7585 2217 }
99c6a71d 2218 strbuf_addbuf(final_buf, &state.stack->output);
574e96a2 2219 pop_stack_element(&state.stack);
3019eca9 2220 return 0;
99c6a71d
KN
2221}
2222
4a68e36d
JK
2223void show_ref_array_item(struct ref_array_item *info,
2224 const struct ref_format *format)
99c6a71d
KN
2225{
2226 struct strbuf final_buf = STRBUF_INIT;
3019eca9 2227 struct strbuf error_buf = STRBUF_INIT;
99c6a71d 2228
3019eca9
OT
2229 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2230 die("%s", error_buf.buf);
99c6a71d 2231 fwrite(final_buf.buf, 1, final_buf.len, stdout);
3019eca9 2232 strbuf_release(&error_buf);
99c6a71d 2233 strbuf_release(&final_buf);
c95b7585
KN
2234 putchar('\n');
2235}
2236
53df97a2 2237void pretty_print_ref(const char *name, const struct object_id *oid,
4a68e36d 2238 const struct ref_format *format)
2111aa79
LP
2239{
2240 struct ref_array_item *ref_item;
0ffaa00f 2241 ref_item = new_ref_array_item(name, oid);
2111aa79 2242 ref_item->kind = ref_kind_from_refname(name);
4a68e36d 2243 show_ref_array_item(ref_item, format);
2111aa79
LP
2244 free_array_item(ref_item);
2245}
2246
29ef53cd
JK
2247static int parse_sorting_atom(const char *atom)
2248{
ab7ded34
JK
2249 /*
2250 * This parses an atom using a dummy ref_format, since we don't
2251 * actually care about the formatting details.
2252 */
2253 struct ref_format dummy = REF_FORMAT_INIT;
29ef53cd 2254 const char *end = atom + strlen(atom);
e6ff7b3b
OT
2255 struct strbuf err = STRBUF_INIT;
2256 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2257 if (res < 0)
2258 die("%s", err.buf);
2259 strbuf_release(&err);
2260 return res;
29ef53cd
JK
2261}
2262
c95b7585
KN
2263/* If no sorting option is given, use refname to sort as default */
2264struct ref_sorting *ref_default_sorting(void)
2265{
2266 static const char cstr_name[] = "refname";
2267
2268 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2269
2270 sorting->next = NULL;
29ef53cd 2271 sorting->atom = parse_sorting_atom(cstr_name);
c95b7585
KN
2272 return sorting;
2273}
2274
18a25650 2275void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
c95b7585 2276{
c95b7585 2277 struct ref_sorting *s;
c95b7585 2278
c95b7585
KN
2279 s = xcalloc(1, sizeof(*s));
2280 s->next = *sorting_tail;
2281 *sorting_tail = s;
2282
2283 if (*arg == '-') {
2284 s->reverse = 1;
2285 arg++;
2286 }
90c00408
KN
2287 if (skip_prefix(arg, "version:", &arg) ||
2288 skip_prefix(arg, "v:", &arg))
2289 s->version = 1;
29ef53cd 2290 s->atom = parse_sorting_atom(arg);
18a25650
JK
2291}
2292
2293int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2294{
2295 if (!arg) /* should --no-sort void the list ? */
2296 return -1;
2297 parse_ref_sorting(opt->value, arg);
c95b7585
KN
2298 return 0;
2299}
5afcb905
KN
2300
2301int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2302{
2303 struct ref_filter *rf = opt->value;
1e43ed98 2304 struct object_id oid;
17d6c744 2305 int no_merged = starts_with(opt->long_name, "no");
5afcb905 2306
17d6c744
ÆAB
2307 if (rf->merge) {
2308 if (no_merged) {
2309 return opterror(opt, "is incompatible with --merged", 0);
2310 } else {
2311 return opterror(opt, "is incompatible with --no-merged", 0);
2312 }
2313 }
5afcb905 2314
17d6c744 2315 rf->merge = no_merged
5afcb905
KN
2316 ? REF_FILTER_MERGED_OMIT
2317 : REF_FILTER_MERGED_INCLUDE;
2318
1e43ed98 2319 if (get_oid(arg, &oid))
5afcb905
KN
2320 die(_("malformed object name %s"), arg);
2321
21e1ee8f
SB
2322 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2323 &oid, 0);
5afcb905
KN
2324 if (!rf->merge_commit)
2325 return opterror(opt, "must point to a commit", 0);
2326
2327 return 0;
2328}