liboxen 0.46.12

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
//! # Branches
//!
//! Interact with Oxen branches.
//!

use std::path::{Path, PathBuf};

use crate::core::refs::with_ref_manager;
use crate::core::versions::MinOxenVersion;
use crate::error::OxenError;
use crate::model::{Branch, Commit, CommitEntry, LocalRepository};
use crate::repositories;
use crate::{core, util};

/// List all the local branches within a repo
pub fn list(repo: &LocalRepository) -> Result<Vec<Branch>, OxenError> {
    with_ref_manager(repo, |manager| manager.list_branches())
}

/// List all the local branches within a repo along with their head commits
pub fn list_with_commits(repo: &LocalRepository) -> Result<Vec<(Branch, Commit)>, OxenError> {
    with_ref_manager(repo, |manager| manager.list_branches_with_commits())
}

/// Get a branch by name, returning an error if it doesn't exist
pub fn get_by_name(repo: &LocalRepository, name: &str) -> Result<Branch, OxenError> {
    with_ref_manager(repo, |manager| manager.get_branch_by_name(name))?
        .ok_or_else(|| OxenError::local_branch_not_found(name))
}

/// Get branch by name or fall back the current
pub fn get_by_name_or_current(
    repo: &LocalRepository,
    branch_name: Option<impl AsRef<str>>,
) -> Result<Branch, OxenError> {
    if let Some(branch_name) = branch_name {
        let branch_name = branch_name.as_ref();
        repositories::branches::get_by_name(repo, branch_name)
    } else {
        match repositories::branches::current_branch(repo)? {
            Some(branch) => Ok(branch),
            None => {
                log::error!("get_by_name_or_current No current branch found");
                Err(OxenError::must_be_on_valid_branch())
            }
        }
    }
}

/// Get commit id from a branch by name
pub fn get_commit_id(repo: &LocalRepository, name: &str) -> Result<Option<String>, OxenError> {
    with_ref_manager(repo, |manager| manager.get_commit_id_for_branch(name))
}

/// Check if a branch exists.
/// Returns Ok(false) if the branch doesn't exist.
/// Returns Err() if there was some other problem accessing the local repository.
pub fn exists(repo: &LocalRepository, name: &str) -> Result<bool, OxenError> {
    match get_by_name(repo, name) {
        Ok(_) => Ok(true),
        Err(OxenError::BranchNotFound(_)) => Ok(false),
        Err(e) => Err(e),
    }
}

/// Get the current branch
pub fn current_branch(repo: &LocalRepository) -> Result<Option<Branch>, OxenError> {
    with_ref_manager(repo, |manager| manager.get_current_branch())
}

/// # Create a new branch from the head commit
/// This creates a new pointer to the current commit with a name,
/// it does not switch you to this branch, you still must call `checkout_branch`
pub fn create_from_head(
    repo: &LocalRepository,
    name: impl AsRef<str>,
) -> Result<Branch, OxenError> {
    let name = name.as_ref();
    let head_commit = repositories::commits::head_commit(repo)?;
    with_ref_manager(repo, |manager| manager.create_branch(name, &head_commit.id))
}

/// # Create a local branch from a specific commit id
pub fn create(
    repo: &LocalRepository,
    name: impl AsRef<str>,
    commit_id: impl AsRef<str>,
) -> Result<Branch, OxenError> {
    let name = name.as_ref();
    let commit_id = commit_id.as_ref();

    if repositories::commits::commit_id_exists(repo, commit_id)? {
        with_ref_manager(repo, |manager| manager.create_branch(name, commit_id))
    } else {
        Err(OxenError::commit_id_does_not_exist(commit_id))
    }
}

