gix-worktree-stream-0.12.0/.cargo_vcs_info.json0000644000000001610000000000100150320ustar { "git": { "sha1": "095c6739b2722a8b9af90776b435ef2da454c0e6" }, "path_in_vcs": "gix-worktree-stream" }gix-worktree-stream-0.12.0/Cargo.toml0000644000000025210000000000100130320ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.65" name = "gix-worktree-stream" version = "0.12.0" authors = ["Sebastian Thiel "] include = [ "src/**/*", "LICENSE-*", ] description = "generate a byte-stream from a git-tree" license = "MIT OR Apache-2.0" repository = "https://github.com/Byron/gitoxide" [lib] doctest = false [dependencies.gix-attributes] version = "^0.22.2" [dependencies.gix-features] version = "^0.38.1" features = [ "progress", "io-pipe", ] [dependencies.gix-filter] version = "^0.11.1" [dependencies.gix-fs] version = "^0.10.2" [dependencies.gix-hash] version = "^0.14.2" [dependencies.gix-object] version = "^0.42.0" [dependencies.gix-path] version = "^0.10.7" [dependencies.gix-traverse] version = "^0.39.0" [dependencies.parking_lot] version = "0.12.1" [dependencies.thiserror] version = "1.0.26" [dev-dependencies] gix-worktree-stream-0.12.0/Cargo.toml.orig000064400000000000000000000021461046102023000165160ustar 00000000000000[package] name = "gix-worktree-stream" version = "0.12.0" repository = "https://github.com/Byron/gitoxide" license = "MIT OR Apache-2.0" description = "generate a byte-stream from a git-tree" authors = ["Sebastian Thiel "] edition = "2021" rust-version = "1.65" include = ["src/**/*", "LICENSE-*"] [lib] doctest = false [dependencies] gix-features = { version = "^0.38.1", path = "../gix-features", features = ["progress", "io-pipe"] } gix-hash = { version = "^0.14.2", path = "../gix-hash" } gix-object = { version = "^0.42.0", path = "../gix-object" } gix-attributes = { version = "^0.22.2", path = "../gix-attributes" } gix-filter = { version = "^0.11.1", path = "../gix-filter" } gix-traverse = { version = "^0.39.0", path = "../gix-traverse" } gix-fs = { version = "^0.10.2", path = "../gix-fs" } gix-path = { version = "^0.10.7", path = "../gix-path" } thiserror = "1.0.26" parking_lot = "0.12.1" [dev-dependencies] gix-testtools = { path = "../tests/tools"} gix-odb = { path = "../gix-odb"} gix-worktree = { path = "../gix-worktree", default-features = false, features = ["attributes"]} gix-worktree-stream-0.12.0/LICENSE-APACHE000064400000000000000000000247461046102023000155650ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. gix-worktree-stream-0.12.0/LICENSE-MIT000064400000000000000000000017771046102023000152740ustar 00000000000000Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. gix-worktree-stream-0.12.0/src/entry.rs000064400000000000000000000125541046102023000161310ustar 00000000000000use std::{ io::{ErrorKind, Read}, path::PathBuf, }; use gix_object::bstr::{BStr, BString}; use crate::{protocol, Entry, Stream}; /// The error returned by [`next_entry()`][Stream::next_entry()]. #[derive(Debug, thiserror::Error)] #[allow(missing_docs)] pub enum Error { #[error(transparent)] Io(#[from] std::io::Error), #[error("Could not find a tree's leaf, typically a blob")] Find(#[from] gix_object::find::existing::Error), #[error("Could not find a tree to traverse")] FindTree(#[from] gix_object::find::existing_iter::Error), #[error("Could not query attributes for path \"{path}\"")] Attributes { path: BString, source: Box, }, #[error(transparent)] Traverse(#[from] gix_traverse::tree::breadthfirst::Error), #[error(transparent)] ConvertToWorktree(#[from] gix_filter::pipeline::convert::to_worktree::Error), } impl Stream { /// Access the next entry of the stream or `None` if there is nothing more to read. pub fn next_entry(&mut self) -> Result>, Error> { assert!( self.path_buf.is_some(), "BUG: must consume and drop entry before getting the next one" ); self.extra_entries.take(); let res = protocol::read_entry_info( &mut self.read, self.path_buf.as_mut().expect("set while producing an entry"), ); match res { Ok((remaining, mode, id)) => { if let Some(err) = self.err.lock().take() { return Err(err); } Ok(Some(Entry { path_buf: self.path_buf.take(), parent: self, id, mode, remaining, })) } Err(err) => { if let Some(err) = self.err.lock().take() { return Err(err); } // unexpected EOF means the other side dropped. We handled potential errors already. if err.kind() == ErrorKind::UnexpectedEof { return Ok(None); } Err(err.into()) } } } } /// The source of an additional entry pub enum Source { /// There is no content, typically the case with directories which are always considered empty. Null, /// Read from the file at the given path. Path(PathBuf), /// Read from memory. Memory(Vec), } impl Source { pub(crate) fn len(&self) -> Option { match self { Source::Null => Some(0), Source::Path(_) => None, Source::Memory(buf) => Some(buf.len()), } } } impl std::fmt::Debug for Entry<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Entry") .field("path_buf", &self.relative_path()) .field("mode", &self.mode) .field("id", &self.id) .field("remaining", &self.remaining) .finish() } } impl Entry<'_> { /// Return the path of this entry as slash-separated path relative to the repository. pub fn relative_path(&self) -> &BStr { self.path_buf.as_ref().expect("always set during our lifetime").as_ref() } /// The amount of bytes that remain to be read, or `None` if it's fully streamed. /// /// This equals the length of the entry in bytes right before reading it. pub fn bytes_remaining(&self) -> Option { self.remaining } } impl<'a> Drop for Entry<'a> { fn drop(&mut self) { if self.remaining == Some(0) { self.parent.path_buf = self.path_buf.take(); } } } impl Entry<'_> { fn fill_buf(&mut self) -> std::io::Result<&[u8]> { if self.parent.pos >= self.parent.filled { let mut u16_buf = [0; 2]; self.parent.read.read_exact(&mut u16_buf)?; let nb = u16::from_le_bytes(u16_buf) as usize; if nb != 0 { self.parent.read.read_exact(&mut self.parent.buf[..nb])?; } self.parent.filled = nb; self.parent.pos = 0; } Ok(&self.parent.buf[self.parent.pos..self.parent.filled]) } } impl std::io::Read for Entry<'_> { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { let buf_len = buf.len(); if let Some(err) = self.parent.err.lock().take() { return Err(std::io::Error::new(ErrorKind::Other, err)); } let bytes_read = match self.remaining.as_mut() { None => { // We expect a zero-read to indicate the end of stream, which is the default way of streams to end. // In our case though, it requires sending an extra zero-write, so we avoid that usually. let input = self.fill_buf()?; let nb = input.len().min(buf.len()); buf[..nb].copy_from_slice(&input[..nb]); self.parent.pos += nb; nb } Some(remaining) => { let bytes_read = self.parent.read.read(&mut buf[..buf_len.min(*remaining)])?; *remaining -= bytes_read; bytes_read } }; if bytes_read == 0 { self.remaining = Some(0); } Ok(bytes_read) } } gix-worktree-stream-0.12.0/src/from_tree/mod.rs000064400000000000000000000121251046102023000175230ustar 00000000000000use std::io::Write; use gix_object::{bstr::BStr, FindExt}; use crate::{entry, entry::Error, protocol, AdditionalEntry, SharedErrorSlot, Stream}; /// Use `objects` to traverse `tree` and fetch the contained blobs to return as [`Stream`], which makes them queryable /// on demand with support for streaming each entry. /// /// `pipeline` is used to convert blobs to their worktree representation, and `attributes` is used to read /// the `export-ignore` attribute. If set on a directory or blob, it won't be added to the archive. /// /// ### Types of entries in stream /// /// We only return blobs (with or without executable), which may be symlinks in which case their content will /// be target of the symlink. /// Directories are never returned, but maybe added by the caller via [Stream::add_entry()]. /// /// ### Progress and interruptions /// /// For per-file progress, integrate progress handling into the calls of [`Stream::next_entry()`] as that /// correlates blobs. /// Additional interrupt handling can be wrapped around the `Read` implementation of each [`Entry`][crate::Entry]. /// For progress on bytes-written, integrate progress reporting when consuming the stream. /// Further it's possible to drop the returned [`Stream`] to halt all operation. /// /// ### Threaded Operation /// /// This function spawns a thread that will access the tree data in the background, synchronized through /// `Stream` so that it will not be faster than the consumer, with at most one file in flight at any time. /// /// ### Limitations /// /// * `export-subst` is not support, as it requires the entire formatting engine of `git log`. pub fn from_tree( tree: gix_hash::ObjectId, objects: Find, pipeline: gix_filter::Pipeline, attributes: impl FnMut(&BStr, gix_object::tree::EntryMode, &mut gix_attributes::search::Outcome) -> Result<(), E> + Send + 'static, ) -> Stream where Find: gix_object::Find + Clone + Send + 'static, E: std::error::Error + Send + Sync + 'static, { let (stream, mut write, additional_entries) = Stream::new(); std::thread::spawn({ let slot = stream.err.clone(); move || { if let Err(err) = run( tree, objects, pipeline, attributes, &mut write, slot.clone(), additional_entries, ) { { let mut slot = slot.lock(); if slot.is_none() { *slot = Some(err); } else { drop(slot); write .channel .send(Err(std::io::Error::new(std::io::ErrorKind::Other, err))) .ok(); } } } } }); stream } fn run( tree: gix_hash::ObjectId, objects: Find, mut pipeline: gix_filter::Pipeline, mut attributes: impl FnMut(&BStr, gix_object::tree::EntryMode, &mut gix_attributes::search::Outcome) -> Result<(), E> + Send + 'static, out: &mut gix_features::io::pipe::Writer, err: SharedErrorSlot, additional_entries: std::sync::mpsc::Receiver, ) -> Result<(), Error> where Find: gix_object::Find + Clone, E: std::error::Error + Send + Sync + 'static, { let mut buf = Vec::new(); let tree_iter = objects.find_tree_iter(tree.as_ref(), &mut buf)?; if pipeline.driver_context_mut().treeish.is_none() { pipeline.driver_context_mut().treeish = Some(tree); } let mut attrs = gix_attributes::search::Outcome::default(); attrs.initialize_with_selection(&Default::default(), Some("export-ignore")); let mut dlg = traverse::Delegate { out, err, pipeline, attrs, objects: objects.clone(), fetch_attributes: move |a: &BStr, b: gix_object::tree::EntryMode, c: &mut gix_attributes::search::Outcome| { attributes(a, b, c).map_err(|err| Error::Attributes { source: Box::new(err), path: a.to_owned(), }) }, path_deque: Default::default(), path: Default::default(), buf: Vec::with_capacity(1024), }; gix_traverse::tree::breadthfirst( tree_iter, gix_traverse::tree::breadthfirst::State::default(), &objects, &mut dlg, )?; for entry in additional_entries { protocol::write_entry_header_and_path( entry.relative_path.as_ref(), &entry.id, entry.mode, entry.source.len(), out, )?; // pipe writer always writes all in one go. #[allow(clippy::unused_io_amount)] match entry.source { entry::Source::Memory(buf) => out.write(&buf).map(|_| ()), entry::Source::Null => out.write(&[]).map(|_| ()), entry::Source::Path(path) => { let file = std::fs::File::open(path)?; protocol::write_stream(&mut buf, file, out) } }? } Ok(()) } mod traverse; gix-worktree-stream-0.12.0/src/from_tree/traverse.rs000064400000000000000000000113771046102023000206070ustar 00000000000000use std::{collections::VecDeque, io::Write}; use gix_filter::{driver::apply::MaybeDelayed, pipeline::convert::ToWorktreeOutcome}; use gix_object::{ bstr::{BStr, BString, ByteSlice, ByteVec}, tree, FindExt, }; use gix_traverse::tree::{visit::Action, Visit}; use crate::{entry::Error, protocol, SharedErrorSlot}; pub struct Delegate<'a, AttributesFn, Find> where Find: gix_object::Find, { pub(crate) out: &'a mut gix_features::io::pipe::Writer, pub(crate) err: SharedErrorSlot, pub(crate) path_deque: VecDeque, pub(crate) path: BString, pub(crate) pipeline: gix_filter::Pipeline, pub(crate) attrs: gix_attributes::search::Outcome, pub(crate) fetch_attributes: AttributesFn, pub(crate) objects: Find, pub(crate) buf: Vec, } impl Delegate<'_, AttributesFn, Find> where Find: gix_object::Find, AttributesFn: FnMut(&BStr, gix_object::tree::EntryMode, &mut gix_attributes::search::Outcome) -> Result<(), Error> + 'static, { fn pop_element(&mut self) { if let Some(pos) = self.path.rfind_byte(b'/') { self.path.resize(pos, 0); } else { self.path.clear(); } } fn push_element(&mut self, name: &BStr) { if !self.path.is_empty() { self.path.push(b'/'); } self.path.push_str(name); } /// Return the state of the `export-ignore` attribute. fn ignore_state(&self) -> gix_attributes::StateRef<'_> { self.attrs .iter_selected() .next() .expect("initialized with one attr") .assignment .state } fn handle_entry(&mut self, entry: &tree::EntryRef<'_>) -> Result { if !entry.mode.is_blob_or_symlink() { return Ok(Action::Continue); } (self.fetch_attributes)(self.path.as_ref(), entry.mode, &mut self.attrs)?; if self.ignore_state().is_set() { return Ok(Action::Continue); } self.objects.find(entry.oid, &mut self.buf)?; self.pipeline.driver_context_mut().blob = Some(entry.oid.into()); let converted = self.pipeline.convert_to_worktree( &self.buf, self.path.as_ref(), &mut |a, b| { (self.fetch_attributes)(a, entry.mode, b).ok(); }, gix_filter::driver::apply::Delay::Forbid, )?; // Our pipe writer always writes the whole amount. #[allow(clippy::unused_io_amount)] match converted { ToWorktreeOutcome::Unchanged(buf) | ToWorktreeOutcome::Buffer(buf) => { protocol::write_entry_header_and_path( self.path.as_ref(), entry.oid, entry.mode, Some(buf.len()), self.out, )?; self.out.write(buf)?; } ToWorktreeOutcome::Process(MaybeDelayed::Immediate(read)) => { protocol::write_entry_header_and_path(self.path.as_ref(), entry.oid, entry.mode, None, self.out)?; protocol::write_stream(&mut self.buf, read, self.out)?; } ToWorktreeOutcome::Process(MaybeDelayed::Delayed(_)) => { unreachable!("we forbade it") } } Ok(Action::Continue) } } impl Visit for Delegate<'_, AttributesFn, Find> where Find: gix_object::Find, AttributesFn: FnMut(&BStr, gix_object::tree::EntryMode, &mut gix_attributes::search::Outcome) -> Result<(), Error> + 'static, { fn pop_front_tracked_path_and_set_current(&mut self) { self.path = self .path_deque .pop_front() .expect("every call is matched with push_tracked_path_component"); } fn push_back_tracked_path_component(&mut self, component: &BStr) { self.push_element(component); self.path_deque.push_back(self.path.clone()); } fn push_path_component(&mut self, component: &BStr) { self.push_element(component); } fn pop_path_component(&mut self) { self.pop_element() } fn visit_tree(&mut self, entry: &tree::EntryRef<'_>) -> Action { if let Err(err) = (self.fetch_attributes)(self.path.as_ref(), entry.mode, &mut self.attrs) { *self.err.lock() = Some(err); Action::Cancel } else if self.ignore_state().is_set() { Action::Skip } else { Action::Continue } } fn visit_nontree(&mut self, entry: &tree::EntryRef<'_>) -> Action { match self.handle_entry(entry) { Ok(action) => action, Err(err) => { *self.err.lock() = Some(err); Action::Cancel } } } } gix-worktree-stream-0.12.0/src/lib.rs000064400000000000000000000201631046102023000155310ustar 00000000000000//! The implementation of creating an archive from a git tree, similar to `git archive`, but using an internal format. //! //! This crate can effectively be used to manipulate worktrees as streams of bytes, which can be decoded using the [`Stream`] type. #![deny(rust_2018_idioms, missing_docs, unsafe_code)] use std::{path::Path, sync::Arc}; use gix_object::bstr::BString; /// A stream of entries that originate from a git tree and optionally from additional entries. /// /// Note that a git tree is mandatory, but the empty tree can be used to effectively disable it. pub struct Stream { read: utils::Read, err: SharedErrorSlot, extra_entries: Option>, // additional_entries: Vec, /// `None` if currently held by an entry. path_buf: Option, /// Another buffer to partially act like a buf-reader. buf: Vec, /// The offset into `buf` for entries being able to act like a buf reader. pos: usize, /// The amount of bytes usable from `buf` (even though it always has a fixed size) filled: usize, } /// #[allow(clippy::empty_docs)] pub mod entry; pub(crate) mod protocol; mod from_tree; pub use from_tree::from_tree; pub(crate) type SharedErrorSlot = Arc>>; /// An entry in a stream. Note that they must be consumed fully, by reading from them till exhaustion. /// /// ### Drop behaviour /// /// If the entry is dropped without reading it till exhaustion, the stream is tainted and /// [`next_entry()`][Stream::next_entry()] will panic next time it is called. pub struct Entry<'a> { /// The kind of entry at [`relative_path`][Self::relative_path()]. pub mode: gix_object::tree::EntryMode, /// The hash of the object, uniquely identifying it. pub id: gix_hash::ObjectId, /// Access to our parent parent: &'a mut Stream, /// The path relative to the repository at which data should be written. path_buf: Option, /// The amount of bytes left to read if the size of bytes to read is known. /// It's also our marker to say that we are depleted, which is important to signal to the /// parent stream that we can proceed reading the next entry. remaining: Option, } /// An entry that is [added to the stream][Stream::add_entry()] by the user, verbatim, without additional worktree conversions. /// /// It may overwrite previously written paths, which may or may not work for the consumer of the stream. pub struct AdditionalEntry { /// The hash of the object, uniquely identifying it. /// Note that it can be [`null()`][gix_hash::ObjectId::null()] as the hash is typically ignored by consumers of the stream. pub id: gix_hash::ObjectId, /// The kind of entry to create. pub mode: gix_object::tree::EntryMode, /// The path relative to the repository at which content should be located. pub relative_path: BString, /// Where to get the content of the entry from. pub source: entry::Source, } /// Lifecycle impl Stream { /// Turn ourselves into the underlying byte stream which is a representation of the underlying git tree. /// /// Note that the format is unspecified, and its sole use is for transport, not for persistence. /// Can be used with [`Self::from_read()`] to decode the contained entries. pub fn into_read(self) -> impl std::io::Read { self.read } /// Return our internal byte stream from which entries would be generated. /// /// Note that the stream must then be consumed in its entirety. pub fn as_read_mut(&mut self) -> &mut impl std::io::Read { self.extra_entries.take(); &mut self.read } /// Create a new instance from a stream of bytes in our format. /// /// It must have been created from [`Self::into_read()`] to be compatible, and must /// not have been persisted. pub fn from_read(read: impl std::io::Read + 'static) -> Self { Self { read: utils::Read::Unknown(Box::new(read)), extra_entries: None, path_buf: Some(Vec::with_capacity(1024).into()), err: Default::default(), buf: std::iter::repeat(0).take(u16::MAX as usize).collect(), pos: 0, filled: 0, } } } /// Entries impl Stream { /// Add `entry` to the list of entries to be returned in calls to [`Self::next_entry()`]. /// /// The entry will be returned after the one contained in the tree, in order of addition. /// # Panics /// If called after the first call to [`Self::next_entry()`]. pub fn add_entry(&mut self, entry: AdditionalEntry) -> &mut Self { self.extra_entries .as_ref() .expect("BUG: must not add entries after the start of entries traversal") .send(entry) .expect("Failure is impossible as thread blocks on the receiving end"); self } /// Add the item at `path` as entry to this stream, which is expected to be under `root`. /// /// Note that the created entries will always have a null SHA1, and that we access this path /// to determine its type, and will access it again when it is requested. pub fn add_entry_from_path(&mut self, root: &Path, path: &Path) -> std::io::Result<&mut Self> { let rela_path = path .strip_prefix(root) .map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err))?; let meta = path.symlink_metadata()?; let relative_path = gix_path::to_unix_separators_on_windows(gix_path::into_bstr(rela_path)).into_owned(); let id = gix_hash::ObjectId::null(gix_hash::Kind::Sha1); let entry = if meta.is_symlink() { let content = std::fs::read_link(path)?; let content = gix_path::into_bstr(content).into_owned(); AdditionalEntry { id, mode: gix_object::tree::EntryKind::Link.into(), relative_path, source: entry::Source::Memory(content.into()), } } else if meta.is_dir() { AdditionalEntry { id, mode: gix_object::tree::EntryKind::Tree.into(), relative_path, source: entry::Source::Null, } } else { let mode = if gix_fs::is_executable(&meta) { gix_object::tree::EntryKind::BlobExecutable } else { gix_object::tree::EntryKind::Blob } .into(); AdditionalEntry { id, mode, relative_path, source: entry::Source::Path(path.to_owned()), } }; Ok(self.add_entry(entry)) } } impl Stream { pub(crate) fn new() -> ( Stream, gix_features::io::pipe::Writer, std::sync::mpsc::Receiver, ) { // 1 write for entry header and 1 for hash, 1 for entry path, + 1 for a buffer, then 32 of these. // Giving some buffer, at the expense of memory, is important to allow consumers to take off bytes more quickly, // otherwise, both threads effectively run in lock-step and nullify the benefit. let in_flight_writes = (2 + 1) * 32; let (write, read) = gix_features::io::pipe::unidirectional(in_flight_writes); let (tx_entries, rx_entries) = std::sync::mpsc::channel(); ( Stream { read: utils::Read::Known(read), extra_entries: Some(tx_entries), path_buf: Some(Vec::with_capacity(1024).into()), err: Default::default(), buf: std::iter::repeat(0).take(u16::MAX as usize).collect(), pos: 0, filled: 0, }, write, rx_entries, ) } } pub(crate) mod utils { pub enum Read { Known(gix_features::io::pipe::Reader), Unknown(Box), } impl std::io::Read for Read { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { match self { Read::Known(r) => r.read(buf), Read::Unknown(r) => r.read(buf), } } } } gix-worktree-stream-0.12.0/src/protocol.rs000064400000000000000000000103011046102023000166150ustar 00000000000000use crate::utils; use gix_object::bstr::{BStr, BString}; use std::io::{self, ErrorKind, Read, Write}; // Format: [usize-LE][usize-LE][byte][byte][hash][relative_path_bytes][object_stream] // Note that stream_len can be usize::MAX to indicate the stream size is unknown pub(crate) fn read_entry_info( read: &mut utils::Read, path_buf: &mut BString, ) -> std::io::Result<(Option, gix_object::tree::EntryMode, gix_hash::ObjectId)> { let mut buf = [0; std::mem::size_of::() * 2 + 2]; read.read_exact(&mut buf)?; let (path_len, rest) = buf.split_at(std::mem::size_of::()); let (stream_len, bytes) = rest.split_at(std::mem::size_of::()); let path_len = usize::from_le_bytes(path_len.try_into().expect("valid")); let stream_size = usize::from_le_bytes(stream_len.try_into().expect("valid")); let mode = byte_to_mode(bytes[0]); let hash_kind = byte_to_hash(bytes[1]); let mut hash = hash_kind.null(); read.read_exact(hash.as_mut_slice())?; clear_and_set_len(path_buf, path_len)?; read.read_exact(path_buf)?; Ok(((stream_size != usize::MAX).then_some(stream_size), mode, hash)) } /// This function must match the read-count of `read_entry_info` for max efficiency. pub(crate) fn write_entry_header_and_path( path: &BStr, oid: &gix_hash::oid, mode: gix_object::tree::EntryMode, stream_len: Option, out: &mut gix_features::io::pipe::Writer, ) -> std::io::Result<()> { const HEADER_LEN: usize = std::mem::size_of::() * 2 + 2; let mut buf = [0u8; HEADER_LEN + gix_hash::Kind::longest().len_in_bytes()]; let (path_len_buf, rest) = buf.split_at_mut(std::mem::size_of::()); let (stream_len_buf, bytes) = rest.split_at_mut(std::mem::size_of::()); path_len_buf.copy_from_slice(&path.len().to_le_bytes()); stream_len_buf.copy_from_slice(&stream_len.unwrap_or(usize::MAX).to_le_bytes()); bytes[0] = mode_to_byte(mode); bytes[1] = hash_to_byte(oid.kind()); bytes[2..][..oid.kind().len_in_bytes()].copy_from_slice(oid.as_bytes()); // We know how `out` works in a pipe writer, it's always writing everything. #[allow(clippy::unused_io_amount)] { out.write(&buf[..HEADER_LEN + oid.kind().len_in_bytes()])?; out.write(path)?; } Ok(()) } /// This writes everything in `input` in such way that the receiver knows exactly how much to read. /// The format is similar to the packetline format, but in binary. pub(crate) fn write_stream( buf: &mut Vec, mut input: impl std::io::Read, out: &mut gix_features::io::pipe::Writer, ) -> std::io::Result<()> { const BUF_LEN: usize = u16::MAX as usize; clear_and_set_len(buf, BUF_LEN)?; // We know how `out` works in a pipe writer, it's always writing everything. #[allow(clippy::unused_io_amount)] loop { match input.read(buf) { Ok(0) => { // terminator out.write(&0_u16.to_le_bytes())?; break; } Ok(n) => { out.write(&(n as u16).to_le_bytes())?; out.write(&buf[..n])?; } Err(ref e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return Err(e), } } Ok(()) } fn byte_to_hash(b: u8) -> gix_hash::Kind { match b { 0 => gix_hash::Kind::Sha1, _ => unreachable!("BUG: we control the protocol"), } } fn byte_to_mode(b: u8) -> gix_object::tree::EntryMode { use gix_object::tree::EntryKind::*; match b { 0 => Tree, 1 => Blob, 2 => BlobExecutable, 3 => Link, 4 => Commit, _ => unreachable!("BUG: we control the protocol"), } .into() } fn hash_to_byte(h: gix_hash::Kind) -> u8 { match h { gix_hash::Kind::Sha1 => 0, } } fn mode_to_byte(m: gix_object::tree::EntryMode) -> u8 { use gix_object::tree::EntryKind::*; match m.kind() { Tree => 0, Blob => 1, BlobExecutable => 2, Link => 3, Commit => 4, } } fn clear_and_set_len(buf: &mut Vec, len: usize) -> io::Result<()> { buf.clear(); buf.try_reserve(len).map_err(|_| ErrorKind::OutOfMemory)?; buf.resize(len, 0); Ok(()) }