liboxen 0.50.1

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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
use crate::config::RepositoryConfig;
use crate::constants::{OXEN_HIDDEN_DIR, REPO_CONFIG_FILENAME};
use crate::core;
use crate::core::staged::staged_db_manager::get_staged_db_manager;
use crate::core::versions::MinOxenVersion;
use crate::core::workspaces::workspace_name_index;
use crate::error::OxenError;
use crate::model::entry::metadata_entry::{WorkspaceChanges, WorkspaceMetadataEntry};
use crate::model::{MetadataEntry, ParsedResource, StagedData, StagedEntryStatus, merkle_tree};
use crate::repositories;
use crate::repositories::merkle_tree::node::EMerkleTreeNode;
use crate::util;

use crate::model::{Commit, LocalRepository, NewCommitBody, Workspace, workspace::WorkspaceConfig};
use crate::view::entries::EMetadataEntry;
use crate::view::merge::Mergeable;

pub mod data_frames;
pub mod df;
pub mod diff;
pub mod files;
pub mod status;
pub mod upload;

pub use df::df;
pub use diff::diff;
pub use upload::upload;

use std::collections::HashMap;
use std::path::Path;
use uuid::Uuid;

/// Loads a workspace from the filesystem. Must call create() first to create the workspace.
///
/// Accepts either a workspace ID or a workspace name. Tries ID-based lookup first (O(1)),
/// then falls back to name lookup (O(1) with index, O(n) without).
///
/// Returns None if the workspace does not exist.
pub fn get(
    repo: &LocalRepository,
    workspace_id: impl AsRef<str>,
) -> Result<Option<Workspace>, OxenError> {
    let workspace_id = workspace_id.as_ref();
    let workspace_id_hash = util::hasher::hash_str_sha256(workspace_id);
    log::debug!("workspace::get workspace_id: {workspace_id:?} hash: {workspace_id_hash:?}");

    // First try: treat input as a workspace ID (O(1) directory lookup)
    let workspace_dir = Workspace::workspace_dir(repo, &workspace_id_hash);
    let config_path = Workspace::config_path_from_dir(&workspace_dir);

    log::debug!("workspace::get directory: {workspace_dir:?}");
    if config_path.exists() {
        return get_by_dir(repo, workspace_dir);
    }

    // Second try: treat input as a workspace name (already returns a loaded Workspace)
    if let Some(workspace) = get_by_name(repo, workspace_id)? {
        return Ok(Some(workspace));
    }

    Ok(None)
}

pub fn get_by_dir(
    repo: &LocalRepository,
    workspace_dir: impl AsRef<Path>,
) -> Result<Option<Workspace>, OxenError> {
    let workspace_dir = workspace_dir.as_ref();
    let workspace_id = workspace_dir.file_name().unwrap().to_str().unwrap();
    let config_path = Workspace::config_path_from_dir(workspace_dir);

    if !config_path.exists() {
        log::debug!("workspace::get workspace not found: {workspace_dir:?}");
        return Ok(None);
    }

    let config_contents = util::fs::read_from_path(&config_path)?;
    let config: WorkspaceConfig = toml::from_str(&config_contents)
        .map_err(|e| OxenError::basic_str(format!("Failed to parse workspace config: {e}")))?;

    let Some(commit) = repositories::commits::get_by_id(repo, &config.workspace_commit_id)? else {
        return Err(OxenError::basic_str(format!(
            "Workspace {} has invalid commit_id {}",
            workspace_id, config.workspace_commit_id
        )));
    };

    // Read repo config file for the storage config
    let config_file = repo.path.join(OXEN_HIDDEN_DIR).join(REPO_CONFIG_FILENAME);
    let repo_config = RepositoryConfig::from_file(&config_file)?;

    Ok(Some(Workspace {
        id: config.workspace_id.unwrap_or(workspace_id.to_owned()),
        name: config.workspace_name,
        base_repo: repo.clone(),
        workspace_repo: LocalRepository::new(workspace_dir, repo_config.storage)?,
        commit,
        is_editable: config.is_editable,
    }))
}

pub fn get_by_name(
    repo: &LocalRepository,
    workspace_name: impl AsRef<str>,
) -> Result<Option<Workspace>, OxenError> {
    let workspace_name = workspace_name.as_ref();

    // Fast path: use the name index if it exists (O(1))
    if workspace_name_index::index_exists(repo) {
        let idx = workspace_name_index::get_index(repo)?;
        let maybe_id = idx.get_id_by_name(workspace_name)?;
        if let Some(id) = maybe_id {
            let id_hash = util::hasher::hash_str_sha256(&id);
            let workspace_dir = Workspace::workspace_dir(repo, &id_hash);
            let result = get_by_dir(repo, &workspace_dir)?;
            if result.is_some() {
                return Ok(result);
            }
            // Stale index entry: workspace dir no longer exists. Clean it up.
            log::warn!(
                "workspace_name_index: stale entry for name '{workspace_name}' -> id '{id}', removing"
            );
            idx.delete(workspace_name)?;
        }
        return Ok(None);
    }

    // Slow path: iterate all workspaces (O(n)), used when index hasn't been created yet
    for workspace in iter_workspaces(repo)? {
        if let Some(workspace) = workspace?
            && workspace.name.as_deref() == Some(workspace_name)
        {
            return Ok(Some(workspace));
        }
    }
    Ok(None)
}

