minor refactoring to make formats.rs less icky

This commit is contained in:
Lynne Megido 2021-07-24 16:20:49 +10:00
parent 863954b2a2
commit 59c87a3729
Signed by: lynnesbian
GPG Key ID: F0A184B5213D9F90
6 changed files with 36 additions and 31 deletions

View File

@ -1,6 +1,7 @@
<component name="InspectionProjectProfileManager"> <component name="InspectionProjectProfileManager">
<profile version="1.0"> <profile version="1.0">
<option name="myName" value="Project Default" /> <option name="myName" value="Project Default" />
<inspection_tool class="DuplicatedCode" enabled="false" level="WEAK WARNING" enabled_by_default="false" />
<inspection_tool class="RegExpRepeatedSpace" enabled="true" level="INFORMATION" enabled_by_default="true" /> <inspection_tool class="RegExpRepeatedSpace" enabled="true" level="INFORMATION" enabled_by_default="true" />
</profile> </profile>
</component> </component>

View File

@ -2,6 +2,10 @@
Dates are given in YYYY-MM-DD format. Dates are given in YYYY-MM-DD format.
## v0.3 ## v0.3
### v0.3.4 (2021-mm-dd)
#### Other
- Refactored `formats.rs`
### v0.3.3 (2021-07-07) ### v0.3.3 (2021-07-07)
#### Features #### Features
- Added `--canonical-paths` flag for outputting canonical paths in output - for example, - Added `--canonical-paths` flag for outputting canonical paths in output - for example,

8
Cargo.lock generated
View File

