forked from ClickHouse/ClickHouse
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-import.cpp
More file actions
1250 lines (1076 loc) · 40 KB
/
Copy pathgit-import.cpp
File metadata and controls
1250 lines (1076 loc) · 40 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
#include <cstdint>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <unordered_set>
#include <unordered_map>
#include <list>
#include <thread>
#include <filesystem>
#include <boost/program_options.hpp>
#include <Common/TerminalSize.h>
#include <Common/Exception.h>
#include <Common/SipHash.h>
#include <Common/StringUtils.h>
#include <Common/ShellCommand.h>
#include <Common/re2.h>
#include <Common/shellQuote.h>
#include <base/find_symbols.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteHelpers.h>
#include <IO/WriteBufferFromFile.h>
#include <IO/WriteBufferFromFileDescriptor.h>
static constexpr auto documentation = R"(
A tool to extract information from Git repository for analytics.
It dumps the data for the following tables:
- commits - commits with statistics;
- file_changes - files changed in every commit with the info about the change and statistics;
- line_changes - every changed line in every changed file in every commit with full info about the line and the information about previous change of this line.
The largest and the most important table is "line_changes".
Allows to answer questions like:
- list files with maximum number of authors;
- show me the oldest lines of code in the repository;
- show me the files with longest history;
- list favorite files for author;
- list largest files with lowest number of authors;
- at what weekday the code has highest chance to stay in repository;
- the distribution of code age across repository;
- files sorted by average code age;
- quickly show file with blame info (rough);
- commits and lines of code distribution by time; by weekday, by author; for specific subdirectories;
- show history for every subdirectory, file, line of file, the number of changes (lines and commits) across time; how the number of contributors was changed across time;
- list files with most modifications;
- list files that were rewritten most number of time or by most of authors;
- what is percentage of code removal by other authors, across authors;
- the matrix of authors that shows what authors tends to rewrite another authors code;
- what is the worst time to write code in sense that the code has highest chance to be rewritten;
- the average time before code will be rewritten and the median (half-life of code decay);
- comments/code percentage change in time / by author / by location;
- who tend to write more tests / cpp code / comments.
The data is intended for analytical purposes. It can be imprecise by many reasons but it should be good enough for its purpose.
The data is not intended to provide any conclusions for managers, it is especially counter-indicative for any kinds of "performance review". Instead you can spend multiple days looking at various interesting statistics.
Run this tool inside your git repository. It will create .tsv files that can be loaded into ClickHouse (or into other DBMS if you dare).
The tool can process large enough repositories in a reasonable time.
It has been tested on:
- ClickHouse: 31 seconds; 3 million rows;
- LLVM: 8 minutes; 62 million rows;
- Linux - 12 minutes; 85 million rows;
- Chromium - 67 minutes; 343 million rows;
(the numbers as of Sep 2020)
Prepare the database by executing the following queries:
DROP DATABASE IF EXISTS git;
CREATE DATABASE git;
CREATE TABLE git.commits
(
hash String,
author LowCardinality(String),
time DateTime,
message String,
files_added UInt32,
files_deleted UInt32,
files_renamed UInt32,
files_modified UInt32,
lines_added UInt32,
lines_deleted UInt32,
hunks_added UInt32,
hunks_removed UInt32,
hunks_changed UInt32
) ENGINE = MergeTree ORDER BY time;
CREATE TABLE git.file_changes
(
change_type Enum('Add' = 1, 'Delete' = 2, 'Modify' = 3, 'Rename' = 4, 'Copy' = 5, 'Type' = 6),
path LowCardinality(String),
old_path LowCardinality(String),
file_extension LowCardinality(String),
lines_added UInt32,
lines_deleted UInt32,
hunks_added UInt32,
hunks_removed UInt32,
hunks_changed UInt32,
commit_hash String,
author LowCardinality(String),
time DateTime,
commit_message String,
commit_files_added UInt32,
commit_files_deleted UInt32,
commit_files_renamed UInt32,
commit_files_modified UInt32,
commit_lines_added UInt32,
commit_lines_deleted UInt32,
commit_hunks_added UInt32,
commit_hunks_removed UInt32,
commit_hunks_changed UInt32
) ENGINE = MergeTree ORDER BY time;
CREATE TABLE git.line_changes
(
sign Int8,
line_number_old UInt32,
line_number_new UInt32,
hunk_num UInt32,
hunk_start_line_number_old UInt32,
hunk_start_line_number_new UInt32,
hunk_lines_added UInt32,
hunk_lines_deleted UInt32,
hunk_context LowCardinality(String),
line LowCardinality(String),
indent UInt8,
line_type Enum('Empty' = 0, 'Comment' = 1, 'Punct' = 2, 'Code' = 3),
prev_commit_hash String,
prev_author LowCardinality(String),
prev_time DateTime,
file_change_type Enum('Add' = 1, 'Delete' = 2, 'Modify' = 3, 'Rename' = 4, 'Copy' = 5, 'Type' = 6),
path LowCardinality(String),
old_path LowCardinality(String),
file_extension LowCardinality(String),
file_lines_added UInt32,
file_lines_deleted UInt32,
file_hunks_added UInt32,
file_hunks_removed UInt32,
file_hunks_changed UInt32,
commit_hash String,
author LowCardinality(String),
time DateTime,
commit_message String,
commit_files_added UInt32,
commit_files_deleted UInt32,
commit_files_renamed UInt32,
commit_files_modified UInt32,
commit_lines_added UInt32,
commit_lines_deleted UInt32,
commit_hunks_added UInt32,
commit_hunks_removed UInt32,
commit_hunks_changed UInt32
) ENGINE = MergeTree ORDER BY time;
Run the tool.
Then insert the data with the following commands:
clickhouse-client --query "INSERT INTO git.commits FORMAT TSV" < commits.tsv
clickhouse-client --query "INSERT INTO git.file_changes FORMAT TSV" < file_changes.tsv
clickhouse-client --query "INSERT INTO git.line_changes FORMAT TSV" < line_changes.tsv
Check out this presentation: https://presentations.clickhouse.com/matemarketing_2020/
)";
namespace po = boost::program_options;
namespace DB
{
namespace ErrorCodes
{
extern const int INCORRECT_DATA;
}
struct Commit
{
std::string hash;
std::string author;
LocalDateTime time{};
std::string message;
uint32_t files_added{};
uint32_t files_deleted{};
uint32_t files_renamed{};
uint32_t files_modified{};
uint32_t lines_added{};
uint32_t lines_deleted{};
uint32_t hunks_added{};
uint32_t hunks_removed{};
uint32_t hunks_changed{};
void writeTextWithoutNewline(WriteBuffer & out) const
{
writeEscapedString(hash, out);
writeChar('\t', out);
writeEscapedString(author, out);
writeChar('\t', out);
writeText(time, out);
writeChar('\t', out);
writeEscapedString(message, out);
writeChar('\t', out);
writeText(files_added, out);
writeChar('\t', out);
writeText(files_deleted, out);
writeChar('\t', out);
writeText(files_renamed, out);
writeChar('\t', out);
writeText(files_modified, out);
writeChar('\t', out);
writeText(lines_added, out);
writeChar('\t', out);
writeText(lines_deleted, out);
writeChar('\t', out);
writeText(hunks_added, out);
writeChar('\t', out);
writeText(hunks_removed, out);
writeChar('\t', out);
writeText(hunks_changed, out);
}
};
enum class FileChangeType : uint8_t
{
Add,
Delete,
Modify,
Rename,
Copy,
Type,
};
static void writeText(FileChangeType type, WriteBuffer & out)
{
switch (type)
{
case FileChangeType::Add: writeString("Add", out); break;
case FileChangeType::Delete: writeString("Delete", out); break;
case FileChangeType::Modify: writeString("Modify", out); break;
case FileChangeType::Rename: writeString("Rename", out); break;
case FileChangeType::Copy: writeString("Copy", out); break;
case FileChangeType::Type: writeString("Type", out); break;
}
}
struct FileChange
{
FileChangeType change_type{};
std::string path;
std::string old_path;
std::string file_extension;
uint32_t lines_added{};
uint32_t lines_deleted{};
uint32_t hunks_added{};
uint32_t hunks_removed{};
uint32_t hunks_changed{};
void writeTextWithoutNewline(WriteBuffer & out) const
{
writeText(change_type, out);
writeChar('\t', out);
writeEscapedString(path, out);
writeChar('\t', out);
writeEscapedString(old_path, out);
writeChar('\t', out);
writeEscapedString(file_extension, out);
writeChar('\t', out);
writeText(lines_added, out);
writeChar('\t', out);
writeText(lines_deleted, out);
writeChar('\t', out);
writeText(hunks_added, out);
writeChar('\t', out);
writeText(hunks_removed, out);
writeChar('\t', out);
writeText(hunks_changed, out);
}
};
enum class LineType : uint8_t
{
Empty,
Comment,
Punct,
Code,
};
static void writeText(LineType type, WriteBuffer & out)
{
switch (type)
{
case LineType::Empty: writeString("Empty", out); break;
case LineType::Comment: writeString("Comment", out); break;
case LineType::Punct: writeString("Punct", out); break;
case LineType::Code: writeString("Code", out); break;
}
}
struct LineChange
{
int8_t sign{}; /// 1 if added, -1 if deleted
uint32_t line_number_old{};
uint32_t line_number_new{};
uint32_t hunk_num{}; /// ordinal number of hunk in diff, starting with 0
uint32_t hunk_start_line_number_old{};
uint32_t hunk_start_line_number_new{};
uint32_t hunk_lines_added{};
uint32_t hunk_lines_deleted{};
std::string hunk_context; /// The context (like a line with function name) as it is calculated by git
std::string line; /// Line content without leading whitespaces
uint8_t indent{}; /// The number of leading whitespaces or tabs * 4
LineType line_type{};
/// Information from the history (blame).
std::string prev_commit_hash;
std::string prev_author;
LocalDateTime prev_time{};
/** Classify line to empty / code / comment / single punctuation char.
* Very rough and mostly suitable for our C++ style.
*/
void setLineInfo(std::string full_line)
{
UInt8 num_spaces = 0;
const char * pos = full_line.data();
const char * end = pos + full_line.size();
while (pos < end)
{
if (*pos == ' ')
++num_spaces;
else if (*pos == '\t')
num_spaces += 4;
else
break;
++pos;
}
indent = std::min<UInt8>(255U, num_spaces);
line.assign(pos, end);
if (pos == end)
{
line_type = LineType::Empty;
}
else if (pos + 1 < end
&& ((pos[0] == '/' && (pos[1] == '/' || pos[1] == '*'))
|| (pos[0] == '*' && pos[1] == ' ') /// This is not precise.
|| (pos[0] == '#' && pos[1] == ' ')))
{
line_type = LineType::Comment;
}
else
{
while (pos < end)
{
if (isAlphaNumericASCII(*pos))
{
line_type = LineType::Code;
break;
}
++pos;
}
if (pos == end)
line_type = LineType::Punct;
}
}
void writeTextWithoutNewline(WriteBuffer & out) const
{
writeText(sign, out);
writeChar('\t', out);
writeText(line_number_old, out);
writeChar('\t', out);
writeText(line_number_new, out);
writeChar('\t', out);
writeText(hunk_num, out);
writeChar('\t', out);
writeText(hunk_start_line_number_old, out);
writeChar('\t', out);
writeText(hunk_start_line_number_new, out);
writeChar('\t', out);
writeText(hunk_lines_added, out);
writeChar('\t', out);
writeText(hunk_lines_deleted, out);
writeChar('\t', out);
writeEscapedString(hunk_context, out);
writeChar('\t', out);
writeEscapedString(line, out);
writeChar('\t', out);
writeText(indent, out);
writeChar('\t', out);
writeText(line_type, out);
writeChar('\t', out);
writeEscapedString(prev_commit_hash, out);
writeChar('\t', out);
writeEscapedString(prev_author, out);
writeChar('\t', out);
writeText(prev_time, out);
}
};
using LineChanges = std::vector<LineChange>;
struct FileDiff
{
explicit FileDiff(FileChange file_change_) : file_change(file_change_) {}
FileChange file_change;
LineChanges line_changes;
};
using CommitDiff = std::map<std::string /* path */, FileDiff>;
/** Parsing helpers */
static void skipUntilWhitespace(ReadBuffer & buf)
{
while (!buf.eof())
{
char * next_pos = find_first_symbols<'\t', '\n', ' '>(buf.position(), buf.buffer().end());
buf.position() = next_pos;
if (!buf.hasPendingData())
continue;
if (*buf.position() == '\t' || *buf.position() == '\n' || *buf.position() == ' ')
return;
}
}
static void skipUntilNextLine(ReadBuffer & buf)
{
while (!buf.eof())
{
char * next_pos = find_first_symbols<'\n'>(buf.position(), buf.buffer().end());
buf.position() = next_pos;
if (!buf.hasPendingData())
continue;
if (*buf.position() == '\n')
{
++buf.position();
return;
}
}
}
static void readStringUntilNextLine(std::string & s, ReadBuffer & buf)
{
s.clear();
while (!buf.eof())
{
char * next_pos = find_first_symbols<'\n'>(buf.position(), buf.buffer().end());
s.append(buf.position(), next_pos - buf.position());
buf.position() = next_pos;
if (!buf.hasPendingData())
continue;
if (*buf.position() == '\n')
{
++buf.position();
return;
}
}
}
/** Writes the resulting tables to files that can be imported to ClickHouse.
*/
struct ResultWriter
{
WriteBufferFromFile commits{"commits.tsv"};
WriteBufferFromFile file_changes{"file_changes.tsv"};
WriteBufferFromFile line_changes{"line_changes.tsv"};
void appendCommit(const Commit & commit, const CommitDiff & files)
{
/// commits table
{
auto & out = commits;
commit.writeTextWithoutNewline(out);
writeChar('\n', out);
}
for (const auto & elem : files)
{
const FileChange & file_change = elem.second.file_change;
/// file_changes table
{
auto & out = file_changes;
file_change.writeTextWithoutNewline(out);
writeChar('\t', out);
commit.writeTextWithoutNewline(out);
writeChar('\n', out);
}
/// line_changes table
for (const auto & line_change : elem.second.line_changes)
{
auto & out = line_changes;
line_change.writeTextWithoutNewline(out);
writeChar('\t', out);
file_change.writeTextWithoutNewline(out);
writeChar('\t', out);
commit.writeTextWithoutNewline(out);
writeChar('\n', out);
}
}
}
void finalize()
{
commits.finalize();
file_changes.finalize();
line_changes.finalize();
}
};
/** See description in "main".
*/
struct Options
{
bool skip_commits_without_parents = true;
bool skip_commits_with_duplicate_diffs = true;
size_t threads = 1;
std::optional<re2::RE2> skip_paths;
std::optional<re2::RE2> skip_commits_with_messages;
std::unordered_set<std::string> skip_commits;
std::optional<size_t> diff_size_limit;
std::string stop_after_commit;
explicit Options(const po::variables_map & options)
{
skip_commits_without_parents = options["skip-commits-without-parents"].as<bool>();
skip_commits_with_duplicate_diffs = options["skip-commits-with-duplicate-diffs"].as<bool>();
threads = options["threads"].as<size_t>();
if (options.contains("skip-paths"))
{
skip_paths.emplace(options["skip-paths"].as<std::string>());
}
if (options.contains("skip-commits-with-messages"))
{
skip_commits_with_messages.emplace(options["skip-commits-with-messages"].as<std::string>());
}
if (options.contains("skip-commit"))
{
auto vec = options["skip-commit"].as<std::vector<std::string>>();
skip_commits.insert(vec.begin(), vec.end());
}
if (options.contains("diff-size-limit"))
{
diff_size_limit = options["diff-size-limit"].as<size_t>();
}
if (options.contains("stop-after-commit"))
{
stop_after_commit = options["stop-after-commit"].as<std::string>();
}
}
};
/** Rough snapshot of repository calculated by application of diffs. It's used to calculate blame info.
* Represented by a list of lines. For every line it contains information about commit that modified this line the last time.
*
* Note that there are many cases when this info may become incorrect.
* The first reason is that git history is non-linear but we form this snapshot by application of commit diffs in some order
* that cannot give us correct results even theoretically.
* The second reason is that we don't process merge commits. But merge commits may contain differences for conflict resolution.
*
* We expect that the information will be mostly correct for the purpose of analytics.
* So, it can provide the expected "blame" info for the most of the lines.
*/
struct FileBlame
{
using Lines = std::list<Commit>;
Lines lines;
/// We walk through this list adding or removing lines.
Lines::iterator it;
size_t current_idx = 1;
FileBlame()
{
it = lines.begin();
}
/// This is important when file was copied or renamed.
FileBlame & operator=(const FileBlame & rhs)
{
if (&rhs == this)
return *this;
lines = rhs.lines;
it = lines.begin();
current_idx = 1;
return *this;
}
FileBlame(const FileBlame & rhs)
{
*this = rhs;
}
/// Move iterator to requested line or stop at the end.
void walk(uint32_t num)
{
while (current_idx < num && it != lines.end())
{
++current_idx;
++it;
}
while (current_idx > num)
{
--current_idx;
--it;
}
}
const Commit * find(uint32_t num)
{
walk(num);
// std::cerr << "current_idx: " << current_idx << ", num: " << num << "\n";
if (current_idx == num && it != lines.end())
return &*it;
return {};
}
void addLine(uint32_t num, Commit commit)
{
walk(num);
/// If the inserted line is over the end of file, we insert empty lines before it.
while (it == lines.end() && current_idx < num)
{
lines.emplace_back();
++current_idx;
}
it = lines.insert(it, commit);
}
void removeLine(uint32_t num)
{
// std::cerr << "Removing line " << num << ", current_idx: " << current_idx << "\n";
walk(num);
if (current_idx == num && it != lines.end())
it = lines.erase(it);
}
};
/// All files with their blame info. When file is renamed, we also rename it in snapshot.
using Snapshot = std::map<std::string /* path */, FileBlame>;
/** Enrich the line changes data with the history info from the snapshot
* - the author, time and commit of the previous change to every found line (blame).
* And update the snapshot.
*/
static void updateSnapshot(Snapshot & snapshot, const Commit & commit, CommitDiff & file_changes)
{
/// Renames and copies.
for (auto & elem : file_changes)
{
auto & file = elem.second.file_change;
if (!file.old_path.empty() && file.path != file.old_path)
snapshot[file.path] = snapshot[file.old_path];
}
for (auto & elem : file_changes)
{
// std::cerr << elem.first << "\n";
FileBlame & file_snapshot = snapshot[elem.first];
std::unordered_map<uint32_t, Commit> deleted_lines;
/// Obtain blame info from previous state of the snapshot
for (auto & line_change : elem.second.line_changes)
{
if (line_change.sign == -1)
{
if (const Commit * prev_commit = file_snapshot.find(line_change.line_number_old);
prev_commit && prev_commit->time <= commit.time)
{
line_change.prev_commit_hash = prev_commit->hash;
line_change.prev_author = prev_commit->author;
line_change.prev_time = prev_commit->time;
deleted_lines[line_change.line_number_old] = *prev_commit;
}
else
{
// std::cerr << "Did not find line " << line_change.line_number_old << " from file " << elem.first << ": " << line_change.line << "\n";
}
}
else if (line_change.sign == 1)
{
uint32_t this_line_in_prev_commit = line_change.hunk_start_line_number_old
+ (line_change.line_number_new - line_change.hunk_start_line_number_new);
if (deleted_lines.contains(this_line_in_prev_commit))
{
const auto & prev_commit = deleted_lines[this_line_in_prev_commit];
if (prev_commit.time <= commit.time)
{
line_change.prev_commit_hash = prev_commit.hash;
line_change.prev_author = prev_commit.author;
line_change.prev_time = prev_commit.time;
}
}
}
}
/// Update the snapshot
for (const auto & line_change : elem.second.line_changes)
{
if (line_change.sign == -1)
{
file_snapshot.removeLine(line_change.line_number_new);
}
else if (line_change.sign == 1)
{
file_snapshot.addLine(line_change.line_number_new, commit);
}
}
}
}
/** Deduplication of commits with identical diffs.
*/
using DiffHashes = std::unordered_set<UInt128>;
static UInt128 diffHash(const CommitDiff & file_changes)
{
SipHash hasher;
for (const auto & elem : file_changes)
{
hasher.update(elem.second.file_change.change_type);
hasher.update(elem.second.file_change.old_path.size());
hasher.update(elem.second.file_change.old_path);
hasher.update(elem.second.file_change.path.size());
hasher.update(elem.second.file_change.path);
hasher.update(elem.second.line_changes.size());
for (const auto & line_change : elem.second.line_changes)
{
hasher.update(line_change.sign);
hasher.update(line_change.line_number_old);
hasher.update(line_change.line_number_new);
hasher.update(line_change.indent);
hasher.update(line_change.line.size());
hasher.update(line_change.line);
}
}
UInt128 hash_of_diff;
hasher.get128(hash_of_diff.items[0], hash_of_diff.items[1]);
return hash_of_diff;
}
/** File changes in form
* :100644 100644 b90fe6bb94 3ffe4c380f M src/Storages/MergeTree/MergeTreeDataMergerMutator.cpp
* :100644 100644 828dedf6b5 828dedf6b5 R100 dbms/src/Functions/GeoUtils.h dbms/src/Functions/PolygonUtils.h
* according to the output of 'git show --raw'
*/
static void processFileChanges(
ReadBuffer & in,
const Options & options,
Commit & commit,
CommitDiff & file_changes)
{
while (checkChar(':', in))
{
FileChange file_change;
/// We don't care about file mode and content hashes.
for (size_t i = 0; i < 4; ++i)
{
skipUntilWhitespace(in);
skipWhitespaceIfAny(in);
}
char change_type = {};
readChar(change_type, in);
/// For rename and copy there is a number called "score". We ignore it.
int score = {};
switch (change_type)
{
case 'A':
file_change.change_type = FileChangeType::Add;
++commit.files_added;
break;
case 'D':
file_change.change_type = FileChangeType::Delete;
++commit.files_deleted;
break;
case 'M':
file_change.change_type = FileChangeType::Modify;
++commit.files_modified;
break;
case 'R':
file_change.change_type = FileChangeType::Rename;
++commit.files_renamed;
readText(score, in);
break;
case 'C':
file_change.change_type = FileChangeType::Copy;
readText(score, in);
break;
case 'T':
file_change.change_type = FileChangeType::Type;
break;
default:
throw Exception(ErrorCodes::INCORRECT_DATA, "Unexpected file change type: {}", change_type);
}
skipWhitespaceIfAny(in);
if (change_type == 'R' || change_type == 'C')
{
readText(file_change.old_path, in);
skipWhitespaceIfAny(in);
readText(file_change.path, in);
}
else
{
readText(file_change.path, in);
}
file_change.file_extension = std::filesystem::path(file_change.path).extension();
/// It gives us extension in form of '.cpp'. There is a reason for it but we remove initial dot for simplicity.
if (!file_change.file_extension.empty() && file_change.file_extension.front() == '.')
file_change.file_extension = file_change.file_extension.substr(1, std::string::npos);
assertChar('\n', in);
if (!(options.skip_paths && re2::RE2::PartialMatch(file_change.path, *options.skip_paths)))
{
file_changes.emplace(
file_change.path,
FileDiff(file_change));
}
}
}
/** Process the list of diffs for every file from the result of "git show".
* Caveats:
* - changes in binary files can be ignored;
* - if a line content begins with '+' or '-' it will be skipped
* it means that if you store diffs in repository and "git show" will display diff-of-diff for you,
* it won't be processed correctly;
* - we expect some specific format of the diff; but it may actually depend on git config;
* - non-ASCII file names are not processed correctly (they will not be found and will be ignored).
*/
static void processDiffs(
ReadBuffer & in,
std::optional<size_t> size_limit,
Commit & commit,
CommitDiff & file_changes)
{
std::string old_file_path;
std::string new_file_path;
FileDiff * file_change_and_line_changes = nullptr;
LineChange line_change;
/// Diffs for every file in form of
/// --- a/src/Storages/StorageReplicatedMergeTree.cpp
/// +++ b/src/Storages/StorageReplicatedMergeTree.cpp
/// @@ -1387,2 +1387 @@ bool StorageReplicatedMergeTree::tryExecuteMerge(const LogEntry & entry)
/// - table_lock, entry.create_time, reserved_space, entry.deduplicate,
/// - entry.force_ttl);
/// + table_lock, entry.create_time, reserved_space, entry.deduplicate);
size_t diff_size = 0;
while (!in.eof())
{
if (checkString("@@ ", in))
{
if (!file_change_and_line_changes)
{
auto file_name = new_file_path.empty() ? old_file_path : new_file_path;
auto it = file_changes.find(file_name);
if (file_changes.end() != it)
file_change_and_line_changes = &it->second;
}
if (file_change_and_line_changes)
{
uint32_t old_lines = 1;
uint32_t new_lines = 1;
assertChar('-', in);
readText(line_change.hunk_start_line_number_old, in);
if (checkChar(',', in))
readText(old_lines, in);
assertString(" +", in);
readText(line_change.hunk_start_line_number_new, in);
if (checkChar(',', in))
readText(new_lines, in);
/// This is needed to simplify the logic of updating snapshot:
/// When all lines are removed we can treat it as repeated removal of line with number 1.
if (line_change.hunk_start_line_number_new == 0)
line_change.hunk_start_line_number_new = 1;
assertString(" @@", in);
if (checkChar(' ', in))
readStringUntilNextLine(line_change.hunk_context, in);
else
assertChar('\n', in);
line_change.hunk_lines_added = new_lines;
line_change.hunk_lines_deleted = old_lines;
++line_change.hunk_num;
line_change.line_number_old = line_change.hunk_start_line_number_old;
line_change.line_number_new = line_change.hunk_start_line_number_new;
if (old_lines && new_lines)
{
++commit.hunks_changed;
++file_change_and_line_changes->file_change.hunks_changed;
}
else if (old_lines)
{
++commit.hunks_removed;
++file_change_and_line_changes->file_change.hunks_removed;
}
else if (new_lines)
{
++commit.hunks_added;
++file_change_and_line_changes->file_change.hunks_added;
}
}
}
else if (checkChar('-', in))
{
if (checkString("-- ", in))
{
if (checkString("a/", in))
{
readStringUntilNextLine(old_file_path, in);
line_change = LineChange{};
file_change_and_line_changes = nullptr;
}
else if (checkString("/dev/null", in))
{
old_file_path.clear();
assertChar('\n', in);
line_change = LineChange{};
file_change_and_line_changes = nullptr;
}
else
skipUntilNextLine(in); /// Actually it can be the line in diff. Skip it for simplicity.
}
else
{
++diff_size;
if (file_change_and_line_changes)
{
++commit.lines_deleted;
++file_change_and_line_changes->file_change.lines_deleted;
line_change.sign = -1;
readStringUntilNextLine(line_change.line, in);