|
| 1 | +use std::{ |
| 2 | + fs, io, |
| 3 | + path::{Path, PathBuf}, |
| 4 | +}; |
| 5 | + |
| 6 | +#[derive(Clone)] |
| 7 | +pub struct BuildStamp { |
| 8 | + path: PathBuf, |
| 9 | + stamp: String, |
| 10 | +} |
| 11 | + |
| 12 | +impl From<BuildStamp> for PathBuf { |
| 13 | + fn from(value: BuildStamp) -> Self { |
| 14 | + value.path |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +impl AsRef<Path> for BuildStamp { |
| 19 | + fn as_ref(&self) -> &Path { |
| 20 | + &self.path |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +impl BuildStamp { |
| 25 | + pub fn new(dir: &Path) -> Self { |
| 26 | + Self { path: dir.join(".stamp"), stamp: String::new() } |
| 27 | + } |
| 28 | + |
| 29 | + pub fn with_stamp(mut self, stamp: String) -> Self { |
| 30 | + self.stamp = stamp; |
| 31 | + self |
| 32 | + } |
| 33 | + |
| 34 | + pub fn with_prefix(mut self, prefix: &str) -> Self { |
| 35 | + assert!( |
| 36 | + !prefix.starts_with('.') && !prefix.ends_with('.'), |
| 37 | + "prefix can not start or end with '.'" |
| 38 | + ); |
| 39 | + |
| 40 | + let stamp_filename = self.path.components().last().unwrap().as_os_str().to_str().unwrap(); |
| 41 | + let stamp_filename = stamp_filename.strip_prefix('.').unwrap_or(stamp_filename); |
| 42 | + self.path.set_file_name(format!(".{prefix}-{stamp_filename}")); |
| 43 | + |
| 44 | + self |
| 45 | + } |
| 46 | + |
| 47 | + pub fn remove(self) -> io::Result<()> { |
| 48 | + match fs::remove_file(&self.path) { |
| 49 | + Ok(()) => Ok(()), |
| 50 | + Err(e) => { |
| 51 | + if e.kind() == io::ErrorKind::NotFound { |
| 52 | + Ok(()) |
| 53 | + } else { |
| 54 | + Err(e) |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + pub fn write(&self) -> io::Result<()> { |
| 61 | + fs::write(&self.path, &self.stamp) |
| 62 | + } |
| 63 | + |
| 64 | + pub fn is_up_to_date(&self) -> bool { |
| 65 | + match fs::read(&self.path) { |
| 66 | + Ok(h) => self.stamp.as_bytes() == h.as_slice(), |
| 67 | + Err(e) if e.kind() == io::ErrorKind::NotFound => false, |
| 68 | + Err(e) => { |
| 69 | + panic!("failed to read stamp file `{}`: {}", self.path.display(), e); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments