liboxen 0.9.4-beta3

Oxen is a fast, unstructured data version control, to help version datasets, written in Rust.
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
use crate::api;
use crate::core::index::{CommitReader, RefReader};
use crate::error::OxenError;
use crate::model::{Commit, LocalRepository, ParsedResource};

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

/// Returns commit_id,branch_or_commit_id,filepath
/// Parses a path looking for either a commit id or a branch name, returns None of neither exist
pub fn parse_resource(
    repo: &LocalRepository,
    path: &Path,
) -> Result<Option<(String, String, PathBuf)>, OxenError> {
    let mut components = path.components().collect::<Vec<_>>();
    let commit_reader = CommitReader::new(repo)?;

    // See if the first component is the commit id
    log::debug!("parse_resource looking for commit id in path {:?}", path);

    if let Some(first_component) = components.first() {
        let base_path: &Path = first_component.as_ref();
        let maybe_commit_id = base_path.to_str().unwrap();
        log::debug!("parse_resource looking for commit id {}", maybe_commit_id);
        if let Ok(Some(commit)) = commit_reader.get_commit_by_id(maybe_commit_id) {
            let mut file_path = PathBuf::new();
            for (i, component) in components.iter().enumerate() {
                if i != 0 {
                    let component_path: &Path = component.as_ref();
                    file_path = file_path.join(component_path);
                }
            }
            log::debug!(
                "parse_resource got commit.id [{}] and filepath [{:?}]",
                commit.id,
                file_path
            );
            return Ok(Some((commit.id.clone(), commit.id, file_path)));
        }
    }

    // See if the component has a valid branch name in it
    log::debug!("parse_resource looking for branch in path {:?}", path);
    let ref_reader = RefReader::new(repo)?;
    let mut file_path = PathBuf::new();
    while let Some(component) = components.pop() {
        let component_path: &Path = component.as_ref();
        if file_path == PathBuf::new() {
            file_path = component_path.to_path_buf();
        } else {
            file_path = component_path.join(file_path);
        }

        log::debug!(
            "parse_resource got file path [{:?}] with {} remaining components",
            file_path,
            components.len()
        );
        // if we have no components, looking at base dir within that branch
        if components.is_empty() {
            let branch_name = file_path.to_str().unwrap();
            if let Some(branch) = ref_reader.get_branch_by_name(branch_name)? {
                log::debug!(
                    "parse_resource got branch [{}] with no file path",
                    branch_name
                );

                return Ok(Some((branch.commit_id, branch.name, PathBuf::from(""))));
            } else {
                return Ok(None);
            }
        }

        let mut branch_path = PathBuf::new();
        for component in components.iter() {
            let component_path: &Path = component.as_ref();
            branch_path = branch_path.join(component_path);
        }

        let branch_name = branch_path.to_str().unwrap();
        log::debug!("parse_resource looking for branch [{}]", branch_name);
        if let Some(branch) = ref_reader.get_branch_by_name(branch_name)? {
            log::debug!(
                "parse_resource got branch [{}] and filepath [{:?}]",
                branch_name,
                file_path
            );

            return Ok(Some((branch.commit_id, branch.name, file_path)));
        }
    }

    Ok(None)
}

