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