worktree: move subcommand
[git] / editor.c
1 #include "cache.h"
2 #include "strbuf.h"
3 #include "run-command.h"
4 #include "sigchain.h"
5
6 #ifndef DEFAULT_EDITOR
7 #define DEFAULT_EDITOR "vi"
8 #endif
9
10 const char *git_editor(void)
11 {
12         const char *editor = getenv("GIT_EDITOR");
13         const char *terminal = getenv("TERM");
14         int terminal_is_dumb = !terminal || !strcmp(terminal, "dumb");
15
16         if (!editor && editor_program)
17                 editor = editor_program;
18         if (!editor && !terminal_is_dumb)
19                 editor = getenv("VISUAL");
20         if (!editor)
21                 editor = getenv("EDITOR");
22
23         if (!editor && terminal_is_dumb)
24                 return NULL;
25
26         if (!editor)
27                 editor = DEFAULT_EDITOR;
28
29         return editor;
30 }
31
32 int launch_editor(const char *path, struct strbuf *buffer, const char *const *env)
33 {
34         const char *editor = git_editor();
35
36         if (!editor)
37                 return error("Terminal is dumb, but EDITOR unset");
38
39         if (strcmp(editor, ":")) {
40                 const char *args[] = { editor, real_path(path), NULL };
41                 struct child_process p = CHILD_PROCESS_INIT;
42                 int ret, sig;
43
44                 p.argv = args;
45                 p.env = env;
46                 p.use_shell = 1;
47                 if (start_command(&p) < 0)
48                         return error("unable to start editor '%s'", editor);
49
50                 sigchain_push(SIGINT, SIG_IGN);
51                 sigchain_push(SIGQUIT, SIG_IGN);
52                 ret = finish_command(&p);
53                 sig = ret - 128;
54                 sigchain_pop(SIGINT);
55                 sigchain_pop(SIGQUIT);
56                 if (sig == SIGINT || sig == SIGQUIT)
57                         raise(sig);
58                 if (ret)
59                         return error("There was a problem with the editor '%s'.",
60                                         editor);
61         }
62
63         if (!buffer)
64                 return 0;
65         if (strbuf_read_file(buffer, path, 0) < 0)
66                 return error_errno("could not read file '%s'", path);
67         return 0;
68 }