Merge branch 'bw/inet-pton-ntop-compat' into maint
[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;
10         const char *args[3];
11         static struct strbuf buffer = STRBUF_INIT;
12
13         args[0] = cmd;
14         args[1] = prompt;
15         args[2] = NULL;
16
17         memset(&pass, 0, sizeof(pass));
18         pass.argv = args;
19         pass.out = -1;
20
21         if (start_command(&pass))
22                 exit(1);
23
24         strbuf_reset(&buffer);
25         if (strbuf_read(&buffer, pass.out, 20) < 0)
26                 die("failed to get '%s' from %s\n", prompt, cmd);
27
28         close(pass.out);
29
30         if (finish_command(&pass))
31                 exit(1);
32
33         strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));
34
35         return buffer.buf;
36 }
37
38 char *git_prompt(const char *prompt, int flags)
39 {
40         char *r;
41
42         if (flags & PROMPT_ASKPASS) {
43                 const char *askpass;
44
45                 askpass = getenv("GIT_ASKPASS");
46                 if (!askpass)
47                         askpass = askpass_program;
48                 if (!askpass)
49                         askpass = getenv("SSH_ASKPASS");
50                 if (askpass && *askpass)
51                         return do_askpass(askpass, prompt);
52         }
53
54         r = git_terminal_prompt(prompt, flags & PROMPT_ECHO);
55         if (!r)
56                 die_errno("could not read '%s'", prompt);
57         return r;
58 }
59
60 char *git_getpass(const char *prompt)
61 {
62         return git_prompt(prompt, PROMPT_ASKPASS);
63 }