add generic terminal prompt function
[git/git.git] / prompt.c
CommitLineData
d3c58b83
JK
1#include "cache.h"
2#include "run-command.h"
3#include "strbuf.h"
4#include "prompt.h"
5
1cb0134f 6static char *do_askpass(const char *cmd, const char *prompt)
d3c58b83 7{
d3c58b83
JK
8 struct child_process pass;
9 const char *args[3];
10 static struct strbuf buffer = STRBUF_INIT;
11
1cb0134f 12 args[0] = cmd;
d3c58b83
JK
13 args[1] = prompt;
14 args[2] = NULL;
15
16 memset(&pass, 0, sizeof(pass));
17 pass.argv = args;
18 pass.out = -1;
19
20 if (start_command(&pass))
21 exit(1);
22
23 strbuf_reset(&buffer);
24 if (strbuf_read(&buffer, pass.out, 20) < 0)
1cb0134f 25 die("failed to get '%s' from %s\n", prompt, cmd);
d3c58b83
JK
26
27 close(pass.out);
28
29 if (finish_command(&pass))
30 exit(1);
31
32 strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));
33
34 return buffer.buf;
35}
1cb0134f
JK
36
37char *git_prompt(const char *prompt, int flags)
38{
39 char *r;
40
41 if (flags & PROMPT_ASKPASS) {
42 const char *askpass;
43
44 askpass = getenv("GIT_ASKPASS");
45 if (!askpass)
46 askpass = askpass_program;
47 if (!askpass)
48 askpass = getenv("SSH_ASKPASS");
49 if (askpass && *askpass)
50 return do_askpass(askpass, prompt);
51 }
52
53 r = getpass(prompt);
54 if (!r)
55 die_errno("could not read '%s'", prompt);
56 return r;
57}
58
59char *git_getpass(const char *prompt)
60{
61 return git_prompt(prompt, PROMPT_ASKPASS);
62}