]> git.ipfire.org Git - thirdparty/git.git/blame - ref-filter.c
hashmap: use *_entry APIs to wrap container_of
[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"
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 }
1031 return "";
1032}
1033
1034static const char *copy_email(const char *buf)
1035{
1036 const char *email = strchr(buf, '<');
1037 const char *eoemail;
1038 if (!email)
1039 return "";
1040 eoemail = strchr(email, '>');
1041 if (!eoemail)
1042 return "";
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];
d22245a2
EW
1568 hashmap_entry_init(&entry->ent,
1569 strhash(worktrees[i]->head_ref));
2582083f 1570
b94e5c1d 1571 hashmap_add(map, &entry->ent);
2582083f
NB
1572 }
1573 }
1574}
1575
1576static void lazy_init_worktree_map(void)
1577{
1578 if (ref_to_worktree_map.worktrees)
1579 return;
1580
1581 ref_to_worktree_map.worktrees = get_worktrees(0);
1582 hashmap_init(&(ref_to_worktree_map.map), ref_to_worktree_map_cmpfnc, NULL, 0);
1583 populate_worktree_map(&(ref_to_worktree_map.map), ref_to_worktree_map.worktrees);
1584}
1585
1586static char *get_worktree_path(const struct used_atom *atom, const struct ref_array_item *ref)
1587{
1588 struct hashmap_entry entry;
1589 struct ref_to_worktree_entry *lookup_result;
1590
1591 lazy_init_worktree_map();
1592
1593 hashmap_entry_init(&entry, strhash(ref->refname));
1594 lookup_result = hashmap_get(&(ref_to_worktree_map.map), &entry, ref->refname);
1595
1596 if (lookup_result)
1597 return xstrdup(lookup_result->wt->path);
1598 else
1599 return xstrdup("");
1600}
1601
c95b7585
KN
1602/*
1603 * Parse the object referred by ref, and grab needed value.
1604 */
e339611b 1605static int populate_value(struct ref_array_item *ref, struct strbuf *err)
c95b7585 1606{
c95b7585 1607 struct object *obj;
2bbc6e8a 1608 int i;
aa46a0da 1609 struct object_info empty = OBJECT_INFO_INIT;
c95b7585
KN
1610
1611 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
1612
1613 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
c95b7585 1614 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
efbd4fdf 1615 NULL, NULL);
c95b7585 1616 if (!ref->symref)
f0062d3b 1617 ref->symref = xstrdup("");
c95b7585
KN
1618 }
1619
1620 /* Fill in specials first */
1621 for (i = 0; i < used_atom_cnt; i++) {
fd935cc7 1622 struct used_atom *atom = &used_atom[i];
b072add7 1623 const char *name = used_atom[i].name;
c95b7585
KN
1624 struct atom_value *v = &ref->value[i];
1625 int deref = 0;
1626 const char *refname;
c95b7585
KN
1627 struct branch *branch = NULL;
1628
63d89fbc 1629 v->handler = append_atom;
c58fc856 1630 v->atom = atom;
63d89fbc 1631
c95b7585
KN
1632 if (*name == '*') {
1633 deref = 1;
1634 name++;
1635 }
1636
1637 if (starts_with(name, "refname"))
a7984101 1638 refname = get_refname(atom, ref);
2582083f
NB
1639 else if (!strcmp(name, "worktreepath")) {
1640 if (ref->kind == FILTER_REFS_BRANCHES)
1641 v->s = get_worktree_path(atom, ref);
1642 else
1643 v->s = xstrdup("");
1644 continue;
1645 }
c95b7585 1646 else if (starts_with(name, "symref"))
a7984101 1647 refname = get_symref(atom, ref);
c95b7585
KN
1648 else if (starts_with(name, "upstream")) {
1649 const char *branch_name;
1650 /* only local branches may have an upstream */
1651 if (!skip_prefix(ref->refname, "refs/heads/",
f0062d3b
OT
1652 &branch_name)) {
1653 v->s = xstrdup("");
c95b7585 1654 continue;
f0062d3b 1655 }
c95b7585
KN
1656 branch = branch_get(branch_name);
1657
1658 refname = branch_get_upstream(branch, NULL);
5339bdad
KN
1659 if (refname)
1660 fill_remote_ref_details(atom, refname, branch, &v->s);
f0062d3b
OT
1661 else
1662 v->s = xstrdup("");
5339bdad 1663 continue;
cc72385f 1664 } else if (atom->u.remote_ref.push) {
c95b7585 1665 const char *branch_name;
f0062d3b 1666 v->s = xstrdup("");
c95b7585
KN
1667 if (!skip_prefix(ref->refname, "refs/heads/",
1668 &branch_name))
1669 continue;
1670 branch = branch_get(branch_name);
1671
cc72385f
JS
1672 if (atom->u.remote_ref.push_remote)
1673 refname = NULL;
1674 else {
1675 refname = branch_get_push(branch, NULL);
1676 if (!refname)
1677 continue;
1678 }
f0062d3b
OT
1679 /* We will definitely re-init v->s on the next line. */
1680 free((char *)v->s);
5339bdad
KN
1681 fill_remote_ref_details(atom, refname, branch, &v->s);
1682 continue;
fd935cc7 1683 } else if (starts_with(name, "color:")) {
f0062d3b 1684 v->s = xstrdup(atom->u.color);
c95b7585
KN
1685 continue;
1686 } else if (!strcmp(name, "flag")) {
1687 char buf[256], *cp = buf;
1688 if (ref->flag & REF_ISSYMREF)
1689 cp = copy_advance(cp, ",symref");
1690 if (ref->flag & REF_ISPACKED)
1691 cp = copy_advance(cp, ",packed");
1692 if (cp == buf)
f0062d3b 1693 v->s = xstrdup("");
c95b7585
KN
1694 else {
1695 *cp = '\0';
1696 v->s = xstrdup(buf + 1);
1697 }
1698 continue;
17769795 1699 } else if (!deref && grab_objectname(name, &ref->objectname, v, atom)) {
c95b7585
KN
1700 continue;
1701 } else if (!strcmp(name, "HEAD")) {
613a0e52 1702 if (atom->u.head && !strcmp(ref->refname, atom->u.head))
f0062d3b 1703 v->s = xstrdup("*");
c95b7585 1704 else
f0062d3b 1705 v->s = xstrdup(" ");
c95b7585 1706 continue;
5bd881d9 1707 } else if (starts_with(name, "align")) {
ce592082 1708 v->handler = align_atom_handler;
f0062d3b 1709 v->s = xstrdup("");
ce592082
KN
1710 continue;
1711 } else if (!strcmp(name, "end")) {
1712 v->handler = end_atom_handler;
f0062d3b 1713 v->s = xstrdup("");
ce592082 1714 continue;
4f3e3b37
KN
1715 } else if (starts_with(name, "if")) {
1716 const char *s;
4f3e3b37
KN
1717 if (skip_prefix(name, "if:", &s))
1718 v->s = xstrdup(s);
f0062d3b
OT
1719 else
1720 v->s = xstrdup("");
c58492d4
KN
1721 v->handler = if_atom_handler;
1722 continue;
1723 } else if (!strcmp(name, "then")) {
1724 v->handler = then_atom_handler;
f0062d3b 1725 v->s = xstrdup("");
c58492d4
KN
1726 continue;
1727 } else if (!strcmp(name, "else")) {
1728 v->handler = else_atom_handler;
f0062d3b 1729 v->s = xstrdup("");
c58492d4 1730 continue;
c95b7585
KN
1731 } else
1732 continue;
1733
c95b7585 1734 if (!deref)
f0062d3b 1735 v->s = xstrdup(refname);
a5e03bf5
JK
1736 else
1737 v->s = xstrfmt("%s^{}", refname);
f0062d3b 1738 free((char *)refname);
c95b7585
KN
1739 }
1740
1741 for (i = 0; i < used_atom_cnt; i++) {
1742 struct atom_value *v = &ref->value[i];
aa46a0da
OT
1743 if (v->s == NULL && used_atom[i].source == SOURCE_NONE)
1744 return strbuf_addf_ret(err, -1, _("missing object %s for %s"),
1745 oid_to_hex(&ref->objectname), ref->refname);
c95b7585 1746 }
aa46a0da
OT
1747
1748 if (need_tagged)
1749 oi.info.contentp = &oi.content;
1750 if (!memcmp(&oi.info, &empty, sizeof(empty)) &&
1751 !memcmp(&oi_deref.info, &empty, sizeof(empty)))
e339611b 1752 return 0;
c95b7585 1753
aa46a0da
OT
1754
1755 oi.oid = ref->objectname;
1756 if (get_object(ref, 0, &obj, &oi, err))
e339611b 1757 return -1;
c95b7585
KN
1758
1759 /*
1760 * If there is no atom that wants to know about tagged
1761 * object, we are done.
1762 */
1763 if (!need_tagged || (obj->type != OBJ_TAG))
e339611b 1764 return 0;
c95b7585
KN
1765
1766 /*
1767 * If it is a tag object, see if we use a value that derefs
1768 * the object, and if we do grab the object it refers to.
1769 */
aa46a0da 1770 oi_deref.oid = ((struct tag *)obj)->tagged->oid;
c95b7585
KN
1771
1772 /*
1773 * NEEDSWORK: This derefs tag only once, which
1774 * is good to deal with chains of trust, but
1775 * is not consistent with what deref_tag() does
1776 * which peels the onion to the core.
1777 */
aa46a0da 1778 return get_object(ref, 1, &obj, &oi_deref, err);
c95b7585
KN
1779}
1780
1781/*
1782 * Given a ref, return the value for the atom. This lazily gets value
1783 * out of the object by calling populate value.
1784 */
e339611b
OT
1785static int get_ref_atom_value(struct ref_array_item *ref, int atom,
1786 struct atom_value **v, struct strbuf *err)
c95b7585
KN
1787{
1788 if (!ref->value) {
e339611b
OT
1789 if (populate_value(ref, err))
1790 return -1;
c95b7585
KN
1791 fill_missing_values(ref->value);
1792 }
1793 *v = &ref->value[atom];
e339611b 1794 return 0;
c95b7585
KN
1795}
1796
bef0e12b
KN
1797/*
1798 * Return 1 if the refname matches one of the patterns, otherwise 0.
1799 * A pattern can be a literal prefix (e.g. a refname "refs/heads/master"
1800 * matches a pattern "refs/heads/mas") or a wildcard (e.g. the same ref
1801 * matches "refs/heads/mas*", too).
1802 */
3bb16a8b 1803static int match_pattern(const struct ref_filter *filter, const char *refname)
bef0e12b 1804{
3bb16a8b
NTND
1805 const char **patterns = filter->name_patterns;
1806 unsigned flags = 0;
1807
1808 if (filter->ignore_case)
1809 flags |= WM_CASEFOLD;
1810
bef0e12b
KN
1811 /*
1812 * When no '--format' option is given we need to skip the prefix
1813 * for matching refs of tags and branches.
1814 */
1815 (void)(skip_prefix(refname, "refs/tags/", &refname) ||
1816 skip_prefix(refname, "refs/heads/", &refname) ||
1817 skip_prefix(refname, "refs/remotes/", &refname) ||
1818 skip_prefix(refname, "refs/", &refname));
1819
1820 for (; *patterns; patterns++) {
55d34269 1821 if (!wildmatch(*patterns, refname, flags))
bef0e12b
KN
1822 return 1;
1823 }
1824 return 0;
1825}
1826
c95b7585
KN
1827/*
1828 * Return 1 if the refname matches one of the patterns, otherwise 0.
1829 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
bef0e12b
KN
1830 * matches a pattern "refs/heads/" but not "refs/heads/m") or a
1831 * wildcard (e.g. the same ref matches "refs/heads/m*", too).
c95b7585 1832 */
3bb16a8b 1833static int match_name_as_path(const struct ref_filter *filter, const char *refname)
c95b7585 1834{
3bb16a8b 1835 const char **pattern = filter->name_patterns;
c95b7585 1836 int namelen = strlen(refname);
3bb16a8b
NTND
1837 unsigned flags = WM_PATHNAME;
1838
1839 if (filter->ignore_case)
1840 flags |= WM_CASEFOLD;
1841
c95b7585
KN
1842 for (; *pattern; pattern++) {
1843 const char *p = *pattern;
1844 int plen = strlen(p);
1845
1846 if ((plen <= namelen) &&
1847 !strncmp(refname, p, plen) &&
1848 (refname[plen] == '\0' ||
1849 refname[plen] == '/' ||
1850 p[plen-1] == '/'))
1851 return 1;
639ab5ef 1852 if (!wildmatch(p, refname, flags))
c95b7585
KN
1853 return 1;
1854 }
1855 return 0;
1856}
1857
bef0e12b
KN
1858/* Return 1 if the refname matches one of the patterns, otherwise 0. */
1859static int filter_pattern_match(struct ref_filter *filter, const char *refname)
1860{
1861 if (!*filter->name_patterns)
1862 return 1; /* No pattern always matches */
1863 if (filter->match_as_path)
3bb16a8b
NTND
1864 return match_name_as_path(filter, refname);
1865 return match_pattern(filter, refname);
bef0e12b
KN
1866}
1867
b31e2680
TB
1868static int qsort_strcmp(const void *va, const void *vb)
1869{
1870 const char *a = *(const char **)va;
1871 const char *b = *(const char **)vb;
1872
1873 return strcmp(a, b);
1874}
1875
1876static void find_longest_prefixes_1(struct string_list *out,
1877 struct strbuf *prefix,
1878 const char **patterns, size_t nr)
cfe004a5 1879{
b31e2680
TB
1880 size_t i;
1881
1882 for (i = 0; i < nr; i++) {
1883 char c = patterns[i][prefix->len];
1884 if (!c || is_glob_special(c)) {
1885 string_list_append(out, prefix->buf);
1886 return;
1887 }
1888 }
1889
1890 i = 0;
1891 while (i < nr) {
1892 size_t end;
1893
1894 /*
1895 * Set "end" to the index of the element _after_ the last one
1896 * in our group.
1897 */
1898 for (end = i + 1; end < nr; end++) {
1899 if (patterns[i][prefix->len] != patterns[end][prefix->len])
1900 break;
1901 }
cfe004a5 1902
b31e2680
TB
1903 strbuf_addch(prefix, patterns[i][prefix->len]);
1904 find_longest_prefixes_1(out, prefix, patterns + i, end - i);
1905 strbuf_setlen(prefix, prefix->len - 1);
cfe004a5 1906
b31e2680
TB
1907 i = end;
1908 }
1909}
1910
1911static void find_longest_prefixes(struct string_list *out,
1912 const char **patterns)
1913{
1914 struct argv_array sorted = ARGV_ARRAY_INIT;
1915 struct strbuf prefix = STRBUF_INIT;
1916
1917 argv_array_pushv(&sorted, patterns);
1918 QSORT(sorted.argv, sorted.argc, qsort_strcmp);
1919
1920 find_longest_prefixes_1(out, &prefix, sorted.argv, sorted.argc);
1921
1922 argv_array_clear(&sorted);
1923 strbuf_release(&prefix);
cfe004a5
JK
1924}
1925
1926/*
1927 * This is the same as for_each_fullref_in(), but it tries to iterate
1928 * only over the patterns we'll care about. Note that it _doesn't_ do a full
1929 * pattern match, so the callback still has to match each ref individually.
1930 */
1931static int for_each_fullref_in_pattern(struct ref_filter *filter,
1932 each_ref_fn cb,
1933 void *cb_data,
1934 int broken)
1935{
b31e2680
TB
1936 struct string_list prefixes = STRING_LIST_INIT_DUP;
1937 struct string_list_item *prefix;
cfe004a5
JK
1938 int ret;
1939
1940 if (!filter->match_as_path) {
1941 /*
1942 * in this case, the patterns are applied after
1943 * prefixes like "refs/heads/" etc. are stripped off,
1944 * so we have to look at everything:
1945 */
1946 return for_each_fullref_in("", cb, cb_data, broken);
1947 }
1948
e674eb25
JK
1949 if (filter->ignore_case) {
1950 /*
1951 * we can't handle case-insensitive comparisons,
1952 * so just return everything and let the caller
1953 * sort it out.
1954 */
1955 return for_each_fullref_in("", cb, cb_data, broken);
1956 }
1957
cfe004a5
JK
1958 if (!filter->name_patterns[0]) {
1959 /* no patterns; we have to look at everything */
1960 return for_each_fullref_in("", cb, cb_data, broken);
1961 }
1962
b31e2680 1963 find_longest_prefixes(&prefixes, filter->name_patterns);
cfe004a5 1964
b31e2680
TB
1965 for_each_string_list_item(prefix, &prefixes) {
1966 ret = for_each_fullref_in(prefix->string, cb, cb_data, broken);
1967 if (ret)
1968 break;
1969 }
cfe004a5 1970
b31e2680 1971 string_list_clear(&prefixes, 0);
cfe004a5
JK
1972 return ret;
1973}
1974
68411046
KN
1975/*
1976 * Given a ref (sha1, refname), check if the ref belongs to the array
1977 * of sha1s. If the given ref is a tag, check if the given tag points
1978 * at one of the sha1s in the given sha1 array.
1979 * the given sha1_array.
1980 * NEEDSWORK:
1981 * 1. Only a single level of inderection is obtained, we might want to
1982 * change this to account for multiple levels (e.g. annotated tags
1983 * pointing to annotated tags pointing to a commit.)
1984 * 2. As the refs are cached we might know what refname peels to without
1985 * the need to parse the object via parse_object(). peel_ref() might be a
1986 * more efficient alternative to obtain the pointee.
1987 */
910650d2 1988static const struct object_id *match_points_at(struct oid_array *points_at,
4ce3621a 1989 const struct object_id *oid,
1990 const char *refname)
68411046 1991{
4ce3621a 1992 const struct object_id *tagged_oid = NULL;
68411046
KN
1993 struct object *obj;
1994
910650d2 1995 if (oid_array_lookup(points_at, oid) >= 0)
4ce3621a 1996 return oid;
109cd76d 1997 obj = parse_object(the_repository, oid);
68411046
KN
1998 if (!obj)
1999 die(_("malformed object at '%s'"), refname);
2000 if (obj->type == OBJ_TAG)
4ce3621a 2001 tagged_oid = &((struct tag *)obj)->tagged->oid;
910650d2 2002 if (tagged_oid && oid_array_lookup(points_at, tagged_oid) >= 0)
4ce3621a 2003 return tagged_oid;
68411046
KN
2004 return NULL;
2005}
2006
0ffaa00f
JK
2007/*
2008 * Allocate space for a new ref_array_item and copy the name and oid to it.
2009 *
2010 * Callers can then fill in other struct members at their leisure.
2011 */
c95b7585 2012static struct ref_array_item *new_ref_array_item(const char *refname,
0ffaa00f 2013 const struct object_id *oid)
c95b7585 2014{
96ffc06f 2015 struct ref_array_item *ref;
0ffaa00f 2016
96ffc06f 2017 FLEX_ALLOC_STR(ref, refname, refname);
53df97a2 2018 oidcpy(&ref->objectname, oid);
c95b7585
KN
2019
2020 return ref;
2021}
2022
427cbc9d
JK
2023struct ref_array_item *ref_array_push(struct ref_array *array,
2024 const char *refname,
2025 const struct object_id *oid)
2026{
2027 struct ref_array_item *ref = new_ref_array_item(refname, oid);
2028
2029 ALLOC_GROW(array->items, array->nr + 1, array->alloc);
2030 array->items[array->nr++] = ref;
c95b7585
KN
2031
2032 return ref;
2033}
2034
2111aa79 2035static int ref_kind_from_refname(const char *refname)
5b4f2851
KN
2036{
2037 unsigned int i;
2038
2039 static struct {
2040 const char *prefix;
2041 unsigned int kind;
2042 } ref_kind[] = {
2043 { "refs/heads/" , FILTER_REFS_BRANCHES },
2044 { "refs/remotes/" , FILTER_REFS_REMOTES },
2045 { "refs/tags/", FILTER_REFS_TAGS}
2046 };
2047
2111aa79 2048 if (!strcmp(refname, "HEAD"))
5b4f2851
KN
2049 return FILTER_REFS_DETACHED_HEAD;
2050
2051 for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
2052 if (starts_with(refname, ref_kind[i].prefix))
2053 return ref_kind[i].kind;
2054 }
2055
2056 return FILTER_REFS_OTHERS;
2057}
2058
2111aa79
LP
2059static int filter_ref_kind(struct ref_filter *filter, const char *refname)
2060{
2061 if (filter->kind == FILTER_REFS_BRANCHES ||
2062 filter->kind == FILTER_REFS_REMOTES ||
2063 filter->kind == FILTER_REFS_TAGS)
2064 return filter->kind;
2065 return ref_kind_from_refname(refname);
2066}
2067
920f93ca
DS
2068struct ref_filter_cbdata {
2069 struct ref_array *array;
2070 struct ref_filter *filter;
2071 struct contains_cache contains_cache;
2072 struct contains_cache no_contains_cache;
2073};
2074
c95b7585
KN
2075/*
2076 * A call-back given to for_each_ref(). Filter refs and keep them for
2077 * later object processing.
2078 */
14de7fba 2079static int ref_filter_handler(const char *refname, const struct object_id *oid, int flag, void *cb_data)
c95b7585
KN
2080{
2081 struct ref_filter_cbdata *ref_cbdata = cb_data;
14de7fba 2082 struct ref_filter *filter = ref_cbdata->filter;
c95b7585 2083 struct ref_array_item *ref;
35257aa0 2084 struct commit *commit = NULL;
5b4f2851 2085 unsigned int kind;
c95b7585
KN
2086
2087 if (flag & REF_BAD_NAME) {
1823c619 2088 warning(_("ignoring ref with broken name %s"), refname);
c95b7585
KN
2089 return 0;
2090 }
2091
7ebc8cbe 2092 if (flag & REF_ISBROKEN) {
1823c619 2093 warning(_("ignoring broken ref %s"), refname);
7ebc8cbe
JH
2094 return 0;
2095 }
2096
5b4f2851
KN
2097 /* Obtain the current ref kind from filter_ref_kind() and ignore unwanted refs. */
2098 kind = filter_ref_kind(filter, refname);
2099 if (!(kind & filter->kind))
2100 return 0;
2101
bef0e12b 2102 if (!filter_pattern_match(filter, refname))
c95b7585
KN
2103 return 0;
2104
4ce3621a 2105 if (filter->points_at.nr && !match_points_at(&filter->points_at, oid, refname))
68411046
KN
2106 return 0;
2107
35257aa0
KN
2108 /*
2109 * A merge filter is applied on refs pointing to commits. Hence
2110 * obtain the commit using the 'oid' available and discard all
2111 * non-commits early. The actual filtering is done later.
2112 */
ac3f5a34 2113 if (filter->merge_commit || filter->with_commit || filter->no_commit || filter->verbose) {
21e1ee8f
SB
2114 commit = lookup_commit_reference_gently(the_repository, oid,
2115 1);
35257aa0
KN
2116 if (!commit)
2117 return 0;
ac3f5a34 2118 /* We perform the filtering for the '--contains' option... */
ee2bd06b 2119 if (filter->with_commit &&
ac3f5a34
ÆAB
2120 !commit_contains(filter, commit, filter->with_commit, &ref_cbdata->contains_cache))
2121 return 0;
2122 /* ...or for the `--no-contains' option */
2123 if (filter->no_commit &&
2124 commit_contains(filter, commit, filter->no_commit, &ref_cbdata->no_contains_cache))
ee2bd06b 2125 return 0;
35257aa0
KN
2126 }
2127
c95b7585
KN
2128 /*
2129 * We do not open the object yet; sort may only need refname
2130 * to do its job and the resulting list may yet to be pruned
2131 * by maxcount logic.
2132 */
427cbc9d 2133 ref = ref_array_push(ref_cbdata->array, refname, oid);
35257aa0 2134 ref->commit = commit;
0ffaa00f 2135 ref->flag = flag;
5b4f2851 2136 ref->kind = kind;
c95b7585 2137
c95b7585
KN
2138 return 0;
2139}
2140
2141/* Free memory allocated for a ref_array_item */
2142static void free_array_item(struct ref_array_item *item)
2143{
2144 free((char *)item->symref);
f0062d3b 2145 if (item->value) {
14d30cdf
2146 int i;
2147 for (i = 0; i < used_atom_cnt; i++)
2148 free((char *)item->value[i].s);
f0062d3b
OT
2149 free(item->value);
2150 }
c95b7585
KN
2151 free(item);
2152}
2153
2154/* Free all memory allocated for ref_array */
2155void ref_array_clear(struct ref_array *array)
2156{
2157 int i;
2158
2159 for (i = 0; i < array->nr; i++)
2160 free_array_item(array->items[i]);
6a83d902 2161 FREE_AND_NULL(array->items);
c95b7585 2162 array->nr = array->alloc = 0;
14d30cdf
2163
2164 for (i = 0; i < used_atom_cnt; i++)
2165 free((char *)used_atom[i].name);
2166 FREE_AND_NULL(used_atom);
2167 used_atom_cnt = 0;
2168
2582083f
NB
2169 if (ref_to_worktree_map.worktrees) {
2170 hashmap_free(&(ref_to_worktree_map.map), 1);
2171 free_worktrees(ref_to_worktree_map.worktrees);
2172 ref_to_worktree_map.worktrees = NULL;
2173 }
c95b7585
KN
2174}
2175
35257aa0
KN
2176static void do_merge_filter(struct ref_filter_cbdata *ref_cbdata)
2177{
2178 struct rev_info revs;
2179 int i, old_nr;
2180 struct ref_filter *filter = ref_cbdata->filter;
2181 struct ref_array *array = ref_cbdata->array;
2182 struct commit **to_clear = xcalloc(sizeof(struct commit *), array->nr);
2183
2abf3503 2184 repo_init_revisions(the_repository, &revs, NULL);
35257aa0
KN
2185
2186 for (i = 0; i < array->nr; i++) {
2187 struct ref_array_item *item = array->items[i];
2188 add_pending_object(&revs, &item->commit->object, item->refname);
2189 to_clear[i] = item->commit;
2190 }
2191
2192 filter->merge_commit->object.flags |= UNINTERESTING;
2193 add_pending_object(&revs, &filter->merge_commit->object, "");
2194
2195 revs.limited = 1;
2196 if (prepare_revision_walk(&revs))
2197 die(_("revision walk setup failed"));
2198
2199 old_nr = array->nr;
2200 array->nr = 0;
2201
2202 for (i = 0; i < old_nr; i++) {
2203 struct ref_array_item *item = array->items[i];
2204 struct commit *commit = item->commit;
2205
2206 int is_merged = !!(commit->object.flags & UNINTERESTING);
2207
2208 if (is_merged == (filter->merge == REF_FILTER_MERGED_INCLUDE))
2209 array->items[array->nr++] = array->items[i];
2210 else
2211 free_array_item(item);
2212 }
2213
5dee6d6f 2214 clear_commit_marks_many(old_nr, to_clear, ALL_REV_FLAGS);
35257aa0
KN
2215 clear_commit_marks(filter->merge_commit, ALL_REV_FLAGS);
2216 free(to_clear);
2217}
2218
14de7fba
KN
2219/*
2220 * API for filtering a set of refs. Based on the type of refs the user
2221 * has requested, we iterate through those refs and apply filters
2222 * as per the given ref_filter structure and finally store the
2223 * filtered refs in the ref_array structure.
2224 */
2225int filter_refs(struct ref_array *array, struct ref_filter *filter, unsigned int type)
2226{
2227 struct ref_filter_cbdata ref_cbdata;
35257aa0 2228 int ret = 0;
5b4f2851 2229 unsigned int broken = 0;
14de7fba
KN
2230
2231 ref_cbdata.array = array;
2232 ref_cbdata.filter = filter;
2233
5b4f2851
KN
2234 if (type & FILTER_REFS_INCLUDE_BROKEN)
2235 broken = 1;
2236 filter->kind = type & FILTER_REFS_KIND_MASK;
2237
a91aca44 2238 init_contains_cache(&ref_cbdata.contains_cache);
ac3f5a34 2239 init_contains_cache(&ref_cbdata.no_contains_cache);
a91aca44 2240
35257aa0 2241 /* Simple per-ref filtering */
5b4f2851 2242 if (!filter->kind)
14de7fba 2243 die("filter_refs: invalid type");
5b4f2851
KN
2244 else {
2245 /*
2246 * For common cases where we need only branches or remotes or tags,
2247 * we only iterate through those refs. If a mix of refs is needed,
2248 * we iterate over all refs and filter out required refs with the help
2249 * of filter_ref_kind().
2250 */
2251 if (filter->kind == FILTER_REFS_BRANCHES)
2252 ret = for_each_fullref_in("refs/heads/", ref_filter_handler, &ref_cbdata, broken);
2253 else if (filter->kind == FILTER_REFS_REMOTES)
2254 ret = for_each_fullref_in("refs/remotes/", ref_filter_handler, &ref_cbdata, broken);
2255 else if (filter->kind == FILTER_REFS_TAGS)
2256 ret = for_each_fullref_in("refs/tags/", ref_filter_handler, &ref_cbdata, broken);
2257 else if (filter->kind & FILTER_REFS_ALL)
cfe004a5 2258 ret = for_each_fullref_in_pattern(filter, ref_filter_handler, &ref_cbdata, broken);
5b4f2851
KN
2259 if (!ret && (filter->kind & FILTER_REFS_DETACHED_HEAD))
2260 head_ref(ref_filter_handler, &ref_cbdata);
2261 }
2262
a91aca44 2263 clear_contains_cache(&ref_cbdata.contains_cache);
ac3f5a34 2264 clear_contains_cache(&ref_cbdata.no_contains_cache);
35257aa0
KN
2265
2266 /* Filters that need revision walking */
2267 if (filter->merge_commit)
2268 do_merge_filter(&ref_cbdata);
2269
2270 return ret;
14de7fba
KN
2271}
2272
c95b7585
KN
2273static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, struct ref_array_item *b)
2274{
2275 struct atom_value *va, *vb;
2276 int cmp;
b072add7 2277 cmp_type cmp_type = used_atom[s->atom].type;
3bb16a8b 2278 int (*cmp_fn)(const char *, const char *);
e339611b 2279 struct strbuf err = STRBUF_INIT;
c95b7585 2280
e339611b
OT
2281 if (get_ref_atom_value(a, s->atom, &va, &err))
2282 die("%s", err.buf);
2283 if (get_ref_atom_value(b, s->atom, &vb, &err))
2284 die("%s", err.buf);
2285 strbuf_release(&err);
3bb16a8b 2286 cmp_fn = s->ignore_case ? strcasecmp : strcmp;
90c00408
KN
2287 if (s->version)
2288 cmp = versioncmp(va->s, vb->s);
2289 else if (cmp_type == FIELD_STR)
3bb16a8b 2290 cmp = cmp_fn(va->s, vb->s);
90c00408 2291 else {
e467dc14 2292 if (va->value < vb->value)
c95b7585 2293 cmp = -1;
e467dc14 2294 else if (va->value == vb->value)
3bb16a8b 2295 cmp = cmp_fn(a->refname, b->refname);
c95b7585
KN
2296 else
2297 cmp = 1;
c95b7585 2298 }
90c00408 2299
c95b7585
KN
2300 return (s->reverse) ? -cmp : cmp;
2301}
2302
83fc4d64 2303static int compare_refs(const void *a_, const void *b_, void *ref_sorting)
c95b7585
KN
2304{
2305 struct ref_array_item *a = *((struct ref_array_item **)a_);
2306 struct ref_array_item *b = *((struct ref_array_item **)b_);
2307 struct ref_sorting *s;
2308
2309 for (s = ref_sorting; s; s = s->next) {
2310 int cmp = cmp_ref_sorting(s, a, b);
2311 if (cmp)
2312 return cmp;
2313 }
2314 return 0;
2315}
2316
2317void ref_array_sort(struct ref_sorting *sorting, struct ref_array *array)
2318{
83fc4d64 2319 QSORT_S(array->items, array->nr, compare_refs, sorting);
c95b7585
KN
2320}
2321
574e96a2 2322static void append_literal(const char *cp, const char *ep, struct ref_formatting_state *state)
c95b7585 2323{
574e96a2
KN
2324 struct strbuf *s = &state->stack->output;
2325
c95b7585
KN
2326 while (*cp && (!ep || cp < ep)) {
2327 if (*cp == '%') {
2328 if (cp[1] == '%')
2329 cp++;
2330 else {
d2330973 2331 int ch = hex2chr(cp + 1);
c95b7585 2332 if (0 <= ch) {
574e96a2 2333 strbuf_addch(s, ch);
c95b7585
KN
2334 cp += 3;
2335 continue;
2336 }
2337 }
2338 }
574e96a2 2339 strbuf_addch(s, *cp);
c95b7585
KN
2340 cp++;
2341 }
2342}
2343
3019eca9 2344int format_ref_array_item(struct ref_array_item *info,
4a68e36d 2345 const struct ref_format *format,
3019eca9
OT
2346 struct strbuf *final_buf,
2347 struct strbuf *error_buf)
c95b7585
KN
2348{
2349 const char *cp, *sp, *ep;
574e96a2
KN
2350 struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
2351
4a68e36d 2352 state.quote_style = format->quote_style;
574e96a2 2353 push_stack_element(&state.stack);
c95b7585 2354
4a68e36d 2355 for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
c95b7585 2356 struct atom_value *atomv;
e6ff7b3b 2357 int pos;
c95b7585
KN
2358
2359 ep = strchr(sp, ')');
2360 if (cp < sp)
574e96a2 2361 append_literal(cp, sp, &state);
e6ff7b3b 2362 pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
e339611b
OT
2363 if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
2364 atomv->handler(atomv, &state, error_buf)) {
3fc8439c
OT
2365 pop_stack_element(&state.stack);
2366 return -1;
2367 }
c95b7585
KN
2368 }
2369 if (*cp) {
2370 sp = cp + strlen(cp);
574e96a2 2371 append_literal(cp, sp, &state);
c95b7585 2372 }
bf285ae6 2373 if (format->need_color_reset_at_eol) {
c95b7585 2374 struct atom_value resetv;
51331aad 2375 resetv.s = GIT_COLOR_RESET;
3fc8439c
OT
2376 if (append_atom(&resetv, &state, error_buf)) {
2377 pop_stack_element(&state.stack);
2378 return -1;
2379 }
c95b7585 2380 }
3019eca9
OT
2381 if (state.stack->prev) {
2382 pop_stack_element(&state.stack);
2383 return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
c95b7585 2384 }
99c6a71d 2385 strbuf_addbuf(final_buf, &state.stack->output);
574e96a2 2386 pop_stack_element(&state.stack);
3019eca9 2387 return 0;
99c6a71d
KN
2388}
2389
4a68e36d
JK
2390void show_ref_array_item(struct ref_array_item *info,
2391 const struct ref_format *format)
99c6a71d
KN
2392{
2393 struct strbuf final_buf = STRBUF_INIT;
3019eca9 2394 struct strbuf error_buf = STRBUF_INIT;
99c6a71d 2395
3019eca9
OT
2396 if (format_ref_array_item(info, format, &final_buf, &error_buf))
2397 die("%s", error_buf.buf);
99c6a71d 2398 fwrite(final_buf.buf, 1, final_buf.len, stdout);
3019eca9 2399 strbuf_release(&error_buf);
99c6a71d 2400 strbuf_release(&final_buf);
c95b7585
KN
2401 putchar('\n');
2402}
2403
53df97a2 2404void pretty_print_ref(const char *name, const struct object_id *oid,
4a68e36d 2405 const struct ref_format *format)
2111aa79
LP
2406{
2407 struct ref_array_item *ref_item;
0ffaa00f 2408 ref_item = new_ref_array_item(name, oid);
2111aa79 2409 ref_item->kind = ref_kind_from_refname(name);
4a68e36d 2410 show_ref_array_item(ref_item, format);
2111aa79
LP
2411 free_array_item(ref_item);
2412}
2413
29ef53cd
JK
2414static int parse_sorting_atom(const char *atom)
2415{
ab7ded34
JK
2416 /*
2417 * This parses an atom using a dummy ref_format, since we don't
2418 * actually care about the formatting details.
2419 */
2420 struct ref_format dummy = REF_FORMAT_INIT;
29ef53cd 2421 const char *end = atom + strlen(atom);
e6ff7b3b
OT
2422 struct strbuf err = STRBUF_INIT;
2423 int res = parse_ref_filter_atom(&dummy, atom, end, &err);
2424 if (res < 0)
2425 die("%s", err.buf);
2426 strbuf_release(&err);
2427 return res;
29ef53cd
JK
2428}
2429
c95b7585
KN
2430/* If no sorting option is given, use refname to sort as default */
2431struct ref_sorting *ref_default_sorting(void)
2432{
2433 static const char cstr_name[] = "refname";
2434
2435 struct ref_sorting *sorting = xcalloc(1, sizeof(*sorting));
2436
2437 sorting->next = NULL;
29ef53cd 2438 sorting->atom = parse_sorting_atom(cstr_name);
c95b7585
KN
2439 return sorting;
2440}
2441
18a25650 2442void parse_ref_sorting(struct ref_sorting **sorting_tail, const char *arg)
c95b7585 2443{
c95b7585 2444 struct ref_sorting *s;
c95b7585 2445
c95b7585
KN
2446 s = xcalloc(1, sizeof(*s));
2447 s->next = *sorting_tail;
2448 *sorting_tail = s;
2449
2450 if (*arg == '-') {
2451 s->reverse = 1;
2452 arg++;
2453 }
90c00408
KN
2454 if (skip_prefix(arg, "version:", &arg) ||
2455 skip_prefix(arg, "v:", &arg))
2456 s->version = 1;
29ef53cd 2457 s->atom = parse_sorting_atom(arg);
18a25650
JK
2458}
2459
2460int parse_opt_ref_sorting(const struct option *opt, const char *arg, int unset)
2461{
95be717c
JK
2462 /*
2463 * NEEDSWORK: We should probably clear the list in this case, but we've
2464 * already munged the global used_atoms list, which would need to be
2465 * undone.
2466 */
2467 BUG_ON_OPT_NEG(unset);
2468
18a25650 2469 parse_ref_sorting(opt->value, arg);
c95b7585
KN
2470 return 0;
2471}
5afcb905
KN
2472
2473int parse_opt_merge_filter(const struct option *opt, const char *arg, int unset)
2474{
2475 struct ref_filter *rf = opt->value;
1e43ed98 2476 struct object_id oid;
17d6c744 2477 int no_merged = starts_with(opt->long_name, "no");
5afcb905 2478
517fe807
JK
2479 BUG_ON_OPT_NEG(unset);
2480
17d6c744
ÆAB
2481 if (rf->merge) {
2482 if (no_merged) {
9440b831
NTND
2483 return error(_("option `%s' is incompatible with --merged"),
2484 opt->long_name);
17d6c744 2485 } else {
9440b831
NTND
2486 return error(_("option `%s' is incompatible with --no-merged"),
2487 opt->long_name);
17d6c744
ÆAB
2488 }
2489 }
5afcb905 2490
17d6c744 2491 rf->merge = no_merged
5afcb905
KN
2492 ? REF_FILTER_MERGED_OMIT
2493 : REF_FILTER_MERGED_INCLUDE;
2494
1e43ed98 2495 if (get_oid(arg, &oid))
5afcb905
KN
2496 die(_("malformed object name %s"), arg);
2497
21e1ee8f
SB
2498 rf->merge_commit = lookup_commit_reference_gently(the_repository,
2499 &oid, 0);
5afcb905 2500 if (!rf->merge_commit)
9440b831 2501 return error(_("option `%s' must point to a commit"), opt->long_name);
5afcb905
KN
2502
2503 return 0;
2504}