blob: 4d469d076bcd58df3af16d98adc9120e34765944 [file] [log] [blame]
Stephan Beyerd82f33e2008-07-25 18:28:41 +02001#include "cache.h"
2#include "strbuf.h"
3#include "run-command.h"
4
Stephan Beyer71982032008-07-25 18:28:42 +02005int launch_editor(const char *path, struct strbuf *buffer, const char *const *env)
Stephan Beyerd82f33e2008-07-25 18:28:41 +02006{
7 const char *editor, *terminal;
8
9 editor = getenv("GIT_EDITOR");
10 if (!editor && editor_program)
11 editor = editor_program;
12 if (!editor)
13 editor = getenv("VISUAL");
14 if (!editor)
15 editor = getenv("EDITOR");
16
17 terminal = getenv("TERM");
Stephan Beyer71982032008-07-25 18:28:42 +020018 if (!editor && (!terminal || !strcmp(terminal, "dumb")))
19 return error("Terminal is dumb but no VISUAL nor EDITOR defined.");
Stephan Beyerd82f33e2008-07-25 18:28:41 +020020
21 if (!editor)
22 editor = "vi";
23
24 if (strcmp(editor, ":")) {
25 size_t len = strlen(editor);
26 int i = 0;
Stephan Beyer71982032008-07-25 18:28:42 +020027 int failed;
Stephan Beyerd82f33e2008-07-25 18:28:41 +020028 const char *args[6];
Brandon Caseyf285a2d2008-10-09 14:12:12 -050029 struct strbuf arg0 = STRBUF_INIT;
Stephan Beyerd82f33e2008-07-25 18:28:41 +020030
Stephan Beyerd82f33e2008-07-25 18:28:41 +020031 if (strcspn(editor, "$ \t'") != len) {
32 /* there are specials */
33 strbuf_addf(&arg0, "%s \"$@\"", editor);
34 args[i++] = "sh";
35 args[i++] = "-c";
36 args[i++] = arg0.buf;
37 }
38 args[i++] = editor;
39 args[i++] = path;
40 args[i] = NULL;
41
Stephan Beyer71982032008-07-25 18:28:42 +020042 failed = run_command_v_opt_cd_env(args, 0, NULL, env);
Stephan Beyerd82f33e2008-07-25 18:28:41 +020043 strbuf_release(&arg0);
Stephan Beyer71982032008-07-25 18:28:42 +020044 if (failed)
45 return error("There was a problem with the editor '%s'.",
46 editor);
Stephan Beyerd82f33e2008-07-25 18:28:41 +020047 }
48
49 if (!buffer)
Stephan Beyer71982032008-07-25 18:28:42 +020050 return 0;
Stephan Beyerd82f33e2008-07-25 18:28:41 +020051 if (strbuf_read_file(buffer, path, 0) < 0)
Stephan Beyer71982032008-07-25 18:28:42 +020052 return error("could not read file '%s': %s",
53 path, strerror(errno));
54 return 0;
Stephan Beyerd82f33e2008-07-25 18:28:41 +020055}