Skip to content

Commit 6234bc1

Browse files
committed
fix implementation as per spec
1 parent 768a5db commit 6234bc1

File tree

1 file changed

+29
-23
lines changed

1 file changed

+29
-23
lines changed

src/iterative_telemetry/__init__.py

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import sys
99
import uuid
1010
from functools import lru_cache
11+
from pathlib import Path
1112
from threading import Thread
1213
from typing import Any, Callable, Dict, Union
1314

@@ -187,39 +188,44 @@ def _system_info():
187188
raise NotImplementedError
188189

189190

191+
def generate_id():
192+
"""TODO: check environ for CI-based ID"""
193+
return str(uuid.uuid4())
194+
195+
190196
@lru_cache(None)
191197
def _find_or_create_user_id():
192198
"""
193199
The user's ID is stored on a file under the global config directory.
194-
The file should contain a JSON with a "user_id" key:
195-
{"user_id": "16fd2706-8baf-433b-82eb-8c7fada847da"}
196-
IDs are generated randomly with UUID.
200+
The file should contain a single string:
201+
16fd2706-8baf-433b-82eb-8c7fada847da
202+
IDs are generated randomly with UUID4.
197203
"""
204+
# DVC backwards-compatibility
205+
old = Path(user_config_dir(os.path.join("dvc", "user_id"), "iterative"))
206+
# cross-product path
207+
new = Path(user_config_dir(os.path.join("iterative", "telemetry"), False))
208+
new.parent.mkdir(mode=0o755, parents=True, exist_ok=True)
209+
lockfile = str(new.with_suffix(".lock"))
198210

199-
config_dir = user_config_dir(os.path.join("iterative", "telemetry"), False)
200-
fname = os.path.join(config_dir, "user_id")
201-
lockfile = os.path.join(config_dir, "user_id.lock")
202-
203-
# Since the `fname` and `lockfile` are under the global config,
204-
# we need to make sure such directory exist already.
205-
os.makedirs(config_dir, exist_ok=True)
211+
uid = generate_id()
206212

207213
try:
208214
with FileLock( # pylint: disable=abstract-class-instantiated
209215
lockfile, timeout=5
210216
):
211-
try:
212-
with open(fname, encoding="utf8") as fobj:
213-
user_id = json.load(fobj)["user_id"]
214-
215-
except (FileNotFoundError, ValueError, KeyError):
216-
user_id = str(uuid.uuid4())
217-
218-
with open(fname, "w", encoding="utf8") as fobj:
219-
json.dump({"user_id": user_id}, fobj)
220-
221-
return user_id
222-
217+
if new.exists():
218+
uid = new.read_text().strip()
219+
else:
220+
if old.exists():
221+
uid = json.load(old.open())["user_id"]
222+
new.write_text(uid)
223+
224+
# only for non-DVC packages,
225+
# write legacy file in case legacy DVC is installed later
226+
if not old.exists() and uid.lower() != "do-not-track":
227+
old.write_text(f'{{"user_id": "{uid}"}}')
228+
229+
return uid
223230
except Timeout:
224231
logger.debug("Failed to acquire %s", lockfile)
225-
return None

0 commit comments

Comments
 (0)