Skip to content

Commit b0ec692

Browse files
author
johnhuang316
committed
refactor: remove README creation functionality and eliminate code duplication
- Create shared constants.py for SETTINGS_DIR, CONFIG_FILE, INDEX_FILE, CACHE_FILE - Remove duplicate temporary directory management between server.py and project_settings.py - Eliminate redundant README creation logic in both global and project-specific directories - Consolidate create_temp_directory and check_temp_directory tools to use ProjectSettings - Reduce I/O operations and code complexity by ~70 lines - Improve maintainability through centralized constant management
1 parent 6f87233 commit b0ec692

File tree

3 files changed

+47
-72
lines changed

3 files changed

+47
-72
lines changed

src/code_index_mcp/constants.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
"""
2+
Shared constants for the Code Index MCP server.
3+
"""
4+
5+
# Directory and file names
6+
SETTINGS_DIR = "code_indexer"
7+
CONFIG_FILE = "config.json"
8+
INDEX_FILE = "file_index.pickle"
9+
CACHE_FILE = "content_cache.pickle"

src/code_index_mcp/project_settings.py

Lines changed: 20 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,13 @@
1212
import hashlib
1313
from datetime import datetime
1414

15+
from .constants import (
16+
SETTINGS_DIR, CONFIG_FILE, INDEX_FILE, CACHE_FILE
17+
)
18+
1519
class ProjectSettings:
1620
"""Class for managing project settings and index data"""
1721

