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