Unnamed repository; edit this file 'description' to name the repository.
Refactor the runnable_args implementation to be more compact
I'm about to complete the match statement here with more of the same. Once you write the exact same code 5 times, it's time for a helper function.
Cormac Relf 4 months ago
parent 2969b3b · commit 5ef0f51
-rw-r--r--crates/rust-analyzer/src/target_spec.rs64
1 files changed, 28 insertions, 36 deletions
diff --git a/crates/rust-analyzer/src/target_spec.rs b/crates/rust-analyzer/src/target_spec.rs
index b8d9acc02a..c87eefc695 100644
--- a/crates/rust-analyzer/src/target_spec.rs
+++ b/crates/rust-analyzer/src/target_spec.rs
@@ -6,7 +6,7 @@ use cargo_metadata::PackageId;
use cfg::{CfgAtom, CfgExpr};
use hir::sym;
use ide::{Cancellable, Crate, FileId, RunnableKind, TestId};
-use project_model::project_json::Runnable;
+use project_model::project_json::{self, Runnable};
use project_model::{CargoFeatures, ManifestPath, TargetKind};
use rustc_hash::FxHashSet;
use triomphe::Arc;
@@ -72,44 +72,36 @@ pub(crate) struct ProjectJsonTargetSpec {
}
impl ProjectJsonTargetSpec {
+ fn find_replace_runnable(
+ &self,
+ kind: project_json::RunnableKind,
+ replacer: &dyn Fn(&Self, &str) -> String,
+ ) -> Option<Runnable> {
+ for runnable in &self.shell_runnables {
+ if runnable.kind == kind {
+ let mut runnable = runnable.clone();
+
+ let replaced_args: Vec<_> =
+ runnable.args.iter().map(|arg| replacer(self, arg)).collect();
+ runnable.args = replaced_args;
+
+ return Some(runnable);
+ }
+ }
+
+ None
+ }
+
pub(crate) fn runnable_args(&self, kind: &RunnableKind) -> Option<Runnable> {
match kind {
- RunnableKind::Bin => {
- for runnable in &self.shell_runnables {
- if matches!(runnable.kind, project_model::project_json::RunnableKind::Run) {
- let mut runnable = runnable.clone();
-
- let replaced_args: Vec<_> = runnable
- .args
- .iter()
- .map(|arg| arg.replace("{label}", &self.label))
- .collect();
- runnable.args = replaced_args;
-
- return Some(runnable);
- }
- }
-
- None
- }
+ RunnableKind::Bin => self
+ .find_replace_runnable(project_json::RunnableKind::Run, &|this, arg| {
+ arg.replace("{label}", &this.label)
+ }),
RunnableKind::Test { test_id, .. } => {
- for runnable in &self.shell_runnables {
- if matches!(runnable.kind, project_model::project_json::RunnableKind::TestOne) {
- let mut runnable = runnable.clone();
-
- let replaced_args: Vec<_> = runnable
- .args
- .iter()
- .map(|arg| arg.replace("{test_id}", &test_id.to_string()))
- .map(|arg| arg.replace("{label}", &self.label))
- .collect();
- runnable.args = replaced_args;
-
- return Some(runnable);
- }
- }
-
- None
+ self.find_replace_runnable(project_json::RunnableKind::Run, &|this, arg| {
+ arg.replace("{label}", &this.label).replace("{test_id}", &test_id.to_string())
+ })
}
RunnableKind::TestMod { .. } => None,
RunnableKind::Bench { .. } => None,