5cc9e9abe798e19705167a7459bb41945f7d617c
   1#include "cache.h"
   2#include "lockfile.h"
   3#include "commit.h"
   4#include "tag.h"
   5#include "refs.h"
   6#include "builtin.h"
   7#include "exec_cmd.h"
   8#include "parse-options.h"
   9#include "diff.h"
  10#include "hashmap.h"
  11#include "argv-array.h"
  12
  13#define SEEN            (1u << 0)
  14#define MAX_TAGS        (FLAG_BITS - 1)
  15
  16static const char * const describe_usage[] = {
  17        N_("git describe [<options>] [<commit-ish>...]"),
  18        N_("git describe [<options>] --dirty"),
  19        NULL
  20};
  21
  22static int debug;       /* Display lots of verbose info */
  23static int all; /* Any valid ref can be used */
  24static int tags;        /* Allow lightweight tags */
  25static int longformat;
  26static int first_parent;
  27static int abbrev = -1; /* unspecified */
  28static int max_candidates = 10;
  29static struct hashmap names;
  30static int have_util;
  31static struct string_list patterns = STRING_LIST_INIT_NODUP;
  32static int always;
  33static const char *dirty;
  34
  35/* diff-index command arguments to check if working tree is dirty. */
  36static const char *diff_index_args[] = {
  37        "diff-index", "--quiet", "HEAD", "--", NULL
  38};
  39
  40struct commit_name {
  41        struct hashmap_entry entry;
  42        unsigned char peeled[20];
  43        struct tag *tag;
  44        unsigned prio:2; /* annotated tag = 2, tag = 1, head = 0 */
  45        unsigned name_checked:1;
  46        unsigned char sha1[20];
  47        char *path;
  48};
  49
  50static const char *prio_names[] = {
  51        "head", "lightweight", "annotated",
  52};
  53
  54static int commit_name_cmp(const struct commit_name *cn1,
  55                const struct commit_name *cn2, const void *peeled)
  56{
  57        return hashcmp(cn1->peeled, peeled ? peeled : cn2->peeled);
  58}
  59
  60static inline struct commit_name *find_commit_name(const unsigned char *peeled)
  61{
  62        return hashmap_get_from_hash(&names, sha1hash(peeled), peeled);
  63}
  64
  65static int replace_name(struct commit_name *e,
  66                               int prio,
  67                               const unsigned char *sha1,
  68                               struct tag **tag)
  69{
  70        if (!e || e->prio < prio)
  71                return 1;
  72
  73        if (e->prio == 2 && prio == 2) {
  74                /* Multiple annotated tags point to the same commit.
  75                 * Select one to keep based upon their tagger date.
  76                 */
  77                struct tag *t;
  78
  79                if (!e->tag) {
  80                        t = lookup_tag(e->sha1);
  81                        if (!t || parse_tag(t))
  82                                return 1;
  83                        e->tag = t;
  84                }
  85
  86                t = lookup_tag(sha1);
  87                if (!t || parse_tag(t))
  88                        return 0;
  89                *tag = t;
  90
  91                if (e->tag->date < t->date)
  92                        return 1;
  93        }
  94
  95        return 0;
  96}
  97
  98static void add_to_known_names(const char *path,
  99                               const unsigned char *peeled,
 100                               int prio,
 101                               const unsigned char *sha1)
 102{
 103        struct commit_name *e = find_commit_name(peeled);
 104        struct tag *tag = NULL;
 105        if (replace_name(e, prio, sha1, &tag)) {
 106                if (!e) {
 107                        e = xmalloc(sizeof(struct commit_name));
 108                        hashcpy(e->peeled, peeled);
 109                        hashmap_entry_init(e, sha1hash(peeled));
 110                        hashmap_add(&names, e);
 111                        e->path = NULL;
 112                }
 113                e->tag = tag;
 114                e->prio = prio;
 115                e->name_checked = 0;
 116                hashcpy(e->sha1, sha1);
 117                free(e->path);
 118                e->path = xstrdup(path);
 119        }
 120}
 121
 122static int get_name(const char *path, const struct object_id *oid, int flag, void *cb_data)
 123{
 124        int is_tag = starts_with(path, "refs/tags/");
 125        struct object_id peeled;
 126        int is_annotated, prio;
 127
 128        /* Reject anything outside refs/tags/ unless --all */
 129        if (!all && !is_tag)
 130                return 0;
 131
 132        /*
 133         * If we're given patterns, accept only tags which match at least one
 134         * pattern.
 135         */
 136        if (patterns.nr) {
 137                struct string_list_item *item;
 138
 139                if (!is_tag)
 140                        return 0;
 141
 142                for_each_string_list_item(item, &patterns) {
 143                        if (!wildmatch(item->string, path + 10, 0, NULL))
 144                                break;
 145
 146                        /* If we get here, no pattern matched. */
 147                        return 0;
 148                }
 149        }
 150
 151        /* Is it annotated? */
 152        if (!peel_ref(path, peeled.hash)) {
 153                is_annotated = !!oidcmp(oid, &peeled);
 154        } else {
 155                oidcpy(&peeled, oid);
 156                is_annotated = 0;
 157        }
 158
 159        /*
 160         * By default, we only use annotated tags, but with --tags
 161         * we fall back to lightweight ones (even without --tags,
 162         * we still remember lightweight ones, only to give hints
 163         * in an error message).  --all allows any refs to be used.
 164         */
 165        if (is_annotated)
 166                prio = 2;
 167        else if (is_tag)
 168                prio = 1;
 169        else
 170                prio = 0;
 171
 172        add_to_known_names(all ? path + 5 : path + 10, peeled.hash, prio, oid->hash);
 173        return 0;
 174}
 175
 176struct possible_tag {
 177        struct commit_name *name;
 178        int depth;
 179        int found_order;
 180        unsigned flag_within;
 181};
 182
 183static int compare_pt(const void *a_, const void *b_)
 184{
 185        struct possible_tag *a = (struct possible_tag *)a_;
 186        struct possible_tag *b = (struct possible_tag *)b_;
 187        if (a->depth != b->depth)
 188                return a->depth - b->depth;
 189        if (a->found_order != b->found_order)
 190                return a->found_order - b->found_order;
 191        return 0;
 192}
 193
 194static unsigned long finish_depth_computation(
 195        struct commit_list **list,
 196        struct possible_tag *best)
 197{
 198        unsigned long seen_commits = 0;
 199        while (*list) {
 200                struct commit *c = pop_commit(list);
 201                struct commit_list *parents = c->parents;
 202                seen_commits++;
 203                if (c->object.flags & best->flag_within) {
 204                        struct commit_list *a = *list;
 205                        while (a) {
 206                                struct commit *i = a->item;
 207                                if (!(i->object.flags & best->flag_within))
 208                                        break;
 209                                a = a->next;
 210                        }
 211                        if (!a)
 212                                break;
 213                } else
 214                        best->depth++;
 215                while (parents) {
 216                        struct commit *p = parents->item;
 217                        parse_commit(p);
 218                        if (!(p->object.flags & SEEN))
 219                                commit_list_insert_by_date(p, list);
 220                        p->object.flags |= c->object.flags;
 221                        parents = parents->next;
 222                }
 223        }
 224        return seen_commits;
 225}
 226
 227static void display_name(struct commit_name *n)
 228{
 229        if (n->prio == 2 && !n->tag) {
 230                n->tag = lookup_tag(n->sha1);
 231                if (!n->tag || parse_tag(n->tag))
 232                        die(_("annotated tag %s not available"), n->path);
 233        }
 234        if (n->tag && !n->name_checked) {
 235                if (!n->tag->tag)
 236                        die(_("annotated tag %s has no embedded name"), n->path);
 237                if (strcmp(n->tag->tag, all ? n->path + 5 : n->path))
 238                        warning(_("tag '%s' is really '%s' here"), n->tag->tag, n->path);
 239                n->name_checked = 1;
 240        }
 241
 242        if (n->tag)
 243                printf("%s", n->tag->tag);
 244        else
 245                printf("%s", n->path);
 246}
 247
 248static void show_suffix(int depth, const unsigned char *sha1)
 249{
 250        printf("-%d-g%s", depth, find_unique_abbrev(sha1, abbrev));
 251}
 252
 253static void describe(const char *arg, int last_one)
 254{
 255        unsigned char sha1[20];
 256        struct commit *cmit, *gave_up_on = NULL;
 257        struct commit_list *list;
 258        struct commit_name *n;
 259        struct possible_tag all_matches[MAX_TAGS];
 260        unsigned int match_cnt = 0, annotated_cnt = 0, cur_match;
 261        unsigned long seen_commits = 0;
 262        unsigned int unannotated_cnt = 0;
 263
 264        if (get_sha1(arg, sha1))
 265                die(_("Not a valid object name %s"), arg);
 266        cmit = lookup_commit_reference(sha1);
 267        if (!cmit)
 268                die(_("%s is not a valid '%s' object"), arg, commit_type);
 269
 270        n = find_commit_name(cmit->object.oid.hash);
 271        if (n && (tags || all || n->prio == 2)) {
 272                /*
 273                 * Exact match to an existing ref.
 274                 */
 275                display_name(n);
 276                if (longformat)
 277                        show_suffix(0, n->tag ? n->tag->tagged->oid.hash : sha1);
 278                if (dirty)
 279                        printf("%s", dirty);
 280                printf("\n");
 281                return;
 282        }
 283
 284        if (!max_candidates)
 285                die(_("no tag exactly matches '%s'"), oid_to_hex(&cmit->object.oid));
 286        if (debug)
 287                fprintf(stderr, _("searching to describe %s\n"), arg);
 288
 289        if (!have_util) {
 290                struct hashmap_iter iter;
 291                struct commit *c;
 292                struct commit_name *n = hashmap_iter_first(&names, &iter);
 293                for (; n; n = hashmap_iter_next(&iter)) {
 294                        c = lookup_commit_reference_gently(n->peeled, 1);
 295                        if (c)
 296                                c->util = n;
 297                }
 298                have_util = 1;
 299        }
 300
 301        list = NULL;
 302        cmit->object.flags = SEEN;
 303        commit_list_insert(cmit, &list);
 304        while (list) {
 305                struct commit *c = pop_commit(&list);
 306                struct commit_list *parents = c->parents;
 307                seen_commits++;
 308                n = c->util;
 309                if (n) {
 310                        if (!tags && !all && n->prio < 2) {
 311                                unannotated_cnt++;
 312                        } else if (match_cnt < max_candidates) {
 313                                struct possible_tag *t = &all_matches[match_cnt++];
 314                                t->name = n;
 315                                t->depth = seen_commits - 1;
 316                                t->flag_within = 1u << match_cnt;
 317                                t->found_order = match_cnt;
 318                                c->object.flags |= t->flag_within;
 319                                if (n->prio == 2)
 320                                        annotated_cnt++;
 321                        }
 322                        else {
 323                                gave_up_on = c;
 324                                break;
 325                        }
 326                }
 327                for (cur_match = 0; cur_match < match_cnt; cur_match++) {
 328                        struct possible_tag *t = &all_matches[cur_match];
 329                        if (!(c->object.flags & t->flag_within))
 330                                t->depth++;
 331                }
 332                if (annotated_cnt && !list) {
 333                        if (debug)
 334                                fprintf(stderr, _("finished search at %s\n"),
 335                                        oid_to_hex(&c->object.oid));
 336                        break;
 337                }
 338                while (parents) {
 339                        struct commit *p = parents->item;
 340                        parse_commit(p);
 341                        if (!(p->object.flags & SEEN))
 342                                commit_list_insert_by_date(p, &list);
 343                        p->object.flags |= c->object.flags;
 344                        parents = parents->next;
 345
 346                        if (first_parent)
 347                                break;
 348                }
 349        }
 350
 351        if (!match_cnt) {
 352                struct object_id *oid = &cmit->object.oid;
 353                if (always) {
 354                        printf("%s", find_unique_abbrev(oid->hash, abbrev));
 355                        if (dirty)
 356                                printf("%s", dirty);
 357                        printf("\n");
 358                        return;
 359                }
 360                if (unannotated_cnt)
 361                        die(_("No annotated tags can describe '%s'.\n"
 362                            "However, there were unannotated tags: try --tags."),
 363                            oid_to_hex(oid));
 364                else
 365                        die(_("No tags can describe '%s'.\n"
 366                            "Try --always, or create some tags."),
 367                            oid_to_hex(oid));
 368        }
 369
 370        QSORT(all_matches, match_cnt, compare_pt);
 371
 372        if (gave_up_on) {
 373                commit_list_insert_by_date(gave_up_on, &list);
 374                seen_commits--;
 375        }
 376        seen_commits += finish_depth_computation(&list, &all_matches[0]);
 377        free_commit_list(list);
 378
 379        if (debug) {
 380                for (cur_match = 0; cur_match < match_cnt; cur_match++) {
 381                        struct possible_tag *t = &all_matches[cur_match];
 382                        fprintf(stderr, " %-11s %8d %s\n",
 383                                prio_names[t->name->prio],
 384                                t->depth, t->name->path);
 385                }
 386                fprintf(stderr, _("traversed %lu commits\n"), seen_commits);
 387                if (gave_up_on) {
 388                        fprintf(stderr,
 389                                _("more than %i tags found; listed %i most recent\n"
 390                                "gave up search at %s\n"),
 391                                max_candidates, max_candidates,
 392                                oid_to_hex(&gave_up_on->object.oid));
 393                }
 394        }
 395
 396        display_name(all_matches[0].name);
 397        if (abbrev)
 398                show_suffix(all_matches[0].depth, cmit->object.oid.hash);
 399        if (dirty)
 400                printf("%s", dirty);
 401        printf("\n");
 402
 403        if (!last_one)
 404                clear_commit_marks(cmit, -1);
 405}
 406
 407int cmd_describe(int argc, const char **argv, const char *prefix)
 408{
 409        int contains = 0;
 410        struct option options[] = {
 411                OPT_BOOL(0, "contains",   &contains, N_("find the tag that comes after the commit")),
 412                OPT_BOOL(0, "debug",      &debug, N_("debug search strategy on stderr")),
 413                OPT_BOOL(0, "all",        &all, N_("use any ref")),
 414                OPT_BOOL(0, "tags",       &tags, N_("use any tag, even unannotated")),
 415                OPT_BOOL(0, "long",       &longformat, N_("always use long format")),
 416                OPT_BOOL(0, "first-parent", &first_parent, N_("only follow first parent")),
 417                OPT__ABBREV(&abbrev),
 418                OPT_SET_INT(0, "exact-match", &max_candidates,
 419                            N_("only output exact matches"), 0),
 420                OPT_INTEGER(0, "candidates", &max_candidates,
 421                            N_("consider <n> most recent tags (default: 10)")),
 422                OPT_STRING_LIST(0, "match", &patterns, N_("pattern"),
 423                           N_("only consider tags matching <pattern>")),
 424                OPT_BOOL(0, "always",        &always,
 425                        N_("show abbreviated commit object as fallback")),
 426                {OPTION_STRING, 0, "dirty",  &dirty, N_("mark"),
 427                        N_("append <mark> on dirty working tree (default: \"-dirty\")"),
 428                        PARSE_OPT_OPTARG, NULL, (intptr_t) "-dirty"},
 429                OPT_END(),
 430        };
 431
 432        git_config(git_default_config, NULL);
 433        argc = parse_options(argc, argv, prefix, options, describe_usage, 0);
 434        if (abbrev < 0)
 435                abbrev = DEFAULT_ABBREV;
 436
 437        if (max_candidates < 0)
 438                max_candidates = 0;
 439        else if (max_candidates > MAX_TAGS)
 440                max_candidates = MAX_TAGS;
 441
 442        save_commit_buffer = 0;
 443
 444        if (longformat && abbrev == 0)
 445                die(_("--long is incompatible with --abbrev=0"));
 446
 447        if (contains) {
 448                struct string_list_item *item;
 449                struct argv_array args;
 450
 451                argv_array_init(&args);
 452                argv_array_pushl(&args, "name-rev",
 453                                 "--peel-tag", "--name-only", "--no-undefined",
 454                                 NULL);
 455                if (always)
 456                        argv_array_push(&args, "--always");
 457                if (!all) {
 458                        argv_array_push(&args, "--tags");
 459                        for_each_string_list_item(item, &patterns)
 460                                argv_array_pushf(&args, "--refs=refs/tags/%s", item->string);
 461                }
 462                if (argc)
 463                        argv_array_pushv(&args, argv);
 464                else
 465                        argv_array_push(&args, "HEAD");
 466                return cmd_name_rev(args.argc, args.argv, prefix);
 467        }
 468
 469        hashmap_init(&names, (hashmap_cmp_fn) commit_name_cmp, 0);
 470        for_each_rawref(get_name, NULL);
 471        if (!names.size && !always)
 472                die(_("No names found, cannot describe anything."));
 473
 474        if (argc == 0) {
 475                if (dirty) {
 476                        static struct lock_file index_lock;
 477                        int fd;
 478
 479                        read_cache_preload(NULL);
 480                        refresh_index(&the_index, REFRESH_QUIET|REFRESH_UNMERGED,
 481                                      NULL, NULL, NULL);
 482                        fd = hold_locked_index(&index_lock, 0);
 483                        if (0 <= fd)
 484                                update_index_if_able(&the_index, &index_lock);
 485
 486                        if (!cmd_diff_index(ARRAY_SIZE(diff_index_args) - 1,
 487                                            diff_index_args, prefix))
 488                                dirty = NULL;
 489                }
 490                describe("HEAD", 1);
 491        } else if (dirty) {
 492                die(_("--dirty is incompatible with commit-ishes"));
 493        } else {
 494                while (argc-- > 0)
 495                        describe(*argv++, argc == 0);
 496        }
 497        return 0;
 498}