-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.mjs
More file actions
493 lines (455 loc) · 14 KB
/
api.mjs
File metadata and controls
493 lines (455 loc) · 14 KB
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// api.mjs - Common git operations
import { execSync } from 'child_process';
import chalk from 'chalk';
/**
* Check if the current directory is a Git repository
* @returns {boolean} True if it's a Git repository
*/
export function isGitRepository() {
try {
execSync('git rev-parse --is-inside-work-tree', { stdio: 'ignore' });
return true;
} catch (error) {
return false;
}
}
/**
* Get the current directory.
* @returns {string} Current directory path.
*/
export function getCurrentDirectory() {
try {
return execSync('pwd', { encoding: 'utf8' }).trim();
} catch (error) {
throw new Error('Failed to get current directory: ' + error.message);
}
}
/**
* Get the current branch name
* @returns {string} Current branch name
*/
export function getCurrentBranch() {
try {
return execSync('git branch --show-current', { encoding: 'utf8' }).trim();
} catch (error) {
throw new Error('Failed to get current branch: ' + error.message);
}
}
/**
* Get all local branches
* @returns {string[]} Array of branch names
*/
export function getLocalBranches() {
try {
const output = execSync('git branch', { encoding: 'utf8' });
return output
.split('\n')
.filter(Boolean)
.map(branch => branch.replace(/^\*?\s*/, '').trim());
} catch (error) {
throw new Error('Failed to get local branches: ' + error.message);
}
}
/**
* Delete a local branch
* @param {string} branchName Branch to delete
* @param {boolean} force Whether to force deletion
* @returns {object} Result of the operation
*/
export function deleteLocalBranch(branchName, force = false) {
try {
const flag = force ? '-D' : '-d';
execSync(`git branch ${flag} ${branchName}`, { encoding: 'utf8' });
return { success: true, message: `Branch ${branchName} deleted successfully` };
} catch (error) {
return {
success: false,
message: `Failed to delete branch ${branchName}: ${error.message}`,
requireForce: !force && error.message.includes('not fully merged')
};
}
}
/**
* Delete a remote branch.
*
* @param {string} branch Branch to delete
* @param {string} remote Remote repository to delete from.
*/
export function deleteRemoteBranch(branch, remote = 'origin') {
try {
execSync(`git push ${remote} --delete ${branch}`);
} catch (error) {
throw new Error(error.message);
}
}
/**
* Get remote repositories
* @returns {string[]} Array of remote names
*/
export function getRemotes() {
try {
const output = execSync('git remote', { encoding: 'utf8' });
return output.split('\n').filter(Boolean);
} catch (error) {
throw new Error('Failed to get remotes: ' + error.message);
}
}
/**
* Execute generic git command and return its output
* @param {string} command Git command to execute
* @returns {string} Command output
*/
export function executeGitCommand(command) {
try {
return execSync(`git ${command}`, { encoding: 'utf8' });
} catch (error) {
throw new Error(`Failed to execute 'git ${command}': ${error.message}`);
}
}
/**
* Get working directory status (changes)
* @returns {string} Git status output
*/
export function getStatus() {
try {
return execSync('git status -s', { encoding: 'utf8' });
} catch (error) {
throw new Error('Failed to get status: ' + error.message);
}
}
/**
* Stash current changes
* @param {string} message Optional stash message
* @returns {boolean} True if changes were stashed
*/
export function stashChanges(message = 'Auto stash before creating feature branch') {
try {
// Check if there are changes to stash
const status = getStatus();
if (!status.trim()) {
return false; // Nothing to stash
}
execSync(`git stash save "${message}"`, { encoding: 'utf8' });
return true;
} catch (error) {
throw new Error('Failed to stash changes: ' + error.message);
}
}
/**
* Apply most recent stash
* @param {boolean} pop Whether to pop or apply (remove or keep the stash)
* @returns {boolean} True if stash was applied
*/
export function applyStash(pop = true) {
try {
const command = pop ? 'git stash pop' : 'git stash apply';
execSync(command, { encoding: 'utf8' });
return true;
} catch (error) {
throw new Error('Failed to apply stash: ' + error.message);
}
}
/**
* Check if there are any stashes
* @returns {boolean} True if there are stashes
*/
export function hasStashes() {
try {
const output = execSync('git stash list', { encoding: 'utf8' });
return output.trim().length > 0;
} catch (error) {
throw new Error('Failed to check stashes: ' + error.message);
}
}
/**
* Checkout a branch
* @param {string} branchName Branch to checkout.
* @returns {boolean} True if checkout was successful
*/
export function checkoutBranch(branchName) {
try {
execSync(`git checkout ${branchName}`, { encoding: 'utf8' });
return true;
} catch (error) {
throw new Error(`Failed to checkout branch ${branchName}: ${error.message}`);
}
}
/**
* Pull with rebase from remote
* @param {string} remote Remote name
* @param {string} branch Branch name
* @returns {boolean} True if pull was successful
*/
export function pullWithRebase(remote = 'origin', branch = null) {
try {
const branchArg = branch ? ` ${branch}` : '';
execSync(`git pull --rebase ${remote}${branchArg}`, { encoding: 'utf8' });
return true;
} catch (error) {
throw new Error(`Failed to pull with rebase: ${error.message}`);
}
}
/**
* Fetch updates from remote without switching to the branch
* More efficient than checkout+pull when not on the target branch
*
* @param {string} branch Branch to update
* @param {string} remote Remote name
* @returns {boolean} True if fetch was successful
*/
export function fetchBranchUpdates(branch, remote = 'origin') {
try {
// Fetch the remote branch and update the local branch
execSync(`git fetch ${remote} ${branch}:${branch}`, { encoding: 'utf8' });
return true;
} catch (error) {
// Handle non-fast-forward updates (e.g., if local branch has diverged)
if (error.message.includes('non-fast-forward')) {
console.log(chalk.yellow(`Cannot fast-forward ${branch}. Local branch has diverged from remote.`));
// Fetch the remote branch without updating local branch
execSync(`git fetch ${remote}`, { encoding: 'utf8' });
return false;
}
throw new Error(`Failed to fetch updates for ${branch}: ${error.message}`);
}
}
/**
* Create a new branch
* @param {string} branchName Name for the new branch
* @param {string} startPoint Branch to create from (default: current HEAD)
* @returns {boolean} True if branch was created
*/
export function createBranch(branchName, startPoint = null) {
try {
const startPointArg = startPoint ? ` ${startPoint}` : '';
execSync(`git checkout -b ${branchName}${startPointArg}`, { encoding: 'utf8' });
return true;
} catch (error) {
throw new Error(`Failed to create branch ${branchName}: ${error.message}`);
}
}
/**
* Convert a string to kebab-case
* @param {string} text Input text
* @returns {string} Kebab-cased text
*/
export function toKebabCase(text) {
return text
.trim()
.toLowerCase()
.replace(/[^\w\s-]/g, '') // Remove special characters except hyphen
.replace(/[\s_]+/g, '-'); // Replace spaces and underscores with hyphens
}
/**
* Check if a branch exists on the remote
* @param {string} branchName Name of the branch to check
* @returns {boolean} True if the branch exists on the remote
*/
export function checkIfRemoteBranchExists(branchName) {
try {
const result = execSync(`git ls-remote --heads origin ${branchName}`, { encoding: 'utf8' });
return result.trim() !== '';
} catch (error) {
// If there's an error, assume the branch doesn't exist remotely
return false;
}
}
/**
* Get all branches (both local and remote)
* @returns {string[]} Array of branch names
*/
export function getAllBranches() {
try {
// Get all branches (both local and remote)
const output = execSync('git branch -a', { encoding: 'utf8' });
// Parse branch names and remove duplicates
return output
.split('\n')
.filter(Boolean)
.map(branch => branch.replace(/^\*?\s*remotes\/origin\//, '').replace(/^\*?\s*/, '').trim())
.filter(branch => !branch.includes('HEAD ->') && !branch.includes('/HEAD')) // Remove HEAD pointers
.filter((branch, index, self) => self.indexOf(branch) === index); // Remove duplicates
} catch (error) {
throw new Error('Failed to get branches: ' + error.message);
}
}
/**
* Pull latest changes from remote for current branch
* @returns {string} Command output
*/
export function pullLatestChanges() {
try {
return execSync('git pull --rebase', { encoding: 'utf8' });
} catch (error) {
throw new Error('Failed to pull latest changes: ' + error.message);
}
}
/**
* List all git tags in the project ordered by most recent
* @returns {string[]} Array of tags ordered by most recent first
*/
export function listTags() {
try {
// Get all tags with their creation dates
const stdout = execSync('git for-each-ref --sort=-creatordate --format="%(refname:short)" refs/tags/', { encoding: 'utf8' });
if (!stdout.trim()) {
console.log('No tags found in this repository.');
return [];
}
// Parse the output to get tags with their dates
return stdout.trim().split('\n').map(tag => {
return tag.trim();
});
} catch (error) {
console.error('Error listing tags:', error.message);
return [];
}
}
/**
* Set upstream and push the current branch to origin
* @param {string} remoteName The remote name to push to (defaults to 'origin')
* @returns {object} Result of the operation
*/
export function setUpstreamAndPush(remoteName = 'origin') {
try {
const currentBranch = getCurrentBranch();
execSync(`git push --set-upstream ${remoteName} ${currentBranch}`, { encoding: 'utf8' });
return {
success: true,
message: `Successfully set upstream and pushed branch ${currentBranch} to ${remoteName}`
};
} catch (error) {
return {
success: false,
message: `Failed to set upstream and push: ${error.message}`
};
}
}
/**
* Push branch to remote.
*
* @param branch
* Branch to push to remote
* @param remoteName
* Remote repository name defaults to 'origin'.
*/
export function pushToRemote(branch, remoteName = 'origin') {
const branches = getAllBranches();
const gitArtifactType = branches.includes(branch) ? 'branch' : 'tag';
try {
console.log(chalk.blue(`\nPushing ${branch} ${gitArtifactType}`));
execSync(`git push ${remoteName} ${branch}`);
} catch (error) {
console.log(chalk.red(`Failed to push ${branch} ${gitArtifactType}: ${error.message}`));
throw new Error(error.message);
}
}
/**
* Gets the main branch for the repository.
*
* Either a main or a master branch.
*
* @returns {string}
*/
export function getMainBranch() {
try {
const branches = getAllBranches();
// Check whether we are using main or master.
// Selects first one found.
return branches.find(branch => branch.startsWith('main') || branch.startsWith('master'));
} catch (error) {
throw new Error('Failed to get main branch: ' + error.message);
}
}
export function mergeBranch(mergeBranch) {
const currentBranch = getCurrentBranch();
try {
execSync(`git merge --no-ff ${mergeBranch} -m "Merge ${mergeBranch} into ${currentBranch}"`);
} catch (e) {
throw new Error(`Failed to merge ${mergeBranch} into ${currentBranch}: ${e.message}`);
}
}
/**
* Get the latest commits from the specified branch
* @param {number} limit Number of commits to retrieve
* @returns {Array} Array of commit objects with hash and message
*/
export function getLatestCommits(limit = 20) {
try {
const output = execSync(`git log -n ${limit} --pretty=format:"%h||%s||%an||%ad" --date=short`, { encoding: 'utf8' });
return output
.split('\n')
.filter(Boolean)
.map(line => {
const [hash, message, author, date] = line.split('||');
return { hash, message, author, date };
});
} catch (error) {
throw new Error('Failed to get latest commits: ' + error.message);
}
}
/**
* Cherry-pick a specific commit to the current branch
* @param {string} commitHash The hash of the commit to cherry-pick
* @returns {object} Result of the operation
*/
export function cherryPickCommit(commitHash) {
try {
// Use -x flag to add a reference to the original commit
execSync(`git cherry-pick -x ${commitHash}`, { encoding: 'utf8' });
return {
success: true,
message: `Successfully cherry-picked commit ${commitHash}`
};
} catch (error) {
return {
success: false,
message: `Failed to cherry-pick commit ${commitHash}: ${error.message}`
};
}
}
/**
* Merge a feature branch into the current branch
* @param {string} featureBranch The feature branch to merge
* @param {string} commitMessage The commit message for the merge
* @returns {object} Result of the operation
*/
export function mergeFeatureBranch(featureBranch, commitMessage) {
try {
// Merge the feature branch with the provided commit message
// Using --no-ff to ensure a merge commit is created
execSync(`git merge --no-ff ${featureBranch} -m "${commitMessage}"`, { encoding: 'utf8' });
return {
success: true,
message: `Successfully merged branch ${featureBranch}`
};
} catch (error) {
// Check if it's a merge conflict
if (error.message.includes('Automatic merge failed')) {
return {
success: false,
message: `Merge conflicts detected. Please resolve conflicts manually and commit.`,
isConflict: true
};
}
return {
success: false,
message: `Failed to merge branch ${featureBranch}: ${error.message}`
};
}
}
/**
* Create a tag.
*
* @param tagName
*/
export async function createTag(tagName) {
console.log(chalk.blue(`\nCreating tag ${tagName}`));
try {
execSync(`git tag -a ${tagName} -m ${tagName}`);
} catch (error) {
console.log(chalk.red(`Failed to create tag ${tagName}`));
console.log(chalk.yellow(error.message));
throw new Error(error.message);
}
}