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