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