garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /programs/src/bin/files.rs

raw

//! The file commands, one program told apart by the name it was started as
//! (`pinnacle_ui::command::FILE_COMMANDS`): `ls`, `cat`, `mkdir`, `rm`,
//! `cp`, `mv` and `touch`; `head`, `tail`, `grep` and `wc` on files (after
//! a `|` they are filters, `pinnacle_records::pipe::AS_FILTERS`); `find`,
//! `du`, `df` and `hex`. Paths are as the terminal's working folder sees
//! them (`PWD`, `pinnacle_records::start::resolve`); what went wrong is the
//! status's summary, and a folder is removed only once the person says yes.

#![no_std]
#![no_main]

extern crate alloc;

use alloc::string::String;
use alloc::vec::Vec;
use pinnacle_records::start::{PWD, resolve};
use pinnacle_rt::fs;
use pinnacle_rt::output::{AskKind, Output};
use pinnacle_ui::command::{copy_file, size, when};

/// The most of a file `cat` shows.
const CAT_MAX: u64 = 1 << 20;

/// The last part of a path, for messages.
fn name(path: &str) -> &str {
    path.rsplit('/').next().filter(|n| !n.is_empty()).unwrap_or(path)
}

struct Files {
    out: Output,
    cwd: String,
    home: &'static str,
    /// What went wrong, one line a path.
    failed: Vec<String>,
}

impl Files {
    fn path(&self, path: &str) -> String {
        resolve(&self.cwd, self.home, path)
    }

    fn fail(&mut self, why: String) {
        self.failed.push(why);
    }

    fn ls(&mut self, paths: &[&str]) {
        let paths = if paths.is_empty() { &["."][..] } else { paths };
        for (i, &arg) in paths.iter().enumerate() {
            let path = self.path(arg);
            let Some(stat) = fs::stat(&path).or_else(|| {
                fs::list(&path).map(|_| fs::Stat {
                    directory: true,
                    size: 0,
                    modified: 0,
                })
            }) else {
                self.fail(alloc::format!("No file or folder {path}"));
                continue;
            };
            if paths.len() > 1 {
                if i > 0 {
                    self.out.text("");
                }
                self.out.text(&alloc::format!("{path}:"));
            }
            let mut rows: Vec<(bool, Vec<String>)> = Vec::new();
            if stat.directory {
                for entry in fs::list(&path).unwrap_or_default() {
                    // A folder is listed with a `/` after its name.
                    let entry = String::from(entry.trim_end_matches('/'));
                    let at = alloc::format!("{}/{entry}", path.trim_end_matches('/'));
                    let s = fs::stat(&at);
                    let folder = s.is_some_and(|s| s.directory);
                    let label = if folder { alloc::format!("{entry}/") } else { entry };
                    let row = alloc::vec![
                        label,
                        s.filter(|s| !s.directory)
                            .map_or_else(String::new, |s| size(s.size)),
                        s.map_or_else(String::new, |s| when(s.modified)),
                    ];
                    rows.push((!folder, row));
                }
                // Folders first, then files, each by name.
                rows.sort_by(|a, b| (a.0, &a.1[0]).cmp(&(b.0, &b.1[0])));
            } else {
                rows.push((
                    true,
                    alloc::vec![String::from(name(&path)), size(stat.size), when(stat.modified)],
                ));
            }
            if rows.is_empty() {
                self.out.text("(empty)");
            } else {
                self.out.table(
                    &["Name", "Size", "Changed"],
                    rows.into_iter().map(|(_, r)| r).collect(),
                );
            }
        }
    }

