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