6
@File : dependency_file.py
7
@Desc: Implementation of the dependency file described in Section 2.2.3.2 of RFC 135.
9
from __future__ import annotations
13
from pathlib import Path
16
from metagpt.utils.common import aread, awrite
17
from metagpt.utils.exceptions import handle_exception
21
"""A class representing a DependencyFile for managing dependencies.
23
:param workdir: The working directory path for the DependencyFile.
26
def __init__(self, workdir: Path | str):
27
"""Initialize a DependencyFile instance.
29
:param workdir: The working directory path for the DependencyFile.
31
self._dependencies = {}
32
self._filename = Path(workdir) / ".dependencies.json"
35
"""Load dependencies from the file asynchronously."""
36
if not self._filename.exists():
38
json_data = await aread(self._filename)
39
json_data = re.sub(r"\\+", "/", json_data)
40
self._dependencies = json.loads(json_data)
44
"""Save dependencies to the file asynchronously."""
45
data = json.dumps(self._dependencies)
46
await awrite(filename=self._filename, data=data)
48
async def update(self, filename: Path | str, dependencies: Set[Path | str], persist=True):
49
"""Update dependencies for a file asynchronously.
51
:param filename: The filename or path.
52
:param dependencies: The set of dependencies.
53
:param persist: Whether to persist the changes immediately.
58
root = self._filename.parent
60
key = Path(filename).relative_to(root).as_posix()
66
for i in dependencies:
68
s = str(Path(i).relative_to(root).as_posix())
71
relative_paths.append(s)
73
self._dependencies[key] = relative_paths
74
elif key in self._dependencies:
75
del self._dependencies[key]
80
async def get(self, filename: Path | str, persist=True):
81
"""Get dependencies for a file asynchronously.
83
:param filename: The filename or path.
84
:param persist: Whether to load dependencies from the file immediately.
85
:return: A set of dependencies.
90
root = self._filename.parent
92
key = Path(filename).relative_to(root).as_posix()
95
return set(self._dependencies.get(str(key), {}))
97
def delete_file(self):
98
"""Delete the dependency file."""
99
self._filename.unlink(missing_ok=True)
103
"""Check if the dependency file exists."""
104
return self._filename.exists()