mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 13:22:18 +00:00
Merge main into feat/script-include-directives
This commit is contained in:
@@ -63,6 +63,15 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
console_clear
|
||||
),
|
||||
cmd!(
|
||||
query "script.listInstalled",
|
||||
"List Installed Scripts",
|
||||
[],
|
||||
None,
|
||||
"{} list the .js and .jsx files of the Scripts folder next to the settings, which File › Scripts lists, each subfolder as a submenu, in menu order; only names are read, never a script's text; links, hidden files, names starting with a dot and folders without a script are left out. VectorCraft's own limits: 2048 folder entries looked at, 512 scripts, 128 subfolders, 4 levels of subfolders, names of 255 bytes, labels of 128 characters, 250 ms → {folder: the Scripts folder's path | null (a session without one, and the web), scripts: [{path, label: the file name without its extension (the whole file name when another row of its folder has that label), folders: [the labels of the subfolders it is in]}], truncated: a limit was reached or a subfolder could not be read, unreadable: the folder is there and could not be read, or is a link}",
|
||||
always,
|
||||
list_installed
|
||||
),
|
||||
cmd!(
|
||||
query "script.check",
|
||||
"Check Script",
|
||||
@@ -173,6 +182,52 @@ fn console_clear(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
Ok(json!({"cleared": s.clear_script_console()}))
|
||||
}
|
||||
|
||||
/// The error for a script that File › Scripts listed and that [`script::folder::read`] no longer
|
||||
/// reads.
|
||||
pub const NOT_LISTED: &str = "the script is no longer in the Scripts folder";
|
||||
|
||||
impl Session {
|
||||
/// Have File › Scripts and `script.listInstalled` list the scripts of the folder `dir`. The
|
||||
/// folder is only read, and never made.
|
||||
pub fn attach_scripts_dir(&mut self, dir: std::path::PathBuf) {
|
||||
self.scripts_dir = Some(dir);
|
||||
}
|
||||
|
||||
/// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders.
|
||||
pub fn scripts_dir(&self) -> Option<&std::path::Path> {
|
||||
self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32"))
|
||||
}
|
||||
|
||||
/// The text of the script at `path`, which a listing of the Scripts folder gave
|
||||
/// ([`script::folder::read`]), checked as `script.run` checks a file's.
|
||||
pub fn installed_script(&self, path: &str) -> Result<String> {
|
||||
let root = self.scripts_dir().ok_or_else(|| EngineError::Other(NOT_LISTED.to_string()))?;
|
||||
crate::file_access::check_read(path).map_err(EngineError::Other)?;
|
||||
// One byte more than a script may have shows that the file is too large.
|
||||
let bytes = script::folder::read(root, std::path::Path::new(path), script::MAX_SOURCE_BYTES + 1)
|
||||
.ok_or_else(|| EngineError::Other(NOT_LISTED.to_string()))?;
|
||||
if bytes.len() > script::MAX_SOURCE_BYTES {
|
||||
return Err(EngineError::Other(TOO_LARGE.to_string()));
|
||||
}
|
||||
script_text(&bytes)
|
||||
}
|
||||
}
|
||||
|
||||
fn list_installed(s: &mut Session, _: &Value) -> Result<Value> {
|
||||
let Some(root) = s.scripts_dir() else {
|
||||
return Ok(json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false}));
|
||||
};
|
||||
let folder = root.to_string_lossy();
|
||||
crate::file_access::check_read(&folder).map_err(EngineError::Other)?;
|
||||
let listing = script::folder::list(root);
|
||||
let scripts: Vec<Value> = listing
|
||||
.scripts()
|
||||
.into_iter()
|
||||
.map(|(folders, label, path)| json!({"path": path.to_string_lossy(), "label": label, "folders": folders}))
|
||||
.collect();
|
||||
Ok(json!({"folder": folder, "scripts": scripts, "truncated": listing.truncated, "unreadable": listing.unreadable}))
|
||||
}
|
||||
|
||||
/// The folder a script is in, which its included files are read from.
|
||||
struct Folder {
|
||||
dir: std::path::PathBuf,
|
||||
|
||||
@@ -168,6 +168,9 @@ pub struct Session {
|
||||
/// Where the plug-ins `plugin.install` installs are kept; `None`: only for the process
|
||||
/// ([`Session::attach_plugin_store`]).
|
||||
plugin_dir: Option<std::path::PathBuf>,
|
||||
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
|
||||
/// ([`Session::attach_scripts_dir`]).
|
||||
scripts_dir: Option<std::path::PathBuf>,
|
||||
/// The plug-in ids whose grant in the plug-in store should be gone but could not be removed:
|
||||
/// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful
|
||||
/// [`Session::store_grant`] for the id takes it out.
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
//! The Scripts folder: the `.js` and `.jsx` files File › Scripts lists, with each subfolder as a
|
||||
//! submenu ([`list`]), and the read of one of them when it is chosen ([`read`]).
|
||||
//!
|
||||
//! A listing reads names and file types only, never a script's text. It follows no link: a symbolic
|
||||
//! link or a Windows junction is left out, whether it is a file, a folder or the Scripts folder
|
||||
//! itself, so a listed script is a plain file in plain folders under the Scripts folder. Names that
|
||||
//! start with a dot, files and folders Windows marks hidden or system, names that are not Unicode
|
||||
//! and names longer than [`MAX_NAME_BYTES`] are left out too, and so is a folder with no script in
|
||||
//! it.
|
||||
//!
|
||||
//! The values here are VectorCraft's own limits: [`MAX_ENTRIES`], [`MAX_SCRIPTS`], [`MAX_FOLDERS`],
|
||||
//! [`MAX_DEPTH`], [`MAX_NAME_BYTES`], [`MAX_LABEL_CHARS`] and [`MAX_SCAN`]. A listing that reaches
|
||||
//! one of them, or that cannot read a subfolder or an entry of a folder, keeps what it found and
|
||||
//! says so ([`Listing::truncated`]).
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::cmd::scripts::runs;
|
||||
|
||||
/// The most folder entries one listing looks at, in the Scripts folder and its subfolders together.
|
||||
pub const MAX_ENTRIES: usize = 2048;
|
||||
/// The most scripts one listing holds.
|
||||
pub const MAX_SCRIPTS: usize = 512;
|
||||
/// The most subfolders one listing reads.
|
||||
pub const MAX_FOLDERS: usize = 128;
|
||||
/// How many levels of subfolders a listing reads below the Scripts folder.
|
||||
pub const MAX_DEPTH: usize = 4;
|
||||
/// The longest file or folder name a listing takes, in UTF-8 bytes.
|
||||
pub const MAX_NAME_BYTES: usize = 255;
|
||||
/// The most characters of a label; a longer one ends in `…`.
|
||||
pub const MAX_LABEL_CHARS: usize = 128;
|
||||
/// How long one listing may take before it stops with what it found.
|
||||
pub const MAX_SCAN: Duration = Duration::from_millis(250);
|
||||
|
||||
/// The limits of one listing.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
pub entries: usize,
|
||||
pub scripts: usize,
|
||||
pub folders: usize,
|
||||
pub depth: usize,
|
||||
pub time: Duration,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Limits { entries: MAX_ENTRIES, scripts: MAX_SCRIPTS, folders: MAX_FOLDERS, depth: MAX_DEPTH, time: MAX_SCAN }
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of a listing.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
/// A script: its label (the file name without its extension) and the file's path as the folder
|
||||
/// gave it.
|
||||
Script { label: String, path: PathBuf },
|
||||
/// A subfolder with at least one script in it or below it: its label (the folder's name) and
|
||||
/// its rows.
|
||||
Folder { label: String, entries: Vec<Entry> },
|
||||
}
|
||||
|
||||
/// What a Scripts folder holds.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Listing {
|
||||
/// The rows of the folder itself, sorted ([`list_with`]).
|
||||
pub entries: Vec<Entry>,
|
||||
/// Some scripts may be missing: a limit was reached or a subfolder could not be read.
|
||||
pub truncated: bool,
|
||||
/// The folder is there and could not be read, or is a link.
|
||||
pub unreadable: bool,
|
||||
}
|
||||
|
||||
impl Listing {
|
||||
/// Every script with the labels of the folders it is in, in menu order.
|
||||
pub fn scripts(&self) -> Vec<(Vec<&str>, &str, &Path)> {
|
||||
fn walk<'a>(entries: &'a [Entry], folders: &mut Vec<&'a str>, out: &mut Vec<(Vec<&'a str>, &'a str, &'a Path)>) {
|
||||
for e in entries {
|
||||
match e {
|
||||
Entry::Script { label, path } => out.push((folders.clone(), label, path)),
|
||||
Entry::Folder { label, entries } => {
|
||||
folders.push(label);
|
||||
walk(entries, folders, out);
|
||||
folders.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut out = vec![];
|
||||
walk(&self.entries, &mut vec![], &mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// What the folder `root` holds, within the default [`Limits`]. A folder that does not exist gives
|
||||
/// an empty listing.
|
||||
pub fn list(root: &Path) -> Listing {
|
||||
let start = std::time::Instant::now();
|
||||
list_with(root, &Limits::default(), &mut || start.elapsed())
|
||||
}
|
||||
|
||||
/// What the folder `root` holds, within `limits`; `elapsed` says how long the listing has taken.
|
||||
/// Each level is sorted by label without regard to case, then by label, then by file name, with
|
||||
/// scripts and subfolders mixed. Two rows of one level never share a label unless both were cut:
|
||||
/// a script whose label another row has shows its whole file name.
|
||||
pub fn list_with(root: &Path, limits: &Limits, elapsed: &mut dyn FnMut() -> Duration) -> Listing {
|
||||
let unreadable = Listing { unreadable: true, ..Listing::default() };
|
||||
match std::fs::symlink_metadata(root) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Listing::default(),
|
||||
Err(_) => return unreadable,
|
||||
Ok(m) if m.file_type().is_symlink() || !m.is_dir() => return unreadable,
|
||||
Ok(_) => {}
|
||||
}
|
||||
// Paths leave as text (menu params, `script.listInstalled`).
|
||||
if root.to_str().is_none() {
|
||||
return unreadable;
|
||||
}
|
||||
let mut scan = Scan { limits, elapsed, visited: 0, scripts: 0, folders: 0, truncated: false, stopped: false };
|
||||
match scan.level(root, 0) {
|
||||
Some(entries) => Listing { entries, truncated: scan.truncated, unreadable: false },
|
||||
None => unreadable,
|
||||
}
|
||||
}
|
||||
|
||||
/// A script or subfolder found in one folder, before the subfolders are read.
|
||||
struct Found {
|
||||
name: String,
|
||||
label: String,
|
||||
folder: bool,
|
||||
}
|
||||
|
||||
struct Scan<'a> {
|
||||
limits: &'a Limits,
|
||||
elapsed: &'a mut dyn FnMut() -> Duration,
|
||||
visited: usize,
|
||||
scripts: usize,
|
||||
folders: usize,
|
||||
truncated: bool,
|
||||
/// The entry or time limit was reached: nothing more is read.
|
||||
stopped: bool,
|
||||
}
|
||||
|
||||
impl Scan<'_> {
|
||||
/// The rows of the folder `dir`, which is `depth` levels below the Scripts folder; `None` when
|
||||
/// it cannot be read.
|
||||
fn level(&mut self, dir: &Path, depth: usize) -> Option<Vec<Entry>> {
|
||||
let mut found: Vec<Found> = vec![];
|
||||
for entry in std::fs::read_dir(dir).ok()? {
|
||||
if self.visited >= self.limits.entries || (self.elapsed)() > self.limits.time {
|
||||
(self.truncated, self.stopped) = (true, true);
|
||||
break;
|
||||
}
|
||||
self.visited += 1;
|
||||
let Ok(entry) = entry else {
|
||||
self.truncated = true;
|
||||
continue;
|
||||
};
|
||||
let Ok(name) = entry.file_name().into_string() else { continue };
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
self.truncated = true;
|
||||
continue;
|
||||
};
|
||||
if name.len() > MAX_NAME_BYTES || name.starts_with('.') || kind.is_symlink() || hidden(&entry) {
|
||||
continue;
|
||||
}
|
||||
if kind.is_dir() {
|
||||
found.push(Found { label: shown(&name), name, folder: true });
|
||||
} else if kind.is_file() && runs(&name) {
|
||||
if self.scripts >= self.limits.scripts {
|
||||
self.truncated = true;
|
||||
continue;
|
||||
}
|
||||
self.scripts += 1;
|
||||
let stem = name.rsplit_once('.').map_or(name.as_str(), |(stem, _)| stem);
|
||||
found.push(Found { label: shown(stem), name, folder: false });
|
||||
}
|
||||
}
|
||||
// A script whose label another row of this folder has shows its whole file name, until no
|
||||
// label is shared. Each pass gives at least one more script its whole file name, and names
|
||||
// are unique within a folder, so this ends within `found.len()` passes.
|
||||
loop {
|
||||
let mut count = std::collections::HashMap::<String, usize>::new();
|
||||
for f in &found {
|
||||
*count.entry(f.label.clone()).or_default() += 1;
|
||||
}
|
||||
let mut renamed = false;
|
||||
for f in found.iter_mut().filter(|f| !f.folder) {
|
||||
if count.get(&f.label).is_some_and(|n| *n > 1) {
|
||||
let whole = shown(&f.name);
|
||||
if f.label != whole {
|
||||
f.label = whole;
|
||||
renamed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !renamed {
|
||||
break;
|
||||
}
|
||||
}
|
||||
found.sort_by(|a, b| (a.label.to_lowercase(), &a.label, &a.name).cmp(&(b.label.to_lowercase(), &b.label, &b.name)));
|
||||
let mut out = Vec::with_capacity(found.len());
|
||||
for f in found {
|
||||
let path = dir.join(&f.name);
|
||||
if !f.folder {
|
||||
out.push(Entry::Script { label: f.label, path });
|
||||
continue;
|
||||
}
|
||||
if self.stopped {
|
||||
continue;
|
||||
}
|
||||
if depth >= self.limits.depth || self.folders >= self.limits.folders {
|
||||
self.truncated = true;
|
||||
continue;
|
||||
}
|
||||
self.folders += 1;
|
||||
match self.level(&path, depth + 1) {
|
||||
Some(entries) if entries.is_empty() => {}
|
||||
Some(entries) => out.push(Entry::Folder { label: f.label, entries }),
|
||||
None => self.truncated = true,
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
}
|
||||
|
||||
/// `name` as a menu shows it: control and bidirectional formatting characters written as escapes,
|
||||
/// and at most [`MAX_LABEL_CHARS`] characters.
|
||||
fn shown(name: &str) -> String {
|
||||
vectorcraft_plugins::permissions::display_text(name, MAX_LABEL_CHARS)
|
||||
}
|
||||
|
||||
/// Does Windows mark `entry` hidden or system?
|
||||
fn hidden(entry: &std::fs::DirEntry) -> bool {
|
||||
entry.metadata().is_ok_and(|m| hidden_meta(&m))
|
||||
}
|
||||
|
||||
/// Does Windows mark the file or folder of `m` hidden or system?
|
||||
#[cfg(windows)]
|
||||
fn hidden_meta(m: &std::fs::Metadata) -> bool {
|
||||
use std::os::windows::fs::MetadataExt as _;
|
||||
const HIDDEN_OR_SYSTEM: u32 = 0x2 | 0x4;
|
||||
m.file_attributes() & HIDDEN_OR_SYSTEM != 0
|
||||
}
|
||||
|
||||
/// Elsewhere a hidden file is one whose name starts with a dot, which the listing leaves out by name.
|
||||
#[cfg(not(windows))]
|
||||
fn hidden_meta(_: &std::fs::Metadata) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Is `path` a folder (`folder`) or a file, and not a link? With `shown`, also not one Windows
|
||||
/// marks hidden or system, which a listing leaves out.
|
||||
fn plain(path: &Path, folder: bool, shown: bool) -> bool {
|
||||
std::fs::symlink_metadata(path)
|
||||
.is_ok_and(|m| !m.file_type().is_symlink() && (if folder { m.is_dir() } else { m.is_file() }) && !(shown && hidden_meta(&m)))
|
||||
}
|
||||
|
||||
/// Is `path` a script a listing of `root` can hold now: a `.js` or `.jsx` file at most
|
||||
/// [`MAX_DEPTH`] folders below `root`, where `root`, each folder on the way and the file are there
|
||||
/// and none is a link, and neither the file nor a folder below `root` is marked hidden or system?
|
||||
pub fn holds(root: &Path, path: &Path) -> bool {
|
||||
let Ok(rest) = path.strip_prefix(root) else { return false };
|
||||
let names: Option<Vec<&str>> = rest
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
Component::Normal(name) => name.to_str().filter(|n| !n.starts_with('.') && n.len() <= MAX_NAME_BYTES),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let Some(names) = names else { return false };
|
||||
let Some((file, folders)) = names.split_last() else { return false };
|
||||
if folders.len() > MAX_DEPTH || !runs(file) || !plain(root, true, false) {
|
||||
return false;
|
||||
}
|
||||
let mut at = root.to_path_buf();
|
||||
for folder in folders {
|
||||
at.push(folder);
|
||||
if !plain(&at, true, true) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
at.push(file);
|
||||
plain(&at, false, true)
|
||||
}
|
||||
|
||||
/// The first `max` bytes of the script at `path`, or `None` when [`holds`] does not hold for it
|
||||
/// before the read and again after it, or it cannot be read. The two checks leave no time in which
|
||||
/// a link stood in for the file or one of its folders for the whole read; a program that swaps one
|
||||
/// in and back out between a check and the open can still have another file read.
|
||||
pub fn read(root: &Path, path: &Path, max: usize) -> Option<Vec<u8>> {
|
||||
if !holds(root, path) {
|
||||
return None;
|
||||
}
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
if !file.metadata().is_ok_and(|m| m.is_file()) {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = vec![];
|
||||
file.take(max as u64).read_to_end(&mut bytes).ok()?;
|
||||
holds(root, path).then_some(bytes)
|
||||
}
|
||||
@@ -50,6 +50,8 @@ use crate::{
|
||||
Clipboard, DocState, DrawMode, EngineError, Journal, NodeId, PaintDefaults, Result, Session, cmd, command_specs, guard, waits_for_tool_edit,
|
||||
};
|
||||
|
||||
pub mod folder;
|
||||
|
||||
/// The most bytes of source a run takes, as a file or as `source`.
|
||||
pub const MAX_SOURCE_BYTES: usize = 8 << 20;
|
||||
/// The instructions a run may execute when `maxFuel` is left out.
|
||||
|
||||
@@ -86,6 +86,7 @@ impl Session {
|
||||
profile_dir: None,
|
||||
color_settings_file: None,
|
||||
plugin_dir: None,
|
||||
scripts_dir: None,
|
||||
ignored_plugin_grants: Default::default(),
|
||||
plugin_output: None,
|
||||
plugin_install_approval: None,
|
||||
|
||||
@@ -151,6 +151,7 @@ mod save;
|
||||
mod saveoptions;
|
||||
mod scalestrokes;
|
||||
mod script_console;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
mod script_run;
|
||||
mod scripts;
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
//! The Scripts folder: what a listing holds and leaves out, its order and labels, its limits, the
|
||||
//! read of a listed script, `script.listInstalled` and the automation read root.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use crate::script::folder::{self, Entry, Limits, Listing};
|
||||
use crate::*;
|
||||
|
||||
/// A fresh folder for the files of test `name`, holding an empty `Scripts` folder.
|
||||
fn folder(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-folder-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("Scripts")).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// Writes the empty file `name` (folders included) under `root`.
|
||||
fn touch(root: &Path, name: &str) -> PathBuf {
|
||||
let path = root.join(name);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, "").unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
/// Makes `link` lead to the folder `target`: a symbolic link, or on Windows a junction, which needs
|
||||
/// no privilege.
|
||||
fn link_folder(target: &Path, link: &Path) {
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(target, link).unwrap();
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let made = std::process::Command::new("cmd").args(["/C", "mklink", "/J"]).arg(link).arg(target).output().unwrap();
|
||||
assert!(made.status.success(), "mklink /J: {}", String::from_utf8_lossy(&made.stderr));
|
||||
}
|
||||
}
|
||||
|
||||
/// A listing's rows as text: `label`, or `label/` followed by the folder's rows in brackets.
|
||||
fn rows(entries: &[Entry]) -> String {
|
||||
let row = |e: &Entry| match e {
|
||||
Entry::Script { label, .. } => label.clone(),
|
||||
Entry::Folder { label, entries } => format!("{label}/[{}]", rows(entries)),
|
||||
};
|
||||
entries.iter().map(row).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
/// A listing within `limits` that takes no time.
|
||||
fn list(root: &Path, limits: Limits) -> Listing {
|
||||
folder::list_with(root, &limits, &mut || Duration::ZERO)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scripts_and_subfolders_are_listed_by_name_without_the_extension() {
|
||||
let dir = folder("names");
|
||||
let root = dir.join("Scripts");
|
||||
for name in
|
||||
["b.js", "A.JSX", "Dessin (été) #1.jsx", "v1.2 draft.Js", "Zeta/inner.jsx", "Zeta/Deep/x.js", "notes.txt", "x.jsxbin", "lib.jsxinc", "js"]
|
||||
{
|
||||
touch(&root, name);
|
||||
}
|
||||
std::fs::create_dir_all(root.join("Empty/Also Empty")).unwrap();
|
||||
let listing = folder::list(&root);
|
||||
assert_eq!(rows(&listing.entries), "A, b, Dessin (été) #1, v1.2 draft, Zeta/[Deep/[x], inner]");
|
||||
assert!(!listing.truncated && !listing.unreadable);
|
||||
// Each script keeps the path the folder gave, whatever its label.
|
||||
let paths: Vec<_> =
|
||||
listing.scripts().into_iter().map(|(folders, label, path)| (folders.join("/"), label.to_string(), path.to_path_buf())).collect();
|
||||
assert_eq!(paths[0], (String::new(), "A".to_string(), root.join("A.JSX")));
|
||||
assert_eq!(paths[4], ("Zeta/Deep".to_string(), "x".to_string(), root.join("Zeta").join("Deep").join("x.js")));
|
||||
assert_eq!(paths.len(), 6);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_whose_label_another_row_has_shows_its_whole_file_name() {
|
||||
let dir = folder("same");
|
||||
let root = dir.join("Scripts");
|
||||
for name in ["tidy.js", "tidy.jsx", "tidy.js.js", "tidy/x.js", "alone.jsx"] {
|
||||
touch(&root, name);
|
||||
}
|
||||
// `tidy.js.js` is labeled `tidy.js` until `tidy.js` takes that label, then shows its whole name.
|
||||
assert_eq!(rows(&folder::list(&root).entries), "alone, tidy/[x], tidy.js, tidy.js.js, tidy.jsx");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_characters_in_a_name_are_written_as_escapes_and_a_long_label_is_cut() {
|
||||
let dir = folder("escapes");
|
||||
let root = dir.join("Scripts");
|
||||
// A right-to-left override, which would show the name backwards.
|
||||
touch(&root, "a\u{202E}sj.js");
|
||||
let long = "n".repeat(200);
|
||||
touch(&root, &format!("{long}.jsx"));
|
||||
let listing = folder::list(&root);
|
||||
let labels: Vec<&str> = listing.scripts().into_iter().map(|(_, label, _)| label).collect();
|
||||
assert_eq!(labels[0], "a\\u{202E}sj");
|
||||
assert_eq!(labels[1], format!("{}…", "n".repeat(folder::MAX_LABEL_CHARS - 1)));
|
||||
assert!(folder::holds(&root, &root.join(format!("{long}.jsx"))));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_names_and_links_are_left_out() {
|
||||
let dir = folder("hidden");
|
||||
let root = dir.join("Scripts");
|
||||
touch(&root, "shown.js");
|
||||
touch(&root, ".hidden.js");
|
||||
touch(&root, ".git/hook.js");
|
||||
let outside = touch(&dir, "Outside/secret.js");
|
||||
// A link out of the folder, and one back to the folder itself.
|
||||
link_folder(outside.parent().unwrap(), &root.join("Out"));
|
||||
link_folder(&root, &root.join("Loop"));
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&outside, root.join("linked.js")).unwrap();
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let marked = touch(&root, "marked.js");
|
||||
assert!(std::process::Command::new("attrib").arg("+h").arg(&marked).status().unwrap().success());
|
||||
}
|
||||
let listing = folder::list(&root);
|
||||
assert_eq!(rows(&listing.entries), "shown");
|
||||
assert!(!listing.truncated && !listing.unreadable);
|
||||
// Nor is a file behind a link read as a listed script.
|
||||
assert!(folder::read(&root, &root.join("shown.js"), 10).is_some());
|
||||
for path in [root.join("Out").join("secret.js"), root.join("Loop").join("shown.js"), root.join(".hidden.js"), root.join("linked.js")] {
|
||||
assert!(folder::read(&root, &path, 10).is_none(), "{}", path.display());
|
||||
}
|
||||
// A script, or the folder it is in, that Windows marks hidden after a listing is not read.
|
||||
#[cfg(windows)]
|
||||
{
|
||||
assert!(folder::read(&root, &root.join("marked.js"), 10).is_none());
|
||||
let inner = touch(&root, "Sub/inner.js");
|
||||
assert!(folder::read(&root, &inner, 10).is_some());
|
||||
assert!(std::process::Command::new("attrib").arg("+h").arg(root.join("Sub")).status().unwrap().success());
|
||||
assert!(folder::read(&root, &inner, 10).is_none());
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(root.join("Out"));
|
||||
let _ = std::fs::remove_dir_all(root.join("Loop"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_that_is_missing_is_empty_and_one_that_is_a_file_or_a_link_is_unreadable() {
|
||||
let dir = folder("root");
|
||||
let root = dir.join("Scripts");
|
||||
touch(&root, "a.js");
|
||||
assert_eq!(folder::list(&dir.join("None")), Listing::default());
|
||||
let file = touch(&dir, "file");
|
||||
assert_eq!(folder::list(&file), Listing { unreadable: true, ..Listing::default() });
|
||||
let link = dir.join("Link");
|
||||
link_folder(&root, &link);
|
||||
assert_eq!(folder::list(&link), Listing { unreadable: true, ..Listing::default() });
|
||||
assert!(folder::read(&link, &link.join("a.js"), 10).is_none());
|
||||
let _ = std::fs::remove_dir_all(&link);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_limit_stops_a_listing_with_what_it_found() {
|
||||
let dir = folder("limits");
|
||||
let root = dir.join("Scripts");
|
||||
for n in 0..10 {
|
||||
touch(&root, &format!("s{n}.js"));
|
||||
}
|
||||
let all = Limits::default();
|
||||
let entries = list(&root, Limits { entries: 4, ..all });
|
||||
assert_eq!((entries.scripts().len(), entries.truncated), (4, true));
|
||||
let scripts = list(&root, Limits { scripts: 3, ..all });
|
||||
assert_eq!((scripts.scripts().len(), scripts.truncated), (3, true));
|
||||
// The clock passes the time limit at the third entry.
|
||||
let mut calls = 0;
|
||||
let timed = folder::list_with(&root, &all, &mut || {
|
||||
calls += 1;
|
||||
if calls > 2 { all.time + Duration::from_millis(1) } else { Duration::ZERO }
|
||||
});
|
||||
assert_eq!((timed.scripts().len(), timed.truncated), (2, true));
|
||||
let whole = list(&root, all);
|
||||
assert_eq!((whole.scripts().len(), whole.truncated), (10, false));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subfolders_past_the_fourth_level_or_the_folder_limit_are_left_out() {
|
||||
let dir = folder("depth");
|
||||
let root = dir.join("Scripts");
|
||||
touch(&root, "1/2/3/4/kept.js");
|
||||
touch(&root, "1/2/3/4/5/deeper.js");
|
||||
let listing = folder::list(&root);
|
||||
assert_eq!(rows(&listing.entries), "1/[2/[3/[4/[kept]]]]");
|
||||
assert!(listing.truncated);
|
||||
assert!(folder::holds(&root, &root.join("1/2/3/4/kept.js")));
|
||||
assert!(!folder::holds(&root, &root.join("1/2/3/4/5/deeper.js")));
|
||||
let two = folder("folders");
|
||||
let root = two.join("Scripts");
|
||||
touch(&root, "a/x.js");
|
||||
touch(&root, "b/y.js");
|
||||
let listing = list(&root, Limits { folders: 1, ..Limits::default() });
|
||||
assert_eq!(rows(&listing.entries), "a/[x]");
|
||||
assert!(listing.truncated);
|
||||
assert!(!folder::list(&root).truncated);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
let _ = std::fs::remove_dir_all(two);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_with_more_scripts_than_the_limit_lists_that_many() {
|
||||
let dir = folder("many");
|
||||
let root = dir.join("Scripts");
|
||||
for n in 0..folder::MAX_SCRIPTS + 40 {
|
||||
touch(&root, &format!("s{n:04}.js"));
|
||||
}
|
||||
let listing = list(&root, Limits::default());
|
||||
assert_eq!((listing.scripts().len(), listing.truncated), (folder::MAX_SCRIPTS, true));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_takes_only_a_script_that_is_still_a_file_under_the_folder() {
|
||||
let dir = folder("read");
|
||||
let root = dir.join("Scripts");
|
||||
let script = touch(&root, "Sub/draw.jsx");
|
||||
std::fs::write(&script, "vc.log(1);").unwrap();
|
||||
assert_eq!(folder::read(&root, &script, 100).as_deref(), Some(&b"vc.log(1);"[..]));
|
||||
assert_eq!(folder::read(&root, &script, 4).as_deref(), Some(&b"vc.l"[..]));
|
||||
let outside = touch(&dir, "outside.js");
|
||||
touch(&root, "notes.txt");
|
||||
for path in [outside, root.join("Sub").join("..").join("..").join("outside.js"), root.join("notes.txt"), root.join("Sub"), root.join("gone.js")] {
|
||||
assert!(folder::read(&root, &path, 100).is_none(), "{}", path.display());
|
||||
}
|
||||
// A folder that took the script's place is not a script.
|
||||
std::fs::remove_file(&script).unwrap();
|
||||
std::fs::create_dir(&script).unwrap();
|
||||
assert!(folder::read(&root, &script, 100).is_none());
|
||||
// Nor is the script read once a link stands in for its folder.
|
||||
let other = touch(&dir, "Other/draw.jsx");
|
||||
std::fs::remove_dir_all(root.join("Sub")).unwrap();
|
||||
link_folder(other.parent().unwrap(), &root.join("Sub"));
|
||||
assert!(folder::read(&root, &root.join("Sub").join("draw.jsx"), 100).is_none());
|
||||
let _ = std::fs::remove_dir_all(root.join("Sub"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_installed_gives_the_folder_and_its_scripts_in_menu_order() {
|
||||
let dir = folder("command");
|
||||
let root = dir.join("Scripts");
|
||||
touch(&root, "Tidy Layers.jsx");
|
||||
touch(&root, "Export/All Artboards.js");
|
||||
let mut s = Session::new();
|
||||
assert_eq!(
|
||||
s.execute("script.listInstalled", &json!({})).unwrap(),
|
||||
json!({"folder": null, "scripts": [], "truncated": false, "unreadable": false})
|
||||
);
|
||||
s.attach_scripts_dir(root.clone());
|
||||
let text = |p: &Path| p.to_string_lossy().into_owned();
|
||||
assert_eq!(
|
||||
s.execute("script.listInstalled", &json!({})).unwrap(),
|
||||
json!({
|
||||
"folder": text(&root),
|
||||
"scripts": [
|
||||
{"path": text(&root.join("Export").join("All Artboards.js")), "label": "All Artboards", "folders": ["Export"]},
|
||||
{"path": text(&root.join("Tidy Layers.jsx")), "label": "Tidy Layers", "folders": []},
|
||||
],
|
||||
"truncated": false,
|
||||
"unreadable": false,
|
||||
})
|
||||
);
|
||||
assert!(!find_command("script.listInstalled").unwrap().journal);
|
||||
assert!(s.execute("script.listInstalled", &json!({"folder": "x"})).is_err());
|
||||
// A folder that is not there yet lists nothing, and the listing does not make it.
|
||||
std::fs::remove_dir_all(&root).unwrap();
|
||||
assert_eq!(s.execute("script.listInstalled", &json!({})).unwrap()["scripts"], json!([]));
|
||||
assert!(!root.exists());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_installed_script_is_read_as_script_run_reads_a_file() {
|
||||
let dir = folder("installed");
|
||||
let root = dir.join("Scripts");
|
||||
let text = |p: &Path| p.to_string_lossy().into_owned();
|
||||
let mut s = Session::new();
|
||||
let script = touch(&root, "draw.jsx");
|
||||
std::fs::write(&script, "\u{feff}vc.log(1);").unwrap();
|
||||
assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED, "no folder is attached");
|
||||
s.attach_scripts_dir(root.clone());
|
||||
assert_eq!(s.installed_script(&text(&script)).unwrap(), "vc.log(1);");
|
||||
std::fs::write(&script, "@JSXBIN@ES@2.0@").unwrap();
|
||||
assert!(s.installed_script(&text(&script)).unwrap_err().to_string().contains("compiled script"));
|
||||
std::fs::write(&script, [0xff, 0xfe]).unwrap();
|
||||
assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), "the script is not UTF-8 text");
|
||||
std::fs::write(&script, vec![b' '; script::MAX_SOURCE_BYTES + 1]).unwrap();
|
||||
assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::TOO_LARGE);
|
||||
std::fs::remove_file(&script).unwrap();
|
||||
assert_eq!(s.installed_script(&text(&script)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED);
|
||||
let outside = touch(&dir, "outside.js");
|
||||
assert_eq!(s.installed_script(&text(&outside)).unwrap_err().to_string(), cmd::scripts::NOT_LISTED);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_automation_read_root_keeps_an_agent_out_of_the_scripts_folder() {
|
||||
let dir = folder("roots");
|
||||
let root = dir.join("Scripts");
|
||||
let script = touch(&root, "draw.js");
|
||||
let work = dir.join("work");
|
||||
std::fs::create_dir_all(&work).unwrap();
|
||||
let mut s = Session::new();
|
||||
s.attach_scripts_dir(root.clone());
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&work], &[]).unwrap().unwrap();
|
||||
let e = crate::file_access::confine(Some(&roots), || s.execute("script.listInstalled", &json!({}))).unwrap_err();
|
||||
assert!(e.to_string().contains("outside the read root"), "{e}");
|
||||
let e = crate::file_access::confine(Some(&roots), || s.installed_script(&script.to_string_lossy())).unwrap_err();
|
||||
assert!(e.to_string().contains("outside the read root"), "{e}");
|
||||
// A read root that holds the folder lets both through.
|
||||
let roots = crate::file_access::AutomationRoots::new(&[&dir], &[]).unwrap().unwrap();
|
||||
crate::file_access::confine(Some(&roots), || {
|
||||
assert_eq!(s.execute("script.listInstalled", &json!({})).unwrap()["scripts"][0]["label"], "draw");
|
||||
assert_eq!(s.installed_script(&script.to_string_lossy()).unwrap(), "");
|
||||
});
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
Reference in New Issue
Block a user