Merge branch 'ab/config-based-hooks-base' into seen
[git] / builtin / hook.c
1 #include "cache.h"
2 #include "builtin.h"
3 #include "config.h"
4 #include "hook.h"
5 #include "parse-options.h"
6 #include "strbuf.h"
7 #include "strvec.h"
8
9 static const char * const builtin_hook_usage[] = {
10         N_("git hook run [--to-stdin=<path>] <hook-name> [-- <hook-args>]"),
11         NULL
12 };
13
14 static int run(int argc, const char **argv, const char *prefix)
15 {
16         int i;
17         struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
18         int rc = 0;
19         int ignore_missing = 0;
20         const char *hook_name;
21         const char *hook_path;
22
23         struct option run_options[] = {
24                 OPT_BOOL(0, "ignore-missing", &ignore_missing,
25                          N_("exit quietly with a zero exit code if the requested hook cannot be found")),
26                 OPT_STRING(0, "to-stdin", &opt.path_to_stdin, N_("path"),
27                            N_("file to read into hooks' stdin")),
28                 OPT_END(),
29         };
30
31         argc = parse_options(argc, argv, prefix, run_options,
32                              builtin_hook_usage, PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH);
33
34         if (argc > 2) {
35                 if (strcmp(argv[2], "--") &&
36                     strcmp(argv[2], "--end-of-options"))
37                         /* Having a -- for "run" is mandatory */
38                         usage_with_options(builtin_hook_usage, run_options);
39                 /* Add our arguments, start after -- */
40                 for (i = 3 ; i < argc; i++)
41                         strvec_push(&opt.args, argv[i]);
42         }
43
44         /* Need to take into account core.hooksPath */
45         git_config(git_default_config, NULL);
46
47         hook_name = argv[1];
48         hook_path = find_hook(hook_name);
49         if (!hook_path) {
50                 if (ignore_missing)
51                         return 0;
52                 error("cannot find a hook named %s", hook_name);
53                 return 1;
54         }
55         rc = run_found_hooks(hook_name, hook_path, &opt);
56
57         run_hooks_opt_clear(&opt);
58
59         return rc;
60 }
61
62 int cmd_hook(int argc, const char **argv, const char *prefix)
63 {
64         struct option builtin_hook_options[] = {
65                 OPT_END(),
66         };
67
68         if (!strcmp(argv[1], "run"))
69                 return run(argc, argv, prefix);
70         usage_with_options(builtin_hook_usage, builtin_hook_options);
71         return 1;
72 }