Skip to content

Commit

Permalink
refactor(_gr.js): move logic into separate, imported functions
Browse files Browse the repository at this point in the history
  • Loading branch information
peterdanwan committed Sep 25, 2024
1 parent 82f66ee commit 3f2f7cf
Show file tree
Hide file tree
Showing 4 changed files with 119 additions and 96 deletions.
105 changes: 9 additions & 96 deletions src/_gr.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,11 @@
// src/_gr.js

import program from './commanderProgram.js';
import getFileContent from './file_functions/getFileContent.js';
import promptAI from './ai.js';
import defaultPrompt from './defaultPrompt.js';
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
import os from 'os';
import chalk from 'chalk';
import ora from 'ora';
import { fileURLToPath } from 'url';

// Define __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Load .gimme_readme_config as environment variables
const configFilePath = path.join(os.homedir(), '.gimme_readme_config');
dotenv.config({ path: configFilePath });
// Option handlers
import handleConfigOption from './option_handlers/handleConfigOption.js';
import handleHelpOption from './option_handlers/handleHelpOption.js';
import handleFilesOption from './option_handlers/handleFilesOption.js';

async function main() {
const args = process.argv;
Expand All @@ -29,91 +16,17 @@ async function main() {
const options = program.opts();

if (args.length == 2) {
console.log(program.help());
process.exit(0);
handleHelpOption(program);
}

// Handle the config option
if (options.config) {
if (!fs.existsSync(configFilePath)) {
// Construct the path to env.sample within the gimme_readme project directory
const sampleFilePath = path.resolve(__dirname, '../env.sample'); // Adjust the path to point to gimme_readme/env.sample

let sampleContent;

try {
// Read the env.sample file from the gimme_readme directory
sampleContent = fs.readFileSync(sampleFilePath, 'utf-8');
} catch (err) {
console.error(`Could not find env.sample in the project directory: ${err.message}`);
process.exit(1);
}

// Create a new config file with the sample content
fs.writeFileSync(configFilePath, sampleContent);
console.log(`Configuration file created at: ${chalk.blue(configFilePath)}`);
} else {
console.log(`Configuration file located at: ${chalk.blue(configFilePath)}`);
}

console.log(
`Please refer to the ${chalk.blue('gimme_readme')} repository for examples on how to configure this file: ${chalk.blue('https://github.com/peterdanwan/gimme_readme')}`
);

process.exit(0);
handleConfigOption();
}

if (options.file) {
const files = options['file'];

// Let the user specify their own prompt, or use the prompt that we have engineered
let prompt = options.prompt || process.env.CUSTOM_PROMPT || defaultPrompt;
const model = options.model || process.env.MODEL || 'gemini-1.5-flash';
const outputFile = options.outputFile || process.env.OUTPUT_FILE || null; // if no options are being specified, the option woudl be null, which means it will go out to terminal in the console
const temperature = options.temperature || process.env.TEMPERATURE || 0.5;
const needToken = options.token || false;

const validFiles = [];

// Check if files is an array and has at least one entry
if (!Array.isArray(files)) {
console.log("error: option '-f, --file [files...]' argument missing ");
process.exit(1);
}

for (const file of files) {
try {
const content = getFileContent(file);
prompt += content + '\n\n';
validFiles.push(file);
} catch (error) {
console.error(error);
process.exit(1);
}
}

if (validFiles.length > 1) {
console.log(chalk.blue('Sending files:'));
for (const validFile of validFiles) {
console.log(`- ${validFile}`);
}
} else {
console.log(`${chalk.blue('Sending file')}: ${validFiles[0]}`);
}

const spinner = ora(` Waiting for a response from the ${chalk.blue(model)} model...\n`).start();

try {
await promptAI(prompt, model, temperature, outputFile, needToken);
spinner.succeed(` Response received from ${chalk.blue(model)} model`);
} catch (error) {
spinner.fail(` Failed to receive response from ${chalk.red(model)} model`);
console.error(error);
process.exit(1);
}
if (options.files) {
const files = options['files'];
await handleFilesOption(files, options);
}

setTimeout(() => process.exit(0), 100);
}

main();
39 changes: 39 additions & 0 deletions src/option_handlers/handleConfigOption.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// src/option_handlers/handleConfigOption.js
import fs from 'fs';
import path from 'path';
import os from 'os';
import chalk from 'chalk';
import { fileURLToPath } from 'url';

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

// Function to handle config option
export default function handleConfigOption() {
const configFilePath = path.join(os.homedir(), '.gimme_readme_config');

if (!fs.existsSync(configFilePath)) {
// Construct the path to env.sample within the gimme_readme project directory
const sampleFilePath = path.resolve(__dirname, '../../env.sample');

let sampleContent;
try {
sampleContent = fs.readFileSync(sampleFilePath, 'utf-8');
} catch (err) {
console.error(`Could not find env.sample in the project directory: ${err.message}`);
process.exit(1);
}

// Create a new config file with the sample content
fs.writeFileSync(configFilePath, sampleContent);
console.log(`Configuration file created at: ${chalk.blue(configFilePath)}`);
} else {
console.log(`Configuration file located at: ${chalk.blue(configFilePath)}`);
}

console.log(
`Please refer to the ${chalk.blue('gimme_readme')} repository for examples on how to configure this file: ${chalk.blue('https://github.com/peterdanwan/gimme_readme')}`
);

process.exit(0);
}
65 changes: 65 additions & 0 deletions src/option_handlers/handleFilesOption.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// src/option_handlers/handleFilesOption.js

import path from 'path';
import os from 'os';
import dotenv from 'dotenv';
import chalk from 'chalk';
import ora from 'ora';

import getFileContent from '../file_functions/getFileContent.js';
import promptAI from '../ai.js';
import defaultPrompt from '../defaultPrompt.js';

// Attempt to load .gimme_readme_config's environment variables
const configFilePath = path.join(os.homedir(), '.gimme_readme_config');
dotenv.config({ path: configFilePath });

export default async function handleFilesOption(files, options) {
// Let the user specify their own prompt, or use the prompt that we have engineered
let prompt = options.prompt || process.env.CUSTOM_PROMPT || defaultPrompt;
const model = options.model || process.env.MODEL || 'gemini-1.5-flash';
const outputFile = options.outputFile || process.env.OUTPUT_FILE || null; // if no options are being specified, the option would be null, which means it will go out to terminal in the console
const temperature = options.temperature || process.env.TEMPERATURE || 0.5;
const needToken = options.token || false;

const validFiles = [];

// Check if files is an array and has at least one entry
if (!Array.isArray(files)) {
console.log("error: option '-f, --files [files...]' argument missing ");
process.exit(1);
}

for (const file of files) {
try {
const content = getFileContent(file);
prompt += content + '\n\n';
validFiles.push(file);
} catch (error) {
console.error(error);
process.exit(1);
}
}

if (validFiles.length > 1) {
console.log(chalk.blue('Sending files:'));
for (const validFile of validFiles) {
console.log(`- ${validFile}`);
}
} else {
console.log(`${chalk.blue('Sending file')}: ${validFiles[0]}`);
}

const spinner = ora(` Waiting for a response from the ${chalk.blue(model)} model...\n`).start();

try {
await promptAI(prompt, model, temperature, outputFile, needToken);
spinner.succeed(` Response received from ${chalk.blue(model)} model`);
} catch (error) {
spinner.fail(` Failed to receive response from ${chalk.red(model)} model`);
console.error(error);
process.exit(1);
}

process.exit(0);
}
6 changes: 6 additions & 0 deletions src/option_handlers/handleHelpOption.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// src/option_handlers/handleHelpOption.js

export default function handleHelpOption(program) {
// Implicit exit code of 0
program.help();
}

0 comments on commit 3f2f7cf

Please sign in to comment.