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