|
| 1 | +import path from 'path' |
| 2 | +import process from 'process' |
| 3 | + |
| 4 | +import { generateCommitMessage } from '../../core/commitGenerator.js' |
| 5 | +import { NoChangesError } from '../../services/errors.js' |
| 6 | +import { getStagedDiff, executeCommit } from '../../services/git.js' |
| 7 | +import * as openaiService from '../../services/openai.js' |
| 8 | +import { confirm } from '../../services/prompt.js' |
| 9 | + |
| 10 | +/** |
| 11 | + * Load API key from environment if not in config |
| 12 | + * @param {string|null} configApiKey - API key from config |
| 13 | + * @returns {Promise<string|null>} The API key |
| 14 | + */ |
| 15 | +async function resolveApiKey(configApiKey) { |
| 16 | + if (configApiKey) return configApiKey |
| 17 | + |
| 18 | + // Try to load from .env |
| 19 | + const dotenv = await import('dotenv') |
| 20 | + const envPath = path.join(process.cwd(), '.env') |
| 21 | + dotenv.config({ path: envPath }) |
| 22 | + |
| 23 | + return process.env.OPENAI_API_KEY || null |
| 24 | +} |
| 25 | + |
| 26 | +/** |
| 27 | + * Create the commit command handler |
| 28 | + * @param {object} deps - Dependencies |
| 29 | + * @param {import('../../config/index.js').ConfigManager} deps.config - Config manager |
| 30 | + * @returns {Function} The command handler |
| 31 | + */ |
| 32 | +export function createCommitCommand({ config }) { |
| 33 | + return async function commitAction() { |
| 34 | + try { |
| 35 | + // Get staged diff |
| 36 | + const diff = await getStagedDiff() |
| 37 | + |
| 38 | + // Resolve API key |
| 39 | + const apiKey = await resolveApiKey(config.get('apiKey')) |
| 40 | + if (!apiKey) { |
| 41 | + console.error( |
| 42 | + 'No OpenAI API key found. Please set it using "git gpt open-api-key add".', |
| 43 | + ) |
| 44 | + process.exit(1) |
| 45 | + } |
| 46 | + |
| 47 | + // Create OpenAI client |
| 48 | + const client = openaiService.createClient(apiKey) |
| 49 | + |
| 50 | + // Generate commit message |
| 51 | + const message = await generateCommitMessage( |
| 52 | + { openaiService, client }, |
| 53 | + { |
| 54 | + diff, |
| 55 | + model: config.get('model'), |
| 56 | + language: config.get('language'), |
| 57 | + prefixEnabled: config.get('prefixEnabled'), |
| 58 | + }, |
| 59 | + ) |
| 60 | + |
| 61 | + // Confirm with user |
| 62 | + const confirmed = await confirm(`${message}.`) |
| 63 | + if (confirmed) { |
| 64 | + executeCommit(message) |
| 65 | + console.log('Committed with the suggested message.') |
| 66 | + } else { |
| 67 | + console.log('Commit canceled.') |
| 68 | + } |
| 69 | + } catch (error) { |
| 70 | + if (error instanceof NoChangesError) { |
| 71 | + console.log('No changes to commit. Commit canceled.') |
| 72 | + process.exit(0) |
| 73 | + } |
| 74 | + console.error(error.message) |
| 75 | + process.exit(1) |
| 76 | + } |
| 77 | + } |
| 78 | +} |
0 commit comments