liboxen 0.46.11

Oxen is a fast, unstructured data version control, to help version large machine learning datasets written in Rust.
Documentation
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
use colored::{ColoredString, Colorize};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::path::{Path, PathBuf};

use crate::model::{
    StagedEntry, StagedEntryStatus, StagedSchema, SummarizedStagedDirStats,
    merge_conflict::EntryMergeConflict,
};

use crate::model::LocalRepository;

// TODO: Display if in Remote mode repo;

pub const MSG_CLEAN_REPO: &str = "nothing to commit, working tree clean\n";
pub const MSG_OXEN_ADD_FILE_EXAMPLE: &str =
    "  (use \"oxen add <file>...\" to update what will be committed)\n";
pub const MSG_OXEN_UNSYNCED_FILE_EXAMPLE: &str =
    "  (use \"oxen restore <file>...\" to download file contents)\n";
pub const MSG_OXEN_RM_FILE_EXAMPLE: &str =
    "  (use \"oxen add/rm <file>...\" to update what will be committed)\n";
pub const MSG_OXEN_ADD_DIR_EXAMPLE: &str =
    "  (use \"oxen add <dir>...\" to update what will be committed)\n";
pub const MSG_OXEN_UNSYNCED_DIR_EXAMPLE: &str =
    "  (use \"oxen restore <dir>...\" to download directories)\n";
pub const MSG_OXEN_RM_DIR_EXAMPLE: &str =
    "  (use \"oxen add/rm <dir>...\" to update what will be committed)\n";
pub const MSG_OXEN_ADD_FILE_RESOLVE_CONFLICT: &str =
    "  (use \"oxen add <file>...\" to mark resolution)\n";
pub const MSG_OXEN_RESTORE_FILE: &str =
    "  (use \"oxen restore <file>...\" to discard changes in working directory)";
pub const MSG_OXEN_RESTORE_STAGED_FILE: &str =
    "  (use \"oxen restore --staged <file> ...\" to unstage)\n";
pub const MSG_OXEN_SHOW_SCHEMA_STAGED: &str =
    "  (use \"oxen schemas --staged <PATH_OR_HASH>\" to view staged schema)\n";

#[derive(Debug, Clone)]
pub struct StagedDataOpts {
    pub paths: Vec<PathBuf>, // Paths to start the search at
    pub skip: usize,
    pub limit: usize,
    pub print_all: bool,
    pub is_remote: bool,
    pub ignore: Option<HashSet<PathBuf>>,
}

impl StagedDataOpts {
    pub fn from_paths(paths: &[PathBuf]) -> StagedDataOpts {
        StagedDataOpts {
            paths: paths.to_owned(),
            ..Default::default()
        }
    }

    pub fn from_paths_remote_mode(paths: &[PathBuf]) -> StagedDataOpts {
        StagedDataOpts {
            paths: paths.to_owned(),
            is_remote: true,
            ..Default::default()
        }
    }
}

impl Default for StagedDataOpts {
    fn default() -> StagedDataOpts {
        StagedDataOpts {
            paths: vec![PathBuf::from("")],
            skip: 0,
            limit: 10,
            print_all: false,
            is_remote: false,
            ignore: None,
        }
    }
}

impl fmt::Display for StagedData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let opts = StagedDataOpts::default();
        let outputs = self.__collect_outputs(&opts);

        for output in outputs {
            write!(f, "{output}")?;
        }

        Ok(())
    }
}

#[derive(Debug, Clone)]
pub struct StagedData {
    pub staged_dirs: SummarizedStagedDirStats,
    pub staged_files: HashMap<PathBuf, StagedEntry>, // All the staged entries will be in here
    pub staged_schemas: HashMap<PathBuf, StagedSchema>, // All the staged entrisumes will be in here
    pub untracked_dirs: Vec<(PathBuf, usize)>,
    pub untracked_files: Vec<PathBuf>,
    pub unsynced_dirs: Vec<(PathBuf, usize)>,
    pub unsynced_files: Vec<PathBuf>,
    pub modified_files: HashSet<PathBuf>,
    pub moved_files: Vec<(PathBuf, PathBuf, String)>,
    pub removed_files: HashSet<PathBuf>,
    pub merge_conflicts: Vec<EntryMergeConflict>,
}

