Debian Codegraph @

thirdparty/folly/build/fbcode_builder/getdeps/copytree.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 #
3 # This source code is licensed under the MIT license found in the
4 # LICENSE file in the root directory of this source tree.
5
6 import os
7 import shutil
8 import subprocess
9
10 from .platform import is_windows
11
12
13 PREFETCHED_DIRS = set()
14
15
16 def containing_repo_type(path):
17 while True:
18 if os.path.exists(os.path.join(path, ".git")):
19 return ("git", path)
20 if os.path.exists(os.path.join(path, ".hg")):
21 return ("hg", path)
22
23 parent = os.path.dirname(path)
24 if parent == path:
25 return None, None
26 path = parent
27
28
29 def find_eden_root(dirpath):
30 """If the specified directory is inside an EdenFS checkout, returns
31 the canonical absolute path to the root of that checkout.
32
33 Returns None if the specified directory is not in an EdenFS checkout.
34 """
35 if is_windows():
36 repo_type, repo_root = containing_repo_type(dirpath)
37 if repo_root is not None:
38 if os.path.exists(os.path.join(repo_root, ".eden", "config")):
39 return repo_root
40 return None
41
42 try:
43 return os.readlink(os.path.join(dirpath, ".eden", "root"))
44 except OSError:
45 return None
46
47
48 def prefetch_dir_if_eden(dirpath) -> None:
49 """After an amend/rebase, Eden may need to fetch a large number
50 of trees from the servers. The simplistic single threaded walk
51 performed by copytree makes this more expensive than is desirable
52 so we help accelerate things by performing a prefetch on the
53 source directory"""
54 global PREFETCHED_DIRS
55 if dirpath in PREFETCHED_DIRS:
56 return
57 root = find_eden_root(dirpath)
58 if root is None:
59 return
60 glob = f"{os.path.relpath(dirpath, root).replace(os.sep, '/')}/**"
61 print(f"Prefetching {glob}")
62 subprocess.call(["edenfsctl", "prefetch", "--repo", root, glob, "--background"])
63 PREFETCHED_DIRS.add(dirpath)
64
65
66 # pyre-fixme[9]: ignore has type `bool`; used as `None`.
67 def copytree(src_dir, dest_dir, ignore: bool = None):
68 """Recursively copy the src_dir to the dest_dir, filtering
69 out entries using the ignore lambda. The behavior of the
70 ignore lambda must match that described by `shutil.copytree`.
71 This `copytree` function knows how to prefetch data when
72 running in an eden repo.
73 TODO: I'd like to either extend this or add a variant that
74 uses watchman to mirror src_dir into dest_dir.
75 """
76 prefetch_dir_if_eden(src_dir)
77 # pyre-fixme[6]: For 3rd param expected
78 # `Union[typing.Callable[[Union[PathLike[str], str], List[str]], Iterable[str]],
79 # typing.Callable[[str, List[str]], Iterable[str]], None]` but got `bool`.
80 return shutil.copytree(src_dir, dest_dir, ignore=ignore)