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