Support - as a CLI argument

Fixes #389
pull/392/head
Wilfred Hughes 2022-09-24 17:23:47 +07:00
parent bec79cb40b
commit 345a88fe53
4 changed files with 28 additions and 4 deletions

@ -11,6 +11,9 @@ which improves diff results in some cases.
### Command Line Interface
Difftastic will now read a file from stdin if given `-` as a path
argument.
`--list-languages` now respects the value of `--color`, whose default
only uses styling when stdout is a TTY.

@ -1,12 +1,14 @@
# Usage
## Diffing Files
## File Arguments
### Diffing Files
```
$ difft sample_files/before.js sample_files/after.js
```
## Diffing Directories
### Diffing Directories
```
$ difft sample_files/dir_before/ sample_files/dir_after/
@ -18,6 +20,14 @@ with the same name.
The `--skip-unchanged` option is useful when diffing directories that
contain many unchanged files.
### Reading stdin
You can read a file from stdin by specifying `-` as the file path.
```
$ cat sample_files/before.js | difft - sample_files/after.js
```
## Language Detection
Difftastic guesses the language used based on the file extension, file

@ -1,5 +1,6 @@
//! File reading utilities.
use std::io::Read;
use std::{
fs,
io::ErrorKind::*,
@ -41,7 +42,7 @@ pub fn read_files_or_die(
}
}
/// Read a path provided in a CLI argument, handling /dev/null
/// Read a path provided in a CLI argument, handling /dev/null and -
/// correctly.
fn read_cli_path(path: &Path) -> std::io::Result<Vec<u8>> {
// Treat /dev/null as an empty file, even on platforms like
@ -51,6 +52,16 @@ fn read_cli_path(path: &Path) -> std::io::Result<Vec<u8>> {
return Ok(vec![]);
}
if path == Path::new("-") {
let stdin = std::io::stdin();
let mut handle = stdin.lock();
let mut bytes = vec![];
handle.read_to_end(&mut bytes)?;
return Ok(bytes);
}
fs::read(path)
}

@ -280,7 +280,7 @@ fn diff_file_content(
}
// Prefer the RHS path for language detection, unless it's /dev/null.
let (guess_src, guess_path) = if rhs_display_path == "/dev/null" {
let (guess_src, guess_path) = if rhs_display_path == "/dev/null" || rhs_display_path == "-" {
// TODO: take a Path directly instead.
(&lhs_src, Path::new(&lhs_display_path))
} else {