/// # Create a branch and check it out in one go
/// This creates a branch with name,
/// then switches HEAD to point to the branch
pub fn create_checkout(repo: &LocalRepository, name: impl AsRef<str>) -> Result<Branch, OxenError> {
    let name = name.as_ref();
    let name = util::fs::linux_path_str(name);
    println!("Create and checkout branch: {name}");
    let head_commit = repositories::commits::head_commit(repo)?;

    with_ref_manager(repo, |manager| {
        let branch = manager.create_branch(&name, &head_commit.id)?;
        manager.set_head(name);
        Ok(branch)
    })
}

/// Update the branch name to point to a commit id, creating the branch if it doesn't exist.
/// Validates that the commit exists before updating.
pub fn update(
    repo: &LocalRepository,
    name: impl AsRef<str>,
    commit_id: impl AsRef<str>,
) -> Result<Branch, OxenError> {
    let name = name.as_ref();
    let commit_id = commit_id.as_ref();

    if !repositories::commits::commit_id_exists(repo, commit_id)? {
        return Err(OxenError::commit_id_does_not_exist(commit_id));
    }

    with_ref_manager(repo, |manager| {
        if let Some(mut branch) = manager.get_branch_by_name(name)? {
            // Set the branch to point to the commit
            manager.set_branch_commit_id(name, commit_id)?;
            branch.commit_id = commit_id.to_string();
            Ok(branch)
        } else {
            manager.create_branch(name, commit_id)
        }
    })
}

/// Delete a local branch
pub fn delete(repo: &LocalRepository, name: impl AsRef<str>) -> Result<Branch, OxenError> {
    let name = name.as_ref();
    // Make sure they don't delete the current checked out branch
    if let Ok(Some(branch)) = current_branch(repo)
        && branch.name == name
    {
        let err = format!("Err: Cannot delete current checked out branch '{name}'");
        return Err(OxenError::basic_str(err));
    }

    if branch_has_been_merged(repo, name)? {
        with_ref_manager(repo, |manager| manager.delete_branch(name))
    } else {
        let err = format!(
            "Err: The branch '{name}' is not fully merged.\nIf you are sure you want to delete it, run 'oxen branch -D {name}'."
        );
        Err(OxenError::basic_str(err))
    }
}

/// # Force delete a local branch
/// Caution! Will delete a local branch without checking if it has been merged or pushed.
pub fn force_delete(repo: &LocalRepository, name: impl AsRef<str>) -> Result<Branch, OxenError> {
    let name = name.as_ref();
    if let Ok(Some(branch)) = current_branch(repo)
        && branch.name == name
    {
        let err = format!("Err: Cannot delete current checked out branch '{name}'");
        return Err(OxenError::basic_str(err));
    }

    with_ref_manager(repo, |manager| manager.delete_branch(name))
}

/// Check if a branch is checked out
pub fn is_checked_out(repo: &LocalRepository, name: &str) -> bool {
    if let Ok(Some(current_branch)) = with_ref_manager(repo, |manager| manager.get_current_branch())
    {
        // If we are already on the branch, do nothing
        if current_branch.name == name {
            return true;
        }
    }
    false
}

/// Checkout a branch
pub async fn checkout_branch_from_commit(
    repo: &LocalRepository,
    name: impl AsRef<str>,
    from_commit: &Option<Commit>,
) -> Result<(), OxenError> {
    let name = name.as_ref();
    log::debug!("checkout_branch {name}");
    match repo.min_version() {
        MinOxenVersion::V0_10_0 => panic!("v0.10.0 no longer supported"),
        _ => core::v_latest::branches::checkout(repo, name, from_commit).await,
    }
}

/// Checkout a subtree from a commit
pub async fn checkout_subtrees_to_commit(
    repo: &LocalRepository,
    to_commit: &Commit,
    subtree_paths: &[PathBuf],
    depth: i32,
) -> Result<(), OxenError> {
    match repo.min_version() {
        MinOxenVersion::V0_10_0 => {
            panic!("checkout_subtree_from_commit not implemented for oxen v0.10.0")
        }
        _ => {
            core::v_latest::branches::checkout_subtrees(repo, to_commit, subtree_paths, depth).await
        }
    }
}

