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