/// Creates a new workspace and saves it to the filesystem
pub fn create(
    base_repo: &LocalRepository,
    commit: &Commit,
    workspace_id: impl AsRef<str>,
    is_editable: bool,
) -> Result<Workspace, OxenError> {
    create_on_disk(base_repo, commit, workspace_id, None, is_editable)
}

pub async fn create_with_name(
    base_repo: &LocalRepository,
    commit: &Commit,
    workspace_id: impl AsRef<str>,
    workspace_name: Option<String>,
    is_editable: bool,
) -> Result<Workspace, OxenError> {
    let workspace_id = workspace_id.as_ref();
    let workspace = create_on_disk(base_repo, commit, workspace_id, workspace_name, is_editable)?;

    // Update the name index (async: rebuild_from_disk may run on a blocking thread)
    if let Some(ref name) = workspace.name {
        ensure_name_index(base_repo).await?;
        let idx = workspace_name_index::get_index(base_repo)?;
        idx.put(name, workspace_id)?;
    }

    Ok(workspace)
}

/// Core sync workspace creation logic shared by `create` and `create_with_name`.
/// Handles validation, directory setup, and TOML config writing — but NOT name indexing.
fn create_on_disk(
    base_repo: &LocalRepository,
    commit: &Commit,
    workspace_id: impl AsRef<str>,
    workspace_name: Option<String>,
    is_editable: bool,
) -> Result<Workspace, OxenError> {
    let workspace_id = workspace_id.as_ref();
    let workspace_id_hash = util::hasher::hash_str_sha256(workspace_id);
    let workspace_dir = Workspace::workspace_dir(base_repo, &workspace_id_hash);
    let oxen_dir = workspace_dir.join(OXEN_HIDDEN_DIR);

    log::debug!("index::workspaces::create called! {oxen_dir:?}");

    if oxen_dir.exists() {
        log::debug!("index::workspaces::create already have oxen repo directory {oxen_dir:?}");
        return Err(OxenError::basic_str(format!(
            "Workspace {workspace_id} already exists"
        )));
    }

    // Validate name uniqueness and non-editable constraints
    if workspace_name.is_some() || !is_editable {
        validate_create_constraints(base_repo, commit, &workspace_name, is_editable)?;
    }

    log::debug!("index::workspaces::create Initializing oxen repo! 🐂");

    let workspace_repo = init_workspace_repo(base_repo, &workspace_dir)?;

    // Serialize the workspace config to TOML
    let workspace_config = WorkspaceConfig {
        workspace_commit_id: commit.id.clone(),
        is_editable,
        workspace_name: workspace_name.clone(),
        workspace_id: Some(workspace_id.to_string()),
    };

    let toml_string = match toml::to_string(&workspace_config) {
        Ok(s) => s,
        Err(e) => {
            return Err(OxenError::basic_str(format!(
                "Failed to serialize workspace config to TOML: {e}"
            )));
        }
    };

    // Write the TOML string to WORKSPACE_CONFIG
    let workspace_config_path = Workspace::config_path_from_dir(&workspace_dir);
    log::debug!("index::workspaces::create writing workspace config to: {workspace_config_path:?}");
    util::fs::write_to_path(&workspace_config_path, toml_string)?;

    Ok(Workspace {
        id: workspace_id.to_owned(),
        name: workspace_name,
        base_repo: base_repo.clone(),
        workspace_repo,
        commit: commit.clone(),
        is_editable,
    })
}

/// Validates name uniqueness and non-editable constraints before workspace creation.
/// Uses the name index for O(1) checks when available, falls back to list() iteration.
fn validate_create_constraints(
    base_repo: &LocalRepository,
    commit: &Commit,
    workspace_name: &Option<String>,
    is_editable: bool,
) -> Result<(), OxenError> {
    let has_index = workspace_name_index::index_exists(base_repo);

    // Fast path: use the index for name checks when we don't need to iterate for non-editable
    if has_index && is_editable {
        if let Some(name) = workspace_name {
            // Check name doesn't collide with an existing workspace name
            let idx = workspace_name_index::get_index(base_repo)?;
            if idx.has_name(name)? {
                return Err(OxenError::WorkspaceAlreadyExists(name.to_string()));
            }
            // Check name doesn't collide with an existing workspace ID
            let name_as_id_hash = util::hasher::hash_str_sha256(name);
            let name_as_id_dir = Workspace::workspace_dir(base_repo, &name_as_id_hash);
            if Workspace::config_path_from_dir(&name_as_id_dir).exists() {
                return Err(OxenError::WorkspaceAlreadyExists(name.to_string()));
            }
        }
        return Ok(());
    }

    // Slow path: iterate all workspaces (needed when index doesn't exist or !is_editable)
    let workspaces = list(base_repo)?;
    for workspace in workspaces {
        if !is_editable {
            check_non_editable_workspace(&workspace, commit)?;
        }
        if let Some(name) = workspace_name {
            check_existing_workspace_name(&workspace, name)?;
        }
    }
    Ok(())
}