impl StagedData {
    pub fn empty() -> StagedData {
        StagedData {
            staged_dirs: SummarizedStagedDirStats::new(),
            staged_files: HashMap::new(),
            staged_schemas: HashMap::new(),
            untracked_dirs: vec![],
            untracked_files: vec![],
            unsynced_dirs: vec![],
            unsynced_files: vec![],
            modified_files: HashSet::new(),
            removed_files: HashSet::new(),
            moved_files: vec![],
            merge_conflicts: vec![],
        }
    }

    // Unsynced dirs and files not included
    pub fn is_clean(&self) -> bool {
        self.staged_files.is_empty()
            && self.staged_dirs.is_empty()
            && self.staged_schemas.is_empty()
            && self.untracked_files.is_empty()
            && self.untracked_dirs.is_empty()
            && self.modified_files.is_empty()
            && self.removed_files.is_empty()
            && self.merge_conflicts.is_empty()
            && self.moved_files.is_empty()
    }

    pub fn has_added_entries(&self) -> bool {
        !self.staged_dirs.is_empty() || !self.staged_files.is_empty()
    }

    pub fn has_unsynced_entries(&self) -> bool {
        !self.unsynced_dirs.is_empty() || !self.unsynced_files.is_empty()
    }

    pub fn has_modified_entries(&self) -> bool {
        !self.modified_files.is_empty()
    }

    pub fn has_removed_entries(&self) -> bool {
        !self.removed_files.is_empty()
    }

    pub fn has_untracked_entries(&self) -> bool {
        !self.untracked_dirs.is_empty() || !self.untracked_files.is_empty()
    }

    pub fn has_merge_conflicts(&self) -> bool {
        !self.merge_conflicts.is_empty()
    }

    pub fn has_moved_entries(&self) -> bool {
        !self.moved_files.is_empty()
    }

    /// Line by line output that we want to print
    ///
    /// # Arguments
    ///
    /// * `skip` - File index to skip printing for
    /// * `limit` - Max number of files to show
    /// * `print_all` - If true, ignores skip and limit and prints everything
    ///
    fn __collect_outputs(&self, opts: &StagedDataOpts) -> Vec<ColoredString> {
        let mut outputs: Vec<ColoredString> = vec![];

        if self.is_clean() {
            // If in remote-mode repo, check for unsynced files
            if let Ok(repo) = LocalRepository::from_current_dir()
                && repo.is_remote_mode()
            {
                self.__collect_unsynced_dirs(&mut outputs, opts);
                self.__collect_unsynced_files(&mut outputs, opts);
            }
            outputs.push(MSG_CLEAN_REPO.to_string().normal());
            return outputs;
        }

        self.staged_dirs(&mut outputs, opts);
        self.staged_files(&mut outputs, opts);
        self.staged_schemas(&mut outputs, opts);
        self.__collect_modified_files(&mut outputs, opts);
        self.__collect_merge_conflicts(&mut outputs, opts);
        self.__collect_unsynced_dirs(&mut outputs, opts);
        self.__collect_unsynced_files(&mut outputs, opts);
        self.__collect_untracked_dirs(&mut outputs, opts);
        self.__collect_untracked_files(&mut outputs, opts);
        self.__collect_removed_files(&mut outputs, opts);

        outputs
    }

    pub fn print(&self) {
        let opts = StagedDataOpts::default();
        let outputs = self.__collect_outputs(&opts);

        for output in outputs {
            print!("{output}")
        }
    }

    pub fn print_with_params(&self, opts: &StagedDataOpts) {
        let outputs = self.__collect_outputs(opts);
        for output in outputs {
            print!("{output}");
        }
    }

    pub fn __collect_merge_conflicts(
        &self,
        outputs: &mut Vec<ColoredString>,
        opts: &StagedDataOpts,
    ) {
        if self.merge_conflicts.is_empty() {
            return;
        }

        outputs.push("Merge conflicts:".to_string().normal());
        outputs.push(format!("  {MSG_OXEN_ADD_FILE_RESOLVE_CONFLICT}").normal());

        self.__collapse_outputs(
            &self.merge_conflicts,
            |conflict| {
                let path = &conflict.base_entry.path;

                // println!(
                //     "    LCA {} {:?}",
                //     conflict.lca_entry.commit_id,
                //     conflict.lca_entry.version_file()
                // );
                // println!(
                //     "    HEAD {} {:?}",
                //     conflict.base_entry.commit_id,
                //     conflict.base_entry.version_file()
                // );
                // println!(
                //     "    MERGE {} {:?}",
                //     conflict.merge_entry.commit_id,
                //     conflict.merge_entry.version_file()
                // );

                vec![
                    "  both modified: ".to_string().yellow(),
                    format!("{}\n", path.to_str().unwrap()).yellow().bold(),
                ]
            },
            outputs,
            opts,
        );
        outputs.push("\n".normal());
    }

