Skip to content

Commit 9d64ee4

Browse files
committed
Improve the log output, better path handling for Windows
1 parent b55d4b8 commit 9d64ee4

File tree

3 files changed

+52
-22
lines changed

3 files changed

+52
-22
lines changed

mlc/index.py

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,16 @@ def __init__(self, repos_path, repos):
4141
self._load_existing_index()
4242
self.build_index()
4343

44+
def _get_stored_mtime(self, key):
45+
"""
46+
Helper method to safely extract mtime from stored data.
47+
Handles both old format (direct mtime) and new format (dict with mtime key).
48+
"""
49+
old = self.modified_times.get(key)
50+
if old is None:
51+
return None
52+
return old["mtime"] if isinstance(old, dict) else old
53+
4454
def _load_modified_times(self):
4555
"""
4656
Load stored mtimes to check for changes in scripts.
@@ -50,7 +60,8 @@ def _load_modified_times(self):
5060
# logger.info(f"Loading modified times from {self.modified_times_file}")
5161
with open(self.modified_times_file, "r") as f:
5262
return json.load(f)
53-
except Exception:
63+
except (json.JSONDecodeError, IOError) as e:
64+
logger.warning(f"Failed to load modified times: {e}")
5465
return {}
5566
return {}
5667

@@ -77,7 +88,8 @@ def _load_existing_index(self):
7788
if isinstance(item.get("repo"), dict):
7889
item["repo"] = Repo(**item["repo"])
7990

80-
except Exception:
91+
except (json.JSONDecodeError, IOError, KeyError, TypeError) as e:
92+
logger.warning(f"Failed to load index for {folder_type}: {e}")
8193
pass # fall back to empty index
8294

8395
def add(self, meta, folder_type, path, repo):
@@ -175,8 +187,7 @@ def build_index(self):
175187
repos_mtime = os.path.getmtime(repos_json_path)
176188

177189
key = f"{repos_json_path}"
178-
old = self.modified_times.get(key)
179-
repo_old_mtime = old["mtime"] if isinstance(old, dict) else old
190+
repo_old_mtime = self._get_stored_mtime(key)
180191

181192
#logger.debug(f"Current repos.json mtime: {repos_mtime}")
182193
#logger.debug(f"Old repos.json mtime: {repo_old_mtime}")
@@ -232,9 +243,17 @@ def build_index(self):
232243
else:
233244
#logger.debug(f"No config file found in {automation_path}, skipping")
234245
delete_flag = False
235-
if automation_dir in self.modified_times:
236-
del self.modified_times[automation_dir]
237-
if any(automation_dir in item["path"] for item in self.indices[folder_type]):
246+
if config_path := os.path.join(automation_path, "meta.yaml"):
247+
if config_path in self.modified_times:
248+
del self.modified_times[config_path]
249+
delete_flag = True
250+
if config_path := os.path.join(automation_path, "meta.json"):
251+
if config_path in self.modified_times:
252+
del self.modified_times[config_path]
253+
delete_flag = True
254+
255+
# Use exact path matching instead of substring
256+
if any(item["path"] == automation_path for item in self.indices[folder_type]):
238257
logger.debug(f"Removed index entry (if it exists) for {folder_type} : {automation_dir}")
239258
delete_flag = True
240259
self._remove_index_entry(automation_path)
@@ -244,11 +263,10 @@ def build_index(self):
244263
current_item_keys.add(config_path)
245264
mtime = self.get_item_mtime(config_path)
246265

247-
old = self.modified_times.get(config_path)
248-
old_mtime = old["mtime"] if isinstance(old, dict) else old
266+
old_mtime = self._get_stored_mtime(config_path)
249267

250268
# skip if unchanged
251-
if old_mtime == mtime and repos_changed != 1:
269+
if old_mtime == mtime and not repos_changed:
252270
# logger.debug(f"No changes detected for {config_path}, skipping reindexing.")
253271
continue
254272
#if(old_mtime is None):
@@ -291,10 +309,12 @@ def build_index(self):
291309

292310
def _remove_index_entry(self, key):
293311
logger.debug(f"Removing index entry for {key}")
312+
# Normalize paths for comparison
313+
normalized_key = os.path.normpath(key)
294314
for ft in self.indices:
295315
self.indices[ft] = [
296316
item for item in self.indices[ft]
297-
if key not in item["path"]
317+
if os.path.normpath(item["path"]) != normalized_key
298318
]
299319

300320
def _delete_by_uid(self, folder_type, uid, alias):

mlc/logger.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ class ColoredFormatter(logging.Formatter):
1515
}
1616

1717
def format(self, record):
18+
# Pad filename and line number for alignment
19+
record.filename = f"{record.filename:<15}" # Left-align filename with 25 char width
20+
record.lineno = f"{record.lineno:>4}" # Right-align line number with 4 char width
21+
1822
# Add color to the levelname
1923
if record.levelname in self.COLORS:
2024
record.levelname = f"{self.COLORS[record.levelname]}{record.levelname}{Style.RESET_ALL}"

mlc/utils.py

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -694,24 +694,30 @@ def extract_file(options):
694694
with zipfile.ZipFile(filename, 'r') as archive:
695695
members = archive.namelist()
696696
for member in members:
697-
# Strip folder levels
698-
stripped_path = os.path.join(
699-
extract_to, *member.split(os.sep)[strip_folders:]
700-
)
701-
if member.endswith('/'): # Directory
702-
os.makedirs(stripped_path, exist_ok=True)
703-
else: # File
704-
os.makedirs(os.path.dirname(stripped_path), exist_ok=True)
705-
with archive.open(member) as source, open(stripped_path, 'wb') as target:
706-
shutil.copyfileobj(source, target)
697+
# Strip folder levels (zip files always use forward slashes internally)
698+
parts = member.split('/')
699+
if len(parts) > strip_folders:
700+
stripped_parts = parts[strip_folders:]
701+
stripped_path = os.path.join(extract_to, *stripped_parts)
702+
stripped_path = os.path.normpath(stripped_path)
703+
704+
if member.endswith('/'): # Directory
705+
os.makedirs(stripped_path, exist_ok=True)
706+
else: # File
707+
os.makedirs(os.path.dirname(stripped_path), exist_ok=True)
708+
with archive.open(member) as source, open(stripped_path, 'wb') as target:
709+
shutil.copyfileobj(source, target)
707710

708711
elif tarfile.is_tarfile(filename):
709712
with tarfile.open(filename, 'r') as archive:
710713
members = archive.getmembers()
711714
for member in members:
712715
if strip_folders:
716+
# Tar files also use forward slashes internally
713717
parts = member.name.split('/')
714-
member.name = '/'.join(parts[strip_folders:])
718+
if len(parts) > strip_folders:
719+
# Join with OS-specific separator for extraction
720+
member.name = os.path.join(*parts[strip_folders:])
715721
archive.extract(member, path=extract_to)
716722

717723
else:

0 commit comments

Comments
 (0)