git clone https://garage44.eu/jeroen/pinnacle.git.. /programs/src/bin/filter.rs
//! The filters of a pipeline, one program told apart by the name it was
//! started as (`pinnacle_records::pipe::FILTERS`): `where`, `sort`, `first`,
//! `last`, `pick`, `count` and `unique`, `head`, `tail`, `grep` and `wc`
//! after a `|`, and `save`, which writes what comes in to a file as text
//! (what `> file` at a line's end becomes). Its stdin is the command
//! before it: it takes in every table and line that command gives, changes them, and gives them on when
//! that command has ended. Questions and progress go on at once, so a
//! question asked before the `|` is still answered; images and files go on
//! as they came. The command before failing is this one failing, with its
//! words.
#![no_std]
#![no_main]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_records::pipe::{Filter, PIPED};
use pinnacle_records::start::{PWD, resolve};
use pinnacle_records::{Output as Message, Record};
use pinnacle_rt::output::Output;
use pinnacle_rt::{Handle, fs};
/// What came in, in the order it came.
enum Piece {
Table {
columns: Vec<String>,
rows: Vec<Vec<String>>,
},
Lines(Vec<String>),
/// A record passed on unchanged, with its handles.
Pass(Vec<u8>, Vec<Handle>),
}
/// Lines added to the pieces: to the last, when it is lines too.
fn add_lines(pieces: &mut Vec<Piece>, lines: impl Iterator<Item = String>) {
if !matches!(pieces.last(), Some(Piece::Lines(_))) {
pieces.push(Piece::Lines(Vec::new()));
}
if let Some(Piece::Lines(all)) = pieces.last_mut() {
all.extend(lines);
}
}
/// What `save` writes: text as it came, a table as tab-separated lines
/// under its header (as Ctrl+C copies one).
fn as_text(pieces: &[Piece]) -> String {
let mut text = String::new();
for piece in pieces {
match piece {
Piece::Lines(lines) => {
for line in lines {
text.push_str(line);
text.push('\n');
}
}
Piece::Table { columns, rows } => {
if columns.iter().any(|c| !c.is_empty()) {
text.push_str(&columns.join("\t"));
text.push('\n');
}
for row in rows {
text.push_str(&row.join("\t"));
text.push('\n');
}
}
Piece::Pass(..) => {}
}
}
text
}
/// What `save` is to do: the file, and whether to add to it.
fn saving(words: &[&str], cwd: &str) -> Result<(String, bool), String> {
let home = pinnacle_ui::command::home();
match words {
["save", file] => Ok((resolve(cwd, home, file), false)),
["save", "-a", file] => Ok((resolve(cwd, home, file), true)),
_ => Err("save and a file: ps | save ps.txt, save -a to add to it".into()),
}
}
#[unsafe(no_mangle)]
fn main(argument: u64) -> u64 {
let out = Output::start(argument);
let words: Vec<&str> = out.args.iter().map(String::as_str).collect();
let name = words.first().copied().unwrap_or("filter");
let cwd = out
.env
.iter()
.find(|(k, _)| k == PWD)
.map_or_else(|| String::from(pinnacle_ui::command::home()), |(_, v)| v.clone());
let save = match name {
"save" => match saving(&words, &cwd) {
Ok(to) => Some(to),
Err(why) => return out.status(2, &why),
},
_ => None,
};
// `save` passes everything through unchanged, into its file.
let filter = match save {
Some(_) => Filter::Pick(Vec::new()),
None => match Filter::parse(&words) {
Ok(f) => f,
Err(why) => return out.status(2, &why),
},
};
if !out.env.iter().any(|(k, _)| k == PIPED) {
let why = alloc::format!(
"{name} changes what the command before a | gives: ls | {}",
words.join(" ")
);
return out.status(2, &why);
}
let mut pieces: Vec<Piece> = Vec::new();
// A plain program's unfinished last line.
let mut partial = String::new();
let mut failed: Option<(u64, String)> = None;
let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE];
while let Some((len, handles)) = out.receive(&mut buffer) {
let message = &buffer[..len.min(buffer.len())];
match Message::of(message) {
Message::Record(Record::Table { columns, rows }) => match pieces.last_mut() {
// A long table comes as several records of the same columns.
Some(Piece::Table { columns: c, rows: r }) if *c == columns => r.extend(rows),
_ => pieces.push(Piece::Table { columns, rows }),
},
Message::Record(Record::Text(text)) => add_lines(&mut pieces, text.split('\n').map(String::from)),
Message::Record(Record::Ask { .. } | Record::Progress { .. }) => {
out.forward(message, handles);
}
Message::Record(Record::Status { code, summary }) => {
if code != 0 {
failed = Some((code, summary));
}
}
Message::Bytes(bytes) => {
partial.push_str(&String::from_utf8_lossy(bytes));
if let Some(end) = partial.rfind('\n') {
let done: String = partial.drain(..=end).collect();
add_lines(
&mut pieces,
done.trim_end_matches('\n')
.split('\n')
.map(|l| String::from(l.trim_end_matches('\r'))),
);
}
}
Message::Record(_) | Message::Malformed => pieces.push(Piece::Pass(message.to_vec(), handles)),
}
}
if !partial.is_empty() {
add_lines(&mut pieces, core::iter::once(partial));
}
if let Some((path, append)) = save {
let text = as_text(&pieces);
let at = match append {
true => fs::stat(&path).map_or(0, |s| s.size),
false => 0,
};
// A quarter megabyte a call, as `cp` writes.
let written = (append || fs::write(&path, &[]))
&& text
.as_bytes()
.chunks(256 * 1024)
.enumerate()
.all(|(i, part)| fs::write_at(&path, at + (i * 256 * 1024) as u64, part));
// What was not text (an image, a file) goes on to the screen.
for piece in pieces {
if let Piece::Pass(message, handles) = piece {
out.forward(&message, handles);
}
}
if !written {
return out.status(1, &alloc::format!("{path} could not be written"));
}
let lines = text.lines().count();
let said = alloc::format!(
"{lines} line{} {} {path}",
if lines == 1 { "" } else { "s" },
if append { "added to" } else { "written to" }
);
return match failed {
Some((code, summary)) => out.status(code, &alloc::format!("{summary}\n{said}")),
None => out.status(0, &said),
};
}
let has_table = pieces.iter().any(|p| matches!(p, Piece::Table { .. }));
for piece in pieces {
match piece {
Piece::Table { columns, rows } => match filter.table(columns, rows) {
Ok((_, rows)) if rows.is_empty() => {
out.text("(no rows left)");
}
Ok((columns, rows)) => {
out.send(&Record::Table { columns, rows });
}
Err(why) => return out.status(1, &why),
},
Piece::Lines(lines) => match filter.lines(lines.clone()) {
Ok(lines) if lines.is_empty() => {
out.text("(no lines left)");
}
Ok(lines) => {
out.text(&lines.join("\n"));
}
// Text beside a table (`ps`'s count under it) is not what
// a column's name is for: it goes on as it came.
Err(_) if has_table => {
out.text(&lines.join("\n"));
}
Err(why) => return out.status(1, &why),
},
Piece::Pass(message, handles) => {
out.forward(&message, handles);
}
}
}
match failed {
Some((code, summary)) => out.status(code, &summary),
None => out.status(0, ""),
}
}