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