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