Skip to content

Commit

Permalink
Add CLI for AI-generated git commit messages with debug and offline o…
Browse files Browse the repository at this point in the history
…ptions.
  • Loading branch information
zackbraksa committed Oct 11, 2024
1 parent 107b188 commit b401678
Showing 1 changed file with 38 additions and 37 deletions.
75 changes: 38 additions & 37 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,51 @@ import { execSync } from 'child_process'
import { program } from 'commander'
import { OpenAI } from 'openai'

function runCLI () {
console.log('Thinking ...')
program
.name('generate')
.description('let AI write your git commit messages')
.option('-d, --debug', 'output extra debugging')
.option('-o, --offline', "don't make any request")
.action(main(program.opts()))

program.parse()
}

export function main (options) {
return async () => {
const diff = getGitDiff()

if (options.debug) {
console.log('diff', diff)
}

if (options.offline) {
console.log('offline mode, skipping request to OpenAI')
return
}

if (diff === '') {
console.log('Your diff are empty, stage your changes first.')
return
}

const client = createOpenAIClient(process.env.OPENAI_API_KEY)
const completion = await getCompletion(diff, client)

console.log('git commit -m', `"${completion.choices[0].message.content}"`)
}
}

export function getGitDiff (execSyncFn = execSync, cwd = process.cwd()) {
try {
const ignoredFiles = ['package-lock.json']
const ignoreArg = ignoredFiles.length
? `-- . ${ignoredFiles.map((file) => `':!${file}'`).join(' ')}`
: ''
const cmd = `git diff --staged ${ignoreArg}`
const diff = execSyncFn(cmd, { cwd }).toString()
const diff = execSyncFn(cmd, { cwd }).toString().trim()
return diff
} catch (error) {
console.warn('Warning: Unable to get git diff. Are you in a git repository with staged changes?')
Expand All @@ -34,40 +71,4 @@ export function createOpenAIClient (apiKey) {
return new OpenAI({ apiKey })
}

export function main (options) {
return async () => {
const diff = getGitDiff()

if (options.debug) {
console.log('diff', diff)
}

if (options.offline) {
console.log('offline mode, skipping request')
return
}

const client = createOpenAIClient(process.env.OPENAI_API_KEY)
const completion = await getCompletion(diff, client)

console.log('git commit -m', `"${completion.choices[0].message.content}"`)
}
}

function runCLI () {
console.log('Thinking ...')
program
.name('generate')
.description('let AI write your git commit messages')
.option('-d, --debug', 'output extra debugging')
.option('-o, --offline', "don't make any request")
.action(main(program.opts()))

program.parse()
}

if (import.meta.url === `file://${process.argv[1]}`) {
runCLI()
}

export { runCLI }

0 comments on commit b401678

Please sign in to comment.