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