Last active
November 30, 2024 02:13
-
-
Save letswritetw/c6485bc3ada935b1170b53d283c9e218 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require('axios'); | |
const { execSync } = require("child_process"); | |
require('dotenv').config(); | |
// 使用 OpenAI API Key | |
const apiKey = process.env.OPEN_API_KEY_COMMIT; | |
const apiUrl = 'https://api.openai.com/v1/chat/completions'; | |
// 取得 git 差異內容 | |
function getGitDiff() { | |
try { | |
// 首先獲取所有更改的檔案列表 | |
const changedFiles = execSync("git diff --cached --name-only", { encoding: "utf-8" }) | |
.split('\n') | |
.filter(file => file && !file.includes('.min.') && file.trim() !== ''); | |
console.log('判斷檔案:', changedFiles); | |
// 然後只對這些檔案執行 git diff | |
const diff = changedFiles.map(file => { | |
try { | |
return execSync(`git diff --cached -- "${file}"`, { encoding: "utf-8" }); | |
} catch (error) { | |
console.error(`Error getting diff for file ${file}:`, error); | |
return ''; | |
} | |
}).join('\n'); | |
return diff; | |
} catch (error) { | |
console.error("Error fetching git diff:", error); | |
return ""; | |
} | |
} | |
// 使用 axios 調用 OpenAI 生成 commit 訊息 | |
async function generateCommitMessage(diff) { | |
try { | |
const response = await axios.post(apiUrl, { | |
model: "gpt-4o-mini", // 使用 GPT-4 模型 | |
messages: [ | |
{ | |
role: "system", | |
content: "你是一個優秀的開發者,負責撰寫簡潔又描述清楚的 Git commit 訊息。", | |
}, | |
{ | |
role: "user", | |
content: `根據以下的 git 差異生成一個有意義的 commit 繁體中文訊息,請包含兩個部分:\n1. Summary(不超過50字)\n2. Description(條列描述變更內容):\n${diff}`, | |
}, | |
], | |
}, { | |
headers: { | |
'Authorization': `Bearer ${apiKey}`, | |
'Content-Type': 'application/json' | |
} | |
}); | |
const commitMessage = Array.isArray(response.data.choices) && response.data.choices.length > 0 ? response.data.choices[0].message.content.trim() : "Default commit message."; | |
return commitMessage; // 回傳完整的 commit 訊息,不做拆解 | |
} catch (error) { | |
console.error("Error generating commit message:", error.response ? error.response.data : error.message); | |
return "Refactor code."; // 如果發生錯誤,回傳一個預設的 commit 訊息 | |
} | |
} | |
// 主執行流程 | |
async function main() { | |
const diff = getGitDiff(); | |
if (!diff) { | |
console.log("No changes to commit."); | |
return; | |
} | |
const commitMessage = await generateCommitMessage(diff); | |
console.log(commitMessage); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment