-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2151 lines (1716 loc) · 69 KB
/
app.py
File metadata and controls
2151 lines (1716 loc) · 69 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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Documentation.AI - Clean Backend Implementation
A comprehensive documentation generator using AI for GitHub repositories.
"""
import os
import json
import logging
import tempfile
import shutil
import zipfile
from datetime import datetime
from typing import Dict, List, Any, Optional
from pathlib import Path
import sys
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
from dotenv import load_dotenv
import requests
import re
from urllib.parse import urlparse
import traceback
# Add the current directory to Python path for importing ai_models
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Import AI models
try:
from ai_models.github_analyzer import GitHubAnalyzer as GitHubAnalyzerModel
from ai_models.documentation_generator import DocumentationGenerator as DocumentationGeneratorModel
from ai_models.rag_pipeline import RAGPipeline as RAGPipelineModel
logger = logging.getLogger(__name__)
logger.info("AI models imported successfully")
except ImportError as e:
logger = logging.getLogger(__name__)
logger.error(f"Failed to import AI models: {e}")
logger.error(traceback.format_exc())
# Define dummy classes as fallback
class GitHubAnalyzer:
def __init__(self):
self.github_token = os.getenv('GITHUB_TOKEN')
def parse_github_url(self, repo_url: str) -> Dict[str, str]:
return {'owner': 'dummy', 'repo': 'dummy'}
def analyze_repository(self, repo_url: str) -> Dict[str, Any]:
raise Exception("AI models not available - import failed")
class DummyDocumentationGenerator:
def generate_documentation(self, analysis_result: Dict[str, Any], rag_result: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
raise Exception("AI models not available - import failed")
class RAGPipeline:
def process(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
raise Exception("AI models not available - import failed")
def process_repository(self, analysis_result: Dict[str, Any]) -> Dict[str, Any]:
raise Exception("AI models not available - import failed")
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__)
# Configuration
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev-secret-key-documentation-ai-2024')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///documentation_ai.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file upload
# Initialize extensions
CORS(app, origins=["http://localhost:3000", "http://localhost:5000", "http://127.0.0.1:3000"])
db = SQLAlchemy(app)
# Configure logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('backend.log', mode='a')
]
)
logger = logging.getLogger(__name__)
# Set Flask's logger to DEBUG as well
app.logger.setLevel(logging.DEBUG)
# Database Models
class AnalysisJob(db.Model):
"""Model for storing repository analysis jobs"""
__tablename__ = 'analysis_jobs'
id = db.Column(db.Integer, primary_key=True)
repo_url = db.Column(db.String(500), nullable=False)
repo_name = db.Column(db.String(200))
repo_owner = db.Column(db.String(100))
status = db.Column(db.String(50), default='pending') # pending, processing, completed, failed
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
result = db.Column(db.Text) # JSON string containing the generated documentation
error_message = db.Column(db.Text)
def __repr__(self):
return f'<AnalysisJob {self.id}: {self.repo_url}>'
def to_dict(self):
"""Convert the job to a dictionary"""
return {
'id': self.id,
'repo_url': self.repo_url,
'repo_name': self.repo_name,
'repo_owner': self.repo_owner,
'status': self.status,
'created_at': self.created_at.isoformat(),
'updated_at': self.updated_at.isoformat(),
'result': json.loads(self.result) if self.result else None,
'error_message': self.error_message
}
# GitHub Repository Analyzer
class GitHubRepositoryAnalyzer:
"""Clean implementation of GitHub repository analyzer"""
def __init__(self):
self.github_token = os.getenv('GITHUB_TOKEN')
self.session = requests.Session()
if self.github_token:
self.session.headers.update({
'Authorization': f'token {self.github_token}',
'Accept': 'application/vnd.github.v3+json'
})
def parse_github_url(self, repo_url: str) -> Dict[str, str]:
"""Parse GitHub repository URL to extract owner and repo name"""
repo_url = repo_url.strip().rstrip('/')
# Handle different GitHub URL formats
patterns = [
r'https://github\.com/([^/]+)/([^/]+)(?:\.git)?/?$',
r'git@github\.com:([^/]+)/([^/]+)\.git$',
r'github\.com/([^/]+)/([^/]+)/?$'
]
for pattern in patterns:
match = re.match(pattern, repo_url)
if match:
owner, repo = match.groups()
# Remove .git suffix if present
repo = repo.replace('.git', '')
return {'owner': owner, 'repo': repo}
raise ValueError(f"Invalid GitHub repository URL: {repo_url}")
def get_repository_info(self, owner: str, repo: str) -> Dict[str, Any]:
"""Fetch repository information from GitHub API"""
try:
url = f"https://api.github.com/repos/{owner}/{repo}"
response = self.session.get(url)
if response.status_code == 404:
raise ValueError("Repository not found")
elif response.status_code != 200:
raise ValueError(f"GitHub API error: {response.status_code}")
return response.json()
except requests.RequestException as e:
logger.error(f"Error fetching repository info: {e}")
raise ValueError(f"Failed to fetch repository information: {str(e)}")
def get_file_tree(self, owner: str, repo: str, path: str = "") -> List[Dict[str, Any]]:
"""Get repository file tree"""
try:
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{path}"
response = self.session.get(url)
if response.status_code != 200:
return []
return response.json()
except Exception as e:
logger.error(f"Error fetching file tree: {e}")
return []
def analyze_repository(self, repo_url: str) -> Dict[str, Any]:
"""Analyze a GitHub repository and return comprehensive information"""
try:
# Parse URL
parsed = self.parse_github_url(repo_url)
owner, repo = parsed['owner'], parsed['repo']
# Get repository info
repo_info = self.get_repository_info(owner, repo)
# Get file structure
file_tree = self.get_file_tree(owner, repo)
# Analyze languages and technologies
languages = self._detect_languages(file_tree, owner, repo)
technologies = self._detect_technologies(file_tree, repo_info)
# Build analysis result
analysis_result = {
'repository_info': {
'name': repo_info.get('name'),
'full_name': repo_info.get('full_name'),
'description': repo_info.get('description', ''),
'html_url': repo_info.get('html_url'),
'clone_url': repo_info.get('clone_url'),
'language': repo_info.get('language'),
'stargazers_count': repo_info.get('stargazers_count', 0),
'forks_count': repo_info.get('forks_count', 0),
'open_issues_count': repo_info.get('open_issues_count', 0),
'created_at': repo_info.get('created_at'),
'updated_at': repo_info.get('updated_at'),
'license': repo_info.get('license', {}).get('name') if repo_info.get('license') else None,
'topics': repo_info.get('topics', [])
},
'file_structure': {
'total_files': len(file_tree),
'languages': languages,
'important_files': self._find_important_files(file_tree),
'directories': [f['name'] for f in file_tree if f['type'] == 'dir'],
'files': [f['name'] for f in file_tree if f['type'] == 'file']
},
'technologies': technologies,
'analysis_metadata': {
'analyzed_at': datetime.utcnow().isoformat(),
'analyzer_version': '2.0.0'
}
}
return analysis_result
except Exception as e:
logger.error(f"Error analyzing repository: {e}")
raise
def _detect_languages(self, file_tree: List[Dict], owner: str, repo: str) -> Dict[str, int]:
"""Detect programming languages in the repository"""
try:
url = f"https://api.github.com/repos/{owner}/{repo}/languages"
response = self.session.get(url)
if response.status_code == 200:
return response.json()
except Exception:
pass
# Fallback: detect from file extensions
language_map = {
'.py': 'Python', '.js': 'JavaScript', '.ts': 'TypeScript',
'.java': 'Java', '.cpp': 'C++', '.c': 'C', '.cs': 'C#',
'.php': 'PHP', '.rb': 'Ruby', '.go': 'Go', '.rs': 'Rust',
'.swift': 'Swift', '.kt': 'Kotlin', '.scala': 'Scala',
'.html': 'HTML', '.css': 'CSS', '.scss': 'SCSS'
}
languages = {}
for file_info in file_tree:
if file_info['type'] == 'file':
ext = Path(file_info['name']).suffix.lower()
if ext in language_map:
lang = language_map[ext]
languages[lang] = languages.get(lang, 0) + 1
return languages
def _detect_technologies(self, file_tree: List[Dict], repo_info: Dict) -> Dict[str, Any]:
"""Detect technologies and frameworks used"""
technologies = {
'frameworks': [],
'databases': [],
'tools': [],
'deployment': []
}
file_names = [f['name'].lower() for f in file_tree if f['type'] == 'file']
# Framework detection
if 'package.json' in file_names:
technologies['frameworks'].append('Node.js')
if 'requirements.txt' in file_names or 'setup.py' in file_names:
technologies['frameworks'].append('Python')
if 'composer.json' in file_names:
technologies['frameworks'].append('PHP')
if 'go.mod' in file_names:
technologies['frameworks'].append('Go')
if 'cargo.toml' in file_names:
technologies['frameworks'].append('Rust')
# Database detection
if any('sql' in name for name in file_names):
technologies['databases'].append('SQL Database')
if 'mongodb' in str(file_names):
technologies['databases'].append('MongoDB')
# Deployment detection
if 'dockerfile' in file_names:
technologies['deployment'].append('Docker')
if 'docker-compose.yml' in file_names or 'docker-compose.yaml' in file_names:
technologies['deployment'].append('Docker Compose')
if '.github' in [f['name'] for f in file_tree if f['type'] == 'dir']:
technologies['deployment'].append('GitHub Actions')
return technologies
def _find_important_files(self, file_tree: List[Dict]) -> List[str]:
"""Find important files in the repository"""
important_patterns = [
'readme.md', 'readme.txt', 'readme',
'license', 'license.txt', 'license.md',
'contributing.md', 'contributing.txt',
'changelog.md', 'changelog.txt', 'changelog',
'package.json', 'requirements.txt', 'setup.py',
'dockerfile', 'docker-compose.yml', 'docker-compose.yaml',
'makefile', 'cmake', '.gitignore'
]
important_files = []
for file_info in file_tree:
if file_info['type'] == 'file':
name = file_info['name'].lower()
if any(pattern in name for pattern in important_patterns):
important_files.append(file_info['name'])
return important_files
# Documentation Generator
class DocumentationGenerator:
"""Generate comprehensive documentation from repository analysis"""
def __init__(self):
self.template_path = Path(__file__).parent / 'templates'
def generate_documentation(self, analysis_result: Dict[str, Any], rag_result: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
"""Generate complete documentation package"""
try:
repo_info = analysis_result.get('repository_info', {})
file_structure = analysis_result.get('file_structure', {})
technologies = analysis_result.get('technologies', {})
documentation = {
'readme': self._generate_readme(repo_info, file_structure, technologies),
'api_docs': self._generate_api_documentation(repo_info, technologies),
'setup_guide': self._generate_setup_guide(repo_info, technologies),
'architecture_docs': self._generate_architecture_docs(repo_info, technologies),
'contributing_guide': self._generate_contributing_guide(repo_info),
'changelog': self._generate_changelog_template(repo_info),
'license': self._generate_license_file(repo_info),
'gitignore': self._generate_gitignore(technologies),
'dockerfile': self._generate_dockerfile(technologies),
'additional_files': {
'.github/workflows/ci.yml': self._generate_github_actions(technologies),
'docs/deployment.md': self._generate_deployment_guide(technologies),
'docs/troubleshooting.md': self._generate_troubleshooting_guide(technologies)
}
}
return documentation
except Exception as e:
logger.error(f"Error generating documentation: {e}")
raise
def _generate_readme(self, repo_info: Dict, file_structure: Dict, technologies: Dict) -> str:
"""Generate a comprehensive README.md file"""
project_name = repo_info.get('name', 'Project')
description = repo_info.get('description', 'A software project')
language = repo_info.get('language', 'Unknown')
readme_content = f"""# {project_name}
{description}
## 📋 Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Technology Stack](#technology-stack)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Usage](#usage)
- [API Documentation](#api-documentation)
- [Project Structure](#project-structure)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)
## 🔍 Overview
{description}
### Key Statistics
- **Primary Language**: {language}
- **Stars**: {repo_info.get('stargazers_count', 0)}
- **Forks**: {repo_info.get('forks_count', 0)}
- **Open Issues**: {repo_info.get('open_issues_count', 0)}
## ✨ Features
{self._generate_features_section(repo_info, technologies)}
## 🛠️ Technology Stack
{self._generate_technology_stack_section(file_structure, technologies)}
## 📋 Prerequisites
{self._generate_prerequisites_section(technologies)}
## 🚀 Installation
{self._generate_installation_section(technologies)}
## 💻 Usage
{self._generate_usage_section(technologies)}
## 📚 API Documentation
{self._generate_api_section(technologies)}
## 📁 Project Structure
```
{project_name}/
{self._generate_project_structure_tree(file_structure)}
```
## 🤝 Contributing
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## 📄 License
{self._generate_license_section(repo_info)}
## 🆘 Support
If you encounter any problems or have questions, please:
- Check the [documentation](docs/)
- Search [existing issues]({repo_info.get('html_url', '')}/issues)
- Create a [new issue]({repo_info.get('html_url', '')}/issues/new)
## 🙏 Acknowledgments
- Thanks to all contributors who have helped build this project
- Built with modern development practices and tools
---
Made with ❤️ by the {project_name} team
"""
return readme_content
def _generate_features_section(self, repo_info: Dict, technologies: Dict) -> str:
"""Generate features section based on detected technologies"""
features = []
frameworks = technologies.get('frameworks', [])
if 'Python' in frameworks:
features.append("- 🐍 **Python-based** - Built with Python for reliability and performance")
if 'Node.js' in frameworks:
features.append("- 🟢 **Node.js** - Fast and scalable JavaScript runtime")
if 'React' in str(technologies):
features.append("- ⚛️ **React** - Modern user interface framework")
if technologies.get('deployment'):
features.append("- 🐳 **Containerized** - Docker support for easy deployment")
features.append("- 📖 **Well Documented** - Comprehensive documentation and examples")
features.append("- 🧪 **Tested** - Automated testing for reliability")
features.append("- 🔧 **Configurable** - Flexible configuration options")
return "\n".join(features) if features else "- Feature documentation coming soon"
def _generate_technology_stack_section(self, file_structure: Dict, technologies: Dict) -> str:
"""Generate technology stack section"""
languages = file_structure.get('languages', {})
frameworks = technologies.get('frameworks', [])
databases = technologies.get('databases', [])
deployment = technologies.get('deployment', [])
stack_content = ""
if languages:
stack_content += "### Languages\n"
for lang, count in languages.items():
stack_content += f"- **{lang}**\n"
stack_content += "\n"
if frameworks:
stack_content += "### Frameworks & Libraries\n"
for framework in frameworks:
stack_content += f"- {framework}\n"
stack_content += "\n"
if databases:
stack_content += "### Databases\n"
for db in databases:
stack_content += f"- {db}\n"
stack_content += "\n"
if deployment:
stack_content += "### Deployment & DevOps\n"
for tool in deployment:
stack_content += f"- {tool}\n"
stack_content += "\n"
return stack_content or "Technology stack information will be updated soon."
def _generate_prerequisites_section(self, technologies: Dict) -> str:
"""Generate prerequisites section"""
prereqs = []
frameworks = technologies.get('frameworks', [])
if 'Python' in frameworks:
prereqs.append("- Python 3.8 or higher")
prereqs.append("- pip (Python package manager)")
if 'Node.js' in frameworks:
prereqs.append("- Node.js 16 or higher")
prereqs.append("- npm or yarn")
if 'Docker' in technologies.get('deployment', []):
prereqs.append("- Docker")
if 'Docker Compose' in technologies.get('deployment', []):
prereqs.append("- Docker Compose")
prereqs.append("- Git")
return "\n".join(prereqs) if prereqs else "- No specific prerequisites required"
def _generate_installation_section(self, technologies: Dict) -> str:
"""Generate installation instructions"""
frameworks = technologies.get('frameworks', [])
installation = "### Quick Start\n\n"
if 'Python' in frameworks:
installation += """```bash
# Clone the repository
git clone <repository-url>
cd <repository-name>
# Create virtual environment
python -m venv venv
source venv/bin/activate # On Windows: venv\\Scripts\\activate
# Install dependencies
pip install -r requirements.txt
# Run the application
python main.py
```
"""
if 'Node.js' in frameworks:
installation += """```bash
# Clone the repository
git clone <repository-url>
cd <repository-name>
# Install dependencies
npm install
# Start development server
npm start
```
"""
if 'Docker' in technologies.get('deployment', []):
installation += """### Using Docker
```bash
# Build and run with Docker
docker build -t project-name .
docker run -p 8000:8000 project-name
```
"""
if 'Docker Compose' in technologies.get('deployment', []):
installation += """```bash
# Or use Docker Compose
docker-compose up --build
```
"""
return installation
def _generate_usage_section(self, technologies: Dict) -> str:
"""Generate usage instructions"""
return """### Basic Usage
```bash
# Example usage commands will be documented here
# Add specific examples based on your project
```
### Configuration
Configuration options can be set through environment variables or configuration files.
### Examples
More detailed examples and tutorials coming soon!
"""
def _generate_api_section(self, technologies: Dict) -> str:
"""Generate API documentation section"""
frameworks = technologies.get('frameworks', [])
if any(web_framework in str(technologies) for web_framework in ['Flask', 'Django', 'Express', 'FastAPI']):
return """### API Endpoints
The application provides the following API endpoints:
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/health` | Health check endpoint |
| GET | `/api/docs` | API documentation |
For detailed API documentation, visit `/api/docs` when the server is running.
"""
return "API documentation will be added when API endpoints are implemented."
def _generate_project_structure_tree(self, file_structure: Dict) -> str:
"""Generate project structure tree"""
directories = file_structure.get('directories', [])
files = file_structure.get('files', [])
tree = ""
for directory in sorted(directories):
tree += f"├── {directory}/\n"
for file in sorted(files):
tree += f"├── {file}\n"
return tree or "└── (Project structure will be documented)"
def _generate_license_section(self, repo_info: Dict) -> str:
"""Generate license section"""
license_name = repo_info.get('license')
if license_name:
return f"This project is licensed under the {license_name} License - see the [LICENSE](LICENSE) file for details."
return "License information not available. Please check the repository for license details."
def _generate_api_documentation(self, repo_info: Dict, technologies: Dict) -> str:
"""Generate detailed API documentation"""
return f"""# API Documentation
## Overview
This document provides detailed information about the {repo_info.get('name', 'Project')} API.
## Base URL
```
http://localhost:8000/api
```
## Authentication
Authentication details will be documented here.
## Endpoints
### Health Check
```http
GET /health
```
Returns the health status of the API.
#### Response
```json
{{
"status": "healthy",
"timestamp": "2024-01-01T00:00:00Z"
}}
```
## Error Handling
The API uses standard HTTP status codes and returns error responses in the following format:
```json
{{
"error": "Error message",
"code": "ERROR_CODE",
"timestamp": "2024-01-01T00:00:00Z"
}}
```
## Rate Limiting
Rate limiting information will be documented here.
"""
def _generate_setup_guide(self, repo_info: Dict, technologies: Dict) -> str:
"""Generate setup guide"""
return f"""# Setup Guide
## Development Environment Setup
### System Requirements
{self._generate_prerequisites_section(technologies)}
### Step-by-Step Setup
{self._generate_installation_section(technologies)}
### Environment Variables
Create a `.env` file in the project root:
```env
# Add your environment variables here
DEBUG=true
PORT=8000
```
### Development Tools
Recommended development tools:
- IDE: VS Code, PyCharm, or your preferred editor
- Version Control: Git
- API Testing: Postman or curl
### Troubleshooting
Common setup issues and solutions will be documented here.
"""
def _generate_architecture_docs(self, repo_info: Dict, technologies: Dict) -> str:
"""Generate architecture documentation"""
return f"""# Architecture Documentation
## System Overview
{repo_info.get('description', 'System architecture documentation')}
## High-Level Architecture
```
[Client] <-> [API Gateway] <-> [Application Layer] <-> [Data Layer]
```
## Components
### Application Layer
- Core business logic
- API endpoints
- Request/response handling
### Data Layer
- Database interactions
- Data models
- Caching layer
## Design Patterns
Architecture patterns and design decisions will be documented here.
## Scalability Considerations
Scalability features and considerations will be documented here.
"""
def _generate_contributing_guide(self, repo_info: Dict) -> str:
"""Generate contributing guide"""
return f"""# Contributing to {repo_info.get('name', 'Project')}
We love your input! We want to make contributing to this project as easy and transparent as possible.
## Development Process
1. Fork the repo
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
## Code of Conduct
This project and everyone participating in it is governed by our Code of Conduct. By participating, you are expected to uphold this code.
## How Can I Contribute?
### Reporting Bugs
- Use the issue tracker to report bugs
- Include a clear description and steps to reproduce
- Add relevant labels and screenshots if applicable
### Suggesting Enhancements
- Use the issue tracker to suggest enhancements
- Provide a clear description of the enhancement
- Explain why this enhancement would be useful
### Pull Requests
- Fill in the required template
- Include appropriate tests
- Update documentation as needed
## Style Guidelines
### Git Commit Messages
- Use the present tense ("Add feature" not "Added feature")
- Use the imperative mood ("Move cursor to..." not "Moves cursor to...")
- Limit the first line to 72 characters or less
### Code Style
- Follow the existing code style
- Run linters and formatters before submitting
- Add comments for complex logic
## Testing
- Write tests for new features
- Ensure all tests pass before submitting PR
- Maintain test coverage
## Documentation
- Update README if needed
- Add docstrings for new functions/classes
- Update API documentation for new endpoints
"""
def _generate_changelog_template(self, repo_info: Dict) -> str:
"""Generate changelog template"""
return f"""# Changelog
All notable changes to {repo_info.get('name', 'this project')} will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- New features will be listed here
### Changed
- Changes to existing functionality will be listed here
### Deprecated
- Soon-to-be removed features will be listed here
### Removed
- Removed features will be listed here
### Fixed
- Bug fixes will be listed here
### Security
- Security fixes will be listed here
## [1.0.0] - {datetime.now().strftime('%Y-%m-%d')}
### Added
- Initial release
- Basic project structure
- Core functionality
---
## Template for new releases:
## [X.Y.Z] - YYYY-MM-DD
### Added
- New features
### Changed
- Changes to existing functionality
### Deprecated
- Soon-to-be removed features
### Removed
- Removed features
### Fixed
- Bug fixes
### Security
- Security fixes
"""
def _generate_license_file(self, repo_info: Dict) -> str:
"""Generate LICENSE file"""
license_name = repo_info.get('license', 'MIT')
current_year = datetime.now().year
if license_name == 'MIT':
return f"""MIT License
Copyright (c) {current_year} {repo_info.get('name', 'Project')}
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
return f"""# License
This project is licensed under the {license_name} License.
Please refer to the original repository for full license details.
"""
def _generate_gitignore(self, technologies: Dict) -> str:
"""Generate .gitignore file"""
frameworks = technologies.get('frameworks', [])
gitignore_content = "# Generated .gitignore\n\n"
if 'Python' in frameworks:
gitignore_content += """# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# Virtual Environment
venv/
env/
ENV/
"""
if 'Node.js' in frameworks:
gitignore_content += """# Node.js
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.npm
.eslintcache
"""
gitignore_content += """# IDEs
.vscode/
.idea/
*.swp
*.swo