parse_pathspec: preserve prefix length via PATHSPEC_PREFIX_ORIGIN
[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_NOGLOB, '!', "noglob" },
61  *      { PATHSPEC_ICASE, '\0', "icase" },
62  *      { PATHSPEC_RECURSIVE, '*', "recursive" },
63  *      { PATHSPEC_REGEXP, '\0', "regexp" },
64  *
65  */
66
67 static struct pathspec_magic {
68         unsigned bit;
69         char mnemonic; /* this cannot be ':'! */
70         const char *name;
71 } pathspec_magic[] = {
72         { PATHSPEC_FROMTOP, '/', "top" },
73 };
74
75 /*
76  * Take an element of a pathspec and check for magic signatures.
77  * Append the result to the prefix. Return the magic bitmap.
78  *
79  * For now, we only parse the syntax and throw out anything other than
80  * "top" magic.
81  *
82  * NEEDSWORK: This needs to be rewritten when we start migrating
83  * get_pathspec() users to use the "struct pathspec" interface.  For
84  * example, a pathspec element may be marked as case-insensitive, but
85  * the prefix part must always match literally, and a single stupid
86  * string cannot express such a case.
87  */
88 static unsigned prefix_pathspec(struct pathspec_item *item,
89                                 unsigned *p_short_magic,
90                                 const char **raw, unsigned flags,
91                                 const char *prefix, int prefixlen,
92                                 const char *elt)
93 {
94         unsigned magic = 0, short_magic = 0;
95         const char *copyfrom = elt, *long_magic_end = NULL;
96         char *match;
97         int i, pathspec_prefix = -1;
98
99         if (elt[0] != ':') {
100                 ; /* nothing to do */
101         } else if (elt[1] == '(') {
102                 /* longhand */
103                 const char *nextat;
104                 for (copyfrom = elt + 2;
105                      *copyfrom && *copyfrom != ')';
106                      copyfrom = nextat) {
107                         size_t len = strcspn(copyfrom, ",)");
108                         if (copyfrom[len] == ',')
109                                 nextat = copyfrom + len + 1;
110                         else
111                                 /* handle ')' and '\0' */
112                                 nextat = copyfrom + len;
113                         if (!len)
114                                 continue;
115                         for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
116                                 if (strlen(pathspec_magic[i].name) == len &&
117                                     !strncmp(pathspec_magic[i].name, copyfrom, len)) {
118                                         magic |= pathspec_magic[i].bit;
119                                         break;
120                                 }
121                                 if (!prefixcmp(copyfrom, "prefix:")) {
122                                         char *endptr;
123                                         pathspec_prefix = strtol(copyfrom + 7,
124                                                                  &endptr, 10);
125                                         if (endptr - copyfrom != len)
126                                                 die(_("invalid parameter for pathspec magic 'prefix'"));
127                                         /* "i" would be wrong, but it does not matter */
128                                         break;
129                                 }
130                         }
131                         if (ARRAY_SIZE(pathspec_magic) <= i)
132                                 die(_("Invalid pathspec magic '%.*s' in '%s'"),
133                                     (int) len, copyfrom, elt);
134                 }
135                 if (*copyfrom != ')')
136                         die(_("Missing ')' at the end of pathspec magic in '%s'"), elt);
137                 long_magic_end = copyfrom;
138                 copyfrom++;
139         } else {
140                 /* shorthand */
141                 for (copyfrom = elt + 1;
142                      *copyfrom && *copyfrom != ':';
143                      copyfrom++) {
144                         char ch = *copyfrom;
145
146                         if (!is_pathspec_magic(ch))
147                                 break;
148                         for (i = 0; i < ARRAY_SIZE(pathspec_magic); i++)
149                                 if (pathspec_magic[i].mnemonic == ch) {
150                                         short_magic |= pathspec_magic[i].bit;
151                                         break;
152                                 }
153                         if (ARRAY_SIZE(pathspec_magic) <= i)
154                                 die(_("Unimplemented pathspec magic '%c' in '%s'"),
155                                     ch, elt);
156                 }
157                 if (*copyfrom == ':')
158                         copyfrom++;
159         }
160
161         magic |= short_magic;
162         *p_short_magic = short_magic;
163
164         if (pathspec_prefix >= 0 &&
165             (prefixlen || (prefix && *prefix)))
166                 die("BUG: 'prefix' magic is supposed to be used at worktree's root");
167
168         if (pathspec_prefix >= 0) {
169                 match = xstrdup(copyfrom);
170                 prefixlen = pathspec_prefix;
171         } else if (magic & PATHSPEC_FROMTOP) {
172                 match = xstrdup(copyfrom);
173                 prefixlen = 0;
174         } else {
175                 match = prefix_path_gently(prefix, prefixlen, &prefixlen, copyfrom);
176                 if (!match)
177                         die(_("%s: '%s' is outside repository"), elt, copyfrom);
178         }
179         *raw = item->match = match;
180         /*
181          * Prefix the pathspec (keep all magic) and assign to
182          * original. Useful for passing to another command.
183          */
184         if (flags & PATHSPEC_PREFIX_ORIGIN) {
185                 struct strbuf sb = STRBUF_INIT;
186                 const char *start = elt;
187                 if (prefixlen && !limit_pathspec_to_literal()) {
188                         /* Preserve the actual prefix length of each pattern */
189                         if (long_magic_end) {
190                                 strbuf_add(&sb, start, long_magic_end - start);
191                                 strbuf_addf(&sb, ",prefix:%d", prefixlen);
192                                 start = long_magic_end;
193                         } else {
194                                 if (*start == ':')
195                                         start++;
196                                 strbuf_addf(&sb, ":(prefix:%d)", prefixlen);
197                         }
198                 }
199                 strbuf_add(&sb, start, copyfrom - start);
200                 strbuf_addstr(&sb, match);
201                 item->original = strbuf_detach(&sb, NULL);
202         } else
203                 item->original = elt;
204         item->len = strlen(item->match);
205         item->prefix = prefixlen;
206
207         if ((flags & PATHSPEC_STRIP_SUBMODULE_SLASH_CHEAP) &&
208             (item->len >= 1 && item->match[item->len - 1] == '/') &&
209             (i = cache_name_pos(item->match, item->len - 1)) >= 0 &&
210             S_ISGITLINK(active_cache[i]->ce_mode)) {
211                 item->len--;
212                 match[item->len] = '\0';
213         }
214
215         if (flags & PATHSPEC_STRIP_SUBMODULE_SLASH_EXPENSIVE)
216                 for (i = 0; i < active_nr; i++) {
217                         struct cache_entry *ce = active_cache[i];
218                         int ce_len = ce_namelen(ce);
219
220                         if (!S_ISGITLINK(ce->ce_mode))
221                                 continue;
222
223                         if (item->len <= ce_len || match[ce_len] != '/' ||
224                             memcmp(ce->name, match, ce_len))
225                                 continue;
226                         if (item->len == ce_len + 1) {
227                                 /* strip trailing slash */
228                                 item->len--;
229                                 match[item->len] = '\0';
230                         } else
231                                 die (_("Pathspec '%s' is in submodule '%.*s'"),
232                                      elt, ce_len, ce->name);
233                 }
234
235         if (limit_pathspec_to_literal())
236                 item->nowildcard_len = item->len;
237         else {
238                 item->nowildcard_len = simple_length(item->match);
239                 if (item->nowildcard_len < prefixlen)
240                         item->nowildcard_len = prefixlen;
241         }
242         item->flags = 0;
243         if (item->nowildcard_len < item->len &&
244             item->match[item->nowildcard_len] == '*' &&
245             no_wildcard(item->match + item->nowildcard_len + 1))
246                 item->flags |= PATHSPEC_ONESTAR;
247
248         /* sanity checks, pathspec matchers assume these are sane */
249         assert(item->nowildcard_len <= item->len &&
250                item->prefix         <= item->len);
251         return magic;
252 }
253
254 static int pathspec_item_cmp(const void *a_, const void *b_)
255 {
256         struct pathspec_item *a, *b;
257
258         a = (struct pathspec_item *)a_;
259         b = (struct pathspec_item *)b_;
260         return strcmp(a->match, b->match);
261 }
262
263 static void NORETURN unsupported_magic(const char *pattern,
264                                        unsigned magic,
265                                        unsigned short_magic)
266 {
267         struct strbuf sb = STRBUF_INIT;
268         int i, n;
269         for (n = i = 0; i < ARRAY_SIZE(pathspec_magic); i++) {
270                 const struct pathspec_magic *m = pathspec_magic + i;
271                 if (!(magic & m->bit))
272                         continue;
273                 if (sb.len)
274                         strbuf_addstr(&sb, " ");
275                 if (short_magic & m->bit)
276                         strbuf_addf(&sb, "'%c'", m->mnemonic);
277                 else
278                         strbuf_addf(&sb, "'%s'", m->name);
279                 n++;
280         }
281         /*
282          * We may want to substitute "this command" with a command
283          * name. E.g. when add--interactive dies when running
284          * "checkout -p"
285          */
286         die(_("%s: pathspec magic not supported by this command: %s"),
287             pattern, sb.buf);
288 }
289
290 /*
291  * Given command line arguments and a prefix, convert the input to
292  * pathspec. die() if any magic in magic_mask is used.
293  */
294 void parse_pathspec(struct pathspec *pathspec,
295                     unsigned magic_mask, unsigned flags,
296                     const char *prefix, const char **argv)
297 {
298         struct pathspec_item *item;
299         const char *entry = argv ? *argv : NULL;
300         int i, n, prefixlen;
301
302         memset(pathspec, 0, sizeof(*pathspec));
303
304         if (flags & PATHSPEC_MAXDEPTH_VALID)
305                 pathspec->magic |= PATHSPEC_MAXDEPTH;
306
307         /* No arguments, no prefix -> no pathspec */
308         if (!entry && !prefix)
309                 return;
310
311         if ((flags & PATHSPEC_PREFER_CWD) &&
312             (flags & PATHSPEC_PREFER_FULL))
313                 die("BUG: PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
314
315         /* No arguments with prefix -> prefix pathspec */
316         if (!entry) {
317                 static const char *raw[2];
318
319                 if (flags & PATHSPEC_PREFER_FULL)
320                         return;
321
322                 if (!(flags & PATHSPEC_PREFER_CWD))
323                         die("BUG: PATHSPEC_PREFER_CWD requires arguments");
324
325                 pathspec->items = item = xmalloc(sizeof(*item));
326                 memset(item, 0, sizeof(*item));
327                 item->match = prefix;
328                 item->original = prefix;
329                 item->nowildcard_len = item->len = strlen(prefix);
330                 item->prefix = item->len;
331                 raw[0] = prefix;
332                 raw[1] = NULL;
333                 pathspec->nr = 1;
334                 pathspec->_raw = raw;
335                 return;
336         }
337
338         n = 0;
339         while (argv[n])
340                 n++;
341
342         pathspec->nr = n;
343         pathspec->items = item = xmalloc(sizeof(*item) * n);
344         pathspec->_raw = argv;
345         prefixlen = prefix ? strlen(prefix) : 0;
346
347         for (i = 0; i < n; i++) {
348                 unsigned short_magic;
349                 entry = argv[i];
350
351                 item[i].magic = prefix_pathspec(item + i, &short_magic,
352                                                 argv + i, flags,
353                                                 prefix, prefixlen, entry);
354                 if (item[i].magic & magic_mask)
355                         unsupported_magic(entry,
356                                           item[i].magic & magic_mask,
357                                           short_magic);
358
359                 if ((flags & PATHSPEC_SYMLINK_LEADING_PATH) &&
360                     has_symlink_leading_path(item[i].match, item[i].len)) {
361                         die(_("pathspec '%s' is beyond a symbolic link"), entry);
362                 }
363
364                 if (item[i].nowildcard_len < item[i].len)
365                         pathspec->has_wildcard = 1;
366                 pathspec->magic |= item[i].magic;
367         }
368
369
370         if (pathspec->magic & PATHSPEC_MAXDEPTH) {
371                 if (flags & PATHSPEC_KEEP_ORDER)
372                         die("BUG: PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
373                 qsort(pathspec->items, pathspec->nr,
374                       sizeof(struct pathspec_item), pathspec_item_cmp);
375         }
376 }
377
378 /*
379  * N.B. get_pathspec() is deprecated in favor of the "struct pathspec"
380  * based interface - see pathspec.c:parse_pathspec().
381  *
382  * Arguments:
383  *  - prefix - a path relative to the root of the working tree
384  *  - pathspec - a list of paths underneath the prefix path
385  *
386  * Iterates over pathspec, prepending each path with prefix,
387  * and return the resulting list.
388  *
389  * If pathspec is empty, return a singleton list containing prefix.
390  *
391  * If pathspec and prefix are both empty, return an empty list.
392  *
393  * This is typically used by built-in commands such as add.c, in order
394  * to normalize argv arguments provided to the built-in into a list of
395  * paths to process, all relative to the root of the working tree.
396  */
397 const char **get_pathspec(const char *prefix, const char **pathspec)
398 {
399         struct pathspec ps;
400         parse_pathspec(&ps,
401                        PATHSPEC_ALL_MAGIC & ~PATHSPEC_FROMTOP,
402                        PATHSPEC_PREFER_CWD,
403                        prefix, pathspec);
404         return ps._raw;
405 }
406
407 void copy_pathspec(struct pathspec *dst, const struct pathspec *src)
408 {
409         *dst = *src;
410         dst->items = xmalloc(sizeof(struct pathspec_item) * dst->nr);
411         memcpy(dst->items, src->items,
412                sizeof(struct pathspec_item) * dst->nr);
413 }
414
415 void free_pathspec(struct pathspec *pathspec)
416 {
417         free(pathspec->items);
418         pathspec->items = NULL;
419 }