Skip to content

Commit

Permalink
Display filenames in error messages
Browse files Browse the repository at this point in the history
Add `--assume_filename` option to change the filename shown when the
input is stdin

Particularly Useful for subcommand use, such as in a git filter or a `find`,
when the controller will forward stderr but will not print the files or
command that produced the stderr
  • Loading branch information
rayrobdod committed May 29, 2024
1 parent 6add14b commit 859edea
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 21 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
## [Unreleased]
* Adjusted some error messages to be slightly more informative
and print in natural-language instead of the programatic debug print style
* Include filenames in error messages
* Implement option `--assume-filename` to print a filename instead of `stdin`
in error messages when input is stdin.

## [v2023.6.10] 2023-06-10
Refactors, process improvements, dependency updating
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ using `git config -l | grep filter`)
To install globally

```bash
git config --global --replace-all filter.png_inflate.clean /opt/png_inflate
git config --global --replace-all filter.png_inflate.clean "/opt/png_inflate --assume-filename %f"
echo "*.png filter=png_inflate" >>${XDG_CONFIG_HOME-${HOME}/.config}/git/attributes
```

To install for a single repository

```bash
git config --local --replace-all filter.png_inflate.clean /opt/png_inflate
git config --local --replace-all filter.png_inflate.clean "/opt/png_inflate --assume-filename %f"
echo "*.png filter=png_inflate" >>.git/info/attributes
```

Expand Down
8 changes: 4 additions & 4 deletions src/file_or_stdio/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ pub enum FileOrStdin {
Stdin(::std::io::Stdin),
}

impl From<Option<String>> for FileOrStdin {
fn from(src: Option<String>) -> FileOrStdin {
impl From<&Option<String>> for FileOrStdin {
fn from(src: &Option<String>) -> FileOrStdin {
match src {
None => FileOrStdin::Stdin(::std::io::stdin()),
Some(s) => FileOrStdin::File(
Expand All @@ -38,8 +38,8 @@ pub enum FileOrStdout {
Stdout(::std::io::Stdout),
}

impl From<Option<String>> for FileOrStdout {
fn from(src: Option<String>) -> FileOrStdout {
impl From<&Option<String>> for FileOrStdout {
fn from(src: &Option<String>) -> FileOrStdout {
match src {
None => FileOrStdout::Stdout(::std::io::stdout()),
Some(s) => FileOrStdout::File(atomicwrites::AtomicFile::new(
Expand Down
50 changes: 35 additions & 15 deletions src/inflate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,17 @@ fn main() {
}

let input = {
let mut infile = FileOrStdin::from(args.input_file);
let mut infile = FileOrStdin::from(&args.input_file);
png::read(&mut infile)
};

let mut outfile = FileOrStdout::from(args.output_file);
let mut outfile = FileOrStdout::from(&args.output_file);
let ignore_unsafe_to_copy = args.ignore_unsafe_to_copy;
let reported_infilename = args
.input_file
.or(args.assume_filename)
.unwrap_or("stdin".to_string());
let reported_outfilename = args.output_file.unwrap_or("stdout".to_string());

match input {
Result::Ok(indata) => {
Expand All @@ -51,19 +56,19 @@ fn main() {
// Ok
},
Result::Err(x) => {
eprintln!("Could not write: {}", x);
eprintln!("Could not write: {}: {}", reported_outfilename, x);
::std::process::exit(1);
},
}
},
Result::Err(x) => {
eprintln!("Could not transform: {}", x);
eprintln!("Could not transform: {}: {}", reported_infilename, x);
::std::process::exit(1);
},
}
},
Result::Err(x) => {
eprintln!("Could not read: {}", x);
eprintln!("Could not read: {}: {}", reported_infilename, x);
::std::process::exit(1);
},
}
Expand Down Expand Up @@ -91,10 +96,7 @@ impl ::std::fmt::Display for Error {
Error::CannotCopySafely(typ) => {
// if `typ` were non-alpha, the typ would have triggered ChunkReadError::InvalidTyp
// and not have gotten this far
let chars: String = typ
.iter()
.map(|x| char::from(*x))
.collect();
let chars: String = typ.iter().map(|x| char::from(*x)).collect();
write!(f, "Found non-safe-to-copy chunk {}", chars)
},
Error::UnsupportedCompressionMethod => {
Expand Down Expand Up @@ -278,14 +280,23 @@ impl<I: Sized + Iterator<Item = png::Chunk>> IteratorExt for I {
}
}

#[derive(Debug, Default, PartialEq)]
enum ArgsState {
#[default]
Open,
ForcePositional,
AssumeFilename,
}

/// A representation of the program arguments
#[derive(Debug, Default)]
struct Args {
force_positional: bool,
state: ArgsState,

help: bool,
version: bool,
ignore_unsafe_to_copy: bool,
assume_filename: Option<String>,

program_name: Option<String>,
input_file: Option<String>,
Expand All @@ -305,20 +316,29 @@ impl Args {
println!();
println!("{}", PROGRAM_DESCRIPTION);
println!();
println!(" {:3} {:20} {}", "", "--copy-unsafe", "continue even upon encounter of unknown not-safe-to-copy chunks");
println!(" {:3} {:20} {}", "-?,", "--help", "display this help message");
println!(" {:3} {:20} {}", "", "--version", "display program version");
println!(" {:3} {:30} {}", "", "--assume-filename filename", "When reading from stdin, use this filename in error reporting");
println!(" {:3} {:30} {}", "", "--copy-unsafe", "continue even upon encounter of unknown not-safe-to-copy chunks");
println!(" {:3} {:30} {}", "-?,", "--help", "display this help message");
println!(" {:3} {:30} {}", "", "--version", "display program version");
}

/// Decode arg, add the result to self, then return self.
/// Intended as the lambda in a Iter::fold invocation.
fn push(mut self, arg: String) -> Args {
#[allow(clippy::iter_nth_zero)]
let arg_zeroth_char = arg.chars().nth(0).unwrap_or('\0');
if !self.force_positional && arg_zeroth_char == '-' {
if self.state == ArgsState::AssumeFilename {
if self.assume_filename != None {
panic!("--assume-filename provided multiple times");
}
self.assume_filename = Option::Some(arg);
self.state = ArgsState::Open;
} else if self.state != ArgsState::ForcePositional && arg_zeroth_char == '-' {
// then the argument is a named argument
if arg == "--" {
self.force_positional = true;
self.state = ArgsState::ForcePositional;
} else if arg == "--assume-filename" || arg == "/assume-filename" {
self.state = ArgsState::AssumeFilename;
} else if arg == "--copy-unsafe" || arg == "/copy-unsafe" {
self.ignore_unsafe_to_copy = true;
} else if arg == "-?" || arg == "--help" || arg == "/?" || arg == "/help" {
Expand Down

0 comments on commit 859edea

Please sign in to comment.