blue-beatle
Version:
๐ค AI-Powered Development Assistant - Intelligent code analysis, problem solving, and terminal automation using Gemini API
1,038 lines (892 loc) โข 35.2 kB
JavaScript
/**
* ๐ Project Manager - Intelligent project management and automation
* Handles project initialization, setup, deployment, and testing
*/
const fs = require('fs-extra');
const path = require('path');
const chalk = require('chalk');
const ora = require('ora');
const inquirer = require('inquirer');
const { execSync } = require('child_process');
class ProjectManager {
constructor() {
this.projectTemplates = {
'react': {
name: 'React Application',
description: 'Modern React app with TypeScript and Vite',
commands: [
'npm create vite@latest . -- --template react-ts',
'npm install',
'npm install -D @types/node'
],
files: {
'.env.example': 'VITE_API_URL=http://localhost:3000\nVITE_APP_NAME=My React App',
'README.md': '# React Application\n\nCreated with Blue Beatle AI Assistant'
}
},
'node': {
name: 'Node.js Application',
description: 'Express.js API with TypeScript',
commands: [
'npm init -y',
'npm install express cors helmet morgan',
'npm install -D @types/node @types/express typescript ts-node nodemon'
],
files: {
'src/index.ts': `import express from 'express';\nimport cors from 'cors';\n\nconst app = express();\nconst PORT = process.env.PORT || 3000;\n\napp.use(cors());\napp.use(express.json());\n\napp.get('/', (req, res) => {\n res.json({ message: 'Hello from Blue Beatle!' });\n});\n\napp.listen(PORT, () => {\n console.log(\`Server running on port \${PORT}\`);\n});`,
'tsconfig.json': '{\n "compilerOptions": {\n "target": "ES2020",\n "module": "commonjs",\n "outDir": "./dist",\n "rootDir": "./src",\n "strict": true,\n "esModuleInterop": true\n }\n}'
}
},
'python': {
name: 'Python Application',
description: 'Python project with FastAPI',
commands: [
'python -m venv venv',
'pip install fastapi uvicorn python-dotenv',
'pip freeze > requirements.txt'
],
files: {
'main.py': `from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI(title="Blue Beatle Python API")\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=["*"],\n allow_methods=["*"],\n allow_headers=["*"],\n)\n\n@app.get("/")\ndef read_root():\n return {"message": "Hello from Blue Beatle Python API!"}\n\nif __name__ == "__main__":\n import uvicorn\n uvicorn.run(app, host="0.0.0.0", port=8000)`,
'.env.example': 'DATABASE_URL=sqlite:///./app.db\nSECRET_KEY=your-secret-key-here'
}
},
'vue': {
name: 'Vue.js Application',
description: 'Vue 3 app with TypeScript and Vite',
commands: [
'npm create vue@latest . -- --typescript --router --pinia',
'npm install'
],
files: {}
},
'angular': {
name: 'Angular Application',
description: 'Angular app with TypeScript',
commands: [
'npx @angular/cli new . --routing --style=scss --skip-git',
'npm install'
],
files: {}
},
'rust': {
name: 'Rust Application',
description: 'Rust project with Cargo',
commands: [
'cargo init .',
'cargo add tokio --features full',
'cargo add serde --features derive'
],
files: {
'src/main.rs': `use std::io;\n\nfn main() {\n println!("Hello from Blue Beatle Rust project!");\n \n let mut input = String::new();\n println!("Enter your name:");\n io::stdin().read_line(&mut input).expect("Failed to read line");\n \n println!("Hello, {}!", input.trim());\n}`
}
},
'go': {
name: 'Go Application',
description: 'Go project with modules',
commands: [
'go mod init macadida-project',
'go get github.com/gin-gonic/gin'
],
files: {
'main.go': `package main\n\nimport (\n\t"net/http"\n\t"github.com/gin-gonic/gin"\n)\n\nfunc main() {\n\tr := gin.Default()\n\t\n\tr.GET("/", func(c *gin.Context) {\n\t\tc.JSON(http.StatusOK, gin.H{\n\t\t\t"message": "Hello from Blue Beatle Go API!",\n\t\t})\n\t})\n\t\n\tr.Run(":8080")\n}`
}
}
};
this.deploymentTargets = {
'vercel': {
name: 'Vercel',
description: 'Deploy to Vercel platform',
commands: ['npx vercel --prod'],
requirements: ['package.json']
},
'netlify': {
name: 'Netlify',
description: 'Deploy to Netlify platform',
commands: ['npx netlify deploy --prod'],
requirements: ['package.json']
},
'heroku': {
name: 'Heroku',
description: 'Deploy to Heroku platform',
commands: [
'heroku create',
'git push heroku main'
],
requirements: ['package.json', '.git']
},
'docker': {
name: 'Docker',
description: 'Build and run Docker container',
commands: [
'docker build -t macadida-app .',
'docker run -p 3000:3000 macadida-app'
],
requirements: ['Dockerfile']
}
};
}
async manage(options = {}) {
if (options.init) {
await this.initializeProject();
} else if (options.setup) {
await this.setupProject(options.setup);
} else if (options.deploy) {
await this.deployProject();
} else if (options.test) {
await this.runTests();
} else {
await this.showProjectMenu();
}
}
async showProjectMenu() {
console.log(chalk.cyan('๐ Project Management Menu\n'));
const { action } = await inquirer.prompt([{
type: 'list',
name: 'action',
message: 'What would you like to do?',
choices: [
{ name: '๐ Initialize new project', value: 'init' },
{ name: 'โ๏ธ Setup existing project', value: 'setup' },
{ name: '๐งช Run tests', value: 'test' },
{ name: '๐ Deploy project', value: 'deploy' },
{ name: '๐ Project analysis', value: 'analyze' },
{ name: '๐ง Project maintenance', value: 'maintain' },
{ name: '๐ Generate documentation', value: 'docs' },
{ name: '๐ Update dependencies', value: 'update' },
{ name: 'โ Exit', value: 'exit' }
]
}]);
switch (action) {
case 'init':
await this.initializeProject();
break;
case 'setup':
await this.setupExistingProject();
break;
case 'test':
await this.runTests();
break;
case 'deploy':
await this.deployProject();
break;
case 'analyze':
await this.analyzeProject();
break;
case 'maintain':
await this.maintainProject();
break;
case 'docs':
await this.generateDocumentation();
break;
case 'update':
await this.updateDependencies();
break;
case 'exit':
console.log(chalk.yellow('๐ Goodbye!'));
break;
}
}
async initializeProject() {
console.log(chalk.cyan('๐ Initialize New Project\n'));
// Get project details
const projectInfo = await inquirer.prompt([
{
type: 'input',
name: 'name',
message: 'Project name:',
validate: input => input.trim() ? true : 'Project name is required'
},
{
type: 'input',
name: 'description',
message: 'Project description:',
default: 'A project created with Blue Beatle AI Assistant'
},
{
type: 'list',
name: 'type',
message: 'Project type:',
choices: Object.entries(this.projectTemplates).map(([key, template]) => ({
name: `${template.name} - ${template.description}`,
value: key
}))
},
{
type: 'confirm',
name: 'git',
message: 'Initialize Git repository?',
default: true
},
{
type: 'confirm',
name: 'createDir',
message: 'Create project in new directory?',
default: true
}
]);
// Create project directory if requested
let projectPath = process.cwd();
if (projectInfo.createDir) {
projectPath = path.join(process.cwd(), projectInfo.name);
await fs.ensureDir(projectPath);
process.chdir(projectPath);
}
const spinner = ora('๐ง Setting up project...').start();
try {
// Initialize Git if requested
if (projectInfo.git) {
execSync('git init', { stdio: 'ignore' });
spinner.text = 'Git repository initialized...';
}
// Setup project based on type
await this.setupProject(projectInfo.type, projectInfo);
spinner.stop();
console.log(chalk.green(`โ
Project "${projectInfo.name}" created successfully!`));
console.log(chalk.cyan(`๐ Location: ${projectPath}`));
// Show next steps
await this.showNextSteps(projectInfo.type);
} catch (error) {
spinner.stop();
console.error(chalk.red('โ Project initialization failed:'), error.message);
}
}
async setupProject(projectType, projectInfo = {}) {
const template = this.projectTemplates[projectType];
if (!template) {
console.error(chalk.red(`โ Unknown project type: ${projectType}`));
return;
}
console.log(chalk.cyan(`โ๏ธ Setting up ${template.name}...\n`));
const spinner = ora('Installing dependencies...').start();
try {
// Run setup commands
for (const command of template.commands) {
spinner.text = `Running: ${command}`;
execSync(command, { stdio: 'ignore' });
}
// Create template files
for (const [filePath, content] of Object.entries(template.files)) {
await fs.ensureDir(path.dirname(filePath));
await fs.writeFile(filePath, content);
}
// Create additional project files
await this.createProjectFiles(projectType, projectInfo);
spinner.stop();
console.log(chalk.green(`โ
${template.name} setup completed!`));
} catch (error) {
spinner.stop();
console.error(chalk.red('โ Setup failed:'), error.message);
throw error;
}
}
async createProjectFiles(projectType, projectInfo) {
// Create .gitignore
const gitignoreContent = this.getGitignoreContent(projectType);
await fs.writeFile('.gitignore', gitignoreContent);
// Create README.md if it doesn't exist
if (!await fs.pathExists('README.md')) {
const readmeContent = this.generateReadme(projectInfo, projectType);
await fs.writeFile('README.md', readmeContent);
}
// Create package.json scripts for Node.js projects
if (['react', 'node', 'vue', 'angular'].includes(projectType)) {
await this.updatePackageJsonScripts(projectType);
}
// Create Docker files if applicable
if (projectType === 'node' || projectType === 'react') {
await this.createDockerFiles(projectType);
}
}
getGitignoreContent(projectType) {
const common = `# Dependencies
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Logs
logs
*.log
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Coverage directory used by tools like istanbul
coverage/
*.lcov
# Build outputs
dist/
build/
`;
const specific = {
'python': `
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
env/
venv/
ENV/
env.bak/
venv.bak/
.pytest_cache/
`,
'rust': `
# Rust
target/
Cargo.lock
`,
'go': `
# Go
*.exe
*.exe~
*.dll
*.so
*.dylib
*.test
*.out
go.work
`,
'java': `
# Java
*.class
*.jar
*.war
*.ear
*.nar
hs_err_pid*
target/
`
};
return common + (specific[projectType] || '');
}
generateReadme(projectInfo, projectType) {
const template = this.projectTemplates[projectType];
return `# ${projectInfo.name || 'Project'}
${projectInfo.description || 'A project created with Blue Beatle AI Assistant'}
## Technology Stack
- **Type:** ${template.name}
- **Created:** ${new Date().toLocaleDateString()}
- **Created with:** Blue Beatle AI Assistant
## Getting Started
### Prerequisites
Make sure you have the following installed:
${this.getPrerequisites(projectType)}
### Installation
1. Clone the repository
\`\`\`bash
git clone <repository-url>
cd ${projectInfo.name || 'project'}
\`\`\`
2. Install dependencies
\`\`\`bash
${this.getInstallCommand(projectType)}
\`\`\`
3. Start the development server
\`\`\`bash
${this.getStartCommand(projectType)}
\`\`\`
## Available Scripts
${this.getAvailableScripts(projectType)}
## Project Structure
\`\`\`
${this.getProjectStructure(projectType)}
\`\`\`
## Contributing
1. Fork the repository
2. Create your feature branch (\`git checkout -b feature/amazing-feature\`)
3. Commit your changes (\`git commit -m 'Add some amazing feature'\`)
4. Push to the branch (\`git push origin feature/amazing-feature\`)
5. Open a Pull Request
## License
This project is licensed under the MIT License.
---
*Generated with โค๏ธ by Blue Beatle AI Assistant*
`;
}
getPrerequisites(projectType) {
const prereqs = {
'react': '- Node.js (v16 or higher)\n- npm or yarn',
'node': '- Node.js (v16 or higher)\n- npm or yarn',
'vue': '- Node.js (v16 or higher)\n- npm or yarn',
'angular': '- Node.js (v16 or higher)\n- Angular CLI',
'python': '- Python (v3.8 or higher)\n- pip',
'rust': '- Rust (latest stable)\n- Cargo',
'go': '- Go (v1.19 or higher)',
'java': '- Java JDK (v11 or higher)\n- Maven or Gradle'
};
return prereqs[projectType] || '- Check project documentation';
}
getInstallCommand(projectType) {
const commands = {
'react': 'npm install',
'node': 'npm install',
'vue': 'npm install',
'angular': 'npm install',
'python': 'pip install -r requirements.txt',
'rust': 'cargo build',
'go': 'go mod download',
'java': 'mvn install'
};
return commands[projectType] || 'npm install';
}
getStartCommand(projectType) {
const commands = {
'react': 'npm run dev',
'node': 'npm run dev',
'vue': 'npm run dev',
'angular': 'ng serve',
'python': 'python main.py',
'rust': 'cargo run',
'go': 'go run main.go',
'java': 'mvn spring-boot:run'
};
return commands[projectType] || 'npm start';
}
getAvailableScripts(projectType) {
const scripts = {
'react': '- `npm run dev` - Start development server\n- `npm run build` - Build for production\n- `npm run preview` - Preview production build',
'node': '- `npm run dev` - Start development server\n- `npm run build` - Build TypeScript\n- `npm start` - Start production server',
'python': '- `python main.py` - Start the application\n- `pytest` - Run tests\n- `pip freeze > requirements.txt` - Update dependencies',
'rust': '- `cargo run` - Run the application\n- `cargo build` - Build the project\n- `cargo test` - Run tests',
'go': '- `go run main.go` - Run the application\n- `go build` - Build the project\n- `go test` - Run tests'
};
return scripts[projectType] || 'Check package.json for available scripts';
}
getProjectStructure(projectType) {
const structures = {
'react': `src/
โโโ components/
โโโ pages/
โโโ hooks/
โโโ utils/
โโโ styles/
โโโ App.tsx
public/
package.json
vite.config.ts`,
'node': `src/
โโโ routes/
โโโ middleware/
โโโ models/
โโโ controllers/
โโโ utils/
โโโ index.ts
package.json
tsconfig.json`,
'python': `main.py
requirements.txt
.env.example
README.md`,
'rust': `src/
โโโ main.rs
โโโ lib.rs
Cargo.toml
README.md`
};
return structures[projectType] || 'Project structure varies by type';
}
async updatePackageJsonScripts(projectType) {
try {
const pkgPath = path.join(process.cwd(), 'package.json');
if (await fs.pathExists(pkgPath)) {
const pkg = await fs.readJson(pkgPath);
const additionalScripts = {
'node': {
'dev': 'nodemon src/index.ts',
'build': 'tsc',
'start': 'node dist/index.js',
'test': 'jest'
},
'react': {
'lint': 'eslint src --ext .ts,.tsx',
'lint:fix': 'eslint src --ext .ts,.tsx --fix',
'type-check': 'tsc --noEmit'
}
};
if (additionalScripts[projectType]) {
pkg.scripts = { ...pkg.scripts, ...additionalScripts[projectType] };
await fs.writeJson(pkgPath, pkg, { spaces: 2 });
}
}
} catch (error) {
console.error(chalk.yellow('โ ๏ธ Could not update package.json scripts:'), error.message);
}
}
async createDockerFiles(projectType) {
const dockerfileContent = this.getDockerfileContent(projectType);
await fs.writeFile('Dockerfile', dockerfileContent);
const dockerignoreContent = `node_modules
npm-debug.log
.git
.gitignore
README.md
.env
.nyc_output
coverage
.vscode`;
await fs.writeFile('.dockerignore', dockerignoreContent);
}
getDockerfileContent(projectType) {
if (projectType === 'node') {
return `FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]`;
}
if (projectType === 'react') {
return `FROM node:18-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]`;
}
return '';
}
async showNextSteps(projectType) {
console.log(chalk.cyan('\n๐ฏ Next Steps:\n'));
const nextSteps = {
'react': [
'Start the development server: npm run dev',
'Open http://localhost:5173 in your browser',
'Edit src/App.tsx to start building your app',
'Add components in the src/components directory'
],
'node': [
'Start the development server: npm run dev',
'Test the API at http://localhost:3000',
'Add routes in the src/routes directory',
'Configure your database connection'
],
'python': [
'Activate virtual environment: source venv/bin/activate (Linux/Mac) or venv\\Scripts\\activate (Windows)',
'Start the server: python main.py',
'Visit http://localhost:8000 to see your API',
'Check http://localhost:8000/docs for API documentation'
]
};
const steps = nextSteps[projectType] || [
'Follow the README.md instructions',
'Start building your application',
'Run tests to ensure everything works'
];
steps.forEach((step, index) => {
console.log(chalk.blue(`${index + 1}. ${step}`));
});
console.log(chalk.green('\n๐ Happy coding with Blue Beatle!'));
}
async setupExistingProject() {
console.log(chalk.cyan('โ๏ธ Setup Existing Project\n'));
// Detect project type
const detectedType = await this.detectProjectType();
if (detectedType) {
console.log(chalk.green(`โ
Detected project type: ${this.projectTemplates[detectedType].name}`));
const { confirm } = await inquirer.prompt([{
type: 'confirm',
name: 'confirm',
message: `Setup as ${this.projectTemplates[detectedType].name}?`,
default: true
}]);
if (confirm) {
await this.setupProject(detectedType);
}
} else {
console.log(chalk.yellow('โ ๏ธ Could not detect project type automatically.'));
const { projectType } = await inquirer.prompt([{
type: 'list',
name: 'projectType',
message: 'Select project type:',
choices: Object.entries(this.projectTemplates).map(([key, template]) => ({
name: template.name,
value: key
}))
}]);
await this.setupProject(projectType);
}
}
async detectProjectType() {
const cwd = process.cwd();
if (await fs.pathExists(path.join(cwd, 'package.json'))) {
const pkg = await fs.readJson(path.join(cwd, 'package.json'));
if (pkg.dependencies?.react) return 'react';
if (pkg.dependencies?.vue) return 'vue';
if (pkg.dependencies?.['@angular/core']) return 'angular';
if (pkg.dependencies?.express) return 'node';
return 'node'; // Default for Node.js projects
}
if (await fs.pathExists(path.join(cwd, 'requirements.txt')) ||
await fs.pathExists(path.join(cwd, 'pyproject.toml'))) {
return 'python';
}
if (await fs.pathExists(path.join(cwd, 'Cargo.toml'))) return 'rust';
if (await fs.pathExists(path.join(cwd, 'go.mod'))) return 'go';
if (await fs.pathExists(path.join(cwd, 'pom.xml'))) return 'java';
return null;
}
async runTests() {
console.log(chalk.cyan('๐งช Running Tests\n'));
const projectType = await this.detectProjectType();
const spinner = ora('Running tests...').start();
try {
let testCommand;
switch (projectType) {
case 'react':
case 'node':
case 'vue':
case 'angular':
testCommand = 'npm test';
break;
case 'python':
testCommand = 'pytest';
break;
case 'rust':
testCommand = 'cargo test';
break;
case 'go':
testCommand = 'go test ./...';
break;
case 'java':
testCommand = 'mvn test';
break;
default:
throw new Error('Unknown project type for testing');
}
const result = execSync(testCommand, { encoding: 'utf8' });
spinner.stop();
console.log(chalk.green('โ
Tests completed successfully!'));
console.log(result);
} catch (error) {
spinner.stop();
console.error(chalk.red('โ Tests failed:'), error.message);
}
}
async deployProject() {
console.log(chalk.cyan('๐ Deploy Project\n'));
const { target } = await inquirer.prompt([{
type: 'list',
name: 'target',
message: 'Select deployment target:',
choices: Object.entries(this.deploymentTargets).map(([key, target]) => ({
name: `${target.name} - ${target.description}`,
value: key
}))
}]);
const deployTarget = this.deploymentTargets[target];
// Check requirements
const missingRequirements = [];
for (const req of deployTarget.requirements) {
if (!await fs.pathExists(req)) {
missingRequirements.push(req);
}
}
if (missingRequirements.length > 0) {
console.log(chalk.red(`โ Missing requirements: ${missingRequirements.join(', ')}`));
return;
}
const spinner = ora(`Deploying to ${deployTarget.name}...`).start();
try {
for (const command of deployTarget.commands) {
spinner.text = `Running: ${command}`;
execSync(command, { stdio: 'inherit' });
}
spinner.stop();
console.log(chalk.green(`โ
Successfully deployed to ${deployTarget.name}!`));
} catch (error) {
spinner.stop();
console.error(chalk.red('โ Deployment failed:'), error.message);
}
}
async analyzeProject() {
console.log(chalk.cyan('๐ Project Analysis\n'));
const analysis = {
type: await this.detectProjectType(),
files: 0,
lines: 0,
dependencies: 0,
size: 0
};
// Count files and lines
const files = await this.getProjectFiles();
analysis.files = files.length;
for (const file of files) {
try {
const content = await fs.readFile(file, 'utf8');
analysis.lines += content.split('\n').length;
analysis.size += content.length;
} catch (error) {
// Skip files that can't be read
}
}
// Count dependencies
if (await fs.pathExists('package.json')) {
const pkg = await fs.readJson('package.json');
analysis.dependencies = Object.keys(pkg.dependencies || {}).length +
Object.keys(pkg.devDependencies || {}).length;
}
// Display analysis
console.log(chalk.blue('๐ Project Statistics:'));
console.log(chalk.gray(` Type: ${analysis.type || 'Unknown'}`));
console.log(chalk.gray(` Files: ${analysis.files}`));
console.log(chalk.gray(` Lines of code: ${analysis.lines.toLocaleString()}`));
console.log(chalk.gray(` Dependencies: ${analysis.dependencies}`));
console.log(chalk.gray(` Size: ${(analysis.size / 1024).toFixed(2)} KB`));
}
async getProjectFiles() {
const files = [];
const extensions = ['.js', '.ts', '.jsx', '.tsx', '.py', '.java', '.cpp', '.c', '.go', '.rs'];
const walkDir = async (dir) => {
const items = await fs.readdir(dir);
for (const item of items) {
if (item.startsWith('.') || item === 'node_modules') continue;
const fullPath = path.join(dir, item);
const stat = await fs.stat(fullPath);
if (stat.isDirectory()) {
await walkDir(fullPath);
} else if (extensions.some(ext => item.endsWith(ext))) {
files.push(fullPath);
}
}
};
await walkDir(process.cwd());
return files;
}
async maintainProject() {
console.log(chalk.cyan('๐ง Project Maintenance\n'));
const { tasks } = await inquirer.prompt([{
type: 'checkbox',
name: 'tasks',
message: 'Select maintenance tasks:',
choices: [
{ name: 'Update dependencies', value: 'update' },
{ name: 'Clean build artifacts', value: 'clean' },
{ name: 'Run security audit', value: 'audit' },
{ name: 'Optimize package.json', value: 'optimize' },
{ name: 'Generate .gitignore', value: 'gitignore' },
{ name: 'Update README', value: 'readme' }
]
}]);
for (const task of tasks) {
await this.runMaintenanceTask(task);
}
}
async runMaintenanceTask(task) {
const spinner = ora(`Running ${task}...`).start();
try {
switch (task) {
case 'update':
await this.updateDependencies();
break;
case 'clean':
await this.cleanBuildArtifacts();
break;
case 'audit':
execSync('npm audit', { stdio: 'inherit' });
break;
case 'optimize':
await this.optimizePackageJson();
break;
case 'gitignore':
const projectType = await this.detectProjectType();
const gitignoreContent = this.getGitignoreContent(projectType);
await fs.writeFile('.gitignore', gitignoreContent);
break;
case 'readme':
// Could regenerate README with current project state
break;
}
spinner.stop();
console.log(chalk.green(`โ
${task} completed`));
} catch (error) {
spinner.stop();
console.error(chalk.red(`โ ${task} failed:`), error.message);
}
}
async updateDependencies() {
const projectType = await this.detectProjectType();
switch (projectType) {
case 'react':
case 'node':
case 'vue':
case 'angular':
execSync('npm update', { stdio: 'inherit' });
break;
case 'python':
execSync('pip install --upgrade -r requirements.txt', { stdio: 'inherit' });
break;
case 'rust':
execSync('cargo update', { stdio: 'inherit' });
break;
case 'go':
execSync('go get -u ./...', { stdio: 'inherit' });
break;
}
}
async cleanBuildArtifacts() {
const artifactDirs = ['dist', 'build', 'target', '__pycache__', '.pytest_cache', 'node_modules/.cache'];
for (const dir of artifactDirs) {
if (await fs.pathExists(dir)) {
await fs.remove(dir);
console.log(chalk.gray(` Removed ${dir}`));
}
}
}
async optimizePackageJson() {
const pkgPath = 'package.json';
if (await fs.pathExists(pkgPath)) {
const pkg = await fs.readJson(pkgPath);
// Sort dependencies
if (pkg.dependencies) {
const sorted = {};
Object.keys(pkg.dependencies).sort().forEach(key => {
sorted[key] = pkg.dependencies[key];
});
pkg.dependencies = sorted;
}
if (pkg.devDependencies) {
const sorted = {};
Object.keys(pkg.devDependencies).sort().forEach(key => {
sorted[key] = pkg.devDependencies[key];
});
pkg.devDependencies = sorted;
}
await fs.writeJson(pkgPath, pkg, { spaces: 2 });
}
}
async generateDocumentation() {
console.log(chalk.cyan('๐ Generating Documentation\n'));
const projectType = await this.detectProjectType();
// This could integrate with documentation generators
console.log(chalk.blue('Documentation generation would include:'));
console.log(chalk.gray('- API documentation'));
console.log(chalk.gray('- Code comments analysis'));
console.log(chalk.gray('- Usage examples'));
console.log(chalk.gray('- Architecture diagrams'));
console.log(chalk.yellow('๐ก Consider using tools like JSDoc, Sphinx, or rustdoc'));
}
}
module.exports = ProjectManager;