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