pub fn parse_resource_from_path(
    repo: &LocalRepository,
    path: &Path,
) -> Result<Option<ParsedResource>, OxenError> {
    let mut components = path.components().collect::<Vec<_>>();
    let commit_reader = CommitReader::new(repo)?;

    // See if the first component is the commit id
    // log::debug!("parse_resource looking for commit id in path {:?}", path);

    if let Some(first_component) = components.first() {
        let base_path: &Path = first_component.as_ref();
        let maybe_commit_id = base_path.to_str().unwrap();
        // log::debug!("parse_resource looking for commit id {}", maybe_commit_id);
        if let Some(commit) = commit_reader.get_commit_by_id(maybe_commit_id)? {
            let mut file_path = PathBuf::new();
            for (i, component) in components.iter().enumerate() {
                if i != 0 {
                    let component_path: &Path = component.as_ref();
                    file_path = file_path.join(component_path);
                }
            }
            // log::debug!(
            //     "parse_resource got commit.id [{}] and filepath [{:?}]",
            //     commit.id,
            //     file_path
            // );
            return Ok(Some(ParsedResource {
                commit,
                branch: None,
                file_path,
                resource: path.to_owned(),
            }));
        }
    }

    // See if the component has a valid branch name in it
    // log::debug!("parse_resource looking for branch in path {:?}", path);
    let ref_reader = RefReader::new(repo)?;
    let mut file_path = PathBuf::new();
    while let Some(component) = components.pop() {
        let component_path: &Path = component.as_ref();
        if file_path == PathBuf::new() {
            file_path = component_path.to_path_buf();
        } else {
            file_path = component_path.join(file_path);
        }

        // log::debug!(
        //     "parse_resource got file path [{:?}] with {} remaining components",
        //     file_path,
        //     components.len()
        // );
        // if we have no components, looking at base dir within that branch
        if components.is_empty() {
            let branch_name = file_path.to_str().unwrap();
            if let Some(branch) = ref_reader.get_branch_by_name(branch_name)? {
                // log::debug!(
                //     "parse_resource got branch [{}] with no file path",
                //     branch_name
                // );

                let commit = commit_reader.get_commit_by_id(&branch.commit_id)?.unwrap();
                file_path = PathBuf::from("");
                return Ok(Some(ParsedResource {
                    commit,
                    branch: Some(branch),
                    file_path,
                    resource: path.to_owned(),
                }));
            } else {
                return Ok(None);
            }
        }

        let mut branch_path = PathBuf::new();
        for component in components.iter() {
            let component_path: &Path = component.as_ref();
            branch_path = branch_path.join(component_path);
        }

        let branch_name = branch_path.to_str().unwrap();
        // log::debug!("parse_resource looking for branch [{}]", branch_name);
        if let Some(branch) = ref_reader.get_branch_by_name(branch_name)? {
            // log::debug!(
            //     "parse_resource got branch [{}] and filepath [{:?}]",
            //     branch_name,
            //     file_path
            // );

            let commit = commit_reader.get_commit_by_id(&branch.commit_id)?.unwrap();
            return Ok(Some(ParsedResource {
                commit,
                branch: Some(branch),
                file_path,
                resource: path.to_owned(),
            }));
        }
    }

    Ok(None)
}

/// Pass in a branch name and maybe get a commit id back
pub fn maybe_get_commit_id_from_branch_name<S: AsRef<str>>(
    repo: &LocalRepository,
    commit_id_or_branch_name: S,
) -> Result<Option<String>, OxenError> {
    let ref_reader = RefReader::new(repo)?;
    ref_reader.get_commit_id_for_branch(commit_id_or_branch_name.as_ref())
}

/// Pass in a commit id or a branch name and resolve it to a
pub fn maybe_get_commit<S: AsRef<str>>(
    repo: &LocalRepository,
    commit_id_or_branch_name: S,
) -> Result<Option<Commit>, OxenError> {
    let commit_reader = CommitReader::new(repo)?;
    if let Some(commit) = commit_reader.get_commit_by_id(&commit_id_or_branch_name)? {
        return Ok(Some(commit));
    }

    match maybe_get_commit_id_from_branch_name(repo, &commit_id_or_branch_name) {
        Ok(Some(commit_id)) => commit_reader.get_commit_by_id(commit_id),
        Ok(None) => Err(OxenError::local_revision_not_found(
            commit_id_or_branch_name.as_ref(),
        )),
        Err(err) => Err(err),
    }
}