    fn cat(&mut self, paths: &[&str]) {
        if paths.is_empty() {
            return self.fail("cat and a file's path".into());
        }
        for &arg in paths {
            let path = self.path(arg);
            match fs::stat(&path) {
                None => self.fail(alloc::format!("No file {path}")),
                Some(s) if s.directory => self.fail(alloc::format!("{path} is a folder: ls shows it")),
                Some(s) => {
                    let Some(data) = fs::read_at(&path, 0, s.size.min(CAT_MAX) as usize) else {
                        self.fail(alloc::format!("{path} could not be read"));
                        continue;
                    };
                    match core::str::from_utf8(&data) {
                        Ok(text) if !text.contains('\0') => {
                            self.out.text(text.strip_suffix('\n').unwrap_or(text));
                            if s.size > CAT_MAX {
                                self.out.text(&alloc::format!(
                                    "… the first {} of {} shown",
                                    size(CAT_MAX),
                                    size(s.size)
                                ));
                            }
                        }
                        _ => {
                            self.out.text(&alloc::format!(
                                "{}: not text, {} ({} bytes)",
                                name(&path),
                                size(s.size),
                                s.size
                            ));
                        }
                    }
                }
            }
        }
    }

    /// Each folder of the path, made where it is missing.
    fn mkdir(&mut self, paths: &[&str]) {
        if paths.is_empty() {
            return self.fail("mkdir and the new folder's path".into());
        }
        for &arg in paths {
            let path = self.path(arg);
            if fs::stat(&path).is_some() {
                self.fail(alloc::format!("{path} is there already"));
                continue;
            }
            let (disk, rest) = path.split_once(":/").unwrap_or(("data", &path));
            let mut at = alloc::format!("{disk}:");
            for part in rest.split('/') {
                at = alloc::format!("{at}/{part}");
                if fs::stat(&at).is_none() && !fs::create_dir(&at) {
                    self.fail(alloc::format!("{at} could not be made"));
                    break;
                }
            }
        }
    }

    fn rm(&mut self, args: &[&str]) {
        let folders = args.iter().any(|a| matches!(*a, "-r" | "-rf" | "-fr" | "-R"));
        let paths: Vec<&str> = args.iter().copied().filter(|a| !a.starts_with('-')).collect();
        if paths.is_empty() {
            return self.fail("rm and a file's path (rm -r for a folder)".into());
        }
        for arg in paths {
            let path = self.path(arg);
            let Some(stat) = fs::stat(&path) else {
                self.fail(alloc::format!("No file or folder {path}"));
                continue;
            };
            if path.ends_with(":/") {
                self.fail(alloc::format!("{path} is a whole disk: not removed"));
                continue;
            }
            if stat.directory {
                if !folders {
                    self.fail(alloc::format!(
                        "{path} is a folder: rm -r removes it and all in it"
                    ));
                    continue;
                }
                let count = fs::list(&path).map_or(0, |l| l.len());
                let prompt = alloc::format!("Remove the folder {path} and the {count} things in it?");
                if self.out.ask(AskKind::YesNo, &prompt, &[]).as_deref() != Some("Yes") {
                    self.fail(alloc::format!("{path} kept"));
                    continue;
                }
            } else if path.starts_with("system:") {
                let prompt = alloc::format!("{path} is on the system disk: remove it all the same?");
                if self.out.ask(AskKind::YesNo, &prompt, &[]).as_deref() != Some("Yes") {
                    self.fail(alloc::format!("{path} kept"));
                    continue;
                }
            }
            if !fs::remove(&path) {
                self.fail(alloc::format!("{path} could not be removed"));
            }
        }
    }

    /// `from` copied to `to`, or into `to` when it is a folder; `from`
    /// removed after, for `mv`.
    fn copy(&mut self, args: &[&str], moving: bool) {
        let verb = if moving { "mv" } else { "cp" };
        let [from, to] = args else {
            return self.fail(alloc::format!("{verb} and two paths: from, to"));
        };
        let (from, mut to) = (self.path(from), self.path(to));
        match fs::stat(&from) {
            None => return self.fail(alloc::format!("No file {from}")),
            Some(s) if s.directory => {
                return self.fail(alloc::format!("{from} is a folder: {verb} takes files"));
            }
            Some(_) => {}
        }
        if fs::stat(&to).is_some_and(|s| s.directory) {
            to = alloc::format!("{}/{}", to.trim_end_matches('/'), name(&from));
        }
        if to == from {
            return self.fail(alloc::format!("{from} is already there"));
        }
        if let Err(why) = copy_file(&from, &to) {
            return self.fail(why);
        }
        if moving && !fs::remove(&from) {
            self.fail(alloc::format!("{to} written, but {from} could not be removed"));
        }
    }

