-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.cpp
965 lines (858 loc) · 33.7 KB
/
file.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
#include <iostream>
#include <bits/stdc++.h>
#include <fstream>
#include <sys/stat.h>
#include <sys/types.h>
#include <string>
#include <cstring>
#include <filesystem>
#include <iomanip>
#include <ctime>
#include <sstream>
#include <iostream>
#include <sqlite3.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "socket_functs.h"
using std::string;
using std::cout;
using std::cin;
using std::cerr;
using std::endl;
using std::string;
using std::fstream;
using std::ios;
using std::filesystem::recursive_directory_iterator;
using std::to_string;
using std::pair;
using std::filesystem::directory_iterator;
namespace fs = std::filesystem;
void status();
struct stat info;
std::vector<string> IGNORE {".git", "revisions"};
void write_file(string text) {
std::ofstream outfile;
outfile.open("Gfg.txt", std::ios_base::app); // append instead of overwrite
outfile << text;
}
// create directory to store file revisions
int create_revisions_directory(string text) {
const char* path = text.c_str();
if( stat( path, &info ) != 0 ) {
if (mkdir(path, 0777) == -1)
cerr << "Error : " << strerror(errno) << endl;
}
else if( info.st_mode & S_IFDIR )
return 2;
else
cout<<"that is not a directory";
return 0;
}
void insert(string file_path);
// get current time as string
string get_curr_time() {
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
std::ostringstream oss;
oss << std::put_time(&tm, "%Y-%m-%d %H-%M-%S");
string timestamp = oss.str();
return timestamp;
}
/* takes vector as input and returns that with lines in .txt based on revision_type */
void get_file_paths(std::vector<string> &_files, string revision_type){
if (std::filesystem::exists(".revisions/files/" + revision_type + ".txt")) {
std::ifstream _type (".revisions/files/" + revision_type + ".txt");
string line;
while(std::getline(_type,line)){
_files.push_back(line);
}
}
}
static int callback(void *param, int argc, char **argv, char **azColName) {
// cout<<"inside callback"<<endl;
// cout<<"param[0]="<<((string*)param)[0]<<endl;
// cout<<"param[1]="<<((string*)param)[1]<<endl;
std::string &s = *static_cast<std::string*>(param);
int i;
// for(i = 0; i<argc; i++) {
// printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
// }
// if count == 0, insert
if ((!strcmp(azColName[0], "COUNT(*)")) && (atoi(argv[0]) == 0)) {
// set flag as 1
string *flag = &((string*)param)[0];
*flag = "1";
return 1;
}
printf("\n");
return 0;
}
// NOTE: only called by status function in order to retrieve file_path stored in db
static int get_db_files_callback(void *param, int argc, char **argv, char **azColName) {
int i;
std::vector<pair<string, int>> *s1 = (std::vector<pair<string, int>> *)param;
// cout<<"argv[0]="<<argv[0]<<endl;
// cout<<"argv[1]="<<argv[1]<<endl;
string file_path = argv[0];
int file_size = atoi(argv[1]);
pair<string, int> tmp(file_path, file_size);
s1->push_back(tmp);
return 0;
}
static int get_latest_commit_id(void *param, int argc, char **argv, char **azColName ) {
int *commit_id = (int*)param;
*commit_id = atoi(argv[0]);
return 0;
}
static int get_files_in_commit(void *param, int argc, char **argv, char **azColName) {
std::vector<string> *s1 = (std::vector<string> *)param;
for(int i = 0; i<argc; i++) {
s1->push_back(argv[i]);
}
return 0;
}
static int get_commits_info(void *param, int argc, char **argv, char **azColName) {
vector<vector<string>> *s1 = (vector<vector<string>> *)param;
vector<string> tmp;
for(int i = 0; i<argc; i++) {
tmp.push_back(argv[i]);
}
s1->push_back(tmp);
return 0;
}
/* get all files in the directory in vector */
void listdir(std::vector<string> &files_ls) {
std::string path = ".";
for (const auto & file : recursive_directory_iterator(path)) {
if (file.path().u8string().string::find(".git") == string::npos && file.path().u8string().string::find("revisions") == string::npos) {
files_ls.push_back(file.path().u8string());
}
}
}
void insert(string file_path, sqlite3 *db) {
char *errmessage = 0;
int connection;
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
string timestamp = get_curr_time();
string query = "INSERT INTO files(file_path, created_at) VALUES ('" + file_path + "', '" + timestamp +"');";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
fprintf(stdout, "Records created successfully\n");
}
}
}
// create files table in sqlite
int create_table() {
sqlite3 *db;
char *errmessage = 0;
int connection;
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
// files table
string query = "CREATE TABLE files (id INTEGER PRIMARY KEY DEFAULT 0, file_path VARCHAR(2048), created_at DATETIME DEFAULT(datetime('now', 'localtime')), file_size INTEGER);";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
// fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
fprintf(stdout, "Files table created successfully\n");
}
}
// commits table
connection = sqlite3_open("vcs.db", &db);
if (!connection){
string query = "CREATE TABLE commits (id INTEGER PRIMARY KEY DEFAULT 0, message VARCHAR(256), branch VARCHAR(256),local_created_at DATETIME DEFAULT(datetime('now', 'localtime')), remote_created_at DATETIME NULL, num_files_changed INTEGER);";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
// fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
fprintf(stdout, "Commit table created successfully\n");
}
}
// file_revisions table ( commit as fk )
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
string query = "CREATE TABLE file_revisions(id INTEGER PRIMARY KEY DEFAULT 0, file_path VARCHAR(1024),is_added BOOLEAN, is_removed BOOLEAN, is_modified BOOLEAN, commit_id INT, FOREIGN KEY(commit_id) REFERENCES commits(id) ON DELETE CASCADE);";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
// fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
fprintf(stdout, "Revisions table created successfully\n");
}
}
// commits_to_push
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
string query = "CREATE TABLE commits_to_push (id INTEGER PRIMARY KEY DEFAULT 0, commit_id INT, FOREIGN KEY(commit_id) REFERENCES commits(id) ON DELETE CASCADE);";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
// fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
fprintf(stdout, "Revisions table created successfully\n");
}
}
sqlite3_close(db);
return 0;
}
// create .txt file based on revision_type(added, modified, removed) called only by status method
// file_paths --> file paths to store on
int file_revision(std::vector<string> file_paths, string revision_type) {
if (file_paths.empty())
return 0;
create_revisions_directory(".revisions/files/");
string tmp_file = "./.revisions/files/" + revision_type + ".txt";
std::vector<string> _files_in_file;
get_file_paths(_files_in_file, revision_type);
// if revision_type is removed, create file with revisions
for (int i=0; i<file_paths.size(); i++) {
// if path already added to file, skip
if (std::find(_files_in_file.begin(), _files_in_file.end(), file_paths[i]) == _files_in_file.end() == 0) {
continue;
}
else {
std::ofstream added;
added.open(".revisions/files/" + revision_type +".txt", std::ios_base::app);
added<<file_paths[i]<<endl;
added.close();
}
}
return 0;
}
// get all files in directory, check for changed files
void commit(std::string message) {
create_revisions_directory(".revisions/commits/");
// in case there are changes and added.txt, modified files are removed
status();
// if .revisions/files folder empty / nothing to commit
if (!fs::exists(fs::path(".revisions/files/"))) {
cout<<"Nothing to commit!\n";
return;
}
sqlite3 *db;
char *errmessage = 0;
int connection;
connection = sqlite3_open("vcs.db", &db);
std::vector<string> added_files;
get_file_paths(added_files, "added");
// insert in files table
if (!connection) {
for(int i = 0; i < added_files.size(); i++) {
std::filesystem::path p{added_files[i]};
string size;
if (std::filesystem::is_directory(p)) {
size = "0";
}
else {
size = to_string(std::filesystem::file_size(p));
}
string query = "INSERT INTO files(file_path, file_size) VALUES ('" + added_files[i] + "', '" + size + "');";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Inserted successfully\n");
}
}
}
else {
cout<<"could not open database";
}
// modified files
connection = sqlite3_open("vcs.db", &db);
std::vector<string> modified_files;
get_file_paths(modified_files, "modified");
if (!connection) {
for(int i = 0; i < modified_files.size(); i++) {
std::filesystem::path p{modified_files[i]};
string size;
if (std::filesystem::is_directory(p)) {
size = "0";
}
else {
size = to_string(std::filesystem::file_size(p));
}
string query = "UPDATE files SET file_size = " + size + " WHERE file_path='" + modified_files[i] + "';";
// cout<<"query: "<<query <<endl;
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Updated successfully\n");
}
}
}
else {
cout<<"could not open database";
}
// removed files
std::vector<std::string> removed_files;
get_file_paths(removed_files, "removed");
if (!connection) {
for(int i = 0; i < removed_files.size(); i++) {
string query = "DELETE FROM files WHERE file_path='" + removed_files[i] + "';";
// cout<<"query: "<<query <<endl;
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Removed successfully\n");
}
}
}
else {
cout<<"could not open database";
}
// insert in commits table
// get current branch
std::ifstream file(".revisions/HEAD");
string current_branch;
std::getline(file, current_branch);
file.close();
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
string query = "INSERT INTO commits(message, num_files_changed, branch) VALUES('" + message + "', " + to_string(modified_files.size() + added_files.size() + removed_files.size()) + ", '" + current_branch + "');";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Inserted successfully\n");
}
}
// get the commit id for latest commit
connection = sqlite3_open("vcs.db", &db);
int commit_id = 0;
if (!connection) {
string query = "SELECT id from commits ORDER BY local_created_at DESC LIMIT 1;";
connection = sqlite3_exec(db, query.c_str(), get_latest_commit_id, &commit_id, &errmessage);
cout<<"Latest commit id: "<<commit_id<<endl;
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Inserted successfully\n");
}
}
// file_revisions table
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
// file revisions for added files;
for(int i = 0; i < added_files.size(); i++) {
string query = "INSERT INTO file_revisions(file_path, is_added, commit_id) VALUES ('" + added_files[i] + "',true, " + to_string(commit_id) + ")";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Inserted successfully\n");
}
}
}
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
// file revisions for modified files;
for(int i = 0; i < modified_files.size(); i++) {
string query = "INSERT INTO file_revisions(file_path, is_modified, commit_id) VALUES ('" + modified_files[i] + "',true, " + to_string(commit_id) + ")";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Inserted successfully\n");
}
}
}
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
// file revisions for removed files;
for(int i = 0; i < removed_files.size(); i++) {
string query = "INSERT INTO file_revisions(file_path, is_removed, commit_id) VALUES ('" + removed_files[i] + "',true, " + to_string(commit_id) + ")";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Inserted successfully\n");
}
}
}
// commits_to_push
connection = sqlite3_open("vcs.db", &db);
if (!connection) {
string query = "INSERT INTO commits_to_push(commit_id) VALUES (" + to_string(commit_id) + ");";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// fprintf(stdout, "Inserted successfully\n");
}
}
sqlite3_close(db);
// delete file
std::filesystem::remove(".revisions/added.txt");
// create specific commit folder and copy added, modified files + deleted.txt based on current branch(HEAD)
if (!fs::exists(".revisions/commits/" + current_branch))
fs::create_directory(".revisions/commits/" + current_branch);
string commit_path = ".revisions/commits/" + current_branch + "/" + to_string(commit_id) + "/";
create_revisions_directory(commit_path);
added_files.insert(added_files.end(), modified_files.begin(), modified_files.end());
std::vector<string> files_in_commit = added_files;
// TODO: add deleted files support
fs::copy_options copyOptions = fs::copy_options::update_existing | fs::copy_options::recursive;
for(int i = 0; i < files_in_commit.size(); i++) {
try {
auto file_path = std::filesystem::path(commit_path + files_in_commit[i]);
std::filesystem::copy(files_in_commit[i], file_path, copyOptions);
}
catch(int i) {
cout<<"Exception: "<<i<<endl;
}
}
// added deleted.txt
if (removed_files.size() > 0) {
std::ofstream deleted_files;
deleted_files.open(commit_path + "/deleted.txt", std::ios_base::app);
for (int i = 0; i < removed_files.size(); i++) {
deleted_files << removed_files[i] <<endl;
}
deleted_files.close();
}
// remove .revisions/files/ dir
fs::remove_all(fs::path(".revisions/files"));
// create / update HEAD ref for local
if (!fs::exists(".revisions/branches/" + current_branch))
fs::create_directories(".revisions/branches/" + current_branch);
std::ofstream head_file(".revisions/branches/" + current_branch + "/HEAD");
head_file << commit_id;
head_file.close();
}
// get files status
void status () {
// rm prev dir to update values
fs::remove_all(fs::path(".revisions/files/"));
sqlite3 *db;
char *errmessage = 0;
int connection;
connection = sqlite3_open("vcs.db", &db);
// status vectors
std::vector<pair<string, int>>db_files; // stores file_path, file_size
std::vector<string> removed;
std::vector<string> modified;
if (!connection) {
string query = "SELECT file_path, file_size FROM files;";
connection = sqlite3_exec(db, query.c_str(), get_db_files_callback, &db_files, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// get listdir
std::vector<string> files_ls;
listdir(files_ls);
// cout<<"files in dir: "<<files_ls.size();
// cout<<"db_files: "<<db_files.size();
for(int i=0; i<db_files.size(); i++) {
// check if file present in dir + db
auto idx = std::find(files_ls.begin(), files_ls.end(), db_files[i].first);
if (idx != files_ls.end()) {
std::filesystem::path p {files_ls[idx - files_ls.begin()]};
int size;
if (std::filesystem::is_directory(p)) {
size = 0;
} else {
size = std::filesystem::file_size(p);
}
// cout<<"size of files_ls: "<<size<<" "<<"size of db_files: "<<db_files[i].second<<endl;
// if even the size is same, then the file is unchanged
if (db_files[i].second == size){
// cout<<"unchanged: "<<db_files[i].first<<endl;
files_ls.erase(std::remove(files_ls.begin(), files_ls.end(), db_files[i].first), files_ls.end());
}
// file is modified
else {
files_ls.erase(std::remove(files_ls.begin(), files_ls.end(), db_files[i].first), files_ls.end());
modified.push_back(db_files[i].first);
}
}
// else add to removed
else
removed.push_back(db_files[i].first);
}
cout<<"Removed: "<<removed.size()<<endl;
cout<<"Added: "<<files_ls.size()<<endl;
cout<<"Modified: "<<modified.size()<<endl;
// remaining files are newly added files
file_revision(files_ls, "added");
for(int i = 0; i < files_ls.size(); i++){
cout<<"\n\u001b[32m[ADDED] "<<files_ls[i]<<"\u001b[0m";
}
file_revision(modified, "modified");
for (int i = 0; i < modified.size(); i++){
cout<<"\n\u001b[33m[MODIFIED]"<<modified[i]<<"\u001b[0m";
}
file_revision(removed, "removed");
for (int i = 0; i < removed.size(); i++){
cout<<"\n\u001b[31m[REMOVED]"<<removed[i]<<"\u001b[0m";
}
}
} else {
cout<<"could not open database";
}
cout<<endl;
sqlite3_close(db);
}
void show_log() {
sqlite3 *db;
char *errmessage = 0;
int connection;
// number of commits to see log of
int n = 1;
cout<<"Enter number of commits to see log of: ";
cin>>n;
// logs of only current branch
std::ifstream file(".revisions/HEAD");
string current_branch;
std::getline(file, current_branch);
file.close();
connection = sqlite3_open("vcs.db", &db);
vector<vector<string>> commit_info;
if (!connection) {
string query = "SELECT id, message, local_created_at from commits WHERE branch='" + current_branch + "' ORDER BY local_created_at DESC LIMIT " + to_string(n) + ";";
connection = sqlite3_exec(db, query.c_str(), get_commits_info, &commit_info, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {}
}
for(int i=0; i<commit_info.size(); i++){
cout<<"--------------------------\n";
// print the files
cout<<"Commit ID: "<<commit_info[i][0]<<endl;
cout<<"Message: "<<commit_info[i][1]<<endl;
cout<<"Timestamp: "<<commit_info[i][2]<<endl;
}
cout<<"Branch: "<<current_branch<<endl;
}
int push_to_server() {
// get the files
sqlite3 *db;
char *errmessage = 0;
int connection;
// get the commit ids
std::vector<string> commit_ids;
connection = sqlite3_open("vcs.db", &db);
int commit_id = 0;
if (!connection) {
string query = "SELECT commit_id from commits_to_push;";
connection = sqlite3_exec(db, query.c_str(), get_files_in_commit, &commit_ids, &errmessage);
if( connection != SQLITE_OK ){
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {}
}
// if nothing to push
if (commit_ids.size() == 0) {
cout<<"No commits to push"<<endl;
return 0;
}
connection = sqlite3_open("vcs.db", &db);
std::vector<string> file_revisions;
for(int i=0; i<commit_ids.size(); i++){
string query = "SELECT (file_path) from file_revisions WHERE commit_id = " + commit_ids[i] + " AND is_removed IS NULL;";
connection = sqlite3_exec(db, query.c_str(), get_files_in_commit, &file_revisions, &errmessage);
if (connection != SQLITE_OK) {
fprintf(stderr, "SQL error: %s\n", errmessage);
sqlite3_free(errmessage);
} else {
// print the files
for (int i = 0; i < file_revisions.size(); i++)
cout<<file_revisions[i]<<endl;
}
}
// push to server
int sock = create_socket_client();
for(int i = 0; i < file_revisions.size(); i++) {
// std::this_thread::sleep_for(std::chrono::milliseconds(4000));
// keep looping till you get response from server and if first file, then send without getting response
cout<<"sending file: "<<file_revisions[i]<<endl;
if (std::filesystem::is_directory(std::filesystem::path(file_revisions[i]))) {
send_mkdir_stream(sock, file_revisions[i]);
} else {
send_data(sock, file_revisions[i]);
}
// keep receiving until you get response from server
char response_arr[1024];
while(1){
int valread = recv(sock, response_arr, sizeof(response_arr), 0);
if (valread > 0 )
break;
for(int i=0; i<valread; i++)
cout<<response_arr[i];
// cout<<"bytes received: "<<valread<<endl;
printf("response: %s\n", response_arr);
// in case server closes socket, valread is 0
if (valread == 0) {
cout<<"\nServer closed connection";
exit(EXIT_FAILURE);
}
}
}
// remove from commits_to_push
for(int i=0; i<commit_ids.size(); i++){
connection = sqlite3_open("vcs.db", &db);
string query = "DELETE FROM commits_to_push WHERE commit_id = " + commit_ids[i] + ";";
connection = sqlite3_exec(db, query.c_str(), callback, 0, &errmessage);
}
cout<<"\u001b[32mPushed successfully to server!\u001b[0m"<<endl;
return 0;
}
/* Go to state based on commit id */
// TODO: fix checkout and get from branch commits
void checkout_commit_id(string commit_id){
fs::copy_options copyOptions = fs::copy_options::update_existing | fs::copy_options::recursive;
for(int i = 1; i < stoi(commit_id)+1; i++) {
try {
// auto file_path = std::filesystem::path(commit_path + files_in_commit[i]);
std::filesystem::copy(fs::path(".revisions/commits/" + to_string(i) + "/"), fs::path("./tmp"), copyOptions);
// removed deleted files
if (fs::exists("./tmp/deleted.txt")){
cout<<"exists"<<endl;
std::ifstream tmp_file("./tmp/deleted.txt");
string line;
while(std::getline(tmp_file,line)){
fs::remove("./tmp/" + line);
}
}
fs::remove("./tmp/deleted.txt");
}
catch(int i) {
cout<<"Exception: "<<i<<endl;
}
}
}
/* creates branch if -b flag is set and points HEAD to it */
void create_branch_and_checkout(string branch_name) {
if (fs::exists(fs::path(".revisions/files"))) {
cout<<"Commit your changes before creating branch!\n";
return;
} else {
// create branch if not exists
if (!fs::exists(".revisions/branches/" + branch_name)){
fs::create_directory(".revisions/branches/" + branch_name);
std::ofstream branches;
branches.open(".revisions/branches/branches.txt", std::ios_base::app);
branches << branch_name<<endl;
branches.close();
std::ofstream head;
head.open(".revisions/HEAD", std::ios::trunc);
head << branch_name << endl;
head.close();
cout<<"Created branch "<<branch_name<<"\n";
return;
} else {
// checkout branch
std::ofstream head;
head.open(".revisions/HEAD", std::ios::trunc);
head << branch_name << endl;
head.close();
return;
}
}
}
/* display all the branches in local repository */
void display_branches() {
// call status to update if there are any changes
status();
// get current branch
std::ifstream file(".revisions/HEAD");
string current_branch;
std::getline(file, current_branch);
file.close();
std::ifstream branches(".revisions/branches/branches.txt");
string line;
cout<<"Branches:\n";
while(std::getline(branches,line)) {
if(strcmp(line.c_str(), current_branch.c_str()) == 0) {
cout<<"* "<<line<<endl;
} else {
cout<<line<<endl;
}
}
branches.close();
}
/* merges branch 2 into branch 1 */
void merge(string branch_2, string branch_1) {
// add files from branch 2 to branch 1
fs::copy_options copyOptions = fs::copy_options::update_existing | fs::copy_options::recursive;
fs::copy(".revisions/commits/" + branch_2, ".revisions/commits/" + branch_1, copyOptions);
cout<<"Merged commits!"<<endl;
// TODO: create commit to keep track of merges
// TODO: implement for multiple users
}
void display_help() {
cout<<"Usage: ./file.out [--help] [status] [commit <message>] [push] [checkout <commit_id>] [log]\n\n";
cout<<"\t Status: Prints current status of files in repository\n";
cout<<"\t Commit: Records the revised files to local storage\n";
cout<<"\t Push: Pushes the file changes to remote server\n";
cout<<"\t Log: Displays the log messages for previous commits\n";
cout<<"\t Checkout: Go back to some particular commit\n";
}
// deprecated as status itself adds the file revisions
// // similar to git add, create temp file to store new files
// int add(string file_path) {
// create_revisions_directory("revisions");
// std::vector<string> files_ls;
// listdir(files_ls);
// std::vector<string> added_files;
// get_file_paths(added_files, "added");
// // cout<<"added files:"<<added_files.size()<<endl;
// // check if file_path entered exists in project dir
// for (int i=0; i<files_ls.size(); i++){
// if(strcmp(files_ls[i].c_str(), ("./" + file_path).c_str()) == 0) {
// if (std::find(added_files.begin(), added_files.end(), "./" + file_path) != added_files.end() != 0) {
// cout<<"File already added!"<<endl;
// return 1;
// }
// std::ofstream added;
// added.open(".revisions/added.txt", std::ios_base::app);
// added << "./" + file_path<<endl;
// cout<<"\nAdded file!";
// return 0;
// }
// }
// cout <<"\nFile not found!";
// return 1;
// }
/* NOTE: deprecated for now */
// int create_file_revision(string text) {
// fstream file;
// auto t = std::time(nullptr);
// auto tm = *std::localtime(&t);
// std::hash<string> hash_string;
// std::ostringstream oss;
// oss << std::put_time(&tm, "%Y-%m-%d %H-%M-%S");
// string timestamp = oss.str();
// string filepath = ".revisions/" + timestamp + ".txt";
// file.open(filepath,std::ios_base::app);
// file <<hash_string(timestamp)<< endl << endl;
// file << "This file was auto-generated on "<<timestamp;
// if(!file)
// {
// cout<<"Error in creating file!!!";
// return 1;
// }
// string path = ".";
// std::ofstream file_list;
// file_list.open(filepath,ios::in | ios::out);
// for (const auto & file : recursive_directory_iterator(path)) {
// int count = 0;
// if (file.path().u8string().string::find(".git") == string::npos){
// // open file_list and add new files
// std::ifstream file_list;
// file_list.open(".revisions/list.txt", std::ios_base::app);
// if (file_list.is_open()) {
// string line;
// while(std::getline(file_list, line)){
// if (line.string::find(file.path().u8string()) != string::npos){
// count++;
// }
// }
// }
// if (count==0) {
// cout << file.path().u8string() << endl;
// std::ofstream tmp;
// tmp.open(".revisions/list.txt", std::ios_base::app);
// tmp <<file.path().u8string() << endl;
// tmp.close();
// }
// file_list.close();
// }
// }
// cout<<"File created successfully.";
// file.close();
// return 0;
// }
bool check_args(const std::string &value, const std::vector<std::string> &array)
{
return std::find(array.begin(), array.end(), value) != array.end();
}
// Driver code
int main(int argc, char* argv[])
{
std::vector<std::string> commands {"status", "commit", "push", "remove", "log", "--help", "checkout", "branch", "merge"};
// check if empty repository
create_table();
if (!fs::exists(".revisions")) {
create_revisions_directory(".revisions");
std::ofstream head(".revisions/HEAD");
head << "main";
head.close();
// stores HEADS of respective branches
create_revisions_directory(".revisions/branches/");
// add master as initial branch
std::ofstream branches(".revisions/branches/branches.txt");
branches << "main\n";
branches.close();
}
if (argc == 1) {
cout<<"Incorrect usage. Run ./a.out <add/commit/push>. Run ./file.out --help for more information."<<endl;
return 1;
}
if (check_args(argv[1], commands)) {
// if (strcmp(argv[1], "add") == 0)
// add(argv[2]);
if (strcmp(argv[1], "commit") == 0){
if (argc != 3) {
cout<<"Invalid format: Enter ./file.out commit <message> "<<endl;
return -1;
}
commit(argv[2]);
}
if (strcmp(argv[1], "status") == 0)
status();
if (strcmp(argv[1], "log") == 0)
show_log();
if (strcmp(argv[1], "push") == 0)
push_to_server();
if (strcmp(argv[1], "--help") == 0)
display_help();
if (strcmp(argv[1], "checkout") == 0){
if (!(2<argc<4)) {
cout<<"Invalid format: Enter ./file.out checkout <commit_id> or ./file.out checkout -b <branch_name>"<<endl;
return -1;
}
if (strcmp(argv[2], "-b")!=0)
checkout_commit_id(argv[2]);
else {
create_branch_and_checkout(argv[3]);
}
}
if ((strcmp(argv[1], "branch") == 0)) {
display_branches();
}
if (strcmp(argv[1], "merge") == 0){
if (argc != 4)
cout<<"Invalid format: Enter ./file.out merge <branch2> <branch1>"<<endl;
else {
merge(argv[2], argv[3]);
}
}
}
else {
cout<<"Unknown command: "<<argv[1]<<endl<<"Run ./a.out <add/commit/push>"<<endl;
}
// create_file_revision("some");
return 0;
}