Skip to content

Commit dd1f4c0

Browse files
authored
Merge pull request #28 from Sid9993/dev
Implemented Color-Coding for Errors and Warnings, fixes #24
2 parents aa19b53 + 0ce2948 commit dd1f4c0

File tree

2 files changed

+50
-14
lines changed

2 files changed

+50
-14
lines changed

mlc/main.py

Lines changed: 48 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,44 @@
1111
from types import SimpleNamespace
1212
import mlc.utils as utils
1313
from pathlib import Path
14+
from colorama import Fore, Style, init
1415
import shutil
16+
# Initialize colorama for Windows support
17+
init(autoreset=True)
18+
class ColoredFormatter(logging.Formatter):
19+
"""Custom formatter class to add colors to log levels"""
20+
COLORS = {
21+
'INFO': Fore.GREEN,
22+
'WARNING': Fore.YELLOW,
23+
'ERROR': Fore.RED
24+
}
25+
26+
def format(self, record):
27+
# Add color to the levelname
28+
if record.levelname in self.COLORS:
29+
record.levelname = f"{self.COLORS[record.levelname]}{record.levelname}{Style.RESET_ALL}"
30+
return super().format(record)
31+
1532

1633
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
34+
1735
logger = logging.getLogger(__name__)
36+
logger.setLevel(logging.INFO)
37+
38+
# Create console handler with the custom formatter
39+
console_handler = logging.StreamHandler()
40+
console_handler.setFormatter(ColoredFormatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
41+
42+
# Remove any existing handlers and add our custom handler
43+
if logger.hasHandlers():
44+
logger.handlers.clear()
45+
46+
logger.addHandler(console_handler)
47+
48+
# # Set up logging configuration
49+
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
50+
# logger = logging.getLogger(__name__)
51+
1852

1953
# Set up logging configuration
2054
def setup_logging(log_path = 'mlc',log_file = 'mlc-log.txt'):
@@ -115,13 +149,13 @@ def load_repos_and_meta(self):
115149
with open(repos_file_path, 'r') as file:
116150
repo_paths = json.load(file) # Load the JSON file into a list
117151
except json.JSONDecodeError as e:
118-
logger.info(f"Error decoding JSON: {e}")
152+
logger.error(f"Error decoding JSON: {e}")
119153
return []
120154
except FileNotFoundError:
121-
logger.info(f"Error: File {repos_file_path} not found.")
155+
logger.error(f"Error: File {repos_file_path} not found.")
122156
return []
123157
except Exception as e:
124-
logger.info(f"Error reading file: {e}")
158+
logger.error(f"Error reading file: {e}")
125159
return []
126160

127161
def is_curdir_inside_path(base_path):
@@ -146,15 +180,15 @@ def is_curdir_inside_path(base_path):
146180

147181
# Check if meta.yaml exists
148182
if not os.path.isfile(meta_yaml_path):
149-
logger.info(f"Warning: {meta_yaml_path} not found. Skipping...")
183+
logger.warning(f"Warning: {meta_yaml_path} not found. Skipping...")
150184
continue
151185

152186
# Load the YAML file
153187
try:
154188
with open(meta_yaml_path, 'r') as yaml_file:
155189
meta = yaml.safe_load(yaml_file)
156190
except yaml.YAMLError as e:
157-
logger.info(f"Error loading YAML in {meta_yaml_path}: {e}")
191+
logger.error(f"Error loading YAML in {meta_yaml_path}: {e}")
158192
continue
159193

160194
if meta['alias'] == "local":
@@ -172,7 +206,7 @@ def load_repos(self):
172206

173207
# Check if the file exists
174208
if not os.path.exists(repos_file_path):
175-
logger.info(f"Error: File not found at {repos_file_path}")
209+
logger.error(f"Error: File not found at {repos_file_path}")
176210
return None
177211

178212
# Load and parse the JSON file
@@ -181,10 +215,10 @@ def load_repos(self):
181215
repos = json.load(file)
182216
return repos
183217
except json.JSONDecodeError as e:
184-
logger.info(f"Error decoding JSON: {e}")
218+
logger.error(f"Error decoding JSON: {e}")
185219
return None
186220
except Exception as e:
187-
logger.info(f"Error reading file: {e}")
221+
logger.error(f"Error reading file: {e}")
188222
return None
189223

190224
def conflicting_repo(self, repo_meta):
@@ -729,7 +763,7 @@ def _process_config_file(self, config_file, folder_type, folder_path, repo):
729763
else:
730764
logger.info(f"Skipping {config_file}: Missing 'uid' field.")
731765
except Exception as e:
732-
logger.info(f"Error processing {config_file}: {e}")
766+
logger.error(f"Error processing {config_file}: {e}")
733767

734768

735769
def _save_indices(self):
@@ -747,7 +781,7 @@ def _save_indices(self):
747781
json.dump(index_data, f, indent=4, cls=CustomJSONEncoder)
748782
logger.info(f"Shared index for {folder_type} saved to {output_file}.")
749783
except Exception as e:
750-
logger.info(f"Error saving shared index for {folder_type}: {e}")
784+
logger.error(f"Error saving shared index for {folder_type}: {e}")
751785

752786
class CustomJSONEncoder(json.JSONEncoder):
753787
def default(self, obj):
@@ -985,6 +1019,7 @@ def pull(self, run_args):
9851019
return res
9861020

9871021
return {'return': 0}
1022+
9881023

9891024
def list(self, run_args):
9901025
logger.info("Listing all repositories.")
@@ -1140,7 +1175,7 @@ def load(self, args):
11401175
config_file = args.get('config_file', default_config_path)
11411176
logger.info(f"In cfg load, config file = {config_file}")
11421177
if not config_file or not os.path.exists(config_file):
1143-
logger.info(f"Error: Configuration file '{config_file}' not found.")
1178+
logger.error(f"Error: Configuration file '{config_file}' not found.")
11441179
return {'return': 1, 'error': f"Error: Configuration file '{config_file}' not found."}
11451180

11461181
#logger.info(f"Loading configuration from {config_file}")
@@ -1153,7 +1188,7 @@ def load(self, args):
11531188
# Store configuration in memory or perform other operations
11541189
self.cfg = config_data
11551190
except yaml.YAMLError as e:
1156-
logger.info(f"Error loading YAML configuration: {e}")
1191+
logger.error(f"Error loading YAML configuration: {e}")
11571192

11581193
return {'return': 0, 'config': self.cfg}
11591194

@@ -1168,7 +1203,7 @@ def unload(self, args):
11681203
logger.info(f"Unloading configuration.")
11691204
del self.config # Remove the loaded config from memory
11701205
else:
1171-
logger.info("Error: No configuration is currently loaded.")
1206+
logger.error("Error: No configuration is currently loaded.")
11721207

11731208
actions = {
11741209
'repo': RepoAction,

pyproject.toml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ classifiers = [
2222
dependencies = [
2323
"requests",
2424
"pyyaml",
25-
"giturlparse"
25+
"giturlparse",
26+
"colorama"
2627
]
2728

2829
[project.urls]

0 commit comments

Comments
 (0)