-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
changeset-gen.js
executable file
·184 lines (160 loc) · 4.55 KB
/
changeset-gen.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
#!/usr/bin/env node
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const { OpenAI } = require('openai');
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
// Initialize OpenAI client
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// Parse command line arguments
const argv = yargs(hideBin(process.argv))
.option('path', {
alias: 'p',
type: 'string',
description: 'Path to the file or directory',
demandOption: true,
})
.option('staged', {
alias: 's',
type: 'boolean',
description: 'Run only against the staged files',
default: false,
})
.help()
.alias('help', 'h').argv;
// Function to find the nearest package.json and get the package name
function getPackageName(filePath) {
let dir = filePath;
while (true) {
const packageJsonPath = path.join(dir, 'package.json');
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
if (packageJson.name) {
return packageJson.name;
} else {
console.error(`Package name not found in ${packageJsonPath}`);
process.exit(1);
}
}
const parentDir = path.dirname(dir);
if (parentDir === dir) {
console.error('Reached root directory without finding package.json');
process.exit(1);
}
dir = parentDir;
}
}
function sanitizeInput(input) {
return input.replace(/[^a-zA-Z0-9_\-\/\.]/g, '');
}
async function generateChangeset(patch, packageName) {
const prompt = `Generate a concise changeset for the following git patch. Focus on the main purpose of the changes and their impact:
${patch}
Please format the changeset as follows:
---
"${packageName}": patch|minor|major
---
<!--- A Brief statement or sentence of the changes --->
Statement of changes.
<!--- Key changes and points as a list, be specific --->
- Key change 1
- optional sub-point 1
- optional sub-point 2
- Key change 2
- Key change 3
- Key change 4
Only return the changeset, nothing else.`;
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: prompt }],
max_tokens: 800,
});
return response.choices[0].message.content
.trim()
.replace('```markdown', '')
.replace('```', '')
.replace(/<!--[\s\S]*?-->\n?/g, '')
.replace(/<\/?[^>]+(>|$)/g, '') // Remove all HTML tags
.trim();
}
function getGitDiffPatch(filePath) {
try {
const sanitizedFilePath = sanitizeInput(filePath);
const baseBranch = execSync(
'git symbolic-ref refs/remotes/origin/HEAD | sed "s@^refs/remotes/origin/@@g" || echo main',
)
.toString()
.trim();
const diffCommand = argv.staged
? `git diff --cached -- "${sanitizedFilePath}"`
: `git diff ${baseBranch} -- "${sanitizedFilePath}"`;
const patch = execSync(diffCommand).toString();
return patch;
} catch (error) {
console.error('Error getting git diff:', error.message);
process.exit(1);
}
}
// Function to generate a random filename
function generateRandomFilename() {
const adjectives = [
'quick',
'lazy',
'sleepy',
'noisy',
'hungry',
'brave',
'calm',
'eager',
'gentle',
'happy',
];
const animals = [
'fox',
'dog',
'cat',
'mouse',
'owl',
'tiger',
'lion',
'bear',
'wolf',
'eagle',
];
const adjective = adjectives[Math.floor(Math.random() * adjectives.length)];
const animal = animals[Math.floor(Math.random() * animals.length)];
return `ai-${adjective}-${animal}.md`;
}
async function main() {
const filePath = path.resolve(argv.path);
if (!fs.existsSync(filePath)) {
console.error(`File or directory not found: ${filePath}`);
process.exit(1);
}
const packageName = getPackageName(filePath);
const patch = getGitDiffPatch(filePath);
if (!patch) {
console.log('No changes detected.');
process.exit(0);
}
try {
const changeset = await generateChangeset(patch, packageName);
console.log('Generated Changeset:');
console.log(changeset);
const changesetsDir = path.resolve('.changeset');
if (!fs.existsSync(changesetsDir)) {
fs.mkdirSync(changesetsDir);
}
const filename = generateRandomFilename();
const fileFullPath = path.join(changesetsDir, filename);
fs.writeFileSync(fileFullPath, changeset);
console.log(`Changeset written to ${fileFullPath}`);
} catch (error) {
console.error('Error generating changeset:', error.message);
process.exit(1);
}
}
main();