csum-file: introduce hashfile_total()
[git.git] / builtin / env--helper.c
blob23c214fff6d69101c29d49bad033b602cd1b3173
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 static enum {
11 ENV_HELPER_TYPE_BOOL = 1,
12 ENV_HELPER_TYPE_ULONG
13 } cmdmode = 0;
15 static int option_parse_type(const struct option *opt, const char *arg,
16 int unset)
18 if (!strcmp(arg, "bool"))
19 cmdmode = ENV_HELPER_TYPE_BOOL;
20 else if (!strcmp(arg, "ulong"))
21 cmdmode = ENV_HELPER_TYPE_ULONG;
22 else
23 die(_("unrecognized --type argument, %s"), arg);
25 return 0;
28 int cmd_env__helper(int argc, const char **argv, const char *prefix)
30 int exit_code = 0;
31 const char *env_variable = NULL;
32 const char *env_default = NULL;
33 int ret;
34 int ret_int, default_int;
35 unsigned long ret_ulong, default_ulong;
36 struct option opts[] = {
37 OPT_CALLBACK_F(0, "type", &cmdmode, N_("type"),
38 N_("value is given this type"), PARSE_OPT_NONEG,
39 option_parse_type),
40 OPT_STRING(0, "default", &env_default, N_("value"),
41 N_("default for git_env_*(...) to fall back on")),
42 OPT_BOOL(0, "exit-code", &exit_code,
43 N_("be quiet only use git_env_*() value as exit code")),
44 OPT_END(),
47 argc = parse_options(argc, argv, prefix, opts, env__helper_usage,
48 PARSE_OPT_KEEP_UNKNOWN);
49 if (env_default && !*env_default)
50 usage_with_options(env__helper_usage, opts);
51 if (!cmdmode)
52 usage_with_options(env__helper_usage, opts);
53 if (argc != 1)
54 usage_with_options(env__helper_usage, opts);
55 env_variable = argv[0];
57 switch (cmdmode) {
58 case ENV_HELPER_TYPE_BOOL:
59 if (env_default) {
60 default_int = git_parse_maybe_bool(env_default);
61 if (default_int == -1) {
62 error(_("option `--default' expects a boolean value with `--type=bool`, not `%s`"),
63 env_default);
64 usage_with_options(env__helper_usage, opts);
66 } else {
67 default_int = 0;
69 ret_int = git_env_bool(env_variable, default_int);
70 if (!exit_code)
71 puts(ret_int ? "true" : "false");
72 ret = ret_int;
73 break;
74 case ENV_HELPER_TYPE_ULONG:
75 if (env_default) {
76 if (!git_parse_ulong(env_default, &default_ulong)) {
77 error(_("option `--default' expects an unsigned long value with `--type=ulong`, not `%s`"),
78 env_default);
79 usage_with_options(env__helper_usage, opts);
81 } else {
82 default_ulong = 0;
84 ret_ulong = git_env_ulong(env_variable, default_ulong);
85 if (!exit_code)
86 printf("%lu\n", ret_ulong);
87 ret = ret_ulong;
88 break;
89 default:
90 BUG("unknown <type> value");
91 break;
94 return !ret;