Skip to content

Commit

Permalink
🚧 Enhance anyhow
Browse files Browse the repository at this point in the history
  • Loading branch information
ChanTsune committed Nov 18, 2024
1 parent 9cdb25e commit 00d453b
Show file tree
Hide file tree
Showing 7 changed files with 32 additions and 40 deletions.
6 changes: 3 additions & 3 deletions cli/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pub mod update;
mod xattr;

use crate::cli::{CipherAlgorithmArgs, Cli, Commands, PasswordArgs};
use std::{fs, io};
use std::fs;

pub fn entry(cli: Cli) -> anyhow::Result<()> {
match cli.commands {
Expand All @@ -34,7 +34,7 @@ pub fn entry(cli: Cli) -> anyhow::Result<()> {
}
}

fn ask_password(args: PasswordArgs) -> io::Result<Option<String>> {
fn ask_password(args: PasswordArgs) -> anyhow::Result<Option<String>> {
if let Some(path) = args.password_file {
return Ok(Some(fs::read_to_string(path)?));
};
Expand All @@ -43,7 +43,7 @@ fn ask_password(args: PasswordArgs) -> io::Result<Option<String>> {
log::warn!("Using a password on the command line interface can be insecure.");
password
}
Some(None) => Some(gix_prompt::securely("Enter password: ").map_err(io::Error::other)?),
Some(None) => Some(gix_prompt::securely("Enter password: ")?),
None => None,
})
}
Expand Down
14 changes: 8 additions & 6 deletions cli/src/command/commons.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::{
cli::{CipherAlgorithmArgs, CompressionAlgorithmArgs, HashAlgorithmArgs},
utils::{self, PathPartExt},
};
use anyhow::Context;
use normalize_path::*;
use pna::{
prelude::*, Archive, EntryBuilder, EntryName, EntryPart, EntryReference, NormalEntry,
Expand Down Expand Up @@ -71,7 +72,7 @@ pub(crate) fn collect_items<I: IntoIterator<Item = P>, P: Into<PathBuf>>(
gitignore: bool,
follow_links: bool,
exclude: Option<Vec<PathBuf>>,
) -> io::Result<Vec<PathBuf>> {
) -> anyhow::Result<Vec<PathBuf>> {
let mut files = files.into_iter();
let exclude = exclude.map(|it| it.into_iter().map(|path| path.normalize()));
let mut target_items = vec![];
Expand Down Expand Up @@ -100,7 +101,7 @@ pub(crate) fn collect_items<I: IntoIterator<Item = P>, P: Into<PathBuf>>(
}
};
for path in walker.into_iter().flatten() {
let path = path.map_err(io::Error::other)?.into_path();
let path = path?.into_path();
if keep_dir || path.is_file() {
target_items.push(path);
}
Expand All @@ -115,14 +116,14 @@ pub(crate) fn create_entry(
keep_options,
owner_options,
}: CreateOptions,
) -> io::Result<NormalEntry> {
) -> anyhow::Result<NormalEntry> {
if path.is_symlink() {
let source = fs::read_link(path)?;
let entry = EntryBuilder::new_symbolic_link(
EntryName::from_lossy(path),
EntryReference::from_lossy(source.as_path()),
)?;
return apply_metadata(entry, path, keep_options, owner_options)?.build();
return Ok(apply_metadata(entry, path, keep_options, owner_options)?.build()?);
} else if path.is_file() {
let mut entry = EntryBuilder::new_file(EntryName::from_lossy(path), option)?;
#[cfg(feature = "memmap")]
Expand All @@ -140,15 +141,16 @@ pub(crate) fn create_entry(
{
entry.write_all(&fs::read(path)?)?;
}
return apply_metadata(entry, path, keep_options, owner_options)?.build();
return Ok(apply_metadata(entry, path, keep_options, owner_options)?.build()?);
} else if path.is_dir() {
let entry = EntryBuilder::new_dir(EntryName::from_lossy(path));
return apply_metadata(entry, path, keep_options, owner_options)?.build();
return Ok(apply_metadata(entry, path, keep_options, owner_options)?.build()?);
}
Err(io::Error::new(
io::ErrorKind::Unsupported,
"Currently not a regular file is not supported.",
))
.with_context(|| "")
}

pub(crate) fn entry_option(
Expand Down
22 changes: 10 additions & 12 deletions cli/src/command/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use crate::{
},
utils::{self, fmt::DurationDisplay},
};
use anyhow::Context;
use bytesize::ByteSize;
use clap::{ArgGroup, Parser, ValueHint};
use pna::{Archive, SolidEntryBuilder, WriteOptions};
Expand Down Expand Up @@ -120,8 +119,7 @@ fn create_archive(args: CreateCommand) -> anyhow::Result<()> {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!("{} is already exists", archive.display()),
))
.with_context(|| "");
))?;
}
log::info!("Create an archive: {}", archive.display());
let mut files = args.file.files;
Expand Down Expand Up @@ -206,14 +204,12 @@ pub(crate) fn create_archive_file<W, F>(
owner_options: OwnerOptions,
solid: bool,
target_items: Vec<PathBuf>,
) -> io::Result<()>
) -> anyhow::Result<()>
where
W: Write,
F: FnMut() -> io::Result<W>,
{
let pool = ThreadPoolBuilder::default()
.build()
.map_err(io::Error::other)?;
let pool = ThreadPoolBuilder::default().build()?;

let (tx, rx) = std::sync::mpsc::channel();
let option = if solid {
Expand Down Expand Up @@ -264,10 +260,8 @@ fn create_archive_with_split(
solid: bool,
target_items: Vec<PathBuf>,
max_file_size: usize,
) -> io::Result<()> {
let pool = ThreadPoolBuilder::default()
.build()
.map_err(io::Error::other)?;
) -> anyhow::Result<()> {
let pool = ThreadPoolBuilder::default().build()?;

let (tx, rx) = std::sync::mpsc::channel();
let option = if solid {
Expand Down Expand Up @@ -301,7 +295,11 @@ fn create_archive_with_split(
let entries = entries_builder.build();
write_split_archive(archive, [entries].into_iter(), max_file_size)?;
} else {
write_split_archive(archive, rx.into_iter(), max_file_size)?;
write_split_archive(
archive,
rx.into_iter().map(|it| it.map_err(io::Error::other)),
max_file_size,
)?;
}
Ok(())
}
6 changes: 2 additions & 4 deletions cli/src/command/extract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,17 +139,15 @@ pub(crate) fn run_extract_archive_reader<'p, Provider>(
files: Vec<String>,
mut password_provider: Provider,
args: OutputOption,
) -> io::Result<()>
) -> anyhow::Result<()>
where
Provider: FnMut() -> Option<&'p str>,
{
let password = password_provider();
let globs =
GlobPatterns::new(files).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;

let pool = ThreadPoolBuilder::default()
.build()
.map_err(io::Error::other)?;
let pool = ThreadPoolBuilder::default().build()?;

let mut hard_link_entries = Vec::new();

Expand Down
2 changes: 1 addition & 1 deletion cli/src/command/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ pub(crate) fn run_list_archive(
password: Option<&str>,
files: &[String],
args: ListOptions,
) -> io::Result<()> {
) -> anyhow::Result<()> {
let globs =
GlobPatterns::new(files).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;

Expand Down
16 changes: 5 additions & 11 deletions cli/src/command/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,8 @@ use crate::{
},
utils,
};
use anyhow::Context;
use clap::{ArgGroup, Args, Parser, ValueHint};
use std::{
fs,
io::{self, stdout},
path::PathBuf,
};
use std::{fs, io, path::PathBuf};

#[derive(Args, Clone, Eq, PartialEq, Hash, Debug)]
#[command(
Expand Down Expand Up @@ -131,10 +126,9 @@ fn run_stdio(args: StdioCommand) -> anyhow::Result<()> {
} else {
unreachable!()
}
.with_context(|| "")
}

fn run_create_archive(args: StdioCommand) -> io::Result<()> {
fn run_create_archive(args: StdioCommand) -> anyhow::Result<()> {
let password = ask_password(args.password)?;
check_password(&password, &args.cipher);
let mut files = args
Expand Down Expand Up @@ -195,7 +189,7 @@ fn run_create_archive(args: StdioCommand) -> io::Result<()> {
)
} else {
create_archive_file(
|| Ok(stdout().lock()),
|| Ok(io::stdout().lock()),
cli_option,
keep_options,
owner_options,
Expand All @@ -205,7 +199,7 @@ fn run_create_archive(args: StdioCommand) -> io::Result<()> {
}
}

fn run_extract_archive(args: StdioCommand) -> io::Result<()> {
fn run_extract_archive(args: StdioCommand) -> anyhow::Result<()> {
let password = ask_password(args.password)?;
let out_option = OutputOption {
overwrite: args.overwrite,
Expand Down Expand Up @@ -241,7 +235,7 @@ fn run_extract_archive(args: StdioCommand) -> io::Result<()> {
}
}

fn run_list_archive(args: StdioCommand) -> io::Result<()> {
fn run_list_archive(args: StdioCommand) -> anyhow::Result<()> {
let password = ask_password(args.password)?;
let list_options = ListOptions {
long: false,
Expand Down
6 changes: 3 additions & 3 deletions cli/src/command/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,15 +140,15 @@ impl Command for UpdateCommand {
}
}

fn update_archive<Strategy: TransformStrategy>(args: UpdateCommand) -> io::Result<()> {
fn update_archive<Strategy: TransformStrategy>(args: UpdateCommand) -> anyhow::Result<()> {
let password = ask_password(args.password)?;
check_password(&password, &args.cipher);
let archive_path = args.file.archive;
if !archive_path.exists() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("{} is not exists", archive_path.display()),
));
))?;
}
let option = entry_option(args.compression, args.cipher, args.hash, password.clone());
let keep_options = KeepOptions {
Expand Down Expand Up @@ -287,7 +287,7 @@ fn update_archive<Strategy: TransformStrategy>(args: UpdateCommand) -> io::Resul
Strategy::transform(
&mut out_archive,
password.as_deref(),
entry.map(Into::into),
entry.map(Into::into).map_err(io::Error::other),
|entry| entry.map(Some),
)?;
}
Expand Down

0 comments on commit 00d453b

Please sign in to comment.