-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathindex.py
More file actions
229 lines (183 loc) · 8.41 KB
/
Copy pathindex.py
File metadata and controls
229 lines (183 loc) · 8.41 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
import subprocess
import datetime
from dotenv import load_dotenv
import os
import json
import time
from datetime import datetime
load_dotenv()
def load_config():
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(script_dir, 'config.json')
with open(config_file, 'r') as f:
config = json.load(f)
if 'tree' not in config or 'system_commands' not in config:
raise KeyError("Missing required keys in config.json")
return config
except (FileNotFoundError, KeyError):
print("⚠️ config.json not found or invalid, using default settings")
return {
"tree": {
"max_depth": 3,
"ignore_patterns": ["venv", "__pycache__", "node_modules", "build", "public", "dist", ".git"],
"ignore_extensions": ["*.pyc", "*.pyo", "*.pyd", "*.so", "*.dll", "*.class"]
},
"system_commands": {
"disk_usage_threshold": 80
}
}
config = load_config()
ignore_patterns = '|'.join(config['tree']['ignore_patterns'])
ignore_extensions = '|'.join(config['tree']['ignore_extensions'])
combined_ignore = f"{ignore_patterns}|{ignore_extensions}"
system_commands = [
"uname -a",
"python --version",
"pip list",
"python -c 'import sys; print(sys.path)'",
"docker ps",
f"df -h | awk '(NR==1) || ($5+0 >= {config['system_commands']['disk_usage_threshold']})'",
"vm_stat | awk '/Pages free:|Pages active:|Pages inactive:|Pages wired down:/ {print}'",
"netstat -an | grep LISTEN | awk '{print $4}' | sort -u",
"printenv | grep -v 'KEY\\|SECRET\\|PASS\\|TOKEN'",
]
project_commands = [
f"tree -d -L {config['tree']['max_depth']} -I '{combined_ignore}'",
]
def get_project_directories():
try:
script_dir = os.path.dirname(os.path.abspath(__file__))
projects_file = os.path.join(script_dir, 'containers-list.md')
with open(projects_file, 'r') as f:
projects = [
line.strip('- \n')
for line in f.readlines()
if line.strip().startswith('-')
]
return projects
except FileNotFoundError:
print("❌ Error: containers-list.md not found in .cursorboost directory")
return []
def run_commands(commands_list, project_dir=None):
print(f"📊 Collecting {'project' if project_dir else 'system'} information...")
output = []
output.append(f"Timestamp: {datetime.utcnow().isoformat()}Z\n")
if project_dir:
original_dir = os.getcwd()
base_project_path = config.get('base_project_path')
if not base_project_path or base_project_path == "<your_project_path>":
raise ValueError(
"❌ Error: 'base_project_path' is not defined or is still set to '<your_project_path>' in the configuration file (config.json). "
"Please update it to your project's root directory."
)
project_path = os.path.join(os.path.expanduser(base_project_path), project_dir)
try:
os.chdir(project_path)
output.append(f"\n### Project: {project_dir} ###\n")
except FileNotFoundError:
print(f" ❌ Project directory not found: {project_path}")
return ""
for command in commands_list:
print(f" ⚡ Running: {command}")
try:
result = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
output.append(f"{command}:\n{result.decode('utf-8')}\n")
except subprocess.CalledProcessError as e:
print(f" ❌ Failed: {command}")
output.append(f"{command} (FAILED):\n{e.output.decode('utf-8')}\n")
if project_dir:
os.chdir(original_dir)
return "\n".join(output)
def write_snapshot(snapshot):
with open("snapshot.txt", "w") as f:
f.write(snapshot)
import openai
def generate_cursorrules(snapshot):
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
print("❌ Error: OPENAI_API_KEY not found in environment variables")
return None
client = openai.OpenAI(api_key=api_key)
response = client.chat.completions.create(
model="chatgpt-4o-latest",
messages=[
{"role": "system", "content": "You are a helpful assistant that injects a user's system information and parses out the most important details. Only respond with the complete file contents, without any additional explanation or commentary."},
{"role": "user", "content": f"You are a coding assistant optimizing text files for LLM-based applications. Using the following system snapshot, generate a text file that highlights the most relevant details for coding context. Only output the complete file contents, without explanations or extra text:\n\n{snapshot}"}
],
temperature=1,
)
return response.choices[0].message.content
def get_docker_logs():
try:
ignore_containers = config.get('docker', {}).get('ignore_containers', [])
containers = subprocess.check_output(
"docker ps --format '{{.ID}} {{.Names}}'",
shell=True
).decode('utf-8').strip().split('\n')
logs = []
for container in containers:
if not container:
continue
container_id, container_name = container.split()
if container_name in ignore_containers:
continue
try:
container_logs = subprocess.check_output(
f"docker logs --tail 25 {container_id}",
shell=True
).decode('utf-8')
logs.append(f"\nDocker Logs for {container_name} ({container_id}):\n")
logs.append(container_logs)
except subprocess.CalledProcessError as e:
logs.append(f"\nError getting logs for {container_name}: {str(e)}\n")
return "\n".join(logs)
except subprocess.CalledProcessError as e:
return "Error getting Docker container list"
def write_cursorrules(cursorrules):
project_description = ""
try:
with open("project-description.txt", "r") as f:
project_description = f"# Project Description:\n{f.read()}\n\n"
except FileNotFoundError:
print("Warning: project-description.txt not found")
docker_logs = get_docker_logs()
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
cursorrules_path = os.path.join(parent_dir, '.cursorrules')
with open(cursorrules_path, "w") as f:
f.write(f"{project_description}{cursorrules}\n\n# Docker Container Logs:\n\n{docker_logs}")
def find_requirements_files(root_dir):
requirements_files = []
for dirpath, dirnames, filenames in os.walk(root_dir):
if '.cursorboost' in dirpath:
continue
if 'requirements.txt' in filenames:
requirements_files.append(os.path.join(dirpath, 'requirements.txt'))
return requirements_files
root_directory = os.getcwd()
requirements_files = find_requirements_files(root_directory)
print("Found requirements files:", requirements_files)
if __name__ == "__main__":
print("🚀 Starting Cursor Boost in continuous mode...")
while True:
print(f"\n⏰ Running update at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
projects = get_project_directories()
if not projects:
print("⚠️ No projects found in containers-list.md")
system_snapshot = run_commands(system_commands)
all_snapshots = [system_snapshot]
for project in projects:
print(f"📂 Processing project: {project}")
project_snapshot = run_commands(project_commands, project)
if project_snapshot:
all_snapshots.append(project_snapshot)
complete_snapshot = "\n\n".join(all_snapshots)
write_snapshot(complete_snapshot)
cursorrules = generate_cursorrules(complete_snapshot)
if cursorrules:
write_cursorrules(cursorrules)
print("✅ .cursorrules updated successfully")
print("✅ Snapshot saved to snapshot.txt")
else:
print("❌ Failed to generate .cursorrules")
time.sleep(60)