-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGitManager.js
More file actions
6222 lines (5426 loc) Β· 198 KB
/
Copy pathGitManager.js
File metadata and controls
6222 lines (5426 loc) Β· 198 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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
const { exec } = require('child_process');
const MessageSplitter = require('./MessageSplitter');
/**
* Git Manager - Full Git Workflow Management for Telegram Bot
* Handles comprehensive git operations with mobile-friendly interface
*/
class GitManager {
constructor(bot, options, keyboardHandlers, mainBot) {
this.bot = bot;
this.options = options;
this.keyboardHandlers = keyboardHandlers;
this.mainBot = mainBot; // Reference to main bot for delegation
this.untrackedFilePagination = null; // For pagination state
this.messageSplitter = new MessageSplitter();
// Enhanced state management for full git operations
this.gitState = {
currentBranch: null,
branches: [],
stagedFiles: [],
unstagedFiles: [],
untrackedFiles: [],
commitInProgress: false,
commitMessageInProgress: false,
commitMessageChatId: null,
amendMessageInProgress: false,
amendMessageChatId: null,
lastCommitMessage: null,
branchSwitchInProgress: false,
branchCreationInProgress: false,
branchCreationChatId: null
};
// Performance optimization: Cache git status and branch info
this.gitStatusCache = {
data: null,
timestamp: 0,
maxAge: 2000 // 2 seconds cache
};
this.branchInfoCache = {
data: null,
timestamp: 0,
maxAge: 5000 // 5 seconds cache (branches change less frequently)
};
}
/**
* Invalidate caches when git state changes (performance optimization)
*/
invalidateCache() {
this.gitStatusCache.data = null;
this.gitStatusCache.timestamp = 0;
this.branchInfoCache.data = null;
this.branchInfoCache.timestamp = 0;
}
/**
* Get file type icon for better mobile UX (Phase 7.4 - UI/UX refinements)
*/
getFileTypeIcon(extension) {
const iconMap = {
'.js': 'π¨',
'.ts': 'π¦',
'.jsx': 'βοΈ',
'.tsx': 'βοΈ',
'.css': 'π¨',
'.scss': 'π¨',
'.html': 'π',
'.md': 'π',
'.json': 'π',
'.txt': 'π',
'.py': 'π',
'.java': 'β',
'.cpp': 'βοΈ',
'.c': 'βοΈ',
'.php': 'π',
'.sql': 'ποΈ',
'.xml': 'π',
'.yml': 'βοΈ',
'.yaml': 'βοΈ',
'.env': 'π§',
'.config': 'βοΈ'
};
return iconMap[extension.toLowerCase()] || 'π';
}
/**
* Analyze git command errors and provide user-friendly messages (Phase 7.3)
*/
analyzeGitError(error, operation = 'git operation') {
const errorMessage = error.message || error.toString();
const errorLower = errorMessage.toLowerCase();
// Authentication/Permission errors
if (errorLower.includes('permission denied') ||
errorLower.includes('authentication failed') ||
errorLower.includes('access denied') ||
errorLower.includes('fatal: could not read from remote repository')) {
return {
type: 'auth',
userMessage: 'π **Authentication Error**',
description: 'Git authentication failed. Please check your credentials.',
solutions: [
'Verify your Git username and email are configured',
'Check if you have access to the repository',
'Update your Git credentials or SSH keys',
'Try using a personal access token if using HTTPS'
],
technicalError: errorMessage
};
}
// Network/Connection errors
if (errorLower.includes('network') ||
errorLower.includes('connection') ||
errorLower.includes('timeout') ||
errorLower.includes('could not resolve host') ||
errorLower.includes('failed to connect')) {
return {
type: 'network',
userMessage: 'π **Network Error**',
description: 'Unable to connect to the remote repository.',
solutions: [
'Check your internet connection',
'Verify the repository URL is correct',
'Try again in a moment',
'Check if the remote server is accessible'
],
technicalError: errorMessage
};
}
// Merge conflicts
if (errorLower.includes('merge conflict') ||
errorLower.includes('conflict') ||
errorLower.includes('automatic merge failed')) {
return {
type: 'conflict',
userMessage: 'βοΈ **Merge Conflict**',
description: 'There are conflicting changes that need to be resolved.',
solutions: [
'Resolve conflicts manually in the affected files',
'Use git status to see which files have conflicts',
'After resolving, stage the files and commit',
'Consider using git mergetool for complex conflicts'
],
technicalError: errorMessage
};
}
// Branch related errors
if (errorLower.includes('branch') &&
(errorLower.includes('already exists') || errorLower.includes('not found'))) {
const isBranchExists = errorLower.includes('already exists');
return {
type: 'branch',
userMessage: isBranchExists ? 'πΏ **Branch Already Exists**' : 'πΏ **Branch Not Found**',
description: isBranchExists ?
'A branch with this name already exists.' :
'The specified branch could not be found.',
solutions: isBranchExists ? [
'Choose a different branch name',
'Delete the existing branch if no longer needed',
'Switch to the existing branch instead'
] : [
'Check the branch name spelling',
'List available branches to see what exists',
'Create the branch if it should exist'
],
technicalError: errorMessage
};
}
// Uncommitted changes
if (errorLower.includes('uncommitted changes') ||
errorLower.includes('working tree clean') ||
errorLower.includes('please commit') ||
errorLower.includes('stash')) {
return {
type: 'uncommitted',
userMessage: 'π **Uncommitted Changes**',
description: 'You have uncommitted changes that prevent this operation.',
solutions: [
'Commit your current changes first',
'Stash changes temporarily: git stash',
'Discard changes if they are not needed',
'Stage and commit specific files'
],
technicalError: errorMessage
};
}
// Repository not found/not a git repository
if (errorLower.includes('not a git repository') ||
errorLower.includes('no such file or directory')) {
return {
type: 'repository',
userMessage: 'π **Repository Error**',
description: 'This directory is not a Git repository or cannot be accessed.',
solutions: [
'Navigate to a valid Git repository',
'Initialize a new repository with git init',
'Clone an existing repository',
'Check if the directory path is correct'
],
technicalError: errorMessage
};
}
// File not found or permission issues
if (errorLower.includes('no such file') ||
errorLower.includes('file not found') ||
errorLower.includes('cannot access')) {
return {
type: 'file',
userMessage: 'π **File Error**',
description: 'The specified file could not be found or accessed.',
solutions: [
'Check if the file exists in the working directory',
'Verify file permissions',
'Refresh the file list and try again',
'Ensure the file has not been deleted'
],
technicalError: errorMessage
};
}
// Generic git command errors
if (errorLower.includes('fatal:') || errorLower.includes('error:')) {
return {
type: 'git',
userMessage: `β οΈ **${operation.charAt(0).toUpperCase() + operation.slice(1)} Error**`,
description: 'A Git command failed to execute properly.',
solutions: [
'Check the repository state',
'Ensure all prerequisites are met',
'Try refreshing and attempting again',
'Check Git configuration'
],
technicalError: errorMessage
};
}
// Default/unknown error
return {
type: 'unknown',
userMessage: `β **${operation.charAt(0).toUpperCase() + operation.slice(1)} Failed**`,
description: 'An unexpected error occurred.',
solutions: [
'Try the operation again',
'Check the repository state',
'Restart the application if needed',
'Contact support if the problem persists'
],
technicalError: errorMessage
};
}
/**
* Format error analysis for user display (Phase 7.3)
* Handles both old errorAnalysis format and new parsedError format
*/
formatErrorMessage(errorData, includeRecovery = true) {
// Handle new parsedError format (from parseGitError)
if (errorData.title && errorData.suggestions) {
let message = `${errorData.title}\n\n`;
message += `**Problem:** ${errorData.message}\n\n`;
if (includeRecovery && errorData.suggestions.length > 0) {
message += '**π‘ Possible Solutions:**\n';
errorData.suggestions.forEach(suggestion => {
message += `β’ ${suggestion}\n`;
});
message += '\n';
}
if (errorData.recoverable) {
message += 'π This issue can usually be resolved. Try the suggestions above.';
} else {
message += 'β οΈ This may require manual intervention or setup changes.';
}
return message;
}
// Handle old errorAnalysis format (backward compatibility)
let message = `${errorData.userMessage}\n\n`;
message += `**Problem:** ${errorData.description}\n\n`;
message += '**π‘ Solutions:**\n';
errorData.solutions.forEach((solution, index) => {
message += `${index + 1}. ${solution}\n`;
});
if (includeRecovery && errorData.technicalError) {
message += `\n**π§ Technical Details:**\n\`${errorData.technicalError}\``;
}
return message;
}
/**
* Enhanced error handling with user-friendly messages and recovery suggestions
*/
parseGitError(error, operation = 'git operation') {
const errorMessage = error.message || error.toString();
const lowercaseError = errorMessage.toLowerCase();
// Authentication errors
if (lowercaseError.includes('authentication failed') ||
lowercaseError.includes('permission denied') ||
lowercaseError.includes('access denied') ||
lowercaseError.includes('credential')) {
return {
type: 'auth',
title: 'π Authentication Error',
message: 'Git authentication failed.',
suggestions: [
'Check your Git credentials (username/password or SSH key)',
'Verify repository access permissions',
'Try: git config --global credential.helper store',
'For SSH: ensure your SSH key is added to your Git provider'
],
recoverable: true
};
}
// Network errors
if (lowercaseError.includes('network') ||
lowercaseError.includes('connection') ||
lowercaseError.includes('timeout') ||
lowercaseError.includes('could not resolve host') ||
lowercaseError.includes('failed to connect')) {
return {
type: 'network',
title: 'π Network Error',
message: 'Unable to connect to remote repository.',
suggestions: [
'Check your internet connection',
'Verify the repository URL is correct',
'Try again in a few moments',
'Check if the Git provider is experiencing issues'
],
recoverable: true
};
}
// Merge conflicts
if (lowercaseError.includes('merge conflict') ||
lowercaseError.includes('conflict') ||
lowercaseError.includes('automatic merge failed')) {
return {
type: 'conflict',
title: 'βοΈ Merge Conflict',
message: 'Git detected conflicting changes.',
suggestions: [
'Resolve conflicts manually using your preferred editor',
'Use git status to see conflicted files',
'After resolving: git add <files> then git commit',
'Or use git merge --abort to cancel the merge'
],
recoverable: true
};
}
// Repository not found
if (lowercaseError.includes('not a git repository') ||
lowercaseError.includes('not found') ||
lowercaseError.includes('does not exist')) {
return {
type: 'repository',
title: 'π Repository Error',
message: 'Git repository not found or inaccessible.',
suggestions: [
'Ensure you\'re in a Git repository directory',
'Initialize with: git init',
'Clone the repository if it\'s remote',
'Check directory permissions'
],
recoverable: false
};
}
// Branch errors
if (lowercaseError.includes('branch') &&
(lowercaseError.includes('already exists') || lowercaseError.includes('not found'))) {
return {
type: 'branch',
title: 'πΏ Branch Error',
message: 'Branch operation failed.',
suggestions: [
'Check if branch name already exists: git branch -a',
'Use a different branch name',
'Delete existing branch: git branch -d <name>',
'Ensure branch name follows Git naming rules'
],
recoverable: true
};
}
// Working directory not clean
if (lowercaseError.includes('working tree clean') ||
lowercaseError.includes('uncommitted changes') ||
lowercaseError.includes('working directory')) {
return {
type: 'dirty',
title: 'π Uncommitted Changes',
message: 'Repository has uncommitted changes.',
suggestions: [
'Commit your changes: git add . && git commit',
'Stash changes: git stash',
'Discard changes: git checkout -- .',
'Check status: git status'
],
recoverable: true
};
}
// Push/pull specific errors
if (lowercaseError.includes('rejected') || lowercaseError.includes('non-fast-forward')) {
return {
type: 'rejected',
title: 'β οΈ Push Rejected',
message: 'Push was rejected by remote repository.',
suggestions: [
'Pull latest changes first: git pull',
'Merge or rebase your changes',
'Use force push with caution: git push --force',
'Check if someone else pushed changes'
],
recoverable: true
};
}
// Generic git error
return {
type: 'generic',
title: 'β Git Error',
message: `${operation} failed: ${errorMessage}`,
suggestions: [
'Check git status for repository state',
'Ensure all files are saved',
'Try the operation again',
'Check Git documentation for this error'
],
recoverable: true
};
}
/**
* Main entry point - Show git overview with full workflow options
*/
async showGitOverview(chatId, options = {}) {
const {
mode = 'overview',
page = 0,
fileIndex = 0,
contextLines = 3,
wordDiff = false
} = options;
try {
// Check if we're in a git repository
const isGitRepo = await this.checkGitRepository();
if (!isGitRepo) {
await this.mainBot.safeSendMessage(chatId,
'β **Not a Git Repository**\n\n' +
'This directory is not a git repository.\n' +
'Use `π Projects` to navigate to a git project.',
{
reply_markup: this.keyboardHandlers.getReplyKeyboardMarkup(this.mainBot.getUserIdFromChat(chatId))
}
);
return;
}
// Get comprehensive git status including branch info
const gitStatus = await this.getGitStatus();
if (mode === 'overview') {
await this.showMainGitInterface(chatId, gitStatus);
} else if (mode === 'files') {
await this.showFileList(chatId, gitStatus, page);
} else if (mode === 'file') {
await this.showDiffFile(chatId, gitStatus, fileIndex, contextLines, wordDiff);
} else if (mode === 'branches') {
await this.showBranchManagement(chatId);
} else if (mode === 'staging') {
await this.showStagingInterface(chatId);
} else if (mode === 'commit') {
await this.showCommitInterface(chatId);
}
} catch (error) {
console.error('[Git Manager] Error:', error);
// Use enhanced error handling
const parsedError = this.parseGitError(error, 'Git Manager');
const errorMessage = this.formatErrorMessage(parsedError);
await this.mainBot.safeSendMessage(chatId, errorMessage, {
reply_markup: {
inline_keyboard: [
[
{ text: 'π Try Again', callback_data: 'git:refresh' },
{ text: 'π Check Status', callback_data: 'git:overview' }
],
[
{ text: 'π Main Menu', callback_data: 'main_menu' }
]
]
}
});
}
}
/**
* Legacy method for backward compatibility with existing /diff command
*/
async showGitDiff(chatId, options = {}) {
return await this.showGitOverview(chatId, options);
}
/**
* Check if current directory is a git repository
*/
async checkGitRepository() {
try {
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
await execAsync('git rev-parse --git-dir', {
cwd: this.options.workingDirectory
});
return true;
} catch {
return false;
}
}
/**
* Get comprehensive git status including branch information (with caching)
*/
async getGitStatus() {
// Check cache first for performance optimization
const now = Date.now();
if (this.gitStatusCache.data &&
(now - this.gitStatusCache.timestamp) < this.gitStatusCache.maxAge) {
return this.gitStatusCache.data;
}
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
const cwd = this.options.workingDirectory;
try {
// Get current branch and ahead/behind info
let currentBranch = 'main';
const aheadBehind = { ahead: 0, behind: 0 };
try {
const branchResult = await execAsync('git branch --show-current', { cwd });
currentBranch = branchResult.stdout.trim() || 'main';
// Get ahead/behind info
const statusResult = await execAsync('git status --porcelain -b', { cwd });
const statusLines = statusResult.stdout.split('\n');
const branchLine = statusLines.find(line => line.startsWith('##'));
if (branchLine) {
const aheadMatch = branchLine.match(/ahead (\d+)/);
const behindMatch = branchLine.match(/behind (\d+)/);
if (aheadMatch) aheadBehind.ahead = parseInt(aheadMatch[1]);
if (behindMatch) aheadBehind.behind = parseInt(behindMatch[1]);
}
} catch (branchError) {
console.log('[Git] Branch info error (using defaults):', branchError.message);
}
// Get basic status (includes untracked files)
const statusResult = await execAsync('git status --porcelain', { cwd });
const modifiedFiles = statusResult.stdout.trim().split('\n').filter(line => line.trim());
// Get diff stats (includes both staged and unstaged changes)
const statsResult = await execAsync('git diff HEAD --stat --color=never', { cwd });
const diffStats = statsResult.stdout.trim();
// Get file details (includes both staged and unstaged changes)
const nameStatusResult = await execAsync('git diff HEAD --name-status', { cwd });
const gitDiffNameStatus = nameStatusResult.stdout.trim().split('\n').filter(line => line.trim());
// Get numeric stats (includes both staged and unstaged changes)
const numStatsResult = await execAsync('git diff HEAD --numstat', { cwd });
const numStats = numStatsResult.stdout.trim().split('\n').filter(line => line.trim());
// Parse git status --porcelain to get ALL files including untracked
const allFiles = [];
const allNumStats = [];
const stagedFiles = [];
const unstagedFiles = [];
const untrackedFiles = [];
modifiedFiles.forEach(line => {
// Git status --porcelain format: XY filename
// X and Y are status codes, followed by space(s), then filename
const status = line.substring(0, 2);
// Find the first non-space character after the status to get the filename
let filenameStart = 2;
while (filenameStart < line.length && line.charAt(filenameStart) === ' ') {
filenameStart++;
}
const filename = line.substring(filenameStart);
// Categorize files by staging status
const xStatus = status.charAt(0); // Staged status
const yStatus = status.charAt(1); // Unstaged status
if (status.includes('??')) {
// Untracked file
untrackedFiles.push(filename);
allFiles.push(`??\t${filename}`);
// For untracked files, count lines and show as all added
try {
const fs = require('fs');
const filePath = path.join(cwd, filename);
const content = fs.readFileSync(filePath, 'utf8');
const lineCount = content.split('\n').length;
allNumStats.push(`${lineCount}\t0\t${filename}`);
} catch {
allNumStats.push(`0\t0\t${filename}`);
}
} else {
// Tracked file - check staging status
if (xStatus !== ' ' && xStatus !== '?') {
stagedFiles.push(filename);
}
if (yStatus !== ' ' && yStatus !== '?') {
unstagedFiles.push(filename);
}
if (status.includes('A')) {
// Added file (staged)
allFiles.push(`A\t${filename}`);
} else if (status.includes('M')) {
// Modified file - use 'M' regardless of position
allFiles.push(`M\t${filename}`);
} else if (status.includes('D')) {
// Deleted file
allFiles.push(`D\t${filename}`);
} else if (status.includes('R')) {
// Renamed file
allFiles.push(`R\t${filename}`);
} else {
// Other status, use first non-space character
const statusChar = status.trim() || status.charAt(0);
allFiles.push(`${statusChar}\t${filename}`);
}
}
});
// Use combined file list (git diff + untracked files) as nameStatus
const nameStatus = allFiles.length > 0 ? allFiles : gitDiffNameStatus;
// Combine numStats from git diff with untracked file stats
const combinedNumStats = [...numStats, ...allNumStats];
const hasChanges = modifiedFiles.length > 0 || (diffStats.length > 0 && diffStats.trim() !== '');
// Update internal state
this.gitState = {
...this.gitState,
currentBranch,
stagedFiles,
unstagedFiles,
untrackedFiles
};
const result = {
modifiedFiles,
diffStats,
nameStatus,
numStats: combinedNumStats,
hasChanges,
currentBranch,
aheadBehind,
stagedFiles,
unstagedFiles,
untrackedFiles
};
// Cache the result for performance optimization
this.gitStatusCache = {
data: result,
timestamp: Date.now(),
maxAge: this.gitStatusCache.maxAge
};
return result;
} catch (error) {
throw new Error(`Git status failed: ${error.message}`);
}
}
/**
* Show main git interface with comprehensive workflow options
*/
async showMainGitInterface(chatId, gitStatus) {
const { currentBranch, aheadBehind, stagedFiles, untrackedFiles } = gitStatus;
// Enhanced mobile-optimized status display (Phase 7.4 - UI/UX refinements)
let text = 'πΏ **Git Repository Manager**\n\n';
// Compact directory display - show only project name for better mobile readability
const projectName = path.basename(this.options.workingDirectory);
text += `π ${this.escapeMarkdown(projectName)}\n`;
// Enhanced branch display with visual status indicators
text += `πΏ **${this.escapeMarkdown(currentBranch)}**`;
// Add ahead/behind indicators with better mobile formatting
if (aheadBehind.ahead > 0 || aheadBehind.behind > 0) {
const indicators = [];
if (aheadBehind.ahead > 0) indicators.push(`βοΈ${aheadBehind.ahead}`);
if (aheadBehind.behind > 0) indicators.push(`βοΈ${aheadBehind.behind}`);
text += ` (${indicators.join(' ')})`;
}
text += '\n\n';
// Enhanced mobile-friendly file status summary with icons and compact layout
const totalChanged = gitStatus.nameStatus.length;
const totalStaged = stagedFiles.length;
const totalUntracked = untrackedFiles.length;
// Visual status indicators for quick scanning
if (gitStatus.hasChanges) {
text += 'π **Status:**\n';
if (totalChanged > 0) text += `π Changed: **${totalChanged}**\n`;
if (totalStaged > 0) text += `β
Staged: **${totalStaged}**\n`;
if (totalUntracked > 0) text += `π Untracked: **${totalUntracked}**\n`;
text += '\n';
} else {
text += 'β
**Working directory is clean**\n\n';
}
// Smart action suggestions based on repository state
if (totalStaged > 0) {
text += 'π‘ *Ready to commit staged changes*\n';
} else if (totalChanged > 0) {
text += 'π‘ *Stage files to prepare for commit*\n';
} else if (aheadBehind.ahead > 0) {
text += 'π‘ *Local commits ready to push*\n';
} else if (aheadBehind.behind > 0) {
text += 'π‘ *Remote updates available to pull*\n';
}
text += '\n**Choose action:**';
// Mobile-optimized keyboard layout with contextual actions
const keyboard = {
inline_keyboard: []
};
// Priority actions in first row based on repository state
if (totalStaged > 0) {
// Ready to commit - prioritize commit action
keyboard.inline_keyboard.push([
{ text: 'π Commit', callback_data: 'git:commit:prepare' },
{ text: 'π¦ Staging', callback_data: 'git:staging:overview' }
]);
} else if (totalChanged > 0) {
// Has changes - prioritize staging
keyboard.inline_keyboard.push([
{ text: 'π¦ Staging', callback_data: 'git:staging:overview' },
{ text: 'π Files', callback_data: 'git:files:0' }
]);
} else {
// Clean or remote actions needed
keyboard.inline_keyboard.push([
{ text: 'π Overview', callback_data: 'git:overview' },
{ text: 'π Files', callback_data: 'git:files:0' }
]);
}
// Branch and remote operations row
keyboard.inline_keyboard.push([
{ text: 'πΏ Branches', callback_data: 'git:branch:list' },
{ text: 'π History', callback_data: 'git:commit:history' }
]);
// Remote operations row with contextual emphasis
const remoteRow = [];
if (aheadBehind.ahead > 0) {
remoteRow.push({ text: 'β¬οΈ Push', callback_data: 'git:push' });
} else {
remoteRow.push({ text: 'β¬οΈ Push', callback_data: 'git:push' });
}
if (aheadBehind.behind > 0) {
remoteRow.push({ text: 'π Pull', callback_data: 'git:pull' });
} else {
remoteRow.push({ text: 'β¬οΈ Fetch', callback_data: 'git:fetch' });
}
keyboard.inline_keyboard.push(remoteRow);
// Refresh button row
keyboard.inline_keyboard.push([
{ text: 'π Refresh', callback_data: 'git:refresh' }
]);
// Send markdown text directly - MarkdownHtmlConverter will handle conversion
await this.mainBot.safeSendMessage(chatId, text, {
reply_markup: keyboard
});
}
/**
* Get comprehensive branch information (with caching)
*/
async getBranchInfo() {
// Check cache first for performance optimization
const now = Date.now();
if (this.branchInfoCache.data &&
(now - this.branchInfoCache.timestamp) < this.branchInfoCache.maxAge) {
return this.branchInfoCache.data;
}
const { exec } = require('child_process');
const { promisify } = require('util');
const execAsync = promisify(exec);
const cwd = this.options.workingDirectory;
try {
// Get current branch
const currentBranchResult = await execAsync('git branch --show-current', { cwd });
const currentBranch = currentBranchResult.stdout.trim() || 'main';
// Get all local branches with verbose info
const branchListResult = await execAsync('git branch -v', { cwd });
const branchLines = branchListResult.stdout.trim().split('\n');
const branches = [];
let currentBranchInfo = null;
for (const line of branchLines) {
// Parse branch line: "* main abc1234 commit message" or " develop def5678 commit message"
const match = line.match(/^(\*?\s*)([^\s]+)\s+([a-f0-9]+)\s+(.*)$/);
if (match) {
const [, marker, branchName, hash, message] = match;
const isCurrent = marker.includes('*');
// Get ahead/behind info only for current branch (performance optimization)
let ahead = 0;
let behind = 0;
if (isCurrent) {
try {
// Check if branch has upstream
const upstreamResult = await execAsync(`git rev-list --count --left-right ${branchName}...origin/${branchName}`, { cwd });
const counts = upstreamResult.stdout.trim().split('\t');
if (counts.length === 2) {
ahead = parseInt(counts[0]) || 0;
behind = parseInt(counts[1]) || 0;
}
} catch (upstreamError) {
// No upstream or other error - ignore
console.log(`[Branch] No upstream for ${branchName}: ${upstreamError.message}`);
}
}
const branchInfo = {
name: branchName,
hash,
message,
current: isCurrent,
ahead,
behind
};
branches.push(branchInfo);
if (isCurrent) {
currentBranchInfo = branchInfo;
}
}
}
const result = {
currentBranch,
currentBranchInfo,
branches
};
// Cache the result for performance optimization
this.branchInfoCache = {
data: result,
timestamp: Date.now(),
maxAge: this.branchInfoCache.maxAge
};
return result;
} catch (error) {
throw new Error(`Failed to get branch info: ${error.message}`);
}
}
/**
* Show branch switching interface
*/
async showBranchSwitchList(chatId) {
try {
const branchInfo = await this.getBranchInfo();
// Filter out current branch from switch options
const availableBranches = branchInfo.branches.filter(branch => !branch.current);
if (availableBranches.length === 0) {
await this.mainBot.safeSendMessage(chatId,
'πΏ **Branch Switching**\n\n' +
'No other branches available to switch to.\n' +
`Currently on: \`${branchInfo.currentBranch}\``,
{
reply_markup: {
inline_keyboard: [[
{ text: 'π Create New Branch', callback_data: 'git:branch:create' },
{ text: 'π Back', callback_data: 'git:branch:list' }
]]
}
}
);
return;
}
let text = 'πΏ **Switch Branch**\n\n';
text += `**Current:** ${branchInfo.currentBranch}\n\n`;
text += '**Available Branches:**\n';
const keyboard = {
inline_keyboard: []
};
// Add branch buttons (max 5 per page for mobile-friendly interface)
const branchesPerPage = 5;
const displayBranches = availableBranches.slice(0, branchesPerPage);
displayBranches.forEach((branch) => {
text += `πΏ ${branch.name}`;
if (branch.ahead > 0 || branch.behind > 0) {
const indicators = [];
if (branch.ahead > 0) indicators.push(`βοΈ ${branch.ahead}`);
if (branch.behind > 0) indicators.push(`βοΈ ${branch.behind}`);
text += ` (${indicators.join(', ')})`;
}
text += '\n';
// Add button for this branch (shorten name if too long)
const buttonText = branch.name.length > 25 ? branch.name.substring(0, 22) + '...' : branch.name;
keyboard.inline_keyboard.push([{
text: `β‘οΈ ${buttonText}`,
callback_data: `git:branch:switch:${encodeURIComponent(branch.name)}`
}]);
});
// Navigation buttons
keyboard.inline_keyboard.push([
{ text: 'π Back to Branches', callback_data: 'git:branch:list' }
]);
await this.mainBot.safeSendMessage(chatId, text, {
reply_markup: keyboard
});
} catch (error) {
console.error('[Branch Switch List] Error:', error);
const parsedError = this.parseGitError(error, 'branch listing');
const errorMessage = this.formatErrorMessage(parsedError);
await this.mainBot.safeSendMessage(chatId,
errorMessage,
{
reply_markup: {
inline_keyboard: [[
{ text: 'π Back to Branches', callback_data: 'git:branch:list' }
]]
}
}
);
}
}
/**
* Switch to a specific branch
*/