-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodekeeper.cpp
989 lines (863 loc) · 29.6 KB
/
codekeeper.cpp
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
#include <iostream>
#include <fstream>
#include <filesystem>
#include <string>
#include <vector>
#include <ctime>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <regex>
#include <sstream>
#include <random>
#include <chrono>
#include <iomanip>
#include <unistd.h> // For getuid()
namespace fs = std::filesystem;
// Structure to hold metadata for commits
struct Commit
{
std::string message;
std::string timestamp;
std::vector<std::string> filePaths;
std::vector<std::string> versionPaths;
};
std::string repositoryPath;
std::string projectName;
// Function to generate a timestamp
std::string getTimestamp()
{
std::time_t now = std::time(nullptr);
char buf[80];
std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", std::localtime(&now));
return buf;
}
// Function to split a string by delimiter
std::vector<std::string> splitString(const std::string &str, char delimiter)
{
std::vector<std::string> tokens;
std::istringstream iss(str);
std::string token;
while (std::getline(iss, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
std::string generateGUID()
{
// Get the current timestamp
auto timestamp = std::chrono::high_resolution_clock::now().time_since_epoch().count();
// Generate random components
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(0, 15); // For hex characters
std::stringstream guidStream;
guidStream << std::hex << std::setw(8) << std::setfill('0') << (timestamp & 0xFFFFFFFF);
guidStream << "-";
for (int i = 0; i < 3; ++i)
{
guidStream << std::setw(4) << std::setfill('0') << dis(gen);
guidStream << "-";
}
guidStream << std::setw(12) << std::setfill('0') << dis(gen);
return guidStream.str();
}
// Function to check if the repository has been initialized
bool isRepositoryInitialized(const std::string &projectName)
{
std::string centralOriginPath = "/usr/bin/Codekeeper"; // You can change this path if needed
std::string keepDirectory = centralOriginPath + "/.keep"; // Path to the .keep directory
std::string repoName = "." + projectName;
std::string repositoryPath = keepDirectory + "/" + repoName; // Path to the project folder under .keep
// Check if the .keep directory exists and the project folder is there
if (fs::exists(keepDirectory) && fs::exists(repositoryPath))
{
std::string projectDetailsFile = repositoryPath + "/projectdetails";
if (fs::exists(projectDetailsFile))
{
return true; // Repository is initialized
}
}
return false; // Repository not initialized
}
// Function to load the repository path
void initRepository(const std::string &projectName)
{
if (projectName.empty())
{
std::cerr << "Error: Project name cannot be empty.\n";
return;
}
// Ensure the application has proper permissions
if (getuid() != 0)
{ // Check if running as root
std::cerr << "Error: You must run 'codekeeper init' as root to set up the central repository.\n";
return;
}
std::string centralOriginPath = "/usr/bin/Codekeeper"; // You can change this path if needed
// Create central origin directory if it doesn't exist
if (!fs::exists(centralOriginPath))
{
fs::create_directories(centralOriginPath);
}
std::string centralConfigFile = centralOriginPath + "/codekeeper_config";
std::string repoName = "." + projectName;
std::string keepDirectory = centralOriginPath + "/.keep"; // Create the .keep directory within the central origin path
std::string repositoryPath = keepDirectory + "/" + repoName; // Place the project folder under .keep
// Create the .keep directory if it doesn't exist
if (!fs::exists(keepDirectory))
{
fs::create_directory(keepDirectory);
}
// Create the project details file in the local repo
std::ofstream repoFile(keepDirectory + "/projectdetails");
repoFile << repositoryPath;
repoFile.close();
// Create the ".versions" folder inside the project folder
fs::create_directories(repositoryPath + "/.versions");
// Create the .bypass file inside the hidden repository
std::ofstream bypassFile(repositoryPath + "/.bypass");
bypassFile << "# Add files or patterns to ignore\n";
bypassFile.close();
// Create the commit_log.txt file
std::ofstream logFile(repositoryPath + "/commit_log.txt");
logFile.close();
// Write the central repository path to the global config
std::ofstream centralConfig(centralConfigFile);
if (centralConfig.is_open())
{
centralConfig << "central_repository_path=" << repositoryPath << "\n";
centralConfig.close();
}
else
{
std::cerr << "Error: Unable to write to central configuration file.\n";
return;
}
std::cout << "Repository '" << repositoryPath << "' initialized successfully.\n";
std::cout << "Central repository configured in '" << centralConfigFile << "'.\n";
}
// // Function to load the repository path
// void initRepository(const std::string& projectName) {
// if (projectName.empty()) {
// std::cerr << "Error: Project name cannot be empty.\n";
// return;
// }
// // Ensure the application has proper permissions
// if (getuid() != 0) { // Check if running as root
// std::cerr << "Error: You must run 'codekeeper init' as root to set up the central repository.\n";
// return;
// }
// std::string centralOriginPath = "/usr/bin/codekeeper"; // You can change this path if needed
// // Create central origin directory if it doesn't exist
// if (!fs::exists(centralOriginPath)) {
// fs::create_directories(centralOriginPath);
// }
// std::string centralConfigFile = centralOriginPath + "/codekeeper_config";
// std::string repoName = "." + projectName;
// std::string keepDirectory = centralOriginPath + "/.keep"; // Create the .keep directory within the central origin path
// std::string repositoryPath = keepDirectory + "/" + repoName; // Place the project folder under .keep
// // Create the .keep directory if it doesn't exist
// if (!fs::exists(keepDirectory)) {
// fs::create_directory(keepDirectory);
// }
// // Create the project details file in the local repo
// std::ofstream repoFile(keepDirectory + "/projectdetails");
// repoFile << repositoryPath;
// repoFile.close();
// // Create the ".versions" folder inside the project folder
// fs::create_directories(repositoryPath + "/.versions");
// // Create the .bypass file inside the hidden repository
// std::ofstream bypassFile(repositoryPath + "/.bypass");
// bypassFile << "# Add files or patterns to ignore\n";
// bypassFile.close();
// // Create the commit_log.txt file
// std::ofstream logFile(repositoryPath + "/commit_log.txt");
// logFile.close();
// // Write the central repository path to the global config
// std::ofstream centralConfig(centralConfigFile);
// if (centralConfig.is_open()) {
// centralConfig << "central_repository_path=" << repositoryPath << "\n";
// centralConfig.close();
// } else {
// std::cerr << "Error: Unable to write to central configuration file.\n";
// return;
// }
// std::cout << "Repository '" << repositoryPath << "' initialized successfully.\n";
// std::cout << "Central repository configured in '" << centralConfigFile << "'.\n";
// }
std::string loadRepositoryPath()
{
std::string centralConfigFile = "/usr/bin/Codekeeper/codekeeper_config";
std::ifstream configFile(centralConfigFile);
if (!configFile.is_open())
{
std::cerr << "Error: Central configuration file not found. Run 'codekeeper init'.\n";
return "";
}
std::string line, repositoryPath;
while (std::getline(configFile, line))
{
if (line.find("central_repository_path=") == 0)
{
repositoryPath = line.substr(line.find('=') + 1);
break;
}
}
if (repositoryPath.empty())
{
std::cerr << "Error: Central repository path not set in the configuration file.\n";
}
return repositoryPath;
}
std::string getCentralRepositoryPath()
{
std::ifstream configFile(".codekeeper_config");
std::string repositoryPath;
if (configFile.is_open())
{
std::getline(configFile, repositoryPath);
}
return repositoryPath;
}
void setCentralRepositoryPath(const std::string &path)
{
std::ofstream configFile(".codekeeper_config");
configFile << path;
}
// Function to retrieve files by commit message
void retrieveFiles(const std::string &commitMessage)
{
if (repositoryPath.empty() || !fs::exists(repositoryPath + "/commit_log.txt"))
{
std::cerr << "Error: Repository not initialized or log file missing.\n";
return;
}
std::ifstream logFile(repositoryPath + "/commit_log.txt");
if (!logFile)
{
std::cerr << "Error: Commit log file not found.\n";
return;
}
std::string line;
while (std::getline(logFile, line))
{
size_t pos = line.find('|');
std::string message = line.substr(0, pos);
if (message == commitMessage)
{
size_t pos2 = line.find('|', pos + 1);
size_t pos3 = line.find_last_of('|');
std::string fileData = line.substr(pos2 + 1, pos3 - pos2 - 1);
std::vector<std::string> tokens = splitString(fileData, '|');
size_t half = tokens.size() / 2;
for (size_t i = 0; i < half; ++i)
{
fs::copy(tokens[half + i], fs::path(tokens[i]).filename(),
fs::copy_options::overwrite_existing);
}
std::cout << "Files retrieved successfully.\n";
logFile.close();
return;
}
}
std::cerr << "Error: Commit message not found.\n";
logFile.close();
}
// utility function
std::vector<std::string> split(const std::string &str, char delimiter)
{
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, delimiter))
{
tokens.push_back(token);
}
return tokens;
}
bool filesAreEqual(const std::string &filePath1, const std::string &filePath2)
{
std::ifstream file1(filePath1, std::ios::binary);
std::ifstream file2(filePath2, std::ios::binary);
return std::equal(std::istreambuf_iterator<char>(file1), std::istreambuf_iterator<char>(),
std::istreambuf_iterator<char>(file2));
}
// function to View History
void viewHistory()
{
repositoryPath = loadRepositoryPath();
if (repositoryPath.empty())
{
std::cerr << "Error: Repository not initialized. Run 'codekeeper init'.\n";
return;
}
std::ifstream logFile(repositoryPath + "/commit_log.txt");
if (!logFile.is_open())
{
std::cerr << "Error: Commit log file not found.\n";
return;
}
std::string line;
while (std::getline(logFile, line))
{
// Commit format: GUID|Message|Timestamp|File1|File2|...|VersionPath1|VersionPath2|...
std::vector<std::string> tokens = split(line, '|');
if (tokens.size() < 4)
continue; // Skip malformed entries
std::cout << "Commit GUID: " << tokens[0] << "\n";
std::cout << "Message: " << tokens[1] << "\n";
std::cout << "Timestamp: " << tokens[2] << "\n";
std::cout << "Files:\n";
for (size_t i = 3; i < tokens.size() - (tokens.size() - 3) / 2; ++i)
{
std::cout << " - " << tokens[i] << "\n";
}
std::cout << "------------------------\n";
}
logFile.close();
}
// function for Conflict resolution
bool checkConflicts(const std::string &filePath)
{
repositoryPath = loadRepositoryPath();
if (repositoryPath.empty())
{
std::cerr << "Error: Repository not initialized. Run 'codekeeper init'.\n";
return false;
}
std::ifstream logFile(repositoryPath + "/commit_log.txt");
if (!logFile.is_open())
{
std::cerr << "Error: Commit log file not found.\n";
return false;
}
std::string latestVersion;
std::string line;
while (std::getline(logFile, line))
{
std::vector<std::string> tokens = split(line, '|');
if (std::find(tokens.begin() + 3, tokens.end(), filePath) != tokens.end())
{
size_t versionIndex = 3 + (tokens.size() - 3) / 2;
for (size_t i = versionIndex; i < tokens.size(); ++i)
{
if (fs::path(tokens[i]).filename() == fs::path(filePath).filename())
{
latestVersion = tokens[i];
break;
}
}
}
}
if (!latestVersion.empty() && fs::exists(filePath))
{
// Compare latest version with the current file
if (!filesAreEqual(filePath, latestVersion))
{
std::cerr << "Conflict detected in file: " << filePath << "\n";
return true;
}
}
return false;
}
void resolveConflict(const std::string &filePath, const std::string &resolutionPath)
{
fs::copy(resolutionPath, filePath, fs::copy_options::overwrite_existing);
std::cout << "Conflict resolved for " << filePath << " using " << resolutionPath << "\n";
}
// function foir archiving
void archiveVersions()
{
repositoryPath = loadRepositoryPath();
if (repositoryPath.empty())
{
std::cerr << "Error: Repository not initialized. Run 'codekeeper init'.\n";
return;
}
std::string versionsPath = repositoryPath + "/.versions";
if (!fs::exists(versionsPath))
{
std::cerr << "Error: No .versions folder found.\n";
return;
}
std::string archivePath = repositoryPath + "/.versions_archive_" + getTimestamp() + ".zip";
// Use a system call to zip the .versions folder (requires zip utility installed)
std::string command = "zip -r " + archivePath + " " + versionsPath;
if (system(command.c_str()) == 0)
{
std::cout << "Archived .versions to " << archivePath << "\n";
}
else
{
std::cerr << "Error: Failed to archive .versions folder.\n";
}
}
// Function for Rollback
void rollback(const std::string &target, const std::string &commitGUID = "")
{
repositoryPath = loadRepositoryPath();
if (repositoryPath.empty())
{
std::cerr << "Error: Repository not initialized. Run 'codekeeper init'.\n";
return;
}
std::ifstream logFile(repositoryPath + "/commit_log.txt");
if (!logFile.is_open())
{
std::cerr << "Error: Commit log file not found.\n";
return;
}
std::string line, foundVersionPath;
while (std::getline(logFile, line))
{
std::vector<std::string> tokens = split(line, '|');
if (tokens.size() < 4)
continue;
if ((!commitGUID.empty() && tokens[0] == commitGUID) ||
(commitGUID.empty() && std::find(tokens.begin() + 3, tokens.end(), target) != tokens.end()))
{
// Found matching commit or file
size_t versionIndex = 3 + (tokens.size() - 3) / 2;
for (size_t i = versionIndex; i < tokens.size(); ++i)
{
if (fs::path(tokens[i]).filename() == fs::path(target).filename())
{
foundVersionPath = tokens[i];
break;
}
}
}
}
if (foundVersionPath.empty())
{
std::cerr << "Error: No matching commit or version found for " << target << ".\n";
return;
}
fs::copy(foundVersionPath, target, fs::copy_options::overwrite_existing);
std::cout << "Rolled back " << target << " to version: " << foundVersionPath << "\n";
}
// Function to create a new branch
void createBranch(const std::string &branchName)
{
if (repositoryPath.empty())
{
repositoryPath = loadRepositoryPath();
if (repositoryPath.empty())
{
return;
}
}
std::string branchesPath = repositoryPath + "/branches";
if (!fs::exists(branchesPath))
{
fs::create_directory(branchesPath);
}
std::string branchPath = branchesPath + "/" + branchName;
if (fs::exists(branchPath))
{
std::cerr << "Error: Branch '" << branchName << "' already exists.\n";
return;
}
fs::create_directory(branchPath);
std::cout << "Branch '" << branchName << "' created successfully.\n";
}
// Function to collect all files from a directory
void collectFilesFromDirectory(const std::string &dirPath, std::vector<std::string> &files, const std::vector<std::string> &ignoredFiles)
{
for (const auto &entry : std::filesystem::recursive_directory_iterator(dirPath))
{
if (entry.is_regular_file())
{
std::string filePath = entry.path().string();
if (std::find(ignoredFiles.begin(), ignoredFiles.end(), filePath) == ignoredFiles.end())
{
files.push_back(filePath);
}
else
{
std::cout << "Skipping ignored file: " << filePath << "\n";
}
}
}
}
// Function to expand wildcards for files and directories
void expandWildcard(const std::string &pattern, std::vector<std::string> &files)
{
std::regex re(pattern);
for (const auto &entry : std::filesystem::directory_iterator("."))
{
if (std::filesystem::is_regular_file(entry) || std::filesystem::is_directory(entry))
{
std::string entryPath = entry.path().string();
if (std::regex_match(entryPath, re))
{
files.push_back(entryPath);
}
}
}
}
// Function to commit files
void commitFiles(const std::vector<std::string> &filePaths, const std::string &commitMessage)
{
repositoryPath = loadRepositoryPath();
if (repositoryPath.empty())
{
std::cerr << "Error: Repository not initialized. Run 'codekeeper init'.\n";
return;
}
// Generate a unique GUID for this commit
std::string commitID = generateGUID();
std::cout << "Commit ID: " << commitID << "\n"; // Optional, for debugging
// Load ignored files from .bypass
std::ifstream bypassFile(repositoryPath + "/.bypass");
std::vector<std::string> ignoredFiles;
std::string line;
while (std::getline(bypassFile, line))
{
if (!line.empty() && line[0] != '#')
{
ignoredFiles.push_back(line);
}
}
std::vector<std::string> allFiles;
for (const auto &filePath : filePaths)
{
if (!fs::exists(filePath))
{
std::cerr << "Error: File or directory " << filePath << " does not exist.\n";
continue;
}
if (fs::is_regular_file(filePath))
{
if (std::find(ignoredFiles.begin(), ignoredFiles.end(), filePath) == ignoredFiles.end())
{
allFiles.push_back(filePath);
}
else
{
std::cout << "Skipping ignored file: " << filePath << "\n";
}
}
else if (fs::is_directory(filePath))
{
collectFilesFromDirectory(filePath, allFiles, ignoredFiles);
}
else
{
std::cerr << "Error: Unsupported file type for " << filePath << ".\n";
}
}
// Commit the collected files
std::vector<std::string> versionPaths;
for (const auto &filePath : allFiles)
{
std::string versionFile = repositoryPath + "/.versions/version_" + commitID + "_" + std::to_string(std::time(nullptr)) +
"_" + fs::path(filePath).filename().string();
fs::copy(filePath, versionFile, fs::copy_options::overwrite_existing);
versionPaths.push_back(versionFile);
}
std::string timestamp = getTimestamp();
std::ofstream logFile(repositoryPath + "/commit_log.txt", std::ios::app);
logFile << commitMessage << "|" << commitID << "|" << timestamp;
for (const auto &filePath : allFiles)
{
logFile << "|" << filePath;
}
logFile << "|";
for (const auto &versionPath : versionPaths)
{
logFile << versionPath << "|";
}
logFile << "\n";
logFile.close();
std::cout << "Files committed successfully with message: " << commitMessage << "\n";
}
// Function to display help message
void displayHelp()
{
std::cout << "CodeKeeper Help:\n";
std::cout << "Available Commands:\n";
std::cout << " init Initialize a new repository.\n";
std::cout << " commit [files] Commit specified files or directories.\n";
std::cout << " Use '*.*' or '.' to commit all files.\n";
std::cout << " rollback [file|guid] Revert a file or repository to a specific version.\n";
std::cout << " history View commit history.\n";
std::cout << " conflicts [file] Check for conflicts in a file.\n";
std::cout << " resolve [file] [res] Resolve a conflict with the specified resolution file.\n";
std::cout << " archive Archive the .versions folder.\n";
std::cout << " auth Authenticate a user.\n";
std::cout << " merge [branch1 branch2] Merge changes from two branches.\n";
std::cout << "\nAuthentication:\n";
std::cout << " Users must authenticate using a valid username and password.\n";
std::cout << " Only authenticated users can commit, rollback, or resolve conflicts.\n";
std::cout << "\nFor more details, consult the documentation.\n";
}
// merging files
void mergeFiles(const std::string &file1, const std::string &file2, const std::string &outputPath)
{
std::ifstream input1(file1);
std::ifstream input2(file2);
std::ofstream output(outputPath);
if (!input1.is_open() || !input2.is_open() || !output.is_open())
{
std::cerr << "Error: Unable to open one or more files for merging.\n";
return;
}
std::string line1, line2;
while (std::getline(input1, line1) || std::getline(input2, line2))
{
if (!line1.empty() && !line2.empty() && line1 != line2)
{
// Conflict: Append both lines with markers
output << "<<<<<<< " << file1 << "\n"
<< line1 << "\n=======\n"
<< line2 << "\n>>>>>>>\n";
}
else
{
// No conflict: Append whichever line is available
output << (!line1.empty() ? line1 : line2) << "\n";
}
line1.clear();
line2.clear();
}
input1.close();
input2.close();
output.close();
std::cout << "Merge complete. Output written to: " << outputPath << "\n";
}
// merging branches
void mergeBranches(const std::string &branch1, const std::string &branch2)
{
repositoryPath = getCentralRepositoryPath();
if (repositoryPath.empty())
{
std::cerr << "Error: Central repository not configured.\n";
return;
}
std::string branch1Path = repositoryPath + "/branches/" + branch1;
std::string branch2Path = repositoryPath + "/branches/" + branch2;
if (!fs::exists(branch1Path) || !fs::exists(branch2Path))
{
std::cerr << "Error: One or both branches do not exist.\n";
return;
}
for (const auto &entry : fs::directory_iterator(branch1Path))
{
std::string file1 = entry.path();
std::string file2 = branch2Path + "/" + fs::path(file1).filename().string();
if (fs::exists(file2))
{
std::string outputFile = branch1Path + "/merged_" + fs::path(file1).filename().string();
mergeFiles(file1, file2, outputFile);
}
}
std::cout << "Branch merge complete. Resolve conflicts in the merged files if necessary.\n";
}
void moveToGitRepo(const std::string &folderPath, const std::string &repoPath)
{
// Ensure the source folder exists
if (!fs::exists(folderPath) || !fs::is_directory(folderPath))
{
std::cerr << "Error: Source folder does not exist or is not a directory.\n";
return;
}
// Ensure the destination repo folder exists
if (!fs::exists(repoPath))
{
std::cerr << "Error: Git repository does not exist at the specified path.\n";
return;
}
// Create a path for the folder inside the Git repo
std::string targetPath = repoPath + "/" + fs::path(folderPath).filename().string();
// Move the folder to the Git repository
try
{
fs::rename(folderPath, targetPath);
std::cout << "Successfully moved folder to: " << targetPath << std::endl;
}
catch (const std::exception &e)
{
std::cerr << "Error: Failed to move folder. " << e.what() << std::endl;
return;
}
// Change directory to the Git repository
if (fs::exists(repoPath + "/.git"))
{
std::cout << "Git repository found. Proceeding with Git operations...\n";
// Change the current working directory to the Git repository
std::string gitCommand = "cd " + repoPath + " && git add . && git commit -m \"Added folder: " + fs::path(folderPath).filename().string() + "\"";
int result = std::system(gitCommand.c_str());
if (result == 0)
{
std::cout << "Successfully committed the folder to Git.\n";
}
else
{
std::cerr << "Error: Failed to commit the folder to Git.\n";
}
}
else
{
std::cerr << "Error: No Git repository found in the specified path.\n";
}
}
void convertToGitRepo(const std::string &folderPath)
{
// Ensure the folder exists
if (!fs::exists(folderPath) || !fs::is_directory(folderPath))
{
std::cerr << "Error: Folder does not exist or is not a directory.\n";
return;
}
// Check if the folder is already a Git repository
if (fs::exists(folderPath + "/.git"))
{
std::cout << "This folder is already a Git repository.\n";
return;
}
// Run `git init` to initialize the folder as a Git repository
std::string gitCommand = "cd " + folderPath + " && git init";
int result = std::system(gitCommand.c_str());
if (result == 0)
{
std::cout << "Successfully converted folder to a Git repository.\n";
}
else
{
std::cerr << "Error: Failed to initialize Git repository.\n";
}
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
displayHelp();
return 1;
}
std::string command = argv[1];
if (command == "-h" || command == "--help")
{
displayHelp();
}
else if (command == "init")
{
std::string projectName = (argc == 3) ? argv[2] : "";
// Check if repository has been initialized before proceeding
if (isRepositoryInitialized(projectName))
{
std::cout << "Repository has already been initialized.\n";
}
else
{
initRepository(projectName);
}
}
else if (command == "commit")
{
if (argc < 4)
{
std::cerr << "Error: Please provide commit message and file paths.\n";
return 1;
}
std::string commitMessage = argv[2];
std::vector<std::string> filePaths(argv + 3, argv + argc);
commitFiles(filePaths, commitMessage);
}
else if (command == "rollack")
{
if (argv[3] == "")
{
std::cerr << "Error: Please provide commit-id or filename.\n";
return 1;
}
std::string filename = argv[3];
rollback(filename);
}
else if (command == "retrieve")
{
if (argc < 3)
{
std::cerr << "Error: Please provide commit message.\n";
return 1;
}
std::string commitMessage = argv[2];
retrieveFiles(commitMessage);
}
else if (command == "branch")
{
if (argc < 3)
{
std::cerr << "Error: Please provide branch name.\n";
return 1;
}
std::string branchName = argv[2];
createBranch(branchName);
}
else if (command == "history")
{
viewHistory();
}
else if (command == "archive")
{
archiveVersions();
}
else if (command == "conflicts")
{
if (argc < 3)
{
std::cerr << "Error: Please provide a file to check for conflicts.\n";
return 1;
}
std::string fileName = argv[2];
bool conflictDetected = checkConflicts(fileName);
if (conflictDetected)
{
std::cout << "Conflict detected in file: " << fileName << "\n";
}
else
{
std::cout << "No conflicts detected in file: " << fileName << "\n";
}
}
else if (command == "resolve")
{
if (argc < 4)
{
std::cerr << "Error: Please provide a file and resolution file.\n";
return 1;
}
std::string fileName = argv[2];
std::string resolutionFile = argv[3];
resolveConflict(fileName, resolutionFile);
}
else if (command == "move")
{
if (argc < 4)
{
std::cerr << "Error: Please provide folder path and repo path.\n";
return 1;
}
std::string folderPath = argv[2];
std::string repoPath = argv[3];
moveToGitRepo(folderPath, repoPath);
}
else if (command == "convert")
{
if (argc < 3)
{
std::cerr << "Error: Please provide folder path.\n";
return 1;
}
std::string folderPath = argv[2];
convertToGitRepo(folderPath);
}
else
{
std::cerr << "Error: Unknown command.\n";
displayHelp();
}
return 0;
}