/// Checkout a commit
pub async fn checkout_commit_from_commit(
    repo: &LocalRepository,
    commit: &Commit,
    from_commit: &Option<Commit>,
) -> Result<(), OxenError> {
    match repo.min_version() {
        MinOxenVersion::V0_10_0 => panic!("v0.10.0 no longer supported"),
        _ => core::v_latest::branches::checkout_commit(repo, commit, from_commit).await,
    }
}

pub fn set_head(repo: &LocalRepository, value: impl AsRef<str>) -> Result<(), OxenError> {
    log::debug!("set_head {}", value.as_ref());
    with_ref_manager(repo, |manager| {
        manager.set_head(value);
        Ok(())
    })
}

fn branch_has_been_merged(repo: &LocalRepository, name: &str) -> Result<bool, OxenError> {
    with_ref_manager(repo, |manager| {
        if let Some(branch_commit_id) = manager.get_commit_id_for_branch(name)? {
            if let Some(commit_id) = manager.head_commit_id()? {
                let history = repositories::commits::list_from(repo, &commit_id)?;
                for commit in history.iter() {
                    if commit.id == branch_commit_id {
                        return Ok(true);
                    }
                }
                // We didn't find commit
                Ok(false)
            } else {
                // Cannot check if it has been merged if we are in a detached HEAD state
                Ok(false)
            }
        } else {
            let err = format!("Err: The branch '{name}' does not exist.");
            Err(OxenError::basic_str(err))
        }
    })
}

pub fn rename_current_branch(repo: &LocalRepository, new_name: &str) -> Result<(), OxenError> {
    if let Ok(Some(branch)) = current_branch(repo) {
        with_ref_manager(repo, |manager| {
            manager.rename_branch(&branch.name, new_name)?;
            manager.set_head(new_name);
            Ok(())
        })
    } else {
        log::error!("rename_current_branch No current branch found");
        Err(OxenError::must_be_on_valid_branch())
    }
}

// Traces through a branches history to list all unique versions of a file
pub fn list_entry_versions_on_branch(
    local_repo: &LocalRepository,
    branch_name: &str,
    path: &Path,
) -> Result<Vec<(Commit, CommitEntry)>, OxenError> {
    let branch = repositories::branches::get_by_name(local_repo, branch_name)?;
    log::debug!(
        "get branch commits for branch {:?} -> {}",
        branch.name,
        branch.commit_id
    );
    match local_repo.min_version() {
        MinOxenVersion::V0_10_0 => panic!("v0.10.0 no longer supported"),
        _ => core::v_latest::branches::list_entry_versions_for_commit(
            local_repo,
            &branch.commit_id,
            path,
        ),
    }
}

