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