@ -417,9 +417,9 @@ dependencies = [
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.27" version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0d8caf72986c1a598726adc988bb5984792ef84f5ee5aa50209145ee8077038" checksum = "5c7ed8b8c7b886ea3ed7dde405212185f423ab44682667c8c6dd14aa1d9f6612"
dependencies = [ dependencies = [
"unicode-xid", "unicode-xid",
] ]
@ -605,9 +605,9 @@ checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
[[package]] [[package]]
name = "syn" name = "syn"
version = "1.0.73" version = "1.0.74"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f71489ff30030d2ae598524f61326b902466f72a0fb1a8564c001cc63425bcc7" checksum = "1873d832550d4588c3dbc20f01361ab00bfe741048f71e3fecf145a7cc18b29c"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",

View File

@ -122,23 +122,14 @@ fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
Ok(()) Ok(())
} }
// TODO: this might need a restructure. pub trait FormatSteps {
// it would be nice if i didn't have to write a case for every OutputFormat variant that looked like
// OutputFormat::PowerShell => PowerShell::new().write_all(...)
// also, JSON's implementation differs vastly from PowerShell and Shell's implementations. Maybe they shouldn't be
// treated as implementing the same trait, since in that case, the format trait is more of a concept rather than an
// actual definition of behaviour.
// structuring code is *hard*
pub trait Format {
fn new() -> Self;
fn rename<W: Write>(&self, _f: &mut W, _from: &Path, _to: &Path) -> io::Result<()> { unreachable!() } fn rename<W: Write>(&self, _f: &mut W, _from: &Path, _to: &Path) -> io::Result<()> { unreachable!() }
fn no_known_extension<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() } fn no_known_extension<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() }
fn unreadable<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() } fn unreadable<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() }
fn unknown_type<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() } fn unknown_type<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()> { unreachable!() }
fn header<W: Write>(&self, _f: &mut W, _entries: &Entries) -> io::Result<()> { unreachable!() } fn header<W: Write>(&self, _f: &mut W, _entries: &Entries) -> io::Result<()> { unreachable!() }
fn footer<W: Write>(&self, _f: &mut W, _entries: &Entries) -> io::Result<()> { unreachable!() } fn footer<W: Write>(&self, _f: &mut W, _entries: &Entries) -> io::Result<()> { unreachable!() }
fn write_steps<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
// TODO: clean this up - it's kinda messy // TODO: clean this up - it's kinda messy
self.header(f, entries)?; self.header(f, entries)?;
@ -185,12 +176,18 @@ pub trait Format {
} }
} }
pub trait Format {
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()>;
}
/// Bourne-Shell compatible script. /// Bourne-Shell compatible script.
pub struct Shell {} pub struct Shell;
impl Format for Shell { impl Format for Shell {
fn new() -> Self { Self {} } fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> { self.write_steps(f, entries) }
}
impl FormatSteps for Shell {
fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> { fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> {
smart_write(f, writablesln!("mv -v -i -- ", from, Space, to)) smart_write(f, writablesln!("mv -v -i -- ", from, Space, to))
} }
@ -238,11 +235,13 @@ impl Format for Shell {
// PowerShell is a noun, not a type // PowerShell is a noun, not a type
#[allow(clippy::doc_markdown)] #[allow(clippy::doc_markdown)]
/// PowerShell script. /// PowerShell script.
pub struct PowerShell {} pub struct PowerShell;
impl Format for PowerShell { impl Format for PowerShell {
fn new() -> Self { Self {} } fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> { self.write_steps(f, entries) }
}
impl FormatSteps for PowerShell {
fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> { fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> {
// unfortunately there doesn't seem to be an equivalent of sh's `mv -i` -- passing the '-Confirm' flag will prompt // unfortunately there doesn't seem to be an equivalent of sh's `mv -i` -- passing the '-Confirm' flag will prompt
// the user to confirm every single rename, and using Move-Item -Force will always overwrite without prompting. // the user to confirm every single rename, and using Move-Item -Force will always overwrite without prompting.
@ -303,7 +302,10 @@ impl Format for PowerShell {
pub struct Text; pub struct Text;
impl Format for Text { impl Format for Text {
fn new() -> Self { Self {} } fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> { self.write_steps(f, entries) }
}
impl FormatSteps for Text {
fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> { fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> {
smart_write(f, writablesln![from, " should be renamed to ", to]) smart_write(f, writablesln![from, " should be renamed to ", to])
} }
@ -337,8 +339,6 @@ pub struct Json;
#[cfg(feature = "json")] #[cfg(feature = "json")]
impl Format for Json { impl Format for Json {
fn new() -> Self { Self {} }
fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> { fn write_all<W: Write>(&self, f: &mut W, entries: &Entries) -> io::Result<()> {
#[derive(serde::Serialize)] #[derive(serde::Serialize)]
struct SerdeEntries<'a> { struct SerdeEntries<'a> {

View File

@ -30,7 +30,7 @@ use walkdir::{DirEntry, WalkDir};
use crate::findings::Findings; use crate::findings::Findings;
use crate::findings::ScanError; use crate::findings::ScanError;
use crate::formats::{Format, PowerShell, Shell}; use crate::formats::Format;
use crate::mime_db::MimeDb; use crate::mime_db::MimeDb;
use crate::parameters::{OutputFormat, ScanOpts}; use crate::parameters::{OutputFormat, ScanOpts};
use crate::utils::{clap_long_version, os_name}; use crate::utils::{clap_long_version, os_name};
@ -142,17 +142,17 @@ fn main() {
if results.is_empty() { if results.is_empty() {
info!("All files have valid extensions!"); info!("All files have valid extensions!");
exit(0); exit(exitcode::OK);
} }
let mut buffered_stdout = BufWriter::new(stdout()); let mut buffered_stdout = BufWriter::new(stdout());
let result = match args.output_format { let result = match args.output_format {
OutputFormat::Sh => Shell::new().write_all(&mut buffered_stdout, &results), OutputFormat::Sh => formats::Shell.write_all(&mut buffered_stdout, &results),
OutputFormat::PowerShell => PowerShell::new().write_all(&mut buffered_stdout, &results), OutputFormat::PowerShell => formats::PowerShell.write_all(&mut buffered_stdout, &results),
#[cfg(feature = "json")] #[cfg(feature = "json")]
OutputFormat::Json => formats::Json::new().write_all(&mut buffered_stdout, &results), OutputFormat::Json => formats::Json.write_all(&mut buffered_stdout, &results),
OutputFormat::Text => formats::Text::new().write_all(&mut buffered_stdout, &results), OutputFormat::Text => formats::Text.write_all(&mut buffered_stdout, &results),
}; };
if result.is_err() { if result.is_err() {

View File

@ -352,8 +352,8 @@ fn outputs_move_commands() {
let mut contents = std::string::String::new(); let mut contents = std::string::String::new();
match *format { match *format {
"Shell" => Shell::new().write_all(&mut cursor, &entries), "Shell" => Shell.write_all(&mut cursor, &entries),
"PowerShell" => PowerShell::new().write_all(&mut cursor, &entries), "PowerShell" => PowerShell.write_all(&mut cursor, &entries),
_ => unreachable!(), _ => unreachable!(),
} }
.expect("Failed to write to cursor"); .expect("Failed to write to cursor");
@ -389,7 +389,7 @@ fn test_json() {
let mut cursor = std::io::Cursor::new(Vec::new()); let mut cursor = std::io::Cursor::new(Vec::new());
let mut contents = std::string::String::new(); let mut contents = std::string::String::new();
Json::new() Json
.write_all(&mut cursor, &entries) .write_all(&mut cursor, &entries)
.expect("Failed to write to cursor"); .expect("Failed to write to cursor");