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