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