    /// A file's text, at most [`CAT_MAX`] of it from `from` on; what is
    /// wrong with it said when it is no text file.
    fn text_of(&mut self, path: &str, from: u64) -> Option<String> {
        match fs::stat(path) {
            None => self.fail(alloc::format!("No file {path}")),
            Some(s) if s.directory => self.fail(alloc::format!("{path} is a folder")),
            Some(s) => {
                let from = from.min(s.size);
                let len = (s.size - from).min(CAT_MAX) as usize;
                match fs::read_at(path, from, len) {
                    None => self.fail(alloc::format!("{path} could not be read")),
                    Some(data) if data.contains(&0) => {
                        self.fail(alloc::format!("{path} is not text: hex shows it"))
                    }
                    Some(data) => return Some(String::from_utf8_lossy(&data).into_owned()),
                }
            }
        }
        None
    }

    /// `head` and `tail`: how many lines (`-n 20`, `-20`), then the files.
    fn ends(&mut self, args: &[&str], tail: bool) {
        let mut count = 10usize;
        let mut paths = Vec::new();
        let mut words = args.iter();
        while let Some(&w) = words.next() {
            let n = match w {
                "-n" => words.next().copied(),
                _ if w.starts_with('-') => Some(&w[1..]),
                _ => {
                    paths.push(w);
                    continue;
                }
            };
            match n.and_then(|n| n.parse().ok()) {
                Some(n) => count = n,
                None => return self.fail("How many lines, as a number: tail -n 50 file".into()),
            }
        }
        let verb = if tail { "tail" } else { "head" };
        if paths.is_empty() {
            return self.fail(alloc::format!("{verb} and a file: {verb} -n 20 file"));
        }
        for (i, &arg) in paths.iter().enumerate() {
            let path = self.path(arg);
            // The end of a large file is read from its end, a log's last
            // megabyte and not all of it.
            let from = match tail {
                true => fs::stat(&path).map_or(0, |s| s.size.saturating_sub(CAT_MAX)),
                false => 0,
            };
            let Some(text) = self.text_of(&path, from) else {
                continue;
            };
            let text = text.strip_suffix('\n').unwrap_or(&text);
            let lines: Vec<&str> = text.split('\n').collect();
            let lines = match tail {
                // The first line of a read from the middle may be part of one.
                true if from > 0 && lines.len() > count => &lines[lines.len() - count..],
                true if from > 0 => &lines[1.min(lines.len())..],
                true => &lines[lines.len().saturating_sub(count)..],
                false => &lines[..count.min(lines.len())],
            };
            if paths.len() > 1 {
                if i > 0 {
                    self.out.text("");
                }
                self.out.text(&alloc::format!("{path}:"));
            }
            if !lines.is_empty() {
                self.out.text(&lines.join("\n"));
            }
        }
    }

    /// Every file under `path`, folders gone into, at most `limit` of
    /// them: their paths, each with what `stat` says.
    fn walk(path: &str, limit: usize, found: &mut Vec<(String, fs::Stat)>) {
        let mut folders = alloc::vec![String::from(path)];
        while let Some(folder) = folders.pop() {
            for entry in fs::list(&folder).unwrap_or_default() {
                if found.len() >= limit {
                    return;
                }
                let name = entry.trim_end_matches('/');
                let at = alloc::format!("{}/{name}", folder.trim_end_matches('/'));
                let Some(stat) = fs::stat(&at).or_else(|| {
                    entry.ends_with('/').then_some(fs::Stat {
                        directory: true,
                        size: 0,
                        modified: 0,
                    })
                }) else {
                    continue;
                };
                if stat.directory {
                    folders.push(at.clone());
                }
                found.push((at, stat));
            }
        }
    }

