Merge branch 'master' of git://git.kernel.org/pub/scm/gitk/gitk
[git] / git.c
1 #include "builtin.h"
2 #include "exec_cmd.h"
3 #include "cache.h"
4 #include "quote.h"
5
6 const char git_usage_string[] =
7         "git [--version] [--exec-path[=GIT_EXEC_PATH]] [-p|--paginate|--no-pager] [--bare] [--git-dir=GIT_DIR] [--work-tree=GIT_WORK_TREE] [--help] COMMAND [ARGS]";
8
9 static void prepend_to_path(const char *dir, int len)
10 {
11         const char *old_path = getenv("PATH");
12         char *path;
13         int path_len = len;
14
15         if (!old_path)
16                 old_path = "/usr/local/bin:/usr/bin:/bin";
17
18         path_len = len + strlen(old_path) + 1;
19
20         path = xmalloc(path_len + 1);
21
22         memcpy(path, dir, len);
23         path[len] = ':';
24         memcpy(path + len + 1, old_path, path_len - len);
25
26         setenv("PATH", path, 1);
27
28         free(path);
29 }
30
31 static int handle_options(const char*** argv, int* argc, int* envchanged)
32 {
33         int handled = 0;
34
35         while (*argc > 0) {
36                 const char *cmd = (*argv)[0];
37                 if (cmd[0] != '-')
38                         break;
39
40                 /*
41                  * For legacy reasons, the "version" and "help"
42                  * commands can be written with "--" prepended
43                  * to make them look like flags.
44                  */
45                 if (!strcmp(cmd, "--help") || !strcmp(cmd, "--version"))
46                         break;
47
48                 /*
49                  * Check remaining flags.
50                  */
51                 if (!prefixcmp(cmd, "--exec-path")) {
52                         cmd += 11;
53                         if (*cmd == '=')
54                                 git_set_exec_path(cmd + 1);
55                         else {
56                                 puts(git_exec_path());
57                                 exit(0);
58                         }
59                 } else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
60                         setup_pager();
61                 } else if (!strcmp(cmd, "--no-pager")) {
62                         setenv("GIT_PAGER", "cat", 1);
63                         if (envchanged)
64                                 *envchanged = 1;
65                 } else if (!strcmp(cmd, "--git-dir")) {
66                         if (*argc < 2) {
67                                 fprintf(stderr, "No directory given for --git-dir.\n" );
68                                 usage(git_usage_string);
69                         }
70                         setenv(GIT_DIR_ENVIRONMENT, (*argv)[1], 1);
71                         if (envchanged)
72                                 *envchanged = 1;
73                         (*argv)++;
74                         (*argc)--;
75                         handled++;
76                 } else if (!prefixcmp(cmd, "--git-dir=")) {
77                         setenv(GIT_DIR_ENVIRONMENT, cmd + 10, 1);
78                         if (envchanged)
79                                 *envchanged = 1;
80                 } else if (!strcmp(cmd, "--work-tree")) {
81                         if (*argc < 2) {
82                                 fprintf(stderr, "No directory given for --work-tree.\n" );
83                                 usage(git_usage_string);
84                         }
85                         setenv(GIT_WORK_TREE_ENVIRONMENT, (*argv)[1], 1);
86                         if (envchanged)
87                                 *envchanged = 1;
88                         (*argv)++;
89                         (*argc)--;
90                 } else if (!prefixcmp(cmd, "--work-tree=")) {
91                         setenv(GIT_WORK_TREE_ENVIRONMENT, cmd + 12, 1);
92                         if (envchanged)
93                                 *envchanged = 1;
94                 } else if (!strcmp(cmd, "--bare")) {
95                         static char git_dir[PATH_MAX+1];
96                         is_bare_repository_cfg = 1;
97                         setenv(GIT_DIR_ENVIRONMENT, getcwd(git_dir, sizeof(git_dir)), 0);
98                         if (envchanged)
99                                 *envchanged = 1;
100                 } else {
101                         fprintf(stderr, "Unknown option: %s\n", cmd);
102                         usage(git_usage_string);
103                 }
104
105                 (*argv)++;
106                 (*argc)--;
107                 handled++;
108         }
109         return handled;
110 }
111
112 static const char *alias_command;
113 static char *alias_string;
114
115 static int git_alias_config(const char *var, const char *value)
116 {
117         if (!prefixcmp(var, "alias.") && !strcmp(var + 6, alias_command)) {
118                 alias_string = xstrdup(value);
119         }
120         return 0;
121 }
122
123 static int split_cmdline(char *cmdline, const char ***argv)
124 {
125         int src, dst, count = 0, size = 16;
126         char quoted = 0;
127
128         *argv = xmalloc(sizeof(char*) * size);
129
130         /* split alias_string */
131         (*argv)[count++] = cmdline;
132         for (src = dst = 0; cmdline[src];) {
133                 char c = cmdline[src];
134                 if (!quoted && isspace(c)) {
135                         cmdline[dst++] = 0;
136                         while (cmdline[++src]
137                                         && isspace(cmdline[src]))
138                                 ; /* skip */
139                         if (count >= size) {
140                                 size += 16;
141                                 *argv = xrealloc(*argv, sizeof(char*) * size);
142                         }
143                         (*argv)[count++] = cmdline + dst;
144                 } else if(!quoted && (c == '\'' || c == '"')) {
145                         quoted = c;
146                         src++;
147                 } else if (c == quoted) {
148                         quoted = 0;
149                         src++;
150                 } else {
151                         if (c == '\\' && quoted != '\'') {
152                                 src++;
153                                 c = cmdline[src];
154                                 if (!c) {
155                                         free(*argv);
156                                         *argv = NULL;
157                                         return error("cmdline ends with \\");
158                                 }
159                         }
160                         cmdline[dst++] = c;
161                         src++;
162                 }
163         }
164
165         cmdline[dst] = 0;
166
167         if (quoted) {
168                 free(*argv);
169                 *argv = NULL;
170                 return error("unclosed quote");
171         }
172
173         return count;
174 }
175
176 static int handle_alias(int *argcp, const char ***argv)
177 {
178         int nongit = 0, envchanged = 0, ret = 0, saved_errno = errno;
179         const char *subdir;
180         int count, option_count;
181         const char** new_argv;
182
183         subdir = setup_git_directory_gently(&nongit);
184
185         alias_command = (*argv)[0];
186         git_config(git_alias_config);
187         if (alias_string) {
188                 if (alias_string[0] == '!') {
189                         if (*argcp > 1) {
190                                 struct strbuf buf;
191
192                                 strbuf_init(&buf, PATH_MAX);
193                                 strbuf_addstr(&buf, alias_string);
194                                 sq_quote_argv(&buf, (*argv) + 1, *argcp - 1, PATH_MAX);
195                                 free(alias_string);
196                                 alias_string = buf.buf;
197                         }
198                         trace_printf("trace: alias to shell cmd: %s => %s\n",
199                                      alias_command, alias_string + 1);
200                         ret = system(alias_string + 1);
201                         if (ret >= 0 && WIFEXITED(ret) &&
202                             WEXITSTATUS(ret) != 127)
203                                 exit(WEXITSTATUS(ret));
204                         die("Failed to run '%s' when expanding alias '%s'\n",
205                             alias_string + 1, alias_command);
206                 }
207                 count = split_cmdline(alias_string, &new_argv);
208                 option_count = handle_options(&new_argv, &count, &envchanged);
209                 if (envchanged)
210                         die("alias '%s' changes environment variables\n"
211                                  "You can use '!git' in the alias to do this.",
212                                  alias_command);
213                 memmove(new_argv - option_count, new_argv,
214                                 count * sizeof(char *));
215                 new_argv -= option_count;
216
217                 if (count < 1)
218                         die("empty alias for %s", alias_command);
219
220                 if (!strcmp(alias_command, new_argv[0]))
221                         die("recursive alias: %s", alias_command);
222
223                 trace_argv_printf(new_argv, count,
224                                   "trace: alias expansion: %s =>",
225                                   alias_command);
226
227                 new_argv = xrealloc(new_argv, sizeof(char*) *
228                                     (count + *argcp + 1));
229                 /* insert after command name */
230                 memcpy(new_argv + count, *argv + 1, sizeof(char*) * *argcp);
231                 new_argv[count+*argcp] = NULL;
232
233                 *argv = new_argv;
234                 *argcp += count - 1;
235
236                 ret = 1;
237         }
238
239         if (subdir)
240                 chdir(subdir);
241
242         errno = saved_errno;
243
244         return ret;
245 }
246
247 const char git_version_string[] = GIT_VERSION;
248
249 #define RUN_SETUP       (1<<0)
250 #define USE_PAGER       (1<<1)
251 /*
252  * require working tree to be present -- anything uses this needs
253  * RUN_SETUP for reading from the configuration file.
254  */
255 #define NEED_WORK_TREE  (1<<2)
256
257 struct cmd_struct {
258         const char *cmd;
259         int (*fn)(int, const char **, const char *);
260         int option;
261 };
262
263 static int run_command(struct cmd_struct *p, int argc, const char **argv)
264 {
265         int status;
266         struct stat st;
267         const char *prefix;
268
269         prefix = NULL;
270         if (p->option & RUN_SETUP)
271                 prefix = setup_git_directory();
272         if (p->option & USE_PAGER)
273                 setup_pager();
274         if (p->option & NEED_WORK_TREE) {
275                 const char *work_tree = get_git_work_tree();
276                 const char *git_dir = get_git_dir();
277                 if (!is_absolute_path(git_dir))
278                         set_git_dir(make_absolute_path(git_dir));
279                 if (!work_tree || chdir(work_tree))
280                         die("%s must be run in a work tree", p->cmd);
281         }
282         trace_argv_printf(argv, argc, "trace: built-in: git");
283
284         status = p->fn(argc, argv, prefix);
285         if (status)
286                 return status;
287
288         /* Somebody closed stdout? */
289         if (fstat(fileno(stdout), &st))
290                 return 0;
291         /* Ignore write errors for pipes and sockets.. */
292         if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
293                 return 0;
294
295         /* Check for ENOSPC and EIO errors.. */
296         if (fflush(stdout))
297                 die("write failure on standard output: %s", strerror(errno));
298         if (ferror(stdout))
299                 die("unknown write failure on standard output");
300         if (fclose(stdout))
301                 die("close failed on standard output: %s", strerror(errno));
302         return 0;
303 }
304
305 static void handle_internal_command(int argc, const char **argv)
306 {
307         const char *cmd = argv[0];
308         static struct cmd_struct commands[] = {
309                 { "add", cmd_add, RUN_SETUP | NEED_WORK_TREE },
310                 { "annotate", cmd_annotate, RUN_SETUP },
311                 { "apply", cmd_apply },
312                 { "archive", cmd_archive },
313                 { "blame", cmd_blame, RUN_SETUP },
314                 { "branch", cmd_branch, RUN_SETUP },
315                 { "bundle", cmd_bundle },
316                 { "cat-file", cmd_cat_file, RUN_SETUP },
317                 { "checkout-index", cmd_checkout_index,
318                         RUN_SETUP | NEED_WORK_TREE},
319                 { "check-ref-format", cmd_check_ref_format },
320                 { "check-attr", cmd_check_attr, RUN_SETUP | NEED_WORK_TREE },
321                 { "cherry", cmd_cherry, RUN_SETUP },
322                 { "cherry-pick", cmd_cherry_pick, RUN_SETUP | NEED_WORK_TREE },
323                 { "commit-tree", cmd_commit_tree, RUN_SETUP },
324                 { "config", cmd_config },
325                 { "count-objects", cmd_count_objects, RUN_SETUP },
326                 { "describe", cmd_describe, RUN_SETUP },
327                 { "diff", cmd_diff },
328                 { "diff-files", cmd_diff_files },
329                 { "diff-index", cmd_diff_index, RUN_SETUP },
330                 { "diff-tree", cmd_diff_tree, RUN_SETUP },
331                 { "fetch", cmd_fetch, RUN_SETUP },
332                 { "fetch-pack", cmd_fetch_pack, RUN_SETUP },
333                 { "fetch--tool", cmd_fetch__tool, RUN_SETUP },
334                 { "fmt-merge-msg", cmd_fmt_merge_msg, RUN_SETUP },
335                 { "for-each-ref", cmd_for_each_ref, RUN_SETUP },
336                 { "format-patch", cmd_format_patch, RUN_SETUP },
337                 { "fsck", cmd_fsck, RUN_SETUP },
338                 { "fsck-objects", cmd_fsck, RUN_SETUP },
339                 { "gc", cmd_gc, RUN_SETUP },
340                 { "get-tar-commit-id", cmd_get_tar_commit_id },
341                 { "grep", cmd_grep, RUN_SETUP | USE_PAGER },
342                 { "help", cmd_help },
343 #ifndef NO_CURL
344                 { "http-fetch", cmd_http_fetch, RUN_SETUP },
345 #endif
346                 { "init", cmd_init_db },
347                 { "init-db", cmd_init_db },
348                 { "log", cmd_log, RUN_SETUP | USE_PAGER },
349                 { "ls-files", cmd_ls_files, RUN_SETUP },
350                 { "ls-tree", cmd_ls_tree, RUN_SETUP },
351                 { "mailinfo", cmd_mailinfo },
352                 { "mailsplit", cmd_mailsplit },
353                 { "merge-base", cmd_merge_base, RUN_SETUP },
354                 { "merge-file", cmd_merge_file },
355                 { "mv", cmd_mv, RUN_SETUP | NEED_WORK_TREE },
356                 { "name-rev", cmd_name_rev, RUN_SETUP },
357                 { "pack-objects", cmd_pack_objects, RUN_SETUP },
358                 { "pickaxe", cmd_blame, RUN_SETUP },
359                 { "prune", cmd_prune, RUN_SETUP },
360                 { "prune-packed", cmd_prune_packed, RUN_SETUP },
361                 { "push", cmd_push, RUN_SETUP },
362                 { "read-tree", cmd_read_tree, RUN_SETUP },
363                 { "reflog", cmd_reflog, RUN_SETUP },
364                 { "repo-config", cmd_config },
365                 { "rerere", cmd_rerere, RUN_SETUP },
366                 { "reset", cmd_reset, RUN_SETUP },
367                 { "rev-list", cmd_rev_list, RUN_SETUP },
368                 { "rev-parse", cmd_rev_parse, RUN_SETUP },
369                 { "revert", cmd_revert, RUN_SETUP | NEED_WORK_TREE },
370                 { "rm", cmd_rm, RUN_SETUP | NEED_WORK_TREE },
371                 { "runstatus", cmd_runstatus, RUN_SETUP | NEED_WORK_TREE },
372                 { "shortlog", cmd_shortlog, RUN_SETUP | USE_PAGER },
373                 { "show-branch", cmd_show_branch, RUN_SETUP },
374                 { "show", cmd_show, RUN_SETUP | USE_PAGER },
375                 { "stripspace", cmd_stripspace },
376                 { "symbolic-ref", cmd_symbolic_ref, RUN_SETUP },
377                 { "tag", cmd_tag, RUN_SETUP },
378                 { "tar-tree", cmd_tar_tree },
379                 { "unpack-objects", cmd_unpack_objects, RUN_SETUP },
380                 { "update-index", cmd_update_index, RUN_SETUP },
381                 { "update-ref", cmd_update_ref, RUN_SETUP },
382                 { "upload-archive", cmd_upload_archive },
383                 { "verify-tag", cmd_verify_tag, RUN_SETUP },
384                 { "version", cmd_version },
385                 { "whatchanged", cmd_whatchanged, RUN_SETUP | USE_PAGER },
386                 { "write-tree", cmd_write_tree, RUN_SETUP },
387                 { "verify-pack", cmd_verify_pack },
388                 { "show-ref", cmd_show_ref, RUN_SETUP },
389                 { "pack-refs", cmd_pack_refs, RUN_SETUP },
390         };
391         int i;
392
393         /* Turn "git cmd --help" into "git help cmd" */
394         if (argc > 1 && !strcmp(argv[1], "--help")) {
395                 argv[1] = argv[0];
396                 argv[0] = cmd = "help";
397         }
398
399         for (i = 0; i < ARRAY_SIZE(commands); i++) {
400                 struct cmd_struct *p = commands+i;
401                 if (strcmp(p->cmd, cmd))
402                         continue;
403                 exit(run_command(p, argc, argv));
404         }
405 }
406
407 int main(int argc, const char **argv)
408 {
409         const char *cmd = argv[0] ? argv[0] : "git-help";
410         char *slash = strrchr(cmd, '/');
411         const char *exec_path = NULL;
412         int done_alias = 0;
413
414         /*
415          * Take the basename of argv[0] as the command
416          * name, and the dirname as the default exec_path
417          * if we don't have anything better.
418          */
419         if (slash) {
420                 *slash++ = 0;
421                 if (*cmd == '/')
422                         exec_path = cmd;
423                 else
424                         exec_path = xstrdup(make_absolute_path(cmd));
425                 cmd = slash;
426         }
427
428         /*
429          * "git-xxxx" is the same as "git xxxx", but we obviously:
430          *
431          *  - cannot take flags in between the "git" and the "xxxx".
432          *  - cannot execute it externally (since it would just do
433          *    the same thing over again)
434          *
435          * So we just directly call the internal command handler, and
436          * die if that one cannot handle it.
437          */
438         if (!prefixcmp(cmd, "git-")) {
439                 cmd += 4;
440                 argv[0] = cmd;
441                 handle_internal_command(argc, argv);
442                 die("cannot handle %s internally", cmd);
443         }
444
445         /* Look for flags.. */
446         argv++;
447         argc--;
448         handle_options(&argv, &argc, NULL);
449         if (argc > 0) {
450                 if (!prefixcmp(argv[0], "--"))
451                         argv[0] += 2;
452         } else {
453                 /* Default command: "help" */
454                 argv[0] = "help";
455                 argc = 1;
456         }
457         cmd = argv[0];
458
459         /*
460          * We execute external git command via execv_git_cmd(),
461          * which looks at "--exec-path" option, GIT_EXEC_PATH
462          * environment, and $(gitexecdir) in Makefile while built,
463          * in this order.  For scripted commands, we prepend
464          * the value of the exec_path variable to the PATH.
465          */
466         if (exec_path)
467                 prepend_to_path(exec_path, strlen(exec_path));
468         exec_path = git_exec_path();
469         prepend_to_path(exec_path, strlen(exec_path));
470
471         while (1) {
472                 /* See if it's an internal command */
473                 handle_internal_command(argc, argv);
474
475                 /* .. then try the external ones */
476                 execv_git_cmd(argv);
477
478                 /* It could be an alias -- this works around the insanity
479                  * of overriding "git log" with "git show" by having
480                  * alias.log = show
481                  */
482                 if (done_alias || !handle_alias(&argc, &argv))
483                         break;
484                 done_alias = 1;
485         }
486
487         if (errno == ENOENT) {
488                 if (done_alias) {
489                         fprintf(stderr, "Expansion of alias '%s' failed; "
490                                 "'%s' is not a git-command\n",
491                                 cmd, argv[0]);
492                         exit(1);
493                 }
494                 help_unknown_cmd(cmd);
495         }
496
497         fprintf(stderr, "Failed to run command '%s': %s\n",
498                 cmd, strerror(errno));
499
500         return 1;
501 }