Skip to content

Commit b0cb57b

Browse files
authored
fix(r2x-python): Adding correct python path. (#32)
1 parent 5b6cc37 commit b0cb57b

12 files changed

Lines changed: 133 additions & 124 deletions

File tree

crates/r2x-ast/src/extractor/mod.rs

Lines changed: 27 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -63,24 +63,27 @@ impl PluginExtractor {
6363
debug!("Found {} manifest.add() calls", manifest_add_calls.len());
6464
let mut plugins = Vec::new();
6565

66-
for add_match in manifest_add_calls {
67-
let add_text = add_match.text();
68-
match self.extract_plugin_from_add_call(add_text.as_ref()) {
69-
Ok(plugin) => {
70-
debug!("Extracted plugin: {}", plugin.name);
71-
plugins.push(plugin);
72-
}
73-
Err(err) => {
74-
debug!(
75-
"Failed to parse manifest.add() call '{}': {}",
76-
add_text.lines().next().unwrap_or(""),
77-
err
78-
);
66+
for add_match in manifest_add_calls {
67+
let add_text = add_match.text();
68+
match self.extract_plugin_from_add_call(add_text.as_ref()) {
69+
Ok(plugin) => {
70+
debug!("Extracted plugin: {}", plugin.name);
71+
plugins.push(plugin);
72+
}
73+
Err(err) => {
74+
debug!(
75+
"Failed to parse manifest.add() call '{}': {}",
76+
add_text.lines().next().unwrap_or(""),
77+
err
78+
);
79+
}
7980
}
8081
}
81-
}
8282

83-
info!("Extracted {} plugins from manifest.add() helpers", plugins.len());
83+
info!(
84+
"Extracted {} plugins from manifest.add() helpers",
85+
plugins.len()
86+
);
8487
return Ok(plugins);
8588
}
8689

@@ -99,14 +102,15 @@ impl PluginExtractor {
99102
}
100103

101104
fn extract_plugin_from_add_call(&self, add_text: &str) -> Result<PluginSpec> {
102-
debug!("Parsing PluginSpec from manifest.add(): {}", add_text.lines().next().unwrap_or(""));
105+
debug!(
106+
"Parsing PluginSpec from manifest.add(): {}",
107+
add_text.lines().next().unwrap_or("")
108+
);
103109

104110
let sg = AstGrep::new(add_text, Python);
105111
let root = sg.root();
106112

107-
let plugin_spec_calls: Vec<_> = root
108-
.find_all("PluginSpec.$METHOD($$$ARGS)")
109-
.collect();
113+
let plugin_spec_calls: Vec<_> = root.find_all("PluginSpec.$METHOD($$$ARGS)").collect();
110114

111115
if plugin_spec_calls.is_empty() {
112116
return Err(anyhow!("No PluginSpec helper call found in manifest.add()"));
@@ -139,8 +143,7 @@ impl PluginExtractor {
139143
let entry = self.qualify_symbol(&entry_value);
140144
let constructor_args = self.resolve_entry_parameters(&entry, &ImplementationType::Class);
141145

142-
let description =
143-
self.find_optional_kwarg_by_role(&kwargs, args::KwArgRole::Description);
146+
let description = self.find_optional_kwarg_by_role(&kwargs, args::KwArgRole::Description);
144147

145148
let method_param = self.find_optional_kwarg_by_role(&kwargs, args::KwArgRole::Method);
146149
let resolved_method = method_param.or_else(|| Self::default_method_for_kind(&kind));
@@ -220,8 +223,7 @@ impl PluginExtractor {
220223
let method_param = self.find_optional_kwarg_by_role(&kwargs, args::KwArgRole::Method);
221224
let constructor_args = self.resolve_entry_parameters(&entry, &ImplementationType::Class);
222225
let kind = self.infer_kind_from_constructor(constructor);
223-
let resolved_method =
224-
method_param.or_else(|| Self::default_method_for_kind(&kind));
226+
let resolved_method = method_param.or_else(|| Self::default_method_for_kind(&kind));
225227

226228
let invocation = InvocationSpec {
227229
implementation: Self::infer_invocation_type(&entry),
@@ -265,11 +267,7 @@ impl PluginExtractor {
265267
Ok(self.qualify_symbol(&symbol))
266268
}
267269

268-
fn find_kwarg_by_role(
269-
&self,
270-
kwargs: &[args::KwArg],
271-
role: args::KwArgRole,
272-
) -> Result<String> {
270+
fn find_kwarg_by_role(&self, kwargs: &[args::KwArg], role: args::KwArgRole) -> Result<String> {
273271
kwargs
274272
.iter()
275273
.find(|kw| kw.role == role)
@@ -313,10 +311,7 @@ impl PluginExtractor {
313311
ImplementationType::Class => self
314312
.extract_class_parameters_from_content(&source, &symbol)
315313
.unwrap_or_else(|e| {
316-
debug!(
317-
"Failed to parse constructor for '{}': {}",
318-
entry, e
319-
);
314+
debug!("Failed to parse constructor for '{}': {}", entry, e);
320315
Vec::new()
321316
}),
322317
ImplementationType::Function => self

crates/r2x-ast/src/extractor/parameters.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -202,10 +202,7 @@ impl PluginExtractor {
202202
Some(param_str[colon_idx + 1..].trim()),
203203
)
204204
} else if let Some(eq_idx) = param_str.find('=') {
205-
(
206-
param_str[..eq_idx].trim(),
207-
Some(param_str[eq_idx..].trim()),
208-
)
205+
(param_str[..eq_idx].trim(), Some(param_str[eq_idx..].trim()))
209206
} else {
210207
(param_str, None)
211208
};

crates/r2x-ast/src/extractor/tests.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -155,15 +155,17 @@ manifest.add(PluginSpec.parser(name="demo.parser", entry=DemoParser))
155155
let plugin_file = pkg_root.join("plugin.py");
156156
fs::write(&plugin_file, content)?;
157157

158-
let extractor =
159-
PluginExtractor::new(plugin_file, "demo.plugin".to_string(), pkg_root.clone())?;
158+
let extractor = PluginExtractor::new(plugin_file, "demo.plugin".to_string(), pkg_root.clone())?;
160159
let plugins = extractor.extract_plugins()?;
161160

162161
assert_eq!(plugins.len(), 1);
163162
assert_eq!(plugins[0].name, "demo.parser");
164163
assert_eq!(plugins[0].entry, "demo.plugin.DemoParser");
165164
assert_eq!(plugins[0].kind, PluginKind::Parser);
166-
assert_eq!(plugins[0].invocation.implementation, ImplementationType::Class);
165+
assert_eq!(
166+
plugins[0].invocation.implementation,
167+
ImplementationType::Class
168+
);
167169
assert!(!plugins[0].invocation.constructor.is_empty());
168170

169171
Ok(())

crates/r2x-cli/src/commands/run/mod.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,10 @@ pub(super) fn build_call_target(bindings: &RuntimeBindings) -> Result<String, Ru
117117
if bindings.plugin_kind == PluginKind::Upgrader {
118118
format!("{}:{}", bindings.entry_module, bindings.entry_name)
119119
} else if let Some(call_method) = &bindings.call_method {
120-
format!("{}:{}.{}", bindings.entry_module, bindings.entry_name, call_method)
120+
format!(
121+
"{}:{}.{}",
122+
bindings.entry_module, bindings.entry_name, call_method
123+
)
121124
} else {
122125
format!("{}:{}", bindings.entry_module, bindings.entry_name)
123126
}

crates/r2x-cli/src/commands/run/pipeline.rs

Lines changed: 68 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -208,40 +208,36 @@ fn run_pipeline(
208208
logger::debug(&format!("Invoking: {}", target));
209209
logger::debug(&format!("Config: {}", final_config_json));
210210

211-
let invocation_result = match bridge.invoke_plugin(
212-
&target,
213-
&final_config_json,
214-
stdin_json,
215-
Some(plugin),
216-
) {
217-
Ok(inv_result) => {
218-
let elapsed = step_start.elapsed();
219-
logger::spinner_success(&format!(
220-
"{} [{}/{}] ({})",
221-
plugin_name,
222-
step_num,
223-
total_steps,
224-
super::format_duration(elapsed)
225-
));
226-
if logger::get_verbosity() > 0 {
227-
if let Some(timings) = &inv_result.timings {
228-
super::print_plugin_timing_breakdown(timings);
211+
let invocation_result =
212+
match bridge.invoke_plugin(&target, &final_config_json, stdin_json, Some(plugin)) {
213+
Ok(inv_result) => {
214+
let elapsed = step_start.elapsed();
215+
logger::spinner_success(&format!(
216+
"{} [{}/{}] ({})",
217+
plugin_name,
218+
step_num,
219+
total_steps,
220+
super::format_duration(elapsed)
221+
));
222+
if logger::get_verbosity() > 0 {
223+
if let Some(timings) = &inv_result.timings {
224+
super::print_plugin_timing_breakdown(timings);
225+
}
229226
}
227+
inv_result
230228
}
231-
inv_result
232-
}
233-
Err(e) => {
234-
let elapsed = step_start.elapsed();
235-
logger::spinner_error(&format!(
236-
"{} [{}/{}] ({})",
237-
plugin_name,
238-
step_num,
239-
total_steps,
240-
super::format_duration(elapsed)
241-
));
242-
return Err(RunError::Bridge(e));
243-
}
244-
};
229+
Err(e) => {
230+
let elapsed = step_start.elapsed();
231+
logger::spinner_error(&format!(
232+
"{} [{}/{}] ({})",
233+
plugin_name,
234+
step_num,
235+
total_steps,
236+
super::format_duration(elapsed)
237+
));
238+
return Err(RunError::Bridge(e));
239+
}
240+
};
245241

246242
let result = invocation_result.output;
247243

@@ -263,18 +259,18 @@ fn run_pipeline(
263259
.bold()
264260
);
265261

266-
if let Some(final_output) = current_stdin {
267-
if let Some(output_path) = output_file {
268-
logger::step(&format!("Writing output to: {}", output_path));
269-
std::fs::write(output_path, final_output.as_bytes())
270-
.map_err(|e| RunError::Pipeline(PipelineError::Io(e)))?;
271-
logger::success(&format!("Output saved to: {}", output_path));
272-
} else if opts.suppress_stdout() {
273-
logger::debug("Pipeline output suppressed due to -qq");
274-
} else {
275-
println!("{}", final_output);
276-
}
262+
if let Some(final_output) = current_stdin {
263+
if let Some(output_path) = output_file {
264+
logger::step(&format!("Writing output to: {}", output_path));
265+
std::fs::write(output_path, final_output.as_bytes())
266+
.map_err(|e| RunError::Pipeline(PipelineError::Io(e)))?;
267+
logger::success(&format!("Output saved to: {}", output_path));
268+
} else if opts.suppress_stdout() {
269+
logger::debug("Pipeline output suppressed due to -qq");
270+
} else {
271+
println!("{}", final_output);
277272
}
273+
}
278274

279275
Ok(())
280276
}
@@ -337,7 +333,11 @@ fn determine_json_path_field(
337333
}
338334
}
339335

340-
if bindings.entry_parameters.iter().any(|p| p.name == "json_path") {
336+
if bindings
337+
.entry_parameters
338+
.iter()
339+
.any(|p| p.name == "json_path")
340+
{
341341
return Some("json_path");
342342
}
343343
if bindings.entry_parameters.iter().any(|p| p.name == "path") {
@@ -413,9 +413,9 @@ fn build_plugin_config(
413413
}
414414
}
415415

416-
let mut final_config = serde_json::Map::new();
417-
let mut store_value_for_folder: Option<serde_json::Value> = None;
418-
if bindings.implementation_type == r2x_manifest::ImplementationType::Class {
416+
let mut final_config = serde_json::Map::new();
417+
let mut store_value_for_folder: Option<serde_json::Value> = None;
418+
if bindings.implementation_type == r2x_manifest::ImplementationType::Class {
419419
let mut config_class_params = serde_json::Map::new();
420420
let mut constructor_params = serde_json::Map::new();
421421
let config_param_names: HashSet<String> = bindings
@@ -438,7 +438,9 @@ fn build_plugin_config(
438438
}
439439
}
440440

441-
if !config_class_params.is_empty() && bindings.entry_parameters.iter().any(|p| p.name == "config") {
441+
if !config_class_params.is_empty()
442+
&& bindings.entry_parameters.iter().any(|p| p.name == "config")
443+
{
442444
final_config.insert(
443445
"config".to_string(),
444446
serde_json::Value::Object(config_class_params),
@@ -462,8 +464,11 @@ fn build_plugin_config(
462464
}
463465
}
464466

465-
let needs_store =
466-
bindings.requires_store || bindings.entry_parameters.iter().any(|p| p.name == "data_store");
467+
let needs_store = bindings.requires_store
468+
|| bindings
469+
.entry_parameters
470+
.iter()
471+
.any(|p| p.name == "data_store");
467472

468473
if needs_store {
469474
let store_value = if let serde_json::Value::Object(ref yaml_map) = yaml_config {
@@ -491,7 +496,10 @@ fn build_plugin_config(
491496
final_config.insert("data_store".to_string(), store_value);
492497
}
493498

494-
if bindings.entry_parameters.iter().any(|p| p.name == "folder_path")
499+
if bindings
500+
.entry_parameters
501+
.iter()
502+
.any(|p| p.name == "folder_path")
495503
&& !final_config.contains_key("folder_path")
496504
{
497505
let explicit_folder = if let serde_json::Value::Object(ref yaml_map) = yaml_config {
@@ -506,14 +514,17 @@ fn build_plugin_config(
506514

507515
let folder_value = explicit_folder
508516
.or_else(|| {
509-
store_value_for_folder.as_ref().and_then(|value| match value {
510-
serde_json::Value::String(s) => Some(serde_json::Value::String(s.clone())),
511-
_ => None,
512-
})
517+
store_value_for_folder
518+
.as_ref()
519+
.and_then(|value| match value {
520+
serde_json::Value::String(s) => {
521+
Some(serde_json::Value::String(s.clone()))
522+
}
523+
_ => None,
524+
})
513525
})
514526
.or_else(|| {
515-
inherited_store_path
516-
.map(|path| serde_json::Value::String(path.to_string()))
527+
inherited_store_path.map(|path| serde_json::Value::String(path.to_string()))
517528
});
518529

519530
if let Some(value) = folder_value {

crates/r2x-cli/src/commands/run/plugin.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,7 @@ use r2x_python::plugin_invoker::PluginInvocationResult;
1010
use std::collections::BTreeMap;
1111
use std::time::Instant;
1212

13-
pub(super) fn handle_plugin_command(
14-
cmd: PluginCommand,
15-
opts: &GlobalOpts,
16-
) -> Result<(), RunError> {
13+
pub(super) fn handle_plugin_command(cmd: PluginCommand, opts: &GlobalOpts) -> Result<(), RunError> {
1714
match cmd.plugin_name {
1815
Some(plugin_name) => {
1916
if cmd.show_help {

crates/r2x-cli/src/help.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,10 @@ pub fn show_plugin_help(plugin_name: &str) -> Result<(), String> {
8383
println!(" --store-name <NAME> Name of the store (optional)");
8484
}
8585

86-
println!("\nCallable: {}.{}", bindings.entry_module, bindings.entry_name);
86+
println!(
87+
"\nCallable: {}.{}",
88+
bindings.entry_module, bindings.entry_name
89+
);
8790
if let Some(call_method) = &bindings.call_method {
8891
println!("Method: {}", call_method);
8992
}
@@ -152,7 +155,6 @@ pub fn show_plugin_help(plugin_name: &str) -> Result<(), String> {
152155
Ok(())
153156
}
154157

155-
156158
#[cfg(test)]
157159
mod tests {
158160
#[test]

crates/r2x-cli/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,6 @@ pub use r2x_manifest::errors::ManifestError;
2626

2727
// Re-export manifest types from new module for convenience
2828
pub use r2x_manifest::{
29-
DecoratorRegistration, FunctionParameter, FunctionSignature,
30-
Manifest, Metadata, Package, VarArgType,
29+
DecoratorRegistration, FunctionParameter, FunctionSignature, Manifest, Metadata, Package,
30+
VarArgType,
3131
};

crates/r2x-cli/src/plugins/discovery.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,7 @@ pub fn discover_and_register_entry_points_with_deps(
8181
for plugin in &discovered_plugins {
8282
logger::debug(&format!(
8383
"Discovered plugin '{}' of kind {:?}",
84-
plugin.name,
85-
plugin.kind
84+
plugin.name, plugin.kind
8685
));
8786
}
8887

0 commit comments

Comments
 (0)