pub fn get_commit_or_head<S: AsRef<str>>(
    repo: &LocalRepository,
    commit_id_or_branch_name: Option<S>,
) -> Result<Commit, OxenError> {
    if commit_id_or_branch_name.is_none() {
        return api::local::commits::head_commit(repo);
    }

    match maybe_get_commit(repo, commit_id_or_branch_name.unwrap().as_ref()) {
        Ok(Some(commit)) => Ok(commit),
        _ => api::local::commits::head_commit(repo),
    }
}

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

    use crate::api;
    use crate::api::local::resource;
    use crate::error::OxenError;

    #[test]
    fn test_parse_resource_for_commit() -> Result<(), OxenError> {
        crate::test::run_training_data_repo_test_fully_committed(|repo| {
            let history = api::local::commits::list(&repo)?;
            let commit = history.first().unwrap();
            let path_str = format!("{}/annotations/train/one_shot.csv", commit.id);
            let path = Path::new(&path_str);

            match resource::parse_resource(&repo, path) {
                Ok(Some((commit_id, _, path))) => {
                    assert_eq!(commit.id, commit_id);
                    assert_eq!(path, Path::new("annotations/train/one_shot.csv"));
                }
                _ => {
                    panic!("Should return a commit");
                }
            }

            Ok(())
        })
    }

    #[test]
    fn test_parse_resource_for_branch() -> Result<(), OxenError> {
        crate::test::run_training_data_repo_test_fully_committed(|repo| {
            let branch_name = "my-branch";
            let branch = api::local::branches::create_checkout(&repo, branch_name)?;

            let path_str = format!("{branch_name}/annotations/train/one_shot.csv");
            let path = Path::new(&path_str);

            match resource::parse_resource(&repo, path) {
                Ok(Some((commit_id, _branch_name, path))) => {
                    println!("Got branch: {branch:?} -> {path:?}");
                    assert_eq!(branch.commit_id, commit_id);
                    assert_eq!(path, Path::new("annotations/train/one_shot.csv"));
                }
                _ => {
                    panic!("Should return a branch");
                }
            }

            Ok(())
        })
    }

    #[test]
    fn test_parse_resource_for_long_branch_name() -> Result<(), OxenError> {
        crate::test::run_training_data_repo_test_fully_committed(|repo| {
            let branch_name = "my/crazy/branch/name";
            let branch = api::local::branches::create_checkout(&repo, branch_name)?;

            let path_str = format!("{branch_name}/annotations/train/one_shot.csv");
            let path = Path::new(&path_str);

            match resource::parse_resource(&repo, path) {
                Ok(Some((commit_id, _branch_name, path))) => {
                    println!("Got branch: {branch:?} -> {path:?}");
                    assert_eq!(branch.commit_id, commit_id);
                    assert_eq!(path, Path::new("annotations/train/one_shot.csv"));
                }
                _ => {
                    panic!("Should return a branch");
                }
            }

            Ok(())
        })
    }

    #[test]
    fn test_parse_resource_for_branch_base_dir() -> Result<(), OxenError> {
        crate::test::run_training_data_repo_test_fully_committed(|repo| {
            let branch_name = "my_branch";
            let branch = api::local::branches::create_checkout(&repo, branch_name)?;

            let path_str = branch_name.to_string();
            let path = Path::new(&path_str);

            match resource::parse_resource(&repo, path) {
                Ok(Some((commit_id, _branch_name, path))) => {
                    println!("Got branch: {branch:?} -> {path:?}");
                    assert_eq!(branch.commit_id, commit_id);
                    assert_eq!(path, Path::new(""));
                }
                _ => {
                    panic!("Should return a branch");
                }
            }

            Ok(())
        })
    }

    #[test]
    fn test_parse_resource_from_path_root_dir() -> Result<(), OxenError> {
        crate::test::run_training_data_repo_test_fully_committed(|repo| {
            let branch_name = "main";
            // let branch = api::local::branches::create_checkout(&repo, branch_name)?;

            let path_str = format!("{branch_name}/");
            let path = Path::new(&path_str);

            match resource::parse_resource_from_path(&repo, path) {
                Ok(Some(resource)) => {
                    assert_eq!(resource.file_path, Path::new(""))
                }
                _ => {
                    panic!("Should return a parsed resource");
                }
            }

            Ok(())
        })
    }

    #[test]
    fn test_parse_resource_from_path_root_dir_complicated_branch() -> Result<(), OxenError> {
        crate::test::run_training_data_repo_test_fully_committed(|repo| {
            let branch_name = "super/complex/branch-name/slashes";
            let _branch = api::local::branches::create_checkout(&repo, branch_name)?;

            let path_str = format!("{branch_name}/");
            let path = Path::new(&path_str);

            match resource::parse_resource_from_path(&repo, path) {
                Ok(Some(resource)) => {
                    assert_eq!(resource.file_path, Path::new(""))
                }
                _ => {
                    panic!("Should return a parsed resource");
                }
            }

            Ok(())
        })
    }

    #[test]
    fn test_parse_resource_from_path_nonroot_complicated_branch() -> Result<(), OxenError> {
        crate::test::run_training_data_repo_test_fully_committed(|repo| {
            let branch_name = "super/complex/branch-name/slashes";
            let _branch = api::local::branches::create_checkout(&repo, branch_name)?;

            let path_str = format!("{branch_name}/folder-new");
            let path = Path::new(&path_str);

            match resource::parse_resource_from_path(&repo, path) {
                Ok(Some(resource)) => {
                    assert_eq!(resource.file_path, Path::new("folder-new"))
                }
                _ => {
                    panic!("Should return a parsed resource");
                }
            }

            Ok(())
        })
    }

    #[test]
    fn test_parse_resource_from_path_with_file() -> Result<(), OxenError> {
        crate::test::run_training_data_repo_test_fully_committed(|repo| {
            let branch_name = "super/complex/branch-name/slashes";
            let _branch = api::local::branches::create_checkout(&repo, branch_name)?;

            let path_str = format!("{branch_name}/folder/item.txt");
            let path = Path::new(&path_str);

            match resource::parse_resource_from_path(&repo, path) {
                Ok(Some(resource)) => {
                    assert_eq!(resource.file_path, Path::new("folder/item.txt"))
                }
                _ => {
                    panic!("Should return a parsed resource");
                }
            }

            Ok(())
        })
    }
}