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