pathspec: support :(glob) syntax
[git] / pathspec.c
1 #include "cache.h"
2 #include "dir.h"
3 #include "pathspec.h"
4
5 /*
6  * Finds which of the given pathspecs match items in the index.
7  *
8  * For each pathspec, sets the corresponding entry in the seen[] array
9  * (which should be specs items long, i.e. the same size as pathspec)
10  * to the nature of the "closest" (i.e. most specific) match found for
11  * that pathspec in the index, if it was a closer type of match than
12  * the existing entry.  As an optimization, matching is skipped
13  * altogether if seen[] already only contains non-zero entries.
14  *
15  * If seen[] has not already been written to, it may make sense
16  * to use find_pathspecs_matching_against_index() instead.
17  */
18 void add_pathspec_matches_against_index(const struct pathspec *pathspec,
19                                         char *seen)
20 {
21         int num_unmatched = 0, i;
22
23         /*
24          * Since we are walking the index as if we were walking the directory,
25          * we have to mark the matched pathspec as seen; otherwise we will
26          * mistakenly think that the user gave a pathspec that did not match
27          * anything.
28          */
29         for (i = 0; i < pathspec->nr; i++)
30                 if (!seen[i])
31                         num_unmatched++;
32         if (!num_unmatched)
33                 return;
34         for (i = 0; i < active_nr; i++) {
35                 struct cache_entry *ce = active_cache[i];
36                 match_pathspec_depth(pathspec, ce->name, ce_namelen(ce), 0, seen);
37         }
38 }
39
40 /*
41  * Finds which of the given pathspecs match items in the index.
42  *
43  * This is a one-shot wrapper around add_pathspec_matches_against_index()
44  * which allocates, populates, and returns a seen[] array indicating the
45  * nature of the "closest" (i.e. most specific) matches which each of the
46  * given pathspecs achieves against all items in the index.
47  */
48 char *find_pathspecs_matching_against_index(const struct pathspec *pathspec)
49 {
50         char *seen = xcalloc(pathspec->nr, 1);
51         add_pathspec_matches_against_index(pathspec, seen);
52         return seen;
53 }
54
55 /*
56  * Magic pathspec
57  *
58  * Possible future magic semantics include stuff like:
59  *
60  *      { PATHSPEC_ICASE, '\0', "icase" },
61  *      { PATHSPEC_RECURSIVE, '*', "recursive" },
62  *      { PATHSPEC_REGEXP, '\0', "regexp" },
63  *
64  */
65
66 static struct pathspec_magic {
67         unsigned bit;
68         char mnemonic; /* this cannot be ':'! */
69         const char *name;
70 } pathspec_magic[] = {
71         { PATHSPEC_FROMTOP, '/', "top" },
72         { PATHSPEC_LITERAL,   0, "literal" },
73         { PATHSPEC_GLOB,   '\0', "glob" },
74 };
75
76 /*
77  * Take an element of a pathspec and check for magic signatures.
78  * Append the result to the prefix. Return the magic bitmap.
79  *
80  * For now, we only parse the syntax and throw out anything other than
81  * "top" magic.
82  *
83  * NEEDSWORK: This needs to be rewritten when we start migrating
84  * get_pathspec() users to use the "struct pathspec" interface.  For
85  * example, a pathspec element may be marked as case-insensitive, but
86  * the prefix part must always match literally, and a single stupid
87  * string cannot express such a case.
88  */
89 static unsigned prefix_pathspec(struct pathspec_item *item,
90                                 unsigned *p_short_magic,
91                                 const char **raw, unsigned flags,
92                                 const char *prefix, int prefixlen,
93                                 const char *elt)
94 {
95         static int literal_global = -1;
96         static int glob_global = -1;
97         static int noglob_global = -1;
98         unsigned magic = 0, short_magic = 0, global_magic = 0;
99         const char *copyfrom = elt, *long_magic_end = NULL;
100         char *match;
101         int i, pathspec_prefix = -1;
102
103         if (literal_global < 0)
104                 literal_global = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
105         if (literal_global)
106                 global_magic |= PATHSPEC_LITERAL;
107
108         if (glob_global < 0)
109                 glob_global = git_env_bool(GIT_GLOB_PATHSPECS_ENVIRONMENT, 0);
110         if (glob_global)
111                 global_magic |= PATHSPEC_GLOB;
112
113         if (noglob_global < 0)
114                 noglob_global = git_env_bool(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, 0);
115
116         if (glob_global && noglob_global)
117                 die(_("global 'glob' and 'noglob' pathspec settings are incompatible"));
118
119         if ((global_magic & PATHSPEC_LITERAL) &&
120             (global_magic & ~PATHSPEC_LITERAL))
121                 die(_("global 'literal' pathspec setting is incompatible "
122                       "with all other global pathspec settings"));
123
124         if (elt[0] != ':' || literal_global) {
125                 ; /* nothing to do */
126         } else if (elt[1] == '(') {
127                 /* longhand */
128                 const char *nextat;
129                 for (copyfrom = elt + 2;
130                      *copyfrom && *copyfrom != ')';
131                      copyfrom = nextat) {
132                         size_t len = strcspn(copyfrom, ",)");
133                         if (copyfrom[len] == ',')
134                                 nextat = copyfrom + len + 1;
135                         else
136                                 /* handle ')' and '\0' */
137                                 nextat = copyfrom + len;
138                         if (!len)
139                                 continue;
140                         for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
141                                 if (strlen(pathspec_magic[i].name) == len &&
142                                     !strncmp(pathspec_magic[i].name, copyfrom, len)) {
143                                         magic |= pathspec_magic[i].bit;
144                                         break;
145                                 }
146                                 if (!prefixcmp(copyfrom, "prefix:")) {
147                                         char *endptr;
148                                         pathspec_prefix = strtol(copyfrom + 7,
149                                                                  &endptr, 10);
150                                         if (endptr - copyfrom != len)
151                                                 die(_("invalid parameter for pathspec magic 'prefix'"));
152                                         /* "i" would be wrong, but it does not matter */
153                                         break;
154                                 }
155                         }
156                         if (ARRAY_SIZE(pathspec_magic) <= i)
157                                 die(_("Invalid pathspec magic '%.*s' in '%s'"),
158                                     (int) len, copyfrom, elt);
159                 }
160                 if (*copyfrom != ')')
161                         die(_("Missing ')' at the end of pathspec magic in '%s'"), elt);
162                 long_magic_end = copyfrom;
163                 copyfrom++;
164         } else {
165                 /* shorthand */
166                 for (copyfrom = elt + 1;
167                      *copyfrom && *copyfrom != ':';
168                      copyfrom++) {
169                         char ch = *copyfrom;
170
171                         if (!is_pathspec_magic(ch))
172                                 break;
173                         for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
174                                 if (pathspec_magic[i].mnemonic == ch) {
175                                         short_magic |= pathspec_magic[i].bit;
176                                         break;
177                                 }
178                         if (ARRAY_SIZE(pathspec_magic) <= i)
179                                 die(_("Unimplemented pathspec magic '%c' in '%s'"),
180                                     ch, elt);
181                 }
182                 if (*copyfrom == ':')
183                         copyfrom++;
184         }
185
186         magic |= short_magic;
187         *p_short_magic = short_magic;
188
189         /* --noglob-pathspec adds :(literal) _unless_ :(glob) is specifed */
190         if (noglob_global && !(magic & PATHSPEC_GLOB))
191                 global_magic |= PATHSPEC_LITERAL;
192
193         /* --glob-pathspec is overriden by :(literal) */
194         if ((global_magic & PATHSPEC_GLOB) && (magic & PATHSPEC_LITERAL))
195                 global_magic &= ~PATHSPEC_GLOB;
196
197         magic |= global_magic;
198
199         if (pathspec_prefix >= 0 &&
200             (prefixlen || (prefix && *prefix)))
201                 die("BUG: 'prefix' magic is supposed to be used at worktree's root");
202
203         if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
204                 die(_("%s: 'literal' and 'glob' are incompatible"), elt);
205
206         if (pathspec_prefix >= 0) {
207                 match = xstrdup(copyfrom);
208                 prefixlen = pathspec_prefix;
209         } else if (magic & PATHSPEC_FROMTOP) {
210                 match = xstrdup(copyfrom);
211                 prefixlen = 0;
212         } else {
213                 match = prefix_path_gently(prefix, prefixlen, &prefixlen, copyfrom);
214                 if (!match)
215                         die(_("%s: '%s' is outside repository"), elt, copyfrom);
216         }
217         *raw = item->match = match;
218         /*
219          * Prefix the pathspec (keep all magic) and assign to
220          * original. Useful for passing to another command.
221          */
222         if (flags & PATHSPEC_PREFIX_ORIGIN) {
223                 struct strbuf sb = STRBUF_INIT;
224                 const char *start = elt;
225                 if (prefixlen && !literal_global) {
226                         /* Preserve the actual prefix length of each pattern */
227                         if (long_magic_end) {
228                                 strbuf_add(&sb, start, long_magic_end - start);
229                                 strbuf_addf(&sb, ",prefix:%d", prefixlen);
230                                 start = long_magic_end;
231                         } else {
232                                 if (*start == ':')
233                                         start++;
234                                 strbuf_addf(&sb, ":(prefix:%d)", prefixlen);
235                         }
236                 }
237                 strbuf_add(&sb, start, copyfrom - start);
238                 strbuf_addstr(&sb, match);
239                 item->original = strbuf_detach(&sb, NULL);
240         } else
241                 item->original = elt;
242         item->len = strlen(item->match);
243         item->prefix = prefixlen;
244
245         if ((flags & PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP) &&
246             (item->len >= 1 && item->match[item->len - 1] == '/') &&
247             (i = cache_name_pos(item->match, item->len - 1)) >= 0 &&
248             S_ISGITLINK(active_cache[i]->ce_mode)) {
249                 item->len--;
250                 match[item->len] = '\0';
251         }
252
253         if (flags & PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE)
254                 for (i = 0; i < active_nr; i++) {
255                         struct cache_entry *ce = active_cache[i];
256                         int ce_len = ce_namelen(ce);
257
258                         if (!S_ISGITLINK(ce->ce_mode))
259                                 continue;
260
261                         if (item->len <= ce_len || match[ce_len] != '/' ||
262                             memcmp(ce->name, match, ce_len))
263                                 continue;
264                         if (item->len == ce_len + 1) {
265                                 /* strip trailing slash */
266                                 item->len--;
267                                 match[item->len] = '\0';
268                         } else
269                                 die (_("Pathspec '%s' is in submodule '%.*s'"),
270                                      elt, ce_len, ce->name);
271                 }
272
273         if (magic & PATHSPEC_LITERAL)
274                 item->nowildcard_len = item->len;
275         else {
276                 item->nowildcard_len = simple_length(item->match);
277                 if (item->nowildcard_len < prefixlen)
278                         item->nowildcard_len = prefixlen;
279         }
280         item->flags = 0;
281         if (magic & PATHSPEC_GLOB) {
282                 /*
283                  * FIXME: should we enable ONESTAR in _GLOB for
284                  * pattern "* * / * . c"?
285                  */
286         } else {
287                 if (item->nowildcard_len < item->len &&
288                     item->match[item->nowildcard_len] == '*' &&
289                     no_wildcard(item->match + item->nowildcard_len + 1))
290                         item->flags |= PATHSPEC_ONESTAR;
291         }
292
293         /* sanity checks, pathspec matchers assume these are sane */
294         assert(item->nowildcard_len <= item->len &&
295                item->prefix         <= item->len);
296         return magic;
297 }
298
299 static int pathspec_item_cmp(const void *a_, const void *b_)
300 {
301         struct pathspec_item *a, *b;
302
303         a = (struct pathspec_item *)a_;
304         b = (struct pathspec_item *)b_;
305         return strcmp(a->match, b->match);
306 }
307
308 static void NORETURN unsupported_magic(const char *pattern,
309                                        unsigned magic,
310                                        unsigned short_magic)
311 {
312         struct strbuf sb = STRBUF_INIT;
313         int i, n;
314         for (n = i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
315                 const struct pathspec_magic *m = pathspec_magic + i;
316                 if (!(magic & m->bit))
317                         continue;
318                 if (sb.len)
319                         strbuf_addstr(&sb, " ");
320                 if (short_magic & m->bit)
321                         strbuf_addf(&sb, "'%c'", m->mnemonic);
322                 else
323                         strbuf_addf(&sb, "'%s'", m->name);
324                 n++;
325         }
326         /*
327          * We may want to substitute "this command" with a command
328          * name. E.g. when add--interactive dies when running
329          * "checkout -p"
330          */
331         die(_("%s: pathspec magic not supported by this command: %s"),
332             pattern, sb.buf);
333 }
334
335 /*
336  * Given command line arguments and a prefix, convert the input to
337  * pathspec. die() if any magic in magic_mask is used.
338  */
339 void parse_pathspec(struct pathspec *pathspec,
340                     unsigned magic_mask, unsigned flags,
341                     const char *prefix, const char **argv)
342 {
343         struct pathspec_item *item;
344         const char *entry = argv ? *argv : NULL;
345         int i, n, prefixlen;
346
347         memset(pathspec, 0, sizeof(*pathspec));
348
349         if (flags & PATHSPEC_MAXDEPTH_VALID)
350                 pathspec->magic |= PATHSPEC_MAXDEPTH;
351
352         /* No arguments, no prefix -> no pathspec */
353         if (!entry && !prefix)
354                 return;
355
356         if ((flags & PATHSPEC_PREFER_CWD) &&
357             (flags & PATHSPEC_PREFER_FULL))
358                 die("BUG: PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
359
360         /* No arguments with prefix -> prefix pathspec */
361         if (!entry) {
362                 static const char *raw[2];
363
364                 if (flags & PATHSPEC_PREFER_FULL)
365                         return;
366
367                 if (!(flags & PATHSPEC_PREFER_CWD))
368                         die("BUG: PATHSPEC_PREFER_CWD requires arguments");
369
370                 pathspec->items = item = xmalloc(sizeof(*item));
371                 memset(item, 0, sizeof(*item));
372                 item->match = prefix;
373                 item->original = prefix;
374                 item->nowildcard_len = item->len = strlen(prefix);
375                 item->prefix = item->len;
376                 raw[0] = prefix;
377                 raw[1] = NULL;
378                 pathspec->nr = 1;
379                 pathspec->_raw = raw;
380                 return;
381         }
382
383         n = 0;
384         while (argv[n])
385                 n++;
386
387         pathspec->nr = n;
388         pathspec->items = item = xmalloc(sizeof(*item) * n);
389         pathspec->_raw = argv;
390         prefixlen = prefix ? strlen(prefix) : 0;
391
392         for (i = 0; i < n; i++) {
393                 unsigned short_magic;
394                 entry = argv[i];
395
396                 item[i].magic = prefix_pathspec(item + i, &short_magic,
397                                                 argv + i, flags,
398                                                 prefix, prefixlen, entry);
399                 if (item[i].magic & magic_mask)
400                         unsupported_magic(entry,
401                                           item[i].magic & magic_mask,
402                                           short_magic);
403
404                 if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
405                     has_symlink_leading_path(item[i].match, item[i].len)) {
406                         die(_("pathspec '%s' is beyond a symbolic link"), entry);
407                 }
408
409                 if (item[i].nowildcard_len < item[i].len)
410                         pathspec->has_wildcard = 1;
411                 pathspec->magic |= item[i].magic;
412         }
413
414
415         if (pathspec->magic & PATHSPEC_MAXDEPTH) {
416                 if (flags & PATHSPEC_KEEP_ORDER)
417                         die("BUG: PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
418                 qsort(pathspec->items, pathspec->nr,
419                       sizeof(struct pathspec_item), pathspec_item_cmp);
420         }
421 }
422
423 /*
424  * N.B. get_pathspec() is deprecated in favor of the "struct pathspec"
425  * based interface - see pathspec.c:parse_pathspec().
426  *
427  * Arguments:
428  *  - prefix - a path relative to the root of the working tree
429  *  - pathspec - a list of paths underneath the prefix path
430  *
431  * Iterates over pathspec, prepending each path with prefix,
432  * and return the resulting list.
433  *
434  * If pathspec is empty, return a singleton list containing prefix.
435  *
436  * If pathspec and prefix are both empty, return an empty list.
437  *
438  * This is typically used by built-in commands such as add.c, in order
439  * to normalize argv arguments provided to the built-in into a list of
440  * paths to process, all relative to the root of the working tree.
441  */
442 const char **get_pathspec(const char *prefix, const char **pathspec)
443 {
444         struct pathspec ps;
445         parse_pathspec(&ps,
446                        PATHSPEC_ALL_MAGIC &
447                        ~(PATHSPEC_FROMTOP | PATHSPEC_LITERAL),
448                        PATHSPEC_PREFER_CWD,
449                        prefix, pathspec);
450         return ps._raw;
451 }
452
453 void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
454 {
455         *dst = *src;
456         dst->items = xmalloc(sizeof(struct pathspec_item) * dst->nr);
457         memcpy(dst->items, src->items,
458                sizeof(struct pathspec_item) * dst->nr);
459 }
460
461 void free_pathspec(struct pathspec *pathspec)
462 {
463         free(pathspec->items);
464         pathspec->items = NULL;
465 }