-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript_registry.py
More file actions
354 lines (294 loc) · 12.4 KB
/
script_registry.py
File metadata and controls
354 lines (294 loc) · 12.4 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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import json
import os
import shutil
import re
from pathlib import Path
from typing import Dict, List, Optional
from datetime import datetime
class ScriptRegistry:
"""Manages the script registry for CLAP"""
# Language to file extension mapping
LANGUAGE_EXTENSIONS = {
'.py': 'Python',
'.sh': 'Bash',
'.R': 'R',
'.r': 'R',
'.m': 'Matlab',
'.js': 'JavaScript',
'.pl': 'Perl',
'.rb': 'Ruby'
}
# Tag options with their colors
TAG_OPTIONS = {
'analysis': '#28A745', # Green
'statistics': '#007BFF', # Blue
'setup': '#DC3545', # Red
'other': '#6F42C1' # Purple
}
def __init__(self):
self.base_path = Path(__file__).parent
self.registry_file = self.base_path / "registry.json"
self.registry_dir = self.base_path / "registry"
# Ensure directories and files exist
self._ensure_registry_structure()
# Load registry
self.registry_data = self._load_registry()
def _ensure_registry_structure(self):
"""Create registry directory and file if they don't exist"""
self.registry_dir.mkdir(parents=True, exist_ok=True)
if not self.registry_file.exists():
self._save_registry({"scripts": []})
def _load_registry(self) -> Dict:
"""Load registry from JSON file"""
try:
with open(self.registry_file, 'r') as f:
return json.load(f)
except (json.JSONDecodeError, IOError) as e:
print(f"Error loading registry: {e}. Creating new registry.")
return {"scripts": []}
def _save_registry(self, data: Dict):
"""Save registry to JSON file"""
try:
with open(self.registry_file, 'w') as f:
json.dump(data, f, indent=4)
except IOError as e:
print(f"Error saving registry: {e}")
def detect_language(self, file_path: str) -> str:
"""Detect language from file extension"""
ext = Path(file_path).suffix.lower()
return self.LANGUAGE_EXTENSIONS.get(ext, "Unknown")
def extract_description_from_file(self, file_path: str) -> str:
"""
Try to extract description from file comments.
Looks for comment blocks at the beginning of the file.
Args:
file_path: Path to the script file
Returns:
String containing the extracted description (max 200 chars).
Returns empty string if no description found or error occurs.
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
lines = f.readlines()
# Skip empty lines at the beginning
start_idx = 0
while start_idx < len(lines) and not lines[start_idx].strip():
start_idx += 1
if start_idx >= len(lines):
return ""
# Detect comment style based on first non-empty line
first_line = lines[start_idx].strip()
description_lines = []
# Python/Bash style (#)
if first_line.startswith('#'):
for line in lines[start_idx:]:
stripped = line.strip()
if stripped.startswith('#'):
# Remove # and shebang lines
if not stripped.startswith('#!'):
desc = stripped.lstrip('#').strip()
if desc:
description_lines.append(desc)
elif stripped:
break # Stop at first non-comment line
# Multi-line comments (/* */ or """)
elif first_line.startswith('"""') or first_line.startswith("'''"):
in_docstring = True
quote = '"""' if '"""' in first_line else "'''"
# Check if docstring ends on same line
if first_line.count(quote) >= 2:
desc = first_line.replace(quote, '').strip()
if desc:
description_lines.append(desc)
else:
for line in lines[start_idx + 1:]:
if quote in line:
desc = line.split(quote)[0].strip()
if desc:
description_lines.append(desc)
break
else:
desc = line.strip()
if desc:
description_lines.append(desc)
# Return first few lines as description (max 200 chars)
if description_lines:
full_desc = ' '.join(description_lines)
return full_desc[:200] if len(full_desc) > 200 else full_desc
except Exception as e:
print(f"Error extracting description: {e}")
return ""
def add_script(
self,
source_file_path: str,
language: str,
project: str,
description: str,
dependencies: str,
author: str,
tags: List[str] = None
) -> bool:
"""
Add a new script to the registry.
Args:
source_file_path: Path to the source script file
language: Programming language (required, non-empty)
project: Project name/category (required, non-empty)
description: Script description
dependencies: Required dependencies
author: Script author
tags: List of tags (e.g., ['analysis', 'statistics'])
Returns:
True if successful, False otherwise
"""
try:
# Validate inputs
if not source_file_path or not source_file_path.strip():
print("Error: Source file path is required")
return False
if not language or not language.strip():
print("Error: Language is required")
return False
if not project or not project.strip():
print("Error: Project name is required")
return False
source_path = Path(source_file_path)
if not source_path.exists():
print(f"Error: Source file does not exist: {source_file_path}")
return False
# Generate unique filename if file already exists
dest_filename = source_path.name
dest_path = self.registry_dir / dest_filename
counter = 1
while dest_path.exists():
name_parts = source_path.stem
ext = source_path.suffix
dest_filename = f"{name_parts}_{counter}{ext}"
dest_path = self.registry_dir / dest_filename
counter += 1
# Copy file to registry directory
shutil.copy2(source_path, dest_path)
# Create registry entry
script_entry = {
"filename": dest_filename,
"name": source_path.stem,
"language": language,
"project": project,
"description": description,
"dependencies": dependencies,
"author": author,
"tags": tags if tags else [],
"added_date": datetime.now().isoformat(),
"relative_path": f"registry/{dest_filename}"
}
# Add to registry
self.registry_data["scripts"].append(script_entry)
self._save_registry(self.registry_data)
return True
except Exception as e:
print(f"Error adding script to registry: {e}")
return False
def get_all_scripts(self) -> List[Dict]:
"""Get all scripts from registry"""
return self.registry_data.get("scripts", [])
def get_script_by_filename(self, filename: str) -> Optional[Dict]:
"""Get a specific script by filename"""
for script in self.registry_data.get("scripts", []):
if script["filename"] == filename:
return script
return None
def filter_scripts(
self,
project: Optional[str] = None,
language: Optional[str] = None,
author: Optional[str] = None,
tag: Optional[str] = None,
search_term: Optional[str] = None
) -> List[Dict]:
"""
Filter scripts based on criteria
Args:
project: Filter by project name
language: Filter by language
author: Filter by author
tag: Filter by tag
search_term: Search in name and description
Returns:
List of matching scripts
"""
scripts = self.get_all_scripts()
if project:
scripts = [s for s in scripts if s.get("project", "").lower() == project.lower()]
if language:
scripts = [s for s in scripts if s.get("language", "").lower() == language.lower()]
if author:
scripts = [s for s in scripts if s.get("author", "").lower() == author.lower()]
if tag:
scripts = [s for s in scripts if tag in (s.get("tags") or [])]
if search_term:
term = search_term.lower()
scripts = [
s for s in scripts
if term in s.get("name", "").lower() or term in s.get("description", "").lower()
]
return scripts
def get_unique_projects(self) -> List[str]:
"""Get list of unique project names"""
projects = set()
for script in self.get_all_scripts():
project = script.get("project", "")
if project:
projects.add(project)
return sorted(list(projects))
def get_unique_languages(self) -> List[str]:
"""Get list of unique languages"""
languages = set()
for script in self.get_all_scripts():
language = script.get("language", "")
if language:
languages.add(language)
return sorted(list(languages))
def get_unique_authors(self) -> List[str]:
"""Get list of unique authors"""
authors = set()
for script in self.get_all_scripts():
author = script.get("author", "")
if author:
authors.add(author)
return sorted(list(authors))
def get_unique_tags(self) -> List[str]:
"""Get list of unique tags from all scripts"""
tags = set()
for script in self.get_all_scripts():
script_tags = script.get("tags") or []
if script_tags:
tags.update(script_tags)
return sorted(list(tags))
def delete_script(self, filename: str) -> bool:
"""
Delete a script from the registry and filesystem
Args:
filename: Name of the script file to delete
Returns:
True if successful, False otherwise
"""
try:
# Find and remove from registry
scripts = self.registry_data.get("scripts", [])
script_to_delete = None
for i, script in enumerate(scripts):
if script["filename"] == filename:
script_to_delete = scripts.pop(i)
break
if script_to_delete:
# Delete file from filesystem
file_path = self.base_path / script_to_delete["relative_path"]
if file_path.exists():
file_path.unlink()
# Save updated registry
self._save_registry(self.registry_data)
return True
return False
except Exception as e:
print(f"Error deleting script: {e}")
return False