Skip to content

Commit

Permalink
add AI snippet gen
Browse files Browse the repository at this point in the history
  • Loading branch information
PranavBarthwal committed Sep 13, 2024
1 parent afc1c41 commit 15a22bb
Show file tree
Hide file tree
Showing 4 changed files with 906 additions and 34 deletions.
81 changes: 66 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<img src="https://github.com/user-attachments/assets/1226438f-19e0-46e4-beff-5483e429ee69" width=200>

# Backend Generator CLI
> 🎉 **Now supporting code snippet generation!** 🚀
> **Now supporting AI powered code snippet generation!** 🚀
![npm](https://img.shields.io/npm/dt/backend-generator-cli?color=brightgreen&label=Total%20Downloads&style=for-the-badge) ![npm](https://img.shields.io/npm/dw/backend-generator-cli?color=blue&label=Weekly%20Downloads&style=for-the-badge)

Expand All @@ -12,8 +12,21 @@
- **Instant Backend Setup**: Generate a clean, well-organized backend project structure with a single command.
- **Best Practices Built-in**: The generated project follows industry-standard best practices for scalable backend development.
- **Custom Code Snippets**: Insert predefined code snippets such as API error handling, file uploading, and more using simple CLI commands.
- **AI-powered Custom Code Snippets**: Generate customizable code snippets using Generative AI with simple CLI commands.
- **Modular and Extensible**: The tool allows you to customize and expand the project structure to meet your specific needs.

## Index
- [Installation](#installation)
- [Commands](#commands)
- [1. run create-project](#1-run-create-project)
- [2. run generate-snippet](#2-run-generate-snippet-snippet-name)
- [3. run generate-ai-snippet](#3-run-generate-ai-snippet-snippetname)
- [Full User Journey Example](#full-user-journey-example)
- [Future Enhancements](#future-enhancements)
- [License](#license)

---

## Installation

To install the CLI globally, use `npm`:
Expand All @@ -24,16 +37,9 @@ npm install -g backend-generator-cli

After installation, you will have access to two main commands: `create-project` to generate the backend structure and `generate-snippet` to inject code snippets.

## Available Snippets

- **`async-ops-handler`**: Handles async operations with proper error handling.
- **`custom-api-error`**: Standardizes API error responses for your app.
- **`custom-api-response`**: Standardizes successful API responses.
- **`multer-file-upload`**: Sets up file upload handling using `multer`.

## Commands

### 1. `create-project`
### 1. `run create-project`
Generate a new backend project with a pre-configured folder structure:

```bash
Expand Down Expand Up @@ -64,7 +70,7 @@ This command will create a new backend project structure in your current directo

This structure is clean, easy to navigate, and ready to be extended with your own business logic and data models.

### 2. `generate-snippet <snippet-name>`
### 2. `run generate-snippet <snippet-name>`

Generate and inject predefined code snippets into your project. Snippets are placed in individual files in your current working directory.

Expand All @@ -78,7 +84,7 @@ This command will create a new file `multer-file-upload.js` in the current worki

### Available Snippets

1. **`async-ops-handler.js`**:
1. **`async-ops-handler`**:
Handles asynchronous operations with error handling.

**Code Snippet**:
Expand All @@ -94,7 +100,7 @@ This command will create a new file `multer-file-upload.js` in the current worki
export { asyncHandler }
```

2. **`custom-api-error.js`**:
2. **`custom-api-error`**:
Standardizes error responses for your API.

**Code Snippet**:
Expand Down Expand Up @@ -123,7 +129,7 @@ This command will create a new file `multer-file-upload.js` in the current worki
export { ApiError }
```

3. **`custom-api-response.js`**:
3. **`custom-api-response`**:
Standardizes successful API responses.

**Code Snippet**:
Expand All @@ -140,7 +146,7 @@ This command will create a new file `multer-file-upload.js` in the current worki
export {ApiResponse}
```

4. **`multer-file-upload.js`**:
4. **`multer-file-upload`**:
Sets up a file upload service using `multer`.

**Code Snippet**:
Expand All @@ -160,6 +166,51 @@ This command will create a new file `multer-file-upload.js` in the current worki

```

### 3. `run generate-ai-snippet <snippetName>`
With the new AI-powered code generation feature, you can generate customized code snippets. For instance, to generate a code snippet for a specific backend functionality, you can run:

```bash
run generate-ai-snippet <snippetName>
```

Example:

```bash
run generate-ai-snippet login-controller
```

This will generate a code snippet for login-controller using AI that looks like :
```bash
Generated Code Snippet for login-controller:

const User = require('../models/User');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');

module.exports.login = async (req, res) => {
try {
const { email, password } = req.body;

const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(401).json({ message: 'Invalid credentials' });
}

const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token, user: { _id: user._id, name: user.name, email: user.email } });
} catch (err) {
console.error(err);
res.status(500).json({ message: 'Server error' });
}
};

The code snippet is generated successfuly and may require some modifications to fit your use case.
```
## Full User Journey Example
Expand Down Expand Up @@ -281,7 +332,7 @@ This flow demonstrates how you can set up your backend project structure and uti
## Future Enhancements
- Add more predefined snippets for common backend use cases.
- Add ability to generate code snippets using AI.
- Add a controller to get the most in-demand snippets.
## License
Expand Down
100 changes: 90 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,51 @@ import { program } from 'commander';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import { GoogleGenerativeAI } from '@google/generative-ai';
import chalk from 'chalk';
import ora from 'ora'; // Import the ora package
import inquirer from 'inquirer'; // Import the inquirer package

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const SNIPPET_PATH = path.join(__dirname, 'snippets'); // Folder containing predefined snippets
const DESTINATION_PATH = process.cwd(); // User's working directory


async function getApiKey() {
const CONFIG_PATH = path.join(__dirname, 'config.json'); // Define path to save the API key

let apiKey = '';

// Check if the API key is already saved in the config file
if (fs.existsSync(CONFIG_PATH)) {
const config = fs.readFileSync(CONFIG_PATH, 'utf-8');
apiKey = JSON.parse(config).apiKey;
}

// If no API key is found, prompt the user for it
if (!apiKey) {
const answers = await inquirer.prompt([
{
type: 'input',
name: 'apiKey',
message: 'Enter your Gemini API key:',
validate: (input) => (input ? true : 'API key is required!'),
},
]);

apiKey = answers.apiKey;

// Save the API key in the config file for future use
fs.writeFileSync(CONFIG_PATH, JSON.stringify({ apiKey }));
}

return apiKey;
}



program
.version('1.0.0')
.description('CLI tool to generate a backend project template and use code snippets');
Expand All @@ -25,15 +63,16 @@ program
try {
// Copy the template files to the destination path
fs.copySync(TEMPLATE_PATH, DESTINATION_PATH);
console.log('\nProject structure created successfully!'
+ '\n\nFollow the steps to get started:'
+ '\n1. cd <your_project_directory>'
+ '\n2. npm install'
+ '\n3. npm run start'
+ '\n\nHappy coding!\n'
console.log(
chalk.green('\nProject structure created successfully!') +
chalk.blue('\n\nFollow the steps to get started:') +
chalk.yellow('\n1. cd <your_project_directory>') +
chalk.yellow('\n2. npm install') +
chalk.yellow('\n3. npm run start') +
chalk.cyan('\n\nHappy coding!\n')
);
} catch (err) {
console.error('Error while generating project structure:', err);
console.error(chalk.red('Error while generating project structure:'), err);
}
});

Expand All @@ -47,7 +86,7 @@ program
const snippetFile = path.join(SNIPPET_PATH, `${snippetName}.js`);

if (!fs.existsSync(snippetFile)) {
console.error(`Error: Snippet "${snippetName}" does not exist.`);
console.error(chalk.red(`Error: Snippet "${snippetName}" does not exist.`));
return;
}

Expand All @@ -57,10 +96,51 @@ program
// Copy the snippet file content to the new file in the working directory
fs.copySync(snippetFile, newSnippetFilePath);

console.log(`\nSnippet "${snippetName}" has been successfully created as "${snippetName}.js" in your current directory!\n`);
console.log(chalk.green(`\nSnippet "${snippetName}" has been successfully created as "${snippetName}.js" in your current directory!\n`));
} catch (err) {
console.error('Error while generating snippet file:', err);
console.error(chalk.red('Error while generating snippet file:'), err);
}
});

// Command to generate code using Google's Generative AI
program
.command('generate-ai-snippet <snippetName>')
.description('Generate a code snippet using Google\'s Generative AI')
.action(async (snippetName) => {


try {
// Prompt the user for an API key
const apiKey = await getApiKey();

const spinner = ora({
text: `Generating code snippet for ${snippetName}...`,
color: 'cyan',
}).start(); // Start the spinner

const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

// Prompt the model to generate a code snippet
const prompt = `You are an expert MERN stack developer specializing in Backend Development using Node.js and Express.js. Generate a javascript code snippet in module js syntax for ${snippetName}. Return only the code snippet strictly adhering to the requirements without unnecessary wrapper text.`;

const result = await model.generateContent(prompt);

// Stop the spinner when the result is generated
spinner.succeed('Code snippet generated successfully!');

// Display the generated code in a styled manner
const generatedCode = result.response.text();

console.log(chalk.blueBright(`\nGenerated Code Snippet for ${snippetName}: \n`));
console.log(chalk.magentaBright(generatedCode));
console.log(chalk.yellowBright(`\nThe code snippet is generated successfully and may require some modifications to fit your use case.\n`));
} catch (error) {
// Stop the spinner with an error
spinner.fail('Error generating content');
console.error(chalk.red('Error generating content:'), error.message || error);
}
});

program.parse(process.argv);

Loading

0 comments on commit 15a22bb

Please sign in to comment.