contrib/completion: fix zsh completion regression from 59d85a2a05
[git/debian.git] / pathspec.c
blob08f8d3eedc39aa46e8bf3a4cba3220ba9b4e74ab
1 #include "cache.h"
2 #include "config.h"
3 #include "dir.h"
4 #include "pathspec.h"
5 #include "attr.h"
6 #include "strvec.h"
7 #include "quote.h"
9 /*
10 * Finds which of the given pathspecs match items in the index.
12 * For each pathspec, sets the corresponding entry in the seen[] array
13 * (which should be specs items long, i.e. the same size as pathspec)
14 * to the nature of the "closest" (i.e. most specific) match found for
15 * that pathspec in the index, if it was a closer type of match than
16 * the existing entry. As an optimization, matching is skipped
17 * altogether if seen[] already only contains non-zero entries.
19 * If seen[] has not already been written to, it may make sense
20 * to use find_pathspecs_matching_against_index() instead.
22 void add_pathspec_matches_against_index(const struct pathspec *pathspec,
23 struct index_state *istate,
24 char *seen,
25 enum ps_skip_worktree_action sw_action)
27 int num_unmatched = 0, i;
30 * Since we are walking the index as if we were walking the directory,
31 * we have to mark the matched pathspec as seen; otherwise we will
32 * mistakenly think that the user gave a pathspec that did not match
33 * anything.
35 for (i = 0; i < pathspec->nr; i++)
36 if (!seen[i])
37 num_unmatched++;
38 if (!num_unmatched)
39 return;
40 /* TODO: audit for interaction with sparse-index. */
41 ensure_full_index(istate);
42 for (i = 0; i < istate->cache_nr; i++) {
43 const struct cache_entry *ce = istate->cache[i];
44 if (sw_action == PS_IGNORE_SKIP_WORKTREE && ce_skip_worktree(ce))
45 continue;
46 ce_path_match(istate, ce, pathspec, seen);
51 * Finds which of the given pathspecs match items in the index.
53 * This is a one-shot wrapper around add_pathspec_matches_against_index()
54 * which allocates, populates, and returns a seen[] array indicating the
55 * nature of the "closest" (i.e. most specific) matches which each of the
56 * given pathspecs achieves against all items in the index.
58 char *find_pathspecs_matching_against_index(const struct pathspec *pathspec,
59 struct index_state *istate,
60 enum ps_skip_worktree_action sw_action)
62 char *seen = xcalloc(pathspec->nr, 1);
63 add_pathspec_matches_against_index(pathspec, istate, seen, sw_action);
64 return seen;
67 char *find_pathspecs_matching_skip_worktree(const struct pathspec *pathspec)
69 struct index_state *istate = the_repository->index;
70 char *seen = xcalloc(pathspec->nr, 1);
71 int i;
73 for (i = 0; i < istate->cache_nr; i++) {
74 struct cache_entry *ce = istate->cache[i];
75 if (ce_skip_worktree(ce))
76 ce_path_match(istate, ce, pathspec, seen);
79 return seen;
83 * Magic pathspec
85 * Possible future magic semantics include stuff like:
87 * { PATHSPEC_RECURSIVE, '*', "recursive" },
88 * { PATHSPEC_REGEXP, '\0', "regexp" },
92 static struct pathspec_magic {
93 unsigned bit;
94 char mnemonic; /* this cannot be ':'! */
95 const char *name;
96 } pathspec_magic[] = {
97 { PATHSPEC_FROMTOP, '/', "top" },
98 { PATHSPEC_LITERAL, '\0', "literal" },
99 { PATHSPEC_GLOB, '\0', "glob" },
100 { PATHSPEC_ICASE, '\0', "icase" },
101 { PATHSPEC_EXCLUDE, '!', "exclude" },
102 { PATHSPEC_ATTR, '\0', "attr" },
105 static void prefix_magic(struct strbuf *sb, int prefixlen, unsigned magic)
107 int i;
108 strbuf_addstr(sb, ":(");
109 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
110 if (magic & pathspec_magic[i].bit) {
111 if (sb->buf[sb->len - 1] != '(')
112 strbuf_addch(sb, ',');
113 strbuf_addstr(sb, pathspec_magic[i].name);
115 strbuf_addf(sb, ",prefix:%d)", prefixlen);
118 static size_t strcspn_escaped(const char *s, const char *stop)
120 const char *i;
122 for (i = s; *i; i++) {
123 /* skip the escaped character */
124 if (i[0] == '\\' && i[1]) {
125 i++;
126 continue;
129 if (strchr(stop, *i))
130 break;
132 return i - s;
135 static inline int invalid_value_char(const char ch)
137 if (isalnum(ch) || strchr(",-_", ch))
138 return 0;
139 return -1;
142 static char *attr_value_unescape(const char *value)
144 const char *src;
145 char *dst, *ret;
147 ret = xmallocz(strlen(value));
148 for (src = value, dst = ret; *src; src++, dst++) {
149 if (*src == '\\') {
150 if (!src[1])
151 die(_("Escape character '\\' not allowed as "
152 "last character in attr value"));
153 src++;
155 if (invalid_value_char(*src))
156 die("cannot use '%c' for value matching", *src);
157 *dst = *src;
159 *dst = '\0';
160 return ret;
163 static void parse_pathspec_attr_match(struct pathspec_item *item, const char *value)
165 struct string_list_item *si;
166 struct string_list list = STRING_LIST_INIT_DUP;
168 if (item->attr_check || item->attr_match)
169 die(_("Only one 'attr:' specification is allowed."));
171 if (!value || !*value)
172 die(_("attr spec must not be empty"));
174 string_list_split(&list, value, ' ', -1);
175 string_list_remove_empty_items(&list, 0);
177 item->attr_check = attr_check_alloc();
178 CALLOC_ARRAY(item->attr_match, list.nr);
180 for_each_string_list_item(si, &list) {
181 size_t attr_len;
182 char *attr_name;
183 const struct git_attr *a;
185 int j = item->attr_match_nr++;
186 const char *attr = si->string;
187 struct attr_match *am = &item->attr_match[j];
189 switch (*attr) {
190 case '!':
191 am->match_mode = MATCH_UNSPECIFIED;
192 attr++;
193 attr_len = strlen(attr);
194 break;
195 case '-':
196 am->match_mode = MATCH_UNSET;
197 attr++;
198 attr_len = strlen(attr);
199 break;
200 default:
201 attr_len = strcspn(attr, "=");
202 if (attr[attr_len] != '=')
203 am->match_mode = MATCH_SET;
204 else {
205 const char *v = &attr[attr_len + 1];
206 am->match_mode = MATCH_VALUE;
207 am->value = attr_value_unescape(v);
209 break;
212 attr_name = xmemdupz(attr, attr_len);
213 a = git_attr(attr_name);
214 if (!a)
215 die(_("invalid attribute name %s"), attr_name);
217 attr_check_append(item->attr_check, a);
219 free(attr_name);
222 if (item->attr_check->nr != item->attr_match_nr)
223 BUG("should have same number of entries");
225 string_list_clear(&list, 0);
228 static inline int get_literal_global(void)
230 static int literal = -1;
232 if (literal < 0)
233 literal = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
235 return literal;
238 static inline int get_glob_global(void)
240 static int glob = -1;
242 if (glob < 0)
243 glob = git_env_bool(GIT_GLOB_PATHSPECS_ENVIRONMENT, 0);
245 return glob;
248 static inline int get_noglob_global(void)
250 static int noglob = -1;
252 if (noglob < 0)
253 noglob = git_env_bool(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, 0);
255 return noglob;
258 static inline int get_icase_global(void)
260 static int icase = -1;
262 if (icase < 0)
263 icase = git_env_bool(GIT_ICASE_PATHSPECS_ENVIRONMENT, 0);
265 return icase;
268 static int get_global_magic(int element_magic)
270 int global_magic = 0;
272 if (get_literal_global())
273 global_magic |= PATHSPEC_LITERAL;
275 /* --glob-pathspec is overridden by :(literal) */
276 if (get_glob_global() && !(element_magic & PATHSPEC_LITERAL))
277 global_magic |= PATHSPEC_GLOB;
279 if (get_glob_global() && get_noglob_global())
280 die(_("global 'glob' and 'noglob' pathspec settings are incompatible"));
282 if (get_icase_global())
283 global_magic |= PATHSPEC_ICASE;
285 if ((global_magic & PATHSPEC_LITERAL) &&
286 (global_magic & ~PATHSPEC_LITERAL))
287 die(_("global 'literal' pathspec setting is incompatible "
288 "with all other global pathspec settings"));
290 /* --noglob-pathspec adds :(literal) _unless_ :(glob) is specified */
291 if (get_noglob_global() && !(element_magic & PATHSPEC_GLOB))
292 global_magic |= PATHSPEC_LITERAL;
294 return global_magic;
298 * Parse the pathspec element looking for long magic
300 * saves all magic in 'magic'
301 * if prefix magic is used, save the prefix length in 'prefix_len'
302 * returns the position in 'elem' after all magic has been parsed
304 static const char *parse_long_magic(unsigned *magic, int *prefix_len,
305 struct pathspec_item *item,
306 const char *elem)
308 const char *pos;
309 const char *nextat;
311 for (pos = elem + 2; *pos && *pos != ')'; pos = nextat) {
312 size_t len = strcspn_escaped(pos, ",)");
313 int i;
315 if (pos[len] == ',')
316 nextat = pos + len + 1; /* handle ',' */
317 else
318 nextat = pos + len; /* handle ')' and '\0' */
320 if (!len)
321 continue;
323 if (starts_with(pos, "prefix:")) {
324 char *endptr;
325 *prefix_len = strtol(pos + 7, &endptr, 10);
326 if (endptr - pos != len)
327 die(_("invalid parameter for pathspec magic 'prefix'"));
328 continue;
331 if (starts_with(pos, "attr:")) {
332 char *attr_body = xmemdupz(pos + 5, len - 5);
333 parse_pathspec_attr_match(item, attr_body);
334 *magic |= PATHSPEC_ATTR;
335 free(attr_body);
336 continue;
339 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
340 if (strlen(pathspec_magic[i].name) == len &&
341 !strncmp(pathspec_magic[i].name, pos, len)) {
342 *magic |= pathspec_magic[i].bit;
343 break;
347 if (ARRAY_SIZE(pathspec_magic) <= i)
348 die(_("Invalid pathspec magic '%.*s' in '%s'"),
349 (int) len, pos, elem);
352 if (*pos != ')')
353 die(_("Missing ')' at the end of pathspec magic in '%s'"),
354 elem);
355 pos++;
357 return pos;
361 * Parse the pathspec element looking for short magic
363 * saves all magic in 'magic'
364 * returns the position in 'elem' after all magic has been parsed
366 static const char *parse_short_magic(unsigned *magic, const char *elem)
368 const char *pos;
370 for (pos = elem + 1; *pos && *pos != ':'; pos++) {
371 char ch = *pos;
372 int i;
374 /* Special case alias for '!' */
375 if (ch == '^') {
376 *magic |= PATHSPEC_EXCLUDE;
377 continue;
380 if (!is_pathspec_magic(ch))
381 break;
383 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
384 if (pathspec_magic[i].mnemonic == ch) {
385 *magic |= pathspec_magic[i].bit;
386 break;
390 if (ARRAY_SIZE(pathspec_magic) <= i)
391 die(_("Unimplemented pathspec magic '%c' in '%s'"),
392 ch, elem);
395 if (*pos == ':')
396 pos++;
398 return pos;
401 static const char *parse_element_magic(unsigned *magic, int *prefix_len,
402 struct pathspec_item *item,
403 const char *elem)
405 if (elem[0] != ':' || get_literal_global())
406 return elem; /* nothing to do */
407 else if (elem[1] == '(')
408 /* longhand */
409 return parse_long_magic(magic, prefix_len, item, elem);
410 else
411 /* shorthand */
412 return parse_short_magic(magic, elem);
416 * Perform the initialization of a pathspec_item based on a pathspec element.
418 static void init_pathspec_item(struct pathspec_item *item, unsigned flags,
419 const char *prefix, int prefixlen,
420 const char *elt)
422 unsigned magic = 0, element_magic = 0;
423 const char *copyfrom = elt;
424 char *match;
425 int pathspec_prefix = -1;
427 item->attr_check = NULL;
428 item->attr_match = NULL;
429 item->attr_match_nr = 0;
431 /* PATHSPEC_LITERAL_PATH ignores magic */
432 if (flags & PATHSPEC_LITERAL_PATH) {
433 magic = PATHSPEC_LITERAL;
434 } else {
435 copyfrom = parse_element_magic(&element_magic,
436 &pathspec_prefix,
437 item,
438 elt);
439 magic |= element_magic;
440 magic |= get_global_magic(element_magic);
443 item->magic = magic;
445 if (pathspec_prefix >= 0 &&
446 (prefixlen || (prefix && *prefix)))
447 BUG("'prefix' magic is supposed to be used at worktree's root");
449 if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
450 die(_("%s: 'literal' and 'glob' are incompatible"), elt);
452 /* Create match string which will be used for pathspec matching */
453 if (pathspec_prefix >= 0) {
454 match = xstrdup(copyfrom);
455 prefixlen = pathspec_prefix;
456 } else if (magic & PATHSPEC_FROMTOP) {
457 match = xstrdup(copyfrom);
458 prefixlen = 0;
459 } else {
460 match = prefix_path_gently(prefix, prefixlen,
461 &prefixlen, copyfrom);
462 if (!match) {
463 const char *hint_path = get_git_work_tree();
464 if (!hint_path)
465 hint_path = get_git_dir();
466 die(_("%s: '%s' is outside repository at '%s'"), elt,
467 copyfrom, absolute_path(hint_path));
471 item->match = match;
472 item->len = strlen(item->match);
473 item->prefix = prefixlen;
476 * Prefix the pathspec (keep all magic) and assign to
477 * original. Useful for passing to another command.
479 if ((flags & PATHSPEC_PREFIX_ORIGIN) &&
480 !get_literal_global()) {
481 struct strbuf sb = STRBUF_INIT;
483 /* Preserve the actual prefix length of each pattern */
484 prefix_magic(&sb, prefixlen, element_magic);
486 strbuf_addstr(&sb, match);
487 item->original = strbuf_detach(&sb, NULL);
488 } else {
489 item->original = xstrdup(elt);
492 if (magic & PATHSPEC_LITERAL) {
493 item->nowildcard_len = item->len;
494 } else {
495 item->nowildcard_len = simple_length(item->match);
496 if (item->nowildcard_len < prefixlen)
497 item->nowildcard_len = prefixlen;
500 item->flags = 0;
501 if (magic & PATHSPEC_GLOB) {
503 * FIXME: should we enable ONESTAR in _GLOB for
504 * pattern "* * / * . c"?
506 } else {
507 if (item->nowildcard_len < item->len &&
508 item->match[item->nowildcard_len] == '*' &&
509 no_wildcard(item->match + item->nowildcard_len + 1))
510 item->flags |= PATHSPEC_ONESTAR;
513 /* sanity checks, pathspec matchers assume these are sane */
514 if (item->nowildcard_len > item->len ||
515 item->prefix > item->len) {
516 BUG("error initializing pathspec_item");
520 static int pathspec_item_cmp(const void *a_, const void *b_)
522 struct pathspec_item *a, *b;
524 a = (struct pathspec_item *)a_;
525 b = (struct pathspec_item *)b_;
526 return strcmp(a->match, b->match);
529 static void NORETURN unsupported_magic(const char *pattern,
530 unsigned magic)
532 struct strbuf sb = STRBUF_INIT;
533 int i;
534 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
535 const struct pathspec_magic *m = pathspec_magic + i;
536 if (!(magic & m->bit))
537 continue;
538 if (sb.len)
539 strbuf_addstr(&sb, ", ");
541 if (m->mnemonic)
542 strbuf_addf(&sb, _("'%s' (mnemonic: '%c')"),
543 m->name, m->mnemonic);
544 else
545 strbuf_addf(&sb, "'%s'", m->name);
548 * We may want to substitute "this command" with a command
549 * name. E.g. when add--interactive dies when running
550 * "checkout -p"
552 die(_("%s: pathspec magic not supported by this command: %s"),
553 pattern, sb.buf);
556 void parse_pathspec(struct pathspec *pathspec,
557 unsigned magic_mask, unsigned flags,
558 const char *prefix, const char **argv)
560 struct pathspec_item *item;
561 const char *entry = argv ? *argv : NULL;
562 int i, n, prefixlen, nr_exclude = 0;
564 memset(pathspec, 0, sizeof(*pathspec));
566 if (flags & PATHSPEC_MAXDEPTH_VALID)
567 pathspec->magic |= PATHSPEC_MAXDEPTH;
569 /* No arguments, no prefix -> no pathspec */
570 if (!entry && !prefix)
571 return;
573 if ((flags & PATHSPEC_PREFER_CWD) &&
574 (flags & PATHSPEC_PREFER_FULL))
575 BUG("PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
577 /* No arguments with prefix -> prefix pathspec */
578 if (!entry) {
579 if (flags & PATHSPEC_PREFER_FULL)
580 return;
582 if (!(flags & PATHSPEC_PREFER_CWD))
583 BUG("PATHSPEC_PREFER_CWD requires arguments");
585 pathspec->items = CALLOC_ARRAY(item, 1);
586 item->match = xstrdup(prefix);
587 item->original = xstrdup(prefix);
588 item->nowildcard_len = item->len = strlen(prefix);
589 item->prefix = item->len;
590 pathspec->nr = 1;
591 return;
594 n = 0;
595 while (argv[n]) {
596 if (*argv[n] == '\0')
597 die("empty string is not a valid pathspec. "
598 "please use . instead if you meant to match all paths");
599 n++;
602 pathspec->nr = n;
603 ALLOC_ARRAY(pathspec->items, n + 1);
604 item = pathspec->items;
605 prefixlen = prefix ? strlen(prefix) : 0;
607 for (i = 0; i < n; i++) {
608 entry = argv[i];
610 init_pathspec_item(item + i, flags, prefix, prefixlen, entry);
612 if (item[i].magic & PATHSPEC_EXCLUDE)
613 nr_exclude++;
614 if (item[i].magic & magic_mask)
615 unsupported_magic(entry, item[i].magic & magic_mask);
617 if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
618 has_symlink_leading_path(item[i].match, item[i].len)) {
619 die(_("pathspec '%s' is beyond a symbolic link"), entry);
622 if (item[i].nowildcard_len < item[i].len)
623 pathspec->has_wildcard = 1;
624 pathspec->magic |= item[i].magic;
628 * If everything is an exclude pattern, add one positive pattern
629 * that matches everything. We allocated an extra one for this.
631 if (nr_exclude == n) {
632 int plen = (!(flags & PATHSPEC_PREFER_CWD)) ? 0 : prefixlen;
633 init_pathspec_item(item + n, 0, prefix, plen, "");
634 pathspec->nr++;
637 if (pathspec->magic & PATHSPEC_MAXDEPTH) {
638 if (flags & PATHSPEC_KEEP_ORDER)
639 BUG("PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
640 QSORT(pathspec->items, pathspec->nr, pathspec_item_cmp);
644 void parse_pathspec_file(struct pathspec *pathspec, unsigned magic_mask,
645 unsigned flags, const char *prefix,
646 const char *file, int nul_term_line)
648 struct strvec parsed_file = STRVEC_INIT;
649 strbuf_getline_fn getline_fn = nul_term_line ? strbuf_getline_nul :
650 strbuf_getline;
651 struct strbuf buf = STRBUF_INIT;
652 struct strbuf unquoted = STRBUF_INIT;
653 FILE *in;
655 if (!strcmp(file, "-"))
656 in = stdin;
657 else
658 in = xfopen(file, "r");
660 while (getline_fn(&buf, in) != EOF) {
661 if (!nul_term_line && buf.buf[0] == '"') {
662 strbuf_reset(&unquoted);
663 if (unquote_c_style(&unquoted, buf.buf, NULL))
664 die(_("line is badly quoted: %s"), buf.buf);
665 strbuf_swap(&buf, &unquoted);
667 strvec_push(&parsed_file, buf.buf);
668 strbuf_reset(&buf);
671 strbuf_release(&unquoted);
672 strbuf_release(&buf);
673 if (in != stdin)
674 fclose(in);
676 parse_pathspec(pathspec, magic_mask, flags, prefix, parsed_file.v);
677 strvec_clear(&parsed_file);
680 void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
682 int i, j;
684 *dst = *src;
685 ALLOC_ARRAY(dst->items, dst->nr);
686 COPY_ARRAY(dst->items, src->items, dst->nr);
688 for (i = 0; i < dst->nr; i++) {
689 struct pathspec_item *d = &dst->items[i];
690 struct pathspec_item *s = &src->items[i];
692 d->match = xstrdup(s->match);
693 d->original = xstrdup(s->original);
695 ALLOC_ARRAY(d->attr_match, d->attr_match_nr);
696 COPY_ARRAY(d->attr_match, s->attr_match, d->attr_match_nr);
697 for (j = 0; j < d->attr_match_nr; j++) {
698 const char *value = s->attr_match[j].value;
699 d->attr_match[j].value = xstrdup_or_null(value);
702 d->attr_check = attr_check_dup(s->attr_check);
706 void clear_pathspec(struct pathspec *pathspec)
708 int i, j;
710 for (i = 0; i < pathspec->nr; i++) {
711 free(pathspec->items[i].match);
712 free(pathspec->items[i].original);
714 for (j = 0; j < pathspec->items[i].attr_match_nr; j++)
715 free(pathspec->items[i].attr_match[j].value);
716 free(pathspec->items[i].attr_match);
718 if (pathspec->items[i].attr_check)
719 attr_check_free(pathspec->items[i].attr_check);
722 FREE_AND_NULL(pathspec->items);
723 pathspec->nr = 0;
726 int match_pathspec_attrs(struct index_state *istate,
727 const char *name, int namelen,
728 const struct pathspec_item *item)
730 int i;
731 char *to_free = NULL;
733 if (name[namelen])
734 name = to_free = xmemdupz(name, namelen);
736 git_check_attr(istate, name, item->attr_check);
738 free(to_free);
740 for (i = 0; i < item->attr_match_nr; i++) {
741 const char *value;
742 int matched;
743 enum attr_match_mode match_mode;
745 value = item->attr_check->items[i].value;
746 match_mode = item->attr_match[i].match_mode;
748 if (ATTR_TRUE(value))
749 matched = (match_mode == MATCH_SET);
750 else if (ATTR_FALSE(value))
751 matched = (match_mode == MATCH_UNSET);
752 else if (ATTR_UNSET(value))
753 matched = (match_mode == MATCH_UNSPECIFIED);
754 else
755 matched = (match_mode == MATCH_VALUE &&
756 !strcmp(item->attr_match[i].value, value));
757 if (!matched)
758 return 0;
761 return 1;