Merge branch 'sg/index-format-doc-update' into maint
[git/debian.git] / builtin / env--helper.c
blob27349098b074f9c3118114ee16f3653f3d61baa2
1 #include "builtin.h"
2 #include "config.h"
3 #include "parse-options.h"
5 static char const * const env__helper_usage[] = {
6 N_("git env--helper --type=[bool|ulong] <options> <env-var>"),
7 NULL
8 };
10 enum cmdmode {
11 ENV_HELPER_TYPE_BOOL = 1,
12 ENV_HELPER_TYPE_ULONG
15 static int option_parse_type(const struct option *opt, const char *arg,
16 int unset)
18 enum cmdmode *cmdmode = opt->value;
20 BUG_ON_OPT_NEG(unset);
22 if (!strcmp(arg, "bool"))
23 *cmdmode = ENV_HELPER_TYPE_BOOL;
24 else if (!strcmp(arg, "ulong"))
25 *cmdmode = ENV_HELPER_TYPE_ULONG;
26 else
27 die(_("unrecognized --type argument, %s"), arg);
29 return 0;
32 int cmd_env__helper(int argc, const char **argv, const char *prefix)
34 int exit_code = 0;
35 const char *env_variable = NULL;
36 const char *env_default = NULL;
37 int ret;
38 int ret_int, default_int;
39 unsigned long ret_ulong, default_ulong;
40 enum cmdmode cmdmode = 0;
41 struct option opts[] = {
42 OPT_CALLBACK_F(0, "type", &cmdmode, N_("type"),
43 N_("value is given this type"), PARSE_OPT_NONEG,
44 option_parse_type),
45 OPT_STRING(0, "default", &env_default, N_("value"),
46 N_("default for git_env_*(...) to fall back on")),
47 OPT_BOOL(0, "exit-code", &exit_code,
48 N_("be quiet only use git_env_*() value as exit code")),
49 OPT_END(),
52 argc = parse_options(argc, argv, prefix, opts, env__helper_usage,
53 PARSE_OPT_KEEP_UNKNOWN);
54 if (env_default && !*env_default)
55 usage_with_options(env__helper_usage, opts);
56 if (!cmdmode)
57 usage_with_options(env__helper_usage, opts);
58 if (argc != 1)
59 usage_with_options(env__helper_usage, opts);
60 env_variable = argv[0];
62 switch (cmdmode) {
63 case ENV_HELPER_TYPE_BOOL:
64 if (env_default) {
65 default_int = git_parse_maybe_bool(env_default);
66 if (default_int == -1) {
67 error(_("option `--default' expects a boolean value with `--type=bool`, not `%s`"),
68 env_default);
69 usage_with_options(env__helper_usage, opts);
71 } else {
72 default_int = 0;
74 ret_int = git_env_bool(env_variable, default_int);
75 if (!exit_code)
76 puts(ret_int ? "true" : "false");
77 ret = ret_int;
78 break;
79 case ENV_HELPER_TYPE_ULONG:
80 if (env_default) {
81 if (!git_parse_ulong(env_default, &default_ulong)) {
82 error(_("option `--default' expects an unsigned long value with `--type=ulong`, not `%s`"),
83 env_default);
84 usage_with_options(env__helper_usage, opts);
86 } else {
87 default_ulong = 0;
89 ret_ulong = git_env_ulong(env_variable, default_ulong);
90 if (!exit_code)
91 printf("%lu\n", ret_ulong);
92 ret = ret_ulong;
93 break;
94 default:
95 BUG("unknown <type> value");
96 break;
99 return !ret;