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