launch_editor: refactor to use start/finish_command
[git/git.git] / editor.c
CommitLineData
d82f33e2
SB
1#include "cache.h"
2#include "strbuf.h"
3#include "run-command.h"
4
8f4b576a
JN
5#ifndef DEFAULT_EDITOR
6#define DEFAULT_EDITOR "vi"
7#endif
8
44fcb497 9const char *git_editor(void)
d82f33e2 10{
d33738d7
JN
11 const char *editor = getenv("GIT_EDITOR");
12 const char *terminal = getenv("TERM");
13 int terminal_is_dumb = !terminal || !strcmp(terminal, "dumb");
d82f33e2 14
d82f33e2
SB
15 if (!editor && editor_program)
16 editor = editor_program;
d33738d7 17 if (!editor && !terminal_is_dumb)
d82f33e2
SB
18 editor = getenv("VISUAL");
19 if (!editor)
20 editor = getenv("EDITOR");
21
d33738d7 22 if (!editor && terminal_is_dumb)
44fcb497 23 return NULL;
d82f33e2
SB
24
25 if (!editor)
8f4b576a 26 editor = DEFAULT_EDITOR;
d82f33e2 27
44fcb497
JN
28 return editor;
29}
30
31int launch_editor(const char *path, struct strbuf *buffer, const char *const *env)
32{
33 const char *editor = git_editor();
34
35 if (!editor)
36 return error("Terminal is dumb, but EDITOR unset");
37
d82f33e2 38 if (strcmp(editor, ":")) {
bac80370 39 const char *args[] = { editor, path, NULL };
f42ca31d 40 struct child_process p;
d82f33e2 41
f42ca31d
JK
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);
48
49 if (finish_command(&p))
7198203a
SB
50 return error("There was a problem with the editor '%s'.",
51 editor);
d82f33e2
SB
52 }
53
54 if (!buffer)
7198203a 55 return 0;
d82f33e2 56 if (strbuf_read_file(buffer, path, 0) < 0)
7198203a
SB
57 return error("could not read file '%s': %s",
58 path, strerror(errno));
59 return 0;
d82f33e2 60}