move git_getpass to its own source file
[git/mingw.git] / prompt.c
blob42a1c9f9fb459c033246d33e8b7f65f0ab5da68f
1 #include "cache.h"
2 #include "run-command.h"
3 #include "strbuf.h"
4 #include "prompt.h"
6 char *git_getpass(const char *prompt)
8 const char *askpass;
9 struct child_process pass;
10 const char *args[3];
11 static struct strbuf buffer = STRBUF_INIT;
13 askpass = getenv("GIT_ASKPASS");
14 if (!askpass)
15 askpass = askpass_program;
16 if (!askpass)
17 askpass = getenv("SSH_ASKPASS");
18 if (!askpass || !(*askpass)) {
19 char *result = getpass(prompt);
20 if (!result)
21 die_errno("Could not read password");
22 return result;
25 args[0] = askpass;
26 args[1] = prompt;
27 args[2] = NULL;
29 memset(&pass, 0, sizeof(pass));
30 pass.argv = args;
31 pass.out = -1;
33 if (start_command(&pass))
34 exit(1);
36 strbuf_reset(&buffer);
37 if (strbuf_read(&buffer, pass.out, 20) < 0)
38 die("failed to read password from %s\n", askpass);
40 close(pass.out);
42 if (finish_command(&pass))
43 exit(1);
45 strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));
47 return buffer.buf;