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