shrupl/src/file/checked.rs

82 lines
2.2 KiB
Rust
Raw Normal View History

use std::{
2025-06-05 22:08:24 +00:00
fs, io,
path::{Path, PathBuf},
};
use serde::{Deserialize, Serialize};
use crate::sharry;
use super::{FileTrait, Uploading};
/// Description of an existing, regular file
///
/// - impl Debug, Clone, Hash for `clap` compatibility
/// - impl serde for appstate caching
/// - impl Ord to handle multiple files given
2025-06-04 16:44:24 +00:00
#[derive(Debug, Clone, Hash, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct Checked {
/// canonical path to a regular file
2025-06-18 19:40:34 +00:00
pub(super) path: PathBuf,
/// size of that file
2025-06-18 19:40:34 +00:00
pub(super) size: u64,
}
impl Checked {
/// create a new checked file from some path reference
///
/// # Errors
///
/// - from `fs::metadata(path)` or `fs::canonicalize`
/// - given path does not correspond to a regular file
pub fn new(value: impl AsRef<Path>) -> io::Result<Self> {
let meta = fs::metadata(&value)?;
if meta.is_file() {
Ok(Self {
path: fs::canonicalize(&value)?,
size: meta.len(),
})
} else {
Err(io::Error::new(
2025-06-05 22:08:24 +00:00
io::ErrorKind::InvalidInput,
"Not a regular file",
))
}
}
/// start uploading this file
///
/// - tries to create a new entry in a share
/// - expects endpoint like `{base_uri}/alias/upload/{share_id}/files/tus`
/// - consumes `self` into a `file::Uploading` struct
///
/// # Errors
///
/// TODO documentation after `ClientError` rework
pub fn start_upload(
self,
client: &impl sharry::Client,
uri: &sharry::Uri,
alias_id: &str,
share_id: &str,
) -> sharry::Result<Uploading> {
let file_id = client.file_create(uri, alias_id, share_id, &self)?;
Ok(Uploading::new(self.path, self.size, file_id))
}
}
2025-06-06 15:21:49 +00:00
impl<'t> FileTrait<'t> for Checked {
2025-06-06 15:21:49 +00:00
/// get a reference to the file's name
///
2025-06-06 22:25:39 +00:00
/// Uses `SharryFile::extract_file_name`, which may **panic**!
2025-06-06 23:42:18 +00:00
fn get_name(&'t self) -> &'t str {
<Self as FileTrait>::extract_file_name(&self.path)
2025-06-06 15:21:49 +00:00
}
/// get the file's size
2025-06-06 23:42:18 +00:00
fn get_size(&self) -> u64 {
self.size
2025-06-06 15:21:49 +00:00
}
}