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