feat(get): add external cacache::get api

This commit is contained in:
Kat Marchán 2019-06-04 20:30:05 +02:00
parent 6504048181
commit d91d214176
No known key found for this signature in database
GPG Key ID: AEB529C08A3C7E9E
4 changed files with 73 additions and 18 deletions

View File

@ -1,23 +1,30 @@
use crate::content::path;
use ssri::Integrity;
use std::fs;
use std::path::Path;
use std::fs::{self, File};
use std::io;
pub fn open(cache: &Path, sri: &Integrity) -> io::Result<File> {
File::open(path::content_path(&cache, &sri))
use ssri::Integrity;
use crate::content::path;
use crate::errors::Error;
pub fn read(cache: &Path, sri: &Integrity) -> Result<Vec<u8>, Error> {
let cpath = path::content_path(&cache, &sri);
let ret = fs::read(&cpath)?;
if sri.clone().check(&ret).is_some() {
Ok(ret)
} else {
Err(Error::IntegrityError)
}
}
pub fn read(cache: &Path, sri: &Integrity) -> io::Result<Vec<u8>> {
fs::read(path::content_path(&cache, &sri))
}
pub fn read_to_string(cache: &Path, sri: &Integrity) -> io::Result<String> {
fs::read_to_string(path::content_path(&cache, &sri))
}
pub fn copy(cache: &Path, sri: &Integrity, to: &Path) -> io::Result<u64> {
fs::copy(path::content_path(&cache, &sri), to)
pub fn copy(cache: &Path, sri: &Integrity, to: &Path) -> Result<u64, Error> {
let cpath = path::content_path(&cache, &sri);
let ret = fs::copy(&cpath, to)?;
let data = fs::read(cpath)?;
if sri.clone().check(data).is_some() {
Ok(ret)
} else {
Err(Error::IntegrityError)
}
}
pub fn has_content(cache: &Path, sri: &Integrity) -> Option<Integrity> {

View File

@ -6,6 +6,10 @@ use serde_json;
#[derive(Fail, Debug)]
pub enum Error {
#[fail(display = "not found")]
NotFound,
#[fail(display = "integrity check failed")]
IntegrityError,
#[fail(display = "{}", _0)]
Io(#[fail(cause)] io::Error),
#[fail(display = "{}", _0)]

39
src/get.rs Normal file
View File

@ -0,0 +1,39 @@
use std::path::Path;
use ssri::Integrity;
use crate::content::read;
use crate::errors::Error;
use crate::index::{self, Entry};
pub fn read(cache: &Path, key: String) -> Result<Vec<u8>, Error> {
if let Some(entry) = index::find(&cache, &key)? {
read_hash(cache, &entry.integrity)
} else {
Err(Error::NotFound)
}
}
pub fn read_hash(cache: &Path, sri: &Integrity) -> Result<Vec<u8>, Error> {
Ok(read::read(cache, sri)?)
}
pub fn copy(cache: &Path, key: String, to: &Path) -> Result<u64, Error> {
if let Some(entry) = index::find(&cache, &key)? {
copy_hash(cache, &entry.integrity, to)
} else {
Err(Error::NotFound)
}
}
pub fn copy_hash(cache: &Path, sri: &Integrity, to: &Path) -> Result<u64, Error> {
Ok(read::copy(cache, sri, to)?)
}
pub fn info(cache: &Path, key: String) -> Result<Option<Entry>, Error> {
index::find(cache, &key)
}
pub fn hash_exists(cache: &Path, sri: &Integrity) -> bool {
read::has_content(&cache, &sri).is_some()
}

View File

@ -1,2 +1,7 @@
pub mod content;
pub mod index;
mod content;
pub mod get;
mod index;
mod errors;
pub use errors::Error;
pub use index::Entry;