-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathprolly-ui.rs
More file actions
2061 lines (1807 loc) · 67.9 KB
/
Copy pathprolly-ui.rs
File metadata and controls
2061 lines (1807 loc) · 67.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
/*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
use clap::Parser;
use prollytree::git::versioned_store::HistoricalAccess;
use prollytree::git::{CommitInfo, DiffOperation, GitVersionedKvStore, KvDiff};
use std::collections::{HashMap, HashSet};
use std::fs;
use std::path::{Path, PathBuf};
#[derive(Parser)]
#[command(name = "prolly-ui")]
#[command(about = "Generate static HTML visualization for git-prolly repositories")]
#[command(version = "0.3.2")]
struct Cli {
/// Path to the main git repository containing datasets as subdirectories
#[arg(help = "Repository path (defaults to current directory)")]
repo_path: Option<PathBuf>,
/// Output HTML file path
#[arg(short, long, default_value = "prolly-ui.html")]
output: PathBuf,
/// Specify which subdirectories are datasets (if not specified, all subdirectories with prolly data will be used)
#[arg(short = 'd', long = "dataset", value_name = "NAME")]
datasets: Vec<String>,
/// Filter to specific branches (if not specified, all branches will be processed)
#[arg(short = 'b', long = "branch", value_name = "BRANCH")]
branches: Vec<String>,
}
#[derive(Debug, Clone)]
struct BranchInfo {
name: String,
commits: Vec<CommitInfo>,
current: bool,
}
#[derive(Debug, Clone)]
struct DatasetInfo {
name: String,
path: PathBuf,
branches: Vec<BranchInfo>,
commit_details: HashMap<String, CommitDiff>,
}
#[derive(Debug, Clone)]
struct RepositoryData {
path: PathBuf,
datasets: Vec<DatasetInfo>,
git_branches: Vec<GitBranchInfo>,
_git_commits: HashMap<String, GitCommitInfo>,
}
#[derive(Debug, Clone)]
struct GitBranchInfo {
name: String,
commits: Vec<GitCommitInfo>,
current: bool,
}
#[derive(Debug, Clone)]
struct GitCommitInfo {
id: String,
author: String,
message: String,
timestamp: i64,
dataset_changes: HashMap<String, Vec<KvDiff>>,
}
#[derive(Debug, Clone)]
struct CommitDiff {
info: CommitInfo,
changes: Vec<KvDiff>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
// Process main repository
let repo_path = cli.repo_path.unwrap_or_else(|| PathBuf::from("."));
println!("📊 Processing repository: {}", repo_path.display());
// Discover or use specified datasets
let dataset_names = if cli.datasets.is_empty() {
// Auto-discover datasets and format them properly
let discovered = discover_datasets(&repo_path)?;
// Convert discovered dataset names to proper format with full paths
discovered
.into_iter()
.map(|name| {
// Capitalize first letter for the tag
let tag = name
.chars()
.enumerate()
.map(|(i, c)| {
if i == 0 {
c.to_uppercase().to_string()
} else {
c.to_string()
}
})
.collect::<String>();
// Return in "Tag:Path" format
format!("{}:{}", tag, repo_path.join(&name).display())
})
.collect()
} else {
cli.datasets
};
if dataset_names.is_empty() {
return Err("No datasets found in the repository".into());
}
println!(
"📁 Found {} dataset(s): {:?}",
dataset_names.len(),
dataset_names
);
// Process each dataset subdirectory
let mut datasets = Vec::new();
for dataset_name in dataset_names {
// Parse dataset name which can be either:
// 1. Simple name (subdirectory of repo_path)
// 2. "Tag:Path" format where Path is absolute
let (tag, dataset_path) = if dataset_name.contains(':') {
let parts: Vec<&str> = dataset_name.splitn(2, ':').collect();
if parts.len() == 2 {
(parts[0].to_string(), PathBuf::from(parts[1]))
} else {
(dataset_name.clone(), repo_path.join(&dataset_name))
}
} else {
(dataset_name.clone(), repo_path.join(&dataset_name))
};
if !dataset_path.exists() {
eprintln!(
"⚠️ Dataset directory does not exist: {}",
dataset_path.display()
);
continue;
}
println!(
" 📊 Processing dataset '{}': {}",
tag,
dataset_path.display()
);
match process_dataset(tag.clone(), &dataset_path, &cli.branches) {
Ok(dataset) => datasets.push(dataset),
Err(e) => eprintln!(" ⚠️ Failed to process dataset '{tag}': {e}"),
}
}
if datasets.is_empty() {
return Err("No valid datasets could be processed".into());
}
// Process actual git repository
println!("🔍 Processing git repository structure...");
// Create a mapping from dataset tags to directory names for git processing
let dataset_mappings: Vec<(String, String)> = datasets
.iter()
.filter_map(|dataset| {
// Extract the directory name from the dataset's actual path
if let Some(dir_name) = dataset.path.file_name() {
if let Some(dir_str) = dir_name.to_str() {
return Some((dataset.name.clone(), dir_str.to_string()));
}
}
None
})
.collect();
let (git_branches, git_commits) =
process_git_repository(&repo_path, &dataset_mappings, &datasets, &cli.branches)?;
let repository_data = RepositoryData {
path: repo_path,
datasets,
git_branches,
_git_commits: git_commits,
};
// Generate HTML
println!("🎨 Generating HTML visualization...");
let html = generate_html(&repository_data)?;
// Write to file
fs::write(&cli.output, html)?;
println!("✅ HTML visualization saved to: {}", cli.output.display());
Ok(())
}
fn discover_datasets(repo_path: &Path) -> Result<Vec<String>, Box<dyn std::error::Error>> {
let mut datasets = Vec::new();
for entry in fs::read_dir(repo_path)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
// Check if this directory contains prolly data files
let has_prolly_config = path.join("prolly_config_tree_config").exists();
let has_hash_mappings = path.join("prolly_hash_mappings").exists();
if has_prolly_config || has_hash_mappings {
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
// Skip hidden directories and git directory
if !name.starts_with('.') {
datasets.push(name.to_string());
}
}
}
}
}
datasets.sort();
Ok(datasets)
}
type GitRepositoryResult =
Result<(Vec<GitBranchInfo>, HashMap<String, GitCommitInfo>), Box<dyn std::error::Error>>;
fn process_git_repository(
repo_path: &Path,
dataset_mappings: &[(String, String)],
datasets: &[DatasetInfo],
branch_filter: &[String],
) -> GitRepositoryResult {
use std::process::Command;
// Use the provided dataset mappings instead of discovering them
let _datasets: Vec<String> = dataset_mappings
.iter()
.map(|(_, dir)| dir.clone())
.collect();
// Get all branches
let branch_output = Command::new("git")
.args(["-C", &repo_path.to_string_lossy(), "branch", "-a"])
.output()?;
if !branch_output.status.success() {
return Err("Failed to list git branches".into());
}
let branch_list = String::from_utf8(branch_output.stdout)?;
let mut git_branches = Vec::new();
let mut all_commits = HashMap::new();
let mut current_branch = String::new();
// Parse branches
let all_branch_names: Vec<String> = branch_list
.lines()
.filter_map(|line| {
let trimmed = line.trim();
if trimmed.starts_with('*') {
current_branch = trimmed[2..].to_string();
Some(current_branch.clone())
} else if !trimmed.is_empty() && !trimmed.contains("remotes/") {
Some(trimmed.to_string())
} else {
None
}
})
.collect();
// Filter branches if specified
let branch_names: Vec<String> = if branch_filter.is_empty() {
all_branch_names
} else {
all_branch_names
.into_iter()
.filter(|branch| branch_filter.contains(branch))
.collect()
};
// Store original branch to restore later
let original_branch = current_branch.clone();
// First, get all commits from all branches to build a complete picture
let all_log_output = Command::new("git")
.args([
"-C",
&repo_path.to_string_lossy(),
"log",
"--all",
"--format=%H|%an|%s|%ct",
// Get ALL commits, no limit
])
.output()?;
if !all_log_output.status.success() {
return Err("Failed to get git log --all".into());
}
let all_log_text = String::from_utf8(all_log_output.stdout)?;
let all_commit_lines: Vec<&str> = all_log_text.lines().collect();
// Parse all commits into a map
for (i, line) in all_commit_lines.iter().enumerate() {
if let Some((id, rest)) = line.split_once('|') {
if let Some((author, rest)) = rest.split_once('|') {
if let Some((message, timestamp_str)) = rest.split_once('|') {
if let Ok(timestamp) = timestamp_str.parse::<i64>() {
// Extract data for ALL commits now that git-prolly show is faster
let should_extract_data = true; // Extract data for ALL commits
let dataset_changes = calculate_commit_changes(
repo_path,
id,
if i + 1 < all_commit_lines.len() {
Some(all_commit_lines[i + 1].split('|').next().unwrap_or(""))
} else {
None
},
dataset_mappings,
datasets,
should_extract_data,
)
.unwrap_or_default();
let commit = GitCommitInfo {
id: id.to_string(),
author: author.to_string(),
message: message.to_string(),
timestamp,
dataset_changes,
};
all_commits.insert(id.to_string(), commit);
}
}
}
}
}
// Now process each branch to get its specific commit ordering
for branch_name in branch_names {
println!("🔍 Processing branch: {branch_name}");
let is_current = branch_name == current_branch;
// Checkout the branch
Command::new("git")
.args(["-C", &repo_path.to_string_lossy(), "checkout", &branch_name])
.output()?;
// Get commits for this specific branch, showing most recent first
// This approach shows the commits in reverse chronological order for this branch
let branch_log_output = Command::new("git")
.args([
"-C",
&repo_path.to_string_lossy(),
"log",
&branch_name, // Specify the branch explicitly
"--format=%H",
// Show ALL commits for this branch, no limit
])
.output()?;
if !branch_log_output.status.success() {
continue; // Skip branches we can't read
}
let branch_log_text = String::from_utf8(branch_log_output.stdout)?;
let mut branch_commits = Vec::new();
// Build commits for this branch using the pre-parsed commit data
for line in branch_log_text.lines() {
let commit_id = line.trim();
if let Some(commit) = all_commits.get(commit_id) {
branch_commits.push(commit.clone());
println!(
" ✓ Branch {}: Added commit {}",
branch_name,
&commit_id[..8]
);
}
}
println!(
" 📊 Branch {} has {} commits",
branch_name,
branch_commits.len()
);
git_branches.push(GitBranchInfo {
name: branch_name,
commits: branch_commits,
current: is_current,
});
}
// Restore original branch
Command::new("git")
.args([
"-C",
&repo_path.to_string_lossy(),
"checkout",
&original_branch,
])
.output()?;
Ok((git_branches, all_commits))
}
fn calculate_commit_changes(
repo_path: &Path,
commit_id: &str,
parent_commit_id: Option<&str>,
dataset_mappings: &[(String, String)],
datasets: &[DatasetInfo],
should_extract_data: bool,
) -> Result<HashMap<String, Vec<KvDiff>>, Box<dyn std::error::Error>> {
use std::process::Command;
let mut dataset_changes = HashMap::new();
// Use git show to see what files changed in this commit
let show_output = if let Some(parent_id) = parent_commit_id {
Command::new("git")
.args([
"-C",
&repo_path.to_string_lossy(),
"diff",
"--name-only",
parent_id,
commit_id,
])
.output()?
} else {
Command::new("git")
.args([
"-C",
&repo_path.to_string_lossy(),
"show",
"--name-only",
"--format=",
commit_id,
])
.output()?
};
if !show_output.status.success() {
return Ok(HashMap::new());
}
let changed_files = String::from_utf8(show_output.stdout)?;
println!(
" 📋 Changed files in commit {}: {:?}",
&commit_id[..8],
changed_files.lines().collect::<Vec<_>>()
);
let affected_datasets: HashSet<String> = changed_files
.lines()
.filter_map(|file_path| {
// Check if this file belongs to a dataset using the mapping
for (tag, dir) in dataset_mappings {
if file_path.starts_with(&format!("{dir}/")) {
return Some(tag.clone());
}
}
None
})
.collect();
println!(" 📊 Affected datasets from git files: {affected_datasets:?}");
// Check ALL datasets for prolly data changes in this commit, not just the ones with file changes
for (dataset_tag, _dataset_dir) in dataset_mappings {
// Check if this dataset had git file changes (for informational purposes)
let _has_git_changes = affected_datasets.contains(dataset_tag);
// Always try to get prolly data changes for each dataset
if should_extract_data {
// Always try to extract prolly-tree data changes for every dataset
// Find the actual dataset path
if let Some(dataset_info) = datasets.iter().find(|d| &d.name == dataset_tag) {
// Always try to extract prolly-tree data changes for every dataset
if let Ok(changes) = get_actual_prolly_changes_with_path(
commit_id,
parent_commit_id,
dataset_tag,
&dataset_info.path,
) {
if !changes.is_empty() {
dataset_changes.insert(dataset_tag.clone(), changes);
}
}
}
}
}
Ok(dataset_changes)
}
fn get_prolly_changes_from_commit(
dataset_path: &Path,
commit_id: &str,
) -> Result<Vec<KvDiff>, Box<dyn std::error::Error>> {
use std::process::Command;
let git_prolly_path = std::env::current_exe()
.map(|p| p.parent().unwrap().join("git-prolly"))
.unwrap_or_else(|_| PathBuf::from("git-prolly"));
// First try the commit ID directly (in case it exists in this dataset)
let output = Command::new(&git_prolly_path)
.args(["show", commit_id])
.current_dir(dataset_path)
.output()?;
if output.status.success() {
let stdout_str = String::from_utf8(output.stdout)?;
// Parse the output from git-prolly show
return parse_prolly_show_output(&stdout_str);
}
// If the exact commit doesn't exist, try to find recent commits with changes
// This handles the case where the main repo commit doesn't exist in the dataset repo
let log_output = Command::new(&git_prolly_path)
.args(["log", "--limit", "20"])
.current_dir(dataset_path)
.output()?;
if log_output.status.success() {
let log_text = String::from_utf8(log_output.stdout)?;
// Parse log output to find commits with actual changes
for line in log_text.lines() {
if line.starts_with("Commit: ") {
if let Some(prolly_commit) = line
.strip_prefix("Commit: ")
.and_then(|s| s.split(' ').next())
{
// Try to get changes for this prolly commit
let show_output = Command::new(&git_prolly_path)
.args(["show", prolly_commit])
.current_dir(dataset_path)
.output()?;
if show_output.status.success() {
if let Ok(changes) =
parse_prolly_show_output(&String::from_utf8(show_output.stdout)?)
{
if !changes.is_empty() {
return Ok(changes);
}
}
}
}
}
}
}
Ok(Vec::new())
}
fn parse_prolly_show_output(show_output: &str) -> Result<Vec<KvDiff>, Box<dyn std::error::Error>> {
let mut diffs = Vec::new();
let mut in_changes_section = false;
for line in show_output.lines() {
let line = line.trim();
if line == "Key-Value Changes:" {
in_changes_section = true;
continue;
}
if !in_changes_section {
continue;
}
// Parse lines with ANSI color codes: "+ key = value", "- key = value", "M key: old -> new"
if line.contains("[32m+ ") && line.contains(" = ") {
// Added key (green) - extract between [32m+ and [0m
if let Some(start) = line.find("[32m+ ") {
if let Some(end) = line.find("[0m") {
let content = &line[start + 6..end]; // Skip "[32m+ "
if let Some(eq_pos) = content.find(" = ") {
let key = content[..eq_pos].to_string();
let mut value = content[eq_pos + 3..].to_string();
// Remove any trailing ANSI escape sequences
if let Some(esc_pos) = value.find('\u{1b}') {
value = value[..esc_pos].to_string();
}
// Clean up quotes properly
value = value.trim_matches('"').to_string();
diffs.push(KvDiff {
key: key.into_bytes(),
operation: DiffOperation::Added(value.into_bytes()),
});
}
}
}
} else if line.contains("[31m- ") && line.contains(" = ") {
// Removed key (red)
if let Some(start) = line.find("[31m- ") {
if let Some(end) = line.find("[0m") {
let content = &line[start + 6..end]; // Skip "[31m- "
if let Some(eq_pos) = content.find(" = ") {
let key = content[..eq_pos].to_string();
let mut value = content[eq_pos + 3..].to_string();
// Remove any trailing ANSI escape sequences
if let Some(esc_pos) = value.find('\u{1b}') {
value = value[..esc_pos].to_string();
}
// Clean up quotes properly
value = value.trim_matches('"').to_string();
diffs.push(KvDiff {
key: key.into_bytes(),
operation: DiffOperation::Removed(value.into_bytes()),
});
}
}
}
} else if line.contains("[33m~ ") && line.contains(" = ") && line.contains(" -> ") {
// Modified key (yellow) - format: [33m~ key = "old" -> "new"[0m
if let Some(start) = line.find("[33m~ ") {
if let Some(end) = line.find("[0m") {
let content = &line[start + 6..end]; // Skip "[33m~ "
if let Some(eq_pos) = content.find(" = ") {
let key = content[..eq_pos].to_string();
let change_part = &content[eq_pos + 3..]; // Skip " = "
if let Some(arrow_pos) = change_part.find(" -> ") {
let mut old_value = change_part[..arrow_pos].to_string();
let mut new_value = change_part[arrow_pos + 4..].to_string();
// Remove any trailing ANSI escape sequences
if let Some(esc_pos) = old_value.find('\u{1b}') {
old_value = old_value[..esc_pos].to_string();
}
if let Some(esc_pos) = new_value.find('\u{1b}') {
new_value = new_value[..esc_pos].to_string();
}
// Clean up quotes properly
old_value = old_value.trim_matches('"').to_string();
new_value = new_value.trim_matches('"').to_string();
diffs.push(KvDiff {
key: key.into_bytes(),
operation: DiffOperation::Modified {
old: old_value.into_bytes(),
new: new_value.into_bytes(),
},
});
}
}
}
}
}
}
Ok(diffs)
}
fn get_actual_prolly_changes_with_path(
commit_id: &str,
_parent_commit_id: Option<&str>,
_dataset_tag: &str,
dataset_path: &Path,
) -> Result<Vec<KvDiff>, Box<dyn std::error::Error>> {
// Use git-prolly show to get the actual changes for this commit
let diffs = get_prolly_changes_from_commit(dataset_path, commit_id)?;
Ok(diffs)
}
/// Get commit history for a specific branch without checking out
fn get_branch_commits(
store: &GitVersionedKvStore<32>,
branch_name: &str,
) -> Result<Vec<CommitInfo>, Box<dyn std::error::Error>> {
// Use git rev-list to get commits for this specific branch
let git_repo = store.git_repo();
let repo_path = git_repo
.path()
.parent()
.ok_or("Failed to get parent directory")?;
let output = std::process::Command::new("git")
.args([
"rev-list",
"--format=format:%H|%an|%cn|%s|%at",
&format!("refs/heads/{branch_name}"),
])
.current_dir(repo_path)
.output()?;
if !output.status.success() {
return Err(format!(
"Failed to get commits for branch {}: {}",
branch_name,
String::from_utf8_lossy(&output.stderr)
)
.into());
}
let stdout = String::from_utf8(output.stdout)?;
let mut commits = Vec::new();
for line in stdout.lines() {
if line.starts_with("commit ") {
continue; // Skip the "commit <hash>" lines
}
if line.trim().is_empty() {
continue;
}
let parts: Vec<&str> = line.split('|').collect();
if parts.len() >= 5 {
let commit_id = gix::ObjectId::from_hex(parts[0].as_bytes())?;
let author = parts[1].to_string();
let committer = parts[2].to_string();
let message = parts[3].to_string();
let timestamp = parts[4].parse::<i64>().unwrap_or(0);
commits.push(CommitInfo {
id: commit_id,
author,
committer,
message,
timestamp,
});
}
}
Ok(commits)
}
/// Get diff between two commits using read-only historical access
fn get_diff_between_commits(
store: &GitVersionedKvStore<32>,
from_commit: &str,
to_commit: &str,
) -> Result<Vec<KvDiff>, Box<dyn std::error::Error>> {
// Get key-value state at both commits using read-only access
let from_state = store.get_keys_at_ref(from_commit)?;
let to_state = store.get_keys_at_ref(to_commit)?;
let mut diffs = Vec::new();
// Find added and modified keys
for (key, to_value) in &to_state {
match from_state.get(key) {
Some(from_value) if from_value != to_value => {
// Modified
diffs.push(KvDiff {
key: key.clone(),
operation: DiffOperation::Modified {
old: from_value.clone(),
new: to_value.clone(),
},
});
}
None => {
// Added
diffs.push(KvDiff {
key: key.clone(),
operation: DiffOperation::Added(to_value.clone()),
});
}
_ => {} // Unchanged
}
}
// Find removed keys
for (key, from_value) in &from_state {
if !to_state.contains_key(key) {
diffs.push(KvDiff {
key: key.clone(),
operation: DiffOperation::Removed(from_value.clone()),
});
}
}
// Sort diffs by key for consistent output
diffs.sort_by(|a, b| a.key.cmp(&b.key));
Ok(diffs)
}
fn process_dataset(
name: String,
path: &Path,
branch_filter: &[String],
) -> Result<DatasetInfo, Box<dyn std::error::Error>> {
let store = GitVersionedKvStore::<32>::open(path)?;
// Get all branches
let all_branches = store.list_branches()?;
let current_branch = store.current_branch().to_string();
// Filter branches if specified
let branches = if branch_filter.is_empty() {
all_branches
} else {
all_branches
.into_iter()
.filter(|branch| branch_filter.contains(branch))
.collect()
};
let mut branch_infos = Vec::new();
let mut commit_details = HashMap::new();
let mut processed_commits = HashSet::new();
for branch_name in branches {
// Get commits for this branch without checking out
// We'll use git commands directly to get the commit history for each branch
let commits = get_branch_commits(&store, &branch_name)?;
// Process each commit
for (i, commit) in commits.iter().enumerate() {
let commit_id = commit.id.to_string();
if !processed_commits.contains(&commit_id) {
processed_commits.insert(commit_id.clone());
// Get changes for this commit using read-only historical access
let changes = if i < commits.len() - 1 {
let parent = &commits[i + 1].id.to_string();
get_diff_between_commits(&store, parent, &commit_id).unwrap_or_default()
} else {
// For initial commit, show all keys as added using historical access
let keys_at_commit = store.get_keys_at_ref(&commit_id).unwrap_or_default();
keys_at_commit
.into_iter()
.map(|(key, value)| KvDiff {
key,
operation: DiffOperation::Added(value),
})
.collect()
};
commit_details.insert(
commit_id.clone(),
CommitDiff {
info: commit.clone(),
changes,
},
);
}
}
branch_infos.push(BranchInfo {
name: branch_name.clone(),
commits,
current: branch_name == current_branch,
});
}
Ok(DatasetInfo {
name,
path: path.to_path_buf(),
branches: branch_infos,
commit_details,
})
}
fn generate_html(repository: &RepositoryData) -> Result<String, Box<dyn std::error::Error>> {
let html = format!(
r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Git-Prolly Visualization (beta)</title>
<style>
* {{
margin: 0;
padding: 0;
box-sizing: border-box;
}}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: #fafafa;
min-height: 100vh;
padding: 20px;
color: #1a1a1a;
}}
.container {{
max-width: 1400px;
margin: 0 auto;
}}
.header {{
background: #ffffff;
border-radius: 12px;
padding: 24px;
margin-bottom: 24px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
border: 1px solid #e5e5e5;
}}
.header h1 {{
color: #1a1a1a;
font-size: 28px;
font-weight: 600;
margin-bottom: 16px;
}}
.repo-and-datasets {{
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 16px;
flex-wrap: wrap;
}}
.repository-path {{
display: inline-block;
background: #f3f4f6;
color: #6b7280;
font-size: 12px;
padding: 4px 8px;
border-radius: 6px;
font-family: ui-monospace, 'SF Mono', 'Monaco', 'Cascadia Code', 'Courier New', monospace;
border: 1px solid #e5e7eb;
}}
.dataset-tags {{
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}}
.dataset-tag {{
background: #f9fafb;
color: #374151;
padding: 4px 10px;
border-radius: 6px;
font-size: 12px;
font-weight: 500;
border: 1px solid #d1d5db;
cursor: default;
}}
.controls {{
display: flex;
align-items: center;
gap: 16px;
}}
.branch-selector {{
display: flex;
align-items: center;
gap: 8px;
}}
.branch-selector label {{
color: #6b7280;
font-weight: 500;
font-size: 14px;
}}
.branch-selector select {{
padding: 8px 12px;
border-radius: 6px;
border: 1px solid #d1d5db;
background: white;
color: #1a1a1a;
font-size: 14px;
cursor: pointer;
transition: all 0.2s ease;
min-width: 120px;
}}
.branch-selector select:hover {{
border-color: #3b82f6;
}}
.branch-selector select:focus {{
outline: none;
border-color: #3b82f6;
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}}