Skip to content

Commit a86ca2d

Browse files
committed
overhaul logic
- drop writing to legacy location, vis.: #32 (comment) - lint & update names
1 parent 79529a7 commit a86ca2d

File tree

1 file changed

+30
-20
lines changed

1 file changed

+30
-20
lines changed

src/iterative_telemetry/__init__.py

Lines changed: 30 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -200,32 +200,42 @@ def _find_or_create_user_id():
200200
{"user_id": "16fd2706-8baf-433b-82eb-8c7fada847da"}
201201
IDs are generated randomly with UUID4.
202202
"""
203+
config_file = Path(
204+
user_config_dir(os.path.join("iterative", "telemetry"), False)
205+
)
206+
config_file.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
207+
lockfile = str(config_file.with_suffix(".lock"))
203208
# DVC backwards-compatibility
204-
old = Path(user_config_dir(str(Path("dvc") / "user_id"), "iterative"))
205-
# cross-product path
206-
new = Path(user_config_dir(str(Path("iterative") / "telemetry"), False))
207-
new.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
208-
lockfile = str(new.with_suffix(".lock"))
209+
config_file_old = Path(
210+
user_config_dir(os.path.join("dvc", "user_id"), "iterative")
211+
)
212+
lockfile_old = str(config_file_old.with_suffix(".lock"))
209213

210214
try:
211215
with FileLock( # pylint: disable=abstract-class-instantiated
212216
lockfile, timeout=5
213217
):
214-
uid = generate_id()
215-
if new.exists():
216-
uid = json.load(new.open(encoding="utf8"))["user_id"]
217-
else:
218-
if old.exists():
219-
uid = json.load(old.open(encoding="utf8"))["user_id"]
220-
json.dump({"user_id": uid}, new.open("w", encoding="utf8"))
221-
222-
# only for non-DVC packages,
223-
# write legacy file in case legacy DVC is installed later
224-
if not old.exists() and uid.lower() != DO_NOT_TRACK_VALUE.lower():
225-
json.dump({"user_id": uid}, old.open("w", encoding="utf8"))
226-
227-
if uid.lower() != DO_NOT_TRACK_VALUE.lower():
228-
return uid
218+
user_id = read_user_id(config_file)
219+
if user_id is None:
220+
if config_file_old.parent.is_dir():
221+
with FileLock(lockfile_old, timeout=5):
222+
user_id = read_user_id(config_file_old)
223+
if user_id is None:
224+
user_id = generate_id()
225+
with config_file.open(mode="w", encoding="utf8") as fd:
226+
json.dump({"user_id": user_id}, fd)
227+
228+
if user_id.lower() != DO_NOT_TRACK_VALUE.lower():
229+
return user_id
229230
except Timeout:
230231
logger.debug("Failed to acquire %s", lockfile)
231232
return None
233+
234+
235+
def read_user_id(config_file: Path):
236+
try:
237+
with config_file.open(encoding="utf8") as fd:
238+
return json.load(fd)["user_id"]
239+
except (FileNotFoundError, ValueError, KeyError):
240+
pass
241+
return None

0 commit comments

Comments
 (0)