]> git.ipfire.org Git - thirdparty/git.git/blob - alias.c
write-or-die.h: move declarations for write-or-die.c functions from cache.h
[thirdparty/git.git] / alias.c
1 #include "git-compat-util.h"
2 #include "alias.h"
3 #include "alloc.h"
4 #include "config.h"
5 #include "gettext.h"
6 #include "string-list.h"
7
8 struct config_alias_data {
9 const char *alias;
10 char *v;
11 struct string_list *list;
12 };
13
14 static int config_alias_cb(const char *key, const char *value, void *d)
15 {
16 struct config_alias_data *data = d;
17 const char *p;
18
19 if (!skip_prefix(key, "alias.", &p))
20 return 0;
21
22 if (data->alias) {
23 if (!strcasecmp(p, data->alias))
24 return git_config_string((const char **)&data->v,
25 key, value);
26 } else if (data->list) {
27 string_list_append(data->list, p);
28 }
29
30 return 0;
31 }
32
33 char *alias_lookup(const char *alias)
34 {
35 struct config_alias_data data = { alias, NULL };
36
37 read_early_config(config_alias_cb, &data);
38
39 return data.v;
40 }
41
42 void list_aliases(struct string_list *list)
43 {
44 struct config_alias_data data = { NULL, NULL, list };
45
46 read_early_config(config_alias_cb, &data);
47 }
48
49 #define SPLIT_CMDLINE_BAD_ENDING 1
50 #define SPLIT_CMDLINE_UNCLOSED_QUOTE 2
51 #define SPLIT_CMDLINE_ARGC_OVERFLOW 3
52 static const char *split_cmdline_errors[] = {
53 N_("cmdline ends with \\"),
54 N_("unclosed quote"),
55 N_("too many arguments"),
56 };
57
58 int split_cmdline(char *cmdline, const char ***argv)
59 {
60 size_t src, dst, count = 0, size = 16;
61 char quoted = 0;
62
63 ALLOC_ARRAY(*argv, size);
64
65 /* split alias_string */
66 (*argv)[count++] = cmdline;
67 for (src = dst = 0; cmdline[src];) {
68 char c = cmdline[src];
69 if (!quoted && isspace(c)) {
70 cmdline[dst++] = 0;
71 while (cmdline[++src]
72 && isspace(cmdline[src]))
73 ; /* skip */
74 ALLOC_GROW(*argv, count + 1, size);
75 (*argv)[count++] = cmdline + dst;
76 } else if (!quoted && (c == '\'' || c == '"')) {
77 quoted = c;
78 src++;
79 } else if (c == quoted) {
80 quoted = 0;
81 src++;
82 } else {
83 if (c == '\\' && quoted != '\'') {
84 src++;
85 c = cmdline[src];
86 if (!c) {
87 FREE_AND_NULL(*argv);
88 return -SPLIT_CMDLINE_BAD_ENDING;
89 }
90 }
91 cmdline[dst++] = c;
92 src++;
93 }
94 }
95
96 cmdline[dst] = 0;
97
98 if (quoted) {
99 FREE_AND_NULL(*argv);
100 return -SPLIT_CMDLINE_UNCLOSED_QUOTE;
101 }
102
103 if (count >= INT_MAX) {
104 FREE_AND_NULL(*argv);
105 return -SPLIT_CMDLINE_ARGC_OVERFLOW;
106 }
107
108 ALLOC_GROW(*argv, count + 1, size);
109 (*argv)[count] = NULL;
110
111 return count;
112 }
113
114 const char *split_cmdline_strerror(int split_cmdline_errno)
115 {
116 return split_cmdline_errors[-split_cmdline_errno - 1];
117 }