GIT v1.3.0-rc4
[git/mingw/4msysgit/kblees.git] / exec_cmd.c
blob590e738969ecfdd7ff2f23da36cdac917215313d
1 #include "cache.h"
2 #include "exec_cmd.h"
3 #define MAX_ARGS 32
5 extern char **environ;
6 static const char *builtin_exec_path = GIT_EXEC_PATH;
7 static const char *current_exec_path = NULL;
9 void git_set_exec_path(const char *exec_path)
11 current_exec_path = exec_path;
15 /* Returns the highest-priority, location to look for git programs. */
16 const char *git_exec_path(void)
18 const char *env;
20 if (current_exec_path)
21 return current_exec_path;
23 env = getenv("GIT_EXEC_PATH");
24 if (env) {
25 return env;
28 return builtin_exec_path;
32 int execv_git_cmd(const char **argv)
34 char git_command[PATH_MAX + 1];
35 int len, err, i;
36 const char *paths[] = { current_exec_path,
37 getenv("GIT_EXEC_PATH"),
38 builtin_exec_path };
40 for (i = 0; i < ARRAY_SIZE(paths); ++i) {
41 const char *exec_dir = paths[i];
42 const char *tmp;
44 if (!exec_dir) continue;
46 if (*exec_dir != '/') {
47 if (!getcwd(git_command, sizeof(git_command))) {
48 fprintf(stderr, "git: cannot determine "
49 "current directory\n");
50 exit(1);
52 len = strlen(git_command);
54 /* Trivial cleanup */
55 while (!strncmp(exec_dir, "./", 2)) {
56 exec_dir += 2;
57 while (*exec_dir == '/')
58 exec_dir++;
60 snprintf(git_command + len, sizeof(git_command) - len,
61 "/%s", exec_dir);
62 } else {
63 strcpy(git_command, exec_dir);
66 len = strlen(git_command);
67 len += snprintf(git_command + len, sizeof(git_command) - len,
68 "/git-%s", argv[0]);
70 if (sizeof(git_command) <= len) {
71 fprintf(stderr,
72 "git: command name given is too long.\n");
73 break;
76 /* argv[0] must be the git command, but the argv array
77 * belongs to the caller, and my be reused in
78 * subsequent loop iterations. Save argv[0] and
79 * restore it on error.
82 tmp = argv[0];
83 argv[0] = git_command;
85 /* execve() can only ever return if it fails */
86 execve(git_command, (char **)argv, environ);
88 err = errno;
90 argv[0] = tmp;
92 return -1;
97 int execl_git_cmd(const char *cmd,...)
99 int argc;
100 const char *argv[MAX_ARGS + 1];
101 const char *arg;
102 va_list param;
104 va_start(param, cmd);
105 argv[0] = cmd;
106 argc = 1;
107 while (argc < MAX_ARGS) {
108 arg = argv[argc++] = va_arg(param, char *);
109 if (!arg)
110 break;
112 va_end(param);
113 if (MAX_ARGS <= argc)
114 return error("too many args to run %s", cmd);
116 argv[argc] = NULL;
117 return execv_git_cmd(argv);