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