/// Ensures the workspace name index exists, lazily creating it if needed.
/// On first call for a repo, rebuilds the index from disk (one-time O(n))
/// on a blocking thread to avoid stalling the async runtime.
async fn ensure_name_index(repo: &LocalRepository) -> Result<(), OxenError> {
    if !workspace_name_index::index_exists(repo) {
        let repo = repo.clone();
        tokio::task::spawn_blocking(move || {
            let idx = workspace_name_index::get_index(&repo)?;
            idx.rebuild_from_disk(&repo)
        })
        .await
        .map_err(|e| OxenError::basic_str(format!("spawn_blocking join error: {e}")))??;
    }
    Ok(())
}

/// A wrapper around Workspace that automatically deletes the workspace when dropped
pub struct TemporaryWorkspace {
    workspace: Workspace,
}

impl TemporaryWorkspace {
    /// Get a reference to the underlying workspace
    pub fn workspace(&self) -> &Workspace {
        &self.workspace
    }
}

impl std::ops::Deref for TemporaryWorkspace {
    type Target = Workspace;

    fn deref(&self) -> &Self::Target {
        &self.workspace
    }
}

impl Drop for TemporaryWorkspace {
    fn drop(&mut self) {
        if let Err(e) = delete(&self.workspace) {
            log::error!("Failed to delete temporary workspace: {e}");
        }
    }
}

/// Creates a new temporary workspace that will be deleted when the reference is dropped
pub async fn create_temporary(
    base_repo: &LocalRepository,
    commit: &Commit,
) -> Result<TemporaryWorkspace, OxenError> {
    let workspace_id = Uuid::new_v4().to_string();
    let workspace_name = format!("temporary-{workspace_id}");
    let workspace =
        create_with_name(base_repo, commit, workspace_id, Some(workspace_name), true).await?;
    Ok(TemporaryWorkspace { workspace })
}

fn check_non_editable_workspace(workspace: &Workspace, commit: &Commit) -> Result<(), OxenError> {
    if workspace.commit.id == commit.id && !workspace.is_editable {
        return Err(OxenError::basic_str(format!(
            "A non-editable workspace already exists for commit {}",
            commit.id
        )));
    }
    Ok(())
}

fn check_existing_workspace_name(
    workspace: &Workspace,
    workspace_name: &str,
) -> Result<(), OxenError> {
    if workspace.name == Some(workspace_name.to_string()) || *workspace_name == workspace.id {
        return Err(OxenError::WorkspaceAlreadyExists(
            workspace_name.to_string(),
        ));
    }
    Ok(())
}

/// Returns a lazy iterator over all workspaces in the repository.
/// Each workspace is loaded from the filesystem on demand.
fn iter_workspaces(
    repo: &LocalRepository,
) -> Result<impl Iterator<Item = Result<Option<Workspace>, OxenError>> + '_, OxenError> {
    let workspaces_dir = Workspace::workspaces_dir(repo);
    log::debug!("workspace::iter_workspaces got workspaces_dir: {workspaces_dir:?}");

    let workspace_hashes = if workspaces_dir.exists() {
        util::fs::list_dirs_in_dir(&workspaces_dir).map_err(|e| {
            OxenError::basic_str(format!("Error listing workspace directories: {e}"))
        })?
    } else {
        Vec::new()
    };

    log::debug!(
        "workspace::iter_workspaces got {} workspaces",
        workspace_hashes.len()
    );

    Ok(workspace_hashes
        .into_iter()
        .map(move |workspace_hash| get_by_dir(repo, &workspace_hash)))
}

pub fn list(repo: &LocalRepository) -> Result<Vec<Workspace>, OxenError> {
    let mut workspaces = Vec::new();
    for workspace in iter_workspaces(repo)? {
        if let Some(workspace) = workspace? {
            workspaces.push(workspace);
        }
    }
    Ok(workspaces)
}

pub fn get_non_editable_by_commit_id(
    repo: &LocalRepository,
    commit_id: impl AsRef<str>,
) -> Result<Workspace, OxenError> {
    let workspaces = list(repo)?;
    for workspace in workspaces {
        if workspace.commit.id == commit_id.as_ref() && !workspace.is_editable {
            return Ok(workspace);
        }
    }
    Err(OxenError::basic_str(
        "No non-editable workspace found for the given commit ID",
    ))
}

