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