mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 19:41:36 -05:00
Merge pull request #10483 from dotCooCoo/fix/windows-evalfile-uri
Scripts: $.evalFile reads the URI paths File.parent gives, on Windows too
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -1352,7 +1352,7 @@ fn encode(s: &str) -> String {
|
||||
}
|
||||
|
||||
/// `s` with its `%xx` escapes read as UTF-8 bytes; `s` as it is when they do not make UTF-8.
|
||||
fn decode(s: &str) -> String {
|
||||
pub(crate) fn decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
|
||||
@@ -359,6 +359,32 @@ fn has_parent(p: &str) -> bool {
|
||||
p.split(['/', '\\']).any(|name| name == "..")
|
||||
}
|
||||
|
||||
/// The paths `value` can name in a `File`'s URI notation, as `File.parent` and `File.fullName` give
|
||||
/// them, other than `value` as written: on a platform that reads drive letters (`windows`), `/c/…`
|
||||
/// is the drive path `C:/…`, and on every platform `%20` and the other escapes are decoded. Only a
|
||||
/// path that starts with one `/` has them; `$.evalFile` tries them after `value` as written
|
||||
/// misses. A `//host/share` path, and a form with a `..` name, is left out.
|
||||
pub fn uri_forms(value: &str, windows: bool) -> Vec<String> {
|
||||
if !value.starts_with('/') || value.starts_with("//") {
|
||||
return Vec::new();
|
||||
}
|
||||
let drive = value.strip_prefix('/').filter(|_| windows && !value.starts_with("//")).and_then(|rest| {
|
||||
let (first, after) = rest.split_once('/').unwrap_or((rest, ""));
|
||||
let letter = first.as_bytes();
|
||||
(letter.len() == 1 && letter[0].is_ascii_alphabetic()).then(|| format!("{}:/{after}", letter[0].to_ascii_uppercase() as char))
|
||||
});
|
||||
let mut forms = Vec::new();
|
||||
for form in drive.iter().map(String::as_str).chain(drive.is_none().then_some(value)) {
|
||||
let decoded = crate::script::files::decode(form);
|
||||
for f in [decoded.as_str(), form] {
|
||||
if f != value && !has_parent(f) && !(windows && f.replace('\\', "/").starts_with("//")) && !forms.iter().any(|g| g == f) {
|
||||
forms.push(f.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
forms
|
||||
}
|
||||
|
||||
/// A real path as people read it.
|
||||
fn display(path: &Path) -> Arc<str> {
|
||||
Arc::from(crate::cmd::findfiles::plain(path.to_path_buf()).to_string_lossy().as_ref())
|
||||
@@ -575,13 +601,18 @@ impl Files {
|
||||
let refused = || (FailKind::Error, format!("script file read refused: {value}"));
|
||||
// A script given as text has no folder, and so no file it may read.
|
||||
let Some(dir) = dir.filter(|_| !has_parent(value)) else { return Err(refused()) };
|
||||
// Each candidate, and whether the scope's refusal passes it over.
|
||||
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), false)];
|
||||
// Each candidate, and whether the scope's refusal passes it over. The path as written comes
|
||||
// first; for `$.evalFile` only, when it misses, fails or is refused, the forms of a path in
|
||||
// URI notation are tried, and when none of them is read either, the error of the path as written stands.
|
||||
let forms = if search { Vec::new() } else { uri_forms(value, cfg!(windows)) };
|
||||
let mut literal_error = None;
|
||||
let mut candidates: Vec<(Option<PathBuf>, bool)> = vec![(Some(dir.join(path)), !forms.is_empty())];
|
||||
candidates.extend(forms.into_iter().map(|f| (Some(dir.join(f)), true)));
|
||||
if search && !path.is_absolute() {
|
||||
candidates.extend(self.include_path.iter().map(|p| ((!has_parent(p)).then(|| dir.join(p).join(path)), false)));
|
||||
candidates.extend(self.jsinclude.iter().filter(|p| p.is_absolute()).map(|p| (Some(p.join(path)), true)));
|
||||
}
|
||||
for (candidate, passed_over_when_refused) in candidates {
|
||||
for (i, (candidate, passed_over_when_refused)) in candidates.into_iter().enumerate() {
|
||||
let Some(candidate) = candidate else { return Err(refused()) };
|
||||
self.probes += 1;
|
||||
if self.probes > MAX_PROBES {
|
||||
@@ -590,12 +621,22 @@ impl Files {
|
||||
match self.scope.read(&candidate, crate::script::MAX_SOURCE_BYTES) {
|
||||
Ok(found) => return Ok(found),
|
||||
Err(ScriptRead::Missing) => {}
|
||||
Err(ScriptRead::Refused) if passed_over_when_refused => {}
|
||||
Err(ScriptRead::Refused) if passed_over_when_refused => {
|
||||
if i == 0 {
|
||||
literal_error = Some(refused());
|
||||
}
|
||||
}
|
||||
Err(ScriptRead::Refused) => return Err(refused()),
|
||||
Err(ScriptRead::TooLarge) => return Err((FailKind::Limit, format!("script file is too large: {value}"))),
|
||||
Err(ScriptRead::Failed(e)) if i == 0 && passed_over_when_refused => {
|
||||
literal_error = Some((FailKind::Error, format!("cannot read script file {value}: {e}")));
|
||||
}
|
||||
Err(ScriptRead::Failed(e)) => return Err((FailKind::Error, format!("cannot read script file {value}: {e}"))),
|
||||
}
|
||||
}
|
||||
if let Some(error) = literal_error {
|
||||
return Err(error);
|
||||
}
|
||||
Err((FailKind::Error, format!("include file not found: {value}")))
|
||||
}
|
||||
|
||||
|
||||
@@ -301,6 +301,40 @@ fn files_are_checked_before_they_are_read() {
|
||||
assert!(s.execute("script.run", &path(&dir.join("folder.js").to_string_lossy())).is_err());
|
||||
}
|
||||
|
||||
/// `$.evalFile` also tries a path in a `File`'s URI notation, as `File.parent` gives
|
||||
/// it: on Windows `/c/…` as the drive path `C:/…`, and on every platform with its escapes decoded,
|
||||
/// after the path as written misses. Relative, share, device and `..` forms are not tried.
|
||||
#[test]
|
||||
fn include_paths_in_uri_notation_name_a_windows_drive() {
|
||||
use crate::script::include::uri_forms;
|
||||
assert_eq!(uri_forms("/c/Users/Test/more.jsx", true), ["C:/Users/Test/more.jsx"]);
|
||||
assert_eq!(uri_forms("/d", true), ["D:/"]);
|
||||
assert_eq!(uri_forms("/c/My%20Scripts/more.jsx", true), ["C:/My Scripts/more.jsx", "C:/My%20Scripts/more.jsx"]);
|
||||
assert_eq!(uri_forms("/home/My%20Scripts/more.jsx", false), ["/home/My Scripts/more.jsx"]);
|
||||
assert!(uri_forms("/c/Users/Test/more.jsx", false).is_empty());
|
||||
for kept in
|
||||
["//host/share/more.jsx", "//?/c/more.jsx", "/c/x/../more.jsx", "/Users/more.jsx", "more.jsx", "my%20file.jsx", "C:/more.jsx", "/1/more.jsx"]
|
||||
{
|
||||
assert!(uri_forms(kept, true).is_empty(), "{kept}: {:?}", uri_forms(kept, true));
|
||||
}
|
||||
assert_eq!(uri_forms("/c/%2E%2E/more.jsx", true), ["C:/%2E%2E/more.jsx"], "an escaped `..` is not decoded into a parent name");
|
||||
// From a folder whose name has a space, `File.parent` gives `%20`, and the sibling is read.
|
||||
let dir = fresh_folder("uri forms");
|
||||
std::fs::write(dir.join("more.jsx"), "'more';").unwrap();
|
||||
let main = dir.join("main.jsx");
|
||||
std::fs::write(&main, "vc.log(File($.fileName).parent + '');\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n").unwrap();
|
||||
let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert!(r["log"][0].as_str().is_some_and(|p| p.contains("uri%20forms")), "{r}");
|
||||
assert_eq!(r["log"][1], "more", "{r}");
|
||||
// A file whose name holds `%20` as written is read before the decoded name.
|
||||
std::fs::write(dir.join("part%20one.jsx"), "'literal';").unwrap();
|
||||
std::fs::write(dir.join("part one.jsx"), "'decoded';").unwrap();
|
||||
let literal = dir.join("part%20one.jsx").to_string_lossy().replace('\\', "/");
|
||||
std::fs::write(&main, format!("vc.log($.evalFile({literal:?}));\n")).unwrap();
|
||||
let r = two_docs().execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap();
|
||||
assert_eq!(r["log"], json!(["literal"]), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
|
||||
let dir = fresh_folder("es2015");
|
||||
|
||||
+3
-1
@@ -3558,7 +3558,9 @@ through `$`:
|
||||
`$.writeln(...values)` does the same and ends the line. Each call counts as a host call.
|
||||
- `$.evalFile(path, timeout?)` runs the file `path` names, relative to the file being run, in the same global
|
||||
environment, so its functions and variables stay defined, and returns its last value (`undefined` for an empty
|
||||
file). Its preprocessor lines are read as the script's are. `timeout` is a number of milliseconds from 0; the file
|
||||
file). Its preprocessor lines are read as the script's are. An absolute path in a `File`'s URI notation, as
|
||||
`File.parent` gives it, is read too: when the path as written names no file it may read, `%20` and the other
|
||||
escapes are decoded, and on Windows `/c/…` names the drive `C:`. `timeout` is a number of milliseconds from 0; the file
|
||||
is read at once and `timeout` is not waited on. The run's fuel and limits apply to the file. An empty path, a
|
||||
missing file and a refused path throw errors the script can catch.
|
||||
- `$.fileName` is the file of the code that reads it: the script, a file it included with `#include`, or a file
|
||||
|
||||
@@ -1142,7 +1142,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: an error `$.evalFile` throws for a file it cannot run is reported at that file's line and column only while no `catch` has taken it. Caught and thrown again later, in the script or in another file, it is reported where it was thrown again, and a new error whose message holds its text is reported where that error was thrown. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`.
|
||||
- Scripts: an uncaught error that one or more `finally` blocks pass on unchanged, in the script or in a function it called, is reported at the line and column where it was thrown, in `script.run`'s report and the Script Console. An error a `finally` block throws is reported at that throw, and one its `return`, `break` or `continue` discards is not reported. VectorCraft's own rule. `crates/engine/src/tests/script_include.rs`, `crates/js/src/host_tests.rs`.
|
||||
- Scripts: an error a `finally` block passes on is still reported where it was thrown when the block's allocations collect garbage under a small heap limit, and a `finally` block that `return`, `break` or `continue` leaves drops the saved location of its error as it leaves, so a collection no longer counts that code as live. VectorCraft's own rule. `crates/js/src/host_tests.rs`.
|
||||
- Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`).
|
||||
- Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, `$.fileName` gives the file of the code that reads it (the file being run for code that `eval` or `Function` compiled), and `$.includePath` the include folders. `$.evalFile` tries the path as written first; only when that file is missing, fails to read (a file over the size limit stops the lookup) or is refused does it read an absolute path in a `File`'s URI notation, with escapes decoded and `/c/...` naming drive C: on Windows. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`).
|
||||
- Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`.
|
||||
- Scripts: `$.fileName` is a read-only name of the script file in use ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: it names the file of the code that reads it, so a function a file included with `#include` or run with `$.evalFile` defined, or one an earlier run of a named engine kept, gives its own file and not the calling file; code from a script given as `source`, and kept code whose place the engine dropped, gives an empty name, and code that `eval` or `Function` compiled gives the file being run. `crates/engine/src/tests/script_include.rs`, `crates/engine/src/tests/script_engines.rs`.
|
||||
- Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`.
|
||||
|
||||
Reference in New Issue
Block a user