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