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