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"
12
13#define DO_REVS 1
14#define DO_NOREV 2
15#define DO_FLAGS 4
16#define DO_NONFLAGS 8
17static int filter = ~0;
18
19static const char *def;
20
21#define NORMAL 0
22#define REVERSED 1
23static int show_type = NORMAL;
24
25#define SHOW_SYMBOLIC_ASIS 1
26#define SHOW_SYMBOLIC_FULL 2
27static int symbolic;
28static int abbrev;
29static int abbrev_ref;
30static int abbrev_ref_strict;
31static int output_sq;
32
33static int stuck_long;
34
35/*
36 * Some arguments are relevant "revision" arguments,
37 * others are about output format or other details.
38 * This sorts it all out.
39 */
40static int is_rev_argument(const char *arg)
41{
42 static const char *rev_args[] = {
43 "--all",
44 "--bisect",
45 "--dense",
46 "--branches=",
47 "--branches",
48 "--header",
49 "--ignore-missing",
50 "--max-age=",
51 "--max-count=",
52 "--min-age=",
53 "--no-merges",
54 "--min-parents=",
55 "--no-min-parents",
56 "--max-parents=",
57 "--no-max-parents",
58 "--objects",
59 "--objects-edge",
60 "--parents",
61 "--pretty",
62 "--remotes=",
63 "--remotes",
64 "--glob=",
65 "--sparse",
66 "--tags=",
67 "--tags",
68 "--topo-order",
69 "--date-order",
70 "--unpacked",
71 NULL
72 };
73 const char **p = rev_args;
74
75 /* accept -<digit>, like traditional "head" */
76 if ((*arg == '-') && isdigit(arg[1]))
77 return 1;
78
79 for (;;) {
80 const char *str = *p++;
81 int len;
82 if (!str)
83 return 0;
84 len = strlen(str);
85 if (!strcmp(arg, str) ||
86 (str[len-1] == '=' && !strncmp(arg, str, len)))
87 return 1;
88 }
89}
90
91/* Output argument as a string, either SQ or normal */
92static void show(const char *arg)
93{
94 if (output_sq) {
95 int sq = '\'', ch;
96
97 putchar(sq);
98 while ((ch = *arg++)) {
99 if (ch == sq)
100 fputs("'\\'", stdout);
101 putchar(ch);
102 }
103 putchar(sq);
104 putchar(' ');
105 }
106 else
107 puts(arg);
108}
109
110/* Like show(), but with a negation prefix according to type */
111static void show_with_type(int type, const char *arg)
112{
113 if (type != show_type)
114 putchar('^');
115 show(arg);
116}
117
118/* Output a revision, only if filter allows it */
119static void show_rev(int type, const unsigned char *sha1, const char *name)
120{
121 if (!(filter & DO_REVS))
122 return;
123 def = NULL;
124
125 if ((symbolic || abbrev_ref) && name) {
126 if (symbolic == SHOW_SYMBOLIC_FULL || abbrev_ref) {
127 unsigned char discard[20];
128 char *full;
129
130 switch (dwim_ref(name, strlen(name), discard, &full)) {
131 case 0:
132 /*
133 * Not found -- not a ref. We could
134 * emit "name" here, but symbolic-full
135 * users are interested in finding the
136 * refs spelled in full, and they would
137 * need to filter non-refs if we did so.
138 */
139 break;
140 case 1: /* happy */
141 if (abbrev_ref)
142 full = shorten_unambiguous_ref(full,
143 abbrev_ref_strict);
144 show_with_type(type, full);
145 break;
146 default: /* ambiguous */
147 error("refname '%s' is ambiguous", name);
148 break;
149 }
150 } else {
151 show_with_type(type, name);
152 }
153 }
154 else if (abbrev)
155 show_with_type(type, find_unique_abbrev(sha1, abbrev));
156 else
157 show_with_type(type, sha1_to_hex(sha1));
158}
159
160/* Output a flag, only if filter allows it. */
161static int show_flag(const char *arg)
162{
163 if (!(filter & DO_FLAGS))
164 return 0;
165 if (filter & (is_rev_argument(arg) ? DO_REVS : DO_NOREV)) {
166 show(arg);
167 return 1;
168 }
169 return 0;
170}
171
172static int show_default(void)
173{
174 const char *s = def;
175
176 if (s) {
177 unsigned char sha1[20];
178
179 def = NULL;
180 if (!get_sha1(s, sha1)) {
181 show_rev(NORMAL, sha1, s);
182 return 1;
183 }
184 }
185 return 0;
186}
187
188static int show_reference(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
189{
190 show_rev(NORMAL, sha1, refname);
191 return 0;
192}
193
194static int anti_reference(const char *refname, const unsigned char *sha1, int flag, void *cb_data)
195{
196 show_rev(REVERSED, sha1, refname);
197 return 0;
198}
199
200static int show_abbrev(const unsigned char *sha1, void *cb_data)
201{
202 show_rev(NORMAL, sha1, NULL);
203 return 0;
204}
205
206static void show_datestring(const char *flag, const char *datestr)
207{
208 static char buffer[100];
209
210 /* date handling requires both flags and revs */
211 if ((filter & (DO_FLAGS | DO_REVS)) != (DO_FLAGS | DO_REVS))
212 return;
213 snprintf(buffer, sizeof(buffer), "%s%lu", flag, approxidate(datestr));
214 show(buffer);
215}
216
217static int show_file(const char *arg, int output_prefix)
218{
219 show_default();
220 if ((filter & (DO_NONFLAGS|DO_NOREV)) == (DO_NONFLAGS|DO_NOREV)) {
221 if (output_prefix) {
222 const char *prefix = startup_info->prefix;
223 show(prefix_filename(prefix,
224 prefix ? strlen(prefix) : 0,
225 arg));
226 } else
227 show(arg);
228 return 1;
229 }
230 return 0;
231}
232
233static int try_difference(const char *arg)
234{
235 char *dotdot;
236 unsigned char sha1[20];
237 unsigned char end[20];
238 const char *next;
239 const char *this;
240 int symmetric;
241 static const char head_by_default[] = "HEAD";
242
243 if (!(dotdot = strstr(arg, "..")))
244 return 0;
245 next = dotdot + 2;
246 this = arg;
247 symmetric = (*next == '.');
248
249 *dotdot = 0;
250 next += symmetric;
251
252 if (!*next)
253 next = head_by_default;
254 if (dotdot == arg)
255 this = head_by_default;
256
257 if (this == head_by_default && next == head_by_default &&
258 !symmetric) {
259 /*
260 * Just ".."? That is not a range but the
261 * pathspec for the parent directory.
262 */
263 *dotdot = '.';
264 return 0;
265 }
266
267 if (!get_sha1_committish(this, sha1) && !get_sha1_committish(next, end)) {
268 show_rev(NORMAL, end, next);
269 show_rev(symmetric ? NORMAL : REVERSED, sha1, this);
270 if (symmetric) {
271 struct commit_list *exclude;
272 struct commit *a, *b;
273 a = lookup_commit_reference(sha1);
274 b = lookup_commit_reference(end);
275 exclude = get_merge_bases(a, b, 1);
276 while (exclude) {
277 struct commit_list *n = exclude->next;
278 show_rev(REVERSED,
279 exclude->item->object.sha1,NULL);
280 free(exclude);
281 exclude = n;
282 }
283 }
284 return 1;
285 }
286 *dotdot = '.';
287 return 0;
288}
289
290static int try_parent_shorthands(const char *arg)
291{
292 char *dotdot;
293 unsigned char sha1[20];
294 struct commit *commit;
295 struct commit_list *parents;
296 int parents_only;
297
298 if ((dotdot = strstr(arg, "^!")))
299 parents_only = 0;
300 else if ((dotdot = strstr(arg, "^@")))
301 parents_only = 1;
302
303 if (!dotdot || dotdot[2])
304 return 0;
305
306 *dotdot = 0;
307 if (get_sha1_committish(arg, sha1))
308 return 0;
309
310 if (!parents_only)
311 show_rev(NORMAL, sha1, arg);
312 commit = lookup_commit_reference(sha1);
313 for (parents = commit->parents; parents; parents = parents->next)
314 show_rev(parents_only ? NORMAL : REVERSED,
315 parents->item->object.sha1, arg);
316
317 return 1;
318}
319
320static int parseopt_dump(const struct option *o, const char *arg, int unset)
321{
322 struct strbuf *parsed = o->value;
323 if (unset)
324 strbuf_addf(parsed, " --no-%s", o->long_name);
325 else if (o->short_name && (o->long_name == NULL || !stuck_long))
326 strbuf_addf(parsed, " -%c", o->short_name);
327 else
328 strbuf_addf(parsed, " --%s", o->long_name);
329 if (arg) {
330 if (!stuck_long)
331 strbuf_addch(parsed, ' ');
332 else if (o->long_name)
333 strbuf_addch(parsed, '=');
334 sq_quote_buf(parsed, arg);
335 }
336 return 0;
337}
338
339static const char *skipspaces(const char *s)
340{
341 while (isspace(*s))
342 s++;
343 return s;
344}
345
346static int cmd_parseopt(int argc, const char **argv, const char *prefix)
347{
348 static int keep_dashdash = 0, stop_at_non_option = 0;
349 static char const * const parseopt_usage[] = {
350 N_("git rev-parse --parseopt [options] -- [<args>...]"),
351 NULL
352 };
353 static struct option parseopt_opts[] = {
354 OPT_BOOL(0, "keep-dashdash", &keep_dashdash,
355 N_("keep the `--` passed as an arg")),
356 OPT_BOOL(0, "stop-at-non-option", &stop_at_non_option,
357 N_("stop parsing after the "
358 "first non-option argument")),
359 OPT_BOOL(0, "stuck-long", &stuck_long,
360 N_("output in stuck long form")),
361 OPT_END(),
362 };
363
364 struct strbuf sb = STRBUF_INIT, parsed = STRBUF_INIT;
365 const char **usage = NULL;
366 struct option *opts = NULL;
367 int onb = 0, osz = 0, unb = 0, usz = 0;
368
369 strbuf_addstr(&parsed, "set --");
370 argc = parse_options(argc, argv, prefix, parseopt_opts, parseopt_usage,
371 PARSE_OPT_KEEP_DASHDASH);
372 if (argc < 1 || strcmp(argv[0], "--"))
373 usage_with_options(parseopt_usage, parseopt_opts);
374
375 /* get the usage up to the first line with a -- on it */
376 for (;;) {
377 if (strbuf_getline(&sb, stdin, '\n') == EOF)
378 die("premature end of input");
379 ALLOC_GROW(usage, unb + 1, usz);
380 if (!strcmp("--", sb.buf)) {
381 if (unb < 1)
382 die("no usage string given before the `--' separator");
383 usage[unb] = NULL;
384 break;
385 }
386 usage[unb++] = strbuf_detach(&sb, NULL);
387 }
388
389 /* parse: (<short>|<short>,<long>|<long>)[=?]? SP+ <help> */
390 while (strbuf_getline(&sb, stdin, '\n') != EOF) {
391 const char *s;
392 struct option *o;
393
394 if (!sb.len)
395 continue;
396
397 ALLOC_GROW(opts, onb + 1, osz);
398 memset(opts + onb, 0, sizeof(opts[onb]));
399
400 o = &opts[onb++];
401 s = strchr(sb.buf, ' ');
402 if (!s || *sb.buf == ' ') {
403 o->type = OPTION_GROUP;
404 o->help = xstrdup(skipspaces(sb.buf));
405 continue;
406 }
407
408 o->type = OPTION_CALLBACK;
409 o->help = xstrdup(skipspaces(s));
410 o->value = &parsed;
411 o->flags = PARSE_OPT_NOARG;
412 o->callback = &parseopt_dump;
413 while (s > sb.buf && strchr("*=?!", s[-1])) {
414 switch (*--s) {
415 case '=':
416 o->flags &= ~PARSE_OPT_NOARG;
417 break;
418 case '?':
419 o->flags &= ~PARSE_OPT_NOARG;
420 o->flags |= PARSE_OPT_OPTARG;
421 break;
422 case '!':
423 o->flags |= PARSE_OPT_NONEG;
424 break;
425 case '*':
426 o->flags |= PARSE_OPT_HIDDEN;
427 break;
428 }
429 }
430
431 if (s - sb.buf == 1) /* short option only */
432 o->short_name = *sb.buf;
433 else if (sb.buf[1] != ',') /* long option only */
434 o->long_name = xmemdupz(sb.buf, s - sb.buf);
435 else {
436 o->short_name = *sb.buf;
437 o->long_name = xmemdupz(sb.buf + 2, s - sb.buf - 2);
438 }
439 }
440 strbuf_release(&sb);
441
442 /* put an OPT_END() */
443 ALLOC_GROW(opts, onb + 1, osz);
444 memset(opts + onb, 0, sizeof(opts[onb]));
445 argc = parse_options(argc, argv, prefix, opts, usage,
446 (keep_dashdash ? PARSE_OPT_KEEP_DASHDASH : 0) |
447 (stop_at_non_option ? PARSE_OPT_STOP_AT_NON_OPTION : 0) |
448 PARSE_OPT_SHELL_EVAL);
449
450 strbuf_addf(&parsed, " --");
451 sq_quote_argv(&parsed, argv, 0);
452 puts(parsed.buf);
453 return 0;
454}
455
456static int cmd_sq_quote(int argc, const char **argv)
457{
458 struct strbuf buf = STRBUF_INIT;
459
460 if (argc)
461 sq_quote_argv(&buf, argv, 0);
462 printf("%s\n", buf.buf);
463 strbuf_release(&buf);
464
465 return 0;
466}
467
468static void die_no_single_rev(int quiet)
469{
470 if (quiet)
471 exit(1);
472 else
473 die("Needed a single revision");
474}
475
476static const char builtin_rev_parse_usage[] =
477N_("git rev-parse --parseopt [options] -- [<args>...]\n"
478 " or: git rev-parse --sq-quote [<arg>...]\n"
479 " or: git rev-parse [options] [<arg>...]\n"
480 "\n"
481 "Run \"git rev-parse --parseopt -h\" for more information on the first usage.");
482
483int cmd_rev_parse(int argc, const char **argv, const char *prefix)
484{
485 int i, as_is = 0, verify = 0, quiet = 0, revs_count = 0, type = 0;
486 int output_prefix = 0;
487 unsigned char sha1[20];
488 const char *name = NULL;
489
490 if (argc > 1 && !strcmp("--parseopt", argv[1]))
491 return cmd_parseopt(argc - 1, argv + 1, prefix);
492
493 if (argc > 1 && !strcmp("--sq-quote", argv[1]))
494 return cmd_sq_quote(argc - 2, argv + 2);
495
496 if (argc > 1 && !strcmp("-h", argv[1]))
497 usage(builtin_rev_parse_usage);
498
499 prefix = setup_git_directory();
500 git_config(git_default_config, NULL);
501 for (i = 1; i < argc; i++) {
502 const char *arg = argv[i];
503
504 if (as_is) {
505 if (show_file(arg, output_prefix) && as_is < 2)
506 verify_filename(prefix, arg, 0);
507 continue;
508 }
509 if (!strcmp(arg,"-n")) {
510 if (++i >= argc)
511 die("-n requires an argument");
512 if ((filter & DO_FLAGS) && (filter & DO_REVS)) {
513 show(arg);
514 show(argv[i]);
515 }
516 continue;
517 }
518 if (!prefixcmp(arg, "-n")) {
519 if ((filter & DO_FLAGS) && (filter & DO_REVS))
520 show(arg);
521 continue;
522 }
523
524 if (*arg == '-') {
525 if (!strcmp(arg, "--")) {
526 as_is = 2;
527 /* Pass on the "--" if we show anything but files.. */
528 if (filter & (DO_FLAGS | DO_REVS))
529 show_file(arg, 0);
530 continue;
531 }
532 if (!strcmp(arg, "--default")) {
533 def = argv[i+1];
534 i++;
535 continue;
536 }
537 if (!strcmp(arg, "--prefix")) {
538 prefix = argv[i+1];
539 startup_info->prefix = prefix;
540 output_prefix = 1;
541 i++;
542 continue;
543 }
544 if (!strcmp(arg, "--revs-only")) {
545 filter &= ~DO_NOREV;
546 continue;
547 }
548 if (!strcmp(arg, "--no-revs")) {
549 filter &= ~DO_REVS;
550 continue;
551 }
552 if (!strcmp(arg, "--flags")) {
553 filter &= ~DO_NONFLAGS;
554 continue;
555 }
556 if (!strcmp(arg, "--no-flags")) {
557 filter &= ~DO_FLAGS;
558 continue;
559 }
560 if (!strcmp(arg, "--verify")) {
561 filter &= ~(DO_FLAGS|DO_NOREV);
562 verify = 1;
563 continue;
564 }
565 if (!strcmp(arg, "--quiet") || !strcmp(arg, "-q")) {
566 quiet = 1;
567 continue;
568 }
569 if (!strcmp(arg, "--short") ||
570 !prefixcmp(arg, "--short=")) {
571 filter &= ~(DO_FLAGS|DO_NOREV);
572 verify = 1;
573 abbrev = DEFAULT_ABBREV;
574 if (arg[7] == '=')
575 abbrev = strtoul(arg + 8, NULL, 10);
576 if (abbrev < MINIMUM_ABBREV)
577 abbrev = MINIMUM_ABBREV;
578 else if (40 <= abbrev)
579 abbrev = 40;
580 continue;
581 }
582 if (!strcmp(arg, "--sq")) {
583 output_sq = 1;
584 continue;
585 }
586 if (!strcmp(arg, "--not")) {
587 show_type ^= REVERSED;
588 continue;
589 }
590 if (!strcmp(arg, "--symbolic")) {
591 symbolic = SHOW_SYMBOLIC_ASIS;
592 continue;
593 }
594 if (!strcmp(arg, "--symbolic-full-name")) {
595 symbolic = SHOW_SYMBOLIC_FULL;
596 continue;
597 }
598 if (!prefixcmp(arg, "--abbrev-ref") &&
599 (!arg[12] || arg[12] == '=')) {
600 abbrev_ref = 1;
601 abbrev_ref_strict = warn_ambiguous_refs;
602 if (arg[12] == '=') {
603 if (!strcmp(arg + 13, "strict"))
604 abbrev_ref_strict = 1;
605 else if (!strcmp(arg + 13, "loose"))
606 abbrev_ref_strict = 0;
607 else
608 die("unknown mode for %s", arg);
609 }
610 continue;
611 }
612 if (!strcmp(arg, "--all")) {
613 for_each_ref(show_reference, NULL);
614 continue;
615 }
616 if (!prefixcmp(arg, "--disambiguate=")) {
617 for_each_abbrev(arg + 15, show_abbrev, NULL);
618 continue;
619 }
620 if (!strcmp(arg, "--bisect")) {
621 for_each_ref_in("refs/bisect/bad", show_reference, NULL);
622 for_each_ref_in("refs/bisect/good", anti_reference, NULL);
623 continue;
624 }
625 if (!prefixcmp(arg, "--branches=")) {
626 for_each_glob_ref_in(show_reference, arg + 11,
627 "refs/heads/", NULL);
628 continue;
629 }
630 if (!strcmp(arg, "--branches")) {
631 for_each_branch_ref(show_reference, NULL);
632 continue;
633 }
634 if (!prefixcmp(arg, "--tags=")) {
635 for_each_glob_ref_in(show_reference, arg + 7,
636 "refs/tags/", NULL);
637 continue;
638 }
639 if (!strcmp(arg, "--tags")) {
640 for_each_tag_ref(show_reference, NULL);
641 continue;
642 }
643 if (!prefixcmp(arg, "--glob=")) {
644 for_each_glob_ref(show_reference, arg + 7, NULL);
645 continue;
646 }
647 if (!prefixcmp(arg, "--remotes=")) {
648 for_each_glob_ref_in(show_reference, arg + 10,
649 "refs/remotes/", NULL);
650 continue;
651 }
652 if (!strcmp(arg, "--remotes")) {
653 for_each_remote_ref(show_reference, NULL);
654 continue;
655 }
656 if (!strcmp(arg, "--local-env-vars")) {
657 int i;
658 for (i = 0; local_repo_env[i]; i++)
659 printf("%s\n", local_repo_env[i]);
660 continue;
661 }
662 if (!strcmp(arg, "--show-toplevel")) {
663 const char *work_tree = get_git_work_tree();
664 if (work_tree)
665 puts(work_tree);
666 continue;
667 }
668 if (!strcmp(arg, "--show-prefix")) {
669 if (prefix)
670 puts(prefix);
671 else
672 putchar('\n');
673 continue;
674 }
675 if (!strcmp(arg, "--show-cdup")) {
676 const char *pfx = prefix;
677 if (!is_inside_work_tree()) {
678 const char *work_tree =
679 get_git_work_tree();
680 if (work_tree)
681 printf("%s\n", work_tree);
682 continue;
683 }
684 while (pfx) {
685 pfx = strchr(pfx, '/');
686 if (pfx) {
687 pfx++;
688 printf("../");
689 }
690 }
691 putchar('\n');
692 continue;
693 }
694 if (!strcmp(arg, "--git-dir")) {
695 const char *gitdir = getenv(GIT_DIR_ENVIRONMENT);
696 static char cwd[PATH_MAX];
697 int len;
698 if (gitdir) {
699 puts(gitdir);
700 continue;
701 }
702 if (!prefix) {
703 puts(".git");
704 continue;
705 }
706 if (!getcwd(cwd, PATH_MAX))
707 die_errno("unable to get current working directory");
708 len = strlen(cwd);
709 printf("%s%s.git\n", cwd, len && cwd[len-1] != '/' ? "/" : "");
710 continue;
711 }
712 if (!strcmp(arg, "--resolve-git-dir")) {
713 const char *gitdir = resolve_gitdir(argv[i+1]);
714 if (!gitdir)
715 die("not a gitdir '%s'", argv[i+1]);
716 puts(gitdir);
717 continue;
718 }
719 if (!strcmp(arg, "--is-inside-git-dir")) {
720 printf("%s\n", is_inside_git_dir() ? "true"
721 : "false");
722 continue;
723 }
724 if (!strcmp(arg, "--is-inside-work-tree")) {
725 printf("%s\n", is_inside_work_tree() ? "true"
726 : "false");
727 continue;
728 }
729 if (!strcmp(arg, "--is-bare-repository")) {
730 printf("%s\n", is_bare_repository() ? "true"
731 : "false");
732 continue;
733 }
734 if (!prefixcmp(arg, "--since=")) {
735 show_datestring("--max-age=", arg+8);
736 continue;
737 }
738 if (!prefixcmp(arg, "--after=")) {
739 show_datestring("--max-age=", arg+8);
740 continue;
741 }
742 if (!prefixcmp(arg, "--before=")) {
743 show_datestring("--min-age=", arg+9);
744 continue;
745 }
746 if (!prefixcmp(arg, "--until=")) {
747 show_datestring("--min-age=", arg+8);
748 continue;
749 }
750 if (show_flag(arg) && verify)
751 die_no_single_rev(quiet);
752 continue;
753 }
754
755 /* Not a flag argument */
756 if (try_difference(arg))
757 continue;
758 if (try_parent_shorthands(arg))
759 continue;
760 name = arg;
761 type = NORMAL;
762 if (*arg == '^') {
763 name++;
764 type = REVERSED;
765 }
766 if (!get_sha1(name, sha1)) {
767 if (verify)
768 revs_count++;
769 else
770 show_rev(type, sha1, name);
771 continue;
772 }
773 if (verify)
774 die_no_single_rev(quiet);
775 as_is = 1;
776 if (!show_file(arg, output_prefix))
777 continue;
778 verify_filename(prefix, arg, 1);
779 }
780 if (verify) {
781 if (revs_count == 1) {
782 show_rev(type, sha1, name);
783 return 0;
784 } else if (revs_count == 0 && show_default())
785 return 0;
786 die_no_single_rev(quiet);
787 } else
788 show_default();
789 return 0;
790}