-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.engine.pas
More file actions
1554 lines (1335 loc) · 55.9 KB
/
Copy pathgit.engine.pas
File metadata and controls
1554 lines (1335 loc) · 55.9 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
unit Git.Engine;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, DateUtils, LazLogger, // DateUtils provides UnixToDateTime
libgit2; // Consumes the flat libgit2-delphi API layer
type
{ Custom exception specifically for Git sub-system failures }
EGitException = class(Exception);
{ Data record to simplify file status outputs to the frontend }
TGitFileStatus = record
Path: string;
State: string;
RawFlags: Cardinal;
end;
// A dynamic array type to pass lists of changed files cleanly
TGitFileStatusArray = array of TGitFileStatus;
TUnifiedNetworkPayload = record
AuthData: git_credential_userpass_payload;
LogOutput: TStrings;
end;
PUnifiedNetworkPayload = ^TUnifiedNetworkPayload;
type
// Holds a single point on our visual timeline graph
TGitGraphNode = record
CommitId: string; // The unique SHA-1 hash of this commit
Message: string; // The summary title text
Author: string; // Author identity
Timestamp: TDateTime;// Timestamp
ParentIds: array of string; // Dynamic array holding all parent SHAs
GraphLane: Integer; // The column index of the node circle dot
ParentLanes: array of Integer; // The destination column lanes this row must route lines toward
ActiveLanes: array of string; // after parent assignment — tells drawing what continues BELOW -- Snapshot array of all branch SHAs traversing through this row cell
IncomingLanes: array of string;// before parent assignment — tells drawing what arrives FROM ABOVE
end;
TGitGraphArray = array of TGitGraphNode;
{ Data record to simplify commit tracking details for the UI }
TGitCommitDetails = record
Id: string; // The Commit SHA Hash string
Message: string; // The Commit Message summary
Author: string; // Author name string
Email: string; // Author email string
Timestamp: TDateTime;
end;
TGitCommitHistoryArray = array of TGitCommitDetails;
{ The Object-Oriented Git Workspace Controller }
TGitRepository = class
private
FHandle: Pgit_repository; // The actual C-pointer tracking our open repository
FIsInitialized: Boolean;
FDefaultAuthorName: string;
FDefaultAuthorEmail: string;
FGitToken: string;
FAnsiUser: AnsiString;
FAnsiToken: AnsiString;
FAuthPayload: git_credential_userpass_payload;
procedure CheckError(const ApiResult: Integer);
procedure LoadUserIdentity;
public
constructor Open(const WorkspacePath: string);
constructor Init(const WorkspacePath: string);
constructor Clone(const URL, LocalPath, Username, Token: string; LogOutput: TStrings);
destructor Destroy; override;
function GetActiveBranchName: string;
function GetStatus: TGitFileStatusArray;
function GetCommitHistory: TGitCommitHistoryArray;
function HasStagedChanges: Boolean;
function GetFileDiff(const RelativeFilePath: string): string;
function GetRemotesList: TStringList;
function GetLocalBranchesList: TStringList;
function IsRebasing: Boolean;
function GetCommitGraph: TGitGraphArray;
procedure Push(const RemoteName, BranchName: string);
procedure Pull(const RemoteName: string; LogOutput: TStrings);
procedure RebaseContinue;
procedure RebaseAbort;
procedure RebaseBranch(const UpstreamBranchName: string);
procedure MergeBranch(const SourceBranchName: string);
procedure RenameBranch(const OldBranchName, NewBranchName: string);
procedure StashSave(const StashMessage, OverrideName, OverrideEmail: string);
procedure StashPop;
procedure DeleteBranch(const BranchName: string);
procedure CreateBranch(const NewBranchName: string);
procedure SwitchToBranch(const BranchName: string);
procedure Fetch(const RemoteName: string; LogOutput: TStrings);
procedure DiscardChanges(const RelativeFilePath: string);
procedure StageFile(const RelativeFilePath: string);
procedure UnstageFile(const RelativeFilePath: string);
procedure Commit(const CommitMessage, OverrideName, OverrideEmail: string);
property GitToken: string read FGitToken write FGitToken;
property DefaultAuthorName: string read FDefaultAuthorName;
property DefaultAuthorEmail: string read FDefaultAuthorEmail;
property Handle: Pgit_repository read FHandle;
end;
implementation
// Standalone context helper used internally by the status callback thread
type
PStatusCallbackPayload = ^TStatusCallbackPayload;
TStatusCallbackPayload = record
List: TGitFileStatusArray;
Count: Integer;
end;
// Internal matching signature mapping for the C callback engine
function InternalStatusCallback(path: PAnsiChar; status_flags: Cardinal; payload: Pointer): Integer; cdecl;
var
Data: PStatusCallbackPayload;
StateStr: string;
begin
Data := PStatusCallbackPayload(payload);
// Decode the bitmask flags down to human readable Pascal strings
if (status_flags and GIT_STATUS_CONFLICTED) <> 0 then StateStr := '🔴 CONFLICT (Unmerged)'
else if (status_flags and GIT_STATUS_WT_NEW) <> 0 then StateStr := 'Untracked'
else if (status_flags and GIT_STATUS_WT_MODIFIED) <> 0 then StateStr := 'Modified'
else if (status_flags and GIT_STATUS_WT_DELETED) <> 0 then StateStr := 'Deleted'
else if (status_flags and GIT_STATUS_INDEX_NEW) <> 0 then StateStr := 'Staged (New)'
else if (status_flags and GIT_STATUS_INDEX_MODIFIED) <> 0 then StateStr := 'Staged (Modified)'
else Exit(0); // Safely skip pristine/clean repository files
// Grow our safe Pascal dynamic array on the fly
Inc(Data^.Count);
SetLength(Data^.List, Data^.Count);
Data^.List[Data^.Count - 1].Path := string(path);
Data^.List[Data^.Count - 1].State := StateStr;
Data^.List[Data^.Count - 1].RawFlags := status_flags;
Result := 0; // 0 tells libgit2 to continue reading the directory tree
end;
// Internal function matching libgit2's network transfer progress signature
function InternalTransferProgressCallback(stats: Pgit_indexer_progress; payload: Pointer): Integer; cdecl;
var
UnifiedPackage: PUnifiedNetworkPayload;
LogStrings: TStrings;
LogMessage: string;
Percent: Double;
begin
UnifiedPackage := PUnifiedNetworkPayload(payload);
if not Assigned(UnifiedPackage) or not Assigned(UnifiedPackage^.LogOutput) then Exit(0);
LogStrings := UnifiedPackage^.LogOutput;
Percent := 0.0;
// 1. Calculate the real-time completion percentage metrics
if stats^.total_objects > 0 then
Percent := (stats^.received_objects / stats^.total_objects) * 100.0;
// 2. Format a highly professional terminal console logging string string
LogMessage := Format('📡 Downloading objects: %d/%d (%d%%) | %d bytes received',
[stats^.received_objects, stats^.total_objects, Trunc(Percent), stats^.received_bytes]);
// Overwrite the last line in the ListBox so it updates smoothly without creating 10,000 lines of scrolling clutter
if (LogStrings.Count > 0) and (Pos('📡 Downloading', LogStrings[LogStrings.Count - 1]) = 1) then
LogStrings[LogStrings.Count - 1] := LogMessage
else
LogStrings.Add(LogMessage);
// Force a native system thread context refresh switch so the UI paints the progress instantly
CheckSynchronize(0);
Result := 0;
end;
{ TGitRepository }
procedure TGitRepository.CheckError(const ApiResult: Integer);
var
LastError: PGit_Error;
begin
// Standardized error-trapping engine for all internal libgit2 interactions
if ApiResult < 0 then
begin
LastError := git_error_last();
if Assigned(LastError) then
raise EGitException.Create('Git Error (' + IntToStr(ApiResult) + '): ' + string(LastError^.message))
else
raise EGitException.Create('Unhandled Git Subsystem Exception. Code: ' + IntToStr(ApiResult));
end;
end;
procedure TGitRepository.LoadUserIdentity;
var
ConfigHandle: Pgit_config;
BufName, BufEmail: PAnsiChar;
begin
// Set safe application-level defaults
FDefaultAuthorName := 'GitBuddy Developer';
FDefaultAuthorEmail := 'developer@gitbuddy.local';
ConfigHandle := nil;
// 1. Take a frozen snapshot of the repository configuration ecosystem.
// This triggers the full escalation logic (Local > Global > System) natively!
if git_repository_config_snapshot(@ConfigHandle, FHandle) = 0 then
begin
try
// 2. Query the prioritized snapshot for the username string
if git_config_get_string(@BufName, ConfigHandle, 'user.name') = 0 then
FDefaultAuthorName := string(BufName);
// 3. Query the prioritized snapshot for the email string
if git_config_get_string(@BufEmail, ConfigHandle, 'user.email') = 0 then
FDefaultAuthorEmail := string(BufEmail);
finally
// 4. Clean up the snapshot out of memory as demanded by the documentation comments
git_config_free(ConfigHandle);
end;
end;
end;
constructor TGitRepository.Open(const WorkspacePath: string);
var
LocalAnsiStr: AnsiString;
begin
inherited Create;
FHandle := nil;
FIsInitialized := False;
// 1. Force spin up the C engine
CheckError(git_libgit2_init());
FIsInitialized := True;
// 2. Protect and transform the incoming Pascal string path safely
LocalAnsiStr := AnsiString(WorkspacePath);
// 3. Open handle securely
CheckError(git_repository_open(@FHandle, PAnsiChar(LocalAnsiStr)));
// 4. Load the user credentials into the object fields immediately upon opening!
LoadUserIdentity;
end;
constructor TGitRepository.Init(const WorkspacePath: string);
var
LocalPathAnsi: AnsiString;
begin
inherited Create;
FHandle := nil;
FIsInitialized := False;
CheckError(git_libgit2_init());
FIsInitialized := True;
LocalPathAnsi := AnsiString(WorkspacePath);
// Initializes the directory structure and assigns
// the live pointer directly to FHandle. The repository object is now ALIVE.
CheckError(git_repository_init(@FHandle, PAnsiChar(LocalPathAnsi), 0));
LoadUserIdentity;
end;
constructor TGitRepository.Clone(const URL, LocalPath, Username, Token: string; LogOutput: TStrings);
var
CloneOpts: git_clone_options;
LocalURL, LocalPathStr: AnsiString;
NetworkPackage: TUnifiedNetworkPayload;
LocalAnsiUser, LocalAnsiToken: AnsiString;
begin
inherited Create;
FHandle := nil;
FIsInitialized := False;
CheckError(git_libgit2_init());
FIsInitialized := True;
LocalURL := AnsiString(URL);
LocalPathStr := AnsiString(LocalPath);
CheckError(git_clone_options_init(@CloneOpts, 1));
LocalAnsiUser := AnsiString(Username);
if LocalAnsiUser = '' then LocalAnsiUser := 'git';
LocalAnsiToken := AnsiString(Token);
NetworkPackage.AuthData.username := PAnsiChar(LocalAnsiUser);
NetworkPackage.AuthData.password := PAnsiChar(LocalAnsiToken);
NetworkPackage.LogOutput := LogOutput;
CloneOpts.fetch_opts.callbacks.credentials := @git_credential_userpass;
CloneOpts.fetch_opts.callbacks.transfer_progress := @InternalTransferProgressCallback;
CloneOpts.fetch_opts.callbacks.payload := @NetworkPackage;
if Assigned(LogOutput) then
LogOutput.Add('📡 Initializing secure object download mapping for clone target: ' + URL);
// Downloads the cloud objects and assigns the live pointer directly to FHandle!
CheckError(git_clone(@FHandle, PAnsiChar(LocalURL), PAnsiChar(LocalPathStr), @CloneOpts));
// Cache the token to the instance field for future push/pull operations
FGitToken := Token;
LoadUserIdentity;
end;
destructor TGitRepository.Destroy;
begin
// Clean up repository context handle automatically out of RAM
if Assigned(FHandle) then
git_repository_free(FHandle);
// Safely spin down subsystem context counters
if FIsInitialized then
git_libgit2_shutdown();
inherited Destroy;
end;
function TGitRepository.GetActiveBranchName: string;
var
HeadRef: Pgit_reference;
BranchName: PAnsiChar;
begin
Result := '';
HeadRef := nil;
// Read head pointer safely
if git_repository_head(@HeadRef, FHandle) = 0 then
begin
BranchName := git_reference_shorthand(HeadRef);
Result := string(BranchName);
git_reference_free(HeadRef); // Free reference memory immediately inside C layer
end
else
begin
// Check if git_repository_head_unborn returns true or read the reference shorthand directly
if git_repository_head_unborn(FHandle) = 1 then
begin
// Pull the virtual path string out of the config
// Alternate bulletproof check: ask libgit2 to resolve the reference name of the symbolic link
if git_reference_dwim(@HeadRef, FHandle, 'HEAD') = 0 then
begin
try
Result := string(git_reference_shorthand(HeadRef)); // Returns 'main' or 'master' flawlessly!
finally
git_reference_free(HeadRef);
end;
end;
end;
end;
if Result = '' then Result := 'main'; // Ultimate structural fallback guard
end;
function TGitRepository.GetStatus: TGitFileStatusArray;
var
PayloadContext: TStatusCallbackPayload;
begin
PayloadContext.Count := 0;
SetLength(PayloadContext.List, 0);
// Feed our internal helper callback function directly to the dynamic loop
CheckError(git_status_foreach(FHandle, @InternalStatusCallback, @PayloadContext));
// Return the fully populated safe Pascal array back to the frontend
Result := PayloadContext.List;
end;
function TGitRepository.GetCommitHistory: TGitCommitHistoryArray;
var
Walker: Pgit_revwalk;
CommitOid: git_oid;
CommitObj: Pointer;
AuthorSig: Pgit_signature;
HistoryList: TGitCommitHistoryArray;
Count: Integer;
Buf: array[0..40] of Char;
begin
Count := 0;
HistoryList := nil;
SetLength(HistoryList, 0);
Walker := nil;
// THE NEWBORN SHIELD: If the repository has zero commits, head is unborn.
// We exit gracefully with our empty array rather than letting the walker throw a crash!
if git_repository_head_unborn(FHandle) = 1 then
Exit;
if git_revwalk_new(@Walker, FHandle) = 0 then
begin
try
git_revwalk_push_head(Walker);
git_revwalk_sorting(Walker, GIT_SORT_TOPOLOGICAL or GIT_SORT_TIME);
while git_revwalk_next(@CommitOid, Walker) = 0 do
begin
CommitObj := nil;
if git_commit_lookup(@CommitObj, FHandle, @CommitOid) = 0 then
begin
try
Inc(Count);
SetLength(HistoryList, Count);
git_oid_fmt(Buf, @CommitOid);
Buf[40] := #0; // Explicitly null-terminate the buffer index
HistoryList[Count - 1].Id := StrPas(Buf);
HistoryList[Count - 1].Message := string(git_commit_message(CommitObj));
AuthorSig := git_commit_author(CommitObj);
if Assigned(AuthorSig) then
begin
// Mapping directly to the 'name_' and 'email' fields found in signature.inc!
HistoryList[Count - 1].Author := string(AuthorSig^.name_);
HistoryList[Count - 1].Email := string(AuthorSig^.email);
HistoryList[Count - 1].Timestamp := UnixToDateTime(AuthorSig^.when.time);
end;
finally
git_commit_free(CommitObj);
end;
end;
end;
finally
git_revwalk_free(Walker);
end;
end;
Result := HistoryList;
end;
procedure TGitRepository.StageFile(const RelativeFilePath: string);
var
IndexHandle: Pgit_index;
LocalPathStr: AnsiString;
begin
IndexHandle := nil;
CheckError(git_repository_index(@IndexHandle, FHandle));
try
LocalPathStr := AnsiString(RelativeFilePath);
CheckError(git_index_add_bypath(IndexHandle, PAnsiChar(LocalPathStr)));
CheckError(git_index_write(IndexHandle)); // Save index back to the disk filesystem
finally
git_index_free(IndexHandle);
end;
end;
procedure TGitRepository.UnstageFile(const RelativeFilePath: string);
var
IndexHandle: Pgit_index;
HeadRef: Pgit_reference;
HeadCommitObj: Pgit_object;
LocalPathStr: AnsiString;
PathsStrArray: git_strarray;
PCharPath: PAnsiChar;
begin
IndexHandle := nil;
HeadRef := nil;
HeadCommitObj := nil;
CheckError(git_repository_index(@IndexHandle, FHandle));
try
LocalPathStr := AnsiString(RelativeFilePath);
PCharPath := PAnsiChar(LocalPathStr);
PathsStrArray.strings := @PCharPath;
PathsStrArray.count := 1;
if git_repository_head(@HeadRef, FHandle) = 0 then
begin
try
if git_reference_peel(@HeadCommitObj, HeadRef, GIT_OBJECT_COMMIT) = 0 then
begin
CheckError(git_reset_default(FHandle, HeadCommitObj, @PathsStrArray));
Exit;
end;
finally
if Assigned(HeadCommitObj) then git_object_free(HeadCommitObj);
if Assigned(HeadRef) then git_reference_free(HeadRef);
end;
end;
CheckError(git_index_remove_bypath(IndexHandle, PAnsiChar(LocalPathStr)));
CheckError(git_index_write(IndexHandle));
finally
git_index_free(IndexHandle);
end;
end;
procedure TGitRepository.Commit(const CommitMessage, OverrideName, OverrideEmail: string);
var
IndexHandle: Pgit_index;
TreeOid: git_oid;
TreeObj: Pgit_tree;
ParentCount: Integer;
HeadRef: Pgit_reference;
HeadOid: git_oid;
MergeHeadOid: git_oid;
ParentsArray: array[0..1] of Pgit_commit; // FIXED: Can hold up to 2 parent commit nodes!
Signature: Pgit_signature;
NewCommitOid: git_oid;
LocalMsg, LocalName, LocalEmail: AnsiString;
I: Integer;
begin
IndexHandle := nil;
TreeObj := nil;
HeadRef := nil;
Signature := nil;
ParentCount := 0;
for I := 0 to 1 do ParentsArray[I] := nil;
LocalMsg := AnsiString(CommitMessage);
if Trim(OverrideName) <> '' then LocalName := AnsiString(OverrideName)
else LocalName := AnsiString(FDefaultAuthorName);
if Trim(OverrideEmail) <> '' then LocalEmail := AnsiString(OverrideEmail)
else LocalEmail := AnsiString(FDefaultAuthorEmail);
CheckError(git_repository_index(@IndexHandle, FHandle));
try
CheckError(git_index_write_tree(@TreeOid, IndexHandle));
CheckError(git_tree_lookup(@TreeObj, FHandle, @TreeOid));
// 1. RESOLVE PARENT 1: Read the current active local HEAD commit reference
if git_repository_head(@HeadRef, FHandle) = 0 then
begin
if git_reference_name_to_id(@HeadOid, FHandle, git_reference_name(HeadRef)) = 0 then
begin
if git_commit_lookup(@ParentsArray[0], FHandle, @HeadOid) = 0 then
ParentCount := 1;
end;
end;
// 2. THE MERGE COMMIT FIX: Check if a merge transaction is currently open on disk
// git_repository_message or checking for MERGE_HEAD provides this state tracking link natively
if (git_repository_state(FHandle) = GIT_REPOSITORY_STATE_MERGE) then
begin
// Read the hidden secondary parent hash string directly out of the .git/MERGE_HEAD tracking file
// Note: git_repository_mergehead_foreach loops through active merge heads. For a single merge, index 0 is fetched.
// If your headers expose 'git_merge_head_lookup', you can substitute it here.
// Alternate fallback: read the OID using the built-in library reference parser
if git_reference_name_to_id(@MergeHeadOid, FHandle, 'MERGE_HEAD') = 0 then
begin
if git_commit_lookup(@ParentsArray[1], FHandle, @MergeHeadOid) = 0 then
ParentCount := 2; // Mark that this commit has TWO parents (A True Merge Commit!)
end;
end;
CheckError(git_signature_now(@Signature, PAnsiChar(LocalName), PAnsiChar(LocalEmail)));
// 3. Create the commit using our updated parents array structure
CheckError(git_commit_create(
@NewCommitOid, FHandle, 'HEAD', Signature, Signature, nil,
PAnsiChar(LocalMsg), TreeObj, ParentCount, @ParentsArray[0]
));
// 4. CLEAN UP THE MERGE STATE: If this was a merge commit, wipe out the temporary MERGE_HEAD file system trackers
if (ParentCount = 2) then
begin
git_repository_state_cleanup(FHandle); // Removes MERGE_HEAD and puts repo back to normal clean state!
end;
finally
for I := 0 to 1 do
begin
if Assigned(ParentsArray[I]) then git_commit_free(ParentsArray[I]);
end;
if Assigned(Signature) then git_signature_free(Signature);
if Assigned(TreeObj) then git_tree_free(TreeObj);
if Assigned(HeadRef) then git_reference_free(HeadRef);
git_index_free(IndexHandle);
end;
end;
function TGitRepository.HasStagedChanges: Boolean;
var
StatusList: TGitFileStatusArray;
I: Integer;
begin
Result := False;
StatusList := GetStatus(); // Pull our existing status scanner array
for I := 0 to High(StatusList) do
begin
// Check if the string status flag maps to any staging state
if (Pos('Staged', StatusList[I].State) > 0) then
begin
Result := True;
Exit; // Break early the moment we confirm at least one staged element
end;
end;
end;
procedure TGitRepository.DiscardChanges(const RelativeFilePath: string);
var
Opts: git_checkout_options;
LocalPathStr: AnsiString;
PCharPath: PAnsiChar;
begin
// 1. NATIVE INITIALIZATION: Sets up default states and internal structure values.
// FPC traces this function call and instantly clears the "not initialized" Hint!
CheckError(git_checkout_options_init(@Opts, 1)); // 1 corresponds to GIT_CHECKOUT_OPTIONS_VERSION
// 2. Set the custom operational checkout strategy configurations
Opts.checkout_strategy := GIT_CHECKOUT_FORCE or GIT_CHECKOUT_DISABLE_PATHSPEC_MATCH;
// 3. Bind our path variable explicitly to the 'paths' attribute
LocalPathStr := AnsiString(RelativeFilePath);
PCharPath := PAnsiChar(LocalPathStr);
Opts.paths.strings := @PCharPath;
Opts.paths.count := 1;
// 4. Execute the forced checkout operation down to disk
CheckError(git_checkout_head(FHandle, @Opts));
end;
// Standalone callback required by libgit2 to process matching diff line chunks
function InternalDiffLineCallback(
{%H-}diff_delta: Pgit_diff_delta; // {%H-} tells the Free Pascal compiler to ignore the unused hint
{%H-}diff_hunk: Pgit_diff_hunk; // {%H-} tells the Free Pascal compiler to ignore the unused hint
diff_line: Pgit_diff_line;
payload: Pointer): Integer; cdecl;
var
OutputStringList: TStringList;
LineText: string;
begin
OutputStringList := TStringList(payload);
LineText := ''; // Explicit assignment initializes the managed type cleanly
// Isolate and capture the line text securely out of the raw C string buffer array
SetLength(LineText, diff_line^.content_len);
if diff_line^.content_len > 0 then
Move(diff_line^.content^, Pointer(LineText)^, diff_line^.content_len); // Corrected pointer buffer cast
// Prefix the text strings based on the Git modification origin signature marker
case Char(diff_line^.origin) of
'+': OutputStringList.Add('+' + LineText); // Injected line
'-': OutputStringList.Add('-' + LineText); // Deleted line
'H': OutputStringList.Add('@@ ' + Trim(LineText) + ' @@'); // Hunk coordinates separator
else
OutputStringList.Add(' ' + LineText); // Unmodified baseline context line
end;
Result := 0;
end;
function TGitRepository.GetFileDiff(const RelativeFilePath: string): string;
var
DiffHandle: Pgit_diff; // Declared cleanly matching header structural expectations
DiffOpts: git_diff_options;
OutputList: TStringList;
LocalPathStr: AnsiString;
PCharPath: PAnsiChar;
HeadRef: Pgit_reference;
CommitObj: Pgit_commit;
TreeObj: Pgit_tree;
begin
Result := '';
DiffHandle := nil;
HeadRef := nil;
CommitObj := nil;
TreeObj := nil;
// 1.
CheckError(git_diff_options_init(@DiffOpts, GIT_DIFF_OPTIONS_VERSION));
OutputList := TStringList.Create;
LocalPathStr := AnsiString(RelativeFilePath);
PCharPath := PAnsiChar(LocalPathStr);
DiffOpts.pathspec.strings := @PCharPath;
DiffOpts.pathspec.count := 1;
try
// 2. THE REBASE CONFLICT OVERRIDE:
if IsRebasing and (git_repository_head(@HeadRef, FHandle) = 0) then
begin
try
// Peel the detached head down to the underlying tree object context
if (git_reference_peel(@CommitObj, HeadRef, GIT_OBJECT_COMMIT) = 0) and
(git_commit_tree(@TreeObj, CommitObj) = 0) then
begin
// Perform native Tree-to-Workdir diffing bypassing the broken unmerged index database
if git_diff_tree_to_workdir(@DiffHandle, FHandle, TreeObj, @DiffOpts) = 0 then
begin
git_diff_print(DiffHandle, GIT_DIFF_FORMAT_PATCH, @InternalDiffLineCallback, OutputList);
Result := OutputList.Text;
end;
end;
finally
if Assigned(TreeObj) then git_tree_free(TreeObj);
if Assigned(CommitObj) then git_commit_free(CommitObj);
if Assigned(HeadRef) then git_reference_free(HeadRef);
end;
end;
// 3. STANDARD FALLBACK: If the repo isn't rebasing, fall back to our index tracker
if (DiffHandle = nil) then
begin
if git_diff_index_to_workdir(@DiffHandle, FHandle, nil, @DiffOpts) = 0 then
begin
git_diff_print(DiffHandle, GIT_DIFF_FORMAT_PATCH, @InternalDiffLineCallback, OutputList);
Result := OutputList.Text;
end;
end;
finally
if Assigned(DiffHandle) then git_diff_free(DiffHandle);
OutputList.Free;
end;
end;
function TGitRepository.GetRemotesList: TStringList;
var
RemoteArr: git_strarray;
I: Integer;
begin
Result := TStringList.Create;
// THE NATIVE Pascal FIX: Directly assign default values.
// This satisfies the strict compiler tracker natively, erasing the Hint!
RemoteArr.strings := nil;
RemoteArr.count := 0;
// 1. Ask libgit2 to query the repository configuration for all configured remote names
if git_remote_list(@RemoteArr, FHandle) = 0 then
begin
try
// 2. Loop through the raw C string array and append them into our clean Pascal list
for I := 0 to RemoteArr.count - 1 do
begin
Result.Add(string(RemoteArr.strings[I]));
end;
finally
git_strarray_dispose(@RemoteArr); // Always free C string array structures cleanly
end;
end;
if Result.Count = 0 then
Result.Add('origin');
end;
procedure TGitRepository.Fetch(const RemoteName: string; LogOutput: TStrings);
var
RemoteHandle: Pgit_remote;
FetchOpts: git_fetch_options;
LocalRemoteName: AnsiString;
ReflogMsg: AnsiString;
NetworkPackage: TUnifiedNetworkPayload; // OUR COMBINED DATA CONSTRUCTOR PASSENGER
begin
RemoteHandle := nil;
LocalRemoteName := AnsiString(RemoteName);
CheckError(git_remote_lookup(@RemoteHandle, FHandle, PAnsiChar(LocalRemoteName)));
try
CheckError(git_fetch_options_init(@FetchOpts, GIT_FETCH_OPTIONS_VERSION));
// 1. Pack our credentials data matching your profile setups
FAnsiUser := AnsiString(FDefaultAuthorName);
FAnsiToken := AnsiString(FGitToken);
NetworkPackage.AuthData.username := PAnsiChar(FAnsiUser);
NetworkPackage.AuthData.password := PAnsiChar(FAnsiToken);
// 2. Pack our UI console logging destination handle
NetworkPackage.LogOutput := LogOutput;
// 3. Link your authentication routine to the stock handler
FetchOpts.callbacks.credentials := @git_credential_userpass;
// 4. Link your dynamic scrolling text renderer callback
FetchOpts.callbacks.transfer_progress := @InternalTransferProgressCallback;
// 5. THE MASTER INTEGRATION LINK: Pass the single address of our combined package structure!
// Both callbacks will now read from their respective parts of this stable shared memory cell.
FetchOpts.callbacks.payload := @NetworkPackage;
if Assigned(LogOutput) then
LogOutput.Add('📡 Initializing secure internet sockets connecting to: ' + RemoteName);
ReflogMsg := AnsiString('Fetch from client UI dashboard');
CheckError(git_remote_fetch(RemoteHandle, nil, @FetchOpts, PAnsiChar(ReflogMsg)));
if Assigned(LogOutput) then
LogOutput.Add('🎉 Synchronization complete!');
finally
if Assigned(RemoteHandle) then
git_remote_free(RemoteHandle);
end;
end;
function TGitRepository.GetLocalBranchesList: TStringList;
var
IteratorHandle: Pgit_branch_iterator;
RefHandle: Pgit_reference;
BranchType: Cardinal; // Holds GIT_BRANCH_LOCAL or GIT_BRANCH_REMOTE
BranchName: PAnsiChar;
begin
Result := TStringList.Create;
IteratorHandle := nil;
RefHandle := nil;
// 1. Create a branch iterator restricted strictly to local branches (GIT_BRANCH_LOCAL = 1)
if git_branch_iterator_new(@IteratorHandle, FHandle, 1) = 0 then
begin
try
// 2. Loop through references until the iterator returns GIT_ITEROVER (usually a negative termination code)
while git_branch_next(@RefHandle, @BranchType, IteratorHandle) = 0 do
begin
try
// 3. Extract the clean short name of the branch reference
if git_branch_name(@BranchName, RefHandle) = 0 then
begin
Result.Add(string(BranchName));
end;
finally
git_reference_free(RefHandle); // Free specific reference handle context inside loop iterations
end;
end;
finally
git_branch_iterator_free(IteratorHandle); // Clean the iterator architecture footprint out of memory
end;
end;
// Fallback safety if the list is completely blank
if Result.Count = 0 then
Result.Add('main');
end;
procedure TGitRepository.SwitchToBranch(const BranchName: string);
var
BranchRef: Pgit_reference;
TargetObj: Pgit_object;
CheckoutOpts: git_checkout_options;
LocalBranchName: AnsiString;
begin
BranchRef := nil;
TargetObj := nil;
LocalBranchName := AnsiString(BranchName);
// 1. Look up the local branch reference pointer using its short name (GIT_BRANCH_LOCAL = 1)
CheckError(git_branch_lookup(@BranchRef, FHandle, PAnsiChar(LocalBranchName), 1));
try
// 2. Resolve (peel) the branch reference down to its underlying target commit object
CheckError(git_reference_peel(@TargetObj, BranchRef, GIT_OBJECT_COMMIT));
try
// 3. Initialize the native checkout options to safely overwrite your working directory files
CheckError(git_checkout_options_init(@CheckoutOpts, 1));
CheckoutOpts.checkout_strategy := GIT_CHECKOUT_SAFE; // Prevents overwriting local unsaved changes
// 4. Update the physical files on your hard disk to match the selected branch target commit tree
CheckError(git_checkout_tree(FHandle, TargetObj, @CheckoutOpts));
// 5. Move the master HEAD tracking pointer to point to the new branch reference name
CheckError(git_repository_set_head(FHandle, git_reference_name(BranchRef)));
finally
if Assigned(TargetObj) then git_object_free(TargetObj);
end;
finally
if Assigned(BranchRef) then git_reference_free(BranchRef);
end;
end;
procedure TGitRepository.CreateBranch(const NewBranchName: string);
var
HeadRef: Pgit_reference;
TargetCommitObj: Pgit_object;
NewBranchRef: Pgit_reference;
LocalBranchName: AnsiString;
begin
HeadRef := nil;
TargetCommitObj := nil;
NewBranchRef := nil;
LocalBranchName := AnsiString(NewBranchName);
// 1. Query the repository to fetch the active HEAD reference
if git_repository_head(@HeadRef, FHandle) <> 0 then
raise EGitException.Create('Cannot create branch: Repository has no historical HEAD commit reference yet.');
try
// 2. Resolve (peel) the HEAD reference down to its underlying target commit object context
CheckError(git_reference_peel(@TargetCommitObj, HeadRef, GIT_OBJECT_COMMIT));
try
// 3. Fire the native libgit2 branch creation engine
// Parameter 1: Destination pointer tracker to receive the new branch reference
// Parameter 2: Active repository pointer handle
// Parameter 3: Name string for the new line
// Parameter 4: Target commit object block to attach the new line to
// Parameter 5: Force overwrite flag (0 = false, do not overwrite if name already exists)
CheckError(git_branch_create(@NewBranchRef, FHandle, PAnsiChar(LocalBranchName), Pgit_commit(TargetCommitObj), 0));
finally
if Assigned(NewBranchRef) then git_reference_free(NewBranchRef);
end;
finally
if Assigned(TargetCommitObj) then git_object_free(TargetCommitObj);
if Assigned(HeadRef) then git_reference_free(HeadRef);
end;
end;
procedure TGitRepository.DeleteBranch(const BranchName: string);
var
BranchRef: Pgit_reference;
LocalBranchName: AnsiString;
begin
BranchRef := nil;
LocalBranchName := AnsiString(BranchName);
// 1. Safety Rule: Proactively block the user if they try to pass their currently active branch name
if CompareText(BranchName, GetActiveBranchName) = 0 then
raise EGitException.Create('Cannot delete branch "' + BranchName + '" because it is currently checked out.' + sLineBreak +
'Please switch to a different branch (like main) first.');
// 2. Look up the targeted local branch reference handle (GIT_BRANCH_LOCAL = 1)
CheckError(git_branch_lookup(@BranchRef, FHandle, PAnsiChar(LocalBranchName), 1));
try
// 3. Fire the native libgit2 structural branch deletion engine execution command
CheckError(git_branch_delete(BranchRef));
finally
// Note: git_branch_delete frees the internal reference memory internally on success,
// but wrapping it inside an assigned safety block safeguards against resource allocation leakage on failures.
if Assigned(BranchRef) then
git_reference_free(BranchRef);
end;
end;
procedure TGitRepository.StashSave(const StashMessage, OverrideName, OverrideEmail: string);
var
StashOid: git_oid;
Signature: Pgit_signature;
LocalMessage, LocalName, LocalEmail: AnsiString;
begin
Signature := nil;
LocalMessage := AnsiString(StashMessage);
// LAST RESORT GUARD: Use the UI overrides if provided, else use discovered config
if Trim(OverrideName) <> '' then LocalName := AnsiString(OverrideName)
else LocalName := AnsiString(FDefaultAuthorName);
if Trim(OverrideEmail) <> '' then LocalEmail := AnsiString(OverrideEmail)
else LocalEmail := AnsiString(FDefaultAuthorEmail);
// Sign the stash entry using your real native Git identity!
CheckError(git_signature_now(@Signature, PAnsiChar(LocalName), PAnsiChar(LocalEmail)));
try
CheckError(git_stash_save(@StashOid, FHandle, Signature, PAnsiChar(LocalMessage), 0));
finally
if Assigned(Signature) then
git_signature_free(Signature);
end;
end;
procedure TGitRepository.StashPop;
var
PopOpts: git_stash_apply_options;
begin
// 1. NATIVE INITIALIZATION: This initializes PopOpts and all its nested
// sub-structures (like checkout_options) to their legal default values!
// FPC traces this and immediately clears the "not initialized" Hint.
CheckError(git_stash_apply_options_init(@PopOpts, 1)); // 1 corresponds to GIT_STASH_APPLY_OPTIONS_VERSION
// 2. OPTIONAL UX REINFORCEMENT: Explicitly ensure the nested checkout strategy
// uses safe workstation safeguards (GIT_CHECKOUT_SAFE = 1).
PopOpts.checkout_options.checkout_strategy := 1;
// 3. Execute the popping stream passing our pristine, natively-configured structure pointer
CheckError(git_stash_pop(FHandle, 0, @PopOpts));
end;
procedure TGitRepository.RenameBranch(const OldBranchName, NewBranchName: string);
var
BranchRef: Pgit_reference;
NewBranchRef: Pgit_reference;
LocalNewName: AnsiString;
LocalOldName: AnsiString;
begin
BranchRef := nil;
NewBranchRef := nil;
LocalOldName := AnsiString(OldBranchName);
LocalNewName := AnsiString(NewBranchName);
// 1. Look up the existing local branch reference handle (GIT_BRANCH_LOCAL = 1)
CheckError(git_branch_lookup(@BranchRef, FHandle, PAnsiChar(LocalOldName), GIT_BRANCH_LOCAL));
try
// 2. Fire the native libgit2 branch moving/renaming execution engine
// Parameter 1: Destination out pointer to receive the updated reference structure
// Parameter 2: Active source branch reference pointer to modify
// Parameter 3: New name string for the line
// Parameter 4: Force overwrite flag (0 = false, do not overwrite if name already exists)
CheckError(git_branch_move(@NewBranchRef, BranchRef, PAnsiChar(LocalNewName), 0));