liboxen 0.46.10

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
//! # oxen restore
//!
//! Restore a file to a previous version
//!

use crate::core;
use crate::core::versions::MinOxenVersion;
use crate::error::OxenError;
use crate::model::LocalRepository;
use crate::opts::RestoreOpts;

/// # Restore a removed file that was committed
///
/// ```ignore
/// use liboxen::repositories;
/// use liboxen::opts::RestoreOpts;
/// use liboxen::util;
///
/// // Initialize the repository
/// let base_dir = Path::new("repo_dir_commit");
/// let repo = repositories::init(base_dir)?;
///
/// // Write file to disk
/// let hello_name = "hello.txt";
/// let hello_path = base_dir.join(hello_name);
/// util::fs::write_to_path(&hello_path, "Hello World");
///
/// // Stage the file
/// repositories::add(&repo, &hello_path).await?;
///
/// // Commit staged
/// let commit = repositories::commit(&repo, "My commit message")?;
///
/// // Remove the file from disk
/// util::fs::remove_file(hello_path)?;
///
/// // Restore the file
/// repositories::restore::restore(&repo, RestoreOpts::from_path_ref(hello_name, commit.id)).await?;
/// ```
pub async fn restore(repo: &LocalRepository, opts: RestoreOpts) -> Result<(), OxenError> {
    match repo.min_version() {
        MinOxenVersion::V0_10_0 => panic!("v0.10.0 no longer supported"),
        _ => core::v_latest::restore::restore(repo, opts).await,
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashSet;
    use std::path::Path;
    use std::path::PathBuf;

    use crate::core::df::tabular;
    use crate::error::OxenError;
    use crate::opts::DFOpts;
    use crate::opts::RestoreOpts;
    use crate::opts::RmOpts;
    use crate::repositories;
    use crate::test;
    use crate::test::append_line_txt_file;
    use crate::util;

    #[tokio::test]
    async fn test_command_restore_removed_file_from_head() -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            // Write to file
            let hello_filename = "hello.txt";
            let hello_file = repo.path.join(hello_filename);
            util::fs::write_to_path(&hello_file, "Hello World")?;

            // Track the file
            repositories::add(&repo, &hello_file).await?;
            // Commit the file
            repositories::commit(&repo, "My message")?;

            // Remove the file from disk
            util::fs::remove_file(&hello_file)?;

            // Check that it doesn't exist, then it does after we restore it
            assert!(!hello_file.exists());
            // Restore takes the filename not the full path to the test repo
            // ie: "hello.txt" instead of data/test/runs/repo_data/test/runs_fc1544ab-cd55-4344-aa13-5360dc91d0fe/hello.txt
            repositories::restore::restore(&repo, RestoreOpts::from_path(hello_filename)).await?;
            assert!(hello_file.exists());

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_command_restore_file_from_commit_id() -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            // Write to file
            let hello_filename = "hello.txt";
            let hello_file = repo.path.join(hello_filename);
            util::fs::write_to_path(&hello_file, "Hello World")?;

            // Track the file
            repositories::add(&repo, &hello_file).await?;
            // Commit the file
            repositories::commit(&repo, "My message")?;

            // Modify the file once
            let first_modification = "Hola Mundo";
            let hello_file = test::modify_txt_file(hello_file, first_modification)?;
            repositories::add(&repo, &hello_file).await?;
            let first_mod_commit = repositories::commit(&repo, "Changing to spanish")?;

            // Modify again
            let second_modification = "Bonjour le monde";
            let hello_file = test::modify_txt_file(hello_file, second_modification)?;
            repositories::add(&repo, &hello_file).await?;
            repositories::commit(&repo, "Changing to french")?;

            // Restore from the first commit
            repositories::restore::restore(
                &repo,
                RestoreOpts::from_path_ref(hello_filename, first_mod_commit.id),
            )
            .await?;
            let content = util::fs::read_from_path(&hello_file)?;
            assert!(hello_file.exists());
            assert_eq!(content, first_modification);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_command_restore_removed_file_from_branch_with_commits_between()
    -> Result<(), OxenError> {
        test::run_training_data_repo_test_no_commits_async(|repo| async move {
            // (file already created in helper)
            let file_to_remove = repo.path.join("labels.txt");

            // Commit the file
            repositories::add(&repo, &file_to_remove).await?;
            repositories::commit(&repo, "Adding labels file")?;

            let orig_branch = repositories::branches::current_branch(&repo)?.unwrap();

            let train_dir = repo.path.join("train");
            repositories::add(&repo, train_dir).await?;
            repositories::commit(&repo, "Adding train dir")?;

            // Branch
            repositories::branches::create_checkout(&repo, "remove-labels")?;

            // Delete the file
            util::fs::remove_file(&file_to_remove)?;

            // We should recognize it as missing now
            let status = repositories::status(&repo)?;
            assert_eq!(status.removed_files.len(), 1);

            // Commit removed file
            repositories::add(&repo, &file_to_remove).await?;
            repositories::commit(&repo, "Removing labels file")?;

            // Make sure file is not there
            assert!(!file_to_remove.exists());

            // Switch back to main branch
            repositories::checkout(&repo, orig_branch.name).await?;
            // Make sure we restore file
            assert!(file_to_remove.exists());

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_directory() -> Result<(), OxenError> {
        test::run_training_data_repo_test_fully_committed_async(|repo| async move {
            let history = repositories::commits::list(&repo)?;
            let last_commit = history.first().unwrap();

            let annotations_dir = Path::new("annotations");

            // Remove one file
            let bbox_file = annotations_dir.join("train").join("bounding_box.csv");
            let bbox_path = repo.path.join(bbox_file);

            let og_bbox_contents = util::fs::read_from_path(&bbox_path)?;

            util::fs::remove_file(&bbox_path)?;

            // Modify another file
            let readme_file = annotations_dir.join("README.md");
            let readme_path = repo.path.join(readme_file);
            let og_readme_contents = util::fs::read_from_path(&readme_path)?;

            let readme_path = test::append_line_txt_file(readme_path, "Adding s'more")?;

            // Restore the directory
            repositories::restore::restore(
                &repo,
                RestoreOpts::from_path_ref(annotations_dir, last_commit.id.clone()),
            )
            .await?;

            // Make sure the removed file is restored
            let restored_contents = util::fs::read_from_path(&bbox_path)?;
            assert_eq!(og_bbox_contents, restored_contents);

            // Make sure the modified file is restored
            let restored_contents = util::fs::read_from_path(readme_path)?;
            assert_eq!(og_readme_contents, restored_contents);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_removed_tabular_data() -> Result<(), OxenError> {
        test::run_training_data_repo_test_fully_committed_async(|repo| async move {
            let history = repositories::commits::list(&repo)?;
            let last_commit = history.first().unwrap();

            let bbox_file = Path::new("annotations")
                .join("train")
                .join("bounding_box.csv");
            let bbox_path = repo.path.join(&bbox_file);

            let og_contents = util::fs::read_from_path(&bbox_path)?;
            util::fs::remove_file(&bbox_path)?;

            println!("restoring {bbox_file:?}");

            repositories::restore::restore(
                &repo,
                RestoreOpts::from_path_ref(bbox_file, last_commit.id.clone()),
            )
            .await?;
            let restored_contents = util::fs::read_from_path(&bbox_path)?;
            assert_eq!(og_contents, restored_contents);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_modified_tabular_data() -> Result<(), OxenError> {
        test::run_training_data_repo_test_fully_committed_async(|repo| async move {
            let history = repositories::commits::list(&repo)?;
            let last_commit = history.first().unwrap();

            let bbox_file = Path::new("annotations")
                .join("train")
                .join("bounding_box.csv");
            let bbox_path = repo.path.join(&bbox_file);

            let og_contents = util::fs::read_from_path(&bbox_path)?;

            let mut opts = DFOpts::empty();
            opts.add_row = Some("{\"file\": \"train/dog_99.jpg\", \"label\": \"dog\", \"min_x\": 101.5, \"min_y\": 32.0, \"width\": 385, \"height\": 330}".to_string());
            let mut df = tabular::read_df(&bbox_path, opts).await?;
            tabular::write_df(&mut df, &bbox_path)?;

            repositories::restore::restore(
                &repo,
                RestoreOpts::from_path_ref(bbox_file, last_commit.id.clone()),
            ).await?;
            let restored_contents = util::fs::read_from_path(&bbox_path)?;
            assert_eq!(og_contents, restored_contents);

            let status = repositories::status(&repo)?;
            assert_eq!(status.modified_files.len(), 0);
            assert!(status.is_clean());

            Ok(())
        }).await
    }

    #[tokio::test]
    async fn test_restore_modified_text_data() -> Result<(), OxenError> {
        test::run_training_data_repo_test_fully_committed_async(|repo| async move {
            let history = repositories::commits::list(&repo)?;
            let last_commit = history.first().unwrap();

            let bbox_file = Path::new("annotations")
                .join("train")
                .join("annotations.txt");
            let bbox_path = repo.path.join(&bbox_file);

            let og_contents = util::fs::read_from_path(&bbox_path)?;
            let new_contents = format!("{og_contents}\nnew 0");
            util::fs::write_to_path(&bbox_path, new_contents)?;

            repositories::restore::restore(
                &repo,
                RestoreOpts::from_path_ref(bbox_file, last_commit.id.clone()),
            )
            .await?;
            let restored_contents = util::fs::read_from_path(&bbox_path)?;
            assert_eq!(og_contents, restored_contents);

            let status = repositories::status(&repo)?;
            assert_eq!(status.modified_files.len(), 0);
            assert!(status.is_clean());

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_staged_file() -> Result<(), OxenError> {
        test::run_training_data_repo_test_no_commits_async(|repo| async move {
            let bbox_file = Path::new("annotations")
                .join("train")
                .join("bounding_box.csv");
            let bbox_path = repo.path.join(&bbox_file);

            // Stage file
            repositories::add(&repo, bbox_path).await?;

            // Make sure is staged
            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_files.len(), 1);
            status.print();

            // Remove from staged
            repositories::restore::restore(&repo, RestoreOpts::from_staged_path(bbox_file)).await?;

            // Make sure is unstaged
            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_files.len(), 0);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_data_frame_with_duplicates() -> Result<(), OxenError> {
        // THIS ONE FAILS BECAUSE OF THE REPOSITOROIES::COMMIT, IT DOESN'T GET TO RESTORE
        test::run_training_data_repo_test_fully_committed_async(|repo| async move {
            let ann_file = Path::new("nlp")
                .join("classification")
                .join("annotations")
                .join("train.tsv");
            let ann_path = repo.path.join(&ann_file);
            let new_line = "new_data,123,456,789";
            append_line_txt_file(&ann_path, new_line)?;
            let orig_df = tabular::read_df(&ann_path, DFOpts::empty()).await?;
            let og_contents = util::fs::read_from_path(&ann_path)?;

            // Commit
            repositories::add(&repo, &ann_path).await?;
            let commit = repositories::commit(&repo, "adding data with duplicates")?;

            // Remove
            util::fs::remove_file(&ann_path)?;

            // Restore from commit
            repositories::restore::restore(&repo, RestoreOpts::from_path_ref(ann_file, commit.id))
                .await?;

            // Make sure is same size
            let restored_df = tabular::read_df(&ann_path, DFOpts::empty()).await?;
            assert_eq!(restored_df.height(), orig_df.height());
            assert_eq!(restored_df.width(), orig_df.width());

            let restored_contents = util::fs::read_from_path(&ann_path)?;
            assert_eq!(og_contents, restored_contents);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_bounding_box_data_frame() -> Result<(), OxenError> {
        test::run_training_data_repo_test_fully_committed_async(|repo| async move {
            let ann_file = Path::new("annotations")
                .join("train")
                .join("bounding_box.csv");
            let ann_path = repo.path.join(&ann_file);

            let new_line = "new_data,123,456,789";
            append_line_txt_file(&ann_path, new_line)?;

            let orig_df = tabular::read_df(&ann_path, DFOpts::empty()).await?;

            let og_contents = util::fs::read_from_path(&ann_path)?;

            // Commit
            repositories::add(&repo, &ann_path).await?;

            let commit = repositories::commit(&repo, "adding data with duplicates")?;

            // Remove
            util::fs::remove_file(&ann_path)?;

            // Restore from commit
            repositories::restore::restore(&repo, RestoreOpts::from_path_ref(ann_file, commit.id))
                .await?;

            // Make sure is same size
            let restored_df = tabular::read_df(&ann_path, DFOpts::empty()).await?;

            assert_eq!(restored_df.height(), orig_df.height());
            assert_eq!(restored_df.width(), orig_df.width());

            let restored_contents = util::fs::read_from_path(&ann_path)?;
            assert_eq!(og_contents, restored_contents);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_staged_directory() -> Result<(), OxenError> {
        test::run_training_data_repo_test_no_commits_async(|repo| async move {
            let relative_path = Path::new("annotations");
            let annotations_dir = repo.path.join(relative_path);

            // Stage file
            repositories::add(&repo, annotations_dir).await?;

            // Make sure is staged
            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_dirs.len(), 3);
            assert_eq!(status.staged_files.len(), 6);
            status.print();

            // Remove from staged
            repositories::restore::restore(&repo, RestoreOpts::from_staged_path(relative_path))
                .await?;

            // Make sure is unstaged
            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_dirs.len(), 0);
            assert_eq!(status.staged_files.len(), 0);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_wildcard_restore_nested_nlp_dir() -> Result<(), OxenError> {
        test::run_training_data_repo_test_no_commits_async(|repo| async move {
            let dir = Path::new("nlp");
            let repo_dir = repo.path.join(dir);
            repositories::add(&repo, repo_dir).await?;

            let status = repositories::status(&repo)?;
            status.print();

            // Should add all the sub dirs
            // nlp/
            //   classification/
            //     annotations/
            assert_eq!(
                status
                    .staged_dirs
                    .paths
                    .get(Path::new("nlp"))
                    .unwrap()
                    .len(),
                1
            );
            // Should add sub files
            // nlp/classification/annotations/train.tsv
            // nlp/classification/annotations/test.tsv
            assert_eq!(status.staged_files.len(), 2);

            repositories::commit(&repo, "Adding nlp dir")?;

            // Remove the nlp dir
            let dir = Path::new("nlp");
            let repo_nlp_dir = repo.path.join(dir);
            std::fs::remove_dir_all(repo_nlp_dir)?;

            let status = repositories::status(&repo)?;
            assert_eq!(status.removed_files.len(), 1);
            assert_eq!(status.staged_files.len(), 0);
            // Add the removed nlp dir with a wildcard
            repositories::add(&repo, "nlp/*").await?;

            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_dirs.len(), 1);
            assert_eq!(status.staged_files.len(), 2);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_wildcard_restore_deleted_and_present() -> Result<(), OxenError> {
        test::run_empty_data_repo_test_no_commits_async(|repo| async move {
            // create the images directory
            let images_dir = repo.path.join("images");
            util::fs::create_dir_all(&images_dir)?;

            // Add and commit the cats
            for i in 1..=3 {
                let test_file = test::test_img_file_with_name(&format!("cat_{i}.jpg"));
                let repo_filepath = images_dir.join(test_file.file_name().unwrap());
                util::fs::copy(&test_file, &repo_filepath)?;
            }

            repositories::add(&repo, &images_dir).await?;
            repositories::commit(&repo, "Adding initial cat images")?;

            // Add and commit the dogs
            for i in 1..=4 {
                let test_file = test::test_img_file_with_name(&format!("dog_{i}.jpg"));
                let repo_filepath = images_dir.join(test_file.file_name().unwrap());
                util::fs::copy(&test_file, &repo_filepath)?;
            }

            repositories::add(&repo, &images_dir).await?;
            repositories::commit(&repo, "Adding initial dog images")?;

            // Remove all the things
            let rm_opts = RmOpts {
                path: PathBuf::from("images/*"),
                recursive: false,
                staged: false,
            };

            repositories::rm(&repo, &rm_opts)?;

            // Should now have 7 staged for removal
            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_files.len(), 7);
            assert_eq!(status.removed_files.len(), 0);

            let mut paths = HashSet::new();
            paths.insert(PathBuf::from("images/*"));

            // Restore staged with wildcard
            let restore_opts = RestoreOpts {
                paths,
                staged: true,
                source_ref: None,
                is_remote: false,
            };

            repositories::restore::restore(&repo, restore_opts).await?;

            let status = repositories::status(&repo)?;

            // Should now have unstaged the 7 ommissions, moving them to removed_files
            assert_eq!(status.removed_files.len(), 7);
            assert_eq!(status.staged_files.len(), 0);

            let mut paths = HashSet::new();
            paths.insert(PathBuf::from("images/*"));

            let restore_opts = RestoreOpts {
                paths,
                staged: false,
                source_ref: None,
                is_remote: false,
            };
            repositories::restore::restore(&repo, restore_opts).await?;

            let status = repositories::status(&repo)?;

            // Should now have restored the 7 files to the working directory, no staged changes
            assert_eq!(status.removed_files.len(), 0);
            assert_eq!(status.staged_files.len(), 0);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_wildcard_prefix_staged() -> Result<(), OxenError> {
        test::run_training_data_repo_test_fully_committed_async(|repo| async move {
            // Repo has 7 images in train/
            let rm_opts = RmOpts {
                path: PathBuf::from("train/*"),
                recursive: false,
                staged: false,
            };
            repositories::rm(&repo, &rm_opts)?;

            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_files.len(), 7); // 3 cats, 4 dogs

            let mut paths = HashSet::new();
            paths.insert(PathBuf::from("train/dog_*.jpg"));

            // Restore just the dogs from the stage
            let restore_opts = RestoreOpts {
                paths,
                staged: true,
                source_ref: None,
                is_remote: false,
            };
            repositories::restore::restore(&repo, restore_opts).await?;

            let status = repositories::status(&repo)?;

            assert_eq!(status.staged_files.len(), 3); // 3 cats should still be staged
            assert_eq!(status.removed_files.len(), 4); // 4 dogs back in working dir

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_restore_staged_schemas_with_wildcard() -> Result<(), OxenError> {
        test::run_training_data_repo_test_fully_committed_async(|repo| async move {
            // Make a new dir in the repo - new_annotations
            let new_annotations_dir = repo.path.join("new_annotations");
            // Copy over bounding_box.csv and one_shot.csv to new_annotations
            let bbox_path = repo
                .path
                .join("annotations")
                .join("train")
                .join("bounding_box.csv");
            let one_shot_path = repo
                .path
                .join("annotations")
                .join("train")
                .join("one_shot.csv");

            // Copy bbox and one_shot to new_annotations
            util::fs::create_dir_all(&new_annotations_dir)?;
            util::fs::copy(bbox_path, new_annotations_dir.join("bounding_box.csv"))?;
            util::fs::copy(one_shot_path, new_annotations_dir.join("one_shot.csv"))?;

            // Get file names for these copied files
            new_annotations_dir
                .join("bounding_box.csv")
                .file_name()
                .unwrap();
            new_annotations_dir
                .join("one_shot.csv")
                .file_name()
                .unwrap();

            // Add both files
            repositories::add(&repo, &new_annotations_dir).await?;

            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_files.len(), 2);
            assert_eq!(status.staged_schemas.len(), 2);

            // Restore *.csv
            let mut paths = HashSet::new();
            paths.insert(PathBuf::from("new_annotations").join(PathBuf::from("*.csv")));

            let restore_opts = RestoreOpts {
                paths,
                staged: true,
                source_ref: None,
                is_remote: false,
            };

            repositories::restore::restore(&repo, restore_opts).await?;

            let status = repositories::status(&repo)?;
            assert_eq!(status.staged_files.len(), 0);
            assert_eq!(status.staged_schemas.len(), 0);

            Ok(())
        })
        .await
    }
}