|
4 | 4 | import os |
5 | 5 | import re |
6 | 6 | import shutil |
7 | | -import uuid |
8 | 7 | import tempfile |
| 8 | +import uuid |
| 9 | +import weakref |
9 | 10 | from datetime import datetime |
10 | 11 | from dateutil.tz import tzlocal |
11 | 12 |
|
@@ -41,7 +42,30 @@ class MerginProject: |
41 | 42 | Linked to existing local directory, with project metadata (mergin.json) and backups located in .mergin directory. |
42 | 43 | """ |
43 | 44 |
|
| 45 | + # To make sure we don't have multiple instances for a single project that |
| 46 | + # then have out-of-date information, we keep this map of absolute project |
| 47 | + # directory paths to instances. |
| 48 | + # The dictionary is a WeakValueDictionary so we don't cause memory leaks |
| 49 | + # (when the instance is GC'd, the entry is deleted). |
| 50 | + project_cache: weakref.WeakValueDictionary[str, "MerginProject"] = weakref.WeakValueDictionary() |
| 51 | + |
| 52 | + def __new__(cls, directory): |
| 53 | + directory = os.path.abspath(directory) |
| 54 | + if instance := cls.project_cache.get(directory): |
| 55 | + return instance |
| 56 | + |
| 57 | + instance = super().__new__(cls) |
| 58 | + cls.project_cache[directory] = instance |
| 59 | + return instance |
| 60 | + |
44 | 61 | def __init__(self, directory): |
| 62 | + # __init__ still gets called after __new__, even if it returns a |
| 63 | + # pre-existing object. Work around this by checking whether we've been |
| 64 | + # initialised. |
| 65 | + if hasattr(self, "_initialised"): |
| 66 | + return |
| 67 | + self._initialised = True |
| 68 | + |
45 | 69 | self.dir = os.path.abspath(directory) |
46 | 70 | if not os.path.exists(self.dir): |
47 | 71 | raise InvalidProject("Project directory does not exist") |
|
0 commit comments