launch_editor: refactor to use start/finish_command
[git.git] / editor.c
blob842f7829fc3a80850fd60b274bfb024b2ada130e
1 #include "cache.h"
2 #include "strbuf.h"
3 #include "run-command.h"
5 #ifndef DEFAULT_EDITOR
6 #define DEFAULT_EDITOR "vi"
7 #endif
9 const char *git_editor(void)
11 const char *editor = getenv("GIT_EDITOR");
12 const char *terminal = getenv("TERM");
13 int terminal_is_dumb = !terminal || !strcmp(terminal, "dumb");
15 if (!editor && editor_program)
16 editor = editor_program;
17 if (!editor && !terminal_is_dumb)
18 editor = getenv("VISUAL");
19 if (!editor)
20 editor = getenv("EDITOR");
22 if (!editor && terminal_is_dumb)
23 return NULL;
25 if (!editor)
26 editor = DEFAULT_EDITOR;
28 return editor;
31 int launch_editor(const char *path, struct strbuf *buffer, const char *const *env)
33 const char *editor = git_editor();
35 if (!editor)
36 return error("Terminal is dumb, but EDITOR unset");
38 if (strcmp(editor, ":")) {
39 const char *args[] = { editor, path, NULL };
40 struct child_process p;
42 memset(&p, 0, sizeof(p));
43 p.argv = args;
44 p.env = env;
45 p.use_shell = 1;
46 if (start_command(&p) < 0)
47 return error("unable to start editor '%s'", editor);
49 if (finish_command(&p))
50 return error("There was a problem with the editor '%s'.",
51 editor);
54 if (!buffer)
55 return 0;
56 if (strbuf_read_file(buffer, path, 0) < 0)
57 return error("could not read file '%s': %s",
58 path, strerror(errno));
59 return 0;