prompt.c 1.4 KB
Newer Older
1 2 3 4
#include "cache.h"
#include "run-command.h"
#include "strbuf.h"
#include "prompt.h"
J
Jeff King 已提交
5
#include "compat/terminal.h"
6

7
static char *do_askpass(const char *cmd, const char *prompt)
8 9 10 11
{
	struct child_process pass;
	const char *args[3];
	static struct strbuf buffer = STRBUF_INIT;
12
	int err = 0;
13

14
	args[0] = cmd;
15 16 17 18 19 20 21 22
	args[1]	= prompt;
	args[2] = NULL;

	memset(&pass, 0, sizeof(pass));
	pass.argv = args;
	pass.out = -1;

	if (start_command(&pass))
23
		return NULL;
24

25
	strbuf_reset(&buffer);
26
	if (strbuf_read(&buffer, pass.out, 20) < 0)
27
		err = 1;
28 29 30 31

	close(pass.out);

	if (finish_command(&pass))
32 33 34 35 36 37 38
		err = 1;

	if (err) {
		error("unable to read askpass response from '%s'", cmd);
		strbuf_release(&buffer);
		return NULL;
	}
39 40 41

	strbuf_setlen(&buffer, strcspn(buffer.buf, "\r\n"));

42
	return buffer.buf;
43
}
44 45 46

char *git_prompt(const char *prompt, int flags)
{
47
	char *r = NULL;
48 49 50 51 52 53 54 55 56 57

	if (flags & PROMPT_ASKPASS) {
		const char *askpass;

		askpass = getenv("GIT_ASKPASS");
		if (!askpass)
			askpass = askpass_program;
		if (!askpass)
			askpass = getenv("SSH_ASKPASS");
		if (askpass && *askpass)
58
			r = do_askpass(askpass, prompt);
59 60 61
	}

	if (!r)
62 63 64 65 66
		r = git_terminal_prompt(prompt, flags & PROMPT_ECHO);
	if (!r) {
		/* prompts already contain ": " at the end */
		die("could not read %s%s", prompt, strerror(errno));
	}
67 68 69 70 71 72 73
	return r;
}

char *git_getpass(const char *prompt)
{
	return git_prompt(prompt, PROMPT_ASKPASS);
}