use std::path::PathBuf;
use std::collections::HashMap;
use crate::error::Result;
#[derive(Debug, Clone, PartialEq)]
pub struct IndexEntry {
pub blob_id: String,
pub mtime_secs: u64,
pub mtime_nanos: u32,
pub size: u64,
pub inode: u64,
}
impl IndexEntry {
pub fn matches_stat(&self, mtime_secs: u64, mtime_nanos: u32, size: u64, inode: u64) -> bool {
self.mtime_secs != 0
&& self.mtime_secs == mtime_secs
&& self.mtime_nanos == mtime_nanos
&& self.size == size
&& self.inode == inode
}
}
pub struct Index {
root: PathBuf,
entries: HashMap<String, IndexEntry>,
}
impl Index {
pub fn new(root: PathBuf) -> Self {
Self {
root,
entries: HashMap::new(),
}
}
fn index_path(&self) -> PathBuf {
self.root.join("index")
}
pub fn load(root: PathBuf) -> Result<Self> {
let path = root.join("index");
let entries = if path.exists() {
let data = std::fs::read_to_string(&path)?;
let mut map = HashMap::new();
for line in data.lines() {
let parts: Vec<&str> = line.split('\0').collect();
match parts.as_slice() {
[path, blob, secs, nanos, size, ino] => {
map.insert(
path.to_string(),
IndexEntry {
blob_id: blob.to_string(),
mtime_secs: secs.parse().unwrap_or(0),
mtime_nanos: nanos.parse().unwrap_or(0),
size: size.parse().unwrap_or(0),
inode: ino.parse().unwrap_or(0),
},
);
}
[path, blob] => {
map.insert(
path.to_string(),
IndexEntry {
blob_id: blob.to_string(),
mtime_secs: 0,
mtime_nanos: 0,
size: 0,
inode: 0,
},
);
}
_ => {}
}
}
map
} else {
HashMap::new()
};
Ok(Self { root, entries })
}
pub fn save(&self) -> Result<()> {
let path = self.index_path();
let mut data = String::new();
let mut paths: Vec<_> = self.entries.keys().collect();
paths.sort();
for p in paths {
if let Some(e) = self.entries.get(p) {
data.push_str(&format!(
"{}\0{}\0{}\0{}\0{}\0{}\n",
p, e.blob_id, e.mtime_secs, e.mtime_nanos, e.size, e.inode
));
}
}
crate::atomic::write_atomic(&path, data.as_bytes())?;
Ok(())
}
pub fn add(&mut self, path: &str, blob_id: &str) {
self.entries.insert(
path.to_string(),
IndexEntry {
blob_id: blob_id.to_string(),
mtime_secs: 0,
mtime_nanos: 0,
size: 0,
inode: 0,
},
);
}
pub fn add_staged(
&mut self,
path: &str,
blob_id: &str,
mtime_secs: u64,
mtime_nanos: u32,
size: u64,
inode: u64,
) {
self.entries.insert(
path.to_string(),
IndexEntry {
blob_id: blob_id.to_string(),
mtime_secs,
mtime_nanos,
size,
inode,
},
);
}
pub fn remove(&mut self, path: &str) {
self.entries.remove(path);
}
pub fn get(&self, path: &str) -> Option<&str> {
self.entries.get(path).map(|e| e.blob_id.as_str())
}
pub fn entry(&self, path: &str) -> Option<&IndexEntry> {
self.entries.get(path)
}
pub fn entries_sorted(&self) -> Vec<(String, String)> {
let mut entries: Vec<_> = self
.entries
.iter()
.map(|(k, v)| (k.clone(), v.blob_id.clone()))
.collect();
entries.sort_by(|a, b| a.0.cmp(&b.0));
entries
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn clear(&mut self) {
self.entries.clear();
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_index_add_and_get() {
let tmp = TempDir::new().unwrap();
let mut idx = Index::new(tmp.path().to_path_buf());
idx.add("src/main.rs", "abc123");
assert_eq!(idx.get("src/main.rs"), Some("abc123"));
assert_eq!(idx.get("src/other.rs"), None);
}
#[test]
fn test_index_remove() {
let tmp = TempDir::new().unwrap();
let mut idx = Index::new(tmp.path().to_path_buf());
idx.add("file.txt", "hash1");
idx.remove("file.txt");
assert_eq!(idx.get("file.txt"), None);
}
#[test]
fn test_index_save_and_load() {
let tmp = TempDir::new().unwrap();
let root = tmp.path().to_path_buf();
let mut idx = Index::new(root.clone());
idx.add("a.rs", "hash_a");
idx.add_staged("b.rs", "hash_b", 1700000000, 123, 456, 789);
idx.save().unwrap();
let loaded = Index::load(root).unwrap();
assert_eq!(loaded.get("a.rs"), Some("hash_a"));
assert_eq!(loaded.get("b.rs"), Some("hash_b"));
assert_eq!(loaded.len(), 2);
let b = loaded.entry("b.rs").unwrap();
assert_eq!(b.mtime_secs, 1700000000);
assert_eq!(b.mtime_nanos, 123);
assert_eq!(b.size, 456);
assert_eq!(b.inode, 789);
assert!(b.matches_stat(1700000000, 123, 456, 789));
assert!(!b.matches_stat(1700000000, 123, 457, 789));
let a = loaded.entry("a.rs").unwrap();
assert!(!a.matches_stat(0, 0, 0, 0));
}
#[test]
fn test_index_load_legacy_format() {
let tmp = TempDir::new().unwrap();
let root = tmp.path().to_path_buf();
std::fs::write(root.join("index"), "a.rs\0hash_a\nb.rs\0hash_b\n").unwrap();
let loaded = Index::load(root).unwrap();
assert_eq!(loaded.get("a.rs"), Some("hash_a"));
assert_eq!(loaded.get("b.rs"), Some("hash_b"));
assert!(loaded.entry("a.rs").unwrap().mtime_secs == 0);
}
#[test]
fn test_index_load_empty() {
let tmp = TempDir::new().unwrap();
let idx = Index::load(tmp.path().to_path_buf()).unwrap();
assert!(idx.is_empty());
}
#[test]
fn test_index_entries_sorted() {
let tmp = TempDir::new().unwrap();
let mut idx = Index::new(tmp.path().to_path_buf());
idx.add("c.rs", "3");
idx.add("a.rs", "1");
idx.add("b.rs", "2");
let entries = idx.entries_sorted();
assert_eq!(entries[0].0, "a.rs");
assert_eq!(entries[1].0, "b.rs");
assert_eq!(entries[2].0, "c.rs");
}
}