pub fn delete(workspace: &Workspace) -> Result<(), OxenError> {
    let workspace_id = workspace.id.to_string();
    let workspace_dir = workspace.dir();
    if !workspace_dir.exists() {
        return Err(OxenError::WorkspaceNotFound(workspace_id.into()));
    }

    log::debug!("workspace::delete cleaning up workspace dir: {workspace_dir:?}");

    // Remove from name index before deleting the workspace directory
    if let Some(ref name) = workspace.name
        && workspace_name_index::index_exists(&workspace.base_repo)
    {
        match workspace_name_index::get_index(&workspace.base_repo) {
            Ok(idx) => {
                if let Err(e) = idx.delete(name) {
                    log::error!("workspace::delete error removing workspace index: {e:?}");
                }
            }
            Err(e) => log::error!("workspace::delete error finding workspace index: {e:?}"),
        }
    }

    // Clean up caches before deleting the workspace
    merkle_tree::merkle_tree_node_cache::remove_from_cache(&workspace.workspace_repo.path)?;
    core::staged::remove_from_cache(&workspace.workspace_repo.path)?;
    match util::fs::remove_dir_all(&workspace_dir) {
        Ok(_) => log::debug!("workspace::delete removed workspace dir: {workspace_dir:?}"),
        Err(e) => log::error!("workspace::delete error removing workspace dir: {e:?}"),
    }

    Ok(())
}

pub fn clear(repo: &LocalRepository) -> Result<(), OxenError> {
    let workspaces_dir = Workspace::workspaces_dir(repo);
    if !workspaces_dir.exists() {
        return Ok(());
    }

    // Evict the name index DB handle from cache before removing the directory
    workspace_name_index::remove_from_cache(repo);

    util::fs::remove_dir_all(&workspaces_dir)?;
    Ok(())
}

pub fn update_commit(workspace: &Workspace, new_commit_id: &str) -> Result<(), OxenError> {
    let config_path = workspace.config_path();

    if !config_path.exists() {
        log::error!("Workspace config not found: {config_path:?}");
        return Err(OxenError::WorkspaceNotFound(workspace.id.as_str().into()));
    }

    let config_contents = util::fs::read_from_path(&config_path)?;
    let mut config: WorkspaceConfig = toml::from_str(&config_contents).map_err(|e| {
        log::error!("Failed to parse workspace config: {config_path:?}, err: {e}");
        OxenError::basic_str(format!("Failed to parse workspace config: {e}"))
    })?;

    log::debug!(
        "Updating workspace {} commit from {} to {}",
        workspace.id,
        config.workspace_commit_id,
        new_commit_id
    );
    config.workspace_commit_id = new_commit_id.to_string();

    let toml_string = toml::to_string(&config).map_err(|e| {
        log::error!("Failed to serialize workspace config to TOML: {config_path:?}, err: {e}");
        OxenError::basic_str(format!("Failed to serialize workspace config to TOML: {e}"))
    })?;

    util::fs::write_to_path(&config_path, toml_string)?;

    Ok(())
}

pub async fn commit(
    workspace: &Workspace,
    new_commit: &NewCommitBody,
    branch_name: impl AsRef<str>,
) -> Result<Commit, OxenError> {
    match workspace.workspace_repo.min_version() {
        MinOxenVersion::V0_10_0 => panic!("v0.10.0 no longer supported"),
        _ => core::v_latest::workspaces::commit::commit(workspace, new_commit, branch_name).await,
    }
}

pub fn mergeability(
    workspace: &Workspace,
    branch_name: impl AsRef<str>,
) -> Result<Mergeable, OxenError> {
    match workspace.workspace_repo.min_version() {
        MinOxenVersion::V0_10_0 => panic!("v0.10.0 no longer supported"),
        _ => core::v_latest::workspaces::commit::mergeability(workspace, branch_name),
    }
}

fn init_workspace_repo(
    repo: &LocalRepository,
    workspace_dir: impl AsRef<Path>,
) -> Result<LocalRepository, OxenError> {
    let workspace_dir = workspace_dir.as_ref();
    match repo.min_version() {
        MinOxenVersion::V0_10_0 => panic!("v0.10.0 no longer supported"),
        _ => core::v_latest::workspaces::init_workspace_repo(repo, workspace_dir),
    }
}

