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