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