oneway_diff: handle removed sparse directories
[alt-git.git] / pathspec.c
blob84ad9c73cfb50a9fd34eed3b5e68fae522c796fe
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 for (i = 0; i < istate->cache_nr; i++) {
41 const struct cache_entry *ce = istate->cache[i];
42 if (sw_action == PS_IGNORE_SKIP_WORKTREE &&
43 (ce_skip_worktree(ce) || !path_in_sparse_checkout(ce->name, istate)))
44 continue;
45 ce_path_match(istate, ce, pathspec, seen);
50 * Finds which of the given pathspecs match items in the index.
52 * This is a one-shot wrapper around add_pathspec_matches_against_index()
53 * which allocates, populates, and returns a seen[] array indicating the
54 * nature of the "closest" (i.e. most specific) matches which each of the
55 * given pathspecs achieves against all items in the index.
57 char *find_pathspecs_matching_against_index(const struct pathspec *pathspec,
58 struct index_state *istate,
59 enum ps_skip_worktree_action sw_action)
61 char *seen = xcalloc(pathspec->nr, 1);
62 add_pathspec_matches_against_index(pathspec, istate, seen, sw_action);
63 return seen;
66 char *find_pathspecs_matching_skip_worktree(const struct pathspec *pathspec)
68 struct index_state *istate = the_repository->index;
69 char *seen = xcalloc(pathspec->nr, 1);
70 int i;
72 for (i = 0; i < istate->cache_nr; i++) {
73 struct cache_entry *ce = istate->cache[i];
74 if (ce_skip_worktree(ce) || !path_in_sparse_checkout(ce->name, istate))
75 ce_path_match(istate, ce, pathspec, seen);
78 return seen;
82 * Magic pathspec
84 * Possible future magic semantics include stuff like:
86 * { PATHSPEC_RECURSIVE, '*', "recursive" },
87 * { PATHSPEC_REGEXP, '\0', "regexp" },
91 static struct pathspec_magic {
92 unsigned bit;
93 char mnemonic; /* this cannot be ':'! */
94 const char *name;
95 } pathspec_magic[] = {
96 { PATHSPEC_FROMTOP, '/', "top" },
97 { PATHSPEC_LITERAL, '\0', "literal" },
98 { PATHSPEC_GLOB, '\0', "glob" },
99 { PATHSPEC_ICASE, '\0', "icase" },
100 { PATHSPEC_EXCLUDE, '!', "exclude" },
101 { PATHSPEC_ATTR, '\0', "attr" },
104 static void prefix_magic(struct strbuf *sb, int prefixlen, unsigned magic)
106 int i;
107 strbuf_addstr(sb, ":(");
108 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
109 if (magic & pathspec_magic[i].bit) {
110 if (sb->buf[sb->len - 1] != '(')
111 strbuf_addch(sb, ',');
112 strbuf_addstr(sb, pathspec_magic[i].name);
114 strbuf_addf(sb, ",prefix:%d)", prefixlen);
117 static size_t strcspn_escaped(const char *s, const char *stop)
119 const char *i;
121 for (i = s; *i; i++) {
122 /* skip the escaped character */
123 if (i[0] == '\\' && i[1]) {
124 i++;
125 continue;
128 if (strchr(stop, *i))
129 break;
131 return i - s;
134 static inline int invalid_value_char(const char ch)
136 if (isalnum(ch) || strchr(",-_", ch))
137 return 0;
138 return -1;
141 static char *attr_value_unescape(const char *value)
143 const char *src;
144 char *dst, *ret;
146 ret = xmallocz(strlen(value));
147 for (src = value, dst = ret; *src; src++, dst++) {
148 if (*src == '\\') {
149 if (!src[1])
150 die(_("Escape character '\\' not allowed as "
151 "last character in attr value"));
152 src++;
154 if (invalid_value_char(*src))
155 die("cannot use '%c' for value matching", *src);
156 *dst = *src;
158 *dst = '\0';
159 return ret;
162 static void parse_pathspec_attr_match(struct pathspec_item *item, const char *value)
164 struct string_list_item *si;
165 struct string_list list = STRING_LIST_INIT_DUP;
167 if (item->attr_check || item->attr_match)
168 die(_("Only one 'attr:' specification is allowed."));
170 if (!value || !*value)
171 die(_("attr spec must not be empty"));
173 string_list_split(&list, value, ' ', -1);
174 string_list_remove_empty_items(&list, 0);
176 item->attr_check = attr_check_alloc();
177 CALLOC_ARRAY(item->attr_match, list.nr);
179 for_each_string_list_item(si, &list) {
180 size_t attr_len;
181 char *attr_name;
182 const struct git_attr *a;
184 int j = item->attr_match_nr++;
185 const char *attr = si->string;
186 struct attr_match *am = &item->attr_match[j];
188 switch (*attr) {
189 case '!':
190 am->match_mode = MATCH_UNSPECIFIED;
191 attr++;
192 attr_len = strlen(attr);
193 break;
194 case '-':
195 am->match_mode = MATCH_UNSET;
196 attr++;
197 attr_len = strlen(attr);
198 break;
199 default:
200 attr_len = strcspn(attr, "=");
201 if (attr[attr_len] != '=')
202 am->match_mode = MATCH_SET;
203 else {
204 const char *v = &attr[attr_len + 1];
205 am->match_mode = MATCH_VALUE;
206 am->value = attr_value_unescape(v);
208 break;
211 attr_name = xmemdupz(attr, attr_len);
212 a = git_attr(attr_name);
213 if (!a)
214 die(_("invalid attribute name %s"), attr_name);
216 attr_check_append(item->attr_check, a);
218 free(attr_name);
221 if (item->attr_check->nr != item->attr_match_nr)
222 BUG("should have same number of entries");
224 string_list_clear(&list, 0);
227 static inline int get_literal_global(void)
229 static int literal = -1;
231 if (literal < 0)
232 literal = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
234 return literal;
237 static inline int get_glob_global(void)
239 static int glob = -1;
241 if (glob < 0)
242 glob = git_env_bool(GIT_GLOB_PATHSPECS_ENVIRONMENT, 0);
244 return glob;
247 static inline int get_noglob_global(void)
249 static int noglob = -1;
251 if (noglob < 0)
252 noglob = git_env_bool(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, 0);
254 return noglob;
257 static inline int get_icase_global(void)
259 static int icase = -1;
261 if (icase < 0)
262 icase = git_env_bool(GIT_ICASE_PATHSPECS_ENVIRONMENT, 0);
264 return icase;
267 static int get_global_magic(int element_magic)
269 int global_magic = 0;
271 if (get_literal_global())
272 global_magic |= PATHSPEC_LITERAL;
274 /* --glob-pathspec is overridden by :(literal) */
275 if (get_glob_global() && !(element_magic & PATHSPEC_LITERAL))
276 global_magic |= PATHSPEC_GLOB;
278 if (get_glob_global() && get_noglob_global())
279 die(_("global 'glob' and 'noglob' pathspec settings are incompatible"));
281 if (get_icase_global())
282 global_magic |= PATHSPEC_ICASE;
284 if ((global_magic & PATHSPEC_LITERAL) &&
285 (global_magic & ~PATHSPEC_LITERAL))
286 die(_("global 'literal' pathspec setting is incompatible "
287 "with all other global pathspec settings"));
289 /* --noglob-pathspec adds :(literal) _unless_ :(glob) is specified */
290 if (get_noglob_global() && !(element_magic & PATHSPEC_GLOB))
291 global_magic |= PATHSPEC_LITERAL;
293 return global_magic;
297 * Parse the pathspec element looking for long magic
299 * saves all magic in 'magic'
300 * if prefix magic is used, save the prefix length in 'prefix_len'
301 * returns the position in 'elem' after all magic has been parsed
303 static const char *parse_long_magic(unsigned *magic, int *prefix_len,
304 struct pathspec_item *item,
305 const char *elem)
307 const char *pos;
308 const char *nextat;
310 for (pos = elem + 2; *pos && *pos != ')'; pos = nextat) {
311 size_t len = strcspn_escaped(pos, ",)");
312 int i;
314 if (pos[len] == ',')
315 nextat = pos + len + 1; /* handle ',' */
316 else
317 nextat = pos + len; /* handle ')' and '\0' */
319 if (!len)
320 continue;
322 if (starts_with(pos, "prefix:")) {
323 char *endptr;
324 *prefix_len = strtol(pos + 7, &endptr, 10);
325 if (endptr - pos != len)
326 die(_("invalid parameter for pathspec magic 'prefix'"));
327 continue;
330 if (starts_with(pos, "attr:")) {
331 char *attr_body = xmemdupz(pos + 5, len - 5);
332 parse_pathspec_attr_match(item, attr_body);
333 *magic |= PATHSPEC_ATTR;
334 free(attr_body);
335 continue;
338 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
339 if (strlen(pathspec_magic[i].name) == len &&
340 !strncmp(pathspec_magic[i].name, pos, len)) {
341 *magic |= pathspec_magic[i].bit;
342 break;
346 if (ARRAY_SIZE(pathspec_magic) <= i)
347 die(_("Invalid pathspec magic '%.*s' in '%s'"),
348 (int) len, pos, elem);
351 if (*pos != ')')
352 die(_("Missing ')' at the end of pathspec magic in '%s'"),
353 elem);
354 pos++;
356 return pos;
360 * Parse the pathspec element looking for short magic
362 * saves all magic in 'magic'
363 * returns the position in 'elem' after all magic has been parsed
365 static const char *parse_short_magic(unsigned *magic, const char *elem)
367 const char *pos;
369 for (pos = elem + 1; *pos && *pos != ':'; pos++) {
370 char ch = *pos;
371 int i;
373 /* Special case alias for '!' */
374 if (ch == '^') {
375 *magic |= PATHSPEC_EXCLUDE;
376 continue;
379 if (!is_pathspec_magic(ch))
380 break;
382 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
383 if (pathspec_magic[i].mnemonic == ch) {
384 *magic |= pathspec_magic[i].bit;
385 break;
389 if (ARRAY_SIZE(pathspec_magic) <= i)
390 die(_("Unimplemented pathspec magic '%c' in '%s'"),
391 ch, elem);
394 if (*pos == ':')
395 pos++;
397 return pos;
400 static const char *parse_element_magic(unsigned *magic, int *prefix_len,
401 struct pathspec_item *item,
402 const char *elem)
404 if (elem[0] != ':' || get_literal_global())
405 return elem; /* nothing to do */
406 else if (elem[1] == '(')
407 /* longhand */
408 return parse_long_magic(magic, prefix_len, item, elem);
409 else
410 /* shorthand */
411 return parse_short_magic(magic, elem);
415 * Perform the initialization of a pathspec_item based on a pathspec element.
417 static void init_pathspec_item(struct pathspec_item *item, unsigned flags,
418 const char *prefix, int prefixlen,
419 const char *elt)
421 unsigned magic = 0, element_magic = 0;
422 const char *copyfrom = elt;
423 char *match;
424 int pathspec_prefix = -1;
426 item->attr_check = NULL;
427 item->attr_match = NULL;
428 item->attr_match_nr = 0;
430 /* PATHSPEC_LITERAL_PATH ignores magic */
431 if (flags & PATHSPEC_LITERAL_PATH) {
432 magic = PATHSPEC_LITERAL;
433 } else {
434 copyfrom = parse_element_magic(&element_magic,
435 &pathspec_prefix,
436 item,
437 elt);
438 magic |= element_magic;
439 magic |= get_global_magic(element_magic);
442 item->magic = magic;
444 if (pathspec_prefix >= 0 &&
445 (prefixlen || (prefix && *prefix)))
446 BUG("'prefix' magic is supposed to be used at worktree's root");
448 if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
449 die(_("%s: 'literal' and 'glob' are incompatible"), elt);
451 /* Create match string which will be used for pathspec matching */
452 if (pathspec_prefix >= 0) {
453 match = xstrdup(copyfrom);
454 prefixlen = pathspec_prefix;
455 } else if (magic & PATHSPEC_FROMTOP) {
456 match = xstrdup(copyfrom);
457 prefixlen = 0;
458 } else {
459 match = prefix_path_gently(prefix, prefixlen,
460 &prefixlen, copyfrom);
461 if (!match) {
462 const char *hint_path = get_git_work_tree();
463 if (!hint_path)
464 hint_path = get_git_dir();
465 die(_("%s: '%s' is outside repository at '%s'"), elt,
466 copyfrom, absolute_path(hint_path));
470 item->match = match;
471 item->len = strlen(item->match);
472 item->prefix = prefixlen;
475 * Prefix the pathspec (keep all magic) and assign to
476 * original. Useful for passing to another command.
478 if ((flags & PATHSPEC_PREFIX_ORIGIN) &&
479 !get_literal_global()) {
480 struct strbuf sb = STRBUF_INIT;
482 /* Preserve the actual prefix length of each pattern */
483 prefix_magic(&sb, prefixlen, element_magic);
485 strbuf_addstr(&sb, match);
486 item->original = strbuf_detach(&sb, NULL);
487 } else {
488 item->original = xstrdup(elt);
491 if (magic & PATHSPEC_LITERAL) {
492 item->nowildcard_len = item->len;
493 } else {
494 item->nowildcard_len = simple_length(item->match);
495 if (item->nowildcard_len < prefixlen)
496 item->nowildcard_len = prefixlen;
499 item->flags = 0;
500 if (magic & PATHSPEC_GLOB) {
502 * FIXME: should we enable ONESTAR in _GLOB for
503 * pattern "* * / * . c"?
505 } else {
506 if (item->nowildcard_len < item->len &&
507 item->match[item->nowildcard_len] == '*' &&
508 no_wildcard(item->match + item->nowildcard_len + 1))
509 item->flags |= PATHSPEC_ONESTAR;
512 /* sanity checks, pathspec matchers assume these are sane */
513 if (item->nowildcard_len > item->len ||
514 item->prefix > item->len) {
515 BUG("error initializing pathspec_item");
519 static int pathspec_item_cmp(const void *a_, const void *b_)
521 struct pathspec_item *a, *b;
523 a = (struct pathspec_item *)a_;
524 b = (struct pathspec_item *)b_;
525 return strcmp(a->match, b->match);
528 static void NORETURN unsupported_magic(const char *pattern,
529 unsigned magic)
531 struct strbuf sb = STRBUF_INIT;
532 int i;
533 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
534 const struct pathspec_magic *m = pathspec_magic + i;
535 if (!(magic & m->bit))
536 continue;
537 if (sb.len)
538 strbuf_addstr(&sb, ", ");
540 if (m->mnemonic)
541 strbuf_addf(&sb, _("'%s' (mnemonic: '%c')"),
542 m->name, m->mnemonic);
543 else
544 strbuf_addf(&sb, "'%s'", m->name);
547 * We may want to substitute "this command" with a command
548 * name. E.g. when add--interactive dies when running
549 * "checkout -p"
551 die(_("%s: pathspec magic not supported by this command: %s"),
552 pattern, sb.buf);
555 void parse_pathspec(struct pathspec *pathspec,
556 unsigned magic_mask, unsigned flags,
557 const char *prefix, const char **argv)
559 struct pathspec_item *item;
560 const char *entry = argv ? *argv : NULL;
561 int i, n, prefixlen, nr_exclude = 0;
563 memset(pathspec, 0, sizeof(*pathspec));
565 if (flags & PATHSPEC_MAXDEPTH_VALID)
566 pathspec->magic |= PATHSPEC_MAXDEPTH;
568 /* No arguments, no prefix -> no pathspec */
569 if (!entry && !prefix)
570 return;
572 if ((flags & PATHSPEC_PREFER_CWD) &&
573 (flags & PATHSPEC_PREFER_FULL))
574 BUG("PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
576 /* No arguments with prefix -> prefix pathspec */
577 if (!entry) {
578 if (flags & PATHSPEC_PREFER_FULL)
579 return;
581 if (!(flags & PATHSPEC_PREFER_CWD))
582 BUG("PATHSPEC_PREFER_CWD requires arguments");
584 pathspec->items = CALLOC_ARRAY(item, 1);
585 item->match = xstrdup(prefix);
586 item->original = xstrdup(prefix);
587 item->nowildcard_len = item->len = strlen(prefix);
588 item->prefix = item->len;
589 pathspec->nr = 1;
590 return;
593 n = 0;
594 while (argv[n]) {
595 if (*argv[n] == '\0')
596 die("empty string is not a valid pathspec. "
597 "please use . instead if you meant to match all paths");
598 n++;
601 pathspec->nr = n;
602 ALLOC_ARRAY(pathspec->items, n + 1);
603 item = pathspec->items;
604 prefixlen = prefix ? strlen(prefix) : 0;
606 for (i = 0; i < n; i++) {
607 entry = argv[i];
609 init_pathspec_item(item + i, flags, prefix, prefixlen, entry);
611 if (item[i].magic & PATHSPEC_EXCLUDE)
612 nr_exclude++;
613 if (item[i].magic & magic_mask)
614 unsupported_magic(entry, item[i].magic & magic_mask);
616 if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
617 has_symlink_leading_path(item[i].match, item[i].len)) {
618 die(_("pathspec '%s' is beyond a symbolic link"), entry);
621 if (item[i].nowildcard_len < item[i].len)
622 pathspec->has_wildcard = 1;
623 pathspec->magic |= item[i].magic;
627 * If everything is an exclude pattern, add one positive pattern
628 * that matches everything. We allocated an extra one for this.
630 if (nr_exclude == n) {
631 int plen = (!(flags & PATHSPEC_PREFER_CWD)) ? 0 : prefixlen;
632 init_pathspec_item(item + n, 0, prefix, plen, ".");
633 pathspec->nr++;
636 if (pathspec->magic & PATHSPEC_MAXDEPTH) {
637 if (flags & PATHSPEC_KEEP_ORDER)
638 BUG("PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
639 QSORT(pathspec->items, pathspec->nr, pathspec_item_cmp);
643 void parse_pathspec_file(struct pathspec *pathspec, unsigned magic_mask,
644 unsigned flags, const char *prefix,
645 const char *file, int nul_term_line)
647 struct strvec parsed_file = STRVEC_INIT;
648 strbuf_getline_fn getline_fn = nul_term_line ? strbuf_getline_nul :
649 strbuf_getline;
650 struct strbuf buf = STRBUF_INIT;
651 struct strbuf unquoted = STRBUF_INIT;
652 FILE *in;
654 if (!strcmp(file, "-"))
655 in = stdin;
656 else
657 in = xfopen(file, "r");
659 while (getline_fn(&buf, in) != EOF) {
660 if (!nul_term_line && buf.buf[0] == '"') {
661 strbuf_reset(&unquoted);
662 if (unquote_c_style(&unquoted, buf.buf, NULL))
663 die(_("line is badly quoted: %s"), buf.buf);
664 strbuf_swap(&buf, &unquoted);
666 strvec_push(&parsed_file, buf.buf);
667 strbuf_reset(&buf);
670 strbuf_release(&unquoted);
671 strbuf_release(&buf);
672 if (in != stdin)
673 fclose(in);
675 parse_pathspec(pathspec, magic_mask, flags, prefix, parsed_file.v);
676 strvec_clear(&parsed_file);
679 void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
681 int i, j;
683 *dst = *src;
684 ALLOC_ARRAY(dst->items, dst->nr);
685 COPY_ARRAY(dst->items, src->items, dst->nr);
687 for (i = 0; i < dst->nr; i++) {
688 struct pathspec_item *d = &dst->items[i];
689 struct pathspec_item *s = &src->items[i];
691 d->match = xstrdup(s->match);
692 d->original = xstrdup(s->original);
694 ALLOC_ARRAY(d->attr_match, d->attr_match_nr);
695 COPY_ARRAY(d->attr_match, s->attr_match, d->attr_match_nr);
696 for (j = 0; j < d->attr_match_nr; j++) {
697 const char *value = s->attr_match[j].value;
698 d->attr_match[j].value = xstrdup_or_null(value);
701 d->attr_check = attr_check_dup(s->attr_check);
705 void clear_pathspec(struct pathspec *pathspec)
707 int i, j;
709 for (i = 0; i < pathspec->nr; i++) {
710 free(pathspec->items[i].match);
711 free(pathspec->items[i].original);
713 for (j = 0; j < pathspec->items[i].attr_match_nr; j++)
714 free(pathspec->items[i].attr_match[j].value);
715 free(pathspec->items[i].attr_match);
717 if (pathspec->items[i].attr_check)
718 attr_check_free(pathspec->items[i].attr_check);
721 FREE_AND_NULL(pathspec->items);
722 pathspec->nr = 0;
725 int match_pathspec_attrs(struct index_state *istate,
726 const char *name, int namelen,
727 const struct pathspec_item *item)
729 int i;
730 char *to_free = NULL;
732 if (name[namelen])
733 name = to_free = xmemdupz(name, namelen);
735 git_check_attr(istate, name, item->attr_check);
737 free(to_free);
739 for (i = 0; i < item->attr_match_nr; i++) {
740 const char *value;
741 int matched;
742 enum attr_match_mode match_mode;
744 value = item->attr_check->items[i].value;
745 match_mode = item->attr_match[i].match_mode;
747 if (ATTR_TRUE(value))
748 matched = (match_mode == MATCH_SET);
749 else if (ATTR_FALSE(value))
750 matched = (match_mode == MATCH_UNSET);
751 else if (ATTR_UNSET(value))
752 matched = (match_mode == MATCH_UNSPECIFIED);
753 else
754 matched = (match_mode == MATCH_VALUE &&
755 !strcmp(item->attr_match[i].value, value));
756 if (!matched)
757 return 0;
760 return 1;