git-name-rev: allow --name-only in combination with --stdin
[git] / sha1_name.c
1 #include "cache.h"
2 #include "tag.h"
3 #include "commit.h"
4 #include "tree.h"
5 #include "blob.h"
6 #include "tree-walk.h"
7 #include "refs.h"
8
9 static int find_short_object_filename(int len, const char *name, unsigned char *sha1)
10 {
11         struct alternate_object_database *alt;
12         char hex[40];
13         int found = 0;
14         static struct alternate_object_database *fakeent;
15
16         if (!fakeent) {
17                 const char *objdir = get_object_directory();
18                 int objdir_len = strlen(objdir);
19                 int entlen = objdir_len + 43;
20                 fakeent = xmalloc(sizeof(*fakeent) + entlen);
21                 memcpy(fakeent->base, objdir, objdir_len);
22                 fakeent->name = fakeent->base + objdir_len + 1;
23                 fakeent->name[-1] = '/';
24         }
25         fakeent->next = alt_odb_list;
26
27         sprintf(hex, "%.2s", name);
28         for (alt = fakeent; alt && found < 2; alt = alt->next) {
29                 struct dirent *de;
30                 DIR *dir;
31                 sprintf(alt->name, "%.2s/", name);
32                 dir = opendir(alt->base);
33                 if (!dir)
34                         continue;
35                 while ((de = readdir(dir)) != NULL) {
36                         if (strlen(de->d_name) != 38)
37                                 continue;
38                         if (memcmp(de->d_name, name + 2, len - 2))
39                                 continue;
40                         if (!found) {
41                                 memcpy(hex + 2, de->d_name, 38);
42                                 found++;
43                         }
44                         else if (memcmp(hex + 2, de->d_name, 38)) {
45                                 found = 2;
46                                 break;
47                         }
48                 }
49                 closedir(dir);
50         }
51         if (found == 1)
52                 return get_sha1_hex(hex, sha1) == 0;
53         return found;
54 }
55
56 static int match_sha(unsigned len, const unsigned char *a, const unsigned char *b)
57 {
58         do {
59                 if (*a != *b)
60                         return 0;
61                 a++;
62                 b++;
63                 len -= 2;
64         } while (len > 1);
65         if (len)
66                 if ((*a ^ *b) & 0xf0)
67                         return 0;
68         return 1;
69 }
70
71 static int find_short_packed_object(int len, const unsigned char *match, unsigned char *sha1)
72 {
73         struct packed_git *p;
74         const unsigned char *found_sha1 = NULL;
75         int found = 0;
76
77         prepare_packed_git();
78         for (p = packed_git; p && found < 2; p = p->next) {
79                 uint32_t num, last;
80                 uint32_t first = 0;
81                 open_pack_index(p);
82                 num = p->num_objects;
83                 last = num;
84                 while (first < last) {
85                         uint32_t mid = (first + last) / 2;
86                         const unsigned char *now;
87                         int cmp;
88
89                         now = nth_packed_object_sha1(p, mid);
90                         cmp = hashcmp(match, now);
91                         if (!cmp) {
92                                 first = mid;
93                                 break;
94                         }
95                         if (cmp > 0) {
96                                 first = mid+1;
97                                 continue;
98                         }
99                         last = mid;
100                 }
101                 if (first < num) {
102                         const unsigned char *now, *next;
103                        now = nth_packed_object_sha1(p, first);
104                         if (match_sha(len, match, now)) {
105                                 next = nth_packed_object_sha1(p, first+1);
106                                if (!next|| !match_sha(len, match, next)) {
107                                         /* unique within this pack */
108                                         if (!found) {
109                                                 found_sha1 = now;
110                                                 found++;
111                                         }
112                                         else if (hashcmp(found_sha1, now)) {
113                                                 found = 2;
114                                                 break;
115                                         }
116                                 }
117                                 else {
118                                         /* not even unique within this pack */
119                                         found = 2;
120                                         break;
121                                 }
122                         }
123                 }
124         }
125         if (found == 1)
126                 hashcpy(sha1, found_sha1);
127         return found;
128 }
129
130 #define SHORT_NAME_NOT_FOUND (-1)
131 #define SHORT_NAME_AMBIGUOUS (-2)
132
133 static int find_unique_short_object(int len, char *canonical,
134                                     unsigned char *res, unsigned char *sha1)
135 {
136         int has_unpacked, has_packed;
137         unsigned char unpacked_sha1[20], packed_sha1[20];
138
139         prepare_alt_odb();
140         has_unpacked = find_short_object_filename(len, canonical, unpacked_sha1);
141         has_packed = find_short_packed_object(len, res, packed_sha1);
142         if (!has_unpacked && !has_packed)
143                 return SHORT_NAME_NOT_FOUND;
144         if (1 < has_unpacked || 1 < has_packed)
145                 return SHORT_NAME_AMBIGUOUS;
146         if (has_unpacked != has_packed) {
147                 hashcpy(sha1, (has_packed ? packed_sha1 : unpacked_sha1));
148                 return 0;
149         }
150         /* Both have unique ones -- do they match? */
151         if (hashcmp(packed_sha1, unpacked_sha1))
152                 return SHORT_NAME_AMBIGUOUS;
153         hashcpy(sha1, packed_sha1);
154         return 0;
155 }
156
157 static int get_short_sha1(const char *name, int len, unsigned char *sha1,
158                           int quietly)
159 {
160         int i, status;
161         char canonical[40];
162         unsigned char res[20];
163
164         if (len < MINIMUM_ABBREV || len > 40)
165                 return -1;
166         hashclr(res);
167         memset(canonical, 'x', 40);
168         for (i = 0; i < len ;i++) {
169                 unsigned char c = name[i];
170                 unsigned char val;
171                 if (c >= '0' && c <= '9')
172                         val = c - '0';
173                 else if (c >= 'a' && c <= 'f')
174                         val = c - 'a' + 10;
175                 else if (c >= 'A' && c <='F') {
176                         val = c - 'A' + 10;
177                         c -= 'A' - 'a';
178                 }
179                 else
180                         return -1;
181                 canonical[i] = c;
182                 if (!(i & 1))
183                         val <<= 4;
184                 res[i >> 1] |= val;
185         }
186
187         status = find_unique_short_object(i, canonical, res, sha1);
188         if (!quietly && (status == SHORT_NAME_AMBIGUOUS))
189                 return error("short SHA1 %.*s is ambiguous.", len, canonical);
190         return status;
191 }
192
193 const char *find_unique_abbrev(const unsigned char *sha1, int len)
194 {
195         int status, exists;
196         static char hex[41];
197
198         exists = has_sha1_file(sha1);
199         memcpy(hex, sha1_to_hex(sha1), 40);
200         if (len == 40 || !len)
201                 return hex;
202         while (len < 40) {
203                 unsigned char sha1_ret[20];
204                 status = get_short_sha1(hex, len, sha1_ret, 1);
205                 if (exists
206                     ? !status
207                     : status == SHORT_NAME_NOT_FOUND) {
208                         hex[len] = 0;
209                         return hex;
210                 }
211                 len++;
212         }
213         return hex;
214 }
215
216 static int ambiguous_path(const char *path, int len)
217 {
218         int slash = 1;
219         int cnt;
220
221         for (cnt = 0; cnt < len; cnt++) {
222                 switch (*path++) {
223                 case '\0':
224                         break;
225                 case '/':
226                         if (slash)
227                                 break;
228                         slash = 1;
229                         continue;
230                 case '.':
231                         continue;
232                 default:
233                         slash = 0;
234                         continue;
235                 }
236                 break;
237         }
238         return slash;
239 }
240
241 int dwim_ref(const char *str, int len, unsigned char *sha1, char **ref)
242 {
243         const char **p, *r;
244         int refs_found = 0;
245
246         *ref = NULL;
247         for (p = ref_rev_parse_rules; *p; p++) {
248                 unsigned char sha1_from_ref[20];
249                 unsigned char *this_result;
250
251                 this_result = refs_found ? sha1_from_ref : sha1;
252                 r = resolve_ref(mkpath(*p, len, str), this_result, 1, NULL);
253                 if (r) {
254                         if (!refs_found++)
255                                 *ref = xstrdup(r);
256                         if (!warn_ambiguous_refs)
257                                 break;
258                 }
259         }
260         return refs_found;
261 }
262
263 int dwim_log(const char *str, int len, unsigned char *sha1, char **log)
264 {
265         const char **p;
266         int logs_found = 0;
267
268         *log = NULL;
269         for (p = ref_rev_parse_rules; *p; p++) {
270                 struct stat st;
271                 unsigned char hash[20];
272                 char path[PATH_MAX];
273                 const char *ref, *it;
274
275                 strcpy(path, mkpath(*p, len, str));
276                 ref = resolve_ref(path, hash, 0, NULL);
277                 if (!ref)
278                         continue;
279                 if (!stat(git_path("logs/%s", path), &st) &&
280                     S_ISREG(st.st_mode))
281                         it = path;
282                 else if (strcmp(ref, path) &&
283                          !stat(git_path("logs/%s", ref), &st) &&
284                          S_ISREG(st.st_mode))
285                         it = ref;
286                 else
287                         continue;
288                 if (!logs_found++) {
289                         *log = xstrdup(it);
290                         hashcpy(sha1, hash);
291                 }
292                 if (!warn_ambiguous_refs)
293                         break;
294         }
295         return logs_found;
296 }
297
298 static int get_sha1_basic(const char *str, int len, unsigned char *sha1)
299 {
300         static const char *warning = "warning: refname '%.*s' is ambiguous.\n";
301         char *real_ref = NULL;
302         int refs_found = 0;
303         int at, reflog_len;
304
305         if (len == 40 && !get_sha1_hex(str, sha1))
306                 return 0;
307
308         /* basic@{time or number} format to query ref-log */
309         reflog_len = at = 0;
310         if (str[len-1] == '}') {
311                 for (at = 0; at < len - 1; at++) {
312                         if (str[at] == '@' && str[at+1] == '{') {
313                                 reflog_len = (len-1) - (at+2);
314                                 len = at;
315                                 break;
316                         }
317                 }
318         }
319
320         /* Accept only unambiguous ref paths. */
321         if (len && ambiguous_path(str, len))
322                 return -1;
323
324         if (!len && reflog_len) {
325                 /* allow "@{...}" to mean the current branch reflog */
326                 refs_found = dwim_ref("HEAD", 4, sha1, &real_ref);
327         } else if (reflog_len)
328                 refs_found = dwim_log(str, len, sha1, &real_ref);
329         else
330                 refs_found = dwim_ref(str, len, sha1, &real_ref);
331
332         if (!refs_found)
333                 return -1;
334
335         if (warn_ambiguous_refs && refs_found > 1)
336                 fprintf(stderr, warning, len, str);
337
338         if (reflog_len) {
339                 int nth, i;
340                 unsigned long at_time;
341                 unsigned long co_time;
342                 int co_tz, co_cnt;
343
344                 /* Is it asking for N-th entry, or approxidate? */
345                 for (i = nth = 0; 0 <= nth && i < reflog_len; i++) {
346                         char ch = str[at+2+i];
347                         if ('0' <= ch && ch <= '9')
348                                 nth = nth * 10 + ch - '0';
349                         else
350                                 nth = -1;
351                 }
352                 if (0 <= nth)
353                         at_time = 0;
354                 else {
355                         char *tmp = xstrndup(str + at + 2, reflog_len);
356                         at_time = approxidate(tmp);
357                         free(tmp);
358                 }
359                 if (read_ref_at(real_ref, at_time, nth, sha1, NULL,
360                                 &co_time, &co_tz, &co_cnt)) {
361                         if (at_time)
362                                 fprintf(stderr,
363                                         "warning: Log for '%.*s' only goes "
364                                         "back to %s.\n", len, str,
365                                         show_date(co_time, co_tz, DATE_RFC2822));
366                         else
367                                 fprintf(stderr,
368                                         "warning: Log for '%.*s' only has "
369                                         "%d entries.\n", len, str, co_cnt);
370                 }
371         }
372
373         free(real_ref);
374         return 0;
375 }
376
377 static int get_sha1_1(const char *name, int len, unsigned char *sha1);
378
379 static int get_parent(const char *name, int len,
380                       unsigned char *result, int idx)
381 {
382         unsigned char sha1[20];
383         int ret = get_sha1_1(name, len, sha1);
384         struct commit *commit;
385         struct commit_list *p;
386
387         if (ret)
388                 return ret;
389         commit = lookup_commit_reference(sha1);
390         if (!commit)
391                 return -1;
392         if (parse_commit(commit))
393                 return -1;
394         if (!idx) {
395                 hashcpy(result, commit->object.sha1);
396                 return 0;
397         }
398         p = commit->parents;
399         while (p) {
400                 if (!--idx) {
401                         hashcpy(result, p->item->object.sha1);
402                         return 0;
403                 }
404                 p = p->next;
405         }
406         return -1;
407 }
408
409 static int get_nth_ancestor(const char *name, int len,
410                             unsigned char *result, int generation)
411 {
412         unsigned char sha1[20];
413         struct commit *commit;
414         int ret;
415
416         ret = get_sha1_1(name, len, sha1);
417         if (ret)
418                 return ret;
419         commit = lookup_commit_reference(sha1);
420         if (!commit)
421                 return -1;
422
423         while (generation--) {
424                 if (parse_commit(commit) || !commit->parents)
425                         return -1;
426                 commit = commit->parents->item;
427         }
428         hashcpy(result, commit->object.sha1);
429         return 0;
430 }
431
432 struct object *peel_to_type(const char *name, int namelen,
433                             struct object *o, enum object_type expected_type)
434 {
435         if (name && !namelen)
436                 namelen = strlen(name);
437         if (!o) {
438                 unsigned char sha1[20];
439                 if (get_sha1_1(name, namelen, sha1))
440                         return NULL;
441                 o = parse_object(sha1);
442         }
443         while (1) {
444                 if (!o || (!o->parsed && !parse_object(o->sha1)))
445                         return NULL;
446                 if (o->type == expected_type)
447                         return o;
448                 if (o->type == OBJ_TAG)
449                         o = ((struct tag*) o)->tagged;
450                 else if (o->type == OBJ_COMMIT)
451                         o = &(((struct commit *) o)->tree->object);
452                 else {
453                         if (name)
454                                 error("%.*s: expected %s type, but the object "
455                                       "dereferences to %s type",
456                                       namelen, name, typename(expected_type),
457                                       typename(o->type));
458                         return NULL;
459                 }
460         }
461 }
462
463 static int peel_onion(const char *name, int len, unsigned char *sha1)
464 {
465         unsigned char outer[20];
466         const char *sp;
467         unsigned int expected_type = 0;
468         struct object *o;
469
470         /*
471          * "ref^{type}" dereferences ref repeatedly until you cannot
472          * dereference anymore, or you get an object of given type,
473          * whichever comes first.  "ref^{}" means just dereference
474          * tags until you get a non-tag.  "ref^0" is a shorthand for
475          * "ref^{commit}".  "commit^{tree}" could be used to find the
476          * top-level tree of the given commit.
477          */
478         if (len < 4 || name[len-1] != '}')
479                 return -1;
480
481         for (sp = name + len - 1; name <= sp; sp--) {
482                 int ch = *sp;
483                 if (ch == '{' && name < sp && sp[-1] == '^')
484                         break;
485         }
486         if (sp <= name)
487                 return -1;
488
489         sp++; /* beginning of type name, or closing brace for empty */
490         if (!strncmp(commit_type, sp, 6) && sp[6] == '}')
491                 expected_type = OBJ_COMMIT;
492         else if (!strncmp(tree_type, sp, 4) && sp[4] == '}')
493                 expected_type = OBJ_TREE;
494         else if (!strncmp(blob_type, sp, 4) && sp[4] == '}')
495                 expected_type = OBJ_BLOB;
496         else if (sp[0] == '}')
497                 expected_type = OBJ_NONE;
498         else
499                 return -1;
500
501         if (get_sha1_1(name, sp - name - 2, outer))
502                 return -1;
503
504         o = parse_object(outer);
505         if (!o)
506                 return -1;
507         if (!expected_type) {
508                 o = deref_tag(o, name, sp - name - 2);
509                 if (!o || (!o->parsed && !parse_object(o->sha1)))
510                         return -1;
511                 hashcpy(sha1, o->sha1);
512         }
513         else {
514                 /*
515                  * At this point, the syntax look correct, so
516                  * if we do not get the needed object, we should
517                  * barf.
518                  */
519                 o = peel_to_type(name, len, o, expected_type);
520                 if (o) {
521                         hashcpy(sha1, o->sha1);
522                         return 0;
523                 }
524                 return -1;
525         }
526         return 0;
527 }
528
529 static int get_describe_name(const char *name, int len, unsigned char *sha1)
530 {
531         const char *cp;
532
533         for (cp = name + len - 1; name + 2 <= cp; cp--) {
534                 char ch = *cp;
535                 if (hexval(ch) & ~0377) {
536                         /* We must be looking at g in "SOMETHING-g"
537                          * for it to be describe output.
538                          */
539                         if (ch == 'g' && cp[-1] == '-') {
540                                 cp++;
541                                 len -= cp - name;
542                                 return get_short_sha1(cp, len, sha1, 1);
543                         }
544                 }
545         }
546         return -1;
547 }
548
549 static int get_sha1_1(const char *name, int len, unsigned char *sha1)
550 {
551         int ret, has_suffix;
552         const char *cp;
553
554         /*
555          * "name~3" is "name^^^", "name~" is "name~1", and "name^" is "name^1".
556          */
557         has_suffix = 0;
558         for (cp = name + len - 1; name <= cp; cp--) {
559                 int ch = *cp;
560                 if ('0' <= ch && ch <= '9')
561                         continue;
562                 if (ch == '~' || ch == '^')
563                         has_suffix = ch;
564                 break;
565         }
566
567         if (has_suffix) {
568                 int num = 0;
569                 int len1 = cp - name;
570                 cp++;
571                 while (cp < name + len)
572                         num = num * 10 + *cp++ - '0';
573                 if (!num && len1 == len - 1)
574                         num = 1;
575                 if (has_suffix == '^')
576                         return get_parent(name, len1, sha1, num);
577                 /* else if (has_suffix == '~') -- goes without saying */
578                 return get_nth_ancestor(name, len1, sha1, num);
579         }
580
581         ret = peel_onion(name, len, sha1);
582         if (!ret)
583                 return 0;
584
585         ret = get_sha1_basic(name, len, sha1);
586         if (!ret)
587                 return 0;
588
589         /* It could be describe output that is "SOMETHING-gXXXX" */
590         ret = get_describe_name(name, len, sha1);
591         if (!ret)
592                 return 0;
593
594         return get_short_sha1(name, len, sha1, 0);
595 }
596
597 static int handle_one_ref(const char *path,
598                 const unsigned char *sha1, int flag, void *cb_data)
599 {
600         struct commit_list **list = cb_data;
601         struct object *object = parse_object(sha1);
602         if (!object)
603                 return 0;
604         if (object->type == OBJ_TAG) {
605                 object = deref_tag(object, path, strlen(path));
606                 if (!object)
607                         return 0;
608         }
609         if (object->type != OBJ_COMMIT)
610                 return 0;
611         insert_by_date((struct commit *)object, list);
612         return 0;
613 }
614
615 /*
616  * This interprets names like ':/Initial revision of "git"' by searching
617  * through history and returning the first commit whose message starts
618  * with the given string.
619  *
620  * For future extension, ':/!' is reserved. If you want to match a message
621  * beginning with a '!', you have to repeat the exclamation mark.
622  */
623
624 #define ONELINE_SEEN (1u<<20)
625 static int get_sha1_oneline(const char *prefix, unsigned char *sha1)
626 {
627         struct commit_list *list = NULL, *backup = NULL, *l;
628         int retval = -1;
629         char *temp_commit_buffer = NULL;
630
631         if (prefix[0] == '!') {
632                 if (prefix[1] != '!')
633                         die ("Invalid search pattern: %s", prefix);
634                 prefix++;
635         }
636         for_each_ref(handle_one_ref, &list);
637         for (l = list; l; l = l->next)
638                 commit_list_insert(l->item, &backup);
639         while (list) {
640                 char *p;
641                 struct commit *commit;
642                 enum object_type type;
643                 unsigned long size;
644
645                 commit = pop_most_recent_commit(&list, ONELINE_SEEN);
646                 if (!parse_object(commit->object.sha1))
647                         continue;
648                 free(temp_commit_buffer);
649                 if (commit->buffer)
650                         p = commit->buffer;
651                 else {
652                         p = read_sha1_file(commit->object.sha1, &type, &size);
653                         if (!p)
654                                 continue;
655                         temp_commit_buffer = p;
656                 }
657                 if (!(p = strstr(p, "\n\n")))
658                         continue;
659                 if (!prefixcmp(p + 2, prefix)) {
660                         hashcpy(sha1, commit->object.sha1);
661                         retval = 0;
662                         break;
663                 }
664         }
665         free(temp_commit_buffer);
666         free_commit_list(list);
667         for (l = backup; l; l = l->next)
668                 clear_commit_marks(l->item, ONELINE_SEEN);
669         return retval;
670 }
671
672 /*
673  * This is like "get_sha1_basic()", except it allows "sha1 expressions",
674  * notably "xyz^" for "parent of xyz"
675  */
676 int get_sha1(const char *name, unsigned char *sha1)
677 {
678         unsigned unused;
679         return get_sha1_with_mode(name, sha1, &unused);
680 }
681
682 int get_sha1_with_mode(const char *name, unsigned char *sha1, unsigned *mode)
683 {
684         int ret, bracket_depth;
685         int namelen = strlen(name);
686         const char *cp;
687
688         *mode = S_IFINVALID;
689         ret = get_sha1_1(name, namelen, sha1);
690         if (!ret)
691                 return ret;
692         /* sha1:path --> object name of path in ent sha1
693          * :path -> object name of path in index
694          * :[0-3]:path -> object name of path in index at stage
695          */
696         if (name[0] == ':') {
697                 int stage = 0;
698                 struct cache_entry *ce;
699                 int pos;
700                 if (namelen > 2 && name[1] == '/')
701                         return get_sha1_oneline(name + 2, sha1);
702                 if (namelen < 3 ||
703                     name[2] != ':' ||
704                     name[1] < '0' || '3' < name[1])
705                         cp = name + 1;
706                 else {
707                         stage = name[1] - '0';
708                         cp = name + 3;
709                 }
710                 namelen = namelen - (cp - name);
711                 if (!active_cache)
712                         read_cache();
713                 pos = cache_name_pos(cp, namelen);
714                 if (pos < 0)
715                         pos = -pos - 1;
716                 while (pos < active_nr) {
717                         ce = active_cache[pos];
718                         if (ce_namelen(ce) != namelen ||
719                             memcmp(ce->name, cp, namelen))
720                                 break;
721                         if (ce_stage(ce) == stage) {
722                                 hashcpy(sha1, ce->sha1);
723                                 *mode = ce->ce_mode;
724                                 return 0;
725                         }
726                         pos++;
727                 }
728                 return -1;
729         }
730         for (cp = name, bracket_depth = 0; *cp; cp++) {
731                 if (*cp == '{')
732                         bracket_depth++;
733                 else if (bracket_depth && *cp == '}')
734                         bracket_depth--;
735                 else if (!bracket_depth && *cp == ':')
736                         break;
737         }
738         if (*cp == ':') {
739                 unsigned char tree_sha1[20];
740                 if (!get_sha1_1(name, cp-name, tree_sha1))
741                         return get_tree_entry(tree_sha1, cp+1, sha1,
742                                               mode);
743         }
744         return ret;
745 }