difftreelog
refactor receive Path in public api arguments
in: master
Fixes #39 Fixes #47
14 files changed
bindings/jsonnet/src/import.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/import.rs
+++ b/bindings/jsonnet/src/import.rs
@@ -12,7 +12,7 @@
fs::File,
io::Read,
os::raw::{c_char, c_int},
- path::PathBuf,
+ path::{Path, PathBuf},
ptr::null_mut,
rc::Rc,
};
@@ -33,7 +33,7 @@
out: RefCell<HashMap<PathBuf, IStr>>,
}
impl ImportResolver for CallbackImportResolver {
- fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
+ fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
let base = CString::new(from.to_str().unwrap()).unwrap().into_raw();
let rel = CString::new(path.to_str().unwrap()).unwrap().into_raw();
let found_here: *mut c_char = null_mut();
@@ -73,9 +73,9 @@
unsafe { CString::from_raw(result_ptr) };
}
- Ok(Rc::new(found_here_buf))
+ Ok(found_here_buf.into())
}
- fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr> {
+ fn load_file_contents(&self, resolved: &Path) -> Result<IStr> {
Ok(self.out.borrow().get(resolved).unwrap().clone())
}
unsafe fn as_any(&self) -> &dyn Any {
@@ -108,27 +108,27 @@
}
}
impl ImportResolver for NativeImportResolver {
- fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
- let mut new_path = from.clone();
+ fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+ let mut new_path = from.to_owned();
new_path.push(path);
if new_path.exists() {
- Ok(Rc::new(new_path))
+ Ok(new_path.into())
} else {
for library_path in self.library_paths.borrow().iter() {
let mut cloned = library_path.clone();
cloned.push(path);
if cloned.exists() {
- return Ok(Rc::new(cloned));
+ return Ok(cloned.into());
}
}
- throw!(ImportFileNotFound(from.clone(), path.clone()))
+ throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
}
}
- fn load_file_contents(&self, id: &PathBuf) -> Result<IStr> {
- let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
+ fn load_file_contents(&self, id: &Path) -> Result<IStr> {
+ let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
let mut out = String::new();
file.read_to_string(&mut out)
- .map_err(|_e| ImportBadFileUtf8(id.clone()))?;
+ .map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;
Ok(out.into())
}
unsafe fn as_any(&self) -> &dyn Any {
bindings/jsonnet/src/lib.rsdiffbeforeafterboth--- a/bindings/jsonnet/src/lib.rs
+++ b/bindings/jsonnet/src/lib.rs
@@ -15,7 +15,6 @@
ffi::{CStr, CString},
os::raw::{c_char, c_double, c_int, c_uint},
path::PathBuf,
- rc::Rc,
};
/// WASM stub
@@ -144,7 +143,7 @@
let snippet = CStr::from_ptr(snippet);
match vm
.evaluate_snippet_raw(
- Rc::new(PathBuf::from(filename.to_str().unwrap())),
+ PathBuf::from(filename.to_str().unwrap()).into(),
snippet.to_str().unwrap().into(),
)
.and_then(|v| vm.with_tla(v))
@@ -220,7 +219,7 @@
let snippet = CStr::from_ptr(snippet);
match vm
.evaluate_snippet_raw(
- Rc::new(PathBuf::from(filename.to_str().unwrap())),
+ PathBuf::from(filename.to_str().unwrap()).into(),
snippet.to_str().unwrap().into(),
)
.and_then(|v| vm.with_tla(v))
@@ -294,7 +293,7 @@
let snippet = CStr::from_ptr(snippet);
match vm
.evaluate_snippet_raw(
- Rc::new(PathBuf::from(filename.to_str().unwrap())),
+ PathBuf::from(filename.to_str().unwrap()).into(),
snippet.to_str().unwrap().into(),
)
.and_then(|v| vm.with_tla(v))
cmds/jrsonnet/src/main.rsdiffbeforeafterboth1use clap::{AppSettings, Clap, IntoApp};2use jrsonnet_cli::{ConfigureState, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};3use jrsonnet_evaluator::{error::LocError, EvaluationState, ManifestFormat};4use std::{5 fs::{create_dir_all, File},6 io::Read,7 io::Write,8 path::PathBuf,9 rc::Rc,10 str::FromStr,11};1213#[cfg(feature = "mimalloc")]14#[global_allocator]15static GLOBAL: mimallocator::Mimalloc = mimallocator::Mimalloc;1617#[derive(Clap)]18#[clap(help_heading = "DEBUG")]19struct DebugOpts {20 /// Required OS stack size.21 /// This shouldn't be changed unless jrsonnet is failing with stack overflow error.22 #[clap(long, name = "size")]23 pub os_stack: Option<usize>,24 /// Generate completions script25 #[clap(long)]26 generate: Option<GenerateTarget>,27}2829enum GenerateTarget {30 Bash,31 Zsh,32 Fish,33 PowerShell,34}35impl FromStr for GenerateTarget {36 type Err = &'static str;3738 fn from_str(s: &str) -> Result<Self, Self::Err> {39 match s {40 "bash" => Ok(Self::Bash),41 "zsh" => Ok(Self::Zsh),42 "fish" => Ok(Self::Fish),43 "powershell" => Ok(Self::PowerShell),44 _ => Err("unknown target"),45 }46 }47}4849#[derive(Clap)]50#[clap(51 global_setting = AppSettings::ColoredHelp,52 global_setting = AppSettings::DeriveDisplayOrder,53)]54struct Opts {55 #[clap(flatten)]56 input: InputOpts,57 #[clap(flatten)]58 general: GeneralOpts,59 #[clap(flatten)]60 manifest: ManifestOpts,61 #[clap(flatten)]62 output: OutputOpts,63 #[clap(flatten)]64 debug: DebugOpts,65}6667fn main() {68 let opts: Opts = Opts::parse();6970 if let Some(target) = opts.debug.generate {71 use clap_generate::{generate, generators};72 use GenerateTarget::*;73 let app = &mut Opts::into_app();74 let buf = &mut std::io::stdout();75 let bin = "jrsonnet";76 match target {77 Bash => generate::<generators::Bash, _>(app, bin, buf),78 Zsh => generate::<generators::Zsh, _>(app, bin, buf),79 Fish => generate::<generators::Fish, _>(app, bin, buf),80 PowerShell => generate::<generators::PowerShell, _>(app, bin, buf),81 }82 std::process::exit(0);83 };8485 let success;86 if let Some(size) = opts.debug.os_stack {87 success = std::thread::Builder::new()88 .stack_size(size * 1024 * 1024)89 .spawn(|| main_catch(opts))90 .expect("new thread spawned")91 .join()92 .expect("thread finished successfully");93 } else {94 success = main_catch(opts)95 }96 if !success {97 std::process::exit(1);98 }99}100101#[derive(thiserror::Error, Debug)]102enum Error {103 // Handled differently104 #[error("evaluation error")]105 Evaluation(jrsonnet_evaluator::error::LocError),106 #[error("io error")]107 Io(#[from] std::io::Error),108 #[error("input is not utf8 encoded")]109 Utf8(#[from] std::str::Utf8Error),110}111impl From<LocError> for Error {112 fn from(e: LocError) -> Self {113 Self::Evaluation(e)114 }115}116117fn main_catch(opts: Opts) -> bool {118 let state = EvaluationState::default();119 if let Err(e) = main_real(&state, opts) {120 if let Error::Evaluation(e) = e {121 eprintln!("{}", state.stringify_err(&e));122 } else {123 eprintln!("{}", e);124 }125 return false;126 }127 true128}129130fn main_real(state: &EvaluationState, opts: Opts) -> Result<(), Error> {131 opts.general.configure(&state)?;132 opts.manifest.configure(&state)?;133134 let val = if opts.input.exec {135 state.set_manifest_format(ManifestFormat::ToString);136 state.evaluate_snippet_raw(137 Rc::new(PathBuf::from("args")),138 (&opts.input.input as &str).into(),139 )?140 } else if opts.input.input == "-" {141 let mut input = Vec::new();142 std::io::stdin().read_to_end(&mut input)?;143 let input_str = std::str::from_utf8(&input)?.into();144 state.evaluate_snippet_raw(Rc::new(PathBuf::from("<stdin>")), input_str)?145 } else {146 state.evaluate_file_raw(&PathBuf::from(opts.input.input))?147 };148149 let val = state.with_tla(val)?;150151 if let Some(multi) = opts.output.multi {152 if opts.output.create_output_dirs {153 let mut dir = multi.clone();154 dir.pop();155 create_dir_all(dir)?;156 }157 for (file, data) in state.manifest_multi(val)?.iter() {158 let mut path = multi.clone();159 path.push(&file as &str);160 if opts.output.create_output_dirs {161 let mut dir = path.clone();162 dir.pop();163 create_dir_all(dir)?;164 }165 println!("{}", path.to_str().expect("path"));166 let mut file = File::create(path)?;167 writeln!(file, "{}", data)?;168 }169 } else if let Some(path) = opts.output.output_file {170 if opts.output.create_output_dirs {171 let mut dir = path.clone();172 dir.pop();173 create_dir_all(dir)?;174 }175 let mut file = File::create(path)?;176 writeln!(file, "{}", state.manifest(val)?)?;177 } else {178 let output = state.manifest(val)?;179 if !output.is_empty() {180 println!("{}", output);181 }182 }183184 Ok(())185}1use clap::{AppSettings, Clap, IntoApp};2use jrsonnet_cli::{ConfigureState, GeneralOpts, InputOpts, ManifestOpts, OutputOpts};3use jrsonnet_evaluator::{error::LocError, EvaluationState, ManifestFormat};4use std::{5 fs::{create_dir_all, File},6 io::Read,7 io::Write,8 path::PathBuf,9 str::FromStr,10};1112#[cfg(feature = "mimalloc")]13#[global_allocator]14static GLOBAL: mimallocator::Mimalloc = mimallocator::Mimalloc;1516#[derive(Clap)]17#[clap(help_heading = "DEBUG")]18struct DebugOpts {19 /// Required OS stack size.20 /// This shouldn't be changed unless jrsonnet is failing with stack overflow error.21 #[clap(long, name = "size")]22 pub os_stack: Option<usize>,23 /// Generate completions script24 #[clap(long)]25 generate: Option<GenerateTarget>,26}2728enum GenerateTarget {29 Bash,30 Zsh,31 Fish,32 PowerShell,33}34impl FromStr for GenerateTarget {35 type Err = &'static str;3637 fn from_str(s: &str) -> Result<Self, Self::Err> {38 match s {39 "bash" => Ok(Self::Bash),40 "zsh" => Ok(Self::Zsh),41 "fish" => Ok(Self::Fish),42 "powershell" => Ok(Self::PowerShell),43 _ => Err("unknown target"),44 }45 }46}4748#[derive(Clap)]49#[clap(50 global_setting = AppSettings::ColoredHelp,51 global_setting = AppSettings::DeriveDisplayOrder,52)]53struct Opts {54 #[clap(flatten)]55 input: InputOpts,56 #[clap(flatten)]57 general: GeneralOpts,58 #[clap(flatten)]59 manifest: ManifestOpts,60 #[clap(flatten)]61 output: OutputOpts,62 #[clap(flatten)]63 debug: DebugOpts,64}6566fn main() {67 let opts: Opts = Opts::parse();6869 if let Some(target) = opts.debug.generate {70 use clap_generate::{generate, generators};71 use GenerateTarget::*;72 let app = &mut Opts::into_app();73 let buf = &mut std::io::stdout();74 let bin = "jrsonnet";75 match target {76 Bash => generate::<generators::Bash, _>(app, bin, buf),77 Zsh => generate::<generators::Zsh, _>(app, bin, buf),78 Fish => generate::<generators::Fish, _>(app, bin, buf),79 PowerShell => generate::<generators::PowerShell, _>(app, bin, buf),80 }81 std::process::exit(0);82 };8384 let success;85 if let Some(size) = opts.debug.os_stack {86 success = std::thread::Builder::new()87 .stack_size(size * 1024 * 1024)88 .spawn(|| main_catch(opts))89 .expect("new thread spawned")90 .join()91 .expect("thread finished successfully");92 } else {93 success = main_catch(opts)94 }95 if !success {96 std::process::exit(1);97 }98}99100#[derive(thiserror::Error, Debug)]101enum Error {102 // Handled differently103 #[error("evaluation error")]104 Evaluation(jrsonnet_evaluator::error::LocError),105 #[error("io error")]106 Io(#[from] std::io::Error),107 #[error("input is not utf8 encoded")]108 Utf8(#[from] std::str::Utf8Error),109}110impl From<LocError> for Error {111 fn from(e: LocError) -> Self {112 Self::Evaluation(e)113 }114}115116fn main_catch(opts: Opts) -> bool {117 let state = EvaluationState::default();118 if let Err(e) = main_real(&state, opts) {119 if let Error::Evaluation(e) = e {120 eprintln!("{}", state.stringify_err(&e));121 } else {122 eprintln!("{}", e);123 }124 return false;125 }126 true127}128129fn main_real(state: &EvaluationState, opts: Opts) -> Result<(), Error> {130 opts.general.configure(&state)?;131 opts.manifest.configure(&state)?;132133 let val = if opts.input.exec {134 state.set_manifest_format(ManifestFormat::ToString);135 state.evaluate_snippet_raw(136 PathBuf::from("args").into(),137 (&opts.input.input as &str).into(),138 )?139 } else if opts.input.input == "-" {140 let mut input = Vec::new();141 std::io::stdin().read_to_end(&mut input)?;142 let input_str = std::str::from_utf8(&input)?.into();143 state.evaluate_snippet_raw(PathBuf::from("<stdin>").into(), input_str)?144 } else {145 state.evaluate_file_raw(&PathBuf::from(opts.input.input))?146 };147148 let val = state.with_tla(val)?;149150 if let Some(multi) = opts.output.multi {151 if opts.output.create_output_dirs {152 let mut dir = multi.clone();153 dir.pop();154 create_dir_all(dir)?;155 }156 for (file, data) in state.manifest_multi(val)?.iter() {157 let mut path = multi.clone();158 path.push(&file as &str);159 if opts.output.create_output_dirs {160 let mut dir = path.clone();161 dir.pop();162 create_dir_all(dir)?;163 }164 println!("{}", path.to_str().expect("path"));165 let mut file = File::create(path)?;166 writeln!(file, "{}", data)?;167 }168 } else if let Some(path) = opts.output.output_file {169 if opts.output.create_output_dirs {170 let mut dir = path.clone();171 dir.pop();172 create_dir_all(dir)?;173 }174 let mut file = File::create(path)?;175 writeln!(file, "{}", state.manifest(val)?)?;176 } else {177 let output = state.manifest(val)?;178 if !output.is_empty() {179 println!("{}", output);180 }181 }182183 Ok(())184}crates/jrsonnet-evaluator/build.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/build.rs
+++ b/crates/jrsonnet-evaluator/build.rs
@@ -15,7 +15,7 @@
let parsed = parse(
STDLIB_STR,
&ParserSettings {
- file_name: Rc::new(PathBuf::from("std.jsonnet")),
+ file_name: PathBuf::from("std.jsonnet").into(),
loc_data: true,
},
)
crates/jrsonnet-evaluator/src/builtin/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/mod.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/mod.rs
@@ -174,7 +174,7 @@
0, s: ty!(string) => Val::Str;
], {
let state = EvaluationState::default();
- let path = Rc::new(PathBuf::from("std.parseJson"));
+ let path = PathBuf::from("std.parseJson").into();
state.evaluate_snippet_raw(path ,s)
})
}
crates/jrsonnet-evaluator/src/builtin/stdlib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
+++ b/crates/jrsonnet-evaluator/src/builtin/stdlib.rs
@@ -1,5 +1,5 @@
use jrsonnet_parser::{LocExpr, ParserSettings};
-use std::{path::PathBuf, rc::Rc};
+use std::path::PathBuf;
thread_local! {
/// To avoid parsing again when issued from the same thread
@@ -25,7 +25,7 @@
jrsonnet_stdlib::STDLIB_STR,
&ParserSettings {
loc_data: true,
- file_name: Rc::new(PathBuf::from("std.jsonnet")),
+ file_name: PathBuf::from("std.jsonnet").into(),
},
)
.unwrap()
crates/jrsonnet-evaluator/src/error.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/error.rs
+++ b/crates/jrsonnet-evaluator/src/error.rs
@@ -5,7 +5,10 @@
use jrsonnet_interner::IStr;
use jrsonnet_parser::{BinaryOpType, ExprLocation, UnaryOpType};
use jrsonnet_types::ValType;
-use std::{path::PathBuf, rc::Rc};
+use std::{
+ path::{Path, PathBuf},
+ rc::Rc,
+};
use thiserror::Error;
#[derive(Error, Debug, Clone)]
@@ -86,7 +89,7 @@
.source_code.chars().nth(error.location.offset).map(|c| c.to_string()).unwrap_or_else(|| "EOF".into())
)]
ImportSyntaxError {
- path: Rc<PathBuf>,
+ path: Rc<Path>,
source_code: IStr,
error: Box<jrsonnet_parser::ParseError>,
},
crates/jrsonnet-evaluator/src/evaluate.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/evaluate.rs
+++ b/crates/jrsonnet-evaluator/src/evaluate.rs
@@ -609,26 +609,26 @@
}
}
Import(path) => {
- let mut tmp = loc
+ let tmp = loc
.clone()
.expect("imports cannot be used without loc_data")
.0;
- let import_location = Rc::make_mut(&mut tmp);
+ let mut import_location = tmp.to_path_buf();
import_location.pop();
push(
loc.as_ref(),
|| format!("import {:?}", path),
- || with_state(|s| s.import_file(import_location, path)),
+ || with_state(|s| s.import_file(&import_location, path)),
)?
}
ImportStr(path) => {
- let mut tmp = loc
+ let tmp = loc
.clone()
.expect("imports cannot be used without loc_data")
.0;
- let import_location = Rc::make_mut(&mut tmp);
+ let mut import_location = tmp.to_path_buf();
import_location.pop();
- Val::Str(with_state(|s| s.import_file_str(import_location, path))?)
+ Val::Str(with_state(|s| s.import_file_str(&import_location, path))?)
}
})
}
crates/jrsonnet-evaluator/src/import.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/import.rs
+++ b/crates/jrsonnet-evaluator/src/import.rs
@@ -6,17 +6,23 @@
use jrsonnet_interner::IStr;
use std::fs;
use std::io::Read;
-use std::{any::Any, cell::RefCell, collections::HashMap, path::PathBuf, rc::Rc};
+use std::{
+ any::Any,
+ cell::RefCell,
+ collections::HashMap,
+ path::{Path, PathBuf},
+ rc::Rc,
+};
/// Implements file resolution logic for `import` and `importStr`
pub trait ImportResolver {
/// Resolves real file path, e.g. `(/home/user/manifests, b.libjsonnet)` can correspond
/// both to `/home/user/manifests/b.libjsonnet` and to `/home/user/${vendor}/b.libjsonnet`
/// where `${vendor}` is a library path.
- fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>>;
+ fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>>;
/// Reads file from filesystem, should be used only with path received from `resolve_file`
- fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr>;
+ fn load_file_contents(&self, resolved: &Path) -> Result<IStr>;
/// # Safety
///
@@ -29,11 +35,11 @@
/// Dummy resolver, can't resolve/load any file
pub struct DummyImportResolver;
impl ImportResolver for DummyImportResolver {
- fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
- throw!(ImportNotSupported(from.clone(), path.clone()))
+ fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+ throw!(ImportNotSupported(from.into(), path.into()))
}
- fn load_file_contents(&self, _resolved: &PathBuf) -> Result<IStr> {
+ fn load_file_contents(&self, _resolved: &Path) -> Result<IStr> {
// Can be only caused by library direct consumer, not by supplied jsonnet
panic!("dummy resolver can't load any file")
}
@@ -57,27 +63,27 @@
pub library_paths: Vec<PathBuf>,
}
impl ImportResolver for FileImportResolver {
- fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
- let mut new_path = from.clone();
- new_path.push(path);
- if new_path.exists() {
- Ok(Rc::new(new_path))
+ fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
+ let mut direct = from.to_path_buf();
+ direct.push(path);
+ if direct.exists() {
+ Ok(direct.into())
} else {
for library_path in self.library_paths.iter() {
let mut cloned = library_path.clone();
cloned.push(path);
if cloned.exists() {
- return Ok(Rc::new(cloned));
+ return Ok(cloned.into());
}
}
- throw!(ImportFileNotFound(from.clone(), path.clone()))
+ throw!(ImportFileNotFound(from.to_owned(), path.to_owned()))
}
}
- fn load_file_contents(&self, id: &PathBuf) -> Result<IStr> {
- let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.clone()))?;
+ fn load_file_contents(&self, id: &Path) -> Result<IStr> {
+ let mut file = File::open(id).map_err(|_e| ResolvedFileNotFound(id.to_owned()))?;
let mut out = String::new();
file.read_to_string(&mut out)
- .map_err(|_e| ImportBadFileUtf8(id.clone()))?;
+ .map_err(|_e| ImportBadFileUtf8(id.to_owned()))?;
Ok(out.into())
}
unsafe fn as_any(&self) -> &dyn Any {
@@ -89,23 +95,23 @@
/// Caches results of the underlying resolver
pub struct CachingImportResolver {
- resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<PathBuf>>>>,
+ resolution_cache: RefCell<HashMap<ResolutionData, Result<Rc<Path>>>>,
loading_cache: RefCell<HashMap<PathBuf, Result<IStr>>>,
inner: Box<dyn ImportResolver>,
}
impl ImportResolver for CachingImportResolver {
- fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
+ fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
self.resolution_cache
.borrow_mut()
- .entry((from.clone(), path.clone()))
+ .entry((from.to_owned(), path.to_owned()))
.or_insert_with(|| self.inner.resolve_file(from, path))
.clone()
}
- fn load_file_contents(&self, resolved: &PathBuf) -> Result<IStr> {
+ fn load_file_contents(&self, resolved: &Path) -> Result<IStr> {
self.loading_cache
.borrow_mut()
- .entry(resolved.clone())
+ .entry(resolved.to_owned())
.or_insert_with(|| self.inner.load_file_contents(resolved))
.clone()
}
crates/jrsonnet-evaluator/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/lib.rs
+++ b/crates/jrsonnet-evaluator/src/lib.rs
@@ -35,7 +35,7 @@
collections::HashMap,
fmt::Debug,
hash::BuildHasherDefault,
- path::PathBuf,
+ path::{Path, PathBuf},
rc::Rc,
};
use trace::{offset_to_location, CodeLocation, CompactFormat, TraceFormat};
@@ -109,8 +109,8 @@
/// Used for stack overflow detection, stacktrace is populated on unwind
stack_depth: usize,
/// Contains file source codes and evaluation results for imports and pretty-printed stacktraces
- files: HashMap<Rc<PathBuf>, FileData>,
- str_files: HashMap<Rc<PathBuf>, IStr>,
+ files: HashMap<Rc<Path>, FileData>,
+ str_files: HashMap<Rc<Path>, IStr>,
}
pub struct FileData {
@@ -156,7 +156,7 @@
impl EvaluationState {
/// Parses and adds file as loaded
- pub fn add_file(&self, path: Rc<PathBuf>, source_code: IStr) -> Result<()> {
+ pub fn add_file(&self, path: Rc<Path>, source_code: IStr) -> Result<()> {
self.add_parsed_file(
path.clone(),
source_code.clone(),
@@ -169,7 +169,7 @@
)
.map_err(|error| ImportSyntaxError {
error: Box::new(error),
- path,
+ path: path.to_owned(),
source_code,
})?,
)?;
@@ -180,7 +180,7 @@
/// Adds file by source code and parsed expr
pub fn add_parsed_file(
&self,
- name: Rc<PathBuf>,
+ name: Rc<Path>,
source_code: IStr,
parsed: LocExpr,
) -> Result<()> {
@@ -195,20 +195,20 @@
Ok(())
}
- pub fn get_source(&self, name: &PathBuf) -> Option<IStr> {
+ pub fn get_source(&self, name: &Path) -> Option<IStr> {
let ro_map = &self.data().files;
ro_map.get(name).map(|value| value.source_code.clone())
}
- pub fn map_source_locations(&self, file: &PathBuf, locs: &[usize]) -> Vec<CodeLocation> {
+ pub fn map_source_locations(&self, file: &Path, locs: &[usize]) -> Vec<CodeLocation> {
offset_to_location(&self.get_source(file).unwrap(), locs)
}
- pub(crate) fn import_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Val> {
+ pub(crate) fn import_file(&self, from: &Path, path: &Path) -> Result<Val> {
let file_path = self.resolve_file(from, path)?;
{
let data = self.data();
let files = &data.files;
- if files.contains_key(&file_path) {
+ if files.contains_key(&file_path as &Path) {
drop(data);
return self.evaluate_loaded_file_raw(&file_path);
}
@@ -217,7 +217,7 @@
self.add_file(file_path.clone(), contents)?;
self.evaluate_loaded_file_raw(&file_path)
}
- pub(crate) fn import_file_str(&self, from: &PathBuf, path: &PathBuf) -> Result<IStr> {
+ pub(crate) fn import_file_str(&self, from: &Path, path: &Path) -> Result<IStr> {
let path = self.resolve_file(from, path)?;
if !self.data().str_files.contains_key(&path) {
let file_str = self.load_file_contents(&path)?;
@@ -226,7 +226,7 @@
Ok(self.data().str_files.get(&path).cloned().unwrap())
}
- fn evaluate_loaded_file_raw(&self, name: &PathBuf) -> Result<Val> {
+ fn evaluate_loaded_file_raw(&self, name: &Path) -> Result<Val> {
let expr: LocExpr = {
let ro_map = &self.data().files;
let value = ro_map
@@ -252,7 +252,7 @@
/// Adds standard library global variable (std) to this evaluator
pub fn with_stdlib(&self) -> &Self {
use jrsonnet_stdlib::STDLIB_STR;
- let std_path = Rc::new(PathBuf::from("std.jsonnet"));
+ let std_path: Rc<Path> = PathBuf::from("std.jsonnet").into();
self.run_in_state(|| {
self.add_parsed_file(
std_path.clone(),
@@ -380,14 +380,14 @@
/// Raw methods evaluate passed values but don't perform TLA execution
impl EvaluationState {
- pub fn evaluate_file_raw(&self, name: &PathBuf) -> Result<Val> {
+ pub fn evaluate_file_raw(&self, name: &Path) -> Result<Val> {
self.run_in_state(|| self.import_file(&std::env::current_dir().expect("cwd"), name))
}
- pub fn evaluate_file_raw_nocwd(&self, name: &PathBuf) -> Result<Val> {
+ pub fn evaluate_file_raw_nocwd(&self, name: &Path) -> Result<Val> {
self.run_in_state(|| self.import_file(&PathBuf::from("."), name))
}
/// Parses and evaluates the given snippet
- pub fn evaluate_snippet_raw(&self, source: Rc<PathBuf>, code: IStr) -> Result<Val> {
+ pub fn evaluate_snippet_raw(&self, source: Rc<Path>, code: IStr) -> Result<Val> {
let parsed = parse(
&code,
&ParserSettings {
@@ -419,7 +419,7 @@
}
pub fn add_ext_code(&self, name: IStr, code: IStr) -> Result<()> {
let value =
- self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("ext_code {}", name))), code)?;
+ self.evaluate_snippet_raw(PathBuf::from(format!("ext_code {}", name)).into(), code)?;
self.add_ext_var(name, value);
Ok(())
}
@@ -432,15 +432,15 @@
}
pub fn add_tla_code(&self, name: IStr, code: IStr) -> Result<()> {
let value =
- self.evaluate_snippet_raw(Rc::new(PathBuf::from(format!("tla_code {}", name))), code)?;
+ self.evaluate_snippet_raw(PathBuf::from(format!("tla_code {}", name)).into(), code)?;
self.add_tla(name, value);
Ok(())
}
- pub fn resolve_file(&self, from: &PathBuf, path: &PathBuf) -> Result<Rc<PathBuf>> {
+ pub fn resolve_file(&self, from: &Path, path: &Path) -> Result<Rc<Path>> {
self.settings().import_resolver.resolve_file(from, path)
}
- pub fn load_file_contents(&self, path: &PathBuf) -> Result<IStr> {
+ pub fn load_file_contents(&self, path: &Path) -> Result<IStr> {
self.settings().import_resolver.load_file_contents(path)
}
@@ -490,7 +490,10 @@
use crate::{error::Error::*, primitive_equals, EvaluationState};
use jrsonnet_interner::IStr;
use jrsonnet_parser::*;
- use std::{path::PathBuf, rc::Rc};
+ use std::{
+ path::{Path, PathBuf},
+ rc::Rc,
+ };
#[test]
#[should_panic]
@@ -499,19 +502,11 @@
state.run_in_state(|| {
state
.push(
- Some(&ExprLocation(
- Rc::new(PathBuf::from("test1.jsonnet")),
- 10,
- 20,
- )),
+ Some(&ExprLocation(PathBuf::from("test1.jsonnet").into(), 10, 20)),
|| "outer".to_owned(),
|| {
state.push(
- Some(&ExprLocation(
- Rc::new(PathBuf::from("test2.jsonnet")),
- 30,
- 40,
- )),
+ Some(&ExprLocation(PathBuf::from("test2.jsonnet").into(), 30, 40)),
|| "inner".to_owned(),
|| Err(RuntimeError("".into()).into()),
)?;
@@ -529,7 +524,7 @@
assert!(primitive_equals(
&state
.evaluate_snippet_raw(
- Rc::new(PathBuf::from("raw.jsonnet")),
+ PathBuf::from("raw.jsonnet").into(),
r#"std.assertEqual(std.base64("test"), "dGVzdA==")"#.into()
)
.unwrap(),
@@ -542,7 +537,7 @@
($str: expr) => {
EvaluationState::default()
.with_stdlib()
- .evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())
+ .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())
.unwrap()
};
}
@@ -552,7 +547,7 @@
evaluator.with_stdlib();
evaluator.run_in_state(|| {
evaluator
- .evaluate_snippet_raw(Rc::new(PathBuf::from("raw.jsonnet")), $str.into())
+ .evaluate_snippet_raw(PathBuf::from("raw.jsonnet").into(), $str.into())
.unwrap()
.to_json(0)
.unwrap()
@@ -909,7 +904,10 @@
"{:?}",
jrsonnet_parser::parse(
"{ x: 1, y: 2 } == { x: 1, y: 2 }",
- &ParserSettings::default()
+ &ParserSettings {
+ file_name: PathBuf::from("equality").into(),
+ loc_data: true,
+ }
)
);
assert_eval!("{ x: 1, y: 2 } == { x: 1, y: 2 }")
@@ -930,8 +928,8 @@
])),
|caller, args| {
assert_eq!(
- caller.unwrap(),
- Rc::new(PathBuf::from("native_caller.jsonnet"))
+ &caller.unwrap() as &Path,
+ &PathBuf::from("native_caller.jsonnet")
);
match (&args[0], &args[1]) {
(Val::Num(a), Val::Num(b)) => Ok(Val::Num(a + b)),
@@ -941,7 +939,7 @@
)),
);
evaluator.evaluate_snippet_raw(
- Rc::new(PathBuf::from("native_caller.jsonnet")),
+ PathBuf::from("native_caller.jsonnet").into(),
"std.assertEqual(std.native(\"native_add\")(1, 2), 3)".into(),
)?;
Ok(())
@@ -993,11 +991,11 @@
struct TestImportResolver(IStr);
impl crate::import::ImportResolver for TestImportResolver {
- fn resolve_file(&self, _: &PathBuf, _: &PathBuf) -> crate::error::Result<Rc<PathBuf>> {
- Ok(Rc::new(PathBuf::from("/test")))
+ fn resolve_file(&self, _: &Path, _: &Path) -> crate::error::Result<Rc<Path>> {
+ Ok(PathBuf::from("/test").into())
}
- fn load_file_contents(&self, _: &PathBuf) -> crate::error::Result<IStr> {
+ fn load_file_contents(&self, _: &Path) -> crate::error::Result<IStr> {
Ok(self.0.clone())
}
@@ -1020,7 +1018,7 @@
let error = state
.evaluate_snippet_raw(
- Rc::new(PathBuf::from("issue40.jsonnet")),
+ PathBuf::from("issue40.jsonnet").into(),
r#"
local conf = {
n: ""
crates/jrsonnet-evaluator/src/native.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/native.rs
+++ b/crates/jrsonnet-evaluator/src/native.rs
@@ -3,24 +3,24 @@
use crate::{error::Result, Val};
use jrsonnet_parser::ParamsDesc;
use std::fmt::Debug;
-use std::path::PathBuf;
+use std::path::Path;
use std::rc::Rc;
pub struct NativeCallback {
pub params: ParamsDesc,
- handler: Box<dyn Fn(Option<Rc<PathBuf>>, &[Val]) -> Result<Val>>,
+ handler: Box<dyn Fn(Option<Rc<Path>>, &[Val]) -> Result<Val>>,
}
impl NativeCallback {
pub fn new(
params: ParamsDesc,
- handler: impl Fn(Option<Rc<PathBuf>>, &[Val]) -> Result<Val> + 'static,
+ handler: impl Fn(Option<Rc<Path>>, &[Val]) -> Result<Val> + 'static,
) -> Self {
Self {
params,
handler: Box::new(handler),
}
}
- pub fn call(&self, caller: Option<Rc<PathBuf>>, args: &[Val]) -> Result<Val> {
+ pub fn call(&self, caller: Option<Rc<Path>>, args: &[Val]) -> Result<Val> {
(self.handler)(caller, args)
}
}
crates/jrsonnet-evaluator/src/trace/mod.rsdiffbeforeafterboth--- a/crates/jrsonnet-evaluator/src/trace/mod.rs
+++ b/crates/jrsonnet-evaluator/src/trace/mod.rs
@@ -2,7 +2,7 @@
use crate::{error::Error, EvaluationState, LocError};
pub use location::*;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
/// The way paths should be displayed
pub enum PathResolver {
@@ -15,7 +15,7 @@
}
impl PathResolver {
- pub fn resolve(&self, from: &PathBuf) -> String {
+ pub fn resolve(&self, from: &Path) -> String {
match self {
Self::FileName => from.file_name().unwrap().to_string_lossy().into_owned(),
Self::Absolute => from.to_string_lossy().into_owned(),
@@ -255,7 +255,7 @@
&self,
out: &mut dyn std::fmt::Write,
source: &str,
- origin: &PathBuf,
+ origin: &Path,
start: &CodeLocation,
end: &CodeLocation,
desc: &str,
crates/jrsonnet-parser/src/expr.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/expr.rs
+++ b/crates/jrsonnet-parser/src/expr.rs
@@ -6,7 +6,7 @@
use std::{
fmt::{Debug, Display},
ops::Deref,
- path::PathBuf,
+ path::{Path, PathBuf},
rc::Rc,
};
@@ -320,7 +320,7 @@
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[cfg_attr(feature = "deserialize", derive(Deserialize))]
#[derive(Clone, PartialEq)]
-pub struct ExprLocation(pub Rc<PathBuf>, pub usize, pub usize);
+pub struct ExprLocation(pub Rc<Path>, pub usize, pub usize);
impl Debug for ExprLocation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}:{:?}-{:?}", self.0, self.1, self.2)
crates/jrsonnet-parser/src/lib.rsdiffbeforeafterboth--- a/crates/jrsonnet-parser/src/lib.rs
+++ b/crates/jrsonnet-parser/src/lib.rs
@@ -1,15 +1,17 @@
#![allow(clippy::redundant_closure_call)]
use peg::parser;
-use std::{path::PathBuf, rc::Rc};
+use std::{
+ path::{Path, PathBuf},
+ rc::Rc,
+};
mod expr;
pub use expr::*;
pub use peg;
-#[derive(Default)]
pub struct ParserSettings {
pub loc_data: bool,
- pub file_name: Rc<PathBuf>,
+ pub file_name: Rc<Path>,
}
parser! {
@@ -304,7 +306,6 @@
use super::{expr::*, parse};
use crate::ParserSettings;
use std::path::PathBuf;
- use std::rc::Rc;
macro_rules! parse {
($s:expr) => {
@@ -312,7 +313,7 @@
$s,
&ParserSettings {
loc_data: false,
- file_name: Rc::new(PathBuf::from("/test.jsonnet")),
+ file_name: PathBuf::from("/test.jsonnet").into(),
},
)
.unwrap()