    /// `grep`: `-i` (always so: case aside), `-v` the lines without it, `-r`
    /// folders gone into; then what to look for and where.
    fn grep(&mut self, args: &[&str]) {
        let invert = args.contains(&"-v");
        let recursive = args
            .iter()
            .any(|a| matches!(*a, "-r" | "-R" | "-rn" | "-ri" | "-ir"));
        let words: Vec<&str> = args.iter().copied().filter(|a| !a.starts_with('-')).collect();
        let Some((&wanted, paths)) = words.split_first() else {
            return self.fail("grep, what to look for, and files: grep error log.txt".into());
        };
        let paths: Vec<&str> = if paths.is_empty() && recursive {
            alloc::vec!["."]
        } else {
            paths.to_vec()
        };
        if paths.is_empty() {
            return self.fail("grep and the files to look in: grep error log.txt, or -r for a folder".into());
        }
        let wanted = wanted.to_lowercase();
        let mut files = Vec::new();
        for &arg in &paths {
            let path = self.path(arg);
            match fs::stat(&path)
                .map(|s| s.directory)
                .or_else(|| fs::list(&path).map(|_| true))
            {
                Some(true) if recursive => {
                    let mut found = Vec::new();
                    Self::walk(&path, 10_000, &mut found);
                    files.extend(found.into_iter().filter(|(_, s)| !s.directory).map(|(p, _)| p));
                }
                Some(true) => self.fail(alloc::format!("{path} is a folder: grep -r looks in it")),
                Some(false) => files.push(path),
                None => self.fail(alloc::format!("No file {path}")),
            }
        }
        let many = files.len() > 1 || recursive;
        let mut rows = Vec::new();
        for path in files {
            let Some(data) =
                fs::stat(&path).and_then(|s| fs::read_at(&path, 0, s.size.min(CAT_MAX) as usize))
            else {
                continue;
            };
            // What is not text is passed over in a folder, as grep -I does.
            if data.contains(&0) {
                continue;
            }
            let text = String::from_utf8_lossy(&data);
            for (n, line) in text.lines().enumerate() {
                if line.to_lowercase().contains(&wanted) != invert {
                    let mut row = alloc::vec![alloc::format!("{}", n + 1), String::from(line)];
                    if many {
                        row.insert(0, path.clone());
                    }
                    rows.push(row);
                }
            }
        }
        let summary = rows.len();
        match many {
            true => self.out.table(&["File", "Line", "Text"], rows),
            false => self.out.table(&["Line", "Text"], rows),
        };
        if summary == 0 && self.failed.is_empty() {
            // As grep, finding nothing is not finding, said in the status.
            self.fail("Nothing found".into());
        }
    }

    /// `wc`: each file's lines, words and bytes.
    fn wc(&mut self, paths: &[&str]) {
        if paths.is_empty() {
            return self.fail("wc and a file: wc notes.txt".into());
        }
        let mut rows = Vec::new();
        for &arg in paths {
            let path = self.path(arg);
            let Some(size) = fs::stat(&path).filter(|s| !s.directory).map(|s| s.size) else {
                self.fail(alloc::format!("No file {path}"));
                continue;
            };
            // Counted a megabyte at a time, so a large file fits.
            let (mut lines, mut words, mut at, mut in_word) = (0u64, 0u64, 0u64, false);
            while at < size {
                let Some(part) =
                    fs::read_at(&path, at, CAT_MAX.min(size - at) as usize).filter(|p| !p.is_empty())
                else {
                    break;
                };
                for &b in &part {
                    lines += u64::from(b == b'\n');
                    let space = b.is_ascii_whitespace();
                    words += u64::from(!space && !in_word);
                    in_word = !space;
                }
                at += part.len() as u64;
            }
            rows.push(alloc::vec![
                String::from(name(&path)),
                alloc::format!("{lines}"),
                alloc::format!("{words}"),
                alloc::format!("{size}"),
            ]);
        }
        if !rows.is_empty() {
            self.out.table(&["File", "Lines", "Words", "Bytes"], rows);
        }
    }

