-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgbranch.js
More file actions
executable file
·302 lines (258 loc) · 14.5 KB
/
Copy pathgbranch.js
File metadata and controls
executable file
·302 lines (258 loc) · 14.5 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
#!/usr/bin/env node
import { execSync } from 'child_process';
import { existsSync } from 'fs';
import chalk from 'chalk';
function validateRepository() {
if (!existsSync('.git')) {
console.error(chalk.red('❌ Error: Not a git repository (or any of the parent directories): .git'));
process.exit(1);
}
}
function showHelp() {
console.log(chalk.magenta.bold('\n🌿 gbranch - Branch Management\n'));
console.log(chalk.cyan('Purpose:'), 'List, create, and manage branches with comprehensive options for local and remote branches.\n');
console.log(chalk.cyan('Command:'), chalk.white('gbranch [branch-name] [options]\n'));
console.log(chalk.cyan('Parameters:'));
console.log(' ' + chalk.white('[branch-name]') + ' - Name of new branch to create\n');
console.log(chalk.cyan('Essential Options:'));
console.log(' ' + chalk.green('-r, --remotes') + ' - List remote branches');
console.log(' ' + chalk.green('-a, --all') + ' - List both local and remote branches');
console.log(' ' + chalk.green('-v, --verbose') + ' - Show commit info for each branch');
console.log(' ' + chalk.green('--merged [commit]') + ' - List branches merged into commit');
console.log(' ' + chalk.green('--no-merged [commit]') + ' - List branches not merged into commit');
console.log(' ' + chalk.green('--contains <commit>') + ' - List branches containing the commit');
console.log(' ' + chalk.green('--sort <key>') + ' - Sort by key (committerdate, authordate, etc.)');
console.log(' ' + chalk.green('-d, --delete') + ' - Delete branch (safe)');
console.log(' ' + chalk.green('-D, --force-delete') + ' - Force delete branch');
console.log(' ' + chalk.green('-m, --move') + ' - Rename/move branch');
console.log(' ' + chalk.green('-c, --copy') + ' - Copy branch');
console.log(' ' + chalk.green('--track') + ' - Set up tracking when creating');
console.log(' ' + chalk.green('--no-track') + ' - Don\'t set up tracking');
console.log(' ' + chalk.green('-h, --help') + ' - Show detailed help information\n');
console.log(chalk.cyan('Common Use Cases:'));
console.log(chalk.white(' gbranch') + ' # List local branches');
console.log(chalk.white(' gbranch feature-auth') + ' # Create new branch');
console.log(chalk.white(' gbranch -a') + ' # List all branches');
console.log(chalk.white(' gbranch -r') + ' # List remote branches');
console.log(chalk.white(' gbranch -v') + ' # Verbose branch list');
console.log(chalk.white(' gbranch --merged') + ' # Show merged branches');
console.log(chalk.white(' gbranch -d old-feature') + ' # Delete branch safely');
console.log(chalk.white(' gbranch --sort=-committerdate') + ' # Sort by recent commits\n');
console.log(chalk.cyan('🔧 Branch Management:'));
console.log(' • Use ' + chalk.yellow('gcheckout') + ' to switch between branches');
console.log(' • Current branch is highlighted with ' + chalk.green('*') + ' and color');
console.log(' • Remote tracking information shown when available');
console.log('\n' + chalk.gray('═'.repeat(60)));
}
function getCurrentBranch() {
try {
return execSync('git branch --show-current', { encoding: 'utf-8' }).trim();
} catch (error) {
return null;
}
}
async function main() {
const args = process.argv.slice(2);
if (args.includes('-h') || args.includes('--help')) {
showHelp();
return;
}
validateRepository();
console.log(chalk.magenta.bold('🌿 Branch Management'));
console.log(chalk.gray('━'.repeat(40)));
// Build git branch command
let branchCmd = 'git branch';
let branchName = '';
let action = 'list';
// Parse arguments
let i = 0;
while (i < args.length) {
const arg = args[i];
if (arg === '-r' || arg === '--remotes') {
branchCmd += ' --remotes';
} else if (arg === '-a' || arg === '--all') {
branchCmd += ' --all';
} else if (arg === '-v' || arg === '--verbose') {
branchCmd += ' --verbose';
} else if (arg === '--merged') {
branchCmd += ' --merged';
if (args[i + 1] && !args[i + 1].startsWith('-')) {
branchCmd += ` ${args[i + 1]}`;
i++; // Skip next argument
}
} else if (arg === '--no-merged') {
branchCmd += ' --no-merged';
if (args[i + 1] && !args[i + 1].startsWith('-')) {
branchCmd += ` ${args[i + 1]}`;
i++; // Skip next argument
}
} else if (arg === '--contains') {
if (args[i + 1] && !args[i + 1].startsWith('-')) {
branchCmd += ` --contains ${args[i + 1]}`;
i++; // Skip next argument
}
} else if (arg === '--sort') {
if (args[i + 1] && !args[i + 1].startsWith('-')) {
branchCmd += ` --sort=${args[i + 1]}`;
i++; // Skip next argument
}
} else if (arg === '-d' || arg === '--delete') {
action = 'delete';
branchCmd = 'git branch --delete';
} else if (arg === '-D' || arg === '--force-delete') {
action = 'force-delete';
branchCmd = 'git branch --delete --force';
} else if (arg === '-m' || arg === '--move') {
action = 'move';
branchCmd = 'git branch --move';
} else if (arg === '-c' || arg === '--copy') {
action = 'copy';
branchCmd = 'git branch --copy';
} else if (arg === '--track') {
branchCmd += ' --track';
} else if (arg === '--no-track') {
branchCmd += ' --no-track';
} else if (!arg.startsWith('-')) {
branchName = arg;
}
i++;
}
// Handle different actions
if (action === 'list') {
if (branchName) {
// Creating a new branch
branchCmd = `git branch ${branchName}`;
if (args.includes('--track')) {
branchCmd += ' --track';
} else if (args.includes('--no-track')) {
branchCmd += ' --no-track';
}
console.log(chalk.cyan(`🔍 Running: ${branchCmd}`));
try {
const result = execSync(branchCmd, { encoding: 'utf-8' });
if (result) console.log(result);
console.log(chalk.green(`✅ Branch '${branchName}' created successfully`));
console.log(chalk.gray('━'.repeat(40)));
console.log(chalk.cyan('� Next Steps:'));
console.log(chalk.white(` gcheckout ${branchName}`) + ' # Switch to new branch');
console.log(chalk.white(' gbranch') + ' # View all branches');
} catch (error) {
console.error(chalk.red(`❌ Error: ${error.message}`));
if (error.message.includes('already exists')) {
console.log(chalk.yellow(`💡 Branch '${branchName}' already exists. Use gcheckout to switch to it.`));
}
process.exit(1);
}
} else {
// Listing branches
console.log(chalk.cyan(`🔍 Running: ${branchCmd}`));
try {
const result = execSync(branchCmd, { encoding: 'utf-8' });
// Enhanced output formatting for branch listing
if (result) {
const branches = result.split('\n').filter(line => line.trim());
const currentBranch = getCurrentBranch();
// Get branch counts
const localBranches = branches.filter(b => !b.includes('remotes/'));
const remoteBranches = branches.filter(b => b.includes('remotes/'));
console.log(chalk.cyan('📋 Branch Summary:'));
console.log(` Local branches: ${chalk.white(localBranches.length)}`);
if (args.includes('-a') || args.includes('--all') || args.includes('-r') || args.includes('--remotes')) {
console.log(` Remote branches: ${chalk.white(remoteBranches.length)}`);
}
console.log(chalk.cyan('🌿 Branches:'));
// Sort branches - current first, then alphabetically
const sortedBranches = branches.sort((a, b) => {
if (a.startsWith('*')) return -1;
if (b.startsWith('*')) return 1;
return a.localeCompare(b);
});
sortedBranches.forEach(branch => {
const cleanBranch = branch.replace(/^\*?\s*/, '');
const isCurrent = branch.startsWith('*');
if (isCurrent) {
console.log(` ${chalk.green('➤')} ${chalk.green.bold(cleanBranch)} ${chalk.gray('← current branch')}`);
} else if (branch.includes('remotes/origin/')) {
const remoteName = cleanBranch.replace('remotes/origin/', '');
console.log(` ${chalk.blue('📡')} ${chalk.blue(remoteName)} ${chalk.gray('(remote)')}`);
} else if (branch.includes('remotes/')) {
console.log(` ${chalk.blue('📡')} ${chalk.blue(cleanBranch)} ${chalk.gray('(remote)')}`);
} else {
// Check if this local branch has a remote
try {
const upstream = execSync(`git rev-parse --abbrev-ref ${cleanBranch}@{upstream} 2>/dev/null || echo ""`, { encoding: 'utf-8' }).trim();
if (upstream) {
console.log(` ${chalk.white('🔗')} ${chalk.white(cleanBranch)} ${chalk.gray('→ ' + upstream)}`);
} else {
console.log(` ${chalk.white('📝')} ${chalk.white(cleanBranch)}`);
}
} catch (e) {
console.log(` ${chalk.white('📝')} ${chalk.white(cleanBranch)}`);
}
}
});
// Show additional information if verbose
if (args.includes('-v') || args.includes('--verbose')) {
console.log(chalk.cyan('📊 Branch Details:'));
try {
// Show last commit for each local branch
const localBranchNames = localBranches.map(b => b.replace(/^\*?\s*/, '')).filter(b => !b.includes('remotes/'));
for (const branchName of localBranchNames.slice(0, 5)) { // Limit to 5 branches
try {
const lastCommit = execSync(`git log -1 --format="%h %s" ${branchName} 2>/dev/null`, { encoding: 'utf-8' }).trim();
const isCurrent = branchName === currentBranch;
const icon = isCurrent ? '➤' : '📝';
const color = isCurrent ? chalk.green : chalk.white;
console.log(` ${color(icon)} ${color(branchName)}: ${chalk.gray(lastCommit)}`);
} catch (e) {
// Ignore errors for individual branches
}
}
if (localBranchNames.length > 5) {
console.log(` ${chalk.gray(`... and ${localBranchNames.length - 5} more branches`)}`);
}
} catch (e) {
// Ignore verbose errors
}
}
console.log(chalk.gray('━'.repeat(40)));
console.log(chalk.cyan('💡 Branch Operations:'));
console.log(chalk.white(' gcheckout <branch>') + ' # Switch to branch');
console.log(chalk.white(' gbranch <new-name>') + ' # Create new branch');
console.log(chalk.white(' gbranch -a') + ' # Show all branches (local + remote)');
console.log(chalk.white(' gbranch -v') + ' # Verbose output with commit info');
console.log(chalk.white(' gbranch -d <branch>') + ' # Delete branch safely');
}
} catch (error) {
console.error(chalk.red(`❌ Error: ${error.message}`));
process.exit(1);
}
}
} else {
// Delete, move, or copy operations
if (!branchName) {
console.error(chalk.red(`❌ Error: Branch name required for ${action} operation`));
process.exit(1);
}
branchCmd += ` ${branchName}`;
if (action === 'force-delete') {
console.log(chalk.red('⚠️ WARNING: Force deleting branch can cause data loss!'));
}
console.log(chalk.cyan(`🔍 Running: ${branchCmd}`));
try {
const result = execSync(branchCmd, { encoding: 'utf-8' });
if (result) console.log(result);
console.log(chalk.green(`✅ Branch ${action} operation completed successfully`));
} catch (error) {
console.error(chalk.red(`❌ Error: ${error.message}`));
if (action === 'delete' && error.message.includes('not fully merged')) {
console.log(chalk.yellow('💡 Use gbranch -D to force delete unmerged branch'));
}
process.exit(1);
}
}
console.log(chalk.green('\n✅ Command completed successfully'));
}
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch(console.error);
}