-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
335 lines (283 loc) Β· 13.6 KB
/
Copy pathutils.py
File metadata and controls
335 lines (283 loc) Β· 13.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
import os
import sys
import logging
from datetime import datetime
from pathlib import Path
DEBUG = True
# Force flush stdout and stderr to ensure print statements are visible
def force_flush():
"""Force flush stdout and stderr to ensure print statements are visible."""
try:
if sys.stdout is not None:
sys.stdout.flush()
except (AttributeError, OSError):
pass
try:
if sys.stderr is not None:
sys.stderr.flush()
except (AttributeError, OSError):
pass
# Module loaded confirmation (only in debug mode)
if DEBUG:
print("π [utils.py] Module loaded successfully", flush=True)
force_flush()
# ========= App Base Path =========
def ensure_dir(directory):
"""Create the given directory path if it does not exist."""
try:
Path(directory).expanduser().resolve().mkdir(parents=True, exist_ok=True)
except Exception as e:
logger.error(f"Failed to create directory: {directory}")
logger.exception(e)
# ========= Logging Setup =========
try:
from rich.logging import RichHandler
_rich_available = True
except ImportError:
_rich_available = False
logger = logging.getLogger("MycoApp")
if not logger.hasHandlers():
log_handlers = []
if _rich_available:
from rich.console import Console
log_handlers.append(RichHandler(console=Console(), show_path=False))
else:
log_handlers.append(logging.StreamHandler())
session_log = Path("logs") / f"mycoapp_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
ensure_dir(session_log.parent)
log_handlers.append(logging.FileHandler(session_log, encoding="utf-8"))
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s [%(levelname)s] %(message)s",
datefmt="[%Y-%m-%d %H:%M:%S]",
handlers=log_handlers
)
def climb_out_of_app_bundle(path, levels=3):
for _ in range(levels):
path = os.path.dirname(path)
return path
def app_root():
"""Return the base path for storing app data depending on runtime mode."""
# Enhanced frozen detection for Nuitka and PyInstaller
is_frozen = getattr(sys, 'frozen', False)
# Platform-specific build detection
if sys.platform == "darwin":
# macOS: Nuitka builds
is_nuitka = hasattr(sys, '_nuitka_build_dir') or 'nuitka' in sys.modules
is_pyinstaller = False # Not used on macOS
# Nuitka detection using their recommended __compiled__ attribute
is_nuitka_compiled = (
hasattr(sys, '__compiled__') or
hasattr(sys.modules.get('__main__', None), '__compiled__') or
any(hasattr(module, '__compiled__') for module in sys.modules.values() if module is not None)
)
# Additional Nuitka detection methods
is_nuitka_build = (
hasattr(sys, '_nuitka_build_dir') or
'nuitka' in sys.modules or
hasattr(sys, '_nuitka_onefile_mode') or
hasattr(sys, '_nuitka_standalone_mode') or
'Nuitka' in str(sys.modules.get('sys', '')) or
is_nuitka_compiled
)
# Check if we're running from a .app bundle (macOS)
is_app_bundle = (
'/Contents/MacOS/' in sys.executable or
'/Contents/MacOS/' in sys.argv[0] or
'.app' in sys.executable or
'.app' in sys.argv[0]
)
# Consider it frozen if any of these conditions are met
is_frozen = is_frozen or is_nuitka or is_nuitka_build or is_app_bundle
elif sys.platform == "win32":
# Windows: PyInstaller builds
is_nuitka = False # Not used on Windows
is_pyinstaller = hasattr(sys, '_MEIPASS')
# PyInstaller onedir detection
is_pyinstaller_onedir = (
is_frozen and
not hasattr(sys, '_MEIPASS') and # onedir doesn't have _MEIPASS
os.path.isdir(sys.executable) # onedir executable is actually a directory
)
# Additional PyInstaller detection
is_pyinstaller_build = is_pyinstaller or is_pyinstaller_onedir
# Check if we're running from a PyInstaller onedir
is_onedir_bundle = (
is_frozen and
os.path.isdir(sys.executable)
)
# Consider it frozen if any of these conditions are met
is_frozen = is_frozen or is_pyinstaller or is_pyinstaller_build or is_onedir_bundle
else:
# Other platforms
is_nuitka = hasattr(sys, '_nuitka_build_dir') or 'nuitka' in sys.modules
is_pyinstaller = hasattr(sys, '_MEIPASS')
is_nuitka_build = is_nuitka
is_app_bundle = False
is_onedir_bundle = False
# Only show essential debug info
if DEBUG:
print(f"π [app_root] Running in {'frozen' if is_frozen else 'development'} mode", flush=True)
if is_frozen:
if sys.platform == "darwin":
print(f"π [app_root] macOS: Nuitka build detected", flush=True)
elif sys.platform == "win32":
print(f"π [app_root] Windows: PyInstaller build detected", flush=True)
force_flush()
if DEBUG:
logger.debug("β
DEBUG: app_root() was called")
try:
if is_frozen:
exe_dir = os.path.dirname(sys.executable)
if sys.platform == "darwin":
if DEBUG:
print("π [app_root] macOS: Resolving shared directory path", flush=True)
# Try different path combinations for shared directory
# For MushTools-v1.3 structure: MushTools-v1.3/MushLog.app, MushView.app, Import_Tool.app, shared/
possible_shared_paths = [
# Look for MushTools-v1.3 structure (apps and shared at same level)
os.path.abspath(os.path.join(exe_dir, "..", "..", "..", "..", "shared")), # 4 levels up (MushTools-v1.3 level)
os.path.abspath(os.path.join(exe_dir, "..", "..", "..", "shared")), # 3 levels up (outside build dir)
os.path.abspath(os.path.join(exe_dir, "..", "..", "shared")), # 2 levels up (build dir level)
# Fallback to inside app bundle (for development/testing)
os.path.abspath(os.path.join(exe_dir, "..", "shared")), # 1 level up
os.path.abspath(os.path.join(exe_dir, "shared")), # Same level
]
# Find the first existing shared path
shared_path = None
for path in possible_shared_paths:
if os.path.exists(path):
shared_path = path
break
if shared_path:
if DEBUG:
print(f"π [app_root] Found shared directory: {shared_path}")
# Check what's in the data directory
data_dir = os.path.join(shared_path, "data")
if os.path.exists(data_dir):
if DEBUG:
print(f"π [app_root] Data directory: {data_dir}")
else:
print(f"β οΈ [app_root] Data directory NOT found: {data_dir}")
result = shared_path
else:
if DEBUG:
print("π [app_root] No shared directory found, using executable directory")
result = exe_dir
elif sys.platform == "win32":
if DEBUG:
print("πͺ [app_root] Windows: Resolving shared directory path", flush=True)
# Try different path combinations for shared directory
# For MushTools-v1.3 structure: MushTools-v1.3/MushLog.app, MushView.app, Import_Tool.app, shared/
possible_shared_paths = [
# Look for MushTools-v1.3 structure (apps and shared at same level)
os.path.abspath(os.path.join(exe_dir, "..", "..", "..", "..", "shared")), # 4 levels up (MushTools-v1.3 level)
os.path.abspath(os.path.join(exe_dir, "..", "..", "..", "shared")), # 3 levels up (outside build dir)
os.path.abspath(os.path.join(exe_dir, "..", "..", "shared")), # 2 levels up (build dir level)
# Fallback to inside app bundle (for development/testing)
os.path.abspath(os.path.join(exe_dir, "..", "shared")), # 1 level up
os.path.abspath(os.path.join(exe_dir, "shared")), # Same level
]
# Find the first existing shared path
shared_path = None
for path in possible_shared_paths:
if os.path.exists(path):
shared_path = path
break
if shared_path:
if DEBUG:
print(f"πͺ [app_root] Found shared directory: {shared_path}")
result = shared_path
else:
if DEBUG:
print("πͺ [app_root] No shared directory found, using executable directory")
result = exe_dir
else:
# Other platforms (Linux, etc.)
print(f"π [app_root] Platform detected: {sys.platform}")
result = exe_dir
else:
# Development mode - minimal output
if DEBUG:
logger.debug("app_root() called in development mode")
script_dir = os.path.dirname(os.path.abspath(__file__))
shared_path = os.path.abspath(os.path.join(script_dir, "..", "shared"))
result = shared_path if os.path.exists(shared_path) else script_dir
if DEBUG:
logger.debug(f"app_root() resolved to: {result}")
return result
except Exception as e:
if is_frozen:
print(f"β [app_root] Exception: {e}")
logger.error(f"app_root() error: {e}")
return os.getcwd()
# ========= Resource Locator =========
def resource_path(relative_path):
"""
Get absolute path to a resource, handling dev, onedir, onefile, and shared folders.
"""
# Enhanced frozen detection for Nuitka and PyInstaller
is_frozen = getattr(sys, 'frozen', False)
is_nuitka = hasattr(sys, '_nuitka_build_dir') or 'nuitka' in sys.modules
is_pyinstaller = hasattr(sys, '_MEIPASS')
# Consider it frozen if any of these conditions are met
is_frozen = is_frozen or is_nuitka or is_pyinstaller
if is_frozen:
print(f"π [resource_path] Looking for: {relative_path}")
possible_paths = []
# PyInstaller or Nuitka onefile mode
if hasattr(sys, '_MEIPASS'):
meipass_path = os.path.join(sys._MEIPASS, relative_path)
possible_paths.append(meipass_path)
if is_frozen:
print(f"π [resource_path] _MEIPASS path: {meipass_path}")
# Frozen onedir mode (PyInstaller/Nuitka)
if is_frozen:
base_path = os.path.dirname(os.path.abspath(sys.argv[0]))
frozen_path = os.path.join(base_path, relative_path)
possible_paths.append(frozen_path)
print(f"π [resource_path] Frozen base path: {base_path}")
print(f"π [resource_path] Frozen path: {frozen_path}")
# Script directory (source mode)
script_dir = os.path.dirname(os.path.abspath(__file__))
if is_frozen:
print(f"π [resource_path] Script directory: {script_dir}")
# Internal resources directory (prioritize bundled resources)
resources_dir = os.path.join(script_dir, "resources")
resources_path = os.path.join(resources_dir, relative_path)
possible_paths.append(resources_path)
if is_frozen:
print(f"π [resource_path] Resources path: {resources_path}")
# Parent's resources (used when launched from outside)
parent_resources = os.path.join(os.path.dirname(script_dir), "resources")
parent_resources_path = os.path.join(parent_resources, relative_path)
possible_paths.append(parent_resources_path)
if is_frozen:
print(f"π [resource_path] Parent resources path: {parent_resources_path}")
# Fallback to current directory
current_path = os.path.join(script_dir, relative_path)
possible_paths.append(current_path)
if is_frozen:
print(f"π [resource_path] Current directory path: {current_path}")
# Shared folder support (multi-app use case) - check last to avoid overriding bundled resources
shared_path = os.path.join(script_dir, "..", "shared", relative_path)
possible_paths.append(shared_path)
if is_frozen:
print(f"π [resource_path] Shared path: {shared_path}")
if is_frozen:
print("π [resource_path] Checking possible paths:")
for i, path in enumerate(possible_paths, 1):
exists = os.path.exists(path)
print(f" {i}. {path} - {'β
EXISTS' if exists else 'β NOT FOUND'}")
if exists:
return os.path.abspath(path)
else:
# Development mode - just check and return first existing path
for path in possible_paths:
if os.path.exists(path):
return os.path.abspath(path)
# Debug fallback if nothing found
fallback = os.path.abspath(possible_paths[0]) if possible_paths else relative_path
if is_frozen:
print(f"π [resource_path] No path found, using fallback: {fallback}")
return fallback