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