-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate_cursor_rules.py
More file actions
433 lines (356 loc) · 14.7 KB
/
Copy pathcreate_cursor_rules.py
File metadata and controls
433 lines (356 loc) · 14.7 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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
import os
import logging
import argparse
from datetime import datetime
VERSION = "0.2.3"
# Base templates for documentation files
BASE_TEMPLATES = {
'architecture_decisions': """# Architectural Decision Records (ADR)
## Overview
This document maintains a record of all significant architectural decisions in the project.
## Format
Each ADR should follow this format:
1. **Date:** When was the decision made
2. **Status:** Proposed, Accepted, Deprecated, Superseded
3. **Context:** What is the issue that we're seeing that is motivating this decision
4. **Decision:** What is the change that we're proposing and/or doing
5. **Consequences:** What becomes easier or more difficult to do because of this change
## Decisions
1. [First Decision Title] - YYYY-MM-DD
- Status: [status]
- Context: [context]
- Decision: [decision]
- Consequences: [consequences]
""",
'best_practices': """# Project Best Practices
## Code Style
- Follow PEP 8 guidelines
- Use meaningful variable and function names
- Keep functions focused and small
## Development Workflow
- Write tests before implementing features
- Review code before committing
- Update documentation alongside code changes
## Quality Assurance
- Run linters before commits
- Maintain test coverage above defined thresholds
- Regular security audits
""",
'issue_resolutions': """# Issue Resolutions
## Purpose
Document insights, challenges, solutions, and lessons learned during development.
## Format
Each entry should include:
- Date
- Context
- Challenge faced
- Solution implemented
- Impact and results
- Lessons learned
## Entries
1. [First Issue] - YYYY-MM-DD
- Context: [context]
- Challenge: [challenge]
- Solution: [solution]
- Impact: [impact]
- Lessons Learned: [lessons]
""",
'performance_metrics': """# Performance Metrics
## Purpose
Track performance metrics, test results, and benchmarks.
## Key Performance Indicators (KPIs)
- Response times
- Resource utilization
- Throughput metrics
## Test Results
- Test Suite: [test suite name]
- Date: [date]
- Results: [test results details]
## Benchmarks
Regular performance benchmark results and analysis.
""",
'security': """# Security Practices and Considerations
## Security Checklist
- [ ] Input validation
- [ ] Authentication and authorization
- [ ] Data encryption
- [ ] Secure communication
- [ ] Regular security audits
## Security Incidents
Document and learn from security-related incidents.
## Best Practices
Current security best practices and guidelines.
""",
'patterns': """# Common Patterns
## Purpose
Document recurring patterns in code reviews.
## Patterns
1. [Pattern Name] - YYYY-MM-DD
- Context: [context]
- Pattern: [pattern description]
- Example: [example code or usage]
""",
'improvement_suggestions': """# Improvement Suggestions
## Purpose
Maintain a list of future improvement suggestions.
## Suggestions
1. [Suggestion Title] - YYYY-MM-DD
- Context: [context]
- Suggestion: [suggestion details]
- Impact: [expected impact]
""",
'project_overview': """# Project Overview
## Purpose
Provide a high-level overview of the project.
## Overview
- Project Name: [project name]
- Description: [brief description]
- Goals: [project goals]
- Milestones: [key milestones]
""",
'task_list': """# Task List
## Purpose
Prioritize and organize tasks and to-dos.
## Tasks
- [ ] [Task Title] - YYYY-MM-DD
- Description: [task description]
- Priority: [priority level]
- Status: [status]
""",
'changelog': """# Changelog
## Purpose
Document important changes made in the project.
## Changes
- YYYY-MM-DD: [change description]
""",
'project_milestones': """# Project Milestones
## Purpose
Document project milestones and progress.
## Milestones
1. [Milestone Title] - YYYY-MM-DD
- Description: [milestone description]
- Status: [status]
""",
'glossary': """# Glossary
## Purpose
Explain difficult concepts and ideas in the project.
## Terms
- [Term]: [definition]
"""
}
# Expanded rule templates
RULE_TEMPLATES = {
"core": """---
description: Essential guidelines for all Python projects
globs: *.py
---
# Core Python Project Guidelines
## 1. Code Quality Fundamentals
- **PEP8 Compliance**: Enforced via flake8 with strict 120 char line limits
- **Type Hints**: Required for all public interfaces, encouraged elsewhere
- **Module Structure**:
- Max 1000 lines per module
- Clear separation of concerns between modules
- **Docstrings**:
- Google-style format with Args, Returns, and Raises sections
- Examples required for complex functions
## 2. Version Control Standards
- **Commit Messages**:
- Imperative mood ("Add feature" not "Added feature")
- 50-character subject line
- Body explaining why and how, not just what
- **Branch Strategy**:
- `main` protected with required reviews
- Feature branches rebased before merge
- Hotfix branches for critical fixes
## 3. Testing Essentials
- **Unit Tests**:
- 100% coverage for core functionality
- Test pyramid adherence (70/20/10 unit/integration/e2e)
- **Fixture Management**:
- Factory pattern for complex test data
- Mocking external services
- **Test Results**:
- Regularly update [performance_metrics.md](mdc:.notes/performance_metrics.md) with the results of the tests and the benchmarks
## 4. Continuous Learning
- **Documentation of Insights**: Regularly update [issue_resolutions.md](mdc:.notes/issue_resolutions.md) with new patterns, anti-patterns, and insights discovered during development.
- **Architectural Decisions**: Document the rationale behind significant architectural decisions in [architecture_decisions.md](mdc:.notes/architecture_decisions.md).
## 5. Self-Improvement Protocol
- **Code Quality Monitoring**: Continuously monitor and improve code quality.
- **Pattern Tracking**: Identify and document recurring patterns in code reviews in [patterns.md](mdc:.notes/patterns.md).
- **Rule Updates**: Periodically update these rules based on project evolution and new best practices.
- **Future Enhancements**: Maintain a list of future improvement suggestions in [improvement_suggestions.md](mdc:.notes/improvement_suggestions.md).
## 6. Implementation Guidelines
- **Modular Design**: Use blueprints or modules for organizing code into logical components.
- **Error Handling**:
- Custom Exceptions: Use custom exception hierarchies for better error management.
- Logging: Implement detailed logging to track and debug issues effectively.
- Meaningful Messages: Provide clear and meaningful error messages for easier troubleshooting.
## 7. General Development Practices
- **Automated Testing**: Set up automated testing using tools like pytest to ensure code quality.
- **Linters**: Use linters (e.g., flake8, pylint) to enforce code style and quality standards.
## 8. Documentation Requirements
- **Comprehensive Docstrings**: Ensure all functions and classes have detailed docstrings.
- **Example Usage**: Include example usage in docstrings to illustrate functionality.
- **Living Documentation**: Maintain a living document in [best_practices.md](mdc:.notes/best_practices.md) for project-specific conventions.
## 9. Security Requirements
- **Input Validation**: Validate all inputs to prevent injection attacks and other vulnerabilities.
- **Sanitization**: Sanitize user inputs to prevent script injection.
- **Access Controls**: Implement proper access controls to protect sensitive data and functionalities.
- **Security Considerations**: Document security considerations and strategies in [security.md](mdc:.notes/security.md).
## 10. Project Management
- **Issue Tracking**: Use issue tracking tools to manage bugs, feature requests, and tasks.
- **Prioritization**: Regularly review and prioritize issues based on project goals and user feedback.
- **Development Log**: Regularly update [changelog.md](mdc:.notes/changelog.md) with important changes made in the project with the reasons behind them explained.
- **Glossary**: Explain the project's difficult concepts and ideas in [glossary.md](mdc:.notes/glossary.md) in a concise manner to help newcomers to understand complex parts of it.
## 11. Adaptability and Flexibility
- **Regular Reviews**: Conduct regular reviews of these rules to ensure they remain relevant and effective.
- **Scalability**: Design the project with scalability in mind to accommodate future growth and changes.
- **Refactoring**: Regularly refactor code to maintain quality and adapt to new requirements.
""",
"advanced": """---
description: Advanced practices for complex Python projects
globs: *.py
---
# Advanced Python Guidelines
## 1. Performance Optimization
- **Benchmarking**:
- Use pytest-benchmark for performance regression tests
- Profile monthly using cProfile/py-spy
- **Concurrency**:
- Threading vs multiprocessing decision tree
- Async/await patterns for I/O bound operations
- **Performance Metrics**: Use [performance_metrics.md](mdc:.notes/performance_metrics.md) to track the performance of the project. Gather the metrics from the tests and the benchmarks and add them to the file.
## 2. CI/CD Pipeline
- **Build Stages**:
- Linting -> Unit Tests -> Integration Tests -> Security Scan
- Parallel test execution
- **Artifact Management**:
- PyPI private repository integration
- Docker image versioning
## 3. Observability
- **Structured Logging**:
- JSON format with severity levels
- Correlation IDs for requests
- **Metrics**:
- Prometheus endpoints for key metrics
- Grafana dashboards for service health
## 4. Security Hardening
- **OWASP Top 10**:
- Parameterized queries enforced
- Regular dependency vulnerability scans
- **Secrets Management**:
- Vault integration required
- Never commit .env files
## 5. Documentation Excellence
- **API Docs**:
- OpenAPI 3.0 specification required
- Postman collection generation
- **Decision Records**:
- ADR template with alternatives considered
- Quarterly architecture reviews
## 6. Scalability Patterns
- **Caching Strategies**:
- Redis integration guidelines
- Cache invalidation workflows
- **Horizontal Scaling**:
- Stateless service design
- Message queue patterns
""",
"supplemental": """---
description: Specialized guidelines for specific contexts
globs: *.py
---
# Supplemental Guidelines
## 1. Advanced Security Practices
- **Detailed Security Practices**: Specific examples or best practices (e.g., handling dependencies, securing API keys).
- **Incident Documentation**: Process for documenting and learning from security incidents in [security.md](mdc:.notes/security.md) in [security.md](mdc:.notes/security.md)
## 2. Team Collaboration and Process
- **Roles and Responsibilities**: Define who is responsible for what (e.g., code quality monitoring, rule updates).
- **Feedback Loop**: Specify the process for team members to suggest changes or improvements directly (e.g., code review, sprint retrospective).
- **Terminology**: Define the project's terminology in [glossary.md](mdc:.notes/glossary.md) to help newcomers to understand complex parts of it.
## 3. Continuous Improvement Loop
1. **Observe**: Monitor code patterns, track issues, and collect relevant metrics.
2. **Learn**: Update documentation, create new patterns, and improve guidelines based on observations.
3. **Adapt**: Update rules and processes to incorporate new insights and improvements.
4. **Document**: Maintain and update relevant markdown files to reflect changes and new knowledge.
"""
}
def create_notes_structure(tiers, overwrite=False):
"""Create project documentation structure with tiered rules"""
os.makedirs('.notes', exist_ok=True)
os.makedirs('.cursor/rules', exist_ok=True)
# Create base documentation files
for name, content in BASE_TEMPLATES.items():
file_path = f'.notes/{name}.md'
if os.path.exists(file_path) and not overwrite:
logging.info(f"Skipped {file_path} as it already exists (use --overwrite to force update)")
else:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(content)
logging.info(f"Created/Updated {file_path}")
current_date = datetime.now().strftime("%Y-%m-%d")
# Create selected rule tiers
for tier in tiers:
filename = f'.cursor/rules/{tier}_guidelines.mdc'
template = RULE_TEMPLATES.get(tier, '')
if template:
content = template.format(version=VERSION, date=current_date)
if os.path.exists(filename) and not overwrite:
logging.info(f"Skipped {filename} as it already exists (use --overwrite to force update)")
else:
with open(filename, 'w', encoding='utf-8') as f:
f.write(content)
logging.info(f"Created/Updated {filename}")
# Create main rules index
main_rules = f"""---
description: Central index for project rules
globs: *.py
---
# Project Rules Index
## Available Guidelines
{chr(10).join(f"- [{tier.title()} Guidelines](.cursor/rules/{tier}_guidelines.mdc)" for tier in tiers)}
## Usage Guide
- All projects: Start with Core guidelines
- Production systems: Add Advanced guidelines
- Special requirements: Include Supplemental guidelines
## Version History
- {VERSION} ({current_date}): Initial version
"""
main_index = '.cursor/rules/main_index.mdc'
if os.path.exists(main_index) and not overwrite:
logging.info("Skipped rule index file (use --overwrite to force update)")
else:
with open(main_index, 'w', encoding='utf-8') as f:
f.write(main_rules)
logging.info("Created/Updated rule index file")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Create project documentation structure',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python create_cursor_rules.py core
python create_cursor_rules.py core advanced
python create_cursor_rules.py core advanced supplemental
"""
)
# Remove choices and set default as None; we do our own validation below.
parser.add_argument("tiers", nargs="*", default=None,
help="Rule tiers to create (core, advanced, supplemental)")
parser.add_argument("--overwrite", "-f", action="store_true",
help="Overwrite existing files if they exist")
args = parser.parse_args()
allowed_tiers = ["core", "advanced", "supplemental"]
if not args.tiers or len(args.tiers) == 0:
args.tiers = ["core"]
else:
for tier in args.tiers:
if tier not in allowed_tiers:
parser.error(f"invalid tier: {tier}. Choose from {allowed_tiers}")
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
create_notes_structure(args.tiers, overwrite=args.overwrite)
logging.info("Documentation structure created successfully")