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