fif/src/formats.rs

324 lines
9.3 KiB
Rust
Raw Normal View History

// SPDX-FileCopyrightText: 2021-2022 Lynnesbian
// SPDX-License-Identifier: GPL-3.0-or-later
2021-10-05 14:24:08 +00:00
2021-10-05 15:30:13 +00:00
//! Logic for handling the various output formats that fif can output to.
#![allow(missing_copy_implementations)]
2021-04-20 05:20:10 +00:00
use std::ffi::OsStr;
use std::io::{self, Write};
#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
2021-03-11 17:44:31 +00:00
use std::path::Path;
use cfg_if::cfg_if;
use snailquote::escape;
2021-05-05 23:27:16 +00:00
use crate::findings::ScanError;
use crate::utils::CLAP_LONG_VERSION;
2021-06-14 07:08:52 +00:00
use crate::Findings;
2021-09-22 15:33:10 +00:00
use crate::String;
2021-10-05 15:30:13 +00:00
/// A macro for creating an array of [`Writable`]s without needing to pepper your code with `into()`s.
/// # Usage
/// ```
2021-08-28 07:54:01 +00:00
/// use crate::fif::writables;
/// use crate::fif::formats::{Writable, smart_write};
/// let mut f = std::io::stdout();
///
/// // Instead of...
2021-08-28 07:54:01 +00:00
/// smart_write(&mut f, &["hello".into(), Writable::Newline]);
/// // ...just use:
2021-08-28 07:54:01 +00:00
/// smart_write(&mut f, writables!["hello", Newline]);
/// ```
2021-08-28 07:54:01 +00:00
#[macro_export]
macro_rules! writables {
[$($args:tt),+] => {
&[$(writables!(@do $args),)*]
};
(@do Newline) => {
$crate::formats::Writable::Newline
};
(@do $arg:expr) => {
$arg.into()
}
}
2021-04-28 11:39:56 +00:00
#[macro_export]
2021-10-05 15:30:13 +00:00
/// Does the same thing as [`writables`], but adds a Newline to the end.
2021-04-28 11:39:56 +00:00
macro_rules! writablesln {
[$($args:tt),+] => {
&[$(writables!(@do $args),)* writables!(@do Newline)]
};
}
#[derive(Debug, PartialEq)]
pub enum Writable<'a> {
2021-02-21 14:46:51 +00:00
String(&'a str),
Path(&'a Path),
Newline,
2021-02-21 14:46:51 +00:00
}
// the lifetime of a lifetime
impl<'a> From<&'a str> for Writable<'a> {
2021-05-05 23:06:05 +00:00
fn from(s: &'a str) -> Writable<'a> { Writable::String(s) }
2021-02-21 14:46:51 +00:00
}
impl<'a> From<&'a Path> for Writable<'a> {
2021-05-05 23:06:05 +00:00
fn from(p: &'a Path) -> Writable<'a> { Writable::Path(p) }
2021-02-21 14:46:51 +00:00
}
impl<'a> From<&'a OsStr> for Writable<'a> {
2021-05-05 23:06:05 +00:00
fn from(p: &'a OsStr) -> Writable<'a> { Writable::Path(p.as_ref()) }
}
fn generated_by() -> String { format!("Generated by fif {}", CLAP_LONG_VERSION.as_str()).into() }
2021-08-28 07:54:01 +00:00
pub fn smart_write<W: Write>(f: &mut W, writeables: &[Writable]) -> io::Result<()> {
2021-02-21 14:46:51 +00:00
// ehhhh
for writeable in writeables {
match writeable {
Writable::Newline => {
cfg_if! {
if #[cfg(windows)] {
2021-06-14 06:53:41 +00:00
write!(f, "\r\n")?;
} else {
2021-06-14 06:53:41 +00:00
writeln!(f,)?;
}
}
}
2021-02-21 14:46:51 +00:00
Writable::String(s) => write!(f, "{}", s)?,
Writable::Path(path) => {
2021-05-05 22:57:42 +00:00
if let Some(path_str) = path.to_str() {
let escaped = escape(path_str);
if escaped.as_ref() == path_str {
// the escaped string is the same as the input - this will occur for inputs like "file.txt" which don't
// need to be escaped. however, it's Best Practice™ to escape such strings anyway, so we prefix/suffix the
// escaped string with single quotes.
2021-06-14 06:53:41 +00:00
write!(f, "'{}'", escaped)?;
} else {
2021-06-14 06:53:41 +00:00
write!(f, "{}", escaped)?;
}
} else {
write!(f, "'")?;
cfg_if! {
if #[cfg(windows)] {
// TODO: implement bonked strings for windows
// something like:
// f.write_all(&*path.as_os_str().encode_wide().collect::<Vec<u16>>())?;
write!(f, "{}", path.as_os_str().to_string_lossy())?;
} else {
f.write_all(&*path.as_os_str().as_bytes())?;
}
}
2021-06-14 06:53:41 +00:00
write!(f, "'")?;
2021-02-21 14:46:51 +00:00
}
}
}
}
2021-02-21 14:46:51 +00:00
Ok(())
}
pub trait FormatSteps {
fn rename<W: Write>(&self, _f: &mut W, _from: &Path, _to: &Path) -> io::Result<()>;
2021-09-22 15:21:15 +00:00
fn no_known_extension<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()>;
fn unreadable<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()>;
fn unknown_type<W: Write>(&self, _f: &mut W, _path: &Path) -> io::Result<()>;
fn header<W: Write>(&self, _f: &mut W) -> io::Result<()>;
fn footer<W: Write>(&self, _f: &mut W) -> io::Result<()>;
fn write_steps<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
self.header(f)?;
for error in errors {
match error {
// failed to read the file
ScanError::File(path) => self.unreadable(f, path)?,
// file was read successfully, but we couldn't determine a MIME type
ScanError::Mime(path) => self.unknown_type(f, path)?,
}
}
2021-02-21 14:46:51 +00:00
if !errors.is_empty() {
// add a blank line between the errors and commands
smart_write(f, writables![Newline])?;
}
for finding in findings {
if let Some(name) = finding.recommended_path() {
self.rename(f, finding.file.as_path(), &name)?;
} else {
self.no_known_extension(f, finding.file.as_path())?;
}
}
self.footer(f)
}
}
pub trait Format {
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()>;
}
/// Bourne-Shell compatible script.
pub struct Shell;
impl Format for Shell {
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
self.write_steps(f, findings, errors)
}
}
impl FormatSteps for Shell {
fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> {
smart_write(f, writablesln!("mv -v -i -- ", from, "\t", to))
}
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(
f,
2021-11-05 15:30:34 +00:00
writablesln!["cat <<- '???'", Newline, "No known extension for ", path, Newline, "???"],
)
}
fn unreadable<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
2021-04-28 11:39:56 +00:00
smart_write(f, writablesln!["# Failed to read", path])
}
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(f, writablesln!["# Failed to detect MIME type for ", path])
}
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
2021-11-05 15:30:34 +00:00
smart_write(f, writablesln!["#!/usr/bin/env sh", Newline, "# ", (generated_by().as_str())])?;
if let Ok(working_directory) = std::env::current_dir() {
2021-04-28 11:39:56 +00:00
smart_write(f, writablesln!["# Run from ", (working_directory.as_path())])?;
}
2021-04-28 11:39:56 +00:00
smart_write(f, writablesln![Newline, "set -e", Newline])
}
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> { smart_write(f, writablesln![Newline, "echo 'Done.'"]) }
2021-02-18 09:48:38 +00:00
}
// PowerShell is a noun, not a type
#[allow(clippy::doc_markdown)]
/// PowerShell script.
pub struct PowerShell;
impl Format for PowerShell {
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
self.write_steps(f, findings, errors)
}
}
impl FormatSteps for PowerShell {
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
// the user to confirm every single rename, and using Move-Item -Force will always overwrite without prompting.
// there doesn't seem to be a way to rename the file, prompting only if the target already exists.
smart_write(
f,
2021-11-05 15:30:34 +00:00
writablesln!["Rename-Item -Verbose -Path ", from, " -NewName ", (to.file_name().unwrap())],
)
}
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(
f,
2021-11-05 15:30:34 +00:00
writablesln!["Write-Output @'", Newline, "No known extension for ", path, Newline, "'@"],
)
}
fn unreadable<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(
f,
2021-06-13 09:24:21 +00:00
writablesln!["Write-Output @'", Newline, "Failed to read ", path, Newline, "'@"],
)
}
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(f, writablesln!["<# Failed to detect MIME type for ", path, " #>"])
}
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
smart_write(
f,
2021-04-28 11:39:56 +00:00
writablesln!["#!/usr/bin/env pwsh", Newline, "<# ", (generated_by().as_str()), " #>"],
)?;
if let Ok(working_directory) = std::env::current_dir() {
2021-04-28 11:39:56 +00:00
smart_write(f, writablesln!["<# Run from ", (working_directory.as_path()), " #>"])?;
}
smart_write(f, writables![Newline])
}
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> {
2021-04-28 11:39:56 +00:00
smart_write(f, writablesln![Newline, "Write-Output 'Done!'"])
}
}
2021-05-05 22:57:42 +00:00
2021-06-07 05:21:47 +00:00
pub struct Text;
impl Format for Text {
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
self.write_steps(f, findings, errors)
}
}
impl FormatSteps for Text {
2021-06-07 05:21:47 +00:00
fn rename<W: Write>(&self, f: &mut W, from: &Path, to: &Path) -> io::Result<()> {
smart_write(f, writablesln![from, " should be renamed to ", to])
}
fn no_known_extension<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(f, writablesln!["No known extension for ", path])
}
fn unreadable<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(f, writablesln!["Encountered IO error while accessing ", path])
}
fn unknown_type<W: Write>(&self, f: &mut W, path: &Path) -> io::Result<()> {
smart_write(f, writablesln!["Couldn't determine type for ", path])
}
fn header<W: Write>(&self, f: &mut W) -> io::Result<()> {
2021-06-07 05:21:47 +00:00
smart_write(f, writablesln![(generated_by().as_str()), Newline])
}
fn footer<W: Write>(&self, f: &mut W) -> io::Result<()> {
2021-06-07 05:21:47 +00:00
smart_write(
f,
// writablesln![Newline, "Processed ", (entries.len().to_string().as_str()), " files"],
&[Writable::Newline],
2021-06-07 05:21:47 +00:00
)
}
}
2021-05-05 22:57:42 +00:00
#[cfg(feature = "json")]
pub struct Json;
#[cfg(feature = "json")]
impl Format for Json {
fn write_all<W: Write>(&self, f: &mut W, findings: &[Findings], errors: &[ScanError]) -> io::Result<()> {
2021-05-05 22:57:42 +00:00
#[derive(serde::Serialize)]
struct SerdeEntries<'a> {
errors: &'a [ScanError<'a>],
findings: &'a [Findings],
2021-05-05 22:57:42 +00:00
}
2021-08-25 05:44:21 +00:00
let result = serde_json::to_writer_pretty(f, &SerdeEntries { errors, findings });
2021-05-05 23:06:05 +00:00
2021-05-05 22:57:42 +00:00
if let Err(err) = result {
log::error!("Error while serialising: {}", err);
2021-05-05 23:06:05 +00:00
return Err(err.into());
2021-05-05 22:57:42 +00:00
}
Ok(())
}
2021-05-05 23:06:05 +00:00
}