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