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