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