pub fn populate_entries_with_workspace_data(
    repo: &LocalRepository,
    directory: &Path,
    workspace: &Workspace,
    entries: &[MetadataEntry],
) -> Result<Vec<EMetadataEntry>, OxenError> {
    let workspace_changes =
        repositories::workspaces::status::status_from_dir(workspace, directory)?;
    let mut dir_entries: Vec<EMetadataEntry> = Vec::new();
    let mut entries: Vec<WorkspaceMetadataEntry> = entries
        .iter()
        .map(|entry| WorkspaceMetadataEntry::from_metadata_entry(entry.clone()))
        .collect();

    let (additions_map, other_changes_map) =
        build_file_status_maps_for_directory(&workspace_changes);
    for entry in entries.iter_mut() {
        let status = other_changes_map.get(&entry.filename).cloned();
        match status {
            Some(status) => {
                entry.changes = Some(WorkspaceChanges {
                    status: status.clone(),
                });
                dir_entries.push(EMetadataEntry::WorkspaceMetadataEntry(entry.clone()));
            }
            _ => {
                dir_entries.push(EMetadataEntry::WorkspaceMetadataEntry(entry.clone()));
            }
        }
    }
    for (file_path, status) in additions_map.iter() {
        if *status == StagedEntryStatus::Added {
            let staged_node = get_staged_db_manager(&workspace.workspace_repo)?
                .read_from_staged_db(file_path)?
                .ok_or_else(|| {
                    OxenError::basic_str(format!(
                        "Staged entry disappeared while resolving workspace metadata: {file_path:?}"
                    ))
                })?;

            let metadata = match staged_node.node.node {
                EMerkleTreeNode::File(file_node) => {
                    repositories::metadata::from_file_node(repo, &file_node, &workspace.commit)?
                }
                EMerkleTreeNode::Directory(dir_node) => {
                    repositories::metadata::from_dir_node(repo, &dir_node, &workspace.commit)?
                }
                _ => {
                    return Err(OxenError::basic_str(
                        "Unexpected node type found in staged db",
                    ));
                }
            };

            let mut ws_entry = WorkspaceMetadataEntry::from_metadata_entry(metadata);
            ws_entry.changes = Some(WorkspaceChanges {
                status: status.clone(),
            });
            dir_entries.push(EMetadataEntry::WorkspaceMetadataEntry(ws_entry));
        }
    }

    Ok(dir_entries)
}

pub fn populate_entry_with_workspace_data(
    file_path: &Path,
    entry: MetadataEntry,
    workspace: &Workspace,
) -> Result<EMetadataEntry, OxenError> {
    let workspace_changes =
        repositories::workspaces::status::status_from_dir(workspace, file_path)?;
    let (_additions_map, other_changes_map) = build_file_status_maps_for_file(&workspace_changes);
    let mut entry = WorkspaceMetadataEntry::from_metadata_entry(entry.clone());
    let changes = other_changes_map.get(file_path.to_str().unwrap()).cloned();
    if let Some(status) = changes {
        entry.changes = Some(WorkspaceChanges {
            status: status.clone(),
        });
    }
    Ok(EMetadataEntry::WorkspaceMetadataEntry(entry))
}

pub fn get_added_entry(
    repo: &LocalRepository,
    file_path: &Path,
    workspace: &Workspace,
    resource: &ParsedResource,
) -> Result<EMetadataEntry, OxenError> {
    let workspace_changes =
        repositories::workspaces::status::status_from_dir(workspace, file_path)?;
    let (additions_map, _other_changes_map) = build_file_status_maps_for_file(&workspace_changes);
    if let Some(status) = additions_map.get(file_path.to_str().unwrap()).cloned() {
        if status != StagedEntryStatus::Added {
            return Err(OxenError::basic_str(
                "Entry is not in the workspace's staged database",
            ));
        }

        let staged_node = get_staged_db_manager(&workspace.workspace_repo)?
            .read_from_staged_db(file_path)?
            .expect("Staged node found in status not present in staged db");

        let metadata = match staged_node.node.node {
            EMerkleTreeNode::File(file_node) => {
                repositories::metadata::from_file_node(repo, &file_node, &workspace.commit)?
            }
            EMerkleTreeNode::Directory(dir_node) => {
                repositories::metadata::from_dir_node(repo, &dir_node, &workspace.commit)?
            }
            _ => {
                return Err(OxenError::basic_str(
                    "Unexpected node type found in staged db",
                ));
            }
        };

        let mut ws_entry = WorkspaceMetadataEntry::from_metadata_entry(metadata);
        ws_entry.changes = Some(WorkspaceChanges {
            status: StagedEntryStatus::Added,
        });
        ws_entry.resource = Some(resource.clone().into());
        Ok(EMetadataEntry::WorkspaceMetadataEntry(ws_entry))
    } else {
        Err(OxenError::basic_str(
            "Entry is not in the workspace's staged database",
        ))
    }
}

/// Build a hashmap mapping file paths to their status from workspace_changes.staged_files.
///
/// Returns a tuple of two hashmaps:
/// - The first hashmap contains file paths mapped to their status if they are added.
/// - The second hashmap contains file paths mapped to their status if they are modified or removed.
///
/// This allows us to track files that were added to the workspace efficiently.
fn build_file_status_maps_for_directory(
    workspace_changes: &StagedData,
) -> (
    HashMap<String, StagedEntryStatus>,
    HashMap<String, StagedEntryStatus>,
) {
    let mut additions_map = HashMap::new();
    let mut other_changes_map = HashMap::new();
    workspace_changes.print();

    for (file_path, entry) in workspace_changes.staged_files.iter() {
        let status = entry.status.clone();
        if status == StagedEntryStatus::Added {
            // For added files, we use the full path as the key. As the staged files are relative to the repository root
            let key = file_path.to_str().unwrap().to_string();
            additions_map.insert(key, status);
        } else {
            // For modified or removed files, we use the file name as the key, as the file path is relative to the directory passed in.
            let key = file_path.file_name().unwrap().to_string_lossy().to_string();
            other_changes_map.insert(key, status);
        }
    }

    (additions_map, other_changes_map)
}

