object-store.h: teach for_each_packed_object to ignore kept packs
[git/debian.git] / pathspec.c
blob44306fdaca2ee817c64b50089a25a2a35748cc34
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 && ce_skip_worktree(ce))
43 continue;
44 ce_path_match(istate, ce, pathspec, seen);
49 * Finds which of the given pathspecs match items in the index.
51 * This is a one-shot wrapper around add_pathspec_matches_against_index()
52 * which allocates, populates, and returns a seen[] array indicating the
53 * nature of the "closest" (i.e. most specific) matches which each of the
54 * given pathspecs achieves against all items in the index.
56 char *find_pathspecs_matching_against_index(const struct pathspec *pathspec,
57 struct index_state *istate,
58 enum ps_skip_worktree_action sw_action)
60 char *seen = xcalloc(pathspec->nr, 1);
61 add_pathspec_matches_against_index(pathspec, istate, seen, sw_action);
62 return seen;
65 char *find_pathspecs_matching_skip_worktree(const struct pathspec *pathspec)
67 struct index_state *istate = the_repository->index;
68 char *seen = xcalloc(pathspec->nr, 1);
69 int i;
71 for (i = 0; i < istate->cache_nr; i++) {
72 struct cache_entry *ce = istate->cache[i];
73 if (ce_skip_worktree(ce))
74 ce_path_match(istate, ce, pathspec, seen);
77 return seen;
81 * Magic pathspec
83 * Possible future magic semantics include stuff like:
85 * { PATHSPEC_RECURSIVE, '*', "recursive" },
86 * { PATHSPEC_REGEXP, '\0', "regexp" },
90 static struct pathspec_magic {
91 unsigned bit;
92 char mnemonic; /* this cannot be ':'! */
93 const char *name;
94 } pathspec_magic[] = {
95 { PATHSPEC_FROMTOP, '/', "top" },
96 { PATHSPEC_LITERAL, '\0', "literal" },
97 { PATHSPEC_GLOB, '\0', "glob" },
98 { PATHSPEC_ICASE, '\0', "icase" },
99 { PATHSPEC_EXCLUDE, '!', "exclude" },
100 { PATHSPEC_ATTR, '\0', "attr" },
103 static void prefix_magic(struct strbuf *sb, int prefixlen, unsigned magic)
105 int i;
106 strbuf_addstr(sb, ":(");
107 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
108 if (magic & pathspec_magic[i].bit) {
109 if (sb->buf[sb->len - 1] != '(')
110 strbuf_addch(sb, ',');
111 strbuf_addstr(sb, pathspec_magic[i].name);
113 strbuf_addf(sb, ",prefix:%d)", prefixlen);
116 static size_t strcspn_escaped(const char *s, const char *stop)
118 const char *i;
120 for (i = s; *i; i++) {
121 /* skip the escaped character */
122 if (i[0] == '\\' && i[1]) {
123 i++;
124 continue;
127 if (strchr(stop, *i))
128 break;
130 return i - s;
133 static inline int invalid_value_char(const char ch)
135 if (isalnum(ch) || strchr(",-_", ch))
136 return 0;
137 return -1;
140 static char *attr_value_unescape(const char *value)
142 const char *src;
143 char *dst, *ret;
145 ret = xmallocz(strlen(value));
146 for (src = value, dst = ret; *src; src++, dst++) {
147 if (*src == '\\') {
148 if (!src[1])
149 die(_("Escape character '\\' not allowed as "
150 "last character in attr value"));
151 src++;
153 if (invalid_value_char(*src))
154 die("cannot use '%c' for value matching", *src);
155 *dst = *src;
157 *dst = '\0';
158 return ret;
161 static void parse_pathspec_attr_match(struct pathspec_item *item, const char *value)
163 struct string_list_item *si;
164 struct string_list list = STRING_LIST_INIT_DUP;
166 if (item->attr_check || item->attr_match)
167 die(_("Only one 'attr:' specification is allowed."));
169 if (!value || !*value)
170 die(_("attr spec must not be empty"));
172 string_list_split(&list, value, ' ', -1);
173 string_list_remove_empty_items(&list, 0);
175 item->attr_check = attr_check_alloc();
176 CALLOC_ARRAY(item->attr_match, list.nr);
178 for_each_string_list_item(si, &list) {
179 size_t attr_len;
180 char *attr_name;
181 const struct git_attr *a;
183 int j = item->attr_match_nr++;
184 const char *attr = si->string;
185 struct attr_match *am = &item->attr_match[j];
187 switch (*attr) {
188 case '!':
189 am->match_mode = MATCH_UNSPECIFIED;
190 attr++;
191 attr_len = strlen(attr);
192 break;
193 case '-':
194 am->match_mode = MATCH_UNSET;
195 attr++;
196 attr_len = strlen(attr);
197 break;
198 default:
199 attr_len = strcspn(attr, "=");
200 if (attr[attr_len] != '=')
201 am->match_mode = MATCH_SET;
202 else {
203 const char *v = &attr[attr_len + 1];
204 am->match_mode = MATCH_VALUE;
205 am->value = attr_value_unescape(v);
207 break;
210 attr_name = xmemdupz(attr, attr_len);
211 a = git_attr(attr_name);
212 if (!a)
213 die(_("invalid attribute name %s"), attr_name);
215 attr_check_append(item->attr_check, a);
217 free(attr_name);
220 if (item->attr_check->nr != item->attr_match_nr)
221 BUG("should have same number of entries");
223 string_list_clear(&list, 0);
226 static inline int get_literal_global(void)
228 static int literal = -1;
230 if (literal < 0)
231 literal = git_env_bool(GIT_LITERAL_PATHSPECS_ENVIRONMENT, 0);
233 return literal;
236 static inline int get_glob_global(void)
238 static int glob = -1;
240 if (glob < 0)
241 glob = git_env_bool(GIT_GLOB_PATHSPECS_ENVIRONMENT, 0);
243 return glob;
246 static inline int get_noglob_global(void)
248 static int noglob = -1;
250 if (noglob < 0)
251 noglob = git_env_bool(GIT_NOGLOB_PATHSPECS_ENVIRONMENT, 0);
253 return noglob;
256 static inline int get_icase_global(void)
258 static int icase = -1;
260 if (icase < 0)
261 icase = git_env_bool(GIT_ICASE_PATHSPECS_ENVIRONMENT, 0);
263 return icase;
266 static int get_global_magic(int element_magic)
268 int global_magic = 0;
270 if (get_literal_global())
271 global_magic |= PATHSPEC_LITERAL;
273 /* --glob-pathspec is overridden by :(literal) */
274 if (get_glob_global() && !(element_magic & PATHSPEC_LITERAL))
275 global_magic |= PATHSPEC_GLOB;
277 if (get_glob_global() && get_noglob_global())
278 die(_("global 'glob' and 'noglob' pathspec settings are incompatible"));
280 if (get_icase_global())
281 global_magic |= PATHSPEC_ICASE;
283 if ((global_magic & PATHSPEC_LITERAL) &&
284 (global_magic & ~PATHSPEC_LITERAL))
285 die(_("global 'literal' pathspec setting is incompatible "
286 "with all other global pathspec settings"));
288 /* --noglob-pathspec adds :(literal) _unless_ :(glob) is specified */
289 if (get_noglob_global() && !(element_magic & PATHSPEC_GLOB))
290 global_magic |= PATHSPEC_LITERAL;
292 return global_magic;
296 * Parse the pathspec element looking for long magic
298 * saves all magic in 'magic'
299 * if prefix magic is used, save the prefix length in 'prefix_len'
300 * returns the position in 'elem' after all magic has been parsed
302 static const char *parse_long_magic(unsigned *magic, int *prefix_len,
303 struct pathspec_item *item,
304 const char *elem)
306 const char *pos;
307 const char *nextat;
309 for (pos = elem + 2; *pos && *pos != ')'; pos = nextat) {
310 size_t len = strcspn_escaped(pos, ",)");
311 int i;
313 if (pos[len] == ',')
314 nextat = pos + len + 1; /* handle ',' */
315 else
316 nextat = pos + len; /* handle ')' and '\0' */
318 if (!len)
319 continue;
321 if (starts_with(pos, "prefix:")) {
322 char *endptr;
323 *prefix_len = strtol(pos + 7, &endptr, 10);
324 if (endptr - pos != len)
325 die(_("invalid parameter for pathspec magic 'prefix'"));
326 continue;
329 if (starts_with(pos, "attr:")) {
330 char *attr_body = xmemdupz(pos + 5, len - 5);
331 parse_pathspec_attr_match(item, attr_body);
332 *magic |= PATHSPEC_ATTR;
333 free(attr_body);
334 continue;
337 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
338 if (strlen(pathspec_magic[i].name) == len &&
339 !strncmp(pathspec_magic[i].name, pos, len)) {
340 *magic |= pathspec_magic[i].bit;
341 break;
345 if (ARRAY_SIZE(pathspec_magic) <= i)
346 die(_("Invalid pathspec magic '%.*s' in '%s'"),
347 (int) len, pos, elem);
350 if (*pos != ')')
351 die(_("Missing ')' at the end of pathspec magic in '%s'"),
352 elem);
353 pos++;
355 return pos;
359 * Parse the pathspec element looking for short magic
361 * saves all magic in 'magic'
362 * returns the position in 'elem' after all magic has been parsed
364 static const char *parse_short_magic(unsigned *magic, const char *elem)
366 const char *pos;
368 for (pos = elem + 1; *pos && *pos != ':'; pos++) {
369 char ch = *pos;
370 int i;
372 /* Special case alias for '!' */
373 if (ch == '^') {
374 *magic |= PATHSPEC_EXCLUDE;
375 continue;
378 if (!is_pathspec_magic(ch))
379 break;
381 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
382 if (pathspec_magic[i].mnemonic == ch) {
383 *magic |= pathspec_magic[i].bit;
384 break;
388 if (ARRAY_SIZE(pathspec_magic) <= i)
389 die(_("Unimplemented pathspec magic '%c' in '%s'"),
390 ch, elem);
393 if (*pos == ':')
394 pos++;
396 return pos;
399 static const char *parse_element_magic(unsigned *magic, int *prefix_len,
400 struct pathspec_item *item,
401 const char *elem)
403 if (elem[0] != ':' || get_literal_global())
404 return elem; /* nothing to do */
405 else if (elem[1] == '(')
406 /* longhand */
407 return parse_long_magic(magic, prefix_len, item, elem);
408 else
409 /* shorthand */
410 return parse_short_magic(magic, elem);
414 * Perform the initialization of a pathspec_item based on a pathspec element.
416 static void init_pathspec_item(struct pathspec_item *item, unsigned flags,
417 const char *prefix, int prefixlen,
418 const char *elt)
420 unsigned magic = 0, element_magic = 0;
421 const char *copyfrom = elt;
422 char *match;
423 int pathspec_prefix = -1;
425 item->attr_check = NULL;
426 item->attr_match = NULL;
427 item->attr_match_nr = 0;
429 /* PATHSPEC_LITERAL_PATH ignores magic */
430 if (flags & PATHSPEC_LITERAL_PATH) {
431 magic = PATHSPEC_LITERAL;
432 } else {
433 copyfrom = parse_element_magic(&element_magic,
434 &pathspec_prefix,
435 item,
436 elt);
437 magic |= element_magic;
438 magic |= get_global_magic(element_magic);
441 item->magic = magic;
443 if (pathspec_prefix >= 0 &&
444 (prefixlen || (prefix && *prefix)))
445 BUG("'prefix' magic is supposed to be used at worktree's root");
447 if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
448 die(_("%s: 'literal' and 'glob' are incompatible"), elt);
450 /* Create match string which will be used for pathspec matching */
451 if (pathspec_prefix >= 0) {
452 match = xstrdup(copyfrom);
453 prefixlen = pathspec_prefix;
454 } else if (magic & PATHSPEC_FROMTOP) {
455 match = xstrdup(copyfrom);
456 prefixlen = 0;
457 } else {
458 match = prefix_path_gently(prefix, prefixlen,
459 &prefixlen, copyfrom);
460 if (!match) {
461 const char *hint_path = get_git_work_tree();
462 if (!hint_path)
463 hint_path = get_git_dir();
464 die(_("%s: '%s' is outside repository at '%s'"), elt,
465 copyfrom, absolute_path(hint_path));
469 item->match = match;
470 item->len = strlen(item->match);
471 item->prefix = prefixlen;
474 * Prefix the pathspec (keep all magic) and assign to
475 * original. Useful for passing to another command.
477 if ((flags & PATHSPEC_PREFIX_ORIGIN) &&
478 !get_literal_global()) {
479 struct strbuf sb = STRBUF_INIT;
481 /* Preserve the actual prefix length of each pattern */
482 prefix_magic(&sb, prefixlen, element_magic);
484 strbuf_addstr(&sb, match);
485 item->original = strbuf_detach(&sb, NULL);
486 } else {
487 item->original = xstrdup(elt);
490 if (magic & PATHSPEC_LITERAL) {
491 item->nowildcard_len = item->len;
492 } else {
493 item->nowildcard_len = simple_length(item->match);
494 if (item->nowildcard_len < prefixlen)
495 item->nowildcard_len = prefixlen;
498 item->flags = 0;
499 if (magic & PATHSPEC_GLOB) {
501 * FIXME: should we enable ONESTAR in _GLOB for
502 * pattern "* * / * . c"?
504 } else {
505 if (item->nowildcard_len < item->len &&
506 item->match[item->nowildcard_len] == '*' &&
507 no_wildcard(item->match + item->nowildcard_len + 1))
508 item->flags |= PATHSPEC_ONESTAR;
511 /* sanity checks, pathspec matchers assume these are sane */
512 if (item->nowildcard_len > item->len ||
513 item->prefix > item->len) {
514 BUG("error initializing pathspec_item");
518 static int pathspec_item_cmp(const void *a_, const void *b_)
520 struct pathspec_item *a, *b;
522 a = (struct pathspec_item *)a_;
523 b = (struct pathspec_item *)b_;
524 return strcmp(a->match, b->match);
527 static void NORETURN unsupported_magic(const char *pattern,
528 unsigned magic)
530 struct strbuf sb = STRBUF_INIT;
531 int i;
532 for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
533 const struct pathspec_magic *m = pathspec_magic + i;
534 if (!(magic & m->bit))
535 continue;
536 if (sb.len)
537 strbuf_addstr(&sb, ", ");
539 if (m->mnemonic)
540 strbuf_addf(&sb, _("'%s' (mnemonic: '%c')"),
541 m->name, m->mnemonic);
542 else
543 strbuf_addf(&sb, "'%s'", m->name);
546 * We may want to substitute "this command" with a command
547 * name. E.g. when add--interactive dies when running
548 * "checkout -p"
550 die(_("%s: pathspec magic not supported by this command: %s"),
551 pattern, sb.buf);
554 void parse_pathspec(struct pathspec *pathspec,
555 unsigned magic_mask, unsigned flags,
556 const char *prefix, const char **argv)
558 struct pathspec_item *item;
559 const char *entry = argv ? *argv : NULL;
560 int i, n, prefixlen, nr_exclude = 0;
562 memset(pathspec, 0, sizeof(*pathspec));
564 if (flags & PATHSPEC_MAXDEPTH_VALID)
565 pathspec->magic |= PATHSPEC_MAXDEPTH;
567 /* No arguments, no prefix -> no pathspec */
568 if (!entry && !prefix)
569 return;
571 if ((flags & PATHSPEC_PREFER_CWD) &&
572 (flags & PATHSPEC_PREFER_FULL))
573 BUG("PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
575 /* No arguments with prefix -> prefix pathspec */
576 if (!entry) {
577 if (flags & PATHSPEC_PREFER_FULL)
578 return;
580 if (!(flags & PATHSPEC_PREFER_CWD))
581 BUG("PATHSPEC_PREFER_CWD requires arguments");
583 pathspec->items = CALLOC_ARRAY(item, 1);
584 item->match = xstrdup(prefix);
585 item->original = xstrdup(prefix);
586 item->nowildcard_len = item->len = strlen(prefix);
587 item->prefix = item->len;
588 pathspec->nr = 1;
589 return;
592 n = 0;
593 while (argv[n]) {
594 if (*argv[n] == '\0')
595 die("empty string is not a valid pathspec. "
596 "please use . instead if you meant to match all paths");
597 n++;
600 pathspec->nr = n;
601 ALLOC_ARRAY(pathspec->items, n + 1);
602 item = pathspec->items;
603 prefixlen = prefix ? strlen(prefix) : 0;
605 for (i = 0; i < n; i++) {
606 entry = argv[i];
608 init_pathspec_item(item + i, flags, prefix, prefixlen, entry);
610 if (item[i].magic & PATHSPEC_EXCLUDE)
611 nr_exclude++;
612 if (item[i].magic & magic_mask)
613 unsupported_magic(entry, item[i].magic & magic_mask);
615 if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
616 has_symlink_leading_path(item[i].match, item[i].len)) {
617 die(_("pathspec '%s' is beyond a symbolic link"), entry);
620 if (item[i].nowildcard_len < item[i].len)
621 pathspec->has_wildcard = 1;
622 pathspec->magic |= item[i].magic;
626 * If everything is an exclude pattern, add one positive pattern
627 * that matches everything. We allocated an extra one for this.
629 if (nr_exclude == n) {
630 int plen = (!(flags & PATHSPEC_PREFER_CWD)) ? 0 : prefixlen;
631 init_pathspec_item(item + n, 0, prefix, plen, "");
632 pathspec->nr++;
635 if (pathspec->magic & PATHSPEC_MAXDEPTH) {
636 if (flags & PATHSPEC_KEEP_ORDER)
637 BUG("PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
638 QSORT(pathspec->items, pathspec->nr, pathspec_item_cmp);
642 void parse_pathspec_file(struct pathspec *pathspec, unsigned magic_mask,
643 unsigned flags, const char *prefix,
644 const char *file, int nul_term_line)
646 struct strvec parsed_file = STRVEC_INIT;
647 strbuf_getline_fn getline_fn = nul_term_line ? strbuf_getline_nul :
648 strbuf_getline;
649 struct strbuf buf = STRBUF_INIT;
650 struct strbuf unquoted = STRBUF_INIT;
651 FILE *in;
653 if (!strcmp(file, "-"))
654 in = stdin;
655 else
656 in = xfopen(file, "r");
658 while (getline_fn(&buf, in) != EOF) {
659 if (!nul_term_line && buf.buf[0] == '"') {
660 strbuf_reset(&unquoted);
661 if (unquote_c_style(&unquoted, buf.buf, NULL))
662 die(_("line is badly quoted: %s"), buf.buf);
663 strbuf_swap(&buf, &unquoted);
665 strvec_push(&parsed_file, buf.buf);
666 strbuf_reset(&buf);
669 strbuf_release(&unquoted);
670 strbuf_release(&buf);
671 if (in != stdin)
672 fclose(in);
674 parse_pathspec(pathspec, magic_mask, flags, prefix, parsed_file.v);
675 strvec_clear(&parsed_file);
678 void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
680 int i, j;
682 *dst = *src;
683 ALLOC_ARRAY(dst->items, dst->nr);
684 COPY_ARRAY(dst->items, src->items, dst->nr);
686 for (i = 0; i < dst->nr; i++) {
687 struct pathspec_item *d = &dst->items[i];
688 struct pathspec_item *s = &src->items[i];
690 d->match = xstrdup(s->match);
691 d->original = xstrdup(s->original);
693 ALLOC_ARRAY(d->attr_match, d->attr_match_nr);
694 COPY_ARRAY(d->attr_match, s->attr_match, d->attr_match_nr);
695 for (j = 0; j < d->attr_match_nr; j++) {
696 const char *value = s->attr_match[j].value;
697 d->attr_match[j].value = xstrdup_or_null(value);
700 d->attr_check = attr_check_dup(s->attr_check);
704 void clear_pathspec(struct pathspec *pathspec)
706 int i, j;
708 for (i = 0; i < pathspec->nr; i++) {
709 free(pathspec->items[i].match);
710 free(pathspec->items[i].original);
712 for (j = 0; j < pathspec->items[i].attr_match_nr; j++)
713 free(pathspec->items[i].attr_match[j].value);
714 free(pathspec->items[i].attr_match);
716 if (pathspec->items[i].attr_check)
717 attr_check_free(pathspec->items[i].attr_check);
720 FREE_AND_NULL(pathspec->items);
721 pathspec->nr = 0;
724 int match_pathspec_attrs(struct index_state *istate,
725 const char *name, int namelen,
726 const struct pathspec_item *item)
728 int i;
729 char *to_free = NULL;
731 if (name[namelen])
732 name = to_free = xmemdupz(name, namelen);
734 git_check_attr(istate, name, item->attr_check);
736 free(to_free);
738 for (i = 0; i < item->attr_match_nr; i++) {
739 const char *value;
740 int matched;
741 enum attr_match_mode match_mode;
743 value = item->attr_check->items[i].value;
744 match_mode = item->attr_match[i].match_mode;
746 if (ATTR_TRUE(value))
747 matched = (match_mode == MATCH_SET);
748 else if (ATTR_FALSE(value))
749 matched = (match_mode == MATCH_UNSET);
750 else if (ATTR_UNSET(value))
751 matched = (match_mode == MATCH_UNSPECIFIED);
752 else
753 matched = (match_mode == MATCH_VALUE &&
754 !strcmp(item->attr_match[i].value, value));
755 if (!matched)
756 return 0;
759 return 1;