#![deny(unsafe_code)]
use std::io::Read;
use std::path::{Path, PathBuf};
use super::{lens, Fail, Input};
use crate::source::detect::{self, Format};
use crate::{cli, sys};
pub fn resolve_input(args: &cli::Args) -> Result<Input, Fail> {
let from_stdin = args.file.as_deref() == Some(Path::new("-"))
|| (args.file.is_none() && !sys::is_tty(sys::STDIN));
if from_stdin {
let mut raw = Vec::new();
std::io::stdin()
.read_to_end(&mut raw)
.map_err(|e| Fail::runtime(format!("reading stdin: {e}")))?;
check_encoding("<stdin>", sniff_head(&raw))?;
let format = lens::format_for(args, None, detect::decide(args.format, None, sniff_head(&raw)));
return Ok(Input {
label: "<stdin>".to_string(),
bytes: Some(raw),
path: None,
format,
tty: sys::tty_fd(),
});
}
let path = match &args.file {
Some(p) => p.clone(),
None => index_path(args.index.as_deref())?,
};
read_document(args, &path)
}
fn read_document(args: &cli::Args, path: &Path) -> Result<Input, Fail> {
if path.is_dir() {
return Ok(Input {
label: path.display().to_string(),
bytes: None,
path: Some(path.to_path_buf()),
format: Format::Text,
tty: sys::tty_fd(),
});
}
if !is_regular(path) {
return stream_document(args, path);
}
let head = head_bytes(path, BOM_BYTES)?;
check_encoding(&path.display().to_string(), &head)?;
let format = lens::format_for(args, Some(path), detect::decide(args.format, Some(path), &head));
Ok(Input {
label: path.display().to_string(),
bytes: None,
path: Some(path.to_path_buf()),
format,
tty: None,
})
}
fn is_regular(path: &Path) -> bool {
match std::fs::metadata(path) {
Ok(m) => m.is_file(),
Err(_) => true,
}
}
const STREAM_CAP: usize = 256 * 1024 * 1024;
fn stream_document(args: &cli::Args, path: &Path) -> Result<Input, Fail> {
let label = path.display().to_string();
let mut f = std::fs::File::open(path).map_err(|e| Fail::runtime(format!("{label}: {e}")))?;
let mut raw = Vec::new();
f.by_ref()
.take(STREAM_CAP as u64 + 1)
.read_to_end(&mut raw)
.map_err(|e| Fail::runtime(format!("{label}: {e}")))?;
if raw.len() > STREAM_CAP {
return Err(Fail::runtime(format!(
"{label}: not a regular file, and larger than {}MiB \u{2014} tread reads a \
stream into memory; redirect it to a file first",
STREAM_CAP / (1024 * 1024)
)));
}
check_encoding(&label, sniff_head(&raw))?;
let format = lens::format_for(args, Some(path), detect::decide(args.format, Some(path), sniff_head(&raw)));
Ok(Input {
label,
bytes: Some(raw),
path: None,
format,
tty: None,
})
}
const SNIFF_BYTES: usize = 8 * 1024;
const BOM_BYTES: usize = 4;
fn sniff_head(raw: &[u8]) -> &[u8] {
&raw[..raw.len().min(SNIFF_BYTES)]
}
fn check_encoding(label: &str, head: &[u8]) -> Result<(), Fail> {
match detect::unreadable_encoding(head) {
None => Ok(()),
Some(enc) => Err(Fail::runtime(format!(
"{label}: {enc} text (byte-order mark); tread reads UTF-8 \
\u{2014} convert it first, e.g. iconv -f {enc} -t UTF-8"
))),
}
}
fn head_bytes(path: &Path, want: usize) -> Result<Vec<u8>, Fail> {
let mut f = std::fs::File::open(path)
.map_err(|e| Fail::runtime(format!("{}: {}", path.display(), e)))?;
let mut buf = vec![0u8; want];
let mut got = 0;
while got < buf.len() {
match f.read(&mut buf[got..]) {
Ok(0) => break,
Ok(n) => got += n,
Err(ref e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
Err(e) => return Err(Fail::runtime(format!("{}: {}", path.display(), e))),
}
}
buf.truncate(got);
Ok(buf)
}
pub fn index_path(index: Option<&Path>) -> Result<PathBuf, Fail> {
let candidate = match index {
Some(p) if p.is_dir() && p.join("README.md").is_file() => p.join("README.md"),
Some(p) if p.is_dir() => p.to_path_buf(),
Some(p) => p.to_path_buf(),
None => PathBuf::from("README.md"),
};
if candidate.exists() {
return Ok(candidate);
}
if index.is_some() {
return Err(Fail::usage(format!(
"index not found: {}",
candidate.display()
)));
}
Err(Fail::usage(format!(
"no input: give a FILE, pipe markdown in, or use --index; try `{} --help`",
cli::BIN
)))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_a_regular_file_can_be_read_lazily() {
let file = crate::testutil::scratch("open-regular");
std::fs::write(&*file, b"id,name\n1,a\n").expect("write");
assert!(is_regular(&file));
let dir = crate::testutil::scratch("open-dir");
std::fs::create_dir(&*dir).expect("mkdir");
assert!(!is_regular(&dir), "a directory is not a regular file");
assert!(is_regular(Path::new("/definitely/not/here")));
}
#[test]
#[cfg(unix)]
fn a_device_is_a_stream_not_a_file() {
assert!(!is_regular(Path::new("/dev/null")));
}
#[test]
fn an_encoding_we_cannot_read_is_refused_with_the_fix() {
let err = check_encoding("x.csv", b"\xff\xfei\x00").expect_err("refused");
assert_eq!(err.code, crate::EXIT_ERROR);
assert!(err.msg.contains("x.csv"), "{}", err.msg);
assert!(err.msg.contains("UTF-16"), "{}", err.msg);
assert!(err.msg.contains("iconv -f UTF-16 -t UTF-8"), "{}", err.msg);
assert!(check_encoding("x.csv", b"\xef\xbb\xbfid,name\n").is_ok());
assert!(check_encoding("x.csv", b"id,name\n").is_ok());
assert!(check_encoding("x.csv", b"").is_ok());
}
}