// For files, we always use the full path as the key, as results are relative to the repository root
fn build_file_status_maps_for_file(
    workspace_changes: &StagedData,
) -> (
    HashMap<String, StagedEntryStatus>,
    HashMap<String, StagedEntryStatus>,
) {
    let mut additions_map = HashMap::new();
    let mut other_changes_map = HashMap::new();
    for (file_path, entry) in workspace_changes.staged_files.iter() {
        let status = entry.status.clone();
        if status == StagedEntryStatus::Added {
            additions_map.insert(file_path.to_str().unwrap().to_string(), status);
        } else {
            other_changes_map.insert(file_path.to_str().unwrap().to_string(), status);
        }
    }
    (additions_map, other_changes_map)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api;
    use crate::constants::{DEFAULT_BRANCH_NAME, WORKSPACE_NAME_INDEX_DIR};
    use crate::repositories;
    use crate::test;
    use crate::util;

    #[tokio::test]
    async fn test_can_commit_different_files_workspaces_without_merge_conflicts()
    -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            // Write two files, hello.txt and goodbye.txt, and commit them
            let hello_file = repo.path.join("hello.txt");
            let goodbye_file = repo.path.join("goodbye.txt");
            util::fs::write_to_path(&hello_file, "Hello")?;
            util::fs::write_to_path(&goodbye_file, "Goodbye")?;
            repositories::add(&repo, &hello_file).await?;
            repositories::add(&repo, &goodbye_file).await?;
            let commit = repositories::commit(&repo, "Adding hello and goodbye files")?;

            {
                // Create temporary workspace in new scope
                let temp_workspace = create_temporary(&repo, &commit).await?;

                // Update the hello file in the temporary workspace
                let workspace_hello_file = temp_workspace.dir().join("hello.txt");
                util::fs::write_to_path(&workspace_hello_file, "Hello again")?;
                repositories::workspaces::files::add(&temp_workspace, workspace_hello_file).await?;
                // Commit the changes to the "main" branch
                repositories::workspaces::commit(
                    &temp_workspace,
                    &NewCommitBody {
                        message: "Updating hello file".to_string(),
                        author: "Bessie".to_string(),
                        email: "bessie@oxen.ai".to_string(),
                    },
                    DEFAULT_BRANCH_NAME,
                )
                .await?;
            } // temp_workspace goes out of scope here and gets cleaned up

            {
                // Create a new temporary workspace off of the same original commit
                let temp_workspace = create_temporary(&repo, &commit).await?;

                // Update the goodbye file in the temporary workspace
                let workspace_goodbye_file = temp_workspace.dir().join("goodbye.txt");
                util::fs::write_to_path(&workspace_goodbye_file, "Goodbye again")?;
                repositories::workspaces::files::add(&temp_workspace, workspace_goodbye_file)
                    .await?;
                // Commit the changes to the "main" branch
                repositories::workspaces::commit(
                    &temp_workspace,
                    &NewCommitBody {
                        message: "Updating goodbye file".to_string(),
                        author: "Bessie".to_string(),
                        email: "bessie@oxen.ai".to_string(),
                    },
                    DEFAULT_BRANCH_NAME,
                )
                .await?;
            } // temp_workspace goes out of scope here and gets cleaned up

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_cannot_commit_different_files_workspaces_with_merge_conflicts()
    -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            // Both workspaces try to commit the same file
            let hello_file = repo.path.join("greetings").join("hello.txt");
            util::fs::write_to_path(&hello_file, "Hello")?;
            repositories::add(&repo, &hello_file).await?;
            let commit = repositories::commit(&repo, "Adding hello file")?;

            {
                // Create temporary workspace in new scope
                let temp_workspace = create_temporary(&repo, &commit).await?;

                // Update the hello file in the temporary workspace
                let workspace_hello_file = temp_workspace.dir().join("greetings").join("hello.txt");
                util::fs::write_to_path(&workspace_hello_file, "Hello again")?;
                repositories::workspaces::files::add(&temp_workspace, workspace_hello_file).await?;
                // Commit the changes to the "main" branch
                repositories::workspaces::commit(
                    &temp_workspace,
                    &NewCommitBody {
                        message: "Updating hello file".to_string(),
                        author: "Bessie".to_string(),
                        email: "bessie@oxen.ai".to_string(),
                    },
                    DEFAULT_BRANCH_NAME,
                )
                .await?;
            } // temp_workspace goes out of scope here and gets cleaned up

            {
                // Create a new temporary workspace off of the same original commit
                let temp_workspace = create_temporary(&repo, &commit).await?;

                // Update the hello file in the temporary workspace
                let workspace_hello_file = temp_workspace.dir().join("greetings").join("hello.txt");
                util::fs::write_to_path(&workspace_hello_file, "Hello again")?;
                repositories::workspaces::files::add(&temp_workspace, workspace_hello_file).await?;
                // Commit the changes to the "main" branch
                let result = repositories::workspaces::commit(
                    &temp_workspace,
                    &NewCommitBody {
                        message: "Updating hello file".to_string(),
                        author: "Bessie".to_string(),
                        email: "bessie@oxen.ai".to_string(),
                    },
                    DEFAULT_BRANCH_NAME,
                )
                .await;

                // We should get a merge conflict error
                assert!(result.is_err());
            } // temp_workspace goes out of scope here and gets cleaned up

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_can_commit_different_files_workspaces_without_merge_conflicts_in_subdirs()
    -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            // Write two files, greetings/hello.txt and greetings/goodbye.txt, and commit them
            let hello_file = repo.path.join("greetings").join("hello.txt");
            let goodbye_file = repo.path.join("greetings").join("goodbye.txt");
            util::fs::write_to_path(&hello_file, "Hello")?;
            util::fs::write_to_path(&goodbye_file, "Goodbye")?;
            repositories::add(&repo, &hello_file).await?;
            repositories::add(&repo, &goodbye_file).await?;
            let commit = repositories::commit(&repo, "Adding hello and goodbye files")?;

            {
                // Create temporary workspace in new scope
                let temp_workspace = create_temporary(&repo, &commit).await?;

                // Update the hello file in the temporary workspace
                let workspace_hello_file = temp_workspace.dir().join("greetings").join("hello.txt");
                util::fs::write_to_path(&workspace_hello_file, "Hello again")?;
                repositories::workspaces::files::add(&temp_workspace, workspace_hello_file).await?;
                // Commit the changes to the "main" branch
                repositories::workspaces::commit(
                    &temp_workspace,
                    &NewCommitBody {
                        message: "Updating hello file".to_string(),
                        author: "Bessie".to_string(),
                        email: "bessie@oxen.ai".to_string(),
                    },
                    DEFAULT_BRANCH_NAME,
                )
                .await?;
            } // temp_workspace goes out of scope here and gets cleaned up

            {
                // Create a new temporary workspace off of the same original commit
                let temp_workspace = create_temporary(&repo, &commit).await?;

                // Update the goodbye file in the temporary workspace
                let workspace_goodbye_file =
                    temp_workspace.dir().join("greetings").join("goodbye.txt");
                util::fs::write_to_path(&workspace_goodbye_file, "Goodbye again")?;
                repositories::workspaces::files::add(&temp_workspace, workspace_goodbye_file)
                    .await?;
                // Commit the changes to the "main" branch
                repositories::workspaces::commit(
                    &temp_workspace,
                    &NewCommitBody {
                        message: "Updating goodbye file".to_string(),
                        author: "Bessie".to_string(),
                        email: "bessie@oxen.ai".to_string(),
                    },
                    DEFAULT_BRANCH_NAME,
                )
                .await?;
            } // temp_workspace goes out of scope here and gets cleaned up

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_temporary_workspace_cleanup() -> Result<(), OxenError> {
        test::run_empty_local_repo_test_async(|repo| async move {
            // Write a test file and commit it
            let test_file = repo.path.join("test.txt");
            util::fs::write_to_path(&test_file, "Hello")?;
            repositories::add(&repo, &test_file).await?;
            let commit = repositories::commit(&repo, "Adding test file")?;
            let workspaces_dir = repo.path.join(".oxen").join("workspaces");

            {
                // Create temporary workspace in new scope
                let temp_workspace = create_temporary(&repo, &commit).await?;

                // Verify workspace exists and contains our file
                assert!(temp_workspace.dir().exists());

                // Test deref functionality by accessing workspace fields/methods
                assert_eq!(temp_workspace.commit.id, commit.id);
                assert!(temp_workspace.is_editable);

                let workspace_count = std::fs::read_dir(&workspaces_dir)?
                    .filter(|e| {
                        e.as_ref()
                            .map(|e| e.file_name() != WORKSPACE_NAME_INDEX_DIR)
                            .unwrap_or(false)
                    })
                    .count();
                assert_eq!(workspace_count, 1);
            } // temp_workspace goes out of scope here

            // Verify workspace was cleaned up (only the name index dir should remain)
            let workspace_count = std::fs::read_dir(&workspaces_dir)?
                .filter(|e| {
                    e.as_ref()
                        .map(|e| e.file_name() != WORKSPACE_NAME_INDEX_DIR)
                        .unwrap_or(false)
                })
                .count();
            assert_eq!(
                workspace_count, 0,
                "Workspace directory should have no workspace dirs after cleanup"
            );

            Ok(())
        })
        .await
    }

    #[tokio::test]
    async fn test_concurrent_workspace_commits() -> Result<(), OxenError> {
        test::run_one_commit_sync_repo_test(|repo, remote_repo| async move {
            // Create two files in different directories to avoid conflicts
            let file1 = repo.path.join("dir1").join("file1.txt");
            let file2 = repo.path.join("dir2").join("file2.txt");
            util::fs::write_to_path(&file1, "File 1 content")?;
            util::fs::write_to_path(&file2, "File 2 content")?;
            repositories::add(&repo, &file1).await?;
            repositories::add(&repo, &file2).await?;
            let _commit = repositories::commit(&repo, "Adding initial files")?;
            repositories::push(&repo).await?;

            // Create two workspaces
            let workspace1 =
                api::client::workspaces::create(&remote_repo, DEFAULT_BRANCH_NAME, "workspace1")
                    .await?;
            let workspace2 =
                api::client::workspaces::create(&remote_repo, DEFAULT_BRANCH_NAME, "workspace2")
                    .await?;

            // Modify files in each workspace
            util::fs::write_to_path(&file1, "Updated file 1")?;
            util::fs::write_to_path(&file2, "Updated file 2")?;
            api::client::workspaces::files::upload_single_file(
                &remote_repo,
                &workspace1.id,
                "dir1",
                file1,
            )
            .await?;
            api::client::workspaces::files::upload_single_file(
                &remote_repo,
                &workspace2.id,
                "dir2",
                file2,
            )
            .await?;

            // Create commit bodies
            let commit_body1 = NewCommitBody {
                message: "Update file 1".to_string(),
                author: "Bessie".to_string(),
                email: "bessie@oxen.ai".to_string(),
            };
            let commit_body2 = NewCommitBody {
                message: "Update file 2".to_string(),
                author: "Bessie".to_string(),
                email: "bessie@oxen.ai".to_string(),
            };

            // Clone necessary values for the second task
            let remote_repo_clone1 = remote_repo.clone();
            let remote_repo_clone2 = remote_repo.clone();

            // Spawn two concurrent commit tasks
            let commit_task1 = tokio::spawn(async move {
                api::client::workspaces::commit(
                    &remote_repo_clone1,
                    DEFAULT_BRANCH_NAME,
                    &workspace1.id,
                    &commit_body1,
                )
                .await
            });
            let commit_task2 = tokio::spawn(async move {
                api::client::workspaces::commit(
                    &remote_repo_clone2,
                    DEFAULT_BRANCH_NAME,
                    &workspace2.id,
                    &commit_body2,
                )
                .await
            });

            // Wait for both tasks to complete
            let result1 = commit_task1.await.expect("Task 1 panicked")?;
            let result2 = commit_task2.await.expect("Task 2 panicked")?;

            // Verify both commits were successful
            assert_ne!(result1.id, result2.id, "Commits should have different IDs");
            assert!(!result1.id.is_empty(), "Commit 1 should have valid ID");
            assert!(!result2.id.is_empty(), "Commit 2 should have valid ID");

            Ok(remote_repo)
        })
        .await
    }

    #[tokio::test]
    async fn test_fully_concurrent_workspace_operations() -> Result<(), OxenError> {
        // Number of concurrent tasks to run
        const NUM_TASKS: usize = 20;

        test::run_one_commit_sync_repo_test(|repo, remote_repo| async move {
            let mut handles = vec![];

            // Spawn NUM_TASKS concurrent tasks
            for i in 0..NUM_TASKS {
                let remote_repo = remote_repo.clone();
                let repo = repo.clone();
                let handle = tokio::spawn(async move {
                    // Create a unique branch for this task
                    let branch_name = format!("branch-{i}");
                    api::client::branches::create_from_branch(
                        &remote_repo,
                        &branch_name,
                        DEFAULT_BRANCH_NAME,
                    )
                    .await?;

                    // Create workspace from the new branch
                    let workspace = api::client::workspaces::create(
                        &remote_repo,
                        &branch_name,
                        &format!("workspace-{i}"),
                    )
                    .await?;

                    // Add a unique file
                    let file_path = repo.path.join(format!("file-{i}.txt"));
                    util::fs::write_to_path(&file_path, format!("content {i}"))?;
                    api::client::workspaces::files::upload_single_file(
                        &remote_repo,
                        &workspace.id,
                        "",
                        file_path,
                    )
                    .await?;

                    // Commit changes back to the task's branch
                    let commit_body = NewCommitBody {
                        message: format!("Commit from task {i}"),
                        author: "Test Author".to_string(),
                        email: "test@oxen.ai".to_string(),
                    };

                    api::client::workspaces::commit(
                        &remote_repo,
                        &branch_name,
                        &workspace.id,
                        &commit_body,
                    )
                    .await?;

                    Ok::<_, OxenError>(())
                });
                handles.push(handle);
            }

            // Wait for all tasks to complete and collect results
            for handle in handles {
                handle
                    .await
                    .map_err(|e| OxenError::basic_str(format!("Task error: {e}")))??;
            }

            Ok(remote_repo)
        })
        .await
    }
}