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