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