Merge branch 'jt/partial-clone-fsck-connectivity'
[git] / builtin / name-rev.c
1 #include "builtin.h"
2 #include "cache.h"
3 #include "config.h"
4 #include "commit.h"
5 #include "tag.h"
6 #include "refs.h"
7 #include "parse-options.h"
8 #include "sha1-lookup.h"
9 #include "commit-slab.h"
10
11 #define CUTOFF_DATE_SLOP 86400 /* one day */
12
13 typedef struct rev_name {
14         const char *tip_name;
15         timestamp_t taggerdate;
16         int generation;
17         int distance;
18         int from_tag;
19 } rev_name;
20
21 define_commit_slab(commit_rev_name, struct rev_name *);
22
23 static timestamp_t cutoff = TIME_MAX;
24 static struct commit_rev_name rev_names;
25
26 /* How many generations are maximally preferred over _one_ merge traversal? */
27 #define MERGE_TRAVERSAL_WEIGHT 65535
28
29 static struct rev_name *get_commit_rev_name(struct commit *commit)
30 {
31         struct rev_name **slot = commit_rev_name_peek(&rev_names, commit);
32
33         return slot ? *slot : NULL;
34 }
35
36 static void set_commit_rev_name(struct commit *commit, struct rev_name *name)
37 {
38         *commit_rev_name_at(&rev_names, commit) = name;
39 }
40
41 static int is_better_name(struct rev_name *name,
42                           const char *tip_name,
43                           timestamp_t taggerdate,
44                           int generation,
45                           int distance,
46                           int from_tag)
47 {
48         /*
49          * When comparing names based on tags, prefer names
50          * based on the older tag, even if it is farther away.
51          */
52         if (from_tag && name->from_tag)
53                 return (name->taggerdate > taggerdate ||
54                         (name->taggerdate == taggerdate &&
55                          name->distance > distance));
56
57         /*
58          * We know that at least one of them is a non-tag at this point.
59          * favor a tag over a non-tag.
60          */
61         if (name->from_tag != from_tag)
62                 return from_tag;
63
64         /*
65          * We are now looking at two non-tags.  Tiebreak to favor
66          * shorter hops.
67          */
68         if (name->distance != distance)
69                 return name->distance > distance;
70
71         /* ... or tiebreak to favor older date */
72         if (name->taggerdate != taggerdate)
73                 return name->taggerdate > taggerdate;
74
75         /* keep the current one if we cannot decide */
76         return 0;
77 }
78
79 static void name_rev(struct commit *commit,
80                 const char *tip_name, timestamp_t taggerdate,
81                 int generation, int distance, int from_tag,
82                 int deref)
83 {
84         struct rev_name *name = get_commit_rev_name(commit);
85         struct commit_list *parents;
86         int parent_number = 1;
87         char *to_free = NULL;
88
89         parse_commit(commit);
90
91         if (commit->date < cutoff)
92                 return;
93
94         if (deref) {
95                 tip_name = to_free = xstrfmt("%s^0", tip_name);
96
97                 if (generation)
98                         die("generation: %d, but deref?", generation);
99         }
100
101         if (name == NULL) {
102                 name = xmalloc(sizeof(rev_name));
103                 set_commit_rev_name(commit, name);
104                 goto copy_data;
105         } else if (is_better_name(name, tip_name, taggerdate,
106                                   generation, distance, from_tag)) {
107 copy_data:
108                 name->tip_name = tip_name;
109                 name->taggerdate = taggerdate;
110                 name->generation = generation;
111                 name->distance = distance;
112                 name->from_tag = from_tag;
113         } else {
114                 free(to_free);
115                 return;
116         }
117
118         for (parents = commit->parents;
119                         parents;
120                         parents = parents->next, parent_number++) {
121                 if (parent_number > 1) {
122                         size_t len;
123                         char *new_name;
124
125                         strip_suffix(tip_name, "^0", &len);
126                         if (generation > 0)
127                                 new_name = xstrfmt("%.*s~%d^%d", (int)len, tip_name,
128                                                    generation, parent_number);
129                         else
130                                 new_name = xstrfmt("%.*s^%d", (int)len, tip_name,
131                                                    parent_number);
132
133                         name_rev(parents->item, new_name, taggerdate, 0,
134                                  distance + MERGE_TRAVERSAL_WEIGHT,
135                                  from_tag, 0);
136                 } else {
137                         name_rev(parents->item, tip_name, taggerdate,
138                                  generation + 1, distance + 1,
139                                  from_tag, 0);
140                 }
141         }
142 }
143
144 static int subpath_matches(const char *path, const char *filter)
145 {
146         const char *subpath = path;
147
148         while (subpath) {
149                 if (!wildmatch(filter, subpath, 0))
150                         return subpath - path;
151                 subpath = strchr(subpath, '/');
152                 if (subpath)
153                         subpath++;
154         }
155         return -1;
156 }
157
158 static const char *name_ref_abbrev(const char *refname, int shorten_unambiguous)
159 {
160         if (shorten_unambiguous)
161                 refname = shorten_unambiguous_ref(refname, 0);
162         else if (starts_with(refname, "refs/heads/"))
163                 refname = refname + 11;
164         else if (starts_with(refname, "refs/"))
165                 refname = refname + 5;
166         return refname;
167 }
168
169 struct name_ref_data {
170         int tags_only;
171         int name_only;
172         struct string_list ref_filters;
173         struct string_list exclude_filters;
174 };
175
176 static struct tip_table {
177         struct tip_table_entry {
178                 struct object_id oid;
179                 const char *refname;
180         } *table;
181         int nr;
182         int alloc;
183         int sorted;
184 } tip_table;
185
186 static void add_to_tip_table(const struct object_id *oid, const char *refname,
187                              int shorten_unambiguous)
188 {
189         refname = name_ref_abbrev(refname, shorten_unambiguous);
190
191         ALLOC_GROW(tip_table.table, tip_table.nr + 1, tip_table.alloc);
192         oidcpy(&tip_table.table[tip_table.nr].oid, oid);
193         tip_table.table[tip_table.nr].refname = xstrdup(refname);
194         tip_table.nr++;
195         tip_table.sorted = 0;
196 }
197
198 static int tipcmp(const void *a_, const void *b_)
199 {
200         const struct tip_table_entry *a = a_, *b = b_;
201         return oidcmp(&a->oid, &b->oid);
202 }
203
204 static int name_ref(const char *path, const struct object_id *oid, int flags, void *cb_data)
205 {
206         struct object *o = parse_object(oid);
207         struct name_ref_data *data = cb_data;
208         int can_abbreviate_output = data->tags_only && data->name_only;
209         int deref = 0;
210         timestamp_t taggerdate = TIME_MAX;
211
212         if (data->tags_only && !starts_with(path, "refs/tags/"))
213                 return 0;
214
215         if (data->exclude_filters.nr) {
216                 struct string_list_item *item;
217
218                 for_each_string_list_item(item, &data->exclude_filters) {
219                         if (subpath_matches(path, item->string) >= 0)
220                                 return 0;
221                 }
222         }
223
224         if (data->ref_filters.nr) {
225                 struct string_list_item *item;
226                 int matched = 0;
227
228                 /* See if any of the patterns match. */
229                 for_each_string_list_item(item, &data->ref_filters) {
230                         /*
231                          * Check all patterns even after finding a match, so
232                          * that we can see if a match with a subpath exists.
233                          * When a user asked for 'refs/tags/v*' and 'v1.*',
234                          * both of which match, the user is showing her
235                          * willingness to accept a shortened output by having
236                          * the 'v1.*' in the acceptable refnames, so we
237                          * shouldn't stop when seeing 'refs/tags/v1.4' matches
238                          * 'refs/tags/v*'.  We should show it as 'v1.4'.
239                          */
240                         switch (subpath_matches(path, item->string)) {
241                         case -1: /* did not match */
242                                 break;
243                         case 0: /* matched fully */
244                                 matched = 1;
245                                 break;
246                         default: /* matched subpath */
247                                 matched = 1;
248                                 can_abbreviate_output = 1;
249                                 break;
250                         }
251                 }
252
253                 /* If none of the patterns matched, stop now */
254                 if (!matched)
255                         return 0;
256         }
257
258         add_to_tip_table(oid, path, can_abbreviate_output);
259
260         while (o && o->type == OBJ_TAG) {
261                 struct tag *t = (struct tag *) o;
262                 if (!t->tagged)
263                         break; /* broken repository */
264                 o = parse_object(&t->tagged->oid);
265                 deref = 1;
266                 taggerdate = t->date;
267         }
268         if (o && o->type == OBJ_COMMIT) {
269                 struct commit *commit = (struct commit *)o;
270                 int from_tag = starts_with(path, "refs/tags/");
271
272                 if (taggerdate == TIME_MAX)
273                         taggerdate = ((struct commit *)o)->date;
274                 path = name_ref_abbrev(path, can_abbreviate_output);
275                 name_rev(commit, xstrdup(path), taggerdate, 0, 0,
276                          from_tag, deref);
277         }
278         return 0;
279 }
280
281 static const unsigned char *nth_tip_table_ent(size_t ix, void *table_)
282 {
283         struct tip_table_entry *table = table_;
284         return table[ix].oid.hash;
285 }
286
287 static const char *get_exact_ref_match(const struct object *o)
288 {
289         int found;
290
291         if (!tip_table.table || !tip_table.nr)
292                 return NULL;
293
294         if (!tip_table.sorted) {
295                 QSORT(tip_table.table, tip_table.nr, tipcmp);
296                 tip_table.sorted = 1;
297         }
298
299         found = sha1_pos(o->oid.hash, tip_table.table, tip_table.nr,
300                          nth_tip_table_ent);
301         if (0 <= found)
302                 return tip_table.table[found].refname;
303         return NULL;
304 }
305
306 /* may return a constant string or use "buf" as scratch space */
307 static const char *get_rev_name(const struct object *o, struct strbuf *buf)
308 {
309         struct rev_name *n;
310         struct commit *c;
311
312         if (o->type != OBJ_COMMIT)
313                 return get_exact_ref_match(o);
314         c = (struct commit *) o;
315         n = get_commit_rev_name(c);
316         if (!n)
317                 return NULL;
318
319         if (!n->generation)
320                 return n->tip_name;
321         else {
322                 int len = strlen(n->tip_name);
323                 if (len > 2 && !strcmp(n->tip_name + len - 2, "^0"))
324                         len -= 2;
325                 strbuf_reset(buf);
326                 strbuf_addf(buf, "%.*s~%d", len, n->tip_name, n->generation);
327                 return buf->buf;
328         }
329 }
330
331 static void show_name(const struct object *obj,
332                       const char *caller_name,
333                       int always, int allow_undefined, int name_only)
334 {
335         const char *name;
336         const struct object_id *oid = &obj->oid;
337         struct strbuf buf = STRBUF_INIT;
338
339         if (!name_only)
340                 printf("%s ", caller_name ? caller_name : oid_to_hex(oid));
341         name = get_rev_name(obj, &buf);
342         if (name)
343                 printf("%s\n", name);
344         else if (allow_undefined)
345                 printf("undefined\n");
346         else if (always)
347                 printf("%s\n", find_unique_abbrev(oid, DEFAULT_ABBREV));
348         else
349                 die("cannot describe '%s'", oid_to_hex(oid));
350         strbuf_release(&buf);
351 }
352
353 static char const * const name_rev_usage[] = {
354         N_("git name-rev [<options>] <commit>..."),
355         N_("git name-rev [<options>] --all"),
356         N_("git name-rev [<options>] --stdin"),
357         NULL
358 };
359
360 static void name_rev_line(char *p, struct name_ref_data *data)
361 {
362         struct strbuf buf = STRBUF_INIT;
363         int forty = 0;
364         char *p_start;
365         for (p_start = p; *p; p++) {
366 #define ishex(x) (isdigit((x)) || ((x) >= 'a' && (x) <= 'f'))
367                 if (!ishex(*p))
368                         forty = 0;
369                 else if (++forty == GIT_SHA1_HEXSZ &&
370                          !ishex(*(p+1))) {
371                         struct object_id oid;
372                         const char *name = NULL;
373                         char c = *(p+1);
374                         int p_len = p - p_start + 1;
375
376                         forty = 0;
377
378                         *(p+1) = 0;
379                         if (!get_oid(p - (GIT_SHA1_HEXSZ - 1), &oid)) {
380                                 struct object *o =
381                                         lookup_object(oid.hash);
382                                 if (o)
383                                         name = get_rev_name(o, &buf);
384                         }
385                         *(p+1) = c;
386
387                         if (!name)
388                                 continue;
389
390                         if (data->name_only)
391                                 printf("%.*s%s", p_len - GIT_SHA1_HEXSZ, p_start, name);
392                         else
393                                 printf("%.*s (%s)", p_len, p_start, name);
394                         p_start = p + 1;
395                 }
396         }
397
398         /* flush */
399         if (p_start != p)
400                 fwrite(p_start, p - p_start, 1, stdout);
401
402         strbuf_release(&buf);
403 }
404
405 int cmd_name_rev(int argc, const char **argv, const char *prefix)
406 {
407         struct object_array revs = OBJECT_ARRAY_INIT;
408         int all = 0, transform_stdin = 0, allow_undefined = 1, always = 0, peel_tag = 0;
409         struct name_ref_data data = { 0, 0, STRING_LIST_INIT_NODUP, STRING_LIST_INIT_NODUP };
410         struct option opts[] = {
411                 OPT_BOOL(0, "name-only", &data.name_only, N_("print only names (no SHA-1)")),
412                 OPT_BOOL(0, "tags", &data.tags_only, N_("only use tags to name the commits")),
413                 OPT_STRING_LIST(0, "refs", &data.ref_filters, N_("pattern"),
414                                    N_("only use refs matching <pattern>")),
415                 OPT_STRING_LIST(0, "exclude", &data.exclude_filters, N_("pattern"),
416                                    N_("ignore refs matching <pattern>")),
417                 OPT_GROUP(""),
418                 OPT_BOOL(0, "all", &all, N_("list all commits reachable from all refs")),
419                 OPT_BOOL(0, "stdin", &transform_stdin, N_("read from stdin")),
420                 OPT_BOOL(0, "undefined", &allow_undefined, N_("allow to print `undefined` names (default)")),
421                 OPT_BOOL(0, "always",     &always,
422                            N_("show abbreviated commit object as fallback")),
423                 {
424                         /* A Hidden OPT_BOOL */
425                         OPTION_SET_INT, 0, "peel-tag", &peel_tag, NULL,
426                         N_("dereference tags in the input (internal use)"),
427                         PARSE_OPT_NOARG | PARSE_OPT_HIDDEN, NULL, 1,
428                 },
429                 OPT_END(),
430         };
431
432         init_commit_rev_name(&rev_names);
433         git_config(git_default_config, NULL);
434         argc = parse_options(argc, argv, prefix, opts, name_rev_usage, 0);
435         if (all + transform_stdin + !!argc > 1) {
436                 error("Specify either a list, or --all, not both!");
437                 usage_with_options(name_rev_usage, opts);
438         }
439         if (all || transform_stdin)
440                 cutoff = 0;
441
442         for (; argc; argc--, argv++) {
443                 struct object_id oid;
444                 struct object *object;
445                 struct commit *commit;
446
447                 if (get_oid(*argv, &oid)) {
448                         fprintf(stderr, "Could not get sha1 for %s. Skipping.\n",
449                                         *argv);
450                         continue;
451                 }
452
453                 commit = NULL;
454                 object = parse_object(&oid);
455                 if (object) {
456                         struct object *peeled = deref_tag(object, *argv, 0);
457                         if (peeled && peeled->type == OBJ_COMMIT)
458                                 commit = (struct commit *)peeled;
459                 }
460
461                 if (!object) {
462                         fprintf(stderr, "Could not get object for %s. Skipping.\n",
463                                         *argv);
464                         continue;
465                 }
466
467                 if (commit) {
468                         if (cutoff > commit->date)
469                                 cutoff = commit->date;
470                 }
471
472                 if (peel_tag) {
473                         if (!commit) {
474                                 fprintf(stderr, "Could not get commit for %s. Skipping.\n",
475                                         *argv);
476                                 continue;
477                         }
478                         object = (struct object *)commit;
479                 }
480                 add_object_array(object, *argv, &revs);
481         }
482
483         if (cutoff)
484                 cutoff = cutoff - CUTOFF_DATE_SLOP;
485         for_each_ref(name_ref, &data);
486
487         if (transform_stdin) {
488                 char buffer[2048];
489
490                 while (!feof(stdin)) {
491                         char *p = fgets(buffer, sizeof(buffer), stdin);
492                         if (!p)
493                                 break;
494                         name_rev_line(p, &data);
495                 }
496         } else if (all) {
497                 int i, max;
498
499                 max = get_max_object_index();
500                 for (i = 0; i < max; i++) {
501                         struct object *obj = get_indexed_object(i);
502                         if (!obj || obj->type != OBJ_COMMIT)
503                                 continue;
504                         show_name(obj, NULL,
505                                   always, allow_undefined, data.name_only);
506                 }
507         } else {
508                 int i;
509                 for (i = 0; i < revs.nr; i++)
510                         show_name(revs.objects[i].item, revs.objects[i].name,
511                                   always, allow_undefined, data.name_only);
512         }
513
514         UNLEAK(revs);
515         return 0;
516 }