summaryrefslogtreecommitdiffstats
path: root/autocorrect.c
blob: 63fa331ef5e2804f86061c3f710ccb55ea156453 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#define USE_THE_REPOSITORY_VARIABLE

#include "git-compat-util.h"
#include "autocorrect.h"
#include "config.h"
#include "parse.h"
#include "strbuf.h"
#include "prompt.h"
#include "gettext.h"

static enum autocorr_mode parse_autocorrect(const char *value)
{
	switch (git_parse_maybe_bool_text(value)) {
		case 1:
			return AUTOCORRECT_IMMEDIATELY;
		case 0:
			return AUTOCORRECT_HINTONLY;
		default: /* other random text */
			break;
	}

	if (!strcmp(value, "prompt"))
		return AUTOCORRECT_PROMPT;
	else if (!strcmp(value, "never"))
		return AUTOCORRECT_NEVER;
	else if (!strcmp(value, "immediate"))
		return AUTOCORRECT_IMMEDIATELY;
	else if (!strcmp(value, "show"))
		return AUTOCORRECT_HINTONLY;
	else
		return AUTOCORRECT_DELAY;
}

static int resolve_autocorr(const char *var, const char *value,
			    const struct config_context *ctx, void *data)
{
	struct autocorr *conf = data;

	if (strcmp(var, "help.autocorrect"))
		return 0;

	conf->mode = parse_autocorrect(value);

	/*
	 * Disable autocorrection prompt in a non-interactive session.
	 */
	if (conf->mode == AUTOCORRECT_PROMPT && (!isatty(0) || !isatty(2)))
		conf->mode = AUTOCORRECT_NEVER;

	if (conf->mode == AUTOCORRECT_DELAY) {
		conf->delay = git_config_int(var, value, ctx->kvi);

		if (!conf->delay)
			conf->mode = AUTOCORRECT_HINTONLY;
		else if (conf->delay <= 1)
			conf->mode = AUTOCORRECT_IMMEDIATELY;
	}

	return 0;
}

void autocorr_resolve(struct autocorr *conf)
{
	read_early_config(the_repository, resolve_autocorr, conf);
}

void autocorr_confirm(struct autocorr *conf, const char *assumed)
{
	if (conf->mode == AUTOCORRECT_IMMEDIATELY) {
		fprintf_ln(stderr,
			   _("Continuing under the assumption that you meant '%s'."),
			   assumed);
	} else if (conf->mode == AUTOCORRECT_PROMPT) {
		char *answer;
		struct strbuf msg = STRBUF_INIT;

		strbuf_addf(&msg, _("Run '%s' instead [y/N]? "), assumed);
		answer = git_prompt(msg.buf, PROMPT_ECHO);
		strbuf_release(&msg);

		if (!(starts_with(answer, "y") || starts_with(answer, "Y")))
			exit(1);
	} else if (conf->mode == AUTOCORRECT_DELAY) {
		fprintf_ln(stderr,
			   _("Continuing in %0.1f seconds, assuming that you meant '%s'."),
			   conf->delay / 10.0, assumed);
		sleep_millisec(conf->delay * 100);
	}
}