    /// `find`: everything under a folder (`.` without one) whose name holds
    /// the text, if one is given.
    fn find(&mut self, args: &[&str]) {
        let (folder, wanted) = match args {
            [] => (".", None),
            [one] if self.is_folder(one) => (*one, None),
            [one] => (".", Some(*one)),
            [folder, wanted] => (*folder, Some(*wanted)),
            _ => return self.fail("find, a folder, and part of a name: find data:/ notes".into()),
        };
        let path = self.path(folder);
        if !self.is_folder(&path) {
            return self.fail(alloc::format!("No folder {path}"));
        }
        const LIMIT: usize = 5000;
        let mut found = Vec::new();
        Self::walk(&path, LIMIT * 4, &mut found);
        let wanted = wanted.map(str::to_lowercase);
        let rows: Vec<Vec<String>> = found
            .into_iter()
            .filter(|(p, _)| {
                wanted
                    .as_ref()
                    .is_none_or(|w| name(p).to_lowercase().contains(w.as_str()))
            })
            .take(LIMIT)
            .map(|(p, s)| {
                let shown = if s.directory { alloc::format!("{p}/") } else { p };
                alloc::vec![
                    shown,
                    if s.directory { String::new() } else { size(s.size) },
                    when(s.modified),
                ]
            })
            .collect();
        if rows.is_empty() {
            return self.fail("Nothing found".into());
        }
        self.out.table(&["Path", "Size", "Changed"], rows);
    }

    fn is_folder(&self, arg: &str) -> bool {
        let path = self.path(arg);
        fs::stat(&path).map_or_else(|| fs::list(&path).is_some(), |s| s.directory)
    }

    /// `du`: what each folder in a folder holds, all under it counted, and
    /// the files beside them; the whole at the end.
    fn du(&mut self, args: &[&str]) {
        let path = self.path(args.first().copied().unwrap_or("."));
        if !self.is_folder(&path) {
            return self.fail(alloc::format!("No folder {path}"));
        }
        let mut rows: Vec<(u64, Vec<String>)> = Vec::new();
        let mut total = 0u64;
        for entry in fs::list(&path).unwrap_or_default() {
            let name = entry.trim_end_matches('/');
            let at = alloc::format!("{}/{name}", path.trim_end_matches('/'));
            let (bytes, files) = match fs::stat(&at) {
                Some(s) if !s.directory => (s.size, 1),
                _ => {
                    let mut found = Vec::new();
                    Self::walk(&at, 100_000, &mut found);
                    let files: Vec<_> = found.iter().filter(|(_, s)| !s.directory).collect();
                    (files.iter().map(|(_, s)| s.size).sum(), files.len())
                }
            };
            total += bytes;
            let label = if entry.ends_with('/') {
                alloc::format!("{name}/")
            } else {
                String::from(name)
            };
            rows.push((bytes, alloc::vec![label, size(bytes), alloc::format!("{files}")]));
        }
        // The largest first: what du is for.
        rows.sort_by_key(|r| core::cmp::Reverse(r.0));
        let mut rows: Vec<Vec<String>> = rows.into_iter().map(|(_, r)| r).collect();
        rows.push(alloc::vec!["(all)".into(), size(total), String::new()]);
        self.out.table(&["Name", "Size", "Files"], rows);
    }