    pub fn unstaged_files(&self) -> Vec<PathBuf> {
        let mut files: Vec<PathBuf> = Vec::new();
        // files.extend(self.untracked_files.clone());
        files.extend(self.modified_files.clone());
        files.extend(
            self.moved_files
                .iter()
                .map(|(path, _removed_path, _hash)| path.clone()),
        );
        // files.extend(self.removed_files.clone());

        // This is a placeholder for the unstaged files logic
        files
    }

    pub fn files_to_stage(&self) -> Vec<PathBuf> {
        let mut files: Vec<PathBuf> = Vec::new();

        files.extend(self.untracked_dirs.iter().map(|(path, _)| path.clone()));
        files.extend(self.untracked_files.clone());
        files.extend(self.modified_files.clone());
        files.extend(
            self.moved_files
                .iter()
                .map(|(path, _removed_path, _hash)| path.clone()),
        );
        files.extend(self.removed_files.clone());

        files
    }

    fn staged_dirs(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        let mut dirs: Vec<Vec<ColoredString>> = vec![];
        for (path, staged_dirs) in self.staged_dirs.paths.iter() {
            let mut dir_row: Vec<ColoredString> = vec![];
            for staged_dir in staged_dirs.iter() {
                if *path == Path::new("") {
                    continue;
                }

                match staged_dir.status {
                    StagedEntryStatus::Added => {
                        dir_row.push("  added: ".green());
                    }
                    StagedEntryStatus::Modified => {
                        dir_row.push("  modified: ".green());
                    }
                    StagedEntryStatus::Removed => {
                        dir_row.push("  removed: ".green());
                    }
                    StagedEntryStatus::Unmodified => {
                        // dir_row.push("  unmodified: ".green());
                    }
                }

                dir_row.push(staged_dir.path.to_str().unwrap().to_string().green().bold());

                let num_files_str = match staged_dir.num_files_staged {
                    1 => Some(format!(" with {} file\n", staged_dir.num_files_staged).normal()),
                    0 => {
                        // limit since we don't have any staged files in this dir
                        log::warn!("Added dir with no files staged: {path:?}");
                        None
                    }
                    _ => Some(format!(" with {} files\n", staged_dir.num_files_staged).normal()),
                };
                if let Some(num_files_str) = num_files_str {
                    dir_row.push(num_files_str);
                } else {
                    dir_row.push("\n".normal());
                }

                if !dir_row.is_empty() {
                    dirs.push(dir_row.clone());
                    dir_row.clear();
                }
            }
        }

        if dirs.is_empty() {
            return;
        }

        outputs.push("Directories to be committed\n".normal());
        self.__collapse_outputs(&dirs, |dir| dir.to_vec(), outputs, opts);
        outputs.push("\n".normal());
    }

