#![deny(unsafe_code)]
pub(crate) mod input;
mod lens;
use std::path::{Path, PathBuf};
use crate::csv::read::Reader;
use crate::source::detect::Format;
use crate::source::json::{self as json, JsonSource};
use crate::source::text::TextSource;
use crate::source::{csv::CsvSource, jsonl::JsonlSource, markdown::MarkdownSource, Source};
use crate::plat::{path as ppath, Platform};
use crate::{cli, md, sys};
pub use input::resolve_input;
pub struct Fail {
pub msg: String,
pub code: i32,
}
impl Fail {
pub fn runtime(msg: impl Into<String>) -> Self {
Fail {
msg: msg.into(),
code: crate::EXIT_ERROR,
}
}
pub fn usage(msg: impl Into<String>) -> Self {
Fail {
msg: msg.into(),
code: crate::EXIT_USAGE,
}
}
}
pub struct Input {
pub label: String,
pub bytes: Option<Vec<u8>>,
pub path: Option<PathBuf>,
pub format: Format,
pub tty: Option<(sys::Fd, bool)>,
}
impl Drop for Input {
fn drop(&mut self) {
if let Some((fd, owned)) = self.tty {
if owned {
sys::close_fd(fd);
}
}
}
}
pub fn navigable(input: &Input) -> bool {
let Some(path) = input.path.as_deref() else {
return false;
};
matches!(input.format, Format::Markdown | Format::Code) || path.is_dir()
}
const PROJECT_MARKERS: [&str; 6] = [
".git",
"Cargo.toml",
"package.json",
"tsconfig.json",
"go.mod",
"pyproject.toml",
];
pub fn corpus_root(file: &Path, cwd: &Path) -> Option<PathBuf> {
let given = file.to_string_lossy();
let here = PathBuf::from(match ppath::is_absolute(Platform::HOST, &given) {
true => ppath::join(Platform::HOST, &given, "")?,
false => ppath::join(Platform::HOST, &cwd.to_string_lossy(), &given)?,
});
let mut at = here.parent()?;
for _ in 0..64 {
if PROJECT_MARKERS.iter().any(|m| at.join(m).exists()) {
return Some(at.to_path_buf());
}
at = at.parent()?;
}
None
}
pub fn build_source(input: &Input, args: &cli::Args) -> Result<Box<dyn Source>, Fail> {
if let Some(name) = args.lens.as_deref() {
if !lens::accepts(name, input.format) {
return Err(lens::needs_records(name, input.format));
}
}
if let Some(p) = input.path.as_deref() {
if p.is_dir() {
return Ok(Box::new(crate::source::dir::DirSource::open(p)));
}
}
match input.format {
Format::Csv => Ok(Box::new(csv_source(input, args)?)),
Format::Json if args.lens.is_some() => Ok(Box::new(lens::array_source_with(input, args)?)),
Format::Json => Ok(Box::new(json_source(input)?)),
Format::Jsonl => Ok(Box::new(lens::jsonl_source_with(input, args)?)),
Format::Code => Ok(Box::new(code_source(input)?)),
Format::Text => Ok(Box::new(text_source(input)?)),
Format::Markdown => Ok(Box::new(MarkdownSource::new(markdown_document(input)?))),
}
}
fn code_source(input: &Input) -> Result<crate::source::code::CodeSource, Fail> {
let path = match input.path.as_deref() {
Some(p) => p,
None => return Err(Fail::usage(String::from("code must be read from a file, not a pipe"))),
};
crate::source::code::CodeSource::open(path)
.map_err(|e| Fail::runtime(format!("{}: {e}", path.display())))
}
fn text_source(input: &Input) -> Result<TextSource, Fail> {
match &input.path {
Some(path) => TextSource::open(path)
.map_err(|e| Fail::runtime(format!("{}: {e}", path.display()))),
None => Ok(TextSource::from_bytes(input.bytes.clone().unwrap_or_default())),
}
}
fn csv_source(input: &Input, args: &cli::Args) -> Result<CsvSource, Fail> {
match &input.path {
Some(path) => CsvSource::open(path, args.delim)
.map_err(|e| Fail::runtime(format!("{}: {e}", path.display()))),
None => Ok(CsvSource::from_bytes(
input.bytes.clone().unwrap_or_default(),
args.delim,
)),
}
}
pub(super) fn jsonl_source(input: &Input) -> Result<JsonlSource, Fail> {
match &input.path {
Some(path) => JsonlSource::open(path)
.map_err(|e| Fail::runtime(format!("{}: {e}", path.display()))),
None => Ok(JsonlSource::from_bytes(input.bytes.clone().unwrap_or_default())),
}
}
fn json_source(input: &Input) -> Result<JsonSource, Fail> {
match &input.path {
Some(path) => {
JsonSource::open(path).map_err(|e| Fail::runtime(format!("{}: {e}", path.display())))
}
None => Ok(JsonSource::from_bytes(input.bytes.clone().unwrap_or_default())),
}
}
pub fn to_jsonl(input: &Input, out: &mut dyn std::io::Write) -> Result<(), Fail> {
let reader = match (&input.path, &input.bytes) {
(Some(p), _) => {
Reader::open(p).map_err(|e| Fail::runtime(format!("{}: {e}", p.display())))?
}
(None, bytes) => Reader::memory(bytes.clone().unwrap_or_default()),
};
json::export::to_jsonl(reader, out).map_err(|e| Fail::runtime(format!("--to-jsonl: {e}")))
}
pub fn markdown_document(input: &Input) -> Result<md::Document, Fail> {
let text = match (&input.bytes, &input.path) {
(Some(raw), _) => md::sanitize::decode(raw.clone()),
(None, Some(path)) => md::sanitize::read_file(path)
.map_err(|e| Fail::runtime(format!("{}: {}", path.display(), e)))?,
(None, None) => String::new(),
};
Ok(md::parse(&text))
}
pub fn toc_text(input: &Input, args: &cli::Args) -> Result<String, Fail> {
if input.format == Format::Markdown {
return Ok(render_outline(&outline(&markdown_document(input)?)));
}
if input.format == Format::Json && args.lens.is_some() {
let mut src = lens::array_source_with(input, args)?;
return Ok(src.summaries(TOC_RECORDS).iter().map(|s| format!("{s}\n")).collect());
}
if input.format == Format::Json {
let mut src = json_source(input)?;
return Ok(src.toc().iter().map(|s| format!("{s}\n")).collect());
}
if input.format == Format::Text {
return Ok(String::new());
}
if input.format == Format::Jsonl {
let mut src = lens::jsonl_source_with(input, args)?;
return Ok(src.summaries(TOC_RECORDS).iter().map(|s| format!("{s}\n")).collect());
}
let mut src = csv_source(input, args)?;
src.set_width(crate::dump_width(args));
Ok(src.columns().iter().map(|c| format!("{c}\n")).collect())
}
const TOC_RECORDS: usize = 1000;
pub fn outline(doc: &md::Document) -> Vec<(u8, String)> {
let mut out = Vec::new();
collect_headings(&doc.blocks, &mut out);
out
}
fn collect_headings(blocks: &[md::Block], out: &mut Vec<(u8, String)>) {
for b in blocks {
match b {
md::Block::Heading { level, content, .. } => {
out.push((*level, md::ast::inline_text(content)));
}
md::Block::Quote { blocks, .. } => collect_headings(blocks, out),
_ => {}
}
}
}
pub fn render_outline(outline: &[(u8, String)]) -> String {
let mut s = String::new();
for (level, text) in outline {
s.push_str(&" ".repeat((*level as usize - 1) * 2));
s.push_str(text);
s.push('\n');
}
s
}
#[cfg(test)]
mod tests {
use super::*;
fn input(path: Option<&str>, format: Format) -> Input {
Input {
label: String::from("t"),
bytes: None,
path: path.map(PathBuf::from),
format,
tty: None,
}
}
#[test]
fn everything_that_produces_links_gets_a_corpus() {
let dir = std::env::temp_dir();
let d = input(dir.to_str(), Format::Text);
assert!(navigable(&d), "a directory listing must navigate");
assert!(navigable(&input(Some("/p/src/a.rs"), Format::Code)));
assert!(navigable(&input(Some("/p/doc.md"), Format::Markdown)));
}
#[test]
fn a_projects_root_is_found_from_a_marker_above_the_file() {
let t = std::env::temp_dir().join(format!("tread-root-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&t);
std::fs::create_dir_all(t.join("src/app/deep")).unwrap();
std::fs::write(t.join("package.json"), "{}\n").unwrap();
let f = t.join("src/app/deep/page.tsx");
std::fs::write(&f, "").unwrap();
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
assert_eq!(corpus_root(&f, &cwd).as_deref(), Some(t.as_path()));
assert!(corpus_root(Path::new("/"), &cwd).is_none());
let _ = std::fs::remove_dir_all(&t);
}
#[test]
fn formats_with_no_links_get_no_corpus() {
assert!(!navigable(&input(Some("/p/a.csv"), Format::Csv)));
assert!(!navigable(&input(Some("/p/a.json"), Format::Json)));
assert!(!navigable(&input(Some("/p/a.jsonl"), Format::Jsonl)));
assert!(!navigable(&input(Some("/p/a.txt"), Format::Text)));
assert!(!navigable(&input(None, Format::Markdown)));
}
}