THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Git Source Code Mirror - This is a publish-only repository and all pull requests are ignored. Please follow Documentation/SubmittingPatches procedure for any of your improvements.
git
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3140 lines
83KB

  1. /*
  2. * This handles recursive filename detection with exclude
  3. * files, index knowledge etc..
  4. *
  5. * See Documentation/technical/api-directory-listing.txt
  6. *
  7. * Copyright (C) Linus Torvalds, 2005-2006
  8. * Junio Hamano, 2005-2006
  9. */
  10. #include "cache.h"
  11. #include "config.h"
  12. #include "dir.h"
  13. #include "object-store.h"
  14. #include "attr.h"
  15. #include "refs.h"
  16. #include "wildmatch.h"
  17. #include "pathspec.h"
  18. #include "utf8.h"
  19. #include "varint.h"
  20. #include "ewah/ewok.h"
  21. #include "fsmonitor.h"
  22. #include "submodule-config.h"
  23. /*
  24. * Tells read_directory_recursive how a file or directory should be treated.
  25. * Values are ordered by significance, e.g. if a directory contains both
  26. * excluded and untracked files, it is listed as untracked because
  27. * path_untracked > path_excluded.
  28. */
  29. enum path_treatment {
  30. path_none = 0,
  31. path_recurse,
  32. path_excluded,
  33. path_untracked
  34. };
  35. /*
  36. * Support data structure for our opendir/readdir/closedir wrappers
  37. */
  38. struct cached_dir {
  39. DIR *fdir;
  40. struct untracked_cache_dir *untracked;
  41. int nr_files;
  42. int nr_dirs;
  43. struct dirent *de;
  44. const char *file;
  45. struct untracked_cache_dir *ucd;
  46. };
  47. static enum path_treatment read_directory_recursive(struct dir_struct *dir,
  48. struct index_state *istate, const char *path, int len,
  49. struct untracked_cache_dir *untracked,
  50. int check_only, int stop_at_first_file, const struct pathspec *pathspec);
  51. static int get_dtype(struct dirent *de, struct index_state *istate,
  52. const char *path, int len);
  53. int count_slashes(const char *s)
  54. {
  55. int cnt = 0;
  56. while (*s)
  57. if (*s++ == '/')
  58. cnt++;
  59. return cnt;
  60. }
  61. int fspathcmp(const char *a, const char *b)
  62. {
  63. return ignore_case ? strcasecmp(a, b) : strcmp(a, b);
  64. }
  65. int fspathncmp(const char *a, const char *b, size_t count)
  66. {
  67. return ignore_case ? strncasecmp(a, b, count) : strncmp(a, b, count);
  68. }
  69. int git_fnmatch(const struct pathspec_item *item,
  70. const char *pattern, const char *string,
  71. int prefix)
  72. {
  73. if (prefix > 0) {
  74. if (ps_strncmp(item, pattern, string, prefix))
  75. return WM_NOMATCH;
  76. pattern += prefix;
  77. string += prefix;
  78. }
  79. if (item->flags & PATHSPEC_ONESTAR) {
  80. int pattern_len = strlen(++pattern);
  81. int string_len = strlen(string);
  82. return string_len < pattern_len ||
  83. ps_strcmp(item, pattern,
  84. string + string_len - pattern_len);
  85. }
  86. if (item->magic & PATHSPEC_GLOB)
  87. return wildmatch(pattern, string,
  88. WM_PATHNAME |
  89. (item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0));
  90. else
  91. /* wildmatch has not learned no FNM_PATHNAME mode yet */
  92. return wildmatch(pattern, string,
  93. item->magic & PATHSPEC_ICASE ? WM_CASEFOLD : 0);
  94. }
  95. static int fnmatch_icase_mem(const char *pattern, int patternlen,
  96. const char *string, int stringlen,
  97. int flags)
  98. {
  99. int match_status;
  100. struct strbuf pat_buf = STRBUF_INIT;
  101. struct strbuf str_buf = STRBUF_INIT;
  102. const char *use_pat = pattern;
  103. const char *use_str = string;
  104. if (pattern[patternlen]) {
  105. strbuf_add(&pat_buf, pattern, patternlen);
  106. use_pat = pat_buf.buf;
  107. }
  108. if (string[stringlen]) {
  109. strbuf_add(&str_buf, string, stringlen);
  110. use_str = str_buf.buf;
  111. }
  112. if (ignore_case)
  113. flags |= WM_CASEFOLD;
  114. match_status = wildmatch(use_pat, use_str, flags);
  115. strbuf_release(&pat_buf);
  116. strbuf_release(&str_buf);
  117. return match_status;
  118. }
  119. static size_t common_prefix_len(const struct pathspec *pathspec)
  120. {
  121. int n;
  122. size_t max = 0;
  123. /*
  124. * ":(icase)path" is treated as a pathspec full of
  125. * wildcard. In other words, only prefix is considered common
  126. * prefix. If the pathspec is abc/foo abc/bar, running in
  127. * subdir xyz, the common prefix is still xyz, not xyz/abc as
  128. * in non-:(icase).
  129. */
  130. GUARD_PATHSPEC(pathspec,
  131. PATHSPEC_FROMTOP |
  132. PATHSPEC_MAXDEPTH |
  133. PATHSPEC_LITERAL |
  134. PATHSPEC_GLOB |
  135. PATHSPEC_ICASE |
  136. PATHSPEC_EXCLUDE |
  137. PATHSPEC_ATTR);
  138. for (n = 0; n < pathspec->nr; n++) {
  139. size_t i = 0, len = 0, item_len;
  140. if (pathspec->items[n].magic & PATHSPEC_EXCLUDE)
  141. continue;
  142. if (pathspec->items[n].magic & PATHSPEC_ICASE)
  143. item_len = pathspec->items[n].prefix;
  144. else
  145. item_len = pathspec->items[n].nowildcard_len;
  146. while (i < item_len && (n == 0 || i < max)) {
  147. char c = pathspec->items[n].match[i];
  148. if (c != pathspec->items[0].match[i])
  149. break;
  150. if (c == '/')
  151. len = i + 1;
  152. i++;
  153. }
  154. if (n == 0 || len < max) {
  155. max = len;
  156. if (!max)
  157. break;
  158. }
  159. }
  160. return max;
  161. }
  162. /*
  163. * Returns a copy of the longest leading path common among all
  164. * pathspecs.
  165. */
  166. char *common_prefix(const struct pathspec *pathspec)
  167. {
  168. unsigned long len = common_prefix_len(pathspec);
  169. return len ? xmemdupz(pathspec->items[0].match, len) : NULL;
  170. }
  171. int fill_directory(struct dir_struct *dir,
  172. struct index_state *istate,
  173. const struct pathspec *pathspec)
  174. {
  175. const char *prefix;
  176. size_t prefix_len;
  177. /*
  178. * Calculate common prefix for the pathspec, and
  179. * use that to optimize the directory walk
  180. */
  181. prefix_len = common_prefix_len(pathspec);
  182. prefix = prefix_len ? pathspec->items[0].match : "";
  183. /* Read the directory and prune it */
  184. read_directory(dir, istate, prefix, prefix_len, pathspec);
  185. return prefix_len;
  186. }
  187. int within_depth(const char *name, int namelen,
  188. int depth, int max_depth)
  189. {
  190. const char *cp = name, *cpe = name + namelen;
  191. while (cp < cpe) {
  192. if (*cp++ != '/')
  193. continue;
  194. depth++;
  195. if (depth > max_depth)
  196. return 0;
  197. }
  198. return 1;
  199. }
  200. /*
  201. * Read the contents of the blob with the given OID into a buffer.
  202. * Append a trailing LF to the end if the last line doesn't have one.
  203. *
  204. * Returns:
  205. * -1 when the OID is invalid or unknown or does not refer to a blob.
  206. * 0 when the blob is empty.
  207. * 1 along with { data, size } of the (possibly augmented) buffer
  208. * when successful.
  209. *
  210. * Optionally updates the given oid_stat with the given OID (when valid).
  211. */
  212. static int do_read_blob(const struct object_id *oid, struct oid_stat *oid_stat,
  213. size_t *size_out, char **data_out)
  214. {
  215. enum object_type type;
  216. unsigned long sz;
  217. char *data;
  218. *size_out = 0;
  219. *data_out = NULL;
  220. data = read_object_file(oid, &type, &sz);
  221. if (!data || type != OBJ_BLOB) {
  222. free(data);
  223. return -1;
  224. }
  225. if (oid_stat) {
  226. memset(&oid_stat->stat, 0, sizeof(oid_stat->stat));
  227. oidcpy(&oid_stat->oid, oid);
  228. }
  229. if (sz == 0) {
  230. free(data);
  231. return 0;
  232. }
  233. if (data[sz - 1] != '\n') {
  234. data = xrealloc(data, st_add(sz, 1));
  235. data[sz++] = '\n';
  236. }
  237. *size_out = xsize_t(sz);
  238. *data_out = data;
  239. return 1;
  240. }
  241. #define DO_MATCH_EXCLUDE (1<<0)
  242. #define DO_MATCH_DIRECTORY (1<<1)
  243. #define DO_MATCH_LEADING_PATHSPEC (1<<2)
  244. /*
  245. * Does the given pathspec match the given name? A match is found if
  246. *
  247. * (1) the pathspec string is leading directory of 'name' ("RECURSIVELY"), or
  248. * (2) the pathspec string has a leading part matching 'name' ("LEADING"), or
  249. * (3) the pathspec string is a wildcard and matches 'name' ("WILDCARD"), or
  250. * (4) the pathspec string is exactly the same as 'name' ("EXACT").
  251. *
  252. * Return value tells which case it was (1-4), or 0 when there is no match.
  253. *
  254. * It may be instructive to look at a small table of concrete examples
  255. * to understand the differences between 1, 2, and 4:
  256. *
  257. * Pathspecs
  258. * | a/b | a/b/ | a/b/c
  259. * ------+-----------+-----------+------------
  260. * a/b | EXACT | EXACT[1] | LEADING[2]
  261. * Names a/b/ | RECURSIVE | EXACT | LEADING[2]
  262. * a/b/c | RECURSIVE | RECURSIVE | EXACT
  263. *
  264. * [1] Only if DO_MATCH_DIRECTORY is passed; otherwise, this is NOT a match.
  265. * [2] Only if DO_MATCH_LEADING_PATHSPEC is passed; otherwise, not a match.
  266. */
  267. static int match_pathspec_item(const struct index_state *istate,
  268. const struct pathspec_item *item, int prefix,
  269. const char *name, int namelen, unsigned flags)
  270. {
  271. /* name/namelen has prefix cut off by caller */
  272. const char *match = item->match + prefix;
  273. int matchlen = item->len - prefix;
  274. /*
  275. * The normal call pattern is:
  276. * 1. prefix = common_prefix_len(ps);
  277. * 2. prune something, or fill_directory
  278. * 3. match_pathspec()
  279. *
  280. * 'prefix' at #1 may be shorter than the command's prefix and
  281. * it's ok for #2 to match extra files. Those extras will be
  282. * trimmed at #3.
  283. *
  284. * Suppose the pathspec is 'foo' and '../bar' running from
  285. * subdir 'xyz'. The common prefix at #1 will be empty, thanks
  286. * to "../". We may have xyz/foo _and_ XYZ/foo after #2. The
  287. * user does not want XYZ/foo, only the "foo" part should be
  288. * case-insensitive. We need to filter out XYZ/foo here. In
  289. * other words, we do not trust the caller on comparing the
  290. * prefix part when :(icase) is involved. We do exact
  291. * comparison ourselves.
  292. *
  293. * Normally the caller (common_prefix_len() in fact) does
  294. * _exact_ matching on name[-prefix+1..-1] and we do not need
  295. * to check that part. Be defensive and check it anyway, in
  296. * case common_prefix_len is changed, or a new caller is
  297. * introduced that does not use common_prefix_len.
  298. *
  299. * If the penalty turns out too high when prefix is really
  300. * long, maybe change it to
  301. * strncmp(match, name, item->prefix - prefix)
  302. */
  303. if (item->prefix && (item->magic & PATHSPEC_ICASE) &&
  304. strncmp(item->match, name - prefix, item->prefix))
  305. return 0;
  306. if (item->attr_match_nr &&
  307. !match_pathspec_attrs(istate, name, namelen, item))
  308. return 0;
  309. /* If the match was just the prefix, we matched */
  310. if (!*match)
  311. return MATCHED_RECURSIVELY;
  312. if (matchlen <= namelen && !ps_strncmp(item, match, name, matchlen)) {
  313. if (matchlen == namelen)
  314. return MATCHED_EXACTLY;
  315. if (match[matchlen-1] == '/' || name[matchlen] == '/')
  316. return MATCHED_RECURSIVELY;
  317. } else if ((flags & DO_MATCH_DIRECTORY) &&
  318. match[matchlen - 1] == '/' &&
  319. namelen == matchlen - 1 &&
  320. !ps_strncmp(item, match, name, namelen))
  321. return MATCHED_EXACTLY;
  322. if (item->nowildcard_len < item->len &&
  323. !git_fnmatch(item, match, name,
  324. item->nowildcard_len - prefix))
  325. return MATCHED_FNMATCH;
  326. /* Perform checks to see if "name" is a leading string of the pathspec */
  327. if (flags & DO_MATCH_LEADING_PATHSPEC) {
  328. /* name is a literal prefix of the pathspec */
  329. int offset = name[namelen-1] == '/' ? 1 : 0;
  330. if ((namelen < matchlen) &&
  331. (match[namelen-offset] == '/') &&
  332. !ps_strncmp(item, match, name, namelen))
  333. return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
  334. /* name" doesn't match up to the first wild character */
  335. if (item->nowildcard_len < item->len &&
  336. ps_strncmp(item, match, name,
  337. item->nowildcard_len - prefix))
  338. return 0;
  339. /*
  340. * Here is where we would perform a wildmatch to check if
  341. * "name" can be matched as a directory (or a prefix) against
  342. * the pathspec. Since wildmatch doesn't have this capability
  343. * at the present we have to punt and say that it is a match,
  344. * potentially returning a false positive
  345. * The submodules themselves will be able to perform more
  346. * accurate matching to determine if the pathspec matches.
  347. */
  348. return MATCHED_RECURSIVELY_LEADING_PATHSPEC;
  349. }
  350. return 0;
  351. }
  352. /*
  353. * Given a name and a list of pathspecs, returns the nature of the
  354. * closest (i.e. most specific) match of the name to any of the
  355. * pathspecs.
  356. *
  357. * The caller typically calls this multiple times with the same
  358. * pathspec and seen[] array but with different name/namelen
  359. * (e.g. entries from the index) and is interested in seeing if and
  360. * how each pathspec matches all the names it calls this function
  361. * with. A mark is left in the seen[] array for each pathspec element
  362. * indicating the closest type of match that element achieved, so if
  363. * seen[n] remains zero after multiple invocations, that means the nth
  364. * pathspec did not match any names, which could indicate that the
  365. * user mistyped the nth pathspec.
  366. */
  367. static int do_match_pathspec(const struct index_state *istate,
  368. const struct pathspec *ps,
  369. const char *name, int namelen,
  370. int prefix, char *seen,
  371. unsigned flags)
  372. {
  373. int i, retval = 0, exclude = flags & DO_MATCH_EXCLUDE;
  374. GUARD_PATHSPEC(ps,
  375. PATHSPEC_FROMTOP |
  376. PATHSPEC_MAXDEPTH |
  377. PATHSPEC_LITERAL |
  378. PATHSPEC_GLOB |
  379. PATHSPEC_ICASE |
  380. PATHSPEC_EXCLUDE |
  381. PATHSPEC_ATTR);
  382. if (!ps->nr) {
  383. if (!ps->recursive ||
  384. !(ps->magic & PATHSPEC_MAXDEPTH) ||
  385. ps->max_depth == -1)
  386. return MATCHED_RECURSIVELY;
  387. if (within_depth(name, namelen, 0, ps->max_depth))
  388. return MATCHED_EXACTLY;
  389. else
  390. return 0;
  391. }
  392. name += prefix;
  393. namelen -= prefix;
  394. for (i = ps->nr - 1; i >= 0; i--) {
  395. int how;
  396. if ((!exclude && ps->items[i].magic & PATHSPEC_EXCLUDE) ||
  397. ( exclude && !(ps->items[i].magic & PATHSPEC_EXCLUDE)))
  398. continue;
  399. if (seen && seen[i] == MATCHED_EXACTLY)
  400. continue;
  401. /*
  402. * Make exclude patterns optional and never report
  403. * "pathspec ':(exclude)foo' matches no files"
  404. */
  405. if (seen && ps->items[i].magic & PATHSPEC_EXCLUDE)
  406. seen[i] = MATCHED_FNMATCH;
  407. how = match_pathspec_item(istate, ps->items+i, prefix, name,
  408. namelen, flags);
  409. if (ps->recursive &&
  410. (ps->magic & PATHSPEC_MAXDEPTH) &&
  411. ps->max_depth != -1 &&
  412. how && how != MATCHED_FNMATCH) {
  413. int len = ps->items[i].len;
  414. if (name[len] == '/')
  415. len++;
  416. if (within_depth(name+len, namelen-len, 0, ps->max_depth))
  417. how = MATCHED_EXACTLY;
  418. else
  419. how = 0;
  420. }
  421. if (how) {
  422. if (retval < how)
  423. retval = how;
  424. if (seen && seen[i] < how)
  425. seen[i] = how;
  426. }
  427. }
  428. return retval;
  429. }
  430. int match_pathspec(const struct index_state *istate,
  431. const struct pathspec *ps,
  432. const char *name, int namelen,
  433. int prefix, char *seen, int is_dir)
  434. {
  435. int positive, negative;
  436. unsigned flags = is_dir ? DO_MATCH_DIRECTORY : 0;
  437. positive = do_match_pathspec(istate, ps, name, namelen,
  438. prefix, seen, flags);
  439. if (!(ps->magic & PATHSPEC_EXCLUDE) || !positive)
  440. return positive;
  441. negative = do_match_pathspec(istate, ps, name, namelen,
  442. prefix, seen,
  443. flags | DO_MATCH_EXCLUDE);
  444. return negative ? 0 : positive;
  445. }
  446. /**
  447. * Check if a submodule is a superset of the pathspec
  448. */
  449. int submodule_path_match(const struct index_state *istate,
  450. const struct pathspec *ps,
  451. const char *submodule_name,
  452. char *seen)
  453. {
  454. int matched = do_match_pathspec(istate, ps, submodule_name,
  455. strlen(submodule_name),
  456. 0, seen,
  457. DO_MATCH_DIRECTORY |
  458. DO_MATCH_LEADING_PATHSPEC);
  459. return matched;
  460. }
  461. int report_path_error(const char *ps_matched,
  462. const struct pathspec *pathspec)
  463. {
  464. /*
  465. * Make sure all pathspec matched; otherwise it is an error.
  466. */
  467. int num, errors = 0;
  468. for (num = 0; num < pathspec->nr; num++) {
  469. int other, found_dup;
  470. if (ps_matched[num])
  471. continue;
  472. /*
  473. * The caller might have fed identical pathspec
  474. * twice. Do not barf on such a mistake.
  475. * FIXME: parse_pathspec should have eliminated
  476. * duplicate pathspec.
  477. */
  478. for (found_dup = other = 0;
  479. !found_dup && other < pathspec->nr;
  480. other++) {
  481. if (other == num || !ps_matched[other])
  482. continue;
  483. if (!strcmp(pathspec->items[other].original,
  484. pathspec->items[num].original))
  485. /*
  486. * Ok, we have a match already.
  487. */
  488. found_dup = 1;
  489. }
  490. if (found_dup)
  491. continue;
  492. error(_("pathspec '%s' did not match any file(s) known to git"),
  493. pathspec->items[num].original);
  494. errors++;
  495. }
  496. return errors;
  497. }
  498. /*
  499. * Return the length of the "simple" part of a path match limiter.
  500. */
  501. int simple_length(const char *match)
  502. {
  503. int len = -1;
  504. for (;;) {
  505. unsigned char c = *match++;
  506. len++;
  507. if (c == '\0' || is_glob_special(c))
  508. return len;
  509. }
  510. }
  511. int no_wildcard(const char *string)
  512. {
  513. return string[simple_length(string)] == '\0';
  514. }
  515. void parse_path_pattern(const char **pattern,
  516. int *patternlen,
  517. unsigned *flags,
  518. int *nowildcardlen)
  519. {
  520. const char *p = *pattern;
  521. size_t i, len;
  522. *flags = 0;
  523. if (*p == '!') {
  524. *flags |= PATTERN_FLAG_NEGATIVE;
  525. p++;
  526. }
  527. len = strlen(p);
  528. if (len && p[len - 1] == '/') {
  529. len--;
  530. *flags |= PATTERN_FLAG_MUSTBEDIR;
  531. }
  532. for (i = 0; i < len; i++) {
  533. if (p[i] == '/')
  534. break;
  535. }
  536. if (i == len)
  537. *flags |= PATTERN_FLAG_NODIR;
  538. *nowildcardlen = simple_length(p);
  539. /*
  540. * we should have excluded the trailing slash from 'p' too,
  541. * but that's one more allocation. Instead just make sure
  542. * nowildcardlen does not exceed real patternlen
  543. */
  544. if (*nowildcardlen > len)
  545. *nowildcardlen = len;
  546. if (*p == '*' && no_wildcard(p + 1))
  547. *flags |= PATTERN_FLAG_ENDSWITH;
  548. *pattern = p;
  549. *patternlen = len;
  550. }
  551. void add_pattern(const char *string, const char *base,
  552. int baselen, struct pattern_list *pl, int srcpos)
  553. {
  554. struct path_pattern *pattern;
  555. int patternlen;
  556. unsigned flags;
  557. int nowildcardlen;
  558. parse_path_pattern(&string, &patternlen, &flags, &nowildcardlen);
  559. if (flags & PATTERN_FLAG_MUSTBEDIR) {
  560. FLEXPTR_ALLOC_MEM(pattern, pattern, string, patternlen);
  561. } else {
  562. pattern = xmalloc(sizeof(*pattern));
  563. pattern->pattern = string;
  564. }
  565. pattern->patternlen = patternlen;
  566. pattern->nowildcardlen = nowildcardlen;
  567. pattern->base = base;
  568. pattern->baselen = baselen;
  569. pattern->flags = flags;
  570. pattern->srcpos = srcpos;
  571. ALLOC_GROW(pl->patterns, pl->nr + 1, pl->alloc);
  572. pl->patterns[pl->nr++] = pattern;
  573. pattern->pl = pl;
  574. }
  575. static int read_skip_worktree_file_from_index(const struct index_state *istate,
  576. const char *path,
  577. size_t *size_out, char **data_out,
  578. struct oid_stat *oid_stat)
  579. {
  580. int pos, len;
  581. len = strlen(path);
  582. pos = index_name_pos(istate, path, len);
  583. if (pos < 0)
  584. return -1;
  585. if (!ce_skip_worktree(istate->cache[pos]))
  586. return -1;
  587. return do_read_blob(&istate->cache[pos]->oid, oid_stat, size_out, data_out);
  588. }
  589. /*
  590. * Frees memory within pl which was allocated for exclude patterns and
  591. * the file buffer. Does not free pl itself.
  592. */
  593. void clear_pattern_list(struct pattern_list *pl)
  594. {
  595. int i;
  596. for (i = 0; i < pl->nr; i++)
  597. free(pl->patterns[i]);
  598. free(pl->patterns);
  599. free(pl->filebuf);
  600. memset(pl, 0, sizeof(*pl));
  601. }
  602. static void trim_trailing_spaces(char *buf)
  603. {
  604. char *p, *last_space = NULL;
  605. for (p = buf; *p; p++)
  606. switch (*p) {
  607. case ' ':
  608. if (!last_space)
  609. last_space = p;
  610. break;
  611. case '\\':
  612. p++;
  613. if (!*p)
  614. return;
  615. /* fallthrough */
  616. default:
  617. last_space = NULL;
  618. }
  619. if (last_space)
  620. *last_space = '\0';
  621. }
  622. /*
  623. * Given a subdirectory name and "dir" of the current directory,
  624. * search the subdir in "dir" and return it, or create a new one if it
  625. * does not exist in "dir".
  626. *
  627. * If "name" has the trailing slash, it'll be excluded in the search.
  628. */
  629. static struct untracked_cache_dir *lookup_untracked(struct untracked_cache *uc,
  630. struct untracked_cache_dir *dir,
  631. const char *name, int len)
  632. {
  633. int first, last;
  634. struct untracked_cache_dir *d;
  635. if (!dir)
  636. return NULL;
  637. if (len && name[len - 1] == '/')
  638. len--;
  639. first = 0;
  640. last = dir->dirs_nr;
  641. while (last > first) {
  642. int cmp, next = first + ((last - first) >> 1);
  643. d = dir->dirs[next];
  644. cmp = strncmp(name, d->name, len);
  645. if (!cmp && strlen(d->name) > len)
  646. cmp = -1;
  647. if (!cmp)
  648. return d;
  649. if (cmp < 0) {
  650. last = next;
  651. continue;
  652. }
  653. first = next+1;
  654. }
  655. uc->dir_created++;
  656. FLEX_ALLOC_MEM(d, name, name, len);
  657. ALLOC_GROW(dir->dirs, dir->dirs_nr + 1, dir->dirs_alloc);
  658. MOVE_ARRAY(dir->dirs + first + 1, dir->dirs + first,
  659. dir->dirs_nr - first);
  660. dir->dirs_nr++;
  661. dir->dirs[first] = d;
  662. return d;
  663. }
  664. static void do_invalidate_gitignore(struct untracked_cache_dir *dir)
  665. {
  666. int i;
  667. dir->valid = 0;
  668. dir->untracked_nr = 0;
  669. for (i = 0; i < dir->dirs_nr; i++)
  670. do_invalidate_gitignore(dir->dirs[i]);
  671. }
  672. static void invalidate_gitignore(struct untracked_cache *uc,
  673. struct untracked_cache_dir *dir)
  674. {
  675. uc->gitignore_invalidated++;
  676. do_invalidate_gitignore(dir);
  677. }
  678. static void invalidate_directory(struct untracked_cache *uc,
  679. struct untracked_cache_dir *dir)
  680. {
  681. int i;
  682. /*
  683. * Invalidation increment here is just roughly correct. If
  684. * untracked_nr or any of dirs[].recurse is non-zero, we
  685. * should increment dir_invalidated too. But that's more
  686. * expensive to do.
  687. */
  688. if (dir->valid)
  689. uc->dir_invalidated++;
  690. dir->valid = 0;
  691. dir->untracked_nr = 0;
  692. for (i = 0; i < dir->dirs_nr; i++)
  693. dir->dirs[i]->recurse = 0;
  694. }
  695. static int add_patterns_from_buffer(char *buf, size_t size,
  696. const char *base, int baselen,
  697. struct pattern_list *pl);
  698. /*
  699. * Given a file with name "fname", read it (either from disk, or from
  700. * an index if 'istate' is non-null), parse it and store the
  701. * exclude rules in "pl".
  702. *
  703. * If "ss" is not NULL, compute SHA-1 of the exclude file and fill
  704. * stat data from disk (only valid if add_patterns returns zero). If
  705. * ss_valid is non-zero, "ss" must contain good value as input.
  706. */
  707. static int add_patterns(const char *fname, const char *base, int baselen,
  708. struct pattern_list *pl, struct index_state *istate,
  709. struct oid_stat *oid_stat)
  710. {
  711. struct stat st;
  712. int r;
  713. int fd;
  714. size_t size = 0;
  715. char *buf;
  716. fd = open(fname, O_RDONLY);
  717. if (fd < 0 || fstat(fd, &st) < 0) {
  718. if (fd < 0)
  719. warn_on_fopen_errors(fname);
  720. else
  721. close(fd);
  722. if (!istate)
  723. return -1;
  724. r = read_skip_worktree_file_from_index(istate, fname,
  725. &size, &buf,
  726. oid_stat);
  727. if (r != 1)
  728. return r;
  729. } else {
  730. size = xsize_t(st.st_size);
  731. if (size == 0) {
  732. if (oid_stat) {
  733. fill_stat_data(&oid_stat->stat, &st);
  734. oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
  735. oid_stat->valid = 1;
  736. }
  737. close(fd);
  738. return 0;
  739. }
  740. buf = xmallocz(size);
  741. if (read_in_full(fd, buf, size) != size) {
  742. free(buf);
  743. close(fd);
  744. return -1;
  745. }
  746. buf[size++] = '\n';
  747. close(fd);
  748. if (oid_stat) {
  749. int pos;
  750. if (oid_stat->valid &&
  751. !match_stat_data_racy(istate, &oid_stat->stat, &st))
  752. ; /* no content change, ss->sha1 still good */
  753. else if (istate &&
  754. (pos = index_name_pos(istate, fname, strlen(fname))) >= 0 &&
  755. !ce_stage(istate->cache[pos]) &&
  756. ce_uptodate(istate->cache[pos]) &&
  757. !would_convert_to_git(istate, fname))
  758. oidcpy(&oid_stat->oid,
  759. &istate->cache[pos]->oid);
  760. else
  761. hash_object_file(buf, size, "blob",
  762. &oid_stat->oid);
  763. fill_stat_data(&oid_stat->stat, &st);
  764. oid_stat->valid = 1;
  765. }
  766. }
  767. add_patterns_from_buffer(buf, size, base, baselen, pl);
  768. return 0;
  769. }
  770. static int add_patterns_from_buffer(char *buf, size_t size,
  771. const char *base, int baselen,
  772. struct pattern_list *pl)
  773. {
  774. int i, lineno = 1;
  775. char *entry;
  776. pl->filebuf = buf;
  777. if (skip_utf8_bom(&buf, size))
  778. size -= buf - pl->filebuf;
  779. entry = buf;
  780. for (i = 0; i < size; i++) {
  781. if (buf[i] == '\n') {
  782. if (entry != buf + i && entry[0] != '#') {
  783. buf[i - (i && buf[i-1] == '\r')] = 0;
  784. trim_trailing_spaces(entry);
  785. add_pattern(entry, base, baselen, pl, lineno);
  786. }
  787. lineno++;
  788. entry = buf + i + 1;
  789. }
  790. }
  791. return 0;
  792. }
  793. int add_patterns_from_file_to_list(const char *fname, const char *base,
  794. int baselen, struct pattern_list *pl,
  795. struct index_state *istate)
  796. {
  797. return add_patterns(fname, base, baselen, pl, istate, NULL);
  798. }
  799. int add_patterns_from_blob_to_list(
  800. struct object_id *oid,
  801. const char *base, int baselen,
  802. struct pattern_list *pl)
  803. {
  804. char *buf;
  805. size_t size;
  806. int r;
  807. r = do_read_blob(oid, NULL, &size, &buf);
  808. if (r != 1)
  809. return r;
  810. add_patterns_from_buffer(buf, size, base, baselen, pl);
  811. return 0;
  812. }
  813. struct pattern_list *add_pattern_list(struct dir_struct *dir,
  814. int group_type, const char *src)
  815. {
  816. struct pattern_list *pl;
  817. struct exclude_list_group *group;
  818. group = &dir->exclude_list_group[group_type];
  819. ALLOC_GROW(group->pl, group->nr + 1, group->alloc);
  820. pl = &group->pl[group->nr++];
  821. memset(pl, 0, sizeof(*pl));
  822. pl->src = src;
  823. return pl;
  824. }
  825. /*
  826. * Used to set up core.excludesfile and .git/info/exclude lists.
  827. */
  828. static void add_patterns_from_file_1(struct dir_struct *dir, const char *fname,
  829. struct oid_stat *oid_stat)
  830. {
  831. struct pattern_list *pl;
  832. /*
  833. * catch setup_standard_excludes() that's called before
  834. * dir->untracked is assigned. That function behaves
  835. * differently when dir->untracked is non-NULL.
  836. */
  837. if (!dir->untracked)
  838. dir->unmanaged_exclude_files++;
  839. pl = add_pattern_list(dir, EXC_FILE, fname);
  840. if (add_patterns(fname, "", 0, pl, NULL, oid_stat) < 0)
  841. die(_("cannot use %s as an exclude file"), fname);
  842. }
  843. void add_patterns_from_file(struct dir_struct *dir, const char *fname)
  844. {
  845. dir->unmanaged_exclude_files++; /* see validate_untracked_cache() */
  846. add_patterns_from_file_1(dir, fname, NULL);
  847. }
  848. int match_basename(const char *basename, int basenamelen,
  849. const char *pattern, int prefix, int patternlen,
  850. unsigned flags)
  851. {
  852. if (prefix == patternlen) {
  853. if (patternlen == basenamelen &&
  854. !fspathncmp(pattern, basename, basenamelen))
  855. return 1;
  856. } else if (flags & PATTERN_FLAG_ENDSWITH) {
  857. /* "*literal" matching against "fooliteral" */
  858. if (patternlen - 1 <= basenamelen &&
  859. !fspathncmp(pattern + 1,
  860. basename + basenamelen - (patternlen - 1),
  861. patternlen - 1))
  862. return 1;
  863. } else {
  864. if (fnmatch_icase_mem(pattern, patternlen,
  865. basename, basenamelen,
  866. 0) == 0)
  867. return 1;
  868. }
  869. return 0;
  870. }
  871. int match_pathname(const char *pathname, int pathlen,
  872. const char *base, int baselen,
  873. const char *pattern, int prefix, int patternlen,
  874. unsigned flags)
  875. {
  876. const char *name;
  877. int namelen;
  878. /*
  879. * match with FNM_PATHNAME; the pattern has base implicitly
  880. * in front of it.
  881. */
  882. if (*pattern == '/') {
  883. pattern++;
  884. patternlen--;
  885. prefix--;
  886. }
  887. /*
  888. * baselen does not count the trailing slash. base[] may or
  889. * may not end with a trailing slash though.
  890. */
  891. if (pathlen < baselen + 1 ||
  892. (baselen && pathname[baselen] != '/') ||
  893. fspathncmp(pathname, base, baselen))
  894. return 0;
  895. namelen = baselen ? pathlen - baselen - 1 : pathlen;
  896. name = pathname + pathlen - namelen;
  897. if (prefix) {
  898. /*
  899. * if the non-wildcard part is longer than the
  900. * remaining pathname, surely it cannot match.
  901. */
  902. if (prefix > namelen)
  903. return 0;
  904. if (fspathncmp(pattern, name, prefix))
  905. return 0;
  906. pattern += prefix;
  907. patternlen -= prefix;
  908. name += prefix;
  909. namelen -= prefix;
  910. /*
  911. * If the whole pattern did not have a wildcard,
  912. * then our prefix match is all we need; we
  913. * do not need to call fnmatch at all.
  914. */
  915. if (!patternlen && !namelen)
  916. return 1;
  917. }
  918. return fnmatch_icase_mem(pattern, patternlen,
  919. name, namelen,
  920. WM_PATHNAME) == 0;
  921. }
  922. /*
  923. * Scan the given exclude list in reverse to see whether pathname
  924. * should be ignored. The first match (i.e. the last on the list), if
  925. * any, determines the fate. Returns the exclude_list element which
  926. * matched, or NULL for undecided.
  927. */
  928. static struct path_pattern *last_matching_pattern_from_list(const char *pathname,
  929. int pathlen,
  930. const char *basename,
  931. int *dtype,
  932. struct pattern_list *pl,
  933. struct index_state *istate)
  934. {
  935. struct path_pattern *res = NULL; /* undecided */
  936. int i;
  937. if (!pl->nr)
  938. return NULL; /* undefined */
  939. for (i = pl->nr - 1; 0 <= i; i--) {
  940. struct path_pattern *pattern = pl->patterns[i];
  941. const char *exclude = pattern->pattern;
  942. int prefix = pattern->nowildcardlen;
  943. if (pattern->flags & PATTERN_FLAG_MUSTBEDIR) {
  944. if (*dtype == DT_UNKNOWN)
  945. *dtype = get_dtype(NULL, istate, pathname, pathlen);
  946. if (*dtype != DT_DIR)
  947. continue;
  948. }
  949. if (pattern->flags & PATTERN_FLAG_NODIR) {
  950. if (match_basename(basename,
  951. pathlen - (basename - pathname),
  952. exclude, prefix, pattern->patternlen,
  953. pattern->flags)) {
  954. res = pattern;
  955. break;
  956. }
  957. continue;
  958. }
  959. assert(pattern->baselen == 0 ||
  960. pattern->base[pattern->baselen - 1] == '/');
  961. if (match_pathname(pathname, pathlen,
  962. pattern->base,
  963. pattern->baselen ? pattern->baselen - 1 : 0,
  964. exclude, prefix, pattern->patternlen,
  965. pattern->flags)) {
  966. res = pattern;
  967. break;
  968. }
  969. }
  970. return res;
  971. }
  972. /*
  973. * Scan the list of patterns to determine if the ordered list
  974. * of patterns matches on 'pathname'.
  975. *
  976. * Return 1 for a match, 0 for not matched and -1 for undecided.
  977. */
  978. enum pattern_match_result path_matches_pattern_list(
  979. const char *pathname, int pathlen,
  980. const char *basename, int *dtype,
  981. struct pattern_list *pl,
  982. struct index_state *istate)
  983. {
  984. struct path_pattern *pattern;
  985. pattern = last_matching_pattern_from_list(pathname, pathlen, basename,
  986. dtype, pl, istate);
  987. if (pattern) {
  988. if (pattern->flags & PATTERN_FLAG_NEGATIVE)
  989. return NOT_MATCHED;
  990. else
  991. return MATCHED;
  992. }
  993. return UNDECIDED;
  994. }
  995. static struct path_pattern *last_matching_pattern_from_lists(
  996. struct dir_struct *dir, struct index_state *istate,
  997. const char *pathname, int pathlen,
  998. const char *basename, int *dtype_p)
  999. {
  1000. int i, j;
  1001. struct exclude_list_group *group;
  1002. struct path_pattern *pattern;
  1003. for (i = EXC_CMDL; i <= EXC_FILE; i++) {
  1004. group = &dir->exclude_list_group[i];
  1005. for (j = group->nr - 1; j >= 0; j--) {
  1006. pattern = last_matching_pattern_from_list(
  1007. pathname, pathlen, basename, dtype_p,
  1008. &group->pl[j], istate);
  1009. if (pattern)
  1010. return pattern;
  1011. }
  1012. }
  1013. return NULL;
  1014. }
  1015. /*
  1016. * Loads the per-directory exclude list for the substring of base
  1017. * which has a char length of baselen.
  1018. */
  1019. static void prep_exclude(struct dir_struct *dir,
  1020. struct index_state *istate,
  1021. const char *base, int baselen)
  1022. {
  1023. struct exclude_list_group *group;
  1024. struct pattern_list *pl;
  1025. struct exclude_stack *stk = NULL;
  1026. struct untracked_cache_dir *untracked;
  1027. int current;
  1028. group = &dir->exclude_list_group[EXC_DIRS];
  1029. /*
  1030. * Pop the exclude lists from the EXCL_DIRS exclude_list_group
  1031. * which originate from directories not in the prefix of the
  1032. * path being checked.
  1033. */
  1034. while ((stk = dir->exclude_stack) != NULL) {
  1035. if (stk->baselen <= baselen &&
  1036. !strncmp(dir->basebuf.buf, base, stk->baselen))
  1037. break;
  1038. pl = &group->pl[dir->exclude_stack->exclude_ix];
  1039. dir->exclude_stack = stk->prev;
  1040. dir->pattern = NULL;
  1041. free((char *)pl->src); /* see strbuf_detach() below */
  1042. clear_pattern_list(pl);
  1043. free(stk);
  1044. group->nr--;
  1045. }
  1046. /* Skip traversing into sub directories if the parent is excluded */
  1047. if (dir->pattern)
  1048. return;
  1049. /*
  1050. * Lazy initialization. All call sites currently just
  1051. * memset(dir, 0, sizeof(*dir)) before use. Changing all of
  1052. * them seems lots of work for little benefit.
  1053. */
  1054. if (!dir->basebuf.buf)
  1055. strbuf_init(&dir->basebuf, PATH_MAX);
  1056. /* Read from the parent directories and push them down. */
  1057. current = stk ? stk->baselen : -1;
  1058. strbuf_setlen(&dir->basebuf, current < 0 ? 0 : current);
  1059. if (dir->untracked)
  1060. untracked = stk ? stk->ucd : dir->untracked->root;
  1061. else
  1062. untracked = NULL;
  1063. while (current < baselen) {
  1064. const char *cp;
  1065. struct oid_stat oid_stat;
  1066. stk = xcalloc(1, sizeof(*stk));
  1067. if (current < 0) {
  1068. cp = base;
  1069. current = 0;
  1070. } else {
  1071. cp = strchr(base + current + 1, '/');
  1072. if (!cp)
  1073. die("oops in prep_exclude");
  1074. cp++;
  1075. untracked =
  1076. lookup_untracked(dir->untracked, untracked,
  1077. base + current,
  1078. cp - base - current);
  1079. }
  1080. stk->prev = dir->exclude_stack;
  1081. stk->baselen = cp - base;
  1082. stk->exclude_ix = group->nr;
  1083. stk->ucd = untracked;
  1084. pl = add_pattern_list(dir, EXC_DIRS, NULL);
  1085. strbuf_add(&dir->basebuf, base + current, stk->baselen - current);
  1086. assert(stk->baselen == dir->basebuf.len);
  1087. /* Abort if the directory is excluded */
  1088. if (stk->baselen) {
  1089. int dt = DT_DIR;
  1090. dir->basebuf.buf[stk->baselen - 1] = 0;
  1091. dir->pattern = last_matching_pattern_from_lists(dir,
  1092. istate,
  1093. dir->basebuf.buf, stk->baselen - 1,
  1094. dir->basebuf.buf + current, &dt);
  1095. dir->basebuf.buf[stk->baselen - 1] = '/';
  1096. if (dir->pattern &&
  1097. dir->pattern->flags & PATTERN_FLAG_NEGATIVE)
  1098. dir->pattern = NULL;
  1099. if (dir->pattern) {
  1100. dir->exclude_stack = stk;
  1101. return;
  1102. }
  1103. }
  1104. /* Try to read per-directory file */
  1105. oidclr(&oid_stat.oid);
  1106. oid_stat.valid = 0;
  1107. if (dir->exclude_per_dir &&
  1108. /*
  1109. * If we know that no files have been added in
  1110. * this directory (i.e. valid_cached_dir() has
  1111. * been executed and set untracked->valid) ..
  1112. */
  1113. (!untracked || !untracked->valid ||
  1114. /*
  1115. * .. and .gitignore does not exist before
  1116. * (i.e. null exclude_oid). Then we can skip
  1117. * loading .gitignore, which would result in
  1118. * ENOENT anyway.
  1119. */
  1120. !is_null_oid(&untracked->exclude_oid))) {
  1121. /*
  1122. * dir->basebuf gets reused by the traversal, but we
  1123. * need fname to remain unchanged to ensure the src
  1124. * member of each struct path_pattern correctly
  1125. * back-references its source file. Other invocations
  1126. * of add_pattern_list provide stable strings, so we
  1127. * strbuf_detach() and free() here in the caller.
  1128. */
  1129. struct strbuf sb = STRBUF_INIT;
  1130. strbuf_addbuf(&sb, &dir->basebuf);
  1131. strbuf_addstr(&sb, dir->exclude_per_dir);
  1132. pl->src = strbuf_detach(&sb, NULL);
  1133. add_patterns(pl->src, pl->src, stk->baselen, pl, istate,
  1134. untracked ? &oid_stat : NULL);
  1135. }
  1136. /*
  1137. * NEEDSWORK: when untracked cache is enabled, prep_exclude()
  1138. * will first be called in valid_cached_dir() then maybe many
  1139. * times more in last_matching_pattern(). When the cache is
  1140. * used, last_matching_pattern() will not be called and
  1141. * reading .gitignore content will be a waste.
  1142. *
  1143. * So when it's called by valid_cached_dir() and we can get
  1144. * .gitignore SHA-1 from the index (i.e. .gitignore is not
  1145. * modified on work tree), we could delay reading the
  1146. * .gitignore content until we absolutely need it in
  1147. * last_matching_pattern(). Be careful about ignore rule
  1148. * order, though, if you do that.
  1149. */
  1150. if (untracked &&
  1151. !oideq(&oid_stat.oid, &untracked->exclude_oid)) {
  1152. invalidate_gitignore(dir->untracked, untracked);
  1153. oidcpy(&untracked->exclude_oid, &oid_stat.oid);
  1154. }
  1155. dir->exclude_stack = stk;
  1156. current = stk->baselen;
  1157. }
  1158. strbuf_setlen(&dir->basebuf, baselen);
  1159. }
  1160. /*
  1161. * Loads the exclude lists for the directory containing pathname, then
  1162. * scans all exclude lists to determine whether pathname is excluded.
  1163. * Returns the exclude_list element which matched, or NULL for
  1164. * undecided.
  1165. */
  1166. struct path_pattern *last_matching_pattern(struct dir_struct *dir,
  1167. struct index_state *istate,
  1168. const char *pathname,
  1169. int *dtype_p)
  1170. {
  1171. int pathlen = strlen(pathname);
  1172. const char *basename = strrchr(pathname, '/');
  1173. basename = (basename) ? basename+1 : pathname;
  1174. prep_exclude(dir, istate, pathname, basename-pathname);
  1175. if (dir->pattern)
  1176. return dir->pattern;
  1177. return last_matching_pattern_from_lists(dir, istate, pathname, pathlen,
  1178. basename, dtype_p);
  1179. }
  1180. /*
  1181. * Loads the exclude lists for the directory containing pathname, then
  1182. * scans all exclude lists to determine whether pathname is excluded.
  1183. * Returns 1 if true, otherwise 0.
  1184. */
  1185. int is_excluded(struct dir_struct *dir, struct index_state *istate,
  1186. const char *pathname, int *dtype_p)
  1187. {
  1188. struct path_pattern *pattern =
  1189. last_matching_pattern(dir, istate, pathname, dtype_p);
  1190. if (pattern)
  1191. return pattern->flags & PATTERN_FLAG_NEGATIVE ? 0 : 1;
  1192. return 0;
  1193. }
  1194. static struct dir_entry *dir_entry_new(const char *pathname, int len)
  1195. {
  1196. struct dir_entry *ent;
  1197. FLEX_ALLOC_MEM(ent, name, pathname, len);
  1198. ent->len = len;
  1199. return ent;
  1200. }
  1201. static struct dir_entry *dir_add_name(struct dir_struct *dir,
  1202. struct index_state *istate,
  1203. const char *pathname, int len)
  1204. {
  1205. if (index_file_exists(istate, pathname, len, ignore_case))
  1206. return NULL;
  1207. ALLOC_GROW(dir->entries, dir->nr+1, dir->alloc);
  1208. return dir->entries[dir->nr++] = dir_entry_new(pathname, len);
  1209. }
  1210. struct dir_entry *dir_add_ignored(struct dir_struct *dir,
  1211. struct index_state *istate,
  1212. const char *pathname, int len)
  1213. {
  1214. if (!index_name_is_other(istate, pathname, len))
  1215. return NULL;
  1216. ALLOC_GROW(dir->ignored, dir->ignored_nr+1, dir->ignored_alloc);
  1217. return dir->ignored[dir->ignored_nr++] = dir_entry_new(pathname, len);
  1218. }
  1219. enum exist_status {
  1220. index_nonexistent = 0,
  1221. index_directory,
  1222. index_gitdir
  1223. };
  1224. /*
  1225. * Do not use the alphabetically sorted index to look up
  1226. * the directory name; instead, use the case insensitive
  1227. * directory hash.
  1228. */
  1229. static enum exist_status directory_exists_in_index_icase(struct index_state *istate,
  1230. const char *dirname, int len)
  1231. {
  1232. struct cache_entry *ce;
  1233. if (index_dir_exists(istate, dirname, len))
  1234. return index_directory;
  1235. ce = index_file_exists(istate, dirname, len, ignore_case);
  1236. if (ce && S_ISGITLINK(ce->ce_mode))
  1237. return index_gitdir;
  1238. return index_nonexistent;
  1239. }
  1240. /*
  1241. * The index sorts alphabetically by entry name, which
  1242. * means that a gitlink sorts as '\0' at the end, while
  1243. * a directory (which is defined not as an entry, but as
  1244. * the files it contains) will sort with the '/' at the
  1245. * end.
  1246. */
  1247. static enum exist_status directory_exists_in_index(struct index_state *istate,
  1248. const char *dirname, int len)
  1249. {
  1250. int pos;
  1251. if (ignore_case)
  1252. return directory_exists_in_index_icase(istate, dirname, len);
  1253. pos = index_name_pos(istate, dirname, len);
  1254. if (pos < 0)
  1255. pos = -pos-1;
  1256. while (pos < istate->cache_nr) {
  1257. const struct cache_entry *ce = istate->cache[pos++];
  1258. unsigned char endchar;
  1259. if (strncmp(ce->name, dirname, len))
  1260. break;
  1261. endchar = ce->name[len];
  1262. if (endchar > '/')
  1263. break;
  1264. if (endchar == '/')
  1265. return index_directory;
  1266. if (!endchar && S_ISGITLINK(ce->ce_mode))
  1267. return index_gitdir;
  1268. }
  1269. return index_nonexistent;
  1270. }
  1271. /*
  1272. * When we find a directory when traversing the filesystem, we
  1273. * have three distinct cases:
  1274. *
  1275. * - ignore it
  1276. * - see it as a directory
  1277. * - recurse into it
  1278. *
  1279. * and which one we choose depends on a combination of existing
  1280. * git index contents and the flags passed into the directory
  1281. * traversal routine.
  1282. *
  1283. * Case 1: If we *already* have entries in the index under that
  1284. * directory name, we always recurse into the directory to see
  1285. * all the files.
  1286. *
  1287. * Case 2: If we *already* have that directory name as a gitlink,
  1288. * we always continue to see it as a gitlink, regardless of whether
  1289. * there is an actual git directory there or not (it might not
  1290. * be checked out as a subproject!)
  1291. *
  1292. * Case 3: if we didn't have it in the index previously, we
  1293. * have a few sub-cases:
  1294. *
  1295. * (a) if "show_other_directories" is true, we show it as
  1296. * just a directory, unless "hide_empty_directories" is
  1297. * also true, in which case we need to check if it contains any
  1298. * untracked and / or ignored files.
  1299. * (b) if it looks like a git directory, and we don't have
  1300. * 'no_gitlinks' set we treat it as a gitlink, and show it
  1301. * as a directory.
  1302. * (c) otherwise, we recurse into it.
  1303. */
  1304. static enum path_treatment treat_directory(struct dir_struct *dir,
  1305. struct index_state *istate,
  1306. struct untracked_cache_dir *untracked,
  1307. const char *dirname, int len, int baselen, int exclude,
  1308. const struct pathspec *pathspec)
  1309. {
  1310. /* The "len-1" is to strip the final '/' */
  1311. switch (directory_exists_in_index(istate, dirname, len-1)) {
  1312. case index_directory:
  1313. return path_recurse;
  1314. case index_gitdir:
  1315. return path_none;
  1316. case index_nonexistent:
  1317. if (dir->flags & DIR_SKIP_NESTED_GIT) {
  1318. int nested_repo;
  1319. struct strbuf sb = STRBUF_INIT;
  1320. strbuf_addstr(&sb, dirname);
  1321. nested_repo = is_nonbare_repository_dir(&sb);
  1322. strbuf_release(&sb);
  1323. if (nested_repo)
  1324. return path_none;
  1325. }
  1326. if (dir->flags & DIR_SHOW_OTHER_DIRECTORIES)
  1327. break;
  1328. if (exclude &&
  1329. (dir->flags & DIR_SHOW_IGNORED_TOO) &&
  1330. (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING)) {
  1331. /*
  1332. * This is an excluded directory and we are
  1333. * showing ignored paths that match an exclude
  1334. * pattern. (e.g. show directory as ignored
  1335. * only if it matches an exclude pattern).
  1336. * This path will either be 'path_excluded`
  1337. * (if we are showing empty directories or if
  1338. * the directory is not empty), or will be
  1339. * 'path_none' (empty directory, and we are
  1340. * not showing empty directories).
  1341. */
  1342. if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
  1343. return path_excluded;
  1344. if (read_directory_recursive(dir, istate, dirname, len,
  1345. untracked, 1, 1, pathspec) == path_excluded)
  1346. return path_excluded;
  1347. return path_none;
  1348. }
  1349. if (!(dir->flags & DIR_NO_GITLINKS)) {
  1350. struct strbuf sb = STRBUF_INIT;
  1351. strbuf_addstr(&sb, dirname);
  1352. if (is_nonbare_repository_dir(&sb))
  1353. return exclude ? path_excluded : path_untracked;
  1354. strbuf_release(&sb);
  1355. }
  1356. return path_recurse;
  1357. }
  1358. /* This is the "show_other_directories" case */
  1359. if (!(dir->flags & DIR_HIDE_EMPTY_DIRECTORIES))
  1360. return exclude ? path_excluded : path_untracked;
  1361. untracked = lookup_untracked(dir->untracked, untracked,
  1362. dirname + baselen, len - baselen);
  1363. /*
  1364. * If this is an excluded directory, then we only need to check if
  1365. * the directory contains any files.
  1366. */
  1367. return read_directory_recursive(dir, istate, dirname, len,
  1368. untracked, 1, exclude, pathspec);
  1369. }
  1370. /*
  1371. * This is an inexact early pruning of any recursive directory
  1372. * reading - if the path cannot possibly be in the pathspec,
  1373. * return true, and we'll skip it early.
  1374. */
  1375. static int simplify_away(const char *path, int pathlen,
  1376. const struct pathspec *pathspec)
  1377. {
  1378. int i;
  1379. if (!pathspec || !pathspec->nr)
  1380. return 0;
  1381. GUARD_PATHSPEC(pathspec,
  1382. PATHSPEC_FROMTOP |
  1383. PATHSPEC_MAXDEPTH |
  1384. PATHSPEC_LITERAL |
  1385. PATHSPEC_GLOB |
  1386. PATHSPEC_ICASE |
  1387. PATHSPEC_EXCLUDE |
  1388. PATHSPEC_ATTR);
  1389. for (i = 0; i < pathspec->nr; i++) {
  1390. const struct pathspec_item *item = &pathspec->items[i];
  1391. int len = item->nowildcard_len;
  1392. if (len > pathlen)
  1393. len = pathlen;
  1394. if (!ps_strncmp(item, item->match, path, len))
  1395. return 0;
  1396. }
  1397. return 1;
  1398. }
  1399. /*
  1400. * This function tells us whether an excluded path matches a
  1401. * list of "interesting" pathspecs. That is, whether a path matched
  1402. * by any of the pathspecs could possibly be ignored by excluding
  1403. * the specified path. This can happen if:
  1404. *
  1405. * 1. the path is mentioned explicitly in the pathspec
  1406. *
  1407. * 2. the path is a directory prefix of some element in the
  1408. * pathspec
  1409. */
  1410. static int exclude_matches_pathspec(const char *path, int pathlen,
  1411. const struct pathspec *pathspec)
  1412. {
  1413. int i;
  1414. if (!pathspec || !pathspec->nr)
  1415. return 0;
  1416. GUARD_PATHSPEC(pathspec,
  1417. PATHSPEC_FROMTOP |
  1418. PATHSPEC_MAXDEPTH |
  1419. PATHSPEC_LITERAL |
  1420. PATHSPEC_GLOB |
  1421. PATHSPEC_ICASE |
  1422. PATHSPEC_EXCLUDE);
  1423. for (i = 0; i < pathspec->nr; i++) {
  1424. const struct pathspec_item *item = &pathspec->items[i];
  1425. int len = item->nowildcard_len;
  1426. if (len == pathlen &&
  1427. !ps_strncmp(item, item->match, path, pathlen))
  1428. return 1;
  1429. if (len > pathlen &&
  1430. item->match[pathlen] == '/' &&
  1431. !ps_strncmp(item, item->match, path, pathlen))
  1432. return 1;
  1433. }
  1434. return 0;
  1435. }
  1436. static int get_index_dtype(struct index_state *istate,
  1437. const char *path, int len)
  1438. {
  1439. int pos;
  1440. const struct cache_entry *ce;
  1441. ce = index_file_exists(istate, path, len, 0);
  1442. if (ce) {
  1443. if (!ce_uptodate(ce))
  1444. return DT_UNKNOWN;
  1445. if (S_ISGITLINK(ce->ce_mode))
  1446. return DT_DIR;
  1447. /*
  1448. * Nobody actually cares about the
  1449. * difference between DT_LNK and DT_REG
  1450. */
  1451. return DT_REG;
  1452. }
  1453. /* Try to look it up as a directory */
  1454. pos = index_name_pos(istate, path, len);
  1455. if (pos >= 0)
  1456. return DT_UNKNOWN;
  1457. pos = -pos-1;
  1458. while (pos < istate->cache_nr) {
  1459. ce = istate->cache[pos++];
  1460. if (strncmp(ce->name, path, len))
  1461. break;
  1462. if (ce->name[len] > '/')
  1463. break;
  1464. if (ce->name[len] < '/')
  1465. continue;
  1466. if (!ce_uptodate(ce))
  1467. break; /* continue? */
  1468. return DT_DIR;
  1469. }
  1470. return DT_UNKNOWN;
  1471. }
  1472. static int get_dtype(struct dirent *de, struct index_state *istate,
  1473. const char *path, int len)
  1474. {
  1475. int dtype = de ? DTYPE(de) : DT_UNKNOWN;
  1476. struct stat st;
  1477. if (dtype != DT_UNKNOWN)
  1478. return dtype;
  1479. dtype = get_index_dtype(istate, path, len);
  1480. if (dtype != DT_UNKNOWN)
  1481. return dtype;
  1482. if (lstat(path, &st))
  1483. return dtype;
  1484. if (S_ISREG(st.st_mode))
  1485. return DT_REG;
  1486. if (S_ISDIR(st.st_mode))
  1487. return DT_DIR;
  1488. if (S_ISLNK(st.st_mode))
  1489. return DT_LNK;
  1490. return dtype;
  1491. }
  1492. static enum path_treatment treat_one_path(struct dir_struct *dir,
  1493. struct untracked_cache_dir *untracked,
  1494. struct index_state *istate,
  1495. struct strbuf *path,
  1496. int baselen,
  1497. const struct pathspec *pathspec,
  1498. int dtype, struct dirent *de)
  1499. {
  1500. int exclude;
  1501. int has_path_in_index = !!index_file_exists(istate, path->buf, path->len, ignore_case);
  1502. enum path_treatment path_treatment;
  1503. if (dtype == DT_UNKNOWN)
  1504. dtype = get_dtype(de, istate, path->buf, path->len);
  1505. /* Always exclude indexed files */
  1506. if (dtype != DT_DIR && has_path_in_index)
  1507. return path_none;
  1508. /*
  1509. * When we are looking at a directory P in the working tree,
  1510. * there are three cases:
  1511. *
  1512. * (1) P exists in the index. Everything inside the directory P in
  1513. * the working tree needs to go when P is checked out from the
  1514. * index.
  1515. *
  1516. * (2) P does not exist in the index, but there is P/Q in the index.
  1517. * We know P will stay a directory when we check out the contents
  1518. * of the index, but we do not know yet if there is a directory
  1519. * P/Q in the working tree to be killed, so we need to recurse.
  1520. *
  1521. * (3) P does not exist in the index, and there is no P/Q in the index
  1522. * to require P to be a directory, either. Only in this case, we
  1523. * know that everything inside P will not be killed without
  1524. * recursing.
  1525. */
  1526. if ((dir->flags & DIR_COLLECT_KILLED_ONLY) &&
  1527. (dtype == DT_DIR) &&
  1528. !has_path_in_index &&
  1529. (directory_exists_in_index(istate, path->buf, path->len) == index_nonexistent))
  1530. return path_none;
  1531. exclude = is_excluded(dir, istate, path->buf, &dtype);
  1532. /*
  1533. * Excluded? If we don't explicitly want to show
  1534. * ignored files, ignore it
  1535. */
  1536. if (exclude && !(dir->flags & (DIR_SHOW_IGNORED|DIR_SHOW_IGNORED_TOO)))
  1537. return path_excluded;
  1538. switch (dtype) {
  1539. default:
  1540. return path_none;
  1541. case DT_DIR:
  1542. strbuf_addch(path, '/');
  1543. path_treatment = treat_directory(dir, istate, untracked,
  1544. path->buf, path->len,
  1545. baselen, exclude, pathspec);
  1546. /*
  1547. * If 1) we only want to return directories that
  1548. * match an exclude pattern and 2) this directory does
  1549. * not match an exclude pattern but all of its
  1550. * contents are excluded, then indicate that we should
  1551. * recurse into this directory (instead of marking the
  1552. * directory itself as an ignored path).
  1553. */
  1554. if (!exclude &&
  1555. path_treatment == path_excluded &&
  1556. (dir->flags & DIR_SHOW_IGNORED_TOO) &&
  1557. (dir->flags & DIR_SHOW_IGNORED_TOO_MODE_MATCHING))
  1558. return path_recurse;
  1559. return path_treatment;
  1560. case DT_REG:
  1561. case DT_LNK:
  1562. return exclude ? path_excluded : path_untracked;
  1563. }
  1564. }
  1565. static enum path_treatment treat_path_fast(struct dir_struct *dir,
  1566. struct untracked_cache_dir *untracked,
  1567. struct cached_dir *cdir,
  1568. struct index_state *istate,
  1569. struct strbuf *path,
  1570. int baselen,
  1571. const struct pathspec *pathspec)
  1572. {
  1573. strbuf_setlen(path, baselen);
  1574. if (!cdir->ucd) {
  1575. strbuf_addstr(path, cdir->file);
  1576. return path_untracked;
  1577. }
  1578. strbuf_addstr(path, cdir->ucd->name);
  1579. /* treat_one_path() does this before it calls treat_directory() */
  1580. strbuf_complete(path, '/');
  1581. if (cdir->ucd->check_only)
  1582. /*
  1583. * check_only is set as a result of treat_directory() getting
  1584. * to its bottom. Verify again the same set of directories
  1585. * with check_only set.
  1586. */
  1587. return read_directory_recursive(dir, istate, path->buf, path->len,
  1588. cdir->ucd, 1, 0, pathspec);
  1589. /*
  1590. * We get path_recurse in the first run when
  1591. * directory_exists_in_index() returns index_nonexistent. We
  1592. * are sure that new changes in the index does not impact the
  1593. * outcome. Return now.
  1594. */
  1595. return path_recurse;
  1596. }
  1597. static enum path_treatment treat_path(struct dir_struct *dir,
  1598. struct untracked_cache_dir *untracked,
  1599. struct cached_dir *cdir,
  1600. struct index_state *istate,
  1601. struct strbuf *path,
  1602. int baselen,
  1603. const struct pathspec *pathspec)
  1604. {
  1605. int dtype;
  1606. struct dirent *de = cdir->de;
  1607. if (!de)
  1608. return treat_path_fast(dir, untracked, cdir, istate, path,
  1609. baselen, pathspec);
  1610. if (is_dot_or_dotdot(de->d_name) || !fspathcmp(de->d_name, ".git"))
  1611. return path_none;
  1612. strbuf_setlen(path, baselen);
  1613. strbuf_addstr(path, de->d_name);
  1614. if (simplify_away(path->buf, path->len, pathspec))
  1615. return path_none;
  1616. dtype = DTYPE(de);
  1617. return treat_one_path(dir, untracked, istate, path, baselen, pathspec, dtype, de);
  1618. }
  1619. static void add_untracked(struct untracked_cache_dir *dir, const char *name)
  1620. {
  1621. if (!dir)
  1622. return;
  1623. ALLOC_GROW(dir->untracked, dir->untracked_nr + 1,
  1624. dir->untracked_alloc);
  1625. dir->untracked[dir->untracked_nr++] = xstrdup(name);
  1626. }
  1627. static int valid_cached_dir(struct dir_struct *dir,
  1628. struct untracked_cache_dir *untracked,
  1629. struct index_state *istate,
  1630. struct strbuf *path,
  1631. int check_only)
  1632. {
  1633. struct stat st;
  1634. if (!untracked)
  1635. return 0;
  1636. /*
  1637. * With fsmonitor, we can trust the untracked cache's valid field.
  1638. */
  1639. refresh_fsmonitor(istate);
  1640. if (!(dir->untracked->use_fsmonitor && untracked->valid)) {
  1641. if (lstat(path->len ? path->buf : ".", &st)) {
  1642. memset(&untracked->stat_data, 0, sizeof(untracked->stat_data));
  1643. return 0;
  1644. }
  1645. if (!untracked->valid ||
  1646. match_stat_data_racy(istate, &untracked->stat_data, &st)) {
  1647. fill_stat_data(&untracked->stat_data, &st);
  1648. return 0;
  1649. }
  1650. }
  1651. if (untracked->check_only != !!check_only)
  1652. return 0;
  1653. /*
  1654. * prep_exclude will be called eventually on this directory,
  1655. * but it's called much later in last_matching_pattern(). We
  1656. * need it now to determine the validity of the cache for this
  1657. * path. The next calls will be nearly no-op, the way
  1658. * prep_exclude() is designed.
  1659. */
  1660. if (path->len && path->buf[path->len - 1] != '/') {
  1661. strbuf_addch(path, '/');
  1662. prep_exclude(dir, istate, path->buf, path->len);
  1663. strbuf_setlen(path, path->len - 1);
  1664. } else
  1665. prep_exclude(dir, istate, path->buf, path->len);
  1666. /* hopefully prep_exclude() haven't invalidated this entry... */
  1667. return untracked->valid;
  1668. }
  1669. static int open_cached_dir(struct cached_dir *cdir,
  1670. struct dir_struct *dir,
  1671. struct untracked_cache_dir *untracked,
  1672. struct index_state *istate,
  1673. struct strbuf *path,
  1674. int check_only)
  1675. {
  1676. const char *c_path;
  1677. memset(cdir, 0, sizeof(*cdir));
  1678. cdir->untracked = untracked;
  1679. if (valid_cached_dir(dir, untracked, istate, path, check_only))
  1680. return 0;
  1681. c_path = path->len ? path->buf : ".";
  1682. cdir->fdir = opendir(c_path);
  1683. if (!cdir->fdir)
  1684. warning_errno(_("could not open directory '%s'"), c_path);
  1685. if (dir->untracked) {
  1686. invalidate_directory(dir->untracked, untracked);
  1687. dir->untracked->dir_opened++;
  1688. }
  1689. if (!cdir->fdir)
  1690. return -1;
  1691. return 0;
  1692. }
  1693. static int read_cached_dir(struct cached_dir *cdir)
  1694. {
  1695. if (cdir->fdir) {
  1696. cdir->de = readdir(cdir->fdir);
  1697. if (!cdir->de)
  1698. return -1;
  1699. return 0;
  1700. }
  1701. while (cdir->nr_dirs < cdir->untracked->dirs_nr) {
  1702. struct untracked_cache_dir *d = cdir->untracked->dirs[cdir->nr_dirs];
  1703. if (!d->recurse) {
  1704. cdir->nr_dirs++;
  1705. continue;
  1706. }
  1707. cdir->ucd = d;
  1708. cdir->nr_dirs++;
  1709. return 0;
  1710. }
  1711. cdir->ucd = NULL;
  1712. if (cdir->nr_files < cdir->untracked->untracked_nr) {
  1713. struct untracked_cache_dir *d = cdir->untracked;
  1714. cdir->file = d->untracked[cdir->nr_files++];
  1715. return 0;
  1716. }
  1717. return -1;
  1718. }
  1719. static void close_cached_dir(struct cached_dir *cdir)
  1720. {
  1721. if (cdir->fdir)
  1722. closedir(cdir->fdir);
  1723. /*
  1724. * We have gone through this directory and found no untracked
  1725. * entries. Mark it valid.
  1726. */
  1727. if (cdir->untracked) {
  1728. cdir->untracked->valid = 1;
  1729. cdir->untracked->recurse = 1;
  1730. }
  1731. }
  1732. /*
  1733. * Read a directory tree. We currently ignore anything but
  1734. * directories, regular files and symlinks. That's because git
  1735. * doesn't handle them at all yet. Maybe that will change some
  1736. * day.
  1737. *
  1738. * Also, we ignore the name ".git" (even if it is not a directory).
  1739. * That likely will not change.
  1740. *
  1741. * If 'stop_at_first_file' is specified, 'path_excluded' is returned
  1742. * to signal that a file was found. This is the least significant value that
  1743. * indicates that a file was encountered that does not depend on the order of
  1744. * whether an untracked or exluded path was encountered first.
  1745. *
  1746. * Returns the most significant path_treatment value encountered in the scan.
  1747. * If 'stop_at_first_file' is specified, `path_excluded` is the most
  1748. * significant path_treatment value that will be returned.
  1749. */
  1750. static enum path_treatment read_directory_recursive(struct dir_struct *dir,
  1751. struct index_state *istate, const char *base, int baselen,
  1752. struct untracked_cache_dir *untracked, int check_only,
  1753. int stop_at_first_file, const struct pathspec *pathspec)
  1754. {
  1755. struct cached_dir cdir;
  1756. enum path_treatment state, subdir_state, dir_state = path_none;
  1757. struct strbuf path = STRBUF_INIT;
  1758. strbuf_add(&path, base, baselen);
  1759. if (open_cached_dir(&cdir, dir, untracked, istate, &path, check_only))
  1760. goto out;
  1761. if (untracked)
  1762. untracked->check_only = !!check_only;
  1763. while (!read_cached_dir(&cdir)) {
  1764. /* check how the file or directory should be treated */
  1765. state = treat_path(dir, untracked, &cdir, istate, &path,
  1766. baselen, pathspec);
  1767. if (state > dir_state)
  1768. dir_state = state;
  1769. /* recurse into subdir if instructed by treat_path */
  1770. if ((state == path_recurse) ||
  1771. ((state == path_untracked) &&
  1772. (get_dtype(cdir.de, istate, path.buf, path.len) == DT_DIR) &&
  1773. ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
  1774. (pathspec &&
  1775. do_match_pathspec(istate, pathspec, path.buf, path.len,
  1776. baselen, NULL, DO_MATCH_LEADING_PATHSPEC) == MATCHED_RECURSIVELY_LEADING_PATHSPEC)))) {
  1777. struct untracked_cache_dir *ud;
  1778. ud = lookup_untracked(dir->untracked, untracked,
  1779. path.buf + baselen,
  1780. path.len - baselen);
  1781. subdir_state =
  1782. read_directory_recursive(dir, istate, path.buf,
  1783. path.len, ud,
  1784. check_only, stop_at_first_file, pathspec);
  1785. if (subdir_state > dir_state)
  1786. dir_state = subdir_state;
  1787. if (pathspec &&
  1788. !match_pathspec(istate, pathspec, path.buf, path.len,
  1789. 0 /* prefix */, NULL,
  1790. 0 /* do NOT special case dirs */))
  1791. state = path_none;
  1792. }
  1793. if (check_only) {
  1794. if (stop_at_first_file) {
  1795. /*
  1796. * If stopping at first file, then
  1797. * signal that a file was found by
  1798. * returning `path_excluded`. This is
  1799. * to return a consistent value
  1800. * regardless of whether an ignored or
  1801. * excluded file happened to be
  1802. * encountered 1st.
  1803. *
  1804. * In current usage, the
  1805. * `stop_at_first_file` is passed when
  1806. * an ancestor directory has matched
  1807. * an exclude pattern, so any found
  1808. * files will be excluded.
  1809. */
  1810. if (dir_state >= path_excluded) {
  1811. dir_state = path_excluded;
  1812. break;
  1813. }
  1814. }
  1815. /* abort early if maximum state has been reached */
  1816. if (dir_state == path_untracked) {
  1817. if (cdir.fdir)
  1818. add_untracked(untracked, path.buf + baselen);
  1819. break;
  1820. }
  1821. /* skip the dir_add_* part */
  1822. continue;
  1823. }
  1824. /* add the path to the appropriate result list */
  1825. switch (state) {
  1826. case path_excluded:
  1827. if (dir->flags & DIR_SHOW_IGNORED)
  1828. dir_add_name(dir, istate, path.buf, path.len);
  1829. else if ((dir->flags & DIR_SHOW_IGNORED_TOO) ||
  1830. ((dir->flags & DIR_COLLECT_IGNORED) &&
  1831. exclude_matches_pathspec(path.buf, path.len,
  1832. pathspec)))
  1833. dir_add_ignored(dir, istate, path.buf, path.len);
  1834. break;
  1835. case path_untracked:
  1836. if (dir->flags & DIR_SHOW_IGNORED)
  1837. break;
  1838. dir_add_name(dir, istate, path.buf, path.len);
  1839. if (cdir.fdir)
  1840. add_untracked(untracked, path.buf + baselen);
  1841. break;
  1842. default:
  1843. break;
  1844. }
  1845. }
  1846. close_cached_dir(&cdir);
  1847. out:
  1848. strbuf_release(&path);
  1849. return dir_state;
  1850. }
  1851. int cmp_dir_entry(const void *p1, const void *p2)
  1852. {
  1853. const struct dir_entry *e1 = *(const struct dir_entry **)p1;
  1854. const struct dir_entry *e2 = *(const struct dir_entry **)p2;
  1855. return name_compare(e1->name, e1->len, e2->name, e2->len);
  1856. }
  1857. /* check if *out lexically strictly contains *in */
  1858. int check_dir_entry_contains(const struct dir_entry *out, const struct dir_entry *in)
  1859. {
  1860. return (out->len < in->len) &&
  1861. (out->name[out->len - 1] == '/') &&
  1862. !memcmp(out->name, in->name, out->len);
  1863. }
  1864. static int treat_leading_path(struct dir_struct *dir,
  1865. struct index_state *istate,
  1866. const char *path, int len,
  1867. const struct pathspec *pathspec)
  1868. {
  1869. struct strbuf sb = STRBUF_INIT;
  1870. int baselen, rc = 0;
  1871. const char *cp;
  1872. int old_flags = dir->flags;
  1873. while (len && path[len - 1] == '/')
  1874. len--;
  1875. if (!len)
  1876. return 1;
  1877. baselen = 0;
  1878. dir->flags &= ~DIR_SHOW_OTHER_DIRECTORIES;
  1879. while (1) {
  1880. cp = path + baselen + !!baselen;
  1881. cp = memchr(cp, '/', path + len - cp);
  1882. if (!cp)
  1883. baselen = len;
  1884. else
  1885. baselen = cp - path;
  1886. strbuf_setlen(&sb, 0);
  1887. strbuf_add(&sb, path, baselen);
  1888. if (!is_directory(sb.buf))
  1889. break;
  1890. if (simplify_away(sb.buf, sb.len, pathspec))
  1891. break;
  1892. if (treat_one_path(dir, NULL, istate, &sb, baselen, pathspec,
  1893. DT_DIR, NULL) == path_none)
  1894. break; /* do not recurse into it */
  1895. if (len <= baselen) {
  1896. rc = 1;
  1897. break; /* finished checking */
  1898. }
  1899. }
  1900. strbuf_release(&sb);
  1901. dir->flags = old_flags;
  1902. return rc;
  1903. }
  1904. static const char *get_ident_string(void)
  1905. {
  1906. static struct strbuf sb = STRBUF_INIT;
  1907. struct utsname uts;
  1908. if (sb.len)
  1909. return sb.buf;
  1910. if (uname(&uts) < 0)
  1911. die_errno(_("failed to get kernel name and information"));
  1912. strbuf_addf(&sb, "Location %s, system %s", get_git_work_tree(),
  1913. uts.sysname);
  1914. return sb.buf;
  1915. }
  1916. static int ident_in_untracked(const struct untracked_cache *uc)
  1917. {
  1918. /*
  1919. * Previous git versions may have saved many NUL separated
  1920. * strings in the "ident" field, but it is insane to manage
  1921. * many locations, so just take care of the first one.
  1922. */
  1923. return !strcmp(uc->ident.buf, get_ident_string());
  1924. }
  1925. static void set_untracked_ident(struct untracked_cache *uc)
  1926. {
  1927. strbuf_reset(&uc->ident);
  1928. strbuf_addstr(&uc->ident, get_ident_string());
  1929. /*
  1930. * This strbuf used to contain a list of NUL separated
  1931. * strings, so save NUL too for backward compatibility.
  1932. */
  1933. strbuf_addch(&uc->ident, 0);
  1934. }
  1935. static void new_untracked_cache(struct index_state *istate)
  1936. {
  1937. struct untracked_cache *uc = xcalloc(1, sizeof(*uc));
  1938. strbuf_init(&uc->ident, 100);
  1939. uc->exclude_per_dir = ".gitignore";
  1940. /* should be the same flags used by git-status */
  1941. uc->dir_flags = DIR_SHOW_OTHER_DIRECTORIES | DIR_HIDE_EMPTY_DIRECTORIES;
  1942. set_untracked_ident(uc);
  1943. istate->untracked = uc;
  1944. istate->cache_changed |= UNTRACKED_CHANGED;
  1945. }
  1946. void add_untracked_cache(struct index_state *istate)
  1947. {
  1948. if (!istate->untracked) {
  1949. new_untracked_cache(istate);
  1950. } else {
  1951. if (!ident_in_untracked(istate->untracked)) {
  1952. free_untracked_cache(istate->untracked);
  1953. new_untracked_cache(istate);
  1954. }
  1955. }
  1956. }
  1957. void remove_untracked_cache(struct index_state *istate)
  1958. {
  1959. if (istate->untracked) {
  1960. free_untracked_cache(istate->untracked);
  1961. istate->untracked = NULL;
  1962. istate->cache_changed |= UNTRACKED_CHANGED;
  1963. }
  1964. }
  1965. static struct untracked_cache_dir *validate_untracked_cache(struct dir_struct *dir,
  1966. int base_len,
  1967. const struct pathspec *pathspec)
  1968. {
  1969. struct untracked_cache_dir *root;
  1970. static int untracked_cache_disabled = -1;
  1971. if (!dir->untracked)
  1972. return NULL;
  1973. if (untracked_cache_disabled < 0)
  1974. untracked_cache_disabled = git_env_bool("GIT_DISABLE_UNTRACKED_CACHE", 0);
  1975. if (untracked_cache_disabled)
  1976. return NULL;
  1977. /*
  1978. * We only support $GIT_DIR/info/exclude and core.excludesfile
  1979. * as the global ignore rule files. Any other additions
  1980. * (e.g. from command line) invalidate the cache. This
  1981. * condition also catches running setup_standard_excludes()
  1982. * before setting dir->untracked!
  1983. */
  1984. if (dir->unmanaged_exclude_files)
  1985. return NULL;
  1986. /*
  1987. * Optimize for the main use case only: whole-tree git
  1988. * status. More work involved in treat_leading_path() if we
  1989. * use cache on just a subset of the worktree. pathspec
  1990. * support could make the matter even worse.
  1991. */
  1992. if (base_len || (pathspec && pathspec->nr))
  1993. return NULL;
  1994. /* Different set of flags may produce different results */
  1995. if (dir->flags != dir->untracked->dir_flags ||
  1996. /*
  1997. * See treat_directory(), case index_nonexistent. Without
  1998. * this flag, we may need to also cache .git file content
  1999. * for the resolve_gitlink_ref() call, which we don't.
  2000. */
  2001. !(dir->flags & DIR_SHOW_OTHER_DIRECTORIES) ||
  2002. /* We don't support collecting ignore files */
  2003. (dir->flags & (DIR_SHOW_IGNORED | DIR_SHOW_IGNORED_TOO |
  2004. DIR_COLLECT_IGNORED)))
  2005. return NULL;
  2006. /*
  2007. * If we use .gitignore in the cache and now you change it to
  2008. * .gitexclude, everything will go wrong.
  2009. */
  2010. if (dir->exclude_per_dir != dir->untracked->exclude_per_dir &&
  2011. strcmp(dir->exclude_per_dir, dir->untracked->exclude_per_dir))
  2012. return NULL;
  2013. /*
  2014. * EXC_CMDL is not considered in the cache. If people set it,
  2015. * skip the cache.
  2016. */
  2017. if (dir->exclude_list_group[EXC_CMDL].nr)
  2018. return NULL;
  2019. if (!ident_in_untracked(dir->untracked)) {
  2020. warning(_("untracked cache is disabled on this system or location"));
  2021. return NULL;
  2022. }
  2023. if (!dir->untracked->root) {
  2024. const int len = sizeof(*dir->untracked->root);
  2025. dir->untracked->root = xmalloc(len);
  2026. memset(dir->untracked->root, 0, len);
  2027. }
  2028. /* Validate $GIT_DIR/info/exclude and core.excludesfile */
  2029. root = dir->untracked->root;
  2030. if (!oideq(&dir->ss_info_exclude.oid,
  2031. &dir->untracked->ss_info_exclude.oid)) {
  2032. invalidate_gitignore(dir->untracked, root);
  2033. dir->untracked->ss_info_exclude = dir->ss_info_exclude;
  2034. }
  2035. if (!oideq(&dir->ss_excludes_file.oid,
  2036. &dir->untracked->ss_excludes_file.oid)) {
  2037. invalidate_gitignore(dir->untracked, root);
  2038. dir->untracked->ss_excludes_file = dir->ss_excludes_file;
  2039. }
  2040. /* Make sure this directory is not dropped out at saving phase */
  2041. root->recurse = 1;
  2042. return root;
  2043. }
  2044. int read_directory(struct dir_struct *dir, struct index_state *istate,
  2045. const char *path, int len, const struct pathspec *pathspec)
  2046. {
  2047. struct untracked_cache_dir *untracked;
  2048. trace_performance_enter();
  2049. if (has_symlink_leading_path(path, len)) {
  2050. trace_performance_leave("read directory %.*s", len, path);
  2051. return dir->nr;
  2052. }
  2053. untracked = validate_untracked_cache(dir, len, pathspec);
  2054. if (!untracked)
  2055. /*
  2056. * make sure untracked cache code path is disabled,
  2057. * e.g. prep_exclude()
  2058. */
  2059. dir->untracked = NULL;
  2060. if (!len || treat_leading_path(dir, istate, path, len, pathspec))
  2061. read_directory_recursive(dir, istate, path, len, untracked, 0, 0, pathspec);
  2062. QSORT(dir->entries, dir->nr, cmp_dir_entry);
  2063. QSORT(dir->ignored, dir->ignored_nr, cmp_dir_entry);
  2064. /*
  2065. * If DIR_SHOW_IGNORED_TOO is set, read_directory_recursive() will
  2066. * also pick up untracked contents of untracked dirs; by default
  2067. * we discard these, but given DIR_KEEP_UNTRACKED_CONTENTS we do not.
  2068. */
  2069. if ((dir->flags & DIR_SHOW_IGNORED_TOO) &&
  2070. !(dir->flags & DIR_KEEP_UNTRACKED_CONTENTS)) {
  2071. int i, j;
  2072. /* remove from dir->entries untracked contents of untracked dirs */
  2073. for (i = j = 0; j < dir->nr; j++) {
  2074. if (i &&
  2075. check_dir_entry_contains(dir->entries[i - 1], dir->entries[j])) {
  2076. FREE_AND_NULL(dir->entries[j]);
  2077. } else {
  2078. dir->entries[i++] = dir->entries[j];
  2079. }
  2080. }
  2081. dir->nr = i;
  2082. }
  2083. trace_performance_leave("read directory %.*s", len, path);
  2084. if (dir->untracked) {
  2085. static int force_untracked_cache = -1;
  2086. static struct trace_key trace_untracked_stats = TRACE_KEY_INIT(UNTRACKED_STATS);
  2087. if (force_untracked_cache < 0)
  2088. force_untracked_cache =
  2089. git_env_bool("GIT_FORCE_UNTRACKED_CACHE", 0);
  2090. trace_printf_key(&trace_untracked_stats,
  2091. "node creation: %u\n"
  2092. "gitignore invalidation: %u\n"
  2093. "directory invalidation: %u\n"
  2094. "opendir: %u\n",
  2095. dir->untracked->dir_created,
  2096. dir->untracked->gitignore_invalidated,
  2097. dir->untracked->dir_invalidated,
  2098. dir->untracked->dir_opened);
  2099. if (force_untracked_cache &&
  2100. dir->untracked == istate->untracked &&
  2101. (dir->untracked->dir_opened ||
  2102. dir->untracked->gitignore_invalidated ||
  2103. dir->untracked->dir_invalidated))
  2104. istate->cache_changed |= UNTRACKED_CHANGED;
  2105. if (dir->untracked != istate->untracked) {
  2106. FREE_AND_NULL(dir->untracked);
  2107. }
  2108. }
  2109. return dir->nr;
  2110. }
  2111. int file_exists(const char *f)
  2112. {
  2113. struct stat sb;
  2114. return lstat(f, &sb) == 0;
  2115. }
  2116. int repo_file_exists(struct repository *repo, const char *path)
  2117. {
  2118. if (repo != the_repository)
  2119. BUG("do not know how to check file existence in arbitrary repo");
  2120. return file_exists(path);
  2121. }
  2122. static int cmp_icase(char a, char b)
  2123. {
  2124. if (a == b)
  2125. return 0;
  2126. if (ignore_case)
  2127. return toupper(a) - toupper(b);
  2128. return a - b;
  2129. }
  2130. /*
  2131. * Given two normalized paths (a trailing slash is ok), if subdir is
  2132. * outside dir, return -1. Otherwise return the offset in subdir that
  2133. * can be used as relative path to dir.
  2134. */
  2135. int dir_inside_of(const char *subdir, const char *dir)
  2136. {
  2137. int offset = 0;
  2138. assert(dir && subdir && *dir && *subdir);
  2139. while (*dir && *subdir && !cmp_icase(*dir, *subdir)) {
  2140. dir++;
  2141. subdir++;
  2142. offset++;
  2143. }
  2144. /* hel[p]/me vs hel[l]/yeah */
  2145. if (*dir && *subdir)
  2146. return -1;
  2147. if (!*subdir)
  2148. return !*dir ? offset : -1; /* same dir */
  2149. /* foo/[b]ar vs foo/[] */
  2150. if (is_dir_sep(dir[-1]))
  2151. return is_dir_sep(subdir[-1]) ? offset : -1;
  2152. /* foo[/]bar vs foo[] */
  2153. return is_dir_sep(*subdir) ? offset + 1 : -1;
  2154. }
  2155. int is_inside_dir(const char *dir)
  2156. {
  2157. char *cwd;
  2158. int rc;
  2159. if (!dir)
  2160. return 0;
  2161. cwd = xgetcwd();
  2162. rc = (dir_inside_of(cwd, dir) >= 0);
  2163. free(cwd);
  2164. return rc;
  2165. }
  2166. int is_empty_dir(const char *path)
  2167. {
  2168. DIR *dir = opendir(path);
  2169. struct dirent *e;
  2170. int ret = 1;
  2171. if (!dir)
  2172. return 0;
  2173. while ((e = readdir(dir)) != NULL)
  2174. if (!is_dot_or_dotdot(e->d_name)) {
  2175. ret = 0;
  2176. break;
  2177. }
  2178. closedir(dir);
  2179. return ret;
  2180. }
  2181. static int remove_dir_recurse(struct strbuf *path, int flag, int *kept_up)
  2182. {
  2183. DIR *dir;
  2184. struct dirent *e;
  2185. int ret = 0, original_len = path->len, len, kept_down = 0;
  2186. int only_empty = (flag & REMOVE_DIR_EMPTY_ONLY);
  2187. int keep_toplevel = (flag & REMOVE_DIR_KEEP_TOPLEVEL);
  2188. struct object_id submodule_head;
  2189. if ((flag & REMOVE_DIR_KEEP_NESTED_GIT) &&
  2190. !resolve_gitlink_ref(path->buf, "HEAD", &submodule_head)) {
  2191. /* Do not descend and nuke a nested git work tree. */
  2192. if (kept_up)
  2193. *kept_up = 1;
  2194. return 0;
  2195. }
  2196. flag &= ~REMOVE_DIR_KEEP_TOPLEVEL;
  2197. dir = opendir(path->buf);
  2198. if (!dir) {
  2199. if (errno == ENOENT)
  2200. return keep_toplevel ? -1 : 0;
  2201. else if (errno == EACCES && !keep_toplevel)
  2202. /*
  2203. * An empty dir could be removable even if it
  2204. * is unreadable:
  2205. */
  2206. return rmdir(path->buf);
  2207. else
  2208. return -1;
  2209. }
  2210. strbuf_complete(path, '/');
  2211. len = path->len;
  2212. while ((e = readdir(dir)) != NULL) {
  2213. struct stat st;
  2214. if (is_dot_or_dotdot(e->d_name))
  2215. continue;
  2216. strbuf_setlen(path, len);
  2217. strbuf_addstr(path, e->d_name);
  2218. if (lstat(path->buf, &st)) {
  2219. if (errno == ENOENT)
  2220. /*
  2221. * file disappeared, which is what we
  2222. * wanted anyway
  2223. */
  2224. continue;
  2225. /* fall thru */
  2226. } else if (S_ISDIR(st.st_mode)) {
  2227. if (!remove_dir_recurse(path, flag, &kept_down))
  2228. continue; /* happy */
  2229. } else if (!only_empty &&
  2230. (!unlink(path->buf) || errno == ENOENT)) {
  2231. continue; /* happy, too */
  2232. }
  2233. /* path too long, stat fails, or non-directory still exists */
  2234. ret = -1;
  2235. break;
  2236. }
  2237. closedir(dir);
  2238. strbuf_setlen(path, original_len);
  2239. if (!ret && !keep_toplevel && !kept_down)
  2240. ret = (!rmdir(path->buf) || errno == ENOENT) ? 0 : -1;
  2241. else if (kept_up)
  2242. /*
  2243. * report the uplevel that it is not an error that we
  2244. * did not rmdir() our directory.
  2245. */
  2246. *kept_up = !ret;
  2247. return ret;
  2248. }
  2249. int remove_dir_recursively(struct strbuf *path, int flag)
  2250. {
  2251. return remove_dir_recurse(path, flag, NULL);
  2252. }
  2253. static GIT_PATH_FUNC(git_path_info_exclude, "info/exclude")
  2254. void setup_standard_excludes(struct dir_struct *dir)
  2255. {
  2256. dir->exclude_per_dir = ".gitignore";
  2257. /* core.excludesfile defaulting to $XDG_CONFIG_HOME/git/ignore */
  2258. if (!excludes_file)
  2259. excludes_file = xdg_config_home("ignore");
  2260. if (excludes_file && !access_or_warn(excludes_file, R_OK, 0))
  2261. add_patterns_from_file_1(dir, excludes_file,
  2262. dir->untracked ? &dir->ss_excludes_file : NULL);
  2263. /* per repository user preference */
  2264. if (startup_info->have_repository) {
  2265. const char *path = git_path_info_exclude();
  2266. if (!access_or_warn(path, R_OK, 0))
  2267. add_patterns_from_file_1(dir, path,
  2268. dir->untracked ? &dir->ss_info_exclude : NULL);
  2269. }
  2270. }
  2271. int remove_path(const char *name)
  2272. {
  2273. char *slash;
  2274. if (unlink(name) && !is_missing_file_error(errno))
  2275. return -1;
  2276. slash = strrchr(name, '/');
  2277. if (slash) {
  2278. char *dirs = xstrdup(name);
  2279. slash = dirs + (slash - name);
  2280. do {
  2281. *slash = '\0';
  2282. } while (rmdir(dirs) == 0 && (slash = strrchr(dirs, '/')));
  2283. free(dirs);
  2284. }
  2285. return 0;
  2286. }
  2287. /*
  2288. * Frees memory within dir which was allocated for exclude lists and
  2289. * the exclude_stack. Does not free dir itself.
  2290. */
  2291. void clear_directory(struct dir_struct *dir)
  2292. {
  2293. int i, j;
  2294. struct exclude_list_group *group;
  2295. struct pattern_list *pl;
  2296. struct exclude_stack *stk;
  2297. for (i = EXC_CMDL; i <= EXC_FILE; i++) {
  2298. group = &dir->exclude_list_group[i];
  2299. for (j = 0; j < group->nr; j++) {
  2300. pl = &group->pl[j];
  2301. if (i == EXC_DIRS)
  2302. free((char *)pl->src);
  2303. clear_pattern_list(pl);
  2304. }
  2305. free(group->pl);
  2306. }
  2307. stk = dir->exclude_stack;
  2308. while (stk) {
  2309. struct exclude_stack *prev = stk->prev;
  2310. free(stk);
  2311. stk = prev;
  2312. }
  2313. strbuf_release(&dir->basebuf);
  2314. }
  2315. struct ondisk_untracked_cache {
  2316. struct stat_data info_exclude_stat;
  2317. struct stat_data excludes_file_stat;
  2318. uint32_t dir_flags;
  2319. };
  2320. #define ouc_offset(x) offsetof(struct ondisk_untracked_cache, x)
  2321. struct write_data {
  2322. int index; /* number of written untracked_cache_dir */
  2323. struct ewah_bitmap *check_only; /* from untracked_cache_dir */
  2324. struct ewah_bitmap *valid; /* from untracked_cache_dir */
  2325. struct ewah_bitmap *sha1_valid; /* set if exclude_sha1 is not null */
  2326. struct strbuf out;
  2327. struct strbuf sb_stat;
  2328. struct strbuf sb_sha1;
  2329. };
  2330. static void stat_data_to_disk(struct stat_data *to, const struct stat_data *from)
  2331. {
  2332. to->sd_ctime.sec = htonl(from->sd_ctime.sec);
  2333. to->sd_ctime.nsec = htonl(from->sd_ctime.nsec);
  2334. to->sd_mtime.sec = htonl(from->sd_mtime.sec);
  2335. to->sd_mtime.nsec = htonl(from->sd_mtime.nsec);
  2336. to->sd_dev = htonl(from->sd_dev);
  2337. to->sd_ino = htonl(from->sd_ino);
  2338. to->sd_uid = htonl(from->sd_uid);
  2339. to->sd_gid = htonl(from->sd_gid);
  2340. to->sd_size = htonl(from->sd_size);
  2341. }
  2342. static void write_one_dir(struct untracked_cache_dir *untracked,
  2343. struct write_data *wd)
  2344. {
  2345. struct stat_data stat_data;
  2346. struct strbuf *out = &wd->out;
  2347. unsigned char intbuf[16];
  2348. unsigned int intlen, value;
  2349. int i = wd->index++;
  2350. /*
  2351. * untracked_nr should be reset whenever valid is clear, but
  2352. * for safety..
  2353. */
  2354. if (!untracked->valid) {
  2355. untracked->untracked_nr = 0;
  2356. untracked->check_only = 0;
  2357. }
  2358. if (untracked->check_only)
  2359. ewah_set(wd->check_only, i);
  2360. if (untracked->valid) {
  2361. ewah_set(wd->valid, i);
  2362. stat_data_to_disk(&stat_data, &untracked->stat_data);
  2363. strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
  2364. }
  2365. if (!is_null_oid(&untracked->exclude_oid)) {
  2366. ewah_set(wd->sha1_valid, i);
  2367. strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
  2368. the_hash_algo->rawsz);
  2369. }
  2370. intlen = encode_varint(untracked->untracked_nr, intbuf);
  2371. strbuf_add(out, intbuf, intlen);
  2372. /* skip non-recurse directories */
  2373. for (i = 0, value = 0; i < untracked->dirs_nr; i++)
  2374. if (untracked->dirs[i]->recurse)
  2375. value++;
  2376. intlen = encode_varint(value, intbuf);
  2377. strbuf_add(out, intbuf, intlen);
  2378. strbuf_add(out, untracked->name, strlen(untracked->name) + 1);
  2379. for (i = 0; i < untracked->untracked_nr; i++)
  2380. strbuf_add(out, untracked->untracked[i],
  2381. strlen(untracked->untracked[i]) + 1);
  2382. for (i = 0; i < untracked->dirs_nr; i++)
  2383. if (untracked->dirs[i]->recurse)
  2384. write_one_dir(untracked->dirs[i], wd);
  2385. }
  2386. void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked)
  2387. {
  2388. struct ondisk_untracked_cache *ouc;
  2389. struct write_data wd;
  2390. unsigned char varbuf[16];
  2391. int varint_len;
  2392. const unsigned hashsz = the_hash_algo->rawsz;
  2393. ouc = xcalloc(1, sizeof(*ouc));
  2394. stat_data_to_disk(&ouc->info_exclude_stat, &untracked->ss_info_exclude.stat);
  2395. stat_data_to_disk(&ouc->excludes_file_stat, &untracked->ss_excludes_file.stat);
  2396. ouc->dir_flags = htonl(untracked->dir_flags);
  2397. varint_len = encode_varint(untracked->ident.len, varbuf);
  2398. strbuf_add(out, varbuf, varint_len);
  2399. strbuf_addbuf(out, &untracked->ident);
  2400. strbuf_add(out, ouc, sizeof(*ouc));
  2401. strbuf_add(out, untracked->ss_info_exclude.oid.hash, hashsz);
  2402. strbuf_add(out, untracked->ss_excludes_file.oid.hash, hashsz);
  2403. strbuf_add(out, untracked->exclude_per_dir, strlen(untracked->exclude_per_dir) + 1);
  2404. FREE_AND_NULL(ouc);
  2405. if (!untracked->root) {
  2406. varint_len = encode_varint(0, varbuf);
  2407. strbuf_add(out, varbuf, varint_len);
  2408. return;
  2409. }
  2410. wd.index = 0;
  2411. wd.check_only = ewah_new();
  2412. wd.valid = ewah_new();
  2413. wd.sha1_valid = ewah_new();
  2414. strbuf_init(&wd.out, 1024);
  2415. strbuf_init(&wd.sb_stat, 1024);
  2416. strbuf_init(&wd.sb_sha1, 1024);
  2417. write_one_dir(untracked->root, &wd);
  2418. varint_len = encode_varint(wd.index, varbuf);
  2419. strbuf_add(out, varbuf, varint_len);
  2420. strbuf_addbuf(out, &wd.out);
  2421. ewah_serialize_strbuf(wd.valid, out);
  2422. ewah_serialize_strbuf(wd.check_only, out);
  2423. ewah_serialize_strbuf(wd.sha1_valid, out);
  2424. strbuf_addbuf(out, &wd.sb_stat);
  2425. strbuf_addbuf(out, &wd.sb_sha1);
  2426. strbuf_addch(out, '\0'); /* safe guard for string lists */
  2427. ewah_free(wd.valid);
  2428. ewah_free(wd.check_only);
  2429. ewah_free(wd.sha1_valid);
  2430. strbuf_release(&wd.out);
  2431. strbuf_release(&wd.sb_stat);
  2432. strbuf_release(&wd.sb_sha1);
  2433. }
  2434. static void free_untracked(struct untracked_cache_dir *ucd)
  2435. {
  2436. int i;
  2437. if (!ucd)
  2438. return;
  2439. for (i = 0; i < ucd->dirs_nr; i++)
  2440. free_untracked(ucd->dirs[i]);
  2441. for (i = 0; i < ucd->untracked_nr; i++)
  2442. free(ucd->untracked[i]);
  2443. free(ucd->untracked);
  2444. free(ucd->dirs);
  2445. free(ucd);
  2446. }
  2447. void free_untracked_cache(struct untracked_cache *uc)
  2448. {
  2449. if (uc)
  2450. free_untracked(uc->root);
  2451. free(uc);
  2452. }
  2453. struct read_data {
  2454. int index;
  2455. struct untracked_cache_dir **ucd;
  2456. struct ewah_bitmap *check_only;
  2457. struct ewah_bitmap *valid;
  2458. struct ewah_bitmap *sha1_valid;
  2459. const unsigned char *data;
  2460. const unsigned char *end;
  2461. };
  2462. static void stat_data_from_disk(struct stat_data *to, const unsigned char *data)
  2463. {
  2464. memcpy(to, data, sizeof(*to));
  2465. to->sd_ctime.sec = ntohl(to->sd_ctime.sec);
  2466. to->sd_ctime.nsec = ntohl(to->sd_ctime.nsec);
  2467. to->sd_mtime.sec = ntohl(to->sd_mtime.sec);
  2468. to->sd_mtime.nsec = ntohl(to->sd_mtime.nsec);
  2469. to->sd_dev = ntohl(to->sd_dev);
  2470. to->sd_ino = ntohl(to->sd_ino);
  2471. to->sd_uid = ntohl(to->sd_uid);
  2472. to->sd_gid = ntohl(to->sd_gid);
  2473. to->sd_size = ntohl(to->sd_size);
  2474. }
  2475. static int read_one_dir(struct untracked_cache_dir **untracked_,
  2476. struct read_data *rd)
  2477. {
  2478. struct untracked_cache_dir ud, *untracked;
  2479. const unsigned char *data = rd->data, *end = rd->end;
  2480. const unsigned char *eos;
  2481. unsigned int value;
  2482. int i;
  2483. memset(&ud, 0, sizeof(ud));
  2484. value = decode_varint(&data);
  2485. if (data > end)
  2486. return -1;
  2487. ud.recurse = 1;
  2488. ud.untracked_alloc = value;
  2489. ud.untracked_nr = value;
  2490. if (ud.untracked_nr)
  2491. ALLOC_ARRAY(ud.untracked, ud.untracked_nr);
  2492. ud.dirs_alloc = ud.dirs_nr = decode_varint(&data);
  2493. if (data > end)
  2494. return -1;
  2495. ALLOC_ARRAY(ud.dirs, ud.dirs_nr);
  2496. eos = memchr(data, '\0', end - data);
  2497. if (!eos || eos == end)
  2498. return -1;
  2499. *untracked_ = untracked = xmalloc(st_add3(sizeof(*untracked), eos - data, 1));
  2500. memcpy(untracked, &ud, sizeof(ud));
  2501. memcpy(untracked->name, data, eos - data + 1);
  2502. data = eos + 1;
  2503. for (i = 0; i < untracked->untracked_nr; i++) {
  2504. eos = memchr(data, '\0', end - data);
  2505. if (!eos || eos == end)
  2506. return -1;
  2507. untracked->untracked[i] = xmemdupz(data, eos - data);
  2508. data = eos + 1;
  2509. }
  2510. rd->ucd[rd->index++] = untracked;
  2511. rd->data = data;
  2512. for (i = 0; i < untracked->dirs_nr; i++) {
  2513. if (read_one_dir(untracked->dirs + i, rd) < 0)
  2514. return -1;
  2515. }
  2516. return 0;
  2517. }
  2518. static void set_check_only(size_t pos, void *cb)
  2519. {
  2520. struct read_data *rd = cb;
  2521. struct untracked_cache_dir *ud = rd->ucd[pos];
  2522. ud->check_only = 1;
  2523. }
  2524. static void read_stat(size_t pos, void *cb)
  2525. {
  2526. struct read_data *rd = cb;
  2527. struct untracked_cache_dir *ud = rd->ucd[pos];
  2528. if (rd->data + sizeof(struct stat_data) > rd->end) {
  2529. rd->data = rd->end + 1;
  2530. return;
  2531. }
  2532. stat_data_from_disk(&ud->stat_data, rd->data);
  2533. rd->data += sizeof(struct stat_data);
  2534. ud->valid = 1;
  2535. }
  2536. static void read_oid(size_t pos, void *cb)
  2537. {
  2538. struct read_data *rd = cb;
  2539. struct untracked_cache_dir *ud = rd->ucd[pos];
  2540. if (rd->data + the_hash_algo->rawsz > rd->end) {
  2541. rd->data = rd->end + 1;
  2542. return;
  2543. }
  2544. hashcpy(ud->exclude_oid.hash, rd->data);
  2545. rd->data += the_hash_algo->rawsz;
  2546. }
  2547. static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
  2548. const unsigned char *sha1)
  2549. {
  2550. stat_data_from_disk(&oid_stat->stat, data);
  2551. hashcpy(oid_stat->oid.hash, sha1);
  2552. oid_stat->valid = 1;
  2553. }
  2554. struct untracked_cache *read_untracked_extension(const void *data, unsigned long sz)
  2555. {
  2556. struct untracked_cache *uc;
  2557. struct read_data rd;
  2558. const unsigned char *next = data, *end = (const unsigned char *)data + sz;
  2559. const char *ident;
  2560. int ident_len;
  2561. ssize_t len;
  2562. const char *exclude_per_dir;
  2563. const unsigned hashsz = the_hash_algo->rawsz;
  2564. const unsigned offset = sizeof(struct ondisk_untracked_cache);
  2565. const unsigned exclude_per_dir_offset = offset + 2 * hashsz;
  2566. if (sz <= 1 || end[-1] != '\0')
  2567. return NULL;
  2568. end--;
  2569. ident_len = decode_varint(&next);
  2570. if (next + ident_len > end)
  2571. return NULL;
  2572. ident = (const char *)next;
  2573. next += ident_len;
  2574. if (next + exclude_per_dir_offset + 1 > end)
  2575. return NULL;
  2576. uc = xcalloc(1, sizeof(*uc));
  2577. strbuf_init(&uc->ident, ident_len);
  2578. strbuf_add(&uc->ident, ident, ident_len);
  2579. load_oid_stat(&uc->ss_info_exclude,
  2580. next + ouc_offset(info_exclude_stat),
  2581. next + offset);
  2582. load_oid_stat(&uc->ss_excludes_file,
  2583. next + ouc_offset(excludes_file_stat),
  2584. next + offset + hashsz);
  2585. uc->dir_flags = get_be32(next + ouc_offset(dir_flags));
  2586. exclude_per_dir = (const char *)next + exclude_per_dir_offset;
  2587. uc->exclude_per_dir = xstrdup(exclude_per_dir);
  2588. /* NUL after exclude_per_dir is covered by sizeof(*ouc) */
  2589. next += exclude_per_dir_offset + strlen(exclude_per_dir) + 1;
  2590. if (next >= end)
  2591. goto done2;
  2592. len = decode_varint(&next);
  2593. if (next > end || len == 0)
  2594. goto done2;
  2595. rd.valid = ewah_new();
  2596. rd.check_only = ewah_new();
  2597. rd.sha1_valid = ewah_new();
  2598. rd.data = next;
  2599. rd.end = end;
  2600. rd.index = 0;
  2601. ALLOC_ARRAY(rd.ucd, len);
  2602. if (read_one_dir(&uc->root, &rd) || rd.index != len)
  2603. goto done;
  2604. next = rd.data;
  2605. len = ewah_read_mmap(rd.valid, next, end - next);
  2606. if (len < 0)
  2607. goto done;
  2608. next += len;
  2609. len = ewah_read_mmap(rd.check_only, next, end - next);
  2610. if (len < 0)
  2611. goto done;
  2612. next += len;
  2613. len = ewah_read_mmap(rd.sha1_valid, next, end - next);
  2614. if (len < 0)
  2615. goto done;
  2616. ewah_each_bit(rd.check_only, set_check_only, &rd);
  2617. rd.data = next + len;
  2618. ewah_each_bit(rd.valid, read_stat, &rd);
  2619. ewah_each_bit(rd.sha1_valid, read_oid, &rd);
  2620. next = rd.data;
  2621. done:
  2622. free(rd.ucd);
  2623. ewah_free(rd.valid);
  2624. ewah_free(rd.check_only);
  2625. ewah_free(rd.sha1_valid);
  2626. done2:
  2627. if (next != end) {
  2628. free_untracked_cache(uc);
  2629. uc = NULL;
  2630. }
  2631. return uc;
  2632. }
  2633. static void invalidate_one_directory(struct untracked_cache *uc,
  2634. struct untracked_cache_dir *ucd)
  2635. {
  2636. uc->dir_invalidated++;
  2637. ucd->valid = 0;
  2638. ucd->untracked_nr = 0;
  2639. }
  2640. /*
  2641. * Normally when an entry is added or removed from a directory,
  2642. * invalidating that directory is enough. No need to touch its
  2643. * ancestors. When a directory is shown as "foo/bar/" in git-status
  2644. * however, deleting or adding an entry may have cascading effect.
  2645. *
  2646. * Say the "foo/bar/file" has become untracked, we need to tell the
  2647. * untracked_cache_dir of "foo" that "bar/" is not an untracked
  2648. * directory any more (because "bar" is managed by foo as an untracked
  2649. * "file").
  2650. *
  2651. * Similarly, if "foo/bar/file" moves from untracked to tracked and it
  2652. * was the last untracked entry in the entire "foo", we should show
  2653. * "foo/" instead. Which means we have to invalidate past "bar" up to
  2654. * "foo".
  2655. *
  2656. * This function traverses all directories from root to leaf. If there
  2657. * is a chance of one of the above cases happening, we invalidate back
  2658. * to root. Otherwise we just invalidate the leaf. There may be a more
  2659. * sophisticated way than checking for SHOW_OTHER_DIRECTORIES to
  2660. * detect these cases and avoid unnecessary invalidation, for example,
  2661. * checking for the untracked entry named "bar/" in "foo", but for now
  2662. * stick to something safe and simple.
  2663. */
  2664. static int invalidate_one_component(struct untracked_cache *uc,
  2665. struct untracked_cache_dir *dir,
  2666. const char *path, int len)
  2667. {
  2668. const char *rest = strchr(path, '/');
  2669. if (rest) {
  2670. int component_len = rest - path;
  2671. struct untracked_cache_dir *d =
  2672. lookup_untracked(uc, dir, path, component_len);
  2673. int ret =
  2674. invalidate_one_component(uc, d, rest + 1,
  2675. len - (component_len + 1));
  2676. if (ret)
  2677. invalidate_one_directory(uc, dir);
  2678. return ret;
  2679. }
  2680. invalidate_one_directory(uc, dir);
  2681. return uc->dir_flags & DIR_SHOW_OTHER_DIRECTORIES;
  2682. }
  2683. void untracked_cache_invalidate_path(struct index_state *istate,
  2684. const char *path, int safe_path)
  2685. {
  2686. if (!istate->untracked || !istate->untracked->root)
  2687. return;
  2688. if (!safe_path && !verify_path(path, 0))
  2689. return;
  2690. invalidate_one_component(istate->untracked, istate->untracked->root,
  2691. path, strlen(path));
  2692. }
  2693. void untracked_cache_remove_from_index(struct index_state *istate,
  2694. const char *path)
  2695. {
  2696. untracked_cache_invalidate_path(istate, path, 1);
  2697. }
  2698. void untracked_cache_add_to_index(struct index_state *istate,
  2699. const char *path)
  2700. {
  2701. untracked_cache_invalidate_path(istate, path, 1);
  2702. }
  2703. static void connect_wt_gitdir_in_nested(const char *sub_worktree,
  2704. const char *sub_gitdir)
  2705. {
  2706. int i;
  2707. struct repository subrepo;
  2708. struct strbuf sub_wt = STRBUF_INIT;
  2709. struct strbuf sub_gd = STRBUF_INIT;
  2710. const struct submodule *sub;
  2711. /* If the submodule has no working tree, we can ignore it. */
  2712. if (repo_init(&subrepo, sub_gitdir, sub_worktree))
  2713. return;
  2714. if (repo_read_index(&subrepo) < 0)
  2715. die(_("index file corrupt in repo %s"), subrepo.gitdir);
  2716. for (i = 0; i < subrepo.index->cache_nr; i++) {
  2717. const struct cache_entry *ce = subrepo.index->cache[i];
  2718. if (!S_ISGITLINK(ce->ce_mode))
  2719. continue;
  2720. while (i + 1 < subrepo.index->cache_nr &&
  2721. !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
  2722. /*
  2723. * Skip entries with the same name in different stages
  2724. * to make sure an entry is returned only once.
  2725. */
  2726. i++;
  2727. sub = submodule_from_path(&subrepo, &null_oid, ce->name);
  2728. if (!sub || !is_submodule_active(&subrepo, ce->name))
  2729. /* .gitmodules broken or inactive sub */
  2730. continue;
  2731. strbuf_reset(&sub_wt);
  2732. strbuf_reset(&sub_gd);
  2733. strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
  2734. strbuf_addf(&sub_gd, "%s/modules/%s", sub_gitdir, sub->name);
  2735. connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
  2736. }
  2737. strbuf_release(&sub_wt);
  2738. strbuf_release(&sub_gd);
  2739. repo_clear(&subrepo);
  2740. }
  2741. void connect_work_tree_and_git_dir(const char *work_tree_,
  2742. const char *git_dir_,
  2743. int recurse_into_nested)
  2744. {
  2745. struct strbuf gitfile_sb = STRBUF_INIT;
  2746. struct strbuf cfg_sb = STRBUF_INIT;
  2747. struct strbuf rel_path = STRBUF_INIT;
  2748. char *git_dir, *work_tree;
  2749. /* Prepare .git file */
  2750. strbuf_addf(&gitfile_sb, "%s/.git", work_tree_);
  2751. if (safe_create_leading_directories_const(gitfile_sb.buf))
  2752. die(_("could not create directories for %s"), gitfile_sb.buf);
  2753. /* Prepare config file */
  2754. strbuf_addf(&cfg_sb, "%s/config", git_dir_);
  2755. if (safe_create_leading_directories_const(cfg_sb.buf))
  2756. die(_("could not create directories for %s"), cfg_sb.buf);
  2757. git_dir = real_pathdup(git_dir_, 1);
  2758. work_tree = real_pathdup(work_tree_, 1);
  2759. /* Write .git file */
  2760. write_file(gitfile_sb.buf, "gitdir: %s",
  2761. relative_path(git_dir, work_tree, &rel_path));
  2762. /* Update core.worktree setting */
  2763. git_config_set_in_file(cfg_sb.buf, "core.worktree",
  2764. relative_path(work_tree, git_dir, &rel_path));
  2765. strbuf_release(&gitfile_sb);
  2766. strbuf_release(&cfg_sb);
  2767. strbuf_release(&rel_path);
  2768. if (recurse_into_nested)
  2769. connect_wt_gitdir_in_nested(work_tree, git_dir);
  2770. free(work_tree);
  2771. free(git_dir);
  2772. }
  2773. /*
  2774. * Migrate the git directory of the given path from old_git_dir to new_git_dir.
  2775. */
  2776. void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_git_dir)
  2777. {
  2778. if (rename(old_git_dir, new_git_dir) < 0)
  2779. die_errno(_("could not migrate git directory from '%s' to '%s'"),
  2780. old_git_dir, new_git_dir);
  2781. connect_work_tree_and_git_dir(path, new_git_dir, 0);
  2782. }