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