pub async fn set_working_repo_to_commit(
    repo: &LocalRepository,
    commit: &Commit,
    from_commit: &Option<Commit>,
) -> Result<(), OxenError> {
    match repo.min_version() {
        MinOxenVersion::V0_10_0 => {
            panic!("set_working_repo_to_commit not implemented for oxen v0.10.0")
        }
        _ => core::v_latest::branches::set_working_repo_to_commit(repo, commit, from_commit).await,
    }
}

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

    use crate::constants::DEFAULT_BRANCH_NAME;
    use crate::core::refs::with_ref_manager;
    use crate::error::OxenError;
    use crate::{repositories, test, util};

    #[tokio::test]
    async fn test_list_branch_versions_main() -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            // Make a dir
            let dir_path = Path::new("test_dir");
            let dir_repo_path = repo.path.join(dir_path);
            util::fs::create_dir_all(dir_repo_path)?;

            // File in the dir
            let file_path = dir_path.join(Path::new("test_file.txt"));
            let file_repo_path = repo.path.join(&file_path);
            util::fs::write_to_path(&file_repo_path, "test")?;

            // Add the dir
            repositories::add(&repo, &repo.path).await?;
            let commit_1 = repositories::commit(&repo, "adding test dir")?;

            // New file in root
            let file_path_2 = Path::new("test_file_2.txt");
            let file_repo_path_2 = repo.path.join(file_path_2);
            util::fs::write_to_path(&file_repo_path_2, "test")?;

            // Add the file
            repositories::add(&repo, &file_repo_path_2).await?;
            let commit_2 = repositories::commit(&repo, "adding test file")?;

            // Now modify both files, add a third
            let file_path_3 = Path::new("test_file_3.txt");
            let file_repo_path_3 = repo.path.join(file_path_3);

            util::fs::write_to_path(file_repo_path_3, "test 3")?;
            util::fs::write_to_path(&file_repo_path_2, "something different now")?;
            util::fs::write_to_path(&file_repo_path, "something different now")?;

            // Add-commit all
            repositories::add(&repo, &repo.path).await?;

            let commit_3 = repositories::commit(&repo, "adding test file 2")?;

            let _branch = repositories::branches::get_by_name(&repo, DEFAULT_BRANCH_NAME)?;

            let file_versions =
                repositories::branches::list_entry_versions_on_branch(&repo, "main", &file_path)?;

            let file_2_versions =
                repositories::branches::list_entry_versions_on_branch(&repo, "main", file_path_2)?;

            let file_3_versions =
                repositories::branches::list_entry_versions_on_branch(&repo, "main", file_path_3)?;

            assert_eq!(file_versions.len(), 2);
            assert_eq!(file_versions[0].0.id, commit_3.id);
            assert_eq!(file_versions[1].0.id, commit_1.id);

            println!("commit_1: {commit_1}");
            println!("commit_2: {commit_2}");
            println!("commit_3: {commit_3}");
            for v in &file_2_versions {
                println!("file_2_versions: {:?} -> {:?}", v.0, v.1);
            }

            assert_eq!(file_2_versions.len(), 2);
            assert_eq!(file_2_versions[0].0.id, commit_3.id);
            assert_eq!(file_2_versions[1].0.id, commit_2.id);

            assert_eq!(file_3_versions.len(), 1);
            assert_eq!(file_3_versions[0].0.id, commit_3.id);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_list_branch_versions_branch_off_main() -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            let dir_path = Path::new("test_dir");
            util::fs::create_dir_all(repo.path.join(dir_path))?;

            let file_path = dir_path.join(Path::new("test_file.txt"));
            let file_repo_path = repo.path.join(&file_path);

            // STARTING ON MAIN

            // Write initial file
            util::fs::write_to_path(&file_repo_path, "test")?;
            repositories::add(&repo, &repo.path).await?;
            let commit_1 = repositories::commit(&repo, "adding test file")?;

            // Change it
            util::fs::write_to_path(&file_repo_path, "something different now")?;
            repositories::add(&repo, &repo.path).await?;
            let commit_2 = repositories::commit(&repo, "adding test file 2")?;

            // Add an irrelevant file - aka this isn't changing for commit 3
            let file_path_2 = Path::new("test_file_2.txt");
            let file_repo_path_2 = repo.path.join(file_path_2);
            util::fs::write_to_path(file_repo_path_2, "test")?;
            repositories::add(&repo, &repo.path).await?;
            let _commit_3 = repositories::commit(&repo, "adding test file 3")?;

            // Branch off of main
            repositories::branches::create_checkout(&repo, "test_branch")?;

            // Change the file again
            util::fs::write_to_path(&file_repo_path, "something different now again")?;
            repositories::add(&repo, &repo.path).await?;
            let commit_4 = repositories::commit(&repo, "adding test file 4")?;

            // One more time on branch
            util::fs::write_to_path(&file_repo_path, "something different now again again")?;
            repositories::add(&repo, &repo.path).await?;
            let commit_5 = repositories::commit(&repo, "adding test file 5")?;

            // Back to main - hacky to avoid async checkout
            with_ref_manager(&repo, |manager| {
                manager.set_head(DEFAULT_BRANCH_NAME);
                Ok(())
            })?;

            // Another commit
            util::fs::write_to_path(&file_repo_path, "something different now again again again")?;
            repositories::add(&repo, &repo.path).await?;
            let commit_6 = repositories::commit(&repo, "adding test file 6")?;

            let _main = repositories::branches::get_by_name(&repo, DEFAULT_BRANCH_NAME)?;
            let _branch = repositories::branches::get_by_name(&repo, "test_branch")?;
            let main_versions =
                repositories::branches::list_entry_versions_on_branch(&repo, "main", &file_path)?;

            let branch_versions = repositories::branches::list_entry_versions_on_branch(
                &repo,
                "test_branch",
                &file_path.to_path_buf(),
            )?;

            for v in &main_versions {
                println!("main: {:?} -> {:?}", v.0, v.1);
            }

            for v in &branch_versions {
                println!("branch: {:?} -> {:?}", v.0, v.1);
            }

            // Main should have commits 6, 2, and 1.
            assert_eq!(main_versions.len(), 3);
            assert_eq!(main_versions[0].0.id, commit_6.id);
            assert_eq!(main_versions[1].0.id, commit_2.id);
            assert_eq!(main_versions[2].0.id, commit_1.id);

            // Branch should have commits 5, 4, 2, and 1.
            assert_eq!(branch_versions.len(), 4);
            assert_eq!(branch_versions[0].0.id, commit_5.id);
            assert_eq!(branch_versions[1].0.id, commit_4.id);
            assert_eq!(branch_versions[2].0.id, commit_2.id);
            assert_eq!(branch_versions[3].0.id, commit_1.id);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_force_update_existing_branch() -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            // Create two commits
            let file_path = repo.path.join("file.txt");
            util::fs::write_to_path(&file_path, "first")?;
            repositories::add(&repo, &file_path).await?;
            let commit_1 = repositories::commit(&repo, "first commit")?;

            util::fs::write_to_path(&file_path, "second")?;
            repositories::add(&repo, &file_path).await?;
            let _commit_2 = repositories::commit(&repo, "second commit")?;

            // Create a branch at current HEAD (commit_2)
            repositories::branches::create_checkout(&repo, "test-branch")?;

            // Force update it back to commit_1
            repositories::branches::update(&repo, "test-branch", &commit_1.id)?;

            // Verify the branch now points to commit_1
            let fetched = repositories::branches::get_by_name(&repo, "test-branch")?;
            assert_eq!(fetched.commit_id, commit_1.id);

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_force_update_creates_new_branch() -> Result<(), OxenError> {
        test::run_one_commit_local_repo_test_async(|repo| async move {
            let head = repositories::commits::head_commit(&repo)?;

            // Force update a branch that doesn't exist yet
            let branch = repositories::branches::update(&repo, "new-branch", &head.id)?;
            assert_eq!(branch.commit_id, head.id);
            assert_eq!(branch.name, "new-branch");

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_force_update_invalid_commit_fails() -> Result<(), OxenError> {
        test::run_one_commit_local_repo_test_async(|repo| async move {
            let result =
                repositories::branches::update(&repo, "test-branch", "nonexistent_commit_id");
            assert!(result.is_err());

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_local_delete_branch() -> Result<(), OxenError> {
        test::run_one_commit_local_repo_test_async(|repo| async move {
            // Get the original branches
            let og_branches = repositories::branches::list(&repo)?;
            let og_branch = repositories::branches::current_branch(&repo)?.unwrap();

            let branch_name = "my-branch";
            repositories::branches::create_checkout(&repo, branch_name)?;

            // Must checkout main again before deleting
            repositories::checkout(&repo, og_branch.name).await?;

            // Now we can delete
            repositories::branches::delete(&repo, branch_name)?;

            // Should be same num as og_branches
            let leftover_branches = repositories::branches::list(&repo)?;
            assert_eq!(og_branches.len(), leftover_branches.len());

            Ok(())
        })
        .await
    }
}