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