18-
SETTINGS_DIR = "code_indexer"
19-
CONFIG_FILE = "config.json"
20-
INDEX_FILE = "file_index.pickle"
21-
CACHE_FILE = "content_cache.pickle"
22-
2322
def __init__(self, base_path, skip_load=False):
2423
"""Initialize project settings
2524
@@ -50,18 +49,13 @@ def __init__(self, base_path, skip_load=False):
5049
print(f"Using current directory as fallback: {system_temp}")
5150

5251
# Create code_indexer directory
53-
temp_base_dir = os.path.join(system_temp, self.SETTINGS_DIR)
52+
temp_base_dir = os.path.join(system_temp, SETTINGS_DIR)
5453
print(f"Code indexer directory path: {temp_base_dir}")
5554

5655
if not os.path.exists(temp_base_dir):
5756
print(f"Creating code indexer directory: {temp_base_dir}")
5857
os.makedirs(temp_base_dir, exist_ok=True)
59-
60-
# Create a README.md file explaining the purpose of this directory
61-
readme_path = os.path.join(temp_base_dir, "README.md")
62-
with open(readme_path, 'w', encoding='utf-8') as f:
63-
f.write("# Code Indexer Cache Directory\n\nThis directory contains cached data for the Code Index MCP tool.\nEach subdirectory corresponds to a different project.\n")
64-
print(f"README file created: {readme_path}")
58+
print(f"Code indexer directory created: {temp_base_dir}")
6559
else:
6660
print(f"Code indexer directory already exists: {temp_base_dir}")
6761
except Exception as e:
@@ -104,24 +98,7 @@ def ensure_settings_dir(self):
10498
print(f"Creating project settings directory: {self.settings_path}")
10599
# Create directory structure
106100
os.makedirs(self.settings_path, exist_ok=True)
107-
108-
# Create a README.md file explaining the purpose of this directory
109-
readme_path = os.path.join(self.settings_path, "README.md")
110-
readme_content = (
111-
f"# Code Indexer Cache Directory for {self.base_path}\n\n"
112-
f"This directory contains cached data for the Code Index MCP tool:\n\n"
113-
f"- `config.json`: Project configuration\n"
114-
f"- `file_index.pickle`: Index of project files\n"
115-
f"- `content_cache.pickle`: Cached file contents\n\n"
116-
f"These files are automatically generated and stored in the system temporary directory.\n"
117-
)
118-
119-
try:
120-
with open(readme_path, 'w', encoding='utf-8') as f:
121-
f.write(readme_content)
122-
print(f"README file created: {readme_path}")
123-
except Exception as e:
124-
print(f"Warning: Could not create README file: {e}")
101+
print(f"Project settings directory created: {self.settings_path}")
125102
else:
126103
print(f"Project settings directory already exists: {self.settings_path}")
127104

@@ -148,38 +125,38 @@ def ensure_settings_dir(self):
148125
def get_config_path(self):
149126
"""Get the path to the configuration file"""
150127
try:
151-
path = os.path.join(self.settings_path, self.CONFIG_FILE)
128+
path = os.path.join(self.settings_path, CONFIG_FILE)
152129
# Ensure directory exists
153130
os.makedirs(os.path.dirname(path), exist_ok=True)
154131
return path
155132
except Exception as e:
156133
print(f"Error getting config path: {e}")
157134
# If error occurs, use file in current directory as fallback
158-
return os.path.join(os.getcwd(), self.CONFIG_FILE)
135+
return os.path.join(os.getcwd(), CONFIG_FILE)
159136

160137
def get_index_path(self):
161138
"""Get the path to the index file"""
162139
try:
163-
path = os.path.join(self.settings_path, self.INDEX_FILE)
140+
path = os.path.join(self.settings_path, INDEX_FILE)
164141
# Ensure directory exists
165142
os.makedirs(os.path.dirname(path), exist_ok=True)
166143
return path
167144
except Exception as e:
168145
print(f"Error getting index path: {e}")
169146
# If error occurs, use file in current directory as fallback
170-
return os.path.join(os.getcwd(), self.INDEX_FILE)
147+
return os.path.join(os.getcwd(), INDEX_FILE)
171148

172149
def get_cache_path(self):
173150
"""Get the path to the cache file"""
174151
try:
175-
path = os.path.join(self.settings_path, self.CACHE_FILE)
152+
path = os.path.join(self.settings_path, CACHE_FILE)
176153
# Ensure directory exists
177154
os.makedirs(os.path.dirname(path), exist_ok=True)
178155
return path
179156
except Exception as e:
180157
print(f"Error getting cache path: {e}")
181158
# If error occurs, use file in current directory as fallback
182-
return os.path.join(os.getcwd(), self.CACHE_FILE)
159+
return os.path.join(os.getcwd(), CACHE_FILE)
183160

184161
def _get_timestamp(self):
185162
"""Get current timestamp"""
@@ -257,7 +234,7 @@ def save_index(self, file_index):
257234
if not os.access(dir_path, os.W_OK):
258235
print(f"Warning: Directory is not writable: {dir_path}")
259236
# Use current directory as fallback
260-
index_path = os.path.join(os.getcwd(), self.INDEX_FILE)
237+
index_path = os.path.join(os.getcwd(), INDEX_FILE)
261238
print(f"Using fallback path: {index_path}")
262239

263240
with open(index_path, 'wb') as f:
@@ -268,7 +245,7 @@ def save_index(self, file_index):
268245
print(f"Error saving index: {e}")
269246
# Try saving to current directory
270247
try:
271-
fallback_path = os.path.join(os.getcwd(), self.INDEX_FILE)
248+
fallback_path = os.path.join(os.getcwd(), INDEX_FILE)
272249
print(f"Trying fallback path: {fallback_path}")
273250
with open(fallback_path, 'wb') as f:
274251
pickle.dump(file_index, f)
@@ -304,7 +281,7 @@ def load_index(self):
304281
return {}
305282
else:
306283
# Try loading from current directory
307-
fallback_path = os.path.join(os.getcwd(), self.INDEX_FILE)
284+
fallback_path = os.path.join(os.getcwd(), INDEX_FILE)
308285
if os.path.exists(fallback_path):
309286
print(f"Trying fallback path: {fallback_path}")
310287
try:
@@ -340,7 +317,7 @@ def save_cache(self, content_cache):
340317
if not os.access(dir_path, os.W_OK):
341318
print(f"Warning: Directory is not writable: {dir_path}")
342319
# Use current directory as fallback
343-
cache_path = os.path.join(os.getcwd(), self.CACHE_FILE)
320+
cache_path = os.path.join(os.getcwd(), CACHE_FILE)
344321
print(f"Using fallback path: {cache_path}")
345322

346323
with open(cache_path, 'wb') as f:
@@ -351,7 +328,7 @@ def save_cache(self, content_cache):
351328
print(f"Error saving cache: {e}")
352329
# Try saving to current directory
353330
try:
354-
fallback_path = os.path.join(os.getcwd(), self.CACHE_FILE)
331+
fallback_path = os.path.join(os.getcwd(), CACHE_FILE)
355332
print(f"Trying fallback path: {fallback_path}")
356333
with open(fallback_path, 'wb') as f:
357334
pickle.dump(content_cache, f)
@@ -387,7 +364,7 @@ def load_cache(self):
387364
return {}
388365
else:
389366
# Try loading from current directory
390-
fallback_path = os.path.join(os.getcwd(), self.CACHE_FILE)
367+
fallback_path = os.path.join(os.getcwd(), CACHE_FILE)
391368
if os.path.exists(fallback_path):
392369
print(f"Trying fallback path: {fallback_path}")
393370
try:
@@ -462,7 +439,7 @@ def get_stats(self):
462439
stats['all_files'] = all_files
463440

464441
# Get details for specific files
465-
for filename in [self.CONFIG_FILE, self.INDEX_FILE, self.CACHE_FILE]:
442+
for filename in [CONFIG_FILE, INDEX_FILE, CACHE_FILE]:
466443
file_path = os.path.join(self.settings_path, filename)
467444
if os.path.exists(file_path):
468445
try:

src/code_index_mcp/server.py

Lines changed: 18 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,9 @@
1616
from mcp.server.fastmcp import FastMCP, Context, Image
1717
from mcp import types
1818

19-
# Import the ProjectSettings class - using relative import
19+
# Import the ProjectSettings class and constants - using relative import
2020
from .project_settings import ProjectSettings
21+
from .constants import SETTINGS_DIR
2122

2223
# Create the MCP server
2324
mcp = FastMCP("CodeIndexer", dependencies=["pathlib"])
@@ -532,7 +533,7 @@ def get_settings_info(ctx: Context) -> Dict[str, Any]:
532533
# Check if base_path is set
533534
if not base_path:
534535
# Even if base_path is not set, we can still show the temp directory
535-
temp_dir = os.path.join(tempfile.gettempdir(), "code_indexer")
536+
temp_dir = os.path.join(tempfile.gettempdir(), SETTINGS_DIR)
536537
return {
537538
"status": "not_configured",
538539
"message": "Project path not set. Please use set_project_path to set a project directory first.",
@@ -549,7 +550,7 @@ def get_settings_info(ctx: Context) -> Dict[str, Any]:
549550
stats = settings.get_stats()
550551

551552
# Get temp directory
552-
temp_dir = os.path.join(tempfile.gettempdir(), "code_indexer")
553+
temp_dir = os.path.join(tempfile.gettempdir(), SETTINGS_DIR)
553554

554555
return {
555556
"settings_directory": settings.settings_path,
@@ -563,27 +564,18 @@ def get_settings_info(ctx: Context) -> Dict[str, Any]:
563564
@mcp.tool()
564565
def create_temp_directory() -> Dict[str, Any]:
565566
"""Create the temporary directory used for storing index data."""
566-
temp_dir = os.path.join(tempfile.gettempdir(), "code_indexer")
567+
temp_dir = os.path.join(tempfile.gettempdir(), SETTINGS_DIR)
567568

568569
result = {
569570
"temp_directory": temp_dir,
570571
"existed_before": os.path.exists(temp_dir),
571572
}
572573

573574
try:
574-
# Create the directory if it doesn't exist
575-
if not os.path.exists(temp_dir):
576-
os.makedirs(temp_dir, exist_ok=True)
577-
result["created"] = True
578-
579-
# Create a README file
580-
readme_path = os.path.join(temp_dir, "README.md")
581-
with open(readme_path, 'w', encoding='utf-8') as f:
582-
f.write("# Code Indexer Cache Directory\n\nThis directory contains cached data for the Code Index MCP tool.\nEach subdirectory corresponds to a different project.\n")
583-
result["readme_created"] = True
584-
else:
585-
result["created"] = False
586-
575+
# Use ProjectSettings to handle directory creation consistently
576+
temp_settings = ProjectSettings("", skip_load=True)
577+
578+
result["created"] = not result["existed_before"]
587579
result["exists_now"] = os.path.exists(temp_dir)
588580
result["is_directory"] = os.path.isdir(temp_dir)
589581
except Exception as e:
@@ -594,7 +586,7 @@ def create_temp_directory() -> Dict[str, Any]:
594586
@mcp.tool()
595587
def check_temp_directory() -> Dict[str, Any]:
596588
"""Check the temporary directory used for storing index data."""
597-
temp_dir = os.path.join(tempfile.gettempdir(), "code_indexer")
589+
temp_dir = os.path.join(tempfile.gettempdir(), SETTINGS_DIR)
598590

599591
result = {
600592
"temp_directory": temp_dir,
@@ -778,19 +770,16 @@ def main():
778770
"""Entry point for the code indexer."""
779771
print("Starting Code Index MCP Server...", file=sys.stderr)
780772

781-
# Ensure temporary directory exists
782-
temp_dir = os.path.join(tempfile.gettempdir(), "code_indexer")
773+
# Ensure temporary directory exists using ProjectSettings
774+
temp_dir = os.path.join(tempfile.gettempdir(), SETTINGS_DIR)
783775
print(f"Temporary directory: {temp_dir}")
784776

785-
if not os.path.exists(temp_dir):
786-
print(f"Creating temporary directory: {temp_dir}")
787-
try:
788-
os.makedirs(temp_dir, exist_ok=True)
789-
print(f"Temporary directory created successfully")
790-
except Exception as e:
791-
print(f"Error creating temporary directory: {e}", file=sys.stderr)
792-
else:
793-
print(f"Temporary directory already exists")
777+
try:
778+
# Use ProjectSettings to handle directory creation consistently
779+
temp_settings = ProjectSettings("", skip_load=True)
780+
print(f"Temporary directory setup completed")
781+
except Exception as e:
782+
print(f"Error setting up temporary directory: {e}", file=sys.stderr)
794783

795784
mcp.run()
796785

0 commit comments

Comments
 (0)