pathspec: small readability changes
[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                 const struct cache_entry *ce = active_cache[i];
36                 ce_path_match(ce, pathspec, 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_RECURSIVE, '*', "recursive" },
61  *      { PATHSPEC_REGEXP, '\0', "regexp" },
62  *
63  */
64
65 static struct pathspec_magic {
66         unsigned bit;
67         char mnemonic; /* this cannot be ':'! */
68         const char *name;
69 } pathspec_magic[] = {
70         { PATHSPEC_FROMTOP,  '/', "top" },
71         { PATHSPEC_LITERAL, '\0', "literal" },
72         { PATHSPEC_GLOB,    '\0', "glob" },
73         { PATHSPEC_ICASE,   '\0', "icase" },
74         { PATHSPEC_EXCLUDE,  '!', "exclude" },
75 };
76
77 static void prefix_magic(struct strbuf *sb, int prefixlen, unsigned magic)
78 {
79         int i;
80         strbuf_addstr(sb, ":(");
81         for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
82                 if (magic & pathspec_magic[i].bit) {
83                         if (sb->buf[sb->len - 1] != '(')
84                                 strbuf_addch(sb, ',');
85                         strbuf_addstr(sb, pathspec_magic[i].name);
86                 }
87         strbuf_addf(sb, ",prefix:%d)", prefixlen);
88 }
89
90 static inline int get_literal_global(void)
91 {
92         static int literal = -1;
93
94         if (literal < 0)
95                 literal = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
96
97         return literal;
98 }
99
100 static inline int get_glob_global(void)
101 {
102         static int glob = -1;
103
104         if (glob < 0)
105                 glob = git_env_bool(GIT_GLOB_PATHSPECS_ENVIRONMENT, 0);
106
107         return glob;
108 }
109
110 static inline int get_noglob_global(void)
111 {
112         static int noglob = -1;
113
114         if (noglob < 0)
115                 noglob = git_env_bool(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, 0);
116
117         return noglob;
118 }
119
120 static inline int get_icase_global(void)
121 {
122         static int icase = -1;
123
124         if (icase < 0)
125                 icase = git_env_bool(GIT_ICASE_PATHSPECS_ENVIRONMENT, 0);
126
127         return icase;
128 }
129
130 static int get_global_magic(int element_magic)
131 {
132         int global_magic = 0;
133
134         if (get_literal_global())
135                 global_magic |= PATHSPEC_LITERAL;
136
137         /* --glob-pathspec is overridden by :(literal) */
138         if (get_glob_global() && !(element_magic & PATHSPEC_LITERAL))
139                 global_magic |= PATHSPEC_GLOB;
140
141         if (get_glob_global() && get_noglob_global())
142                 die(_("global 'glob' and 'noglob' pathspec settings are incompatible"));
143
144         if (get_icase_global())
145                 global_magic |= PATHSPEC_ICASE;
146
147         if ((global_magic & PATHSPEC_LITERAL) &&
148             (global_magic & ~PATHSPEC_LITERAL))
149                 die(_("global 'literal' pathspec setting is incompatible "
150                       "with all other global pathspec settings"));
151
152         /* --noglob-pathspec adds :(literal) _unless_ :(glob) is specified */
153         if (get_noglob_global() && !(element_magic & PATHSPEC_GLOB))
154                 global_magic |= PATHSPEC_LITERAL;
155
156         return global_magic;
157 }
158
159 /*
160  * Parse the pathspec element looking for long magic
161  *
162  * saves all magic in 'magic'
163  * if prefix magic is used, save the prefix length in 'prefix_len'
164  * returns the position in 'elem' after all magic has been parsed
165  */
166 static const char *parse_long_magic(unsigned *magic, int *prefix_len,
167                                     const char *elem)
168 {
169         const char *pos;
170         const char *nextat;
171
172         for (pos = elem + 2; *pos && *pos != ')'; pos = nextat) {
173                 size_t len = strcspn(pos, ",)");
174                 int i;
175
176                 if (pos[len] == ',')
177                         nextat = pos + len + 1; /* handle ',' */
178                 else
179                         nextat = pos + len; /* handle ')' and '\0' */
180
181                 if (!len)
182                         continue;
183
184                 if (starts_with(pos, "prefix:")) {
185                         char *endptr;
186                         *prefix_len = strtol(pos + 7, &endptr, 10);
187                         if (endptr - pos != len)
188                                 die(_("invalid parameter for pathspec magic 'prefix'"));
189                         continue;
190                 }
191
192                 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
193                         if (strlen(pathspec_magic[i].name) == len &&
194                             !strncmp(pathspec_magic[i].name, pos, len)) {
195                                 *magic |= pathspec_magic[i].bit;
196                                 break;
197                         }
198                 }
199
200                 if (ARRAY_SIZE(pathspec_magic) <= i)
201                         die(_("Invalid pathspec magic '%.*s' in '%s'"),
202                             (int) len, pos, elem);
203         }
204
205         if (*pos != ')')
206                 die(_("Missing ')' at the end of pathspec magic in '%s'"),
207                     elem);
208         pos++;
209
210         return pos;
211 }
212
213 /*
214  * Parse the pathspec element looking for short magic
215  *
216  * saves all magic in 'magic'
217  * returns the position in 'elem' after all magic has been parsed
218  */
219 static const char *parse_short_magic(unsigned *magic, const char *elem)
220 {
221         const char *pos;
222
223         for (pos = elem + 1; *pos && *pos != ':'; pos++) {
224                 char ch = *pos;
225                 int i;
226
227                 if (!is_pathspec_magic(ch))
228                         break;
229
230                 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
231                         if (pathspec_magic[i].mnemonic == ch) {
232                                 *magic |= pathspec_magic[i].bit;
233                                 break;
234                         }
235                 }
236
237                 if (ARRAY_SIZE(pathspec_magic) <= i)
238                         die(_("Unimplemented pathspec magic '%c' in '%s'"),
239                             ch, elem);
240         }
241
242         if (*pos == ':')
243                 pos++;
244
245         return pos;
246 }
247
248 static const char *parse_element_magic(unsigned *magic, int *prefix_len,
249                                        const char *elem)
250 {
251         if (elem[0] != ':' || get_literal_global())
252                 return elem; /* nothing to do */
253         else if (elem[1] == '(')
254                 /* longhand */
255                 return parse_long_magic(magic, prefix_len, elem);
256         else
257                 /* shorthand */
258                 return parse_short_magic(magic, elem);
259 }
260
261 static void strip_submodule_slash_cheap(struct pathspec_item *item)
262 {
263         if (item->len >= 1 && item->match[item->len - 1] == '/') {
264                 int i = cache_name_pos(item->match, item->len - 1);
265
266                 if (i >= 0 && S_ISGITLINK(active_cache[i]->ce_mode)) {
267                         item->len--;
268                         item->match[item->len] = '\0';
269                 }
270         }
271 }
272
273 static void strip_submodule_slash_expensive(struct pathspec_item *item)
274 {
275         int i;
276
277         for (i = 0; i < active_nr; i++) {
278                 struct cache_entry *ce = active_cache[i];
279                 int ce_len = ce_namelen(ce);
280
281                 if (!S_ISGITLINK(ce->ce_mode))
282                         continue;
283
284                 if (item->len <= ce_len || item->match[ce_len] != '/' ||
285                     memcmp(ce->name, item->match, ce_len))
286                         continue;
287
288                 if (item->len == ce_len + 1) {
289                         /* strip trailing slash */
290                         item->len--;
291                         item->match[item->len] = '\0';
292                 } else {
293                         die(_("Pathspec '%s' is in submodule '%.*s'"),
294                             item->original, ce_len, ce->name);
295                 }
296         }
297 }
298
299 /*
300  * Take an element of a pathspec and check for magic signatures.
301  * Append the result to the prefix. Return the magic bitmap.
302  *
303  * For now, we only parse the syntax and throw out anything other than
304  * "top" magic.
305  *
306  * NEEDSWORK: This needs to be rewritten when we start migrating
307  * get_pathspec() users to use the "struct pathspec" interface.  For
308  * example, a pathspec element may be marked as case-insensitive, but
309  * the prefix part must always match literally, and a single stupid
310  * string cannot express such a case.
311  */
312 static unsigned prefix_pathspec(struct pathspec_item *item, unsigned flags,
313                                 const char *prefix, int prefixlen,
314                                 const char *elt)
315 {
316         unsigned magic = 0, element_magic = 0;
317         const char *copyfrom = elt;
318         char *match;
319         int pathspec_prefix = -1;
320
321         /* PATHSPEC_LITERAL_PATH ignores magic */
322         if (flags & PATHSPEC_LITERAL_PATH) {
323                 magic = PATHSPEC_LITERAL;
324         } else {
325                 copyfrom = parse_element_magic(&element_magic,
326                                                &pathspec_prefix,
327                                                elt);
328                 magic |= element_magic;
329                 magic |= get_global_magic(element_magic);
330         }
331
332         if (pathspec_prefix >= 0 &&
333             (prefixlen || (prefix && *prefix)))
334                 die("BUG: 'prefix' magic is supposed to be used at worktree's root");
335
336         if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
337                 die(_("%s: 'literal' and 'glob' are incompatible"), elt);
338
339         /* Create match string which will be used for pathspec matching */
340         if (pathspec_prefix >= 0) {
341                 match = xstrdup(copyfrom);
342                 prefixlen = pathspec_prefix;
343         } else if (magic & PATHSPEC_FROMTOP) {
344                 match = xstrdup(copyfrom);
345                 prefixlen = 0;
346         } else {
347                 match = prefix_path_gently(prefix, prefixlen,
348                                            &prefixlen, copyfrom);
349                 if (!match)
350                         die(_("%s: '%s' is outside repository"), elt, copyfrom);
351         }
352
353         item->match = match;
354         item->len = strlen(item->match);
355         item->prefix = prefixlen;
356
357         /*
358          * Prefix the pathspec (keep all magic) and assign to
359          * original. Useful for passing to another command.
360          */
361         if ((flags & PATHSPEC_PREFIX_ORIGIN) &&
362             prefixlen && !get_literal_global()) {
363                 struct strbuf sb = STRBUF_INIT;
364
365                 /* Preserve the actual prefix length of each pattern */
366                 prefix_magic(&sb, prefixlen, element_magic);
367
368                 strbuf_addstr(&sb, match);
369                 item->original = strbuf_detach(&sb, NULL);
370         } else {
371                 item->original = xstrdup(elt);
372         }
373
374         if (flags & PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP)
375                 strip_submodule_slash_cheap(item);
376
377         if (flags & PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE)
378                 strip_submodule_slash_expensive(item);
379
380         if (magic & PATHSPEC_LITERAL) {
381                 item->nowildcard_len = item->len;
382         } else {
383                 item->nowildcard_len = simple_length(item->match);
384                 if (item->nowildcard_len < prefixlen)
385                         item->nowildcard_len = prefixlen;
386         }
387
388         item->flags = 0;
389         if (magic & PATHSPEC_GLOB) {
390                 /*
391                  * FIXME: should we enable ONESTAR in _GLOB for
392                  * pattern "* * / * . c"?
393                  */
394         } else {
395                 if (item->nowildcard_len < item->len &&
396                     item->match[item->nowildcard_len] == '*' &&
397                     no_wildcard(item->match + item->nowildcard_len + 1))
398                         item->flags |= PATHSPEC_ONESTAR;
399         }
400
401         /* sanity checks, pathspec matchers assume these are sane */
402         assert(item->nowildcard_len <= item->len &&
403                item->prefix         <= item->len);
404         return magic;
405 }
406
407 static int pathspec_item_cmp(const void *a_, const void *b_)
408 {
409         struct pathspec_item *a, *b;
410
411         a = (struct pathspec_item *)a_;
412         b = (struct pathspec_item *)b_;
413         return strcmp(a->match, b->match);
414 }
415
416 static void NORETURN unsupported_magic(const char *pattern,
417                                        unsigned magic)
418 {
419         struct strbuf sb = STRBUF_INIT;
420         int i;
421         for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
422                 const struct pathspec_magic *m = pathspec_magic + i;
423                 if (!(magic & m->bit))
424                         continue;
425                 if (sb.len)
426                         strbuf_addstr(&sb, ", ");
427
428                 if (m->mnemonic)
429                         strbuf_addf(&sb, _("'%s' (mnemonic: '%c')"),
430                                     m->name, m->mnemonic);
431                 else
432                         strbuf_addf(&sb, "'%s'", m->name);
433         }
434         /*
435          * We may want to substitute "this command" with a command
436          * name. E.g. when add--interactive dies when running
437          * "checkout -p"
438          */
439         die(_("%s: pathspec magic not supported by this command: %s"),
440             pattern, sb.buf);
441 }
442
443 /*
444  * Given command line arguments and a prefix, convert the input to
445  * pathspec. die() if any magic in magic_mask is used.
446  */
447 void parse_pathspec(struct pathspec *pathspec,
448                     unsigned magic_mask, unsigned flags,
449                     const char *prefix, const char **argv)
450 {
451         struct pathspec_item *item;
452         const char *entry = argv ? *argv : NULL;
453         int i, n, prefixlen, warn_empty_string, nr_exclude = 0;
454
455         memset(pathspec, 0, sizeof(*pathspec));
456
457         if (flags & PATHSPEC_MAXDEPTH_VALID)
458                 pathspec->magic |= PATHSPEC_MAXDEPTH;
459
460         /* No arguments, no prefix -> no pathspec */
461         if (!entry && !prefix)
462                 return;
463
464         if ((flags & PATHSPEC_PREFER_CWD) &&
465             (flags & PATHSPEC_PREFER_FULL))
466                 die("BUG: PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
467
468         /* No arguments with prefix -> prefix pathspec */
469         if (!entry) {
470                 if (flags & PATHSPEC_PREFER_FULL)
471                         return;
472
473                 if (!(flags & PATHSPEC_PREFER_CWD))
474                         die("BUG: PATHSPEC_PREFER_CWD requires arguments");
475
476                 pathspec->items = item = xcalloc(1, sizeof(*item));
477                 item->match = xstrdup(prefix);
478                 item->original = xstrdup(prefix);
479                 item->nowildcard_len = item->len = strlen(prefix);
480                 item->prefix = item->len;
481                 pathspec->nr = 1;
482                 return;
483         }
484
485         n = 0;
486         warn_empty_string = 1;
487         while (argv[n]) {
488                 if (*argv[n] == '\0' && warn_empty_string) {
489                         warning(_("empty strings as pathspecs will be made invalid in upcoming releases. "
490                                   "please use . instead if you meant to match all paths"));
491                         warn_empty_string = 0;
492                 }
493                 n++;
494         }
495
496         pathspec->nr = n;
497         ALLOC_ARRAY(pathspec->items, n);
498         item = pathspec->items;
499         prefixlen = prefix ? strlen(prefix) : 0;
500
501         for (i = 0; i < n; i++) {
502                 entry = argv[i];
503
504                 item[i].magic = prefix_pathspec(item + i, flags,
505                                                 prefix, prefixlen, entry);
506
507                 if (item[i].magic & PATHSPEC_EXCLUDE)
508                         nr_exclude++;
509                 if (item[i].magic & magic_mask)
510                         unsupported_magic(entry, item[i].magic & magic_mask);
511
512                 if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
513                     has_symlink_leading_path(item[i].match, item[i].len)) {
514                         die(_("pathspec '%s' is beyond a symbolic link"), entry);
515                 }
516
517                 if (item[i].nowildcard_len < item[i].len)
518                         pathspec->has_wildcard = 1;
519                 pathspec->magic |= item[i].magic;
520         }
521
522         if (nr_exclude == n)
523                 die(_("There is nothing to exclude from by :(exclude) patterns.\n"
524                       "Perhaps you forgot to add either ':/' or '.' ?"));
525
526
527         if (pathspec->magic & PATHSPEC_MAXDEPTH) {
528                 if (flags & PATHSPEC_KEEP_ORDER)
529                         die("BUG: PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
530                 QSORT(pathspec->items, pathspec->nr, pathspec_item_cmp);
531         }
532 }
533
534 void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
535 {
536         int i;
537
538         *dst = *src;
539         ALLOC_ARRAY(dst->items, dst->nr);
540         COPY_ARRAY(dst->items, src->items, dst->nr);
541
542         for (i = 0; i < dst->nr; i++) {
543                 dst->items[i].match = xstrdup(src->items[i].match);
544                 dst->items[i].original = xstrdup(src->items[i].original);
545         }
546 }
547
548 void clear_pathspec(struct pathspec *pathspec)
549 {
550         int i;
551
552         for (i = 0; i < pathspec->nr; i++) {
553                 free(pathspec->items[i].match);
554                 free(pathspec->items[i].original);
555         }
556         free(pathspec->items);
557         pathspec->items = NULL;
558         pathspec->nr = 0;
559 }