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