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