]> git.ipfire.org Git - thirdparty/git.git/blame - builtin/for-each-ref.c
Merge branch 'br/imap-send-via-libcurl'
[thirdparty/git.git] / builtin / for-each-ref.c
CommitLineData
baffc0e7 1#include "builtin.h"
9f613ddd
JH
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"
c3428da8 10#include "parse-options.h"
8cae19d9 11#include "remote.h"
fddb74c9 12#include "color.h"
9f613ddd
JH
13
14/* Quoting styles */
15#define QUOTE_NONE 0
16#define QUOTE_SHELL 1
17#define QUOTE_PERL 2
c9ecf4f1
JS
18#define QUOTE_PYTHON 4
19#define QUOTE_TCL 8
9f613ddd
JH
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 refinfo {
35 char *refname;
36 unsigned char objectname[20];
5cdd628c
JH
37 int flag;
38 const char *symref;
9f613ddd
JH
39 struct atom_value *value;
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" },
9e1a2acf 51 { "parent" },
9f613ddd
JH
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 },
3175aa1e
JH
68 { "creator" },
69 { "creatordate", FIELD_TIME },
9f613ddd
JH
70 { "subject" },
71 { "body" },
72 { "contents" },
e2b23972
MG
73 { "contents:subject" },
74 { "contents:body" },
75 { "contents:signature" },
8cae19d9 76 { "upstream" },
5cdd628c 77 { "symref" },
88fb7f27 78 { "flag" },
7a48b832 79 { "HEAD" },
fddb74c9 80 { "color" },
9f613ddd
JH
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 */
93static const char **used_atom;
94static cmp_type *used_atom_type;
b9cf14d4 95static int used_atom_cnt, need_tagged, need_symref;
db64eb65 96static int need_color_reset_at_eol;
9f613ddd
JH
97
98/*
99 * Used to parse format string and sort specifiers
100 */
101static int parse_atom(const char *atom, const char *ep)
102{
103 const char *sp;
9f613ddd
JH
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);
b64265ca
AP
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, ':');
070f6918 129 if (!formatp || ep < formatp)
b64265ca
AP
130 formatp = ep;
131 if (len == formatp - sp && !memcmp(valid_atom[i].name, sp, len))
9f613ddd
JH
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++;
2756ca43
RS
141 REALLOC_ARRAY(used_atom, used_atom_cnt);
142 REALLOC_ARRAY(used_atom_type, used_atom_cnt);
182af834 143 used_atom[at] = xmemdupz(atom, ep - atom);
9f613ddd 144 used_atom_type[at] = valid_atom[i].cmp_type;
20322e0b
JH
145 if (*atom == '*')
146 need_tagged = 1;
5cdd628c
JH
147 if (!strcmp(used_atom[at], "symref"))
148 need_symref = 1;
9f613ddd
JH
149 return at;
150}
151
152/*
153 * In a format string, find the next occurrence of %(atom).
154 */
155static const char *find_next(const char *cp)
156{
157 while (*cp) {
158 if (*cp == '%') {
40dae309
JH
159 /*
160 * %( is the start of an atom;
3dff5379 161 * %% is a quoted per-cent.
9f613ddd
JH
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 */
c3428da8 178static int verify_format(const char *format)
9f613ddd
JH
179{
180 const char *cp, *sp;
db64eb65
RR
181 static const char color_reset[] = "color:reset";
182
183 need_color_reset_at_eol = 0;
9f613ddd
JH
184 for (cp = format; *cp && (sp = find_next(cp)); ) {
185 const char *ep = strchr(sp, ')');
db64eb65
RR
186 int at;
187
9f613ddd 188 if (!ep)
8e0fbe67 189 return error("malformed format string %s", sp);
9f613ddd 190 /* sp points at "%(" and ep points at the closing ")" */
db64eb65 191 at = parse_atom(sp + 2, ep);
9f613ddd 192 cp = ep + 1;
db64eb65 193
50e19a83 194 if (starts_with(used_atom[at], "color:"))
db64eb65 195 need_color_reset_at_eol = !!strcmp(used_atom[at], color_reset);
9f613ddd 196 }
c3428da8 197 return 0;
9f613ddd
JH
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{
21666f1a
NP
208 enum object_type type;
209 void *buf = read_sha1_file(sha1, &type, sz);
9f613ddd
JH
210
211 if (buf)
212 *obj = parse_object_buffer(sha1, type, *sz, buf, eaten);
213 else
214 *obj = NULL;
215 return buf;
216}
217
b74cf648
JK
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
9f613ddd
JH
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"))
df843662 247 v->s = typename(obj->type);
9f613ddd
JH
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 }
b74cf648
JK
254 else if (deref)
255 grab_objectname(name, obj->sha1, v);
9f613ddd
JH
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;
87412ec1
JK
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 }
9f613ddd
JH
281 }
282}
283
9f613ddd
JH
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);
4bbaa1eb 304 v->ul = commit_list_count(commit->parents);
9f613ddd
JH
305 sprintf(s, "%lu", v->ul);
306 v->s = s;
9f613ddd
JH
307 }
308 else if (!strcmp(name, "parent")) {
4bbaa1eb 309 int num = commit_list_count(commit->parents);
9f613ddd
JH
310 int i;
311 struct commit_list *parents;
9e1a2acf 312 char *s = xmalloc(41 * num + 1);
9f613ddd
JH
313 v->s = s;
314 for (i = 0, parents = commit->parents;
315 parents;
9e1a2acf 316 parents = parents->next, i = i + 41) {
9f613ddd
JH
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 }
9e1a2acf
JH
322 if (!i)
323 *s = '\0';
9f613ddd
JH
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++;
a74fa110 339 if (*eol == '\n')
9f613ddd
JH
340 return ""; /* end of header */
341 buf = eol;
342 }
343 return "";
344}
345
3a55602e 346static const char *copy_line(const char *buf)
9f613ddd 347{
94e02e7f 348 const char *eol = strchrnul(buf, '\n');
182af834 349 return xmemdupz(buf, eol - buf);
9f613ddd
JH
350}
351
3a55602e 352static const char *copy_name(const char *buf)
9f613ddd 353{
182af834 354 const char *cp;
6b30852d 355 for (cp = buf; *cp && *cp != '\n'; cp++) {
182af834
PH
356 if (!strncmp(cp, " <", 2))
357 return xmemdupz(buf, cp - buf);
358 }
359 return "";
9f613ddd
JH
360}
361
3a55602e 362static const char *copy_email(const char *buf)
9f613ddd
JH
363{
364 const char *email = strchr(buf, '<');
e64c1b00
JK
365 const char *eoemail;
366 if (!email)
367 return "";
368 eoemail = strchr(email, '>');
369 if (!eoemail)
9f613ddd 370 return "";
182af834 371 return xmemdupz(email, eoemail + 1 - email);
9f613ddd
JH
372}
373
7f6e275b
JK
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
d392e712 386static void grab_date(const char *buf, struct atom_value *v, const char *atomname)
9f613ddd
JH
387{
388 const char *eoemail = strstr(buf, "> ");
389 char *zone;
390 unsigned long timestamp;
391 long tz;
d392e712
AP
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 }
9f613ddd
JH
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;
d392e712 415 v->s = xstrdup(show_date(timestamp, tz, date_mode));
9f613ddd
JH
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") &&
59556548 442 !starts_with(name + wholen, "date"))
9f613ddd
JH
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);
59556548 454 else if (starts_with(name + wholen, "date"))
d392e712 455 grab_date(wholine, v, name);
9f613ddd 456 }
3175aa1e 457
40dae309
JH
458 /*
459 * For a tag or a commit object, if "creator" or "creatordate" is
3175aa1e
JH
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
59556548 476 if (starts_with(name, "creatordate"))
d392e712 477 grab_date(wholine, v, name);
3175aa1e
JH
478 else if (!strcmp(name, "creator"))
479 v->s = copy_line(wholine);
480 }
9f613ddd
JH
481}
482
7ec0f31e
JK
483static void find_subpos(const char *buf, unsigned long sz,
484 const char **sub, unsigned long *sublen,
e2b23972
MG
485 const char **body, unsigned long *bodylen,
486 unsigned long *nonsiglen,
487 const char **sig, unsigned long *siglen)
9f613ddd 488{
7ec0f31e
JK
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;
9f613ddd 496 }
7ec0f31e 497 /* skip any empty lines */
9f613ddd
JH
498 while (*buf == '\n')
499 buf++;
7ec0f31e 500
e2b23972
MG
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
7ec0f31e
JK
505 /* subject is first non-empty line */
506 *sub = buf;
7f6e275b 507 /* subject goes to first empty line */
e2b23972 508 while (buf < *sig && *buf && *buf != '\n') {
7f6e275b
JK
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;
7ec0f31e
JK
518
519 /* skip any empty lines */
9f613ddd 520 while (*buf == '\n')
7ec0f31e 521 buf++;
9f613ddd 522 *body = buf;
7ec0f31e 523 *bodylen = strlen(buf);
e2b23972 524 *nonsiglen = *sig - buf;
9f613ddd
JH
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;
e2b23972
MG
531 const char *subpos = NULL, *bodypos = NULL, *sigpos = NULL;
532 unsigned long sublen = 0, bodylen = 0, nonsiglen = 0, siglen = 0;
9f613ddd
JH
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") &&
e2b23972
MG
543 strcmp(name, "contents") &&
544 strcmp(name, "contents:subject") &&
545 strcmp(name, "contents:body") &&
546 strcmp(name, "contents:signature"))
9f613ddd
JH
547 continue;
548 if (!subpos)
7ec0f31e
JK
549 find_subpos(buf, sz,
550 &subpos, &sublen,
e2b23972
MG
551 &bodypos, &bodylen, &nonsiglen,
552 &sigpos, &siglen);
9f613ddd
JH
553
554 if (!strcmp(name, "subject"))
7f6e275b 555 v->s = copy_subject(subpos, sublen);
e2b23972
MG
556 else if (!strcmp(name, "contents:subject"))
557 v->s = copy_subject(subpos, sublen);
9f613ddd 558 else if (!strcmp(name, "body"))
7ec0f31e 559 v->s = xmemdupz(bodypos, bodylen);
e2b23972
MG
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);
9f613ddd 564 else if (!strcmp(name, "contents"))
f8290630 565 v->s = xstrdup(subpos);
9f613ddd
JH
566 }
567}
568
40dae309
JH
569/*
570 * We want to have empty print-string for field requests
9f613ddd
JH
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:
2543d9b6 606 /* grab_tree_values(val, deref, obj, buf, sz); */
9f613ddd
JH
607 break;
608 case OBJ_BLOB:
2543d9b6 609 /* grab_blob_values(val, deref, obj, buf, sz); */
9f613ddd
JH
610 break;
611 default:
612 die("Eh? Object of type %d?", obj->type);
613 }
614}
615
88fb7f27
JH
616static inline char *copy_advance(char *dst, const char *src)
617{
618 while (*src)
619 *dst++ = *src++;
620 return dst;
621}
622
9f613ddd
JH
623/*
624 * Parse the object referred by ref, and grab needed value.
625 */
626static void populate_value(struct refinfo *ref)
627{
628 void *buf;
629 struct object *obj;
630 int eaten, i;
631 unsigned long size;
632 const unsigned char *tagged;
633
693eb02a 634 ref->value = xcalloc(used_atom_cnt, sizeof(struct atom_value));
9f613ddd 635
5cdd628c
JH
636 if (need_symref && (ref->flag & REF_ISSYMREF) && !ref->symref) {
637 unsigned char unused1[20];
7695d118
RS
638 ref->symref = resolve_refdup(ref->refname, RESOLVE_REF_READING,
639 unused1, NULL);
96ec7b1e 640 if (!ref->symref)
5cdd628c
JH
641 ref->symref = "";
642 }
643
9f613ddd
JH
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];
7d66f21a 648 int deref = 0;
8db9a4b8
JK
649 const char *refname;
650 const char *formatp;
b28061ce 651 struct branch *branch = NULL;
8db9a4b8 652
7d66f21a
BW
653 if (*name == '*') {
654 deref = 1;
655 name++;
656 }
7d66f21a 657
59556548 658 if (starts_with(name, "refname"))
8db9a4b8 659 refname = ref->refname;
59556548 660 else if (starts_with(name, "symref"))
5cdd628c 661 refname = ref->symref ? ref->symref : "";
59556548 662 else if (starts_with(name, "upstream")) {
8cae19d9 663 /* only local branches may have an upstream */
59556548 664 if (!starts_with(ref->refname, "refs/heads/"))
8cae19d9
JK
665 continue;
666 branch = branch_get(ref->refname + 11);
667
668 if (!branch || !branch->merge || !branch->merge[0] ||
669 !branch->merge[0]->dst)
670 continue;
671 refname = branch->merge[0]->dst;
ad704485 672 } else if (starts_with(name, "color:")) {
fddb74c9
RR
673 char color[COLOR_MAXLEN] = "";
674
f6c5a296
JK
675 if (color_parse(name + 6, color) < 0)
676 die(_("unable to parse format"));
fddb74c9
RR
677 v->s = xstrdup(color);
678 continue;
679 } else if (!strcmp(name, "flag")) {
88fb7f27
JH
680 char buf[256], *cp = buf;
681 if (ref->flag & REF_ISSYMREF)
682 cp = copy_advance(cp, ",symref");
683 if (ref->flag & REF_ISPACKED)
684 cp = copy_advance(cp, ",packed");
685 if (cp == buf)
686 v->s = "";
687 else {
688 *cp = '\0';
689 v->s = xstrdup(buf + 1);
690 }
691 continue;
cb6bd572 692 } else if (!deref && grab_objectname(name, ref->objectname, v)) {
b74cf648 693 continue;
7a48b832
RR
694 } else if (!strcmp(name, "HEAD")) {
695 const char *head;
696 unsigned char sha1[20];
b28061ce 697
7695d118
RS
698 head = resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
699 sha1, NULL);
7a48b832
RR
700 if (!strcmp(ref->refname, head))
701 v->s = "*";
702 else
703 v->s = " ";
704 continue;
705 } else
8db9a4b8
JK
706 continue;
707
708 formatp = strchr(name, ':');
8db9a4b8 709 if (formatp) {
b28061ce
RR
710 int num_ours, num_theirs;
711
8db9a4b8
JK
712 formatp++;
713 if (!strcmp(formatp, "short"))
2bb98169
BW
714 refname = shorten_unambiguous_ref(refname,
715 warn_ambiguous_refs);
b28061ce 716 else if (!strcmp(formatp, "track") &&
ad704485 717 starts_with(name, "upstream")) {
b28061ce
RR
718 char buf[40];
719
720 stat_tracking_info(branch, &num_ours, &num_theirs);
721 if (!num_ours && !num_theirs)
722 v->s = "";
723 else if (!num_ours) {
724 sprintf(buf, "[behind %d]", num_theirs);
725 v->s = xstrdup(buf);
726 } else if (!num_theirs) {
727 sprintf(buf, "[ahead %d]", num_ours);
728 v->s = xstrdup(buf);
729 } else {
730 sprintf(buf, "[ahead %d, behind %d]",
731 num_ours, num_theirs);
732 v->s = xstrdup(buf);
733 }
734 continue;
735 } else if (!strcmp(formatp, "trackshort") &&
ad704485 736 starts_with(name, "upstream")) {
b28061ce
RR
737 assert(branch);
738 stat_tracking_info(branch, &num_ours, &num_theirs);
739 if (!num_ours && !num_theirs)
740 v->s = "=";
741 else if (!num_ours)
742 v->s = "<";
743 else if (!num_theirs)
744 v->s = ">";
745 else
746 v->s = "<>";
747 continue;
748 } else
8db9a4b8
JK
749 die("unknown %.*s format %s",
750 (int)(formatp - name), name, formatp);
751 }
752
753 if (!deref)
754 v->s = refname;
755 else {
756 int len = strlen(refname);
757 char *s = xmalloc(len + 4);
758 sprintf(s, "%s^{}", refname);
759 v->s = s;
9f613ddd
JH
760 }
761 }
762
b7dd2d20
AK
763 for (i = 0; i < used_atom_cnt; i++) {
764 struct atom_value *v = &ref->value[i];
765 if (v->s == NULL)
766 goto need_obj;
767 }
768 return;
769
770 need_obj:
771 buf = get_obj(ref->objectname, &obj, &size, &eaten);
772 if (!buf)
773 die("missing object %s for %s",
774 sha1_to_hex(ref->objectname), ref->refname);
775 if (!obj)
776 die("parse_object_buffer failed on %s for %s",
777 sha1_to_hex(ref->objectname), ref->refname);
778
9f613ddd
JH
779 grab_values(ref->value, 0, obj, buf, size);
780 if (!eaten)
781 free(buf);
782
40dae309
JH
783 /*
784 * If there is no atom that wants to know about tagged
9f613ddd
JH
785 * object, we are done.
786 */
787 if (!need_tagged || (obj->type != OBJ_TAG))
788 return;
789
40dae309
JH
790 /*
791 * If it is a tag object, see if we use a value that derefs
9f613ddd
JH
792 * the object, and if we do grab the object it refers to.
793 */
794 tagged = ((struct tag *)obj)->tagged->sha1;
795
40dae309
JH
796 /*
797 * NEEDSWORK: This derefs tag only once, which
9f613ddd
JH
798 * is good to deal with chains of trust, but
799 * is not consistent with what deref_tag() does
800 * which peels the onion to the core.
801 */
802 buf = get_obj(tagged, &obj, &size, &eaten);
803 if (!buf)
804 die("missing object %s for %s",
805 sha1_to_hex(tagged), ref->refname);
806 if (!obj)
807 die("parse_object_buffer failed on %s for %s",
808 sha1_to_hex(tagged), ref->refname);
809 grab_values(ref->value, 1, obj, buf, size);
810 if (!eaten)
811 free(buf);
812}
813
814/*
815 * Given a ref, return the value for the atom. This lazily gets value
816 * out of the object by calling populate value.
817 */
818static void get_value(struct refinfo *ref, int atom, struct atom_value **v)
819{
820 if (!ref->value) {
821 populate_value(ref);
822 fill_missing_values(ref->value);
823 }
824 *v = &ref->value[atom];
825}
826
340adb8b
JH
827struct grab_ref_cbdata {
828 struct refinfo **grab_array;
829 const char **grab_pattern;
830 int grab_cnt;
831};
9f613ddd
JH
832
833/*
40dae309
JH
834 * A call-back given to for_each_ref(). Filter refs and keep them for
835 * later object processing.
9f613ddd 836 */
340adb8b 837static int grab_single_ref(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
9f613ddd 838{
340adb8b 839 struct grab_ref_cbdata *cb = cb_data;
9f613ddd
JH
840 struct refinfo *ref;
841 int cnt;
842
971c41c7
RS
843 if (flag & REF_BAD_NAME) {
844 warning("ignoring ref with broken name %s", refname);
845 return 0;
846 }
847
340adb8b 848 if (*cb->grab_pattern) {
9f613ddd
JH
849 const char **pattern;
850 int namelen = strlen(refname);
340adb8b 851 for (pattern = cb->grab_pattern; *pattern; pattern++) {
9f613ddd
JH
852 const char *p = *pattern;
853 int plen = strlen(p);
854
855 if ((plen <= namelen) &&
856 !strncmp(refname, p, plen) &&
857 (refname[plen] == '\0' ||
114ef908
BS
858 refname[plen] == '/' ||
859 p[plen-1] == '/'))
9f613ddd 860 break;
eb07894f 861 if (!wildmatch(p, refname, WM_PATHNAME, NULL))
9f613ddd
JH
862 break;
863 }
864 if (!*pattern)
865 return 0;
866 }
867
40dae309
JH
868 /*
869 * We do not open the object yet; sort may only need refname
9f613ddd
JH
870 * to do its job and the resulting list may yet to be pruned
871 * by maxcount logic.
872 */
873 ref = xcalloc(1, sizeof(*ref));
874 ref->refname = xstrdup(refname);
875 hashcpy(ref->objectname, sha1);
5cdd628c 876 ref->flag = flag;
9f613ddd 877
340adb8b 878 cnt = cb->grab_cnt;
2756ca43 879 REALLOC_ARRAY(cb->grab_array, cnt + 1);
340adb8b
JH
880 cb->grab_array[cnt++] = ref;
881 cb->grab_cnt = cnt;
9f613ddd
JH
882 return 0;
883}
884
9f613ddd
JH
885static int cmp_ref_sort(struct ref_sort *s, struct refinfo *a, struct refinfo *b)
886{
887 struct atom_value *va, *vb;
888 int cmp;
889 cmp_type cmp_type = used_atom_type[s->atom];
890
891 get_value(a, s->atom, &va);
892 get_value(b, s->atom, &vb);
893 switch (cmp_type) {
894 case FIELD_STR:
895 cmp = strcmp(va->s, vb->s);
896 break;
897 default:
898 if (va->ul < vb->ul)
899 cmp = -1;
900 else if (va->ul == vb->ul)
901 cmp = 0;
902 else
903 cmp = 1;
904 break;
905 }
906 return (s->reverse) ? -cmp : cmp;
907}
908
909static struct ref_sort *ref_sort;
910static int compare_refs(const void *a_, const void *b_)
911{
912 struct refinfo *a = *((struct refinfo **)a_);
913 struct refinfo *b = *((struct refinfo **)b_);
914 struct ref_sort *s;
915
916 for (s = ref_sort; s; s = s->next) {
917 int cmp = cmp_ref_sort(s, a, b);
918 if (cmp)
919 return cmp;
920 }
921 return 0;
922}
923
924static void sort_refs(struct ref_sort *sort, struct refinfo **refs, int num_refs)
925{
926 ref_sort = sort;
927 qsort(refs, num_refs, sizeof(struct refinfo *), compare_refs);
928}
929
db64eb65 930static void print_value(struct atom_value *v, int quote_style)
9f613ddd 931{
10d0167f 932 struct strbuf sb = STRBUF_INIT;
9f613ddd
JH
933 switch (quote_style) {
934 case QUOTE_NONE:
935 fputs(v->s, stdout);
936 break;
937 case QUOTE_SHELL:
10d0167f 938 sq_quote_buf(&sb, v->s);
9f613ddd
JH
939 break;
940 case QUOTE_PERL:
10d0167f 941 perl_quote_buf(&sb, v->s);
9f613ddd
JH
942 break;
943 case QUOTE_PYTHON:
10d0167f 944 python_quote_buf(&sb, v->s);
9f613ddd 945 break;
5558e55c 946 case QUOTE_TCL:
10d0167f 947 tcl_quote_buf(&sb, v->s);
5558e55c 948 break;
9f613ddd 949 }
10d0167f
NTND
950 if (quote_style != QUOTE_NONE) {
951 fputs(sb.buf, stdout);
952 strbuf_release(&sb);
953 }
9f613ddd
JH
954}
955
956static int hex1(char ch)
957{
958 if ('0' <= ch && ch <= '9')
959 return ch - '0';
960 else if ('a' <= ch && ch <= 'f')
961 return ch - 'a' + 10;
962 else if ('A' <= ch && ch <= 'F')
963 return ch - 'A' + 10;
964 return -1;
965}
966static int hex2(const char *cp)
967{
968 if (cp[0] && cp[1])
969 return (hex1(cp[0]) << 4) | hex1(cp[1]);
970 else
971 return -1;
972}
973
974static void emit(const char *cp, const char *ep)
975{
976 while (*cp && (!ep || cp < ep)) {
977 if (*cp == '%') {
978 if (cp[1] == '%')
979 cp++;
980 else {
981 int ch = hex2(cp + 1);
982 if (0 <= ch) {
983 putchar(ch);
984 cp += 3;
985 continue;
986 }
987 }
988 }
989 putchar(*cp);
990 cp++;
991 }
992}
993
994static void show_ref(struct refinfo *info, const char *format, int quote_style)
995{
996 const char *cp, *sp, *ep;
997
998 for (cp = format; *cp && (sp = find_next(cp)); cp = ep + 1) {
db64eb65
RR
999 struct atom_value *atomv;
1000
9f613ddd
JH
1001 ep = strchr(sp, ')');
1002 if (cp < sp)
1003 emit(cp, sp);
db64eb65
RR
1004 get_value(info, parse_atom(sp + 2, ep), &atomv);
1005 print_value(atomv, quote_style);
9f613ddd
JH
1006 }
1007 if (*cp) {
1008 sp = cp + strlen(cp);
1009 emit(cp, sp);
1010 }
db64eb65
RR
1011 if (need_color_reset_at_eol) {
1012 struct atom_value resetv;
1013 char color[COLOR_MAXLEN] = "";
1014
f6c5a296
JK
1015 if (color_parse("reset", color) < 0)
1016 die("BUG: couldn't parse 'reset' as a color");
db64eb65
RR
1017 resetv.s = color;
1018 print_value(&resetv, quote_style);
1019 }
9f613ddd
JH
1020 putchar('\n');
1021}
1022
1023static struct ref_sort *default_sort(void)
1024{
1025 static const char cstr_name[] = "refname";
1026
1027 struct ref_sort *sort = xcalloc(1, sizeof(*sort));
1028
1029 sort->next = NULL;
1030 sort->atom = parse_atom(cstr_name, cstr_name + strlen(cstr_name));
1031 return sort;
1032}
1033
186458b1 1034static int opt_parse_sort(const struct option *opt, const char *arg, int unset)
c3428da8
PH
1035{
1036 struct ref_sort **sort_tail = opt->value;
1037 struct ref_sort *s;
1038 int len;
1039
1040 if (!arg) /* should --no-sort void the list ? */
1041 return -1;
1042
3b51222c
KK
1043 s = xcalloc(1, sizeof(*s));
1044 s->next = *sort_tail;
1045 *sort_tail = s;
c3428da8
PH
1046
1047 if (*arg == '-') {
1048 s->reverse = 1;
1049 arg++;
1050 }
1051 len = strlen(arg);
1052 s->atom = parse_atom(arg, arg+len);
1053 return 0;
1054}
1055
1056static char const * const for_each_ref_usage[] = {
18913521 1057 N_("git for-each-ref [options] [<pattern>]"),
c3428da8
PH
1058 NULL
1059};
1060
1061int cmd_for_each_ref(int argc, const char **argv, const char *prefix)
9f613ddd
JH
1062{
1063 int i, num_refs;
c3428da8 1064 const char *format = "%(objectname) %(objecttype)\t%(refname)";
9f613ddd 1065 struct ref_sort *sort = NULL, **sort_tail = &sort;
9fac800c 1066 int maxcount = 0, quote_style = 0;
9f613ddd 1067 struct refinfo **refs;
340adb8b 1068 struct grab_ref_cbdata cbdata;
9f613ddd 1069
c3428da8 1070 struct option opts[] = {
9fac800c 1071 OPT_BIT('s', "shell", &quote_style,
18913521 1072 N_("quote placeholders suitably for shells"), QUOTE_SHELL),
9fac800c 1073 OPT_BIT('p', "perl", &quote_style,
18913521 1074 N_("quote placeholders suitably for perl"), QUOTE_PERL),
9fac800c 1075 OPT_BIT(0 , "python", &quote_style,
18913521 1076 N_("quote placeholders suitably for python"), QUOTE_PYTHON),
9fac800c 1077 OPT_BIT(0 , "tcl", &quote_style,
b799a696 1078 N_("quote placeholders suitably for Tcl"), QUOTE_TCL),
c3428da8
PH
1079
1080 OPT_GROUP(""),
18913521
NTND
1081 OPT_INTEGER( 0 , "count", &maxcount, N_("show only <n> matched refs")),
1082 OPT_STRING( 0 , "format", &format, N_("format"), N_("format to use for the output")),
1083 OPT_CALLBACK(0 , "sort", sort_tail, N_("key"),
1084 N_("field name to sort on"), &opt_parse_sort),
c3428da8
PH
1085 OPT_END(),
1086 };
1087
37782920 1088 parse_options(argc, argv, prefix, opts, for_each_ref_usage, 0);
c3428da8
PH
1089 if (maxcount < 0) {
1090 error("invalid --count argument: `%d'", maxcount);
1091 usage_with_options(for_each_ref_usage, opts);
9f613ddd 1092 }
9fac800c 1093 if (HAS_MULTI_BITS(quote_style)) {
c9ecf4f1 1094 error("more than one quoting style?");
c3428da8
PH
1095 usage_with_options(for_each_ref_usage, opts);
1096 }
1097 if (verify_format(format))
1098 usage_with_options(for_each_ref_usage, opts);
9f613ddd
JH
1099
1100 if (!sort)
1101 sort = default_sort();
9f613ddd 1102
2bb98169
BW
1103 /* for warn_ambiguous_refs */
1104 git_config(git_default_config, NULL);
1105
340adb8b 1106 memset(&cbdata, 0, sizeof(cbdata));
c3428da8 1107 cbdata.grab_pattern = argv;
b7dd2d20 1108 for_each_rawref(grab_single_ref, &cbdata);
340adb8b
JH
1109 refs = cbdata.grab_array;
1110 num_refs = cbdata.grab_cnt;
9f613ddd 1111
9f613ddd
JH
1112 sort_refs(sort, refs, num_refs);
1113
1114 if (!maxcount || num_refs < maxcount)
1115 maxcount = num_refs;
1116 for (i = 0; i < maxcount; i++)
1117 show_ref(refs[i], format, quote_style);
1118 return 0;
1119}