Code

1ae086ad1761e08a522138bf843c2ef1bb9c192f
[git.git] / builtin-rev-parse.c
1 /*
2  * rev-parse.c
3  *
4  * Copyright (C) Linus Torvalds, 2005
5  */
6 #include "cache.h"
7 #include "commit.h"
8 #include "refs.h"
9 #include "quote.h"
10 #include "builtin.h"
11 #include "parse-options.h"
13 #define DO_REVS         1
14 #define DO_NOREV        2
15 #define DO_FLAGS        4
16 #define DO_NONFLAGS     8
17 static int filter = ~0;
19 static const char *def;
21 #define NORMAL 0
22 #define REVERSED 1
23 static int show_type = NORMAL;
25 #define SHOW_SYMBOLIC_ASIS 1
26 #define SHOW_SYMBOLIC_FULL 2
27 static int symbolic;
28 static int abbrev;
29 static int output_sq;
31 static int revs_count;
33 /*
34  * Some arguments are relevant "revision" arguments,
35  * others are about output format or other details.
36  * This sorts it all out.
37  */
38 static int is_rev_argument(const char *arg)
39 {
40         static const char *rev_args[] = {
41                 "--all",
42                 "--bisect",
43                 "--dense",
44                 "--branches",
45                 "--header",
46                 "--max-age=",
47                 "--max-count=",
48                 "--min-age=",
49                 "--no-merges",
50                 "--objects",
51                 "--objects-edge",
52                 "--parents",
53                 "--pretty",
54                 "--remotes",
55                 "--sparse",
56                 "--tags",
57                 "--topo-order",
58                 "--date-order",
59                 "--unpacked",
60                 NULL
61         };
62         const char **p = rev_args;
64         /* accept -<digit>, like traditional "head" */
65         if ((*arg == '-') && isdigit(arg[1]))
66                 return 1;
68         for (;;) {
69                 const char *str = *p++;
70                 int len;
71                 if (!str)
72                         return 0;
73                 len = strlen(str);
74                 if (!strcmp(arg, str) ||
75                     (str[len-1] == '=' && !strncmp(arg, str, len)))
76                         return 1;
77         }
78 }
80 /* Output argument as a string, either SQ or normal */
81 static void show(const char *arg)
82 {
83         if (output_sq) {
84                 int sq = '\'', ch;
86                 putchar(sq);
87                 while ((ch = *arg++)) {
88                         if (ch == sq)
89                                 fputs("'\\'", stdout);
90                         putchar(ch);
91                 }
92                 putchar(sq);
93                 putchar(' ');
94         }
95         else
96                 puts(arg);
97 }
99 /* Like show(), but with a negation prefix according to type */
100 static void show_with_type(int type, const char *arg)
102         if (type != show_type)
103                 putchar('^');
104         show(arg);
107 /* Output a revision, only if filter allows it */
108 static void show_rev(int type, const unsigned char *sha1, const char *name)
110         if (!(filter & DO_REVS))
111                 return;
112         def = NULL;
113         revs_count++;
115         if (symbolic && name) {
116                 if (symbolic == SHOW_SYMBOLIC_FULL) {
117                         unsigned char discard[20];
118                         char *full;
120                         switch (dwim_ref(name, strlen(name), discard, &full)) {
121                         case 0:
122                                 /*
123                                  * Not found -- not a ref.  We could
124                                  * emit "name" here, but symbolic-full
125                                  * users are interested in finding the
126                                  * refs spelled in full, and they would
127                                  * need to filter non-refs if we did so.
128                                  */
129                                 break;
130                         case 1: /* happy */
131                                 show_with_type(type, full);
132                                 break;
133                         default: /* ambiguous */
134                                 error("refname '%s' is ambiguous", name);
135                                 break;
136                         }
137                 } else {
138                         show_with_type(type, name);
139                 }
140         }
141         else if (abbrev)
142                 show_with_type(type, find_unique_abbrev(sha1, abbrev));
143         else
144                 show_with_type(type, sha1_to_hex(sha1));
147 /* Output a flag, only if filter allows it. */
148 static int show_flag(const char *arg)
150         if (!(filter & DO_FLAGS))
151                 return 0;
152         if (filter & (is_rev_argument(arg) ? DO_REVS : DO_NOREV)) {
153                 show(arg);
154                 return 1;
155         }
156         return 0;
159 static void show_default(void)
161         const char *s = def;
163         if (s) {
164                 unsigned char sha1[20];
166                 def = NULL;
167                 if (!get_sha1(s, sha1)) {
168                         show_rev(NORMAL, sha1, s);
169                         return;
170                 }
171         }
174 static int show_reference(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
176         show_rev(NORMAL, sha1, refname);
177         return 0;
180 static void show_datestring(const char *flag, const char *datestr)
182         static char buffer[100];
184         /* date handling requires both flags and revs */
185         if ((filter & (DO_FLAGS | DO_REVS)) != (DO_FLAGS | DO_REVS))
186                 return;
187         snprintf(buffer, sizeof(buffer), "%s%lu", flag, approxidate(datestr));
188         show(buffer);
191 static int show_file(const char *arg)
193         show_default();
194         if ((filter & (DO_NONFLAGS|DO_NOREV)) == (DO_NONFLAGS|DO_NOREV)) {
195                 show(arg);
196                 return 1;
197         }
198         return 0;
201 static int try_difference(const char *arg)
203         char *dotdot;
204         unsigned char sha1[20];
205         unsigned char end[20];
206         const char *next;
207         const char *this;
208         int symmetric;
210         if (!(dotdot = strstr(arg, "..")))
211                 return 0;
212         next = dotdot + 2;
213         this = arg;
214         symmetric = (*next == '.');
216         *dotdot = 0;
217         next += symmetric;
219         if (!*next)
220                 next = "HEAD";
221         if (dotdot == arg)
222                 this = "HEAD";
223         if (!get_sha1(this, sha1) && !get_sha1(next, end)) {
224                 show_rev(NORMAL, end, next);
225                 show_rev(symmetric ? NORMAL : REVERSED, sha1, this);
226                 if (symmetric) {
227                         struct commit_list *exclude;
228                         struct commit *a, *b;
229                         a = lookup_commit_reference(sha1);
230                         b = lookup_commit_reference(end);
231                         exclude = get_merge_bases(a, b, 1);
232                         while (exclude) {
233                                 struct commit_list *n = exclude->next;
234                                 show_rev(REVERSED,
235                                          exclude->item->object.sha1,NULL);
236                                 free(exclude);
237                                 exclude = n;
238                         }
239                 }
240                 return 1;
241         }
242         *dotdot = '.';
243         return 0;
246 static int parseopt_dump(const struct option *o, const char *arg, int unset)
248         struct strbuf *parsed = o->value;
249         if (unset)
250                 strbuf_addf(parsed, " --no-%s", o->long_name);
251         else if (o->short_name)
252                 strbuf_addf(parsed, " -%c", o->short_name);
253         else
254                 strbuf_addf(parsed, " --%s", o->long_name);
255         if (arg) {
256                 strbuf_addch(parsed, ' ');
257                 sq_quote_buf(parsed, arg);
258         }
259         return 0;
262 static const char *skipspaces(const char *s)
264         while (isspace(*s))
265                 s++;
266         return s;
269 static int cmd_parseopt(int argc, const char **argv, const char *prefix)
271         static int keep_dashdash = 0;
272         static char const * const parseopt_usage[] = {
273                 "git-rev-parse --parseopt [options] -- [<args>...]",
274                 NULL
275         };
276         static struct option parseopt_opts[] = {
277                 OPT_BOOLEAN(0, "keep-dashdash", &keep_dashdash,
278                                         "keep the `--` passed as an arg"),
279                 OPT_END(),
280         };
282         struct strbuf sb, parsed;
283         const char **usage = NULL;
284         struct option *opts = NULL;
285         int onb = 0, osz = 0, unb = 0, usz = 0;
287         strbuf_init(&parsed, 0);
288         strbuf_addstr(&parsed, "set --");
289         argc = parse_options(argc, argv, parseopt_opts, parseopt_usage,
290                              PARSE_OPT_KEEP_DASHDASH);
291         if (argc < 1 || strcmp(argv[0], "--"))
292                 usage_with_options(parseopt_usage, parseopt_opts);
294         strbuf_init(&sb, 0);
295         /* get the usage up to the first line with a -- on it */
296         for (;;) {
297                 if (strbuf_getline(&sb, stdin, '\n') == EOF)
298                         die("premature end of input");
299                 ALLOC_GROW(usage, unb + 1, usz);
300                 if (!strcmp("--", sb.buf)) {
301                         if (unb < 1)
302                                 die("no usage string given before the `--' separator");
303                         usage[unb] = NULL;
304                         break;
305                 }
306                 usage[unb++] = strbuf_detach(&sb, NULL);
307         }
309         /* parse: (<short>|<short>,<long>|<long>)[=?]? SP+ <help> */
310         while (strbuf_getline(&sb, stdin, '\n') != EOF) {
311                 const char *s;
312                 struct option *o;
314                 if (!sb.len)
315                         continue;
317                 ALLOC_GROW(opts, onb + 1, osz);
318                 memset(opts + onb, 0, sizeof(opts[onb]));
320                 o = &opts[onb++];
321                 s = strchr(sb.buf, ' ');
322                 if (!s || *sb.buf == ' ') {
323                         o->type = OPTION_GROUP;
324                         o->help = xstrdup(skipspaces(sb.buf));
325                         continue;
326                 }
328                 o->type = OPTION_CALLBACK;
329                 o->help = xstrdup(skipspaces(s));
330                 o->value = &parsed;
331                 o->callback = &parseopt_dump;
332                 switch (s[-1]) {
333                 case '=':
334                         s--;
335                         break;
336                 case '?':
337                         o->flags = PARSE_OPT_OPTARG;
338                         s--;
339                         break;
340                 default:
341                         o->flags = PARSE_OPT_NOARG;
342                         break;
343                 }
345                 if (s - sb.buf == 1) /* short option only */
346                         o->short_name = *sb.buf;
347                 else if (sb.buf[1] != ',') /* long option only */
348                         o->long_name = xmemdupz(sb.buf, s - sb.buf);
349                 else {
350                         o->short_name = *sb.buf;
351                         o->long_name = xmemdupz(sb.buf + 2, s - sb.buf - 2);
352                 }
353         }
354         strbuf_release(&sb);
356         /* put an OPT_END() */
357         ALLOC_GROW(opts, onb + 1, osz);
358         memset(opts + onb, 0, sizeof(opts[onb]));
359         argc = parse_options(argc, argv, opts, usage,
360                              keep_dashdash ? PARSE_OPT_KEEP_DASHDASH : 0);
362         strbuf_addf(&parsed, " --");
363         sq_quote_argv(&parsed, argv, 0);
364         puts(parsed.buf);
365         return 0;
368 int cmd_rev_parse(int argc, const char **argv, const char *prefix)
370         int i, as_is = 0, verify = 0;
371         unsigned char sha1[20];
373         if (argc > 1 && !strcmp("--parseopt", argv[1]))
374                 return cmd_parseopt(argc - 1, argv + 1, prefix);
376         prefix = setup_git_directory();
377         git_config(git_default_config);
378         for (i = 1; i < argc; i++) {
379                 const char *arg = argv[i];
381                 if (as_is) {
382                         if (show_file(arg) && as_is < 2)
383                                 verify_filename(prefix, arg);
384                         continue;
385                 }
386                 if (!strcmp(arg,"-n")) {
387                         if (++i >= argc)
388                                 die("-n requires an argument");
389                         if ((filter & DO_FLAGS) && (filter & DO_REVS)) {
390                                 show(arg);
391                                 show(argv[i]);
392                         }
393                         continue;
394                 }
395                 if (!prefixcmp(arg, "-n")) {
396                         if ((filter & DO_FLAGS) && (filter & DO_REVS))
397                                 show(arg);
398                         continue;
399                 }
401                 if (*arg == '-') {
402                         if (!strcmp(arg, "--")) {
403                                 as_is = 2;
404                                 /* Pass on the "--" if we show anything but files.. */
405                                 if (filter & (DO_FLAGS | DO_REVS))
406                                         show_file(arg);
407                                 continue;
408                         }
409                         if (!strcmp(arg, "--default")) {
410                                 def = argv[i+1];
411                                 i++;
412                                 continue;
413                         }
414                         if (!strcmp(arg, "--revs-only")) {
415                                 filter &= ~DO_NOREV;
416                                 continue;
417                         }
418                         if (!strcmp(arg, "--no-revs")) {
419                                 filter &= ~DO_REVS;
420                                 continue;
421                         }
422                         if (!strcmp(arg, "--flags")) {
423                                 filter &= ~DO_NONFLAGS;
424                                 continue;
425                         }
426                         if (!strcmp(arg, "--no-flags")) {
427                                 filter &= ~DO_FLAGS;
428                                 continue;
429                         }
430                         if (!strcmp(arg, "--verify")) {
431                                 filter &= ~(DO_FLAGS|DO_NOREV);
432                                 verify = 1;
433                                 continue;
434                         }
435                         if (!strcmp(arg, "--short") ||
436                             !prefixcmp(arg, "--short=")) {
437                                 filter &= ~(DO_FLAGS|DO_NOREV);
438                                 verify = 1;
439                                 abbrev = DEFAULT_ABBREV;
440                                 if (arg[7] == '=')
441                                         abbrev = strtoul(arg + 8, NULL, 10);
442                                 if (abbrev < MINIMUM_ABBREV)
443                                         abbrev = MINIMUM_ABBREV;
444                                 else if (40 <= abbrev)
445                                         abbrev = 40;
446                                 continue;
447                         }
448                         if (!strcmp(arg, "--sq")) {
449                                 output_sq = 1;
450                                 continue;
451                         }
452                         if (!strcmp(arg, "--not")) {
453                                 show_type ^= REVERSED;
454                                 continue;
455                         }
456                         if (!strcmp(arg, "--symbolic")) {
457                                 symbolic = SHOW_SYMBOLIC_ASIS;
458                                 continue;
459                         }
460                         if (!strcmp(arg, "--symbolic-full-name")) {
461                                 symbolic = SHOW_SYMBOLIC_FULL;
462                                 continue;
463                         }
464                         if (!strcmp(arg, "--all")) {
465                                 for_each_ref(show_reference, NULL);
466                                 continue;
467                         }
468                         if (!strcmp(arg, "--branches")) {
469                                 for_each_branch_ref(show_reference, NULL);
470                                 continue;
471                         }
472                         if (!strcmp(arg, "--tags")) {
473                                 for_each_tag_ref(show_reference, NULL);
474                                 continue;
475                         }
476                         if (!strcmp(arg, "--remotes")) {
477                                 for_each_remote_ref(show_reference, NULL);
478                                 continue;
479                         }
480                         if (!strcmp(arg, "--show-prefix")) {
481                                 if (prefix)
482                                         puts(prefix);
483                                 continue;
484                         }
485                         if (!strcmp(arg, "--show-cdup")) {
486                                 const char *pfx = prefix;
487                                 if (!is_inside_work_tree()) {
488                                         const char *work_tree =
489                                                 get_git_work_tree();
490                                         if (work_tree)
491                                                 printf("%s\n", work_tree);
492                                         continue;
493                                 }
494                                 while (pfx) {
495                                         pfx = strchr(pfx, '/');
496                                         if (pfx) {
497                                                 pfx++;
498                                                 printf("../");
499                                         }
500                                 }
501                                 putchar('\n');
502                                 continue;
503                         }
504                         if (!strcmp(arg, "--git-dir")) {
505                                 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
506                                 static char cwd[PATH_MAX];
507                                 if (gitdir) {
508                                         puts(gitdir);
509                                         continue;
510                                 }
511                                 if (!prefix) {
512                                         puts(".git");
513                                         continue;
514                                 }
515                                 if (!getcwd(cwd, PATH_MAX))
516                                         die("unable to get current working directory");
517                                 printf("%s/.git\n", cwd);
518                                 continue;
519                         }
520                         if (!strcmp(arg, "--is-inside-git-dir")) {
521                                 printf("%s\n", is_inside_git_dir() ? "true"
522                                                 : "false");
523                                 continue;
524                         }
525                         if (!strcmp(arg, "--is-inside-work-tree")) {
526                                 printf("%s\n", is_inside_work_tree() ? "true"
527                                                 : "false");
528                                 continue;
529                         }
530                         if (!strcmp(arg, "--is-bare-repository")) {
531                                 printf("%s\n", is_bare_repository() ? "true"
532                                                 : "false");
533                                 continue;
534                         }
535                         if (!prefixcmp(arg, "--since=")) {
536                                 show_datestring("--max-age=", arg+8);
537                                 continue;
538                         }
539                         if (!prefixcmp(arg, "--after=")) {
540                                 show_datestring("--max-age=", arg+8);
541                                 continue;
542                         }
543                         if (!prefixcmp(arg, "--before=")) {
544                                 show_datestring("--min-age=", arg+9);
545                                 continue;
546                         }
547                         if (!prefixcmp(arg, "--until=")) {
548                                 show_datestring("--min-age=", arg+8);
549                                 continue;
550                         }
551                         if (show_flag(arg) && verify)
552                                 die("Needed a single revision");
553                         continue;
554                 }
556                 /* Not a flag argument */
557                 if (try_difference(arg))
558                         continue;
559                 if (!get_sha1(arg, sha1)) {
560                         show_rev(NORMAL, sha1, arg);
561                         continue;
562                 }
563                 if (*arg == '^' && !get_sha1(arg+1, sha1)) {
564                         show_rev(REVERSED, sha1, arg+1);
565                         continue;
566                 }
567                 as_is = 1;
568                 if (!show_file(arg))
569                         continue;
570                 if (verify)
571                         die("Needed a single revision");
572                 verify_filename(prefix, arg);
573         }
574         show_default();
575         if (verify && revs_count != 1)
576                 die("Needed a single revision");
577         return 0;