use cfg_if to make the code more readable

This commit is contained in:
Lynne Megido 2021-02-27 12:13:57 +10:00
parent b141b85ea7
commit ebc2bcfb41
Signed by: lynnesbian
GPG key ID: F0A184B5213D9F90
4 changed files with 134 additions and 132 deletions

2
Cargo.lock generated
View file

@ -176,7 +176,7 @@ checksum = "de853764b47027c2e862a995c34978ffa63c1501f2e15f987ba11bd4f9bba193"
[[package]] [[package]]
name = "fif" name = "fif"
version = "0.2.4" version = "0.2.5"
dependencies = [ dependencies = [
"cached", "cached",
"cfg-if", "cfg-if",

View file

@ -1,7 +1,7 @@
[package] [package]
name = "fif" name = "fif"
description = "A command-line tool for detecting and optionally correcting files with incorrect extensions." description = "A command-line tool for detecting and optionally correcting files with incorrect extensions."
version = "0.2.4" version = "0.2.5"
authors = ["Lynnesbian <lynne@bune.city>"] authors = ["Lynnesbian <lynne@bune.city>"]
edition = "2018" edition = "2018"
license = "GPL-3.0-or-later" license = "GPL-3.0-or-later"

View file

@ -17,6 +17,7 @@
use std::io::{stdout, BufWriter}; use std::io::{stdout, BufWriter};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use cfg_if::cfg_if;
use clap::Clap; use clap::Clap;
use log::{debug, error, info, trace, warn}; use log::{debug, error, info, trace, warn};
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
@ -40,14 +41,17 @@ mod mimedb;
mod parameters; mod parameters;
mod scanerror; mod scanerror;
#[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))] cfg_if! {
if #[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))] {
static MIMEDB: OnceCell<mimedb::InferDb> = OnceCell::new(); static MIMEDB: OnceCell<mimedb::InferDb> = OnceCell::new();
} else {
#[cfg(any(all(target_os = "linux", not(feature = "infer-backend")), all(not(target_os = "linux"), not(feature = "xdg-mime-backend"))))]
static MIMEDB: OnceCell<mimedb::XdgDb> = OnceCell::new(); static MIMEDB: OnceCell<mimedb::XdgDb> = OnceCell::new();
}
}
cfg_if! {
// TODO: test if this actually works on a windows machine // TODO: test if this actually works on a windows machine
#[cfg(windows)] if #[cfg(windows)] {
fn is_hidden(entry: &DirEntry) -> bool { fn is_hidden(entry: &DirEntry) -> bool {
use std::os::windows::prelude::*; use std::os::windows::prelude::*;
std::fs::metadata(entry.path()) // try to get metadata for file std::fs::metadata(entry.path()) // try to get metadata for file
@ -56,14 +60,15 @@ fn is_hidden(entry: &DirEntry) -> bool {
|f| f.file_attributes() & 0x2 > 0, // flag for hidden - https://docs.microsoft.com/windows/win32/fileio/file-attribute-constants |f| f.file_attributes() & 0x2 > 0, // flag for hidden - https://docs.microsoft.com/windows/win32/fileio/file-attribute-constants
) )
} }
} else {
#[cfg(not(windows))]
fn is_hidden(entry: &DirEntry) -> bool { fn is_hidden(entry: &DirEntry) -> bool {
entry entry
.file_name() .file_name()
.to_str() .to_str()
.map_or(false, |f| f.starts_with('.') && f != ".") .map_or(false, |f| f.starts_with('.') && f != ".")
} }
}
}
fn wanted_file(args: &parameters::Parameters, exts: &[&str], entry: &DirEntry) -> bool { fn wanted_file(args: &parameters::Parameters, exts: &[&str], entry: &DirEntry) -> bool {
if !args.scan_hidden && is_hidden(entry) { if !args.scan_hidden && is_hidden(entry) {
@ -129,8 +134,8 @@ fn scan_file(entry: &DirEntry) -> Result<Findings, (ScanError, PathBuf)> {
} }
fn scan_from_walkdir(entries: &[DirEntry]) -> Vec<Result<Findings, (ScanError, PathBuf)>> { fn scan_from_walkdir(entries: &[DirEntry]) -> Vec<Result<Findings, (ScanError, PathBuf)>> {
#[cfg(feature = "multi-threaded")] cfg_if! {
{ if #[cfg(feature = "multi-threaded")] {
// rather than using a standard par_iter, split the entries into chunks of 32 first. // rather than using a standard par_iter, split the entries into chunks of 32 first.
// this allows each spawned thread to handle 32 files before before closing, rather than creating a new thread for // this allows each spawned thread to handle 32 files before before closing, rather than creating a new thread for
// each file. this leads to a pretty substantial speedup that i'm pretty substantially happy about 0u0 // each file. this leads to a pretty substantial speedup that i'm pretty substantially happy about 0u0
@ -143,13 +148,11 @@ fn scan_from_walkdir(entries: &[DirEntry]) -> Vec<Result<Findings, (ScanError, P
.collect::<Vec<_>>() .collect::<Vec<_>>()
}) })
.collect() .collect()
} } else {
#[cfg(not(feature = "multi-threaded"))]
{
entries.iter().map(|entry: &DirEntry| scan_file(entry)).collect() entries.iter().map(|entry: &DirEntry| scan_file(entry)).collect()
} }
} }
}
fn main() { fn main() {
let args = parameters::Parameters::parse(); let args = parameters::Parameters::parse();
@ -162,17 +165,19 @@ fn main() {
// .target(env_logger::Target::Stdout) // log to stdout rather than stderr // .target(env_logger::Target::Stdout) // log to stdout rather than stderr
.init(); .init();
#[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))] cfg_if! {
if #[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))] {
MIMEDB MIMEDB
.set(mimedb::InferDb::init()) .set(mimedb::InferDb::init())
.or(Err("Failed to initialise Infer backend!")) .or(Err("Failed to initialise Infer backend!"))
.unwrap(); .unwrap();
} else {
#[cfg(any(all(target_os = "linux", not(feature = "infer-backend")), all(not(target_os = "linux"), not(feature = "xdg-mime-backend"))))]
MIMEDB MIMEDB
.set(mimedb::XdgDb::init()) .set(mimedb::XdgDb::init())
.or(Err("Failed to initialise XDG Mime backend!")) .or(Err("Failed to initialise XDG Mime backend!"))
.unwrap(); .unwrap();
}
}
debug!("Iterating directory: {:?}", args.dirs); debug!("Iterating directory: {:?}", args.dirs);

View file

@ -1,6 +1,4 @@
#[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))] use cfg_if::cfg_if;
use std::str::FromStr;
use mime_guess::Mime; use mime_guess::Mime;
pub trait MimeDb { pub trait MimeDb {
@ -8,12 +6,14 @@ pub trait MimeDb {
fn get_type(&self, data: &[u8]) -> Option<Mime>; fn get_type(&self, data: &[u8]) -> Option<Mime>;
} }
#[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))] cfg_if! {
if #[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))] {
use std::str::FromStr;
pub struct InferDb { pub struct InferDb {
db: infer::Infer, db: infer::Infer,
} }
#[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))]
fn open_document_check(buf: &[u8], kind: &str) -> bool { fn open_document_check(buf: &[u8], kind: &str) -> bool {
let mime = format!("application/vnd.oasis.opendocument.{}", kind); let mime = format!("application/vnd.oasis.opendocument.{}", kind);
let mime = mime.as_bytes(); let mime = mime.as_bytes();
@ -21,7 +21,6 @@ fn open_document_check(buf: &[u8], kind: &str) -> bool {
buf.len() > 38 + mime.len() && buf.starts_with(b"PK\x03\x04") && buf[38..mime.len() + 38] == mime[..] buf.len() > 38 + mime.len() && buf.starts_with(b"PK\x03\x04") && buf[38..mime.len() + 38] == mime[..]
} }
#[cfg(any(all(not(target_os = "linux"), not(feature = "xdg-mime-backend")), all(target_os = "linux", feature = "infer-backend")))]
impl MimeDb for InferDb { impl MimeDb for InferDb {
fn init() -> Self { fn init() -> Self {
let mut info = infer::Infer::new(); let mut info = infer::Infer::new();
@ -82,21 +81,19 @@ impl MimeDb for InferDb {
self.db.get(data).map(|f| Mime::from_str(f.mime_type()).unwrap()) self.db.get(data).map(|f| Mime::from_str(f.mime_type()).unwrap())
} }
} }
} else {
#[cfg(any(all(target_os = "linux", not(feature = "infer-backend")), all(not(target_os = "linux"), not(feature = "xdg-mime-backend"))))]
pub struct XdgDb { pub struct XdgDb {
db: xdg_mime::SharedMimeInfo, db: xdg_mime::SharedMimeInfo,
} }
#[cfg(any(all(target_os = "linux", not(feature = "infer-backend")), all(not(target_os = "linux"), not(feature = "xdg-mime-backend"))))]
impl MimeDb for XdgDb { impl MimeDb for XdgDb {
fn init() -> Self { fn init() -> Self {
Self { Self { db: xdg_mime::SharedMimeInfo::new() }
db: xdg_mime::SharedMimeInfo::new(),
}
} }
fn get_type(&self, data: &[u8]) -> Option<Mime> { fn get_type(&self, data: &[u8]) -> Option<Mime> {
self.db.get_mime_type_for_data(&data).map(|m| m.0) self.db.get_mime_type_for_data(&data).map(|m| m.0)
} }
} }
}
}