d1b7e81dbfc14474ed78e3dabc79d90a8e236cbb
1#include "builtin.h"
2#include "cache.h"
3#include "refs.h"
4#include "object.h"
5#include "tag.h"
6#include "commit.h"
7#include "tree.h"
8#include "blob.h"
9#include "quote.h"
10#include "parse-options.h"
11#include "remote.h"
12#include "color.h"
13
14/* Quoting styles */
15#define QUOTE_NONE 0
16#define QUOTE_SHELL 1
17#define QUOTE_PERL 2
18#define QUOTE_PYTHON 4
19#define QUOTE_TCL 8
20
21typedef enum { FIELD_STR, FIELD_ULONG, FIELD_TIME } cmp_type;
22
23struct atom_value {
24 const char *s;
25 unsigned long ul; /* used for sorting when not FIELD_STR */
26};
27
28struct ref_sort {
29 struct ref_sort *next;
30 int atom; /* index into used_atom array */
31 unsigned reverse : 1;
32};
33
34struct ref_array_item {
35 unsigned char objectname[20];
36 int flag;
37 const char *symref;
38 struct atom_value *value;
39 char *refname;
40};
41
42static struct {
43 const char *name;
44 cmp_type cmp_type;
45} valid_atom[] = {
46 { "refname" },
47 { "objecttype" },
48 { "objectsize", FIELD_ULONG },
49 { "objectname" },
50 { "tree" },
51 { "parent" },
52 { "numparent", FIELD_ULONG },
53 { "object" },
54 { "type" },
55 { "tag" },
56 { "author" },
57 { "authorname" },
58 { "authoremail" },
59 { "authordate", FIELD_TIME },
60 { "committer" },
61 { "committername" },
62 { "committeremail" },
63 { "committerdate", FIELD_TIME },
64 { "tagger" },
65 { "taggername" },
66 { "taggeremail" },
67 { "taggerdate", FIELD_TIME },
68 { "creator" },
69 { "creatordate", FIELD_TIME },
70 { "subject" },
71 { "body" },
72 { "contents" },
73 { "contents:subject" },
74 { "contents:body" },
75 { "contents:signature" },
76 { "upstream" },
77 { "push" },
78 { "symref" },
79 { "flag" },
80 { "HEAD" },
81 { "color" },
82};
83
84/*
85 * An atom is a valid field atom listed above, possibly prefixed with
86 * a "*" to denote deref_tag().
87 *
88 * We parse given format string and sort specifiers, and make a list
89 * of properties that we need to extract out of objects. ref_array_item
90 * structure will hold an array of values extracted that can be
91 * indexed with the "atom number", which is an index into this
92 * array.
93 */
94static const char **used_atom;
95static cmp_type *used_atom_type;
96static int used_atom_cnt, need_tagged, need_symref;
97static int need_color_reset_at_eol;
98
99/*
100 * Used to parse format string and sort specifiers
101 */
102static int parse_atom(const char *atom, const char *ep)
103{
104 const char *sp;
105 int i, at;
106
107 sp = atom;
108 if (*sp == '*' && sp < ep)
109 sp++; /* deref */
110 if (ep <= sp)
111 die("malformed field name: %.*s", (int)(ep-atom), atom);
112
113 /* Do we have the atom already used elsewhere? */
114 for (i = 0; i < used_atom_cnt; i++) {
115 int len = strlen(used_atom[i]);
116 if (len == ep - atom && !memcmp(used_atom[i], atom, len))
117 return i;
118 }
119
120 /* Is the atom a valid one? */
121 for (i = 0; i < ARRAY_SIZE(valid_atom); i++) {
122 int len = strlen(valid_atom[i].name);
123 /*
124 * If the atom name has a colon, strip it and everything after
125 * it off - it specifies the format for this entry, and
126 * shouldn't be used for checking against the valid_atom
127 * table.
128 */
129 const char *formatp = strchr(sp, ':');
130 if (!formatp || ep < formatp)
131 formatp = ep;
132 if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
133 break;
134 }
135
136 if (ARRAY_SIZE(valid_atom) <= i)
137 die("unknown field name: %.*s", (int)(ep-atom), atom);
138
139 /* Add it in, including the deref prefix */
140 at = used_atom_cnt;
141 used_atom_cnt++;
142 REALLOC_ARRAY(used_atom, used_atom_cnt);
143 REALLOC_ARRAY(used_atom_type, used_atom_cnt);
144 used_atom[at] = xmemdupz(atom, ep - atom);
145 used_atom_type[at] = valid_atom[i].cmp_type;
146 if (*atom == '*')
147 need_tagged = 1;
148 if (!strcmp(used_atom[at], "symref"))
149 need_symref = 1;
150 return at;
151}
152
153/*
154 * In a format string, find the next occurrence of %(atom).
155 */
156static const char *find_next(const char *cp)
157{
158 while (*cp) {
159 if (*cp == '%') {
160 /*
161 * %( is the start of an atom;
162 * %% is a quoted per-cent.
163 */
164 if (cp[1] == '(')
165 return cp;
166 else if (cp[1] == '%')
167 cp++; /* skip over two % */
168 /* otherwise this is a singleton, literal % */
169 }
170 cp++;
171 }
172 return NULL;
173}
174
175/*
176 * Make sure the format string is well formed, and parse out
177 * the used atoms.
178 */
179static int verify_format(const char *format)
180{
181 const char *cp, *sp;
182
183 need_color_reset_at_eol = 0;
184 for (cp = format; *cp && (sp = find_next(cp)); ) {
185 const char *color, *ep = strchr(sp, ')');
186 int at;
187
188 if (!ep)
189 return error("malformed format string %s", sp);
190 /* sp points at "%(" and ep points at the closing ")" */
191 at = parse_atom(sp + 2, ep);
192 cp = ep + 1;
193
194 if (skip_prefix(used_atom[at], "color:", &color))
195 need_color_reset_at_eol = !!strcmp(color, "reset");
196 }
197 return 0;
198}
199
200/*
201 * Given an object name, read the object data and size, and return a
202 * "struct object". If the object data we are returning is also borrowed
203 * by the "struct object" representation, set *eaten as well---it is a
204 * signal from parse_object_buffer to us not to free the buffer.
205 */
206static void *get_obj(const unsigned char *sha1, struct object **obj, unsigned long *sz, int *eaten)
207{
208 enum object_type type;
209 void *buf = read_sha1_file(sha1, &type, sz);
210
211 if (buf)
212 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
213 else
214 *obj = NULL;
215 return buf;
216}
217
218static int grab_objectname(const char *name, const unsigned char *sha1,
219 struct atom_value *v)
220{
221 if (!strcmp(name, "objectname")) {
222 char *s = xmalloc(41);
223 strcpy(s, sha1_to_hex(sha1));
224 v->s = s;
225 return 1;
226 }
227 if (!strcmp(name, "objectname:short")) {
228 v->s = xstrdup(find_unique_abbrev(sha1, DEFAULT_ABBREV));
229 return 1;
230 }
231 return 0;
232}
233
234/* See grab_values */
235static void grab_common_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
236{
237 int i;
238
239 for (i = 0; i < used_atom_cnt; i++) {
240 const char *name = used_atom[i];
241 struct atom_value *v = &val[i];
242 if (!!deref != (*name == '*'))
243 continue;
244 if (deref)
245 name++;
246 if (!strcmp(name, "objecttype"))
247 v->s = typename(obj->type);
248 else if (!strcmp(name, "objectsize")) {
249 char *s = xmalloc(40);
250 sprintf(s, "%lu", sz);
251 v->ul = sz;
252 v->s = s;
253 }
254 else if (deref)
255 grab_objectname(name, obj->sha1, v);
256 }
257}
258
259/* See grab_values */
260static void grab_tag_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
261{
262 int i;
263 struct tag *tag = (struct tag *) obj;
264
265 for (i = 0; i < used_atom_cnt; i++) {
266 const char *name = used_atom[i];
267 struct atom_value *v = &val[i];
268 if (!!deref != (*name == '*'))
269 continue;
270 if (deref)
271 name++;
272 if (!strcmp(name, "tag"))
273 v->s = tag->tag;
274 else if (!strcmp(name, "type") && tag->tagged)
275 v->s = typename(tag->tagged->type);
276 else if (!strcmp(name, "object") && tag->tagged) {
277 char *s = xmalloc(41);
278 strcpy(s, sha1_to_hex(tag->tagged->sha1));
279 v->s = s;
280 }
281 }
282}
283
284/* See grab_values */
285static void grab_commit_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
286{
287 int i;
288 struct commit *commit = (struct commit *) obj;
289
290 for (i = 0; i < used_atom_cnt; i++) {
291 const char *name = used_atom[i];
292 struct atom_value *v = &val[i];
293 if (!!deref != (*name == '*'))
294 continue;
295 if (deref)
296 name++;
297 if (!strcmp(name, "tree")) {
298 char *s = xmalloc(41);
299 strcpy(s, sha1_to_hex(commit->tree->object.sha1));
300 v->s = s;
301 }
302 if (!strcmp(name, "numparent")) {
303 char *s = xmalloc(40);
304 v->ul = commit_list_count(commit->parents);
305 sprintf(s, "%lu", v->ul);
306 v->s = s;
307 }
308 else if (!strcmp(name, "parent")) {
309 int num = commit_list_count(commit->parents);
310 int i;
311 struct commit_list *parents;
312 char *s = xmalloc(41 * num + 1);
313 v->s = s;
314 for (i = 0, parents = commit->parents;
315 parents;
316 parents = parents->next, i = i + 41) {
317 struct commit *parent = parents->item;
318 strcpy(s+i, sha1_to_hex(parent->object.sha1));
319 if (parents->next)
320 s[i+40] = ' ';
321 }
322 if (!i)
323 *s = '\0';
324 }
325 }
326}
327
328static const char *find_wholine(const char *who, int wholen, const char *buf, unsigned long sz)
329{
330 const char *eol;
331 while (*buf) {
332 if (!strncmp(buf, who, wholen) &&
333 buf[wholen] == ' ')
334 return buf + wholen + 1;
335 eol = strchr(buf, '\n');
336 if (!eol)
337 return "";
338 eol++;
339 if (*eol == '\n')
340 return ""; /* end of header */
341 buf = eol;
342 }
343 return "";
344}
345
346static const char *copy_line(const char *buf)
347{
348 const char *eol = strchrnul(buf, '\n');
349 return xmemdupz(buf, eol - buf);
350}
351
352static const char *copy_name(const char *buf)
353{
354 const char *cp;
355 for (cp = buf; *cp && *cp != '\n'; cp++) {
356 if (!strncmp(cp, " <", 2))
357 return xmemdupz(buf, cp - buf);
358 }
359 return "";
360}
361
362static const char *copy_email(const char *buf)
363{
364 const char *email = strchr(buf, '<');
365 const char *eoemail;
366 if (!email)
367 return "";
368 eoemail = strchr(email, '>');
369 if (!eoemail)
370 return "";
371 return xmemdupz(email, eoemail + 1 - email);
372}
373
374static char *copy_subject(const char *buf, unsigned long len)
375{
376 char *r = xmemdupz(buf, len);
377 int i;
378
379 for (i = 0; i < len; i++)
380 if (r[i] == '\n')
381 r[i] = ' ';
382
383 return r;
384}
385
386static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
387{
388 const char *eoemail = strstr(buf, "> ");
389 char *zone;
390 unsigned long timestamp;
391 long tz;
392 enum date_mode date_mode = DATE_NORMAL;
393 const char *formatp;
394
395 /*
396 * We got here because atomname ends in "date" or "date<something>";
397 * it's not possible that <something> is not ":<format>" because
398 * parse_atom() wouldn't have allowed it, so we can assume that no
399 * ":" means no format is specified, and use the default.
400 */
401 formatp = strchr(atomname, ':');
402 if (formatp != NULL) {
403 formatp++;
404 date_mode = parse_date_format(formatp);
405 }
406
407 if (!eoemail)
408 goto bad;
409 timestamp = strtoul(eoemail + 2, &zone, 10);
410 if (timestamp == ULONG_MAX)
411 goto bad;
412 tz = strtol(zone, NULL, 10);
413 if ((tz == LONG_MIN || tz == LONG_MAX) && errno == ERANGE)
414 goto bad;
415 v->s = xstrdup(show_date(timestamp, tz, date_mode));
416 v->ul = timestamp;
417 return;
418 bad:
419 v->s = "";
420 v->ul = 0;
421}
422
423/* See grab_values */
424static void grab_person(const char *who, struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
425{
426 int i;
427 int wholen = strlen(who);
428 const char *wholine = NULL;
429
430 for (i = 0; i < used_atom_cnt; i++) {
431 const char *name = used_atom[i];
432 struct atom_value *v = &val[i];
433 if (!!deref != (*name == '*'))
434 continue;
435 if (deref)
436 name++;
437 if (strncmp(who, name, wholen))
438 continue;
439 if (name[wholen] != 0 &&
440 strcmp(name + wholen, "name") &&
441 strcmp(name + wholen, "email") &&
442 !starts_with(name + wholen, "date"))
443 continue;
444 if (!wholine)
445 wholine = find_wholine(who, wholen, buf, sz);
446 if (!wholine)
447 return; /* no point looking for it */
448 if (name[wholen] == 0)
449 v->s = copy_line(wholine);
450 else if (!strcmp(name + wholen, "name"))
451 v->s = copy_name(wholine);
452 else if (!strcmp(name + wholen, "email"))
453 v->s = copy_email(wholine);
454 else if (starts_with(name + wholen, "date"))
455 grab_date(wholine, v, name);
456 }
457
458 /*
459 * For a tag or a commit object, if "creator" or "creatordate" is
460 * requested, do something special.
461 */
462 if (strcmp(who, "tagger") && strcmp(who, "committer"))
463 return; /* "author" for commit object is not wanted */
464 if (!wholine)
465 wholine = find_wholine(who, wholen, buf, sz);
466 if (!wholine)
467 return;
468 for (i = 0; i < used_atom_cnt; i++) {
469 const char *name = used_atom[i];
470 struct atom_value *v = &val[i];
471 if (!!deref != (*name == '*'))
472 continue;
473 if (deref)
474 name++;
475
476 if (starts_with(name, "creatordate"))
477 grab_date(wholine, v, name);
478 else if (!strcmp(name, "creator"))
479 v->s = copy_line(wholine);
480 }
481}
482
483static void find_subpos(const char *buf, unsigned long sz,
484 const char **sub, unsigned long *sublen,
485 const char **body, unsigned long *bodylen,
486 unsigned long *nonsiglen,
487 const char **sig, unsigned long *siglen)
488{
489 const char *eol;
490 /* skip past header until we hit empty line */
491 while (*buf && *buf != '\n') {
492 eol = strchrnul(buf, '\n');
493 if (*eol)
494 eol++;
495 buf = eol;
496 }
497 /* skip any empty lines */
498 while (*buf == '\n')
499 buf++;
500
501 /* parse signature first; we might not even have a subject line */
502 *sig = buf + parse_signature(buf, strlen(buf));
503 *siglen = strlen(*sig);
504
505 /* subject is first non-empty line */
506 *sub = buf;
507 /* subject goes to first empty line */
508 while (buf < *sig && *buf && *buf != '\n') {
509 eol = strchrnul(buf, '\n');
510 if (*eol)
511 eol++;
512 buf = eol;
513 }
514 *sublen = buf - *sub;
515 /* drop trailing newline, if present */
516 if (*sublen && (*sub)[*sublen - 1] == '\n')
517 *sublen -= 1;
518
519 /* skip any empty lines */
520 while (*buf == '\n')
521 buf++;
522 *body = buf;
523 *bodylen = strlen(buf);
524 *nonsiglen = *sig - buf;
525}
526
527/* See grab_values */
528static void grab_sub_body_contents(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
529{
530 int i;
531 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
532 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
533
534 for (i = 0; i < used_atom_cnt; i++) {
535 const char *name = used_atom[i];
536 struct atom_value *v = &val[i];
537 if (!!deref != (*name == '*'))
538 continue;
539 if (deref)
540 name++;
541 if (strcmp(name, "subject") &&
542 strcmp(name, "body") &&
543 strcmp(name, "contents") &&
544 strcmp(name, "contents:subject") &&
545 strcmp(name, "contents:body") &&
546 strcmp(name, "contents:signature"))
547 continue;
548 if (!subpos)
549 find_subpos(buf, sz,
550 &subpos, &sublen,
551 &bodypos, &bodylen, &nonsiglen,
552 &sigpos, &siglen);
553
554 if (!strcmp(name, "subject"))
555 v->s = copy_subject(subpos, sublen);
556 else if (!strcmp(name, "contents:subject"))
557 v->s = copy_subject(subpos, sublen);
558 else if (!strcmp(name, "body"))
559 v->s = xmemdupz(bodypos, bodylen);
560 else if (!strcmp(name, "contents:body"))
561 v->s = xmemdupz(bodypos, nonsiglen);
562 else if (!strcmp(name, "contents:signature"))
563 v->s = xmemdupz(sigpos, siglen);
564 else if (!strcmp(name, "contents"))
565 v->s = xstrdup(subpos);
566 }
567}
568
569/*
570 * We want to have empty print-string for field requests
571 * that do not apply (e.g. "authordate" for a tag object)
572 */
573static void fill_missing_values(struct atom_value *val)
574{
575 int i;
576 for (i = 0; i < used_atom_cnt; i++) {
577 struct atom_value *v = &val[i];
578 if (v->s == NULL)
579 v->s = "";
580 }
581}
582
583/*
584 * val is a list of atom_value to hold returned values. Extract
585 * the values for atoms in used_atom array out of (obj, buf, sz).
586 * when deref is false, (obj, buf, sz) is the object that is
587 * pointed at by the ref itself; otherwise it is the object the
588 * ref (which is a tag) refers to.
589 */
590static void grab_values(struct atom_value *val, int deref, struct object *obj, void *buf, unsigned long sz)
591{
592 grab_common_values(val, deref, obj, buf, sz);
593 switch (obj->type) {
594 case OBJ_TAG:
595 grab_tag_values(val, deref, obj, buf, sz);
596 grab_sub_body_contents(val, deref, obj, buf, sz);
597 grab_person("tagger", val, deref, obj, buf, sz);
598 break;
599 case OBJ_COMMIT:
600 grab_commit_values(val, deref, obj, buf, sz);
601 grab_sub_body_contents(val, deref, obj, buf, sz);
602 grab_person("author", val, deref, obj, buf, sz);
603 grab_person("committer", val, deref, obj, buf, sz);
604 break;
605 case OBJ_TREE:
606 /* grab_tree_values(val, deref, obj, buf, sz); */
607 break;
608 case OBJ_BLOB:
609 /* grab_blob_values(val, deref, obj, buf, sz); */
610 break;
611 default:
612 die("Eh? Object of type %d?", obj->type);
613 }
614}
615
616static inline char *copy_advance(char *dst, const char *src)
617{
618 while (*src)
619 *dst++ = *src++;
620 return dst;
621}
622
623/*
624 * Parse the object referred by ref, and grab needed value.
625 */
626static void populate_value(struct ref_array_item *ref)
627{
628 void *buf;
629 struct object *obj;
630 int eaten, i;
631 unsigned long size;
632 const unsigned char *tagged;
633
634 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
635
636 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
637 unsigned char unused1[20];
638 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
639 unused1, NULL);
640 if (!ref->symref)
641 ref->symref = "";
642 }
643
644 /* Fill in specials first */
645 for (i = 0; i < used_atom_cnt; i++) {
646 const char *name = used_atom[i];
647 struct atom_value *v = &ref->value[i];
648 int deref = 0;
649 const char *refname;
650 const char *formatp;
651 struct branch *branch = NULL;
652
653 if (*name == '*') {
654 deref = 1;
655 name++;
656 }
657
658 if (starts_with(name, "refname"))
659 refname = ref->refname;
660 else if (starts_with(name, "symref"))
661 refname = ref->symref ? ref->symref : "";
662 else if (starts_with(name, "upstream")) {
663 const char *branch_name;
664 /* only local branches may have an upstream */
665 if (!skip_prefix(ref->refname, "refs/heads/",
666 &branch_name))
667 continue;
668 branch = branch_get(branch_name);
669
670 refname = branch_get_upstream(branch, NULL);
671 if (!refname)
672 continue;
673 } else if (starts_with(name, "push")) {
674 const char *branch_name;
675 if (!skip_prefix(ref->refname, "refs/heads/",
676 &branch_name))
677 continue;
678 branch = branch_get(branch_name);
679
680 refname = branch_get_push(branch, NULL);
681 if (!refname)
682 continue;
683 } else if (starts_with(name, "color:")) {
684 char color[COLOR_MAXLEN] = "";
685
686 if (color_parse(name + 6, color) < 0)
687 die(_("unable to parse format"));
688 v->s = xstrdup(color);
689 continue;
690 } else if (!strcmp(name, "flag")) {
691 char buf[256], *cp = buf;
692 if (ref->flag & REF_ISSYMREF)
693 cp = copy_advance(cp, ",symref");
694 if (ref->flag & REF_ISPACKED)
695 cp = copy_advance(cp, ",packed");
696 if (cp == buf)
697 v->s = "";
698 else {
699 *cp = '\0';
700 v->s = xstrdup(buf + 1);
701 }
702 continue;
703 } else if (!deref && grab_objectname(name, ref->objectname, v)) {
704 continue;
705 } else if (!strcmp(name, "HEAD")) {
706 const char *head;
707 unsigned char sha1[20];
708
709 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
710 sha1, NULL);
711 if (!strcmp(ref->refname, head))
712 v->s = "*";
713 else
714 v->s = " ";
715 continue;
716 } else
717 continue;
718
719 formatp = strchr(name, ':');
720 if (formatp) {
721 int num_ours, num_theirs;
722
723 formatp++;
724 if (!strcmp(formatp, "short"))
725 refname = shorten_unambiguous_ref(refname,
726 warn_ambiguous_refs);
727 else if (!strcmp(formatp, "track") &&
728 (starts_with(name, "upstream") ||
729 starts_with(name, "push"))) {
730 char buf[40];
731
732 if (stat_tracking_info(branch, &num_ours,
733 &num_theirs, NULL))
734 continue;
735
736 if (!num_ours && !num_theirs)
737 v->s = "";
738 else if (!num_ours) {
739 sprintf(buf, "[behind %d]", num_theirs);
740 v->s = xstrdup(buf);
741 } else if (!num_theirs) {
742 sprintf(buf, "[ahead %d]", num_ours);
743 v->s = xstrdup(buf);
744 } else {
745 sprintf(buf, "[ahead %d, behind %d]",
746 num_ours, num_theirs);
747 v->s = xstrdup(buf);
748 }
749 continue;
750 } else if (!strcmp(formatp, "trackshort") &&
751 (starts_with(name, "upstream") ||
752 starts_with(name, "push"))) {
753 assert(branch);
754
755 if (stat_tracking_info(branch, &num_ours,
756 &num_theirs, NULL))
757 continue;
758
759 if (!num_ours && !num_theirs)
760 v->s = "=";
761 else if (!num_ours)
762 v->s = "<";
763 else if (!num_theirs)
764 v->s = ">";
765 else
766 v->s = "<>";
767 continue;
768 } else
769 die("unknown %.*s format %s",
770 (int)(formatp - name), name, formatp);
771 }
772
773 if (!deref)
774 v->s = refname;
775 else {
776 int len = strlen(refname);
777 char *s = xmalloc(len + 4);
778 sprintf(s, "%s^{}", refname);
779 v->s = s;
780 }
781 }
782
783 for (i = 0; i < used_atom_cnt; i++) {
784 struct atom_value *v = &ref->value[i];
785 if (v->s == NULL)
786 goto need_obj;
787 }
788 return;
789
790 need_obj:
791 buf = get_obj(ref->objectname, &obj, &size, &eaten);
792 if (!buf)
793 die("missing object %s for %s",
794 sha1_to_hex(ref->objectname), ref->refname);
795 if (!obj)
796 die("parse_object_buffer failed on %s for %s",
797 sha1_to_hex(ref->objectname), ref->refname);
798
799 grab_values(ref->value, 0, obj, buf, size);
800 if (!eaten)
801 free(buf);
802
803 /*
804 * If there is no atom that wants to know about tagged
805 * object, we are done.
806 */
807 if (!need_tagged || (obj->type != OBJ_TAG))
808 return;
809
810 /*
811 * If it is a tag object, see if we use a value that derefs
812 * the object, and if we do grab the object it refers to.
813 */
814 tagged = ((struct tag *)obj)->tagged->sha1;
815
816 /*
817 * NEEDSWORK: This derefs tag only once, which
818 * is good to deal with chains of trust, but
819 * is not consistent with what deref_tag() does
820 * which peels the onion to the core.
821 */
822 buf = get_obj(tagged, &obj, &size, &eaten);
823 if (!buf)
824 die("missing object %s for %s",
825 sha1_to_hex(tagged), ref->refname);
826 if (!obj)
827 die("parse_object_buffer failed on %s for %s",
828 sha1_to_hex(tagged), ref->refname);
829 grab_values(ref->value, 1, obj, buf, size);
830 if (!eaten)
831 free(buf);
832}
833
834/*
835 * Given a ref, return the value for the atom. This lazily gets value
836 * out of the object by calling populate value.
837 */
838static void get_value(struct ref_array_item *ref, int atom, struct atom_value **v)
839{
840 if (!ref->value) {
841 populate_value(ref);
842 fill_missing_values(ref->value);
843 }
844 *v = &ref->value[atom];
845}
846
847struct grab_ref_cbdata {
848 struct ref_array_item **grab_array;
849 const char **grab_pattern;
850 int grab_cnt;
851};
852
853/*
854 * Return 1 if the refname matches one of the patterns, otherwise 0.
855 * A pattern can be path prefix (e.g. a refname "refs/heads/master"
856 * matches a pattern "refs/heads/") or a wildcard (e.g. the same ref
857 * matches "refs/heads/m*",too).
858 */
859static int match_name_as_path(const char **pattern, const char *refname)
860{
861 int namelen = strlen(refname);
862 for (; *pattern; pattern++) {
863 const char *p = *pattern;
864 int plen = strlen(p);
865
866 if ((plen <= namelen) &&
867 !strncmp(refname, p, plen) &&
868 (refname[plen] == '\0' ||
869 refname[plen] == '/' ||
870 p[plen-1] == '/'))
871 return 1;
872 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
873 return 1;
874 }
875 return 0;
876}
877
878/* Allocate space for a new ref_array_item and copy the objectname and flag to it */
879static struct ref_array_item *new_ref_array_item(const char *refname,
880 const unsigned char *objectname,
881 int flag)
882{
883 struct ref_array_item *ref = xcalloc(1, sizeof(struct ref_array_item));
884 ref->refname = xstrdup(refname);
885 hashcpy(ref->objectname, objectname);
886 ref->flag = flag;
887
888 return ref;
889}
890
891/*
892 * A call-back given to for_each_ref(). Filter refs and keep them for
893 * later object processing.
894 */
895static int grab_single_ref(const char *refname, const struct object_id *oid,
896 int flag, void *cb_data)
897{
898 struct grab_ref_cbdata *cb = cb_data;
899 struct ref_array_item *ref;
900
901 if (flag & REF_BAD_NAME) {
902 warning("ignoring ref with broken name %s", refname);
903 return 0;
904 }
905
906 if (*cb->grab_pattern && !match_name_as_path(cb->grab_pattern, refname))
907 return 0;
908
909 /*
910 * We do not open the object yet; sort may only need refname
911 * to do its job and the resulting list may yet to be pruned
912 * by maxcount logic.
913 */
914 ref = new_ref_array_item(refname, oid->hash, flag);
915
916 REALLOC_ARRAY(cb->grab_array, cb->grab_cnt + 1);
917 cb->grab_array[cb->grab_cnt++] = ref;
918 return 0;
919}
920
921static int cmp_ref_sort(struct ref_sort *s, struct ref_array_item *a, struct ref_array_item *b)
922{
923 struct atom_value *va, *vb;
924 int cmp;
925 cmp_type cmp_type = used_atom_type[s->atom];
926
927 get_value(a, s->atom, &va);
928 get_value(b, s->atom, &vb);
929 switch (cmp_type) {
930 case FIELD_STR:
931 cmp = strcmp(va->s, vb->s);
932 break;
933 default:
934 if (va->ul < vb->ul)
935 cmp = -1;
936 else if (va->ul == vb->ul)
937 cmp = 0;
938 else
939 cmp = 1;
940 break;
941 }
942 return (s->reverse) ? -cmp : cmp;
943}
944
945static struct ref_sort *ref_sort;
946static int compare_refs(const void *a_, const void *b_)
947{
948 struct ref_array_item *a = *((struct ref_array_item **)a_);
949 struct ref_array_item *b = *((struct ref_array_item **)b_);
950 struct ref_sort *s;
951
952 for (s = ref_sort; s; s = s->next) {
953 int cmp = cmp_ref_sort(s, a, b);
954 if (cmp)
955 return cmp;
956 }
957 return 0;
958}
959
960static void sort_refs(struct ref_sort *sort, struct ref_array_item **refs, int num_refs)
961{
962 ref_sort = sort;
963 qsort(refs, num_refs, sizeof(struct ref_array_item *), compare_refs);
964}
965
966static void print_value(struct atom_value *v, int quote_style)
967{
968 struct strbuf sb = STRBUF_INIT;
969 switch (quote_style) {
970 case QUOTE_NONE:
971 fputs(v->s, stdout);
972 break;
973 case QUOTE_SHELL:
974 sq_quote_buf(&sb, v->s);
975 break;
976 case QUOTE_PERL:
977 perl_quote_buf(&sb, v->s);
978 break;
979 case QUOTE_PYTHON:
980 python_quote_buf(&sb, v->s);
981 break;
982 case QUOTE_TCL:
983 tcl_quote_buf(&sb, v->s);
984 break;
985 }
986 if (quote_style != QUOTE_NONE) {
987 fputs(sb.buf, stdout);
988 strbuf_release(&sb);
989 }
990}
991
992static int hex1(char ch)
993{
994 if ('0' <= ch && ch <= '9')
995 return ch - '0';
996 else if ('a' <= ch && ch <= 'f')
997 return ch - 'a' + 10;
998 else if ('A' <= ch && ch <= 'F')
999 return ch - 'A' + 10;
1000 return -1;
1001}
1002static int hex2(const char *cp)
1003{
1004 if (cp[0] && cp[1])
1005 return (hex1(cp[0]) << 4) | hex1(cp[1]);
1006 else
1007 return -1;
1008}
1009
1010static void emit(const char *cp, const char *ep)
1011{
1012 while (*cp && (!ep || cp < ep)) {
1013 if (*cp == '%') {
1014 if (cp[1] == '%')
1015 cp++;
1016 else {
1017 int ch = hex2(cp + 1);
1018 if (0 <= ch) {
1019 putchar(ch);
1020 cp += 3;
1021 continue;
1022 }
1023 }
1024 }
1025 putchar(*cp);
1026 cp++;
1027 }
1028}
1029
1030static void show_ref(struct ref_array_item *info, const char *format, int quote_style)
1031{
1032 const char *cp, *sp, *ep;
1033
1034 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
1035 struct atom_value *atomv;
1036
1037 ep = strchr(sp, ')');
1038 if (cp < sp)
1039 emit(cp, sp);
1040 get_value(info, parse_atom(sp + 2, ep), &atomv);
1041 print_value(atomv, quote_style);
1042 }
1043 if (*cp) {
1044 sp = cp + strlen(cp);
1045 emit(cp, sp);
1046 }
1047 if (need_color_reset_at_eol) {
1048 struct atom_value resetv;
1049 char color[COLOR_MAXLEN] = "";
1050
1051 if (color_parse("reset", color) < 0)
1052 die("BUG: couldn't parse 'reset' as a color");
1053 resetv.s = color;
1054 print_value(&resetv, quote_style);
1055 }
1056 putchar('\n');
1057}
1058
1059static struct ref_sort *default_sort(void)
1060{
1061 static const char cstr_name[] = "refname";
1062
1063 struct ref_sort *sort = xcalloc(1, sizeof(*sort));
1064
1065 sort->next = NULL;
1066 sort->atom = parse_atom(cstr_name, cstr_name + strlen(cstr_name));
1067 return sort;
1068}
1069
1070static int opt_parse_sort(const struct option *opt, const char *arg, int unset)
1071{
1072 struct ref_sort **sort_tail = opt->value;
1073 struct ref_sort *s;
1074 int len;
1075
1076 if (!arg) /* should --no-sort void the list ? */
1077 return -1;
1078
1079 s = xcalloc(1, sizeof(*s));
1080 s->next = *sort_tail;
1081 *sort_tail = s;
1082
1083 if (*arg == '-') {
1084 s->reverse = 1;
1085 arg++;
1086 }
1087 len = strlen(arg);
1088 s->atom = parse_atom(arg, arg+len);
1089 return 0;
1090}
1091
1092static char const * const for_each_ref_usage[] = {
1093 N_("git for-each-ref [<options>] [<pattern>]"),
1094 NULL
1095};
1096
1097int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
1098{
1099 int i, num_refs;
1100 const char *format = "%(objectname) %(objecttype)\t%(refname)";
1101 struct ref_sort *sort = NULL, **sort_tail = &sort;
1102 int maxcount = 0, quote_style = 0;
1103 struct ref_array_item **refs;
1104 struct grab_ref_cbdata cbdata;
1105
1106 struct option opts[] = {
1107 OPT_BIT('s', "shell", "e_style,
1108 N_("quote placeholders suitably for shells"), QUOTE_SHELL),
1109 OPT_BIT('p', "perl", "e_style,
1110 N_("quote placeholders suitably for perl"), QUOTE_PERL),
1111 OPT_BIT(0 , "python", "e_style,
1112 N_("quote placeholders suitably for python"), QUOTE_PYTHON),
1113 OPT_BIT(0 , "tcl", "e_style,
1114 N_("quote placeholders suitably for Tcl"), QUOTE_TCL),
1115
1116 OPT_GROUP(""),
1117 OPT_INTEGER( 0 , "count", &maxcount, N_("show only <n> matched refs")),
1118 OPT_STRING( 0 , "format", &format, N_("format"), N_("format to use for the output")),
1119 OPT_CALLBACK(0 , "sort", sort_tail, N_("key"),
1120 N_("field name to sort on"), &opt_parse_sort),
1121 OPT_END(),
1122 };
1123
1124 parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
1125 if (maxcount < 0) {
1126 error("invalid --count argument: `%d'", maxcount);
1127 usage_with_options(for_each_ref_usage, opts);
1128 }
1129 if (HAS_MULTI_BITS(quote_style)) {
1130 error("more than one quoting style?");
1131 usage_with_options(for_each_ref_usage, opts);
1132 }
1133 if (verify_format(format))
1134 usage_with_options(for_each_ref_usage, opts);
1135
1136 if (!sort)
1137 sort = default_sort();
1138
1139 /* for warn_ambiguous_refs */
1140 git_config(git_default_config, NULL);
1141
1142 memset(&cbdata, 0, sizeof(cbdata));
1143 cbdata.grab_pattern = argv;
1144 for_each_rawref(grab_single_ref, &cbdata);
1145 refs = cbdata.grab_array;
1146 num_refs = cbdata.grab_cnt;
1147
1148 sort_refs(sort, refs, num_refs);
1149
1150 if (!maxcount || num_refs < maxcount)
1151 maxcount = num_refs;
1152 for (i = 0; i < maxcount; i++)
1153 show_ref(refs[i], format, quote_style);
1154 return 0;
1155}