prompt: clean up strbuf usage
[git.git] / prompt.c
blob64f817b36d9b654986d8499786bb5873b8246fd8
1 #include "cache.h"
2 #include "run-command.h"
3 #include "strbuf.h"
4 #include "prompt.h"
5 #include "compat/terminal.h"
7 static char *do_askpass(const char *cmd, const char *prompt)
9 struct child_process pass;
10 const char *args[3];
11 static struct strbuf buffer = STRBUF_INIT;
13 args[0] = cmd;
14 args[1] = prompt;
15 args[2] = NULL;
17 memset(&pass, 0, sizeof(pass));
18 pass.argv = args;
19 pass.out = -1;
21 if (start_command(&pass))
22 exit(1);
24 if (strbuf_read(&buffer, pass.out, 20) < 0)
25 die("failed to get '%s' from %s\n", prompt, cmd);
27 close(pass.out);
29 if (finish_command(&pass))
30 exit(1);
32 strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));
34 return strbuf_detach(&buffer, NULL);
37 char *git_prompt(const char *prompt, int flags)
39 char *r;
41 if (flags & PROMPT_ASKPASS) {
42 const char *askpass;
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);
53 r = git_terminal_prompt(prompt, flags & PROMPT_ECHO);
54 if (!r)
55 die_errno("could not read '%s'", prompt);
56 return r;
59 char *git_getpass(const char *prompt)
61 return git_prompt(prompt, PROMPT_ASKPASS);