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