Merge branch 'gc/config-context'
[alt-git.git] / alias.c
blob910dd252a01586721dc0a41b99b5699a7f22a732
1 #include "git-compat-util.h"
2 #include "alias.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "gettext.h"
6 #include "strbuf.h"
7 #include "string-list.h"
9 struct config_alias_data {
10 const char *alias;
11 char *v;
12 struct string_list *list;
15 static int config_alias_cb(const char *key, const char *value,
16 const struct config_context *ctx UNUSED, void *d)
18 struct config_alias_data *data = d;
19 const char *p;
21 if (!skip_prefix(key, "alias.", &p))
22 return 0;
24 if (data->alias) {
25 if (!strcasecmp(p, data->alias))
26 return git_config_string((const char **)&data->v,
27 key, value);
28 } else if (data->list) {
29 string_list_append(data->list, p);
32 return 0;
35 char *alias_lookup(const char *alias)
37 struct config_alias_data data = { alias, NULL };
39 read_early_config(config_alias_cb, &data);
41 return data.v;
44 void list_aliases(struct string_list *list)
46 struct config_alias_data data = { NULL, NULL, list };
48 read_early_config(config_alias_cb, &data);
51 void quote_cmdline(struct strbuf *buf, const char **argv)
53 for (const char **argp = argv; *argp; argp++) {
54 if (argp != argv)
55 strbuf_addch(buf, ' ');
56 strbuf_addch(buf, '"');
57 for (const char *p = *argp; *p; p++) {
58 const char c = *p;
60 if (c == '"' || c =='\\')
61 strbuf_addch(buf, '\\');
62 strbuf_addch(buf, c);
64 strbuf_addch(buf, '"');
68 #define SPLIT_CMDLINE_BAD_ENDING 1
69 #define SPLIT_CMDLINE_UNCLOSED_QUOTE 2
70 #define SPLIT_CMDLINE_ARGC_OVERFLOW 3
71 static const char *split_cmdline_errors[] = {
72 N_("cmdline ends with \\"),
73 N_("unclosed quote"),
74 N_("too many arguments"),
77 int split_cmdline(char *cmdline, const char ***argv)
79 size_t src, dst, count = 0, size = 16;
80 char quoted = 0;
82 ALLOC_ARRAY(*argv, size);
84 /* split alias_string */
85 (*argv)[count++] = cmdline;
86 for (src = dst = 0; cmdline[src];) {
87 char c = cmdline[src];
88 if (!quoted && isspace(c)) {
89 cmdline[dst++] = 0;
90 while (cmdline[++src]
91 && isspace(cmdline[src]))
92 ; /* skip */
93 ALLOC_GROW(*argv, count + 1, size);
94 (*argv)[count++] = cmdline + dst;
95 } else if (!quoted && (c == '\'' || c == '"')) {
96 quoted = c;
97 src++;
98 } else if (c == quoted) {
99 quoted = 0;
100 src++;
101 } else {
102 if (c == '\\' && quoted != '\'') {
103 src++;
104 c = cmdline[src];
105 if (!c) {
106 FREE_AND_NULL(*argv);
107 return -SPLIT_CMDLINE_BAD_ENDING;
110 cmdline[dst++] = c;
111 src++;
115 cmdline[dst] = 0;
117 if (quoted) {
118 FREE_AND_NULL(*argv);
119 return -SPLIT_CMDLINE_UNCLOSED_QUOTE;
122 if (count >= INT_MAX) {
123 FREE_AND_NULL(*argv);
124 return -SPLIT_CMDLINE_ARGC_OVERFLOW;
127 ALLOC_GROW(*argv, count + 1, size);
128 (*argv)[count] = NULL;
130 return count;
133 const char *split_cmdline_strerror(int split_cmdline_errno)
135 return split_cmdline_errors[-split_cmdline_errno - 1];