refactor git_getpass into generic prompt function

This will allow callers to specify more options (e.g., leaving echo on). The original git_getpass becomes a slim wrapper around the new function. Signed-off-by: Jeff King <peff@peff.net> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jeff King committed Dec 10, 2011 at 05:40 UTC 1cb0134f3414be187cc3eb98e9740aeeb07dcb16
2 files changed +33 -16
prompt.c
+30 -16
@@ -3,26 +3,13 @@
3 #include "strbuf.h"
4 #include "prompt.h"
5
6 -char *git_getpass(const char *prompt)
6 +static char *do_askpass(const char *cmd, const char *prompt)
7 {
8 - const char *askpass;
8 struct child_process pass;
9 const char *args[3];
10 static struct strbuf buffer = STRBUF_INIT;
11
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;
23 - }
24 -
25 - args[0] = askpass;
12 + args[0] = cmd;
13 args[1] = prompt;
14 args[2] = NULL;
15
@@ -35,7 +22,7 @@ char *git_getpass(const char *prompt)
22
23 strbuf_reset(&buffer);
24 if (strbuf_read(&buffer, pass.out, 20) < 0)
38 - die("failed to read password from %s\n", askpass);
25 + die("failed to get '%s' from %s\n", prompt, cmd);
26
27 close(pass.out);
28
@@ -46,3 +33,30 @@ char *git_getpass(const char *prompt)
33
34 return buffer.buf;
35 }
36 +
37 +char *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 +
59 +char *git_getpass(const char *prompt)
60 +{
61 + return git_prompt(prompt, PROMPT_ASKPASS);
62 +}
prompt.h
+3
@@ -1,6 +1,9 @@
1 #ifndef PROMPT_H
2 #define PROMPT_H
3
4 +#define PROMPT_ASKPASS (1<<0)
5 +
6 +char *git_prompt(const char *prompt, int flags);
7 char *git_getpass(const char *prompt);
8
9 #endif /* PROMPT_H */