create is_running_in_accessible_mode helper

also renamed some variables
This commit is contained in:
João M. Bezerra 2022-06-04 14:50:03 -03:00
parent 278bc980c1
commit 801189ec02
10 changed files with 48 additions and 33 deletions

16
src/accessible.rs Normal file
View File

@ -0,0 +1,16 @@
use once_cell::sync::OnceCell;
/// Whether to enable accessible output (removes info output and reduces other
/// output, removes visual markers like '[' and ']').
/// Removes th progress bar as well
pub static ACCESSIBLE: OnceCell<bool> = OnceCell::new();
pub fn is_running_in_accessible_mode() -> bool {
ACCESSIBLE.get().copied().unwrap_or(false)
}
pub fn set_accessible(value: bool) {
if ACCESSIBLE.get().is_none() {
ACCESSIBLE.set(value).unwrap();
}
}

View File

@ -8,14 +8,8 @@ use std::{
use clap::Parser; use clap::Parser;
use fs_err as fs; use fs_err as fs;
use once_cell::sync::OnceCell;
use crate::{utils::FileVisibilityPolicy, Opts, QuestionPolicy, Subcommand}; use crate::{accessible::set_accessible, utils::FileVisibilityPolicy, Opts, QuestionPolicy, Subcommand};
/// Whether to enable accessible output (removes info output and reduces other
/// output, removes visual markers like '[' and ']').
/// Removes th progress bar as well
pub static ACCESSIBLE: OnceCell<bool> = OnceCell::new();
impl Opts { impl Opts {
/// A helper method that calls `clap::Parser::parse`. /// A helper method that calls `clap::Parser::parse`.
@ -26,7 +20,7 @@ impl Opts {
pub fn parse_args() -> crate::Result<(Self, QuestionPolicy, FileVisibilityPolicy)> { pub fn parse_args() -> crate::Result<(Self, QuestionPolicy, FileVisibilityPolicy)> {
let mut opts = Self::parse(); let mut opts = Self::parse();
ACCESSIBLE.set(opts.accessible).unwrap(); set_accessible(opts.accessible);
let (Subcommand::Compress { files, .. } let (Subcommand::Compress { files, .. }
| Subcommand::Decompress { files, .. } | Subcommand::Decompress { files, .. }

View File

@ -20,14 +20,14 @@ use crate::{
// Compress files into an `output_file` // Compress files into an `output_file`
// //
// files are the list of paths to be compressed: ["dir/file1.txt", "dir/file2.txt"] // - `files`: is the list of paths to be compressed: ["dir/file1.txt", "dir/file2.txt"]
// formats contains each format necessary for compression, example: [Tar, Gz] (in compression order) // - `extensions`: contains each compression format necessary for compressing, example: [Tar, Gz] (in compression order)
// output_file is the resulting compressed file name, example: "compressed.tar.gz" // - `output_file` is the resulting compressed file name, example: "compressed.tar.gz"
// //
// Returns Ok(true) if compressed all files successfully, and Ok(false) if user opted to skip files // Returns Ok(true) if compressed all files successfully, and Ok(false) if user opted to skip files
pub fn compress_files( pub fn compress_files(
files: Vec<PathBuf>, files: Vec<PathBuf>,
formats: Vec<Extension>, extensions: Vec<Extension>,
output_file: fs::File, output_file: fs::File,
output_dir: &Path, output_dir: &Path,
question_policy: QuestionPolicy, question_policy: QuestionPolicy,
@ -72,13 +72,13 @@ pub fn compress_files(
Ok(encoder) Ok(encoder)
}; };
let (first_extension, extensions) = split_first_compression_format(&formats); let (first_format, formats) = split_first_compression_format(&extensions);
for format in extensions.iter().rev() { for format in formats.iter().rev() {
writer = chain_writer_encoder(format, writer)?; writer = chain_writer_encoder(format, writer)?;
} }
match first_extension { match first_format {
Gzip | Bzip | Lz4 | Lzma | Snappy | Zstd => { Gzip | Bzip | Lz4 | Lzma | Snappy | Zstd => {
let _progress = Progress::new_accessible_aware( let _progress = Progress::new_accessible_aware(
total_input_size, total_input_size,
@ -88,7 +88,7 @@ pub fn compress_files(
})), })),
); );
writer = chain_writer_encoder(&first_extension, writer)?; writer = chain_writer_encoder(&first_format, writer)?;
let mut reader = fs::File::open(&files[0]).unwrap(); let mut reader = fs::File::open(&files[0]).unwrap();
io::copy(&mut reader, &mut writer)?; io::copy(&mut reader, &mut writer)?;
} }
@ -113,7 +113,7 @@ pub fn compress_files(
writer.flush()?; writer.flush()?;
} }
Zip => { Zip => {
if formats.len() > 1 { if !formats.is_empty() {
warn_user_about_loading_zip_in_memory(); warn_user_about_loading_zip_in_memory();
// give user the option to continue compressing after warning is shown // give user the option to continue compressing after warning is shown

View File

@ -1,6 +1,4 @@
//! Core of the crate, where the `compress_files` and `decompress_file` functions are implemented //! Receive command from the cli and call the respective function for that command.
//!
//! Also, where correctly call functions based on the detected `Command`.
mod compress; mod compress;
mod decompress; mod decompress;

View File

@ -7,7 +7,7 @@ use std::{
fmt::{self, Display}, fmt::{self, Display},
}; };
use crate::utils::colors::*; use crate::{accessible::is_running_in_accessible_mode, utils::colors::*};
/// All errors that can be generated by `ouch` /// All errors that can be generated by `ouch`
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]
@ -56,7 +56,7 @@ impl Display for FinalError {
// Title // Title
// //
// When in ACCESSIBLE mode, the square brackets are suppressed // When in ACCESSIBLE mode, the square brackets are suppressed
if *crate::cli::ACCESSIBLE.get().unwrap_or(&false) { if is_running_in_accessible_mode() {
write!(f, "{}ERROR{}: {}", *RED, *RESET, self.title)?; write!(f, "{}ERROR{}: {}", *RED, *RESET, self.title)?;
} else { } else {
write!(f, "{}[ERROR]{} {}", *RED, *RESET, self.title)?; write!(f, "{}[ERROR]{} {}", *RED, *RESET, self.title)?;
@ -73,7 +73,7 @@ impl Display for FinalError {
writeln!(f)?; writeln!(f)?;
// to reduce redundant output for text-to-speach systems, braille // to reduce redundant output for text-to-speach systems, braille
// displays and so on, only print "hints" once in ACCESSIBLE mode // displays and so on, only print "hints" once in ACCESSIBLE mode
if *crate::cli::ACCESSIBLE.get().unwrap_or(&false) { if is_running_in_accessible_mode() {
write!(f, "\n{}hints:{}", *GREEN, *RESET)?; write!(f, "\n{}hints:{}", *GREEN, *RESET)?;
for hint in &self.hints { for hint in &self.hints {
write!(f, "\n{}", hint)?; write!(f, "\n{}", hint)?;

View File

@ -1,10 +1,11 @@
//! Implementation of the 'list' command, print list of files in an archive //! Some implementation helpers related to the 'list' command.
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use indicatif::{ProgressBar, ProgressStyle}; use indicatif::{ProgressBar, ProgressStyle};
use self::tree::Tree; use self::tree::Tree;
use crate::accessible::is_running_in_accessible_mode;
/// Options controlling how archive contents should be listed /// Options controlling how archive contents should be listed
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
@ -33,7 +34,7 @@ pub fn list_files(
println!("Archive: {}", archive.display()); println!("Archive: {}", archive.display());
if list_options.tree { if list_options.tree {
let pb = if !crate::cli::ACCESSIBLE.get().unwrap() { let pb = if !is_running_in_accessible_mode() {
let template = "{wide_msg} [{elapsed_precise}] {spinner:.green}"; let template = "{wide_msg} [{elapsed_precise}] {spinner:.green}";
let pb = ProgressBar::new_spinner(); let pb = ProgressBar::new_spinner();
pb.set_style(ProgressStyle::default_bar().template(template)); pb.set_style(ProgressStyle::default_bar().template(template));
@ -46,7 +47,7 @@ pub fn list_files(
.into_iter() .into_iter()
.map(|file| { .map(|file| {
let file = file?; let file = file?;
if !crate::cli::ACCESSIBLE.get().unwrap() { if !is_running_in_accessible_mode() {
pb.as_ref() pb.as_ref()
.expect("exists") .expect("exists")
.set_message(format!("Processing: {}", file.path.display())); .set_message(format!("Processing: {}", file.path.display()));
@ -77,7 +78,7 @@ fn print_entry(name: impl std::fmt::Display, is_dir: bool) {
// if in ACCESSIBLE mode, use colors but print final / in case colors // if in ACCESSIBLE mode, use colors but print final / in case colors
// aren't read out aloud with a screen reader or aren't printed on a // aren't read out aloud with a screen reader or aren't printed on a
// braille reader // braille reader
} else if *crate::cli::ACCESSIBLE.get().unwrap() { } else if is_running_in_accessible_mode() {
println!("{}{}{}/{}", *BLUE, *STYLE_BOLD, name, *ALL_RESET); println!("{}{}{}/{}", *BLUE, *STYLE_BOLD, name, *ALL_RESET);
} else { } else {
println!("{}{}{}{}", *BLUE, *STYLE_BOLD, name, *ALL_RESET); println!("{}{}{}{}", *BLUE, *STYLE_BOLD, name, *ALL_RESET);
@ -105,6 +106,7 @@ mod tree {
file: Option<FileInArchive>, file: Option<FileInArchive>,
children: LinkedHashMap<OsString, Tree>, children: LinkedHashMap<OsString, Tree>,
} }
impl Tree { impl Tree {
/// Insert a file into the tree /// Insert a file into the tree
pub fn insert(&mut self, file: FileInArchive) { pub fn insert(&mut self, file: FileInArchive) {

View File

@ -1,5 +1,7 @@
//! Macros used on ouch. //! Macros used on ouch.
use crate::accessible::is_running_in_accessible_mode;
/// Macro that prints \[INFO\] messages, wraps [`println`]. /// Macro that prints \[INFO\] messages, wraps [`println`].
/// ///
/// There are essentially two different versions of the `info!()` macro: /// There are essentially two different versions of the `info!()` macro:
@ -28,7 +30,7 @@ macro_rules! info {
(@$display_handle: expr, accessible, $($arg:tt)*) => { (@$display_handle: expr, accessible, $($arg:tt)*) => {
let display_handle = &mut $display_handle; let display_handle = &mut $display_handle;
// if in ACCESSIBLE mode, suppress the "[INFO]" and just print the message // if in ACCESSIBLE mode, suppress the "[INFO]" and just print the message
if !(*$crate::cli::ACCESSIBLE.get().unwrap()) { if !$crate::accessible::is_running_in_accessible_mode() {
$crate::macros::_info_helper(display_handle); $crate::macros::_info_helper(display_handle);
} }
writeln!(display_handle, $($arg)*).unwrap(); writeln!(display_handle, $($arg)*).unwrap();
@ -39,8 +41,7 @@ macro_rules! info {
info!(@::std::io::stdout(), inaccessible, $($arg)*); info!(@::std::io::stdout(), inaccessible, $($arg)*);
}; };
(@$display_handle: expr, inaccessible, $($arg:tt)*) => { (@$display_handle: expr, inaccessible, $($arg:tt)*) => {
if (!$crate::cli::ACCESSIBLE.get().unwrap()) if !$crate::accessible::is_running_in_accessible_mode() {
{
let display_handle = &mut $display_handle; let display_handle = &mut $display_handle;
$crate::macros::_info_helper(display_handle); $crate::macros::_info_helper(display_handle);
writeln!(display_handle, $($arg)*).unwrap(); writeln!(display_handle, $($arg)*).unwrap();
@ -68,7 +69,7 @@ macro_rules! warning {
pub fn _warning_helper() { pub fn _warning_helper() {
use crate::utils::colors::{ORANGE, RESET}; use crate::utils::colors::{ORANGE, RESET};
if *crate::cli::ACCESSIBLE.get().unwrap() { if is_running_in_accessible_mode() {
eprint!("{}Warning:{} ", *ORANGE, *RESET); eprint!("{}Warning:{} ", *ORANGE, *RESET);
} else { } else {
eprint!("{}[WARNING]{} ", *ORANGE, *RESET); eprint!("{}[WARNING]{} ", *ORANGE, *RESET);

View File

@ -1,6 +1,7 @@
// Macros should be declared first // Macros should be declared first
pub mod macros; pub mod macros;
pub mod accessible;
pub mod archive; pub mod archive;
pub mod cli; pub mod cli;
pub mod commands; pub mod commands;

View File

@ -8,6 +8,8 @@ use std::{
use indicatif::{ProgressBar, ProgressStyle}; use indicatif::{ProgressBar, ProgressStyle};
use crate::accessible::is_running_in_accessible_mode;
/// Draw a ProgressBar using a function that checks periodically for the progress /// Draw a ProgressBar using a function that checks periodically for the progress
pub struct Progress { pub struct Progress {
draw_stop: Sender<()>, draw_stop: Sender<()>,
@ -51,7 +53,7 @@ impl Progress {
precise: bool, precise: bool,
current_position_fn: Option<Box<dyn Fn() -> u64 + Send>>, current_position_fn: Option<Box<dyn Fn() -> u64 + Send>>,
) -> Option<Self> { ) -> Option<Self> {
if *crate::cli::ACCESSIBLE.get().unwrap() { if is_running_in_accessible_mode() {
return None; return None;
} }
Some(Self::new(total_input_size, precise, current_position_fn)) Some(Self::new(total_input_size, precise, current_position_fn))

View File

@ -13,6 +13,7 @@ use fs_err as fs;
use super::{strip_cur_dir, to_utf}; use super::{strip_cur_dir, to_utf};
use crate::{ use crate::{
accessible::is_running_in_accessible_mode,
error::{Error, Result}, error::{Error, Result},
utils::colors, utils::colors,
}; };
@ -126,7 +127,7 @@ impl<'a> Confirmation<'a> {
// Ask the same question to end while no valid answers are given // Ask the same question to end while no valid answers are given
loop { loop {
if *crate::cli::ACCESSIBLE.get().unwrap() { if is_running_in_accessible_mode() {
print!( print!(
"{} {}yes{}/{}no{}: ", "{} {}yes{}/{}no{}: ",
message, message,