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
/* Copyright (c) 2020 aspen <luxx4x@protonmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #![forbid(unsafe_code)] #![deny( clippy::complexity, clippy::correctness, clippy::perf, clippy::style, broken_intra_doc_links )] use std::{ collections::BTreeMap, convert::AsRef, fmt::{self, Display}, path::{Path, PathBuf}, }; #[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord, Default)] pub struct Sfv { /// The file paths and their checksums/hashes pub files: BTreeMap<PathBuf, Vec<u8>>, } impl Sfv { /// Create a new, empty [Sfv] object pub fn new() -> Self { Self::default() } /// Convert a SFV file in string format to a [Sfv] object. /// /// ```rust /// use sfv::Sfv; /// use std::collections::BTreeMap; /// use std::path::PathBuf; /// /// let sfv_file = r#" /// ; This is a comment /// file_one.zip c45ad668 /// file_two.zip 7903b8e6 /// file_three.zip e99a65fb /// "#; /// /// let sfv = Sfv::from_sfv("/test", sfv_file).unwrap(); /// assert_eq!( /// *sfv.files.get(&PathBuf::from("/test/file_one.zip")).unwrap(), /// vec![0xc4, 0x5a, 0xd6, 0x68] /// ) /// ``` pub fn from_sfv<P: AsRef<Path>, S: AsRef<str>>(base_directory: P, sfv: S) -> Result<Self, ()> { Self::from_sfv_impl(base_directory.as_ref().to_path_buf(), sfv.as_ref()) } fn from_sfv_impl(base_directory: PathBuf, sfv: &str) -> Result<Self, ()> { let mut files: BTreeMap<PathBuf, Vec<u8>> = BTreeMap::new(); sfv // Trim the file's training/leading whitespace .trim() // Split the file into each line .lines() // Trim all the leading/trailing whitespace .map(str::trim) // Filter out all comments .filter(|line| !line.starts_with(';')) // Now we do the actual parsing .try_for_each(|line| -> Result<(), ()> { // Split the line by it's whitespace (spaces/tabs/etc) let split = line.split_ascii_whitespace().collect::<Vec<&str>>(); // If there's not at least two entries, skip. if split.len() < 2 { return Ok(()); } let (file, checksum) = ( base_directory.join(split[0]), hex::decode(split[1]).map_err(|_| ())?, ); files.insert(file, checksum); Ok(()) })?; Ok(Self { files }) } /// Adds a file and checksum entry to the [Sfv]. /// /// ```rust /// use sfv::Sfv; /// use std::path::PathBuf; /// /// let mut sfv = Sfv::new(); /// let path = PathBuf::from("/test.txt"); /// let checksum: Vec<u8> = vec![0x42, 0x42, 0x42, 0x42]; /// sfv.add_file(&path, &checksum); /// /// assert_eq!( /// *sfv.files.get(&PathBuf::from("/test.txt")).unwrap(), /// vec![0x42, 0x42, 0x42, 0x42] /// ) /// ``` pub fn add_file<P: AsRef<Path>, D: AsRef<[u8]>>(&mut self, path: P, data: D) { self.add_file_impl(path.as_ref().to_path_buf(), data.as_ref()) } fn add_file_impl(&mut self, path: PathBuf, data: &[u8]) { self.files.insert(path, data.to_vec()); } } impl Display for Sfv { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f, "; Generated by sfv-rs {}", env!("CARGO_PKG_VERSION"))?; self.files .iter() .try_for_each(|(path, checksum)| -> fmt::Result { let path = path.to_string_lossy(); let checksum = hex::encode(checksum); writeln!(f, "{} {}", path, checksum) }) } }