Skip to main content

gix_shallow/
lib.rs

1//! [Read](read()) and [write](write()) shallow files, while performing typical operations on them.
2//!
3//! ## Examples
4//!
5//! ```
6//! # fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
7//! let first = gix_hash::ObjectId::from_hex(b"1111111111111111111111111111111111111111")?;
8//! let second = gix_hash::ObjectId::from_hex(b"2222222222222222222222222222222222222222")?;
9//! # let dir = tempfile::tempdir()?;
10//! # let shallow_file = dir.path().join("shallow");
11//! # std::fs::write(&shallow_file, format!("{first}\n"))?;
12//!
13//! let shallow = gix_shallow::read(&shallow_file)
14//!     .map_err(gix_error::Exn::into_error)?
15//!     .expect("a shallow boundary");
16//! let lock = gix_lock::File::acquire_to_update_resource(
17//!     &shallow_file,
18//!     gix_lock::acquire::Fail::Immediately,
19//!     None,
20//! )
21//! .map_err(|err| err.into_error())?;
22//! gix_shallow::write(lock, Some(shallow), &[gix_shallow::Update::Shallow(second)])
23//!     .map_err(gix_error::Exn::into_error)?;
24//!
25//! let ids = gix_shallow::read(&shallow_file)
26//!     .map_err(gix_error::Exn::into_error)?
27//!     .expect("a shallow boundary")
28//!     .into_iter()
29//!     .collect::<Vec<_>>();
30//! assert_eq!(ids, vec![first, second]);
31//! # Ok(()) }
32//! ```
33#![deny(missing_docs)]
34#![forbid(unsafe_code)]
35
36use gix_error::ExnResult;
37/// An instruction on how to
38#[derive(PartialEq, Eq, Debug, Hash, Ord, PartialOrd, Clone, Copy)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40pub enum Update {
41    /// Shallow the given `id`.
42    Shallow(gix_hash::ObjectId),
43    /// Don't shallow the given `id` anymore.
44    Unshallow(gix_hash::ObjectId),
45}
46
47/// Return a list of shallow commits as unconditionally read from `shallow_file`.
48///
49/// The list of shallow commits represents the shallow boundary, beyond which we are lacking all (parent) commits.
50/// Note that the list is never empty, as `Ok(None)` is returned in that case indicating the repository
51/// isn't a shallow clone.
52pub fn read(shallow_file: &std::path::Path) -> ExnResult<Option<nonempty::NonEmpty<gix_hash::ObjectId>>> {
53    use bstr::ByteSlice;
54    use gix_error::{ErrorExt, ResultExt, message};
55    let buf = match std::fs::read(shallow_file) {
56        Ok(buf) => buf,
57        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
58        Err(err) => {
59            return Err(err
60                .and_raise(message("Could not open shallow file for reading"))
61                .erased());
62        }
63    };
64
65    let mut commits = buf
66        .lines()
67        .map(gix_hash::ObjectId::from_hex)
68        .collect::<Result<Vec<_>, _>>()
69        .or_raise_erased(|| {
70            gix_error::corruption("Could not decode a line in shallow file as hex-encoded object hash")
71        })?;
72
73    commits.sort();
74    Ok(nonempty::NonEmpty::from_vec(commits))
75}
76
77///
78pub mod write {
79    pub(crate) mod function {
80        use std::io::Write;
81
82        use gix_error::{ErrorExt, ExnMessageResult, ResultExt, message};
83
84        use crate::Update;
85
86        /// Write the [previously obtained](crate::read()) (possibly non-existing) `shallow_commits` to the shallow `file`
87        /// after applying all `updates`.
88        ///
89        /// If this leaves the list of shallow commits empty, the file is removed.
90        ///
91        /// ### Deviation
92        ///
93        /// Git also prunes the set of shallow commits while writing, we don't until we support some sort of pruning.
94        pub fn write(
95            mut file: gix_lock::File,
96            shallow_commits: Option<nonempty::NonEmpty<gix_hash::ObjectId>>,
97            updates: &[Update],
98        ) -> ExnMessageResult {
99            let mut shallow_commits = shallow_commits.map(Vec::from).unwrap_or_default();
100            for update in updates {
101                match update {
102                    Update::Shallow(id) => {
103                        shallow_commits.push(*id);
104                    }
105                    Update::Unshallow(id) => shallow_commits.retain(|oid| oid != id),
106                }
107            }
108            if shallow_commits.is_empty() {
109                if let Err(err) = std::fs::remove_file(file.resource_path())
110                    && err.kind() != std::io::ErrorKind::NotFound
111                {
112                    return Err(err.and_raise(message("Could not remove an empty shallow file")));
113                }
114                drop(file);
115                return Ok(());
116            }
117            shallow_commits.sort();
118            let mut buf = Vec::<u8>::new();
119            for commit in shallow_commits {
120                commit
121                    .write_hex_to(&mut buf)
122                    .or_raise(|| message("Failed to write object id to shallow file"))?;
123                buf.push(b'\n');
124            }
125            file.write_all(&buf)
126                .or_raise(|| message("Failed to write object id to shallow file"))?;
127            file.flush()
128                .or_raise(|| message("Failed to write object id to shallow file"))?;
129            file.commit().or_raise(|| message("Could not commit shallow file"))?;
130            Ok(())
131        }
132    }
133}
134pub use write::function::write;