    fn staged_files(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        if self.staged_files.is_empty() {
            return;
        }
        outputs.push("Files to be committed:\n".normal());
        if (!self.staged_files.is_empty() || !self.staged_dirs.is_empty()) && !opts.is_remote {
            outputs.push(MSG_OXEN_RESTORE_STAGED_FILE.normal())
        }

        let files = &self.staged_files;
        // // For each added, look for a removed with the same hash. If there is a match, delete both entries and replace them with a moved entry
        let mut files_vec: Vec<(&PathBuf, &StagedEntry)> = files.iter().collect();

        // For display purposes, filter out the entries that are already displayed in moved_files
        let moved_paths: HashSet<&PathBuf> = self
            .moved_files
            .iter()
            .flat_map(|(path, removed_path, _hash)| vec![path, removed_path])
            .collect();

        files_vec.retain(|(p, _)| !moved_paths.contains(p));

        files_vec.sort_by(|(a, _), (b, _)| a.partial_cmp(b).unwrap());
        self.__collapse_outputs(
            &files_vec,
            |(path, entry)| match entry.status {
                StagedEntryStatus::Removed => {
                    vec![
                        "  removed: ".green(),
                        format!("{}\n", path.to_str().unwrap()).green().bold(),
                    ]
                }
                StagedEntryStatus::Modified => {
                    vec![
                        "  modified: ".green(),
                        format!("{}\n", path.to_str().unwrap()).green().bold(),
                    ]
                }
                StagedEntryStatus::Added => {
                    vec![
                        "  new file: ".green(),
                        format!("{}\n", path.to_str().unwrap()).green().bold(),
                    ]
                }
                StagedEntryStatus::Unmodified => {
                    vec![]
                }
            },
            outputs,
            opts,
        );

        let mut moved_entries = self.moved_files.clone();
        moved_entries.sort_by(|(_, old_a, _), (_, old_b, _)| old_a.partial_cmp(old_b).unwrap());

        self.__collapse_outputs(
            &self.moved_files,
            |(path, removed_path, _hash)| {
                vec![
                    "  moved: ".green(),
                    format!(
                        "{} -> {}\n",
                        removed_path.to_str().unwrap(),
                        path.to_str().unwrap()
                    )
                    .green()
                    .bold(),
                ]
            },
            outputs,
            opts,
        );

        // TODO: Can this be more generic?
        let total = self.staged_dirs.num_files_staged;
        if opts.is_remote && total > opts.limit {
            let remaining = total - opts.limit;
            outputs.push(format!("  ... and {remaining} others\n").normal());
        }
        outputs.push("\n".normal());
    }

    fn staged_schemas(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        if self.staged_schemas.is_empty() {
            return;
        }
        outputs.push("Schemas to be committed\n".normal());
        outputs.push(MSG_OXEN_SHOW_SCHEMA_STAGED.normal());

        let mut files_vec: Vec<(&PathBuf, &StagedSchema)> = self.staged_schemas.iter().collect();
        files_vec.sort_by(|(a, _), (b, _)| a.partial_cmp(b).unwrap());
        self.__collapse_outputs(
            &files_vec,
            |(path, staged_schema)| {
                let schema_ref = &staged_schema.schema.hash;

                match staged_schema.status {
                    StagedEntryStatus::Removed => {
                        vec![
                            "  removed schema: ".green(),
                            format!("{} {}\n", path.to_str().unwrap(), schema_ref)
                                .green()
                                .bold(),
                        ]
                    }
                    StagedEntryStatus::Modified => {
                        vec![
                            "  modified schema: ".green(),
                            format!("{} {}\n", path.to_str().unwrap(), schema_ref)
                                .green()
                                .bold(),
                        ]
                    }
                    StagedEntryStatus::Added => {
                        vec![
                            "  new schema: ".green(),
                            format!("{} {}\n", path.to_str().unwrap(), schema_ref)
                                .green()
                                .bold(),
                        ]
                    }
                    StagedEntryStatus::Unmodified => {
                        vec![]
                    }
                }
            },
            outputs,
            opts,
        );
        outputs.push("\n".normal());
    }

    fn __collect_modified_files(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        if self.modified_files.is_empty() {
            // nothing to print
            return;
        }

        outputs.push("Modified files:".to_string().normal());

        if opts.is_remote {
            outputs.push("\n".to_string().normal());
        } else {
            outputs.push(format!("  {MSG_OXEN_ADD_FILE_EXAMPLE}").normal());
        }

        let mut files: Vec<PathBuf> = self.modified_files.iter().cloned().collect();
        files.sort();

        self.__collapse_outputs(
            &files,
            |file| {
                vec![
                    "  modified: ".to_string().yellow(),
                    format!("{}\n", file.to_str().unwrap()).yellow().bold(),
                ]
            },
            outputs,
            opts,
        );
        outputs.push("\n".normal());
    }

