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