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