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