    fn __collect_removed_files(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        if self.removed_files.is_empty() {
            // nothing to print
            return;
        }

        outputs.push("Removed Files\n".to_string().normal());
        outputs.push(MSG_OXEN_RM_FILE_EXAMPLE.to_string().normal());

        let mut files: Vec<PathBuf> = self.removed_files.iter().cloned().collect();
        files.sort();

        self.__collapse_outputs(
            &files,
            |file| {
                vec![
                    "  removed: ".to_string().red(),
                    format!("{}\n", file.to_str().unwrap()).red().bold(),
                ]
            },
            outputs,
            opts,
        );
        outputs.push("\n".normal());
    }

    fn __collect_unsynced_dirs(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        // List untracked files
        if !self.unsynced_dirs.is_empty() {
            outputs.push("Unsynced Directories\n".normal());
            outputs.push(MSG_OXEN_UNSYNCED_DIR_EXAMPLE.normal());

            let mut dirs = self.unsynced_dirs.clone();
            dirs.sort_by(|(a, _), (b, _)| a.partial_cmp(b).unwrap());

            let max_dir_len = dirs
                .iter()
                .map(|(path, _size)| path.to_str().unwrap().len())
                .max()
                .unwrap();

            self.__collapse_outputs(
                &dirs,
                |(path, size)| {
                    let path_str = path.to_str().unwrap();
                    let num_spaces = max_dir_len - path_str.len();
                    vec![
                        format!("  {} {}", path_str, StagedData::spaces(num_spaces))
                            .white()
                            .bold(),
                        format!("({} {})\n", size, StagedData::item_str_plural(*size)).normal(),
                    ]
                },
                outputs,
                opts,
            );
            outputs.push("\n".normal());
        }
    }

    fn __collect_unsynced_files(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        // List untracked files
        if !self.unsynced_files.is_empty() {
            outputs.push("Unsynced Files\n".normal());
            outputs.push(MSG_OXEN_UNSYNCED_FILE_EXAMPLE.normal());

            let mut files = self.unsynced_files.clone();
            files.sort();

            self.__collapse_outputs(
                &files,
                |f| vec![format!("  {}\n", f.to_str().unwrap()).white().bold()],
                outputs,
                opts,
            );
            outputs.push("\n".normal());
        }
    }

    fn __collect_untracked_dirs(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        // List untracked files
        if !self.untracked_dirs.is_empty() {
            outputs.push("Untracked Directories\n".normal());
            outputs.push(MSG_OXEN_ADD_DIR_EXAMPLE.normal());

            let mut dirs = self.untracked_dirs.clone();
            dirs.sort_by(|(a, _), (b, _)| a.partial_cmp(b).unwrap());

            let max_dir_len = dirs
                .iter()
                .map(|(path, _size)| path.to_str().unwrap().len())
                .max()
                .unwrap();

            self.__collapse_outputs(
                &dirs,
                |(path, size)| {
                    let path_str = path.to_str().unwrap();
                    let num_spaces = max_dir_len - path_str.len();
                    vec![
                        format!("  {} {}", path_str, StagedData::spaces(num_spaces))
                            .red()
                            .bold(),
                        format!("({} {})\n", size, StagedData::item_str_plural(*size)).normal(),
                    ]
                },
                outputs,
                opts,
            );
            outputs.push("\n".normal());
        }
    }

    fn __collect_untracked_files(&self, outputs: &mut Vec<ColoredString>, opts: &StagedDataOpts) {
        // List untracked files
        if !self.untracked_files.is_empty() {
            outputs.push("Untracked Files\n".normal());
            outputs.push(MSG_OXEN_ADD_FILE_EXAMPLE.normal());

            let mut files = self.untracked_files.clone();
            files.sort();

            self.__collapse_outputs(
                &files,
                |f| vec![format!("  {}\n", f.to_str().unwrap()).red().bold()],
                outputs,
                opts,
            );
            outputs.push("\n".normal());
        }
    }

    fn __collapse_outputs<T, F>(
        &self,
        inputs: &[T],
        to_components: F,
        outputs: &mut Vec<ColoredString>,
        opts: &StagedDataOpts,
    ) where
        F: Fn(&T) -> Vec<ColoredString>,
    {
        log::debug!(
            "__collapse_outputs inputs.len(): {} opts: {:?}",
            inputs.len(),
            opts
        );
        if inputs.is_empty() {
            return;
        }

        let total = opts.skip + opts.limit;
        for (i, input) in inputs.iter().enumerate() {
            if i < opts.skip && !opts.print_all {
                continue;
            }
            if i >= total && !opts.print_all {
                break;
            }
            let mut components = to_components(input);
            outputs.append(&mut components);
        }

        if inputs.len() > opts.limit && !opts.print_all {
            let remaining = inputs.len() - opts.limit;
            outputs.push(format!("  ... and {remaining} others\n").normal());
        }
    }

