Coverage for planit/eos/get_eos_data.py: 34%
50 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-11 15:42 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-11 15:42 +0000
1import os
2import pathlib
3import shutil
4import urllib.request
5import zipfile
6import platformdirs
8# Changing requires a new GitHub/PyPI release!
9DATA_VERSION = "v1.3.0"
11CACHE_DIR = platformdirs.user_cache_path("planit")
12#CACHE_DIR = pathlib.Path.home() / ".planit"
13VERSION_FILE = CACHE_DIR / "data_version.txt"
15# Map directory keys to their remote zip file names
16# Need to add new EoS here!
17REMOTE_DIRECTORIES = {
18 "aneos-pyrolite-2022": "aneos-pyrolite-2022.zip",
19 "aqua-water": "aqua-water.zip",
20 "5-phase-water": "5-phase-water.zip",
21 "aneos-Fe85Si15-2020-master": "aneos-Fe85Si15-2020-master.zip",
22 "SCVH": "SCVH.zip",
23 "aneos-water": "aneos-water.zip",
24 }
25# Map to internal source for testing/install from source
26# Need to add new EoS here!
27REPO_SOURCE_DATA = {
28 "aneos-pyrolite-2022": pathlib.Path(__file__).parent.parent / "eos/data/aneos-pyrolite-2022",
29 "aqua-water": pathlib.Path(__file__).parent.parent / "eos/data/aqua-water",
30 "5-phase-water": pathlib.Path(__file__).parent.parent / "eos/data/5-phase-water",
31 "aneos-Fe85Si15-2020-master": pathlib.Path(__file__).parent.parent / "eos/data/aneos-Fe85Si15-2020-master",
32 "SCVH": pathlib.Path(__file__).parent.parent / "eos/data/SCVH",
33 "aneos-water": pathlib.Path(__file__).parent.parent / "eos/data/aneos-water",
34 }
37def check_local_version_valid() -> bool:
38 """Checks if the downloaded data match the required version."""
39 if not VERSION_FILE.exists():
40 return False
41 try:
42 return VERSION_FILE.read_text().strip() == DATA_VERSION
43 except Exception:
44 return False
47def get_eosdata_path(dir_key: str, use_repo_source=True, debug=False) -> pathlib.Path:
48 """
49 Returns the path to a local directory.
50 Downloads and extracts the entire directory structure if missing or outdated.
51 """
52 if (dir_key not in REMOTE_DIRECTORIES) and (dir_key not in REPO_SOURCE_DATA):
53 raise ValueError(f"Unknown EoS key: '{dir_key}'")
55 source_repo_path = REPO_SOURCE_DATA.get(dir_key)
56 if source_repo_path and source_repo_path.exists() and use_repo_source:
57 return str(source_repo_path)+'/'
59 zip_filename = REMOTE_DIRECTORIES[dir_key]
60 folder_name = zip_filename.replace(".zip", "") # The extracted folder name
61 local_dir_path = CACHE_DIR / folder_name
63 # Check versioning status
64 is_version_valid = check_local_version_valid()
66 # Trigger update: Clear out the old directory if it's outdated
67 if not is_version_valid and local_dir_path.exists():
68 print(f"🔄 Outdated data found. Removing old version of {folder_name}...")
69 shutil.rmtree(local_dir_path, ignore_errors=True)
71 # Standard Lazy Load Check: If it exists and matches version, return it
72 if is_version_valid and local_dir_path.exists():
73 return str(local_dir_path)+'/'
75 # Construct the download URL
76 url = f"https://github.com/PhilJCarter/planit/releases/download/{DATA_VERSION}/{zip_filename}"
77 temp_zip_path = CACHE_DIR / f"temp_{zip_filename}"
79 print(f"📥 Fetching EoS files: '{dir_key}' ({DATA_VERSION})...")
80 CACHE_DIR.mkdir(parents=True, exist_ok=True)
82 try:
83 # Step 1: Download the single zip file
84 req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
85 with urllib.request.urlopen(req) as response, open(temp_zip_path, 'wb') as out_file:
86 out_file.write(response.read())
88 # Step 2: Unzip the entire directory structure automatically
89 if debug:
90 print(f"📦 Extracting files into {local_dir_path}...")
91 with zipfile.ZipFile(temp_zip_path, 'r') as zip_ref:
92 zip_ref.extractall(CACHE_DIR) # Extracts the folder directly into your cache
94 # Step 3: Write the version token file and clean up the zip archive
95 VERSION_FILE.write_text(DATA_VERSION)
96 temp_zip_path.unlink() # Delete the temporary zip archive to preserve disk space
98 if debug:
99 print(f"✅ Directory {folder_name} successfully set up!")
100 return str(local_dir_path)+'/'
102 except Exception as e:
103 # Clean up corrupted states on failure
104 if temp_zip_path.exists():
105 temp_zip_path.unlink()
107 raise RuntimeError(f"Failed to fetch directory bundle '{dir_key}' from GitHub: {e}")