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