1#include "cache.h"
2#include "config.h"
3#include "lockfile.h"
4#include "commit.h"
5#include "tag.h"
6#include "blob.h"
7#include "refs.h"
8#include "builtin.h"
9#include "exec-cmd.h"
10#include "parse-options.h"
11#include "revision.h"
12#include "diff.h"
13#include "hashmap.h"
14#include "argv-array.h"
15#include "run-command.h"
16#include "revision.h"
17#include "list-objects.h"
18#include "commit-slab.h"
19
20#define MAX_TAGS (FLAG_BITS - 1)
21
22define_commit_slab(commit_names, struct commit_name *);
23
24static const char * const describe_usage[] = {
25 N_("git describe [<options>] [<commit-ish>...]"),
26 N_("git describe [<options>] --dirty"),
27 NULL
28};
29
30static int debug; /* Display lots of verbose info */
31static int all; /* Any valid ref can be used */
32static int tags; /* Allow lightweight tags */
33static int longformat;
34static int first_parent;
35static int abbrev = -1; /* unspecified */
36static int max_candidates = 10;
37static struct hashmap names;
38static int have_util;
39static struct string_list patterns = STRING_LIST_INIT_NODUP;
40static struct string_list exclude_patterns = STRING_LIST_INIT_NODUP;
41static int always;
42static const char *suffix, *dirty, *broken;
43static struct commit_names commit_names;
44
45/* diff-index command arguments to check if working tree is dirty. */
46static const char *diff_index_args[] = {
47 "diff-index", "--quiet", "HEAD", "--", NULL
48};
49
50struct commit_name {
51 struct hashmap_entry entry;
52 struct object_id peeled;
53 struct tag *tag;
54 unsigned prio:2; /* annotated tag = 2, tag = 1, head = 0 */
55 unsigned name_checked:1;
56 struct object_id oid;
57 char *path;
58};
59
60static const char *prio_names[] = {
61 N_("head"), N_("lightweight"), N_("annotated"),
62};
63
64static int commit_name_cmp(const void *unused_cmp_data,
65 const void *entry,
66 const void *entry_or_key,
67 const void *peeled)
68{
69 const struct commit_name *cn1 = entry;
70 const struct commit_name *cn2 = entry_or_key;
71
72 return oidcmp(&cn1->peeled, peeled ? peeled : &cn2->peeled);
73}
74
75static inline struct commit_name *find_commit_name(const struct object_id *peeled)
76{
77 return hashmap_get_from_hash(&names, sha1hash(peeled->hash), peeled->hash);
78}
79
80static int replace_name(struct commit_name *e,
81 int prio,
82 const struct object_id *oid,
83 struct tag **tag)
84{
85 if (!e || e->prio < prio)
86 return 1;
87
88 if (e->prio == 2 && prio == 2) {
89 /* Multiple annotated tags point to the same commit.
90 * Select one to keep based upon their tagger date.
91 */
92 struct tag *t;
93
94 if (!e->tag) {
95 t = lookup_tag(&e->oid);
96 if (!t || parse_tag(t))
97 return 1;
98 e->tag = t;
99 }
100
101 t = lookup_tag(oid);
102 if (!t || parse_tag(t))
103 return 0;
104 *tag = t;
105
106 if (e->tag->date < t->date)
107 return 1;
108 }
109
110 return 0;
111}
112
113static void add_to_known_names(const char *path,
114 const struct object_id *peeled,
115 int prio,
116 const struct object_id *oid)
117{
118 struct commit_name *e = find_commit_name(peeled);
119 struct tag *tag = NULL;
120 if (replace_name(e, prio, oid, &tag)) {
121 if (!e) {
122 e = xmalloc(sizeof(struct commit_name));
123 oidcpy(&e->peeled, peeled);
124 hashmap_entry_init(e, sha1hash(peeled->hash));
125 hashmap_add(&names, e);
126 e->path = NULL;
127 }
128 e->tag = tag;
129 e->prio = prio;
130 e->name_checked = 0;
131 oidcpy(&e->oid, oid);
132 free(e->path);
133 e->path = xstrdup(path);
134 }
135}
136
137static int get_name(const char *path, const struct object_id *oid, int flag, void *cb_data)
138{
139 int is_tag = 0;
140 struct object_id peeled;
141 int is_annotated, prio;
142 const char *path_to_match = NULL;
143
144 if (skip_prefix(path, "refs/tags/", &path_to_match)) {
145 is_tag = 1;
146 } else if (all) {
147 if ((exclude_patterns.nr || patterns.nr) &&
148 !skip_prefix(path, "refs/heads/", &path_to_match) &&
149 !skip_prefix(path, "refs/remotes/", &path_to_match)) {
150 /* Only accept reference of known type if there are match/exclude patterns */
151 return 0;
152 }
153 } else {
154 /* Reject anything outside refs/tags/ unless --all */
155 return 0;
156 }
157
158 /*
159 * If we're given exclude patterns, first exclude any tag which match
160 * any of the exclude pattern.
161 */
162 if (exclude_patterns.nr) {
163 struct string_list_item *item;
164
165 for_each_string_list_item(item, &exclude_patterns) {
166 if (!wildmatch(item->string, path_to_match, 0))
167 return 0;
168 }
169 }
170
171 /*
172 * If we're given patterns, accept only tags which match at least one
173 * pattern.
174 */
175 if (patterns.nr) {
176 int found = 0;
177 struct string_list_item *item;
178
179 for_each_string_list_item(item, &patterns) {
180 if (!wildmatch(item->string, path_to_match, 0)) {
181 found = 1;
182 break;
183 }
184 }
185
186 if (!found)
187 return 0;
188 }
189
190 /* Is it annotated? */
191 if (!peel_ref(path, &peeled)) {
192 is_annotated = !!oidcmp(oid, &peeled);
193 } else {
194 oidcpy(&peeled, oid);
195 is_annotated = 0;
196 }
197
198 /*
199 * By default, we only use annotated tags, but with --tags
200 * we fall back to lightweight ones (even without --tags,
201 * we still remember lightweight ones, only to give hints
202 * in an error message). --all allows any refs to be used.
203 */
204 if (is_annotated)
205 prio = 2;
206 else if (is_tag)
207 prio = 1;
208 else
209 prio = 0;
210
211 add_to_known_names(all ? path + 5 : path + 10, &peeled, prio, oid);
212 return 0;
213}
214
215struct possible_tag {
216 struct commit_name *name;
217 int depth;
218 int found_order;
219 unsigned flag_within;
220};
221
222static int compare_pt(const void *a_, const void *b_)
223{
224 struct possible_tag *a = (struct possible_tag *)a_;
225 struct possible_tag *b = (struct possible_tag *)b_;
226 if (a->depth != b->depth)
227 return a->depth - b->depth;
228 if (a->found_order != b->found_order)
229 return a->found_order - b->found_order;
230 return 0;
231}
232
233static unsigned long finish_depth_computation(
234 struct commit_list **list,
235 struct possible_tag *best)
236{
237 unsigned long seen_commits = 0;
238 while (*list) {
239 struct commit *c = pop_commit(list);
240 struct commit_list *parents = c->parents;
241 seen_commits++;
242 if (c->object.flags & best->flag_within) {
243 struct commit_list *a = *list;
244 while (a) {
245 struct commit *i = a->item;
246 if (!(i->object.flags & best->flag_within))
247 break;
248 a = a->next;
249 }
250 if (!a)
251 break;
252 } else
253 best->depth++;
254 while (parents) {
255 struct commit *p = parents->item;
256 parse_commit(p);
257 if (!(p->object.flags & SEEN))
258 commit_list_insert_by_date(p, list);
259 p->object.flags |= c->object.flags;
260 parents = parents->next;
261 }
262 }
263 return seen_commits;
264}
265
266static void append_name(struct commit_name *n, struct strbuf *dst)
267{
268 if (n->prio == 2 && !n->tag) {
269 n->tag = lookup_tag(&n->oid);
270 if (!n->tag || parse_tag(n->tag))
271 die(_("annotated tag %s not available"), n->path);
272 }
273 if (n->tag && !n->name_checked) {
274 if (!n->tag->tag)
275 die(_("annotated tag %s has no embedded name"), n->path);
276 if (strcmp(n->tag->tag, all ? n->path + 5 : n->path))
277 warning(_("tag '%s' is really '%s' here"), n->tag->tag, n->path);
278 n->name_checked = 1;
279 }
280
281 if (n->tag) {
282 if (all)
283 strbuf_addstr(dst, "tags/");
284 strbuf_addstr(dst, n->tag->tag);
285 } else {
286 strbuf_addstr(dst, n->path);
287 }
288}
289
290static void append_suffix(int depth, const struct object_id *oid, struct strbuf *dst)
291{
292 strbuf_addf(dst, "-%d-g%s", depth, find_unique_abbrev(oid, abbrev));
293}
294
295static void describe_commit(struct object_id *oid, struct strbuf *dst)
296{
297 struct commit *cmit, *gave_up_on = NULL;
298 struct commit_list *list;
299 struct commit_name *n;
300 struct possible_tag all_matches[MAX_TAGS];
301 unsigned int match_cnt = 0, annotated_cnt = 0, cur_match;
302 unsigned long seen_commits = 0;
303 unsigned int unannotated_cnt = 0;
304
305 cmit = lookup_commit_reference(oid);
306
307 n = find_commit_name(&cmit->object.oid);
308 if (n && (tags || all || n->prio == 2)) {
309 /*
310 * Exact match to an existing ref.
311 */
312 append_name(n, dst);
313 if (longformat)
314 append_suffix(0, n->tag ? &n->tag->tagged->oid : oid, dst);
315 if (suffix)
316 strbuf_addstr(dst, suffix);
317 return;
318 }
319
320 if (!max_candidates)
321 die(_("no tag exactly matches '%s'"), oid_to_hex(&cmit->object.oid));
322 if (debug)
323 fprintf(stderr, _("No exact match on refs or tags, searching to describe\n"));
324
325 if (!have_util) {
326 struct hashmap_iter iter;
327 struct commit *c;
328 struct commit_name *n;
329
330 init_commit_names(&commit_names);
331 n = hashmap_iter_first(&names, &iter);
332 for (; n; n = hashmap_iter_next(&iter)) {
333 c = lookup_commit_reference_gently(&n->peeled, 1);
334 if (c)
335 *commit_names_at(&commit_names, c) = n;
336 }
337 have_util = 1;
338 }
339
340 list = NULL;
341 cmit->object.flags = SEEN;
342 commit_list_insert(cmit, &list);
343 while (list) {
344 struct commit *c = pop_commit(&list);
345 struct commit_list *parents = c->parents;
346 struct commit_name **slot;
347
348 seen_commits++;
349 slot = commit_names_peek(&commit_names, c);
350 n = slot ? *slot : NULL;
351 if (n) {
352 if (!tags && !all && n->prio < 2) {
353 unannotated_cnt++;
354 } else if (match_cnt < max_candidates) {
355 struct possible_tag *t = &all_matches[match_cnt++];
356 t->name = n;
357 t->depth = seen_commits - 1;
358 t->flag_within = 1u << match_cnt;
359 t->found_order = match_cnt;
360 c->object.flags |= t->flag_within;
361 if (n->prio == 2)
362 annotated_cnt++;
363 }
364 else {
365 gave_up_on = c;
366 break;
367 }
368 }
369 for (cur_match = 0; cur_match < match_cnt; cur_match++) {
370 struct possible_tag *t = &all_matches[cur_match];
371 if (!(c->object.flags & t->flag_within))
372 t->depth++;
373 }
374 if (annotated_cnt && !list) {
375 if (debug)
376 fprintf(stderr, _("finished search at %s\n"),
377 oid_to_hex(&c->object.oid));
378 break;
379 }
380 while (parents) {
381 struct commit *p = parents->item;
382 parse_commit(p);
383 if (!(p->object.flags & SEEN))
384 commit_list_insert_by_date(p, &list);
385 p->object.flags |= c->object.flags;
386 parents = parents->next;
387
388 if (first_parent)
389 break;
390 }
391 }
392
393 if (!match_cnt) {
394 struct object_id *cmit_oid = &cmit->object.oid;
395 if (always) {
396 strbuf_add_unique_abbrev(dst, cmit_oid, abbrev);
397 if (suffix)
398 strbuf_addstr(dst, suffix);
399 return;
400 }
401 if (unannotated_cnt)
402 die(_("No annotated tags can describe '%s'.\n"
403 "However, there were unannotated tags: try --tags."),
404 oid_to_hex(cmit_oid));
405 else
406 die(_("No tags can describe '%s'.\n"
407 "Try --always, or create some tags."),
408 oid_to_hex(cmit_oid));
409 }
410
411 QSORT(all_matches, match_cnt, compare_pt);
412
413 if (gave_up_on) {
414 commit_list_insert_by_date(gave_up_on, &list);
415 seen_commits--;
416 }
417 seen_commits += finish_depth_computation(&list, &all_matches[0]);
418 free_commit_list(list);
419
420 if (debug) {
421 static int label_width = -1;
422 if (label_width < 0) {
423 int i, w;
424 for (i = 0; i < ARRAY_SIZE(prio_names); i++) {
425 w = strlen(_(prio_names[i]));
426 if (label_width < w)
427 label_width = w;
428 }
429 }
430 for (cur_match = 0; cur_match < match_cnt; cur_match++) {
431 struct possible_tag *t = &all_matches[cur_match];
432 fprintf(stderr, " %-*s %8d %s\n",
433 label_width, _(prio_names[t->name->prio]),
434 t->depth, t->name->path);
435 }
436 fprintf(stderr, _("traversed %lu commits\n"), seen_commits);
437 if (gave_up_on) {
438 fprintf(stderr,
439 _("more than %i tags found; listed %i most recent\n"
440 "gave up search at %s\n"),
441 max_candidates, max_candidates,
442 oid_to_hex(&gave_up_on->object.oid));
443 }
444 }
445
446 append_name(all_matches[0].name, dst);
447 if (abbrev)
448 append_suffix(all_matches[0].depth, &cmit->object.oid, dst);
449 if (suffix)
450 strbuf_addstr(dst, suffix);
451}
452
453struct process_commit_data {
454 struct object_id current_commit;
455 struct object_id looking_for;
456 struct strbuf *dst;
457 struct rev_info *revs;
458};
459
460static void process_commit(struct commit *commit, void *data)
461{
462 struct process_commit_data *pcd = data;
463 pcd->current_commit = commit->object.oid;
464}
465
466static void process_object(struct object *obj, const char *path, void *data)
467{
468 struct process_commit_data *pcd = data;
469
470 if (!oidcmp(&pcd->looking_for, &obj->oid) && !pcd->dst->len) {
471 reset_revision_walk();
472 describe_commit(&pcd->current_commit, pcd->dst);
473 strbuf_addf(pcd->dst, ":%s", path);
474 free_commit_list(pcd->revs->commits);
475 pcd->revs->commits = NULL;
476 }
477}
478
479static void describe_blob(struct object_id oid, struct strbuf *dst)
480{
481 struct rev_info revs;
482 struct argv_array args = ARGV_ARRAY_INIT;
483 struct process_commit_data pcd = { null_oid, oid, dst, &revs};
484
485 argv_array_pushl(&args, "internal: The first arg is not parsed",
486 "--objects", "--in-commit-order", "--reverse", "HEAD",
487 NULL);
488
489 init_revisions(&revs, NULL);
490 if (setup_revisions(args.argc, args.argv, &revs, NULL) > 1)
491 BUG("setup_revisions could not handle all args?");
492
493 if (prepare_revision_walk(&revs))
494 die("revision walk setup failed");
495
496 traverse_commit_list(&revs, process_commit, process_object, &pcd);
497 reset_revision_walk();
498}
499
500static void describe(const char *arg, int last_one)
501{
502 struct object_id oid;
503 struct commit *cmit;
504 struct strbuf sb = STRBUF_INIT;
505
506 if (debug)
507 fprintf(stderr, _("describe %s\n"), arg);
508
509 if (get_oid(arg, &oid))
510 die(_("Not a valid object name %s"), arg);
511 cmit = lookup_commit_reference_gently(&oid, 1);
512
513 if (cmit)
514 describe_commit(&oid, &sb);
515 else if (oid_object_info(the_repository, &oid, NULL) == OBJ_BLOB)
516 describe_blob(oid, &sb);
517 else
518 die(_("%s is neither a commit nor blob"), arg);
519
520 puts(sb.buf);
521
522 if (!last_one)
523 clear_commit_marks(cmit, -1);
524
525 strbuf_release(&sb);
526}
527
528int cmd_describe(int argc, const char **argv, const char *prefix)
529{
530 int contains = 0;
531 struct option options[] = {
532 OPT_BOOL(0, "contains", &contains, N_("find the tag that comes after the commit")),
533 OPT_BOOL(0, "debug", &debug, N_("debug search strategy on stderr")),
534 OPT_BOOL(0, "all", &all, N_("use any ref")),
535 OPT_BOOL(0, "tags", &tags, N_("use any tag, even unannotated")),
536 OPT_BOOL(0, "long", &longformat, N_("always use long format")),
537 OPT_BOOL(0, "first-parent", &first_parent, N_("only follow first parent")),
538 OPT__ABBREV(&abbrev),
539 OPT_SET_INT(0, "exact-match", &max_candidates,
540 N_("only output exact matches"), 0),
541 OPT_INTEGER(0, "candidates", &max_candidates,
542 N_("consider <n> most recent tags (default: 10)")),
543 OPT_STRING_LIST(0, "match", &patterns, N_("pattern"),
544 N_("only consider tags matching <pattern>")),
545 OPT_STRING_LIST(0, "exclude", &exclude_patterns, N_("pattern"),
546 N_("do not consider tags matching <pattern>")),
547 OPT_BOOL(0, "always", &always,
548 N_("show abbreviated commit object as fallback")),
549 {OPTION_STRING, 0, "dirty", &dirty, N_("mark"),
550 N_("append <mark> on dirty working tree (default: \"-dirty\")"),
551 PARSE_OPT_OPTARG, NULL, (intptr_t) "-dirty"},
552 {OPTION_STRING, 0, "broken", &broken, N_("mark"),
553 N_("append <mark> on broken working tree (default: \"-broken\")"),
554 PARSE_OPT_OPTARG, NULL, (intptr_t) "-broken"},
555 OPT_END(),
556 };
557
558 git_config(git_default_config, NULL);
559 argc = parse_options(argc, argv, prefix, options, describe_usage, 0);
560 if (abbrev < 0)
561 abbrev = DEFAULT_ABBREV;
562
563 if (max_candidates < 0)
564 max_candidates = 0;
565 else if (max_candidates > MAX_TAGS)
566 max_candidates = MAX_TAGS;
567
568 save_commit_buffer = 0;
569
570 if (longformat && abbrev == 0)
571 die(_("--long is incompatible with --abbrev=0"));
572
573 if (contains) {
574 struct string_list_item *item;
575 struct argv_array args;
576
577 argv_array_init(&args);
578 argv_array_pushl(&args, "name-rev",
579 "--peel-tag", "--name-only", "--no-undefined",
580 NULL);
581 if (always)
582 argv_array_push(&args, "--always");
583 if (!all) {
584 argv_array_push(&args, "--tags");
585 for_each_string_list_item(item, &patterns)
586 argv_array_pushf(&args, "--refs=refs/tags/%s", item->string);
587 for_each_string_list_item(item, &exclude_patterns)
588 argv_array_pushf(&args, "--exclude=refs/tags/%s", item->string);
589 }
590 if (argc)
591 argv_array_pushv(&args, argv);
592 else
593 argv_array_push(&args, "HEAD");
594 return cmd_name_rev(args.argc, args.argv, prefix);
595 }
596
597 hashmap_init(&names, commit_name_cmp, NULL, 0);
598 for_each_rawref(get_name, NULL);
599 if (!hashmap_get_size(&names) && !always)
600 die(_("No names found, cannot describe anything."));
601
602 if (argc == 0) {
603 if (broken) {
604 struct child_process cp = CHILD_PROCESS_INIT;
605 argv_array_pushv(&cp.args, diff_index_args);
606 cp.git_cmd = 1;
607 cp.no_stdin = 1;
608 cp.no_stdout = 1;
609
610 if (!dirty)
611 dirty = "-dirty";
612
613 switch (run_command(&cp)) {
614 case 0:
615 suffix = NULL;
616 break;
617 case 1:
618 suffix = dirty;
619 break;
620 default:
621 /* diff-index aborted abnormally */
622 suffix = broken;
623 }
624 } else if (dirty) {
625 struct lock_file index_lock = LOCK_INIT;
626 struct rev_info revs;
627 struct argv_array args = ARGV_ARRAY_INIT;
628 int fd, result;
629
630 read_cache_preload(NULL);
631 refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED,
632 NULL, NULL, NULL);
633 fd = hold_locked_index(&index_lock, 0);
634 if (0 <= fd)
635 update_index_if_able(&the_index, &index_lock);
636
637 init_revisions(&revs, prefix);
638 argv_array_pushv(&args, diff_index_args);
639 if (setup_revisions(args.argc, args.argv, &revs, NULL) != 1)
640 BUG("malformed internal diff-index command line");
641 result = run_diff_index(&revs, 0);
642
643 if (!diff_result_code(&revs.diffopt, result))
644 suffix = NULL;
645 else
646 suffix = dirty;
647 }
648 describe("HEAD", 1);
649 } else if (dirty) {
650 die(_("--dirty is incompatible with commit-ishes"));
651 } else if (broken) {
652 die(_("--broken is incompatible with commit-ishes"));
653 } else {
654 while (argc-- > 0)
655 describe(*argv++, argc == 0);
656 }
657 return 0;
658}