test-parse-options: --expect=<string> option to simplify tests
[git] / prompt.c
1 #include "cache.h"
2 #include "run-command.h"
3 #include "strbuf.h"
4 #include "prompt.h"
5 #include "compat/terminal.h"
6
7 static char *do_askpass(const char *cmd, const char *prompt)
8 {
9         struct child_process pass = CHILD_PROCESS_INIT;
10         const char *args[3];
11         static struct strbuf buffer = STRBUF_INIT;
12         int err = 0;
13
14         args[0] = cmd;
15         args[1] = prompt;
16         args[2] = NULL;
17
18         pass.argv = args;
19         pass.out = -1;
20
21         if (start_command(&pass))
22                 return NULL;
23
24         strbuf_reset(&buffer);
25         if (strbuf_read(&buffer, pass.out, 20) < 0)
26                 err = 1;
27
28         close(pass.out);
29
30         if (finish_command(&pass))
31                 err = 1;
32
33         if (err) {
34                 error("unable to read askpass response from '%s'", cmd);
35                 strbuf_release(&buffer);
36                 return NULL;
37         }
38
39         strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));
40
41         return buffer.buf;
42 }
43
44 char *git_prompt(const char *prompt, int flags)
45 {
46         char *r = NULL;
47
48         if (flags & PROMPT_ASKPASS) {
49                 const char *askpass;
50
51                 askpass = getenv("GIT_ASKPASS");
52                 if (!askpass)
53                         askpass = askpass_program;
54                 if (!askpass)
55                         askpass = getenv("SSH_ASKPASS");
56                 if (askpass && *askpass)
57                         r = do_askpass(askpass, prompt);
58         }
59
60         if (!r) {
61                 const char *err;
62
63                 if (git_env_bool("GIT_TERMINAL_PROMPT", 1)) {
64                         r = git_terminal_prompt(prompt, flags & PROMPT_ECHO);
65                         err = strerror(errno);
66                 } else {
67                         err = "terminal prompts disabled";
68                 }
69                 if (!r) {
70                         /* prompts already contain ": " at the end */
71                         die("could not read %s%s", prompt, err);
72                 }
73         }
74         return r;
75 }