    pub fn item_str_plural(n: usize) -> String {
        if n == 1 {
            String::from("item")
        } else {
            String::from("items")
        }
    }

    pub fn spaces(n: usize) -> String {
        let mut ret = String::from("");
        for _ in 0..n {
            ret.push(' ');
        }
        ret
    }
}

#[cfg(test)]
mod tests {

    use colored::Colorize;
    use std::path::PathBuf;

    use crate::model::StagedEntryStatus;
    use crate::model::staged_data::{
        MSG_CLEAN_REPO, MSG_OXEN_ADD_DIR_EXAMPLE, MSG_OXEN_ADD_FILE_EXAMPLE,
        MSG_OXEN_RESTORE_STAGED_FILE, MSG_OXEN_RM_FILE_EXAMPLE, StagedDataOpts,
    };
    use crate::model::{StagedData, StagedEntry};

    #[test]
    fn test_staged_data_collect_clean_repo() {
        let staged_data = StagedData::empty();
        let opts = StagedDataOpts::default();
        let outputs = staged_data.__collect_outputs(&opts);
        assert_eq!(outputs.len(), 1);
        assert_eq!(outputs[0].to_string(), MSG_CLEAN_REPO);
    }

    #[test]
    fn staged_files() {
        let mut staged_data = StagedData::empty();
        staged_data.staged_files.insert(
            PathBuf::from("file_1.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );
        staged_data.staged_files.insert(
            PathBuf::from("file_2.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );
        staged_data.staged_files.insert(
            PathBuf::from("file_3.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );
        staged_data.staged_files.insert(
            PathBuf::from("file_4.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );
        staged_data.staged_files.insert(
            PathBuf::from("file_5.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );

        let opts = StagedDataOpts {
            limit: 3,
            ..StagedDataOpts::default()
        };
        let outputs = staged_data.__collect_outputs(&opts);
        assert_eq!(outputs[0], "Files to be committed:\n".normal());
        assert_eq!(outputs[1], MSG_OXEN_RESTORE_STAGED_FILE.normal());
        assert_eq!(outputs[2], "  new file: ".green());
        assert_eq!(outputs[3], "file_1.jpg\n".green().bold());
        assert_eq!(outputs[4], "  new file: ".green());
        assert_eq!(outputs[5], "file_2.jpg\n".green().bold());
        assert_eq!(outputs[6], "  new file: ".green());
        assert_eq!(outputs[7], "file_3.jpg\n".green().bold());
        assert_eq!(outputs[8], "  ... and 2 others\n".normal());
    }

    #[test]
    fn staged_files_length() {
        let mut staged_data = StagedData::empty();
        staged_data.staged_files.insert(
            PathBuf::from("file_1.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );
        staged_data.staged_files.insert(
            PathBuf::from("file_2.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );
        staged_data.staged_files.insert(
            PathBuf::from("file_3.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );
        staged_data.staged_files.insert(
            PathBuf::from("file_4.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );
        staged_data.staged_files.insert(
            PathBuf::from("file_5.jpg"),
            StagedEntry::empty_status(StagedEntryStatus::Added),
        );

        let opts = StagedDataOpts {
            limit: 3,
            skip: 2,
            ..StagedDataOpts::default()
        };
        let outputs = staged_data.__collect_outputs(&opts);
        assert_eq!(outputs[0], "Files to be committed:\n".normal());
        assert_eq!(outputs[1], MSG_OXEN_RESTORE_STAGED_FILE.normal());
        assert_eq!(outputs[2], "  new file: ".green());
        assert_eq!(outputs[3], "file_3.jpg\n".green().bold());
        assert_eq!(outputs[4], "  new file: ".green());
        assert_eq!(outputs[5], "file_4.jpg\n".green().bold());
        assert_eq!(outputs[6], "  new file: ".green());
        assert_eq!(outputs[7], "file_5.jpg\n".green().bold());
        assert_eq!(outputs[8], "  ... and 2 others\n".normal());
    }

    #[test]
    fn test_staged_data_collect_untracked_files() {
        let mut staged_data = StagedData::empty();
        staged_data
            .untracked_files
            .push(PathBuf::from("file_1.jpg"));
        staged_data
            .untracked_files
            .push(PathBuf::from("file_2.jpg"));
        staged_data
            .untracked_files
            .push(PathBuf::from("file_3.jpg"));
        staged_data
            .untracked_files
            .push(PathBuf::from("file_4.jpg"));
        staged_data
            .untracked_files
            .push(PathBuf::from("file_5.jpg"));

        let opts = StagedDataOpts {
            limit: 3,
            ..StagedDataOpts::default()
        };
        let outputs = staged_data.__collect_outputs(&opts);
        assert_eq!(outputs[0], "Untracked Files\n".normal());
        assert_eq!(outputs[1], MSG_OXEN_ADD_FILE_EXAMPLE.normal());
        assert_eq!(outputs[2], "  file_1.jpg\n".red().bold());
        assert_eq!(outputs[3], "  file_2.jpg\n".red().bold());
        assert_eq!(outputs[4], "  file_3.jpg\n".red().bold());
        assert_eq!(outputs[5], "  ... and 2 others\n".normal());
    }

    #[test]
    fn test_staged_data_collect_untracked_files_print_all() {
        let mut staged_data = StagedData::empty();
        staged_data
            .untracked_files
            .push(PathBuf::from("file_1.jpg"));
        staged_data
            .untracked_files
            .push(PathBuf::from("file_2.jpg"));
        staged_data
            .untracked_files
            .push(PathBuf::from("file_3.jpg"));
        staged_data
            .untracked_files
            .push(PathBuf::from("file_4.jpg"));
        staged_data
            .untracked_files
            .push(PathBuf::from("file_5.jpg"));

        let opts = StagedDataOpts {
            print_all: true,
            ..StagedDataOpts::default()
        };
        let outputs = staged_data.__collect_outputs(&opts);
        assert_eq!(outputs[0], "Untracked Files\n".normal());
        assert_eq!(outputs[1], MSG_OXEN_ADD_FILE_EXAMPLE.normal());
        assert_eq!(outputs[2], "  file_1.jpg\n".red().bold());
        assert_eq!(outputs[3], "  file_2.jpg\n".red().bold());
        assert_eq!(outputs[4], "  file_3.jpg\n".red().bold());
        assert_eq!(outputs[5], "  file_4.jpg\n".red().bold());
        assert_eq!(outputs[6], "  file_5.jpg\n".red().bold());
    }

    #[test]
    fn test_staged_data_collect_untracked_dirs() {
        let mut staged_data = StagedData::empty();
        staged_data
            .untracked_dirs
            .push((PathBuf::from("train"), 10));
        staged_data.untracked_dirs.push((PathBuf::from("test"), 4));
        staged_data
            .untracked_dirs
            .push((PathBuf::from("annotations"), 1));

        let opts = StagedDataOpts {
            limit: 3,
            ..StagedDataOpts::default()
        };
        let outputs = staged_data.__collect_outputs(&opts);
        assert_eq!(outputs[0], "Untracked Directories\n".normal());
        assert_eq!(outputs[1], MSG_OXEN_ADD_DIR_EXAMPLE.normal());
        assert_eq!(outputs[2], "  annotations ".red().bold());
        assert_eq!(outputs[3], "(1 item)\n".normal());
        assert_eq!(outputs[4], "  test        ".red().bold());
        assert_eq!(outputs[5], "(4 items)\n".normal());
        assert_eq!(outputs[6], "  train       ".red().bold());
        assert_eq!(outputs[7], "(10 items)\n".normal());
    }

    #[test]
    fn test_staged_data_remove_file() {
        let mut staged_data = StagedData::empty();
        staged_data.removed_files.insert(PathBuf::from("README.md"));

        let opts = StagedDataOpts::default();
        let outputs = staged_data.__collect_outputs(&opts);
        assert_eq!(outputs[0], "Removed Files\n".normal());
        assert_eq!(outputs[1], MSG_OXEN_RM_FILE_EXAMPLE.normal());
        assert_eq!(outputs[2], "  removed: ".red());
        assert_eq!(outputs[3], "README.md\n".red().bold());
    }
}