    /// `df`: each disk there is, how large and how full.
    fn df(&mut self) {
        let mut rows = Vec::new();
        for label in ["system", "packages", "data", "backup"] {
            let Some((all, free)) = fs::disk(label) else {
                continue;
            };
            let used = all.saturating_sub(free);
            let percent = used * 100 / all.max(1);
            rows.push(alloc::vec![
                alloc::format!("{label}:/"),
                size(all),
                size(used),
                size(free),
                alloc::format!("{percent}%"),
            ]);
        }
        if rows.is_empty() {
            return self.fail("No disks to say anything of".into());
        }
        self.out.table(&["Disk", "Size", "Used", "Free", "Full"], rows);
    }

    /// `hex`: 512 bytes of a file from an offset (0, or the number after
    /// it), sixteen a row, with their text beside.
    fn hex(&mut self, args: &[&str]) {
        let (arg, offset) = match args {
            [file] => (*file, 0),
            [file, offset] => match offset
                .strip_prefix("0x")
                .map_or_else(|| offset.parse().ok(), |h| u64::from_str_radix(h, 16).ok())
            {
                Some(o) => (*file, o),
                None => return self.fail(alloc::format!("An offset, as a number: not “{offset}”")),
            },
            _ => return self.fail("hex, a file, and an offset if not from its start".into()),
        };
        let path = self.path(arg);
        let Some(data) = fs::stat(&path)
            .filter(|s| !s.directory)
            .and_then(|_| fs::read_at(&path, offset, 512))
        else {
            return self.fail(alloc::format!("No file {path}"));
        };
        let rows = data
            .chunks(16)
            .enumerate()
            .map(|(i, row)| {
                let hex: Vec<String> = row.iter().map(|b| alloc::format!("{b:02x}")).collect();
                let text: String = row
                    .iter()
                    .map(|&b| if (0x20..0x7f).contains(&b) { b as char } else { '.' })
                    .collect();
                alloc::vec![
                    alloc::format!("{:08x}", offset + i as u64 * 16),
                    hex.join(" "),
                    text
                ]
            })
            .collect();
        self.out.table(&["Offset", "Bytes", "Text"], rows);
    }

    fn touch(&mut self, paths: &[&str]) {
        if paths.is_empty() {
            return self.fail("touch and a file's path".into());
        }
        for &arg in paths {
            let path = self.path(arg);
            if fs::stat(&path).is_none() && !fs::write(&path, &[]) {
                self.fail(alloc::format!("{path} could not be made"));
            }
        }
    }
}

#[unsafe(no_mangle)]
fn main(argument: u64) -> u64 {
    let out = Output::start(argument);
    let home = pinnacle_ui::command::home();
    let cwd = out
        .env
        .iter()
        .find(|(k, _)| k == PWD)
        .map_or_else(|| String::from(home), |(_, v)| v.clone());
    let args = out.args.clone();
    let words: Vec<&str> = args.iter().skip(1).map(String::as_str).collect();
    let mut files = Files {
        out,
        cwd,
        home,
        failed: Vec::new(),
    };
    match args.first().map(String::as_str) {
        Some("ls") => files.ls(&words),
        Some("cat") => files.cat(&words),
        Some("mkdir") => files.mkdir(&words),
        Some("rm") => files.rm(&words),
        Some("cp") => files.copy(&words, false),
        Some("mv") => files.copy(&words, true),
        Some("touch") => files.touch(&words),
        Some("head") => files.ends(&words, false),
        Some("tail") => files.ends(&words, true),
        Some("grep") => files.grep(&words),
        Some("wc") => files.wc(&words),
        Some("find") => files.find(&words),
        Some("du") => files.du(&words),
        Some("df") => files.df(),
        Some("hex") => files.hex(&words),
        _ => files.fail("files is started as one of the file commands: help lists them".into()),
    }
    let code = u64::from(!files.failed.is_empty());
    files.out.status(code, &files.failed.join("\n"))
}