дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 01:01:17 +02:00
Порівняти коміти
4
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
79b73394d8 | ||
|
|
42e7f777f1 | ||
|
|
b5dbd3c020 | ||
|
|
4034853f91 |
No files matched your search
Створено
@@ -4684,6 +4684,7 @@ dependencies = [
|
||||
"ide-text",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
"semver",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"specta",
|
||||
@@ -6208,6 +6209,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-appender",
|
||||
"tracing-subscriber",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -60,6 +60,7 @@ pub struct Host {
|
||||
pub languages: Arc<LanguageRegistry>,
|
||||
syntax: Arc<OnceLock<Arc<Syntax>>>,
|
||||
pub global_settings: SettingsStore,
|
||||
pub dependency_versions: Arc<ide_workspace::dependencies::VersionCache>,
|
||||
pub terminals: TerminalManager,
|
||||
pub processes: ProcessManager,
|
||||
/// Debug sessions (adapters run on this machine, next to the project).
|
||||
@@ -104,6 +105,9 @@ impl Host {
|
||||
ssh,
|
||||
environment: environment::Environment::new(project_environment, local_data_dir.clone()),
|
||||
global_settings,
|
||||
dependency_versions: Arc::new(ide_workspace::dependencies::VersionCache::new(
|
||||
data_dir.join("cache/dependency-versions"),
|
||||
)),
|
||||
// Sessions, runs and terminals report to the window that started them (`window_sink`).
|
||||
terminals: TerminalManager::new(),
|
||||
processes: ProcessManager::new(),
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Repository version lookups for manifest inspections and completion.
|
||||
use crate::{Host, rpc::Dispatcher};
|
||||
use ide_core::{CancellationToken, DocId, IdeError, IdeResult, RequestId};
|
||||
use ide_workspace::dependencies::{DependencyVersionSource, DependencyVersions, cargo};
|
||||
|
||||
struct CratesIo;
|
||||
impl DependencyVersionSource for CratesIo {
|
||||
fn id(&self) -> &'static str {
|
||||
"crates-io"
|
||||
}
|
||||
|
||||
fn fetch(&self, package: &str, cancel: &CancellationToken) -> IdeResult<Vec<String>> {
|
||||
let path = cargo::index_path(package).ok_or_else(|| IdeError::internal("invalid crate name"))?;
|
||||
let search_path = std::env::var_os("PATH").unwrap_or_default();
|
||||
let text = ide_tools::Http::new(&search_path)?.https_only().get_text_limited(
|
||||
&format!("https://index.crates.io/{path}"),
|
||||
Some(16 * 1024 * 1024),
|
||||
cancel,
|
||||
)?;
|
||||
cargo::parse_index(&text).ok_or_else(|| IdeError::internal("invalid sparse index"))
|
||||
}
|
||||
}
|
||||
|
||||
/// `offset` limits a completion request to its version string; inspections omit it.
|
||||
pub async fn dependency_versions(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
doc: DocId,
|
||||
offset: Option<u32>,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<DependencyVersions>> {
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let cancel = host.begin_request(request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
let snap = project.documents.snapshot(doc)?;
|
||||
if snap.large || snap.read_only || snap.path.file_name().is_none_or(|n| n != "Cargo.toml") {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for dependency in cargo::dependencies(&snap.text) {
|
||||
if offset.is_some_and(|pos| pos < dependency.from || pos > dependency.to) {
|
||||
continue;
|
||||
}
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let versions = cache.versions(&CratesIo, &dependency.package, &cancel)?;
|
||||
let update = cargo::update(&dependency.requirement, &versions);
|
||||
out.push(DependencyVersions { dependency, versions, update });
|
||||
}
|
||||
Ok(out)
|
||||
})
|
||||
.await;
|
||||
host.end_request(request);
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("dependency_versions", |c| async move {
|
||||
dependency_versions(&c.host, &c.window, c.arg("doc")?, c.arg("offset")?, c.arg("request")?).await
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::HostConfig;
|
||||
use std::sync::Arc;
|
||||
|
||||
struct Source;
|
||||
impl DependencyVersionSource for Source {
|
||||
fn id(&self) -> &'static str {
|
||||
"crates-io"
|
||||
}
|
||||
fn fetch(&self, _: &str, _: &CancellationToken) -> IdeResult<Vec<String>> {
|
||||
Ok(vec!["1.10.0".into(), "0.2.1".into()])
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn host_uses_synced_document_cache_and_cursor_filter_without_network() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
let text = "# 中文 😀\n[dependencies]\ntokio = { version = \"0.2\", features = [\"full\"] }\nserde = \"1.0.100\"\nlocal = { path = \"../x\", version = \"0.2\" }\n";
|
||||
let path = root.join("Cargo.toml");
|
||||
std::fs::write(&path, text).unwrap();
|
||||
let host = Host::new(HostConfig {
|
||||
config_dir: base.join("config"),
|
||||
data_dir: base.join("data"),
|
||||
languages: Arc::new(ide_language::LanguageRegistry::load(None).unwrap()),
|
||||
syntax: Arc::default(),
|
||||
sink_for: Box::new(|_| Arc::new(|_| {})),
|
||||
owner: |w| w,
|
||||
runtime: tokio::runtime::Handle::current(),
|
||||
project_environment: false,
|
||||
});
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
let info = project.documents.open(&path).unwrap();
|
||||
for package in ["tokio", "serde"] {
|
||||
host.dependency_versions.versions(&Source, package, &CancellationToken::new()).unwrap();
|
||||
}
|
||||
let all = dependency_versions(&host, "main", info.id, None, RequestId(410)).await.unwrap();
|
||||
assert_eq!(all.len(), 2);
|
||||
assert_eq!(all[0].update.as_ref().unwrap().replacement, "1.10");
|
||||
assert!(all[1].update.is_none());
|
||||
let offset = all[1].dependency.from;
|
||||
let at_cursor = dependency_versions(&host, "main", info.id, Some(offset), RequestId(411)).await.unwrap();
|
||||
assert_eq!(at_cursor.len(), 1);
|
||||
assert_eq!(at_cursor[0].dependency.package, "serde");
|
||||
assert!(dependency_versions(&host, "main", info.id, Some(0), RequestId(412)).await.unwrap().is_empty());
|
||||
host.cancel_request(RequestId(413));
|
||||
assert!(dependency_versions(&host, "main", info.id, None, RequestId(413)).await.is_err());
|
||||
let other = root.join("other.toml");
|
||||
std::fs::write(&other, text).unwrap();
|
||||
let info = project.documents.open(&other).unwrap();
|
||||
assert!(dependency_versions(&host, "main", info.id, None, RequestId(414)).await.unwrap().is_empty());
|
||||
host.close_project("main");
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ pub mod build;
|
||||
pub mod bytes;
|
||||
pub mod coverage;
|
||||
pub mod debug;
|
||||
pub mod dependencies;
|
||||
pub mod deploy;
|
||||
pub mod doc;
|
||||
pub mod env;
|
||||
@@ -69,6 +70,7 @@ pub fn register_all(d: &mut crate::rpc::Dispatcher) {
|
||||
analysis::register(d);
|
||||
syntax::register(d);
|
||||
spell::register(d);
|
||||
dependencies::register(d);
|
||||
history::register(d);
|
||||
coverage::register(d);
|
||||
build::register(d);
|
||||
|
||||
@@ -5,6 +5,23 @@ use crate::rpc::Dispatcher;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use ide_run::RunConfig;
|
||||
|
||||
pub async fn run_dotnet_resolve(host: &Host, window: &str, config: RunConfig, debug: bool) -> IdeResult<RunConfig> {
|
||||
host.require_trust(window)?;
|
||||
if !matches!(config.kind.as_str(), "dotnet" | "dotnet-test")
|
||||
|| config.extras.target.as_ref().is_some_and(|s| !s.is_empty())
|
||||
{
|
||||
return Err(IdeError::invalid(".NET Project requires the local machine"));
|
||||
}
|
||||
let project = host.project(window)?;
|
||||
let mut config = host.blocking(move || ide_run::dotnet::resolve(&project.root, config)).await?;
|
||||
if debug {
|
||||
let root = host.project(window)?.root.clone();
|
||||
let target = ide_run::dotnet::target_path(&root, &config).await?;
|
||||
config.extras.params.insert("targetPath".into(), target);
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
fn application_cache(project: &crate::project::Project, id: &str) -> std::path::PathBuf {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut hash = std::collections::hash_map::DefaultHasher::new();
|
||||
@@ -206,6 +223,9 @@ pub async fn run_tomcat_update(host: &Host, window: &str, config: RunConfig, mod
|
||||
|
||||
/// Commands of this module the remote server answers.
|
||||
pub(crate) fn register(d: &mut Dispatcher) {
|
||||
d.add("run_dotnet_resolve", |c| async move {
|
||||
run_dotnet_resolve(&c.host, &c.window, c.arg("config")?, c.arg("debug")?).await
|
||||
});
|
||||
d.add("run_application_build", |c| async move {
|
||||
run_application_build(&c.host, &c.window, c.arg("config")?, c.arg("module")?).await
|
||||
});
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
//! Detection never fails: unreadable or malformed files simply contribute nothing.
|
||||
|
||||
pub(crate) mod cmake;
|
||||
mod dotnet;
|
||||
|
||||
use crate::RunConfig;
|
||||
use serde_json::Value as Json;
|
||||
@@ -33,6 +34,7 @@ pub(crate) fn detect_with_profiles(
|
||||
detect_go(root, &mut out);
|
||||
detect_python(root, &mut out);
|
||||
cmake::detect(root, profiles, &mut out);
|
||||
dotnet::detect(root, &mut out);
|
||||
detect_make(root, &mut out);
|
||||
detect_just(root, &mut out);
|
||||
detect_godot(root, &mut out);
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
//! Runnable .NET projects and launch profiles, without a solution model.
|
||||
|
||||
use crate::{
|
||||
RunConfig,
|
||||
dotnet::{parse_project, profiles, solution_projects},
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
fs,
|
||||
path::Path,
|
||||
};
|
||||
|
||||
pub(crate) fn detect(root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let mut dirs = vec![root.to_path_buf()];
|
||||
let mut projects = BTreeSet::new();
|
||||
while let Some(dir) = dirs.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else { continue };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if entry.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
if !name.starts_with('.')
|
||||
&& !matches!(
|
||||
name.as_str(),
|
||||
"bin" | "obj" | "node_modules" | "target" | "build" | "dist" | "vendor" | "packages"
|
||||
)
|
||||
{
|
||||
dirs.push(path);
|
||||
}
|
||||
} else if entry.file_type().is_ok_and(|t| t.is_file()) {
|
||||
match path.extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase().as_str() {
|
||||
"csproj" => {
|
||||
projects.insert(path);
|
||||
}
|
||||
"sln" | "slnx" => {
|
||||
if let Ok(src) = fs::read_to_string(&path) {
|
||||
for project in solution_projects(
|
||||
&src,
|
||||
path.extension().is_some_and(|e| e.eq_ignore_ascii_case("slnx")),
|
||||
) {
|
||||
projects.insert(dir.join(project));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let root = dunce::canonicalize(root).unwrap_or_else(|_| root.into());
|
||||
let projects: BTreeSet<_> = projects.into_iter().filter_map(|p| dunce::canonicalize(p).ok()).collect();
|
||||
for path in projects {
|
||||
let Some(project) = fs::read_to_string(&path).ok().and_then(|s| parse_project(&s)) else { continue };
|
||||
let rel = path.strip_prefix(&root).unwrap_or(&path).to_string_lossy().replace('\\', "/");
|
||||
let name = path.file_stem().unwrap_or_default().to_string_lossy();
|
||||
let profiles = profiles(&path);
|
||||
let mut params = BTreeMap::from([
|
||||
("project".into(), rel.clone()),
|
||||
("framework".into(), project.frameworks.first().cloned().unwrap_or_default()),
|
||||
("frameworks".into(), project.frameworks.join(";")),
|
||||
("profiles".into(), serde_json::to_string(&profiles).unwrap_or_default()),
|
||||
("launchProfile".into(), String::new()),
|
||||
("programArgs".into(), String::new()),
|
||||
]);
|
||||
if project.executable && !project.test {
|
||||
out.push(detected(&rel, &name, "", params.clone(), false));
|
||||
for profile in profiles.keys() {
|
||||
params.insert("launchProfile".into(), profile.clone());
|
||||
out.push(detected(&rel, &name, profile, params.clone(), false));
|
||||
}
|
||||
}
|
||||
if project.test {
|
||||
params.insert("launchProfile".into(), String::new());
|
||||
out.push(detected(&rel, &name, "", params, true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn detected(project: &str, name: &str, profile: &str, params: BTreeMap<String, String>, test: bool) -> RunConfig {
|
||||
let op = if test { "test" } else { "run" };
|
||||
let mut config = super::config(
|
||||
format!("dotnet:{project}:{op}:{profile}"),
|
||||
if test {
|
||||
format!("dotnet test ({name})")
|
||||
} else if profile.is_empty() {
|
||||
format!("{name} (.NET Project)")
|
||||
} else {
|
||||
format!("{name}: {profile}")
|
||||
},
|
||||
if test { "dotnet-test" } else { "dotnet" },
|
||||
"dotnet",
|
||||
&[],
|
||||
);
|
||||
config.args = command_args(¶ms, test);
|
||||
config.is_test = test;
|
||||
config.debug_adapter = (!test).then(|| "netcoredbg".into());
|
||||
config.extras.params = params;
|
||||
if !test {
|
||||
config.extras.before_launch.push(crate::BeforeLaunchTask { kind: "dotnetBuild".into(), target: String::new() });
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
fn command_args(params: &BTreeMap<String, String>, test: bool) -> Vec<String> {
|
||||
let mut args = if test {
|
||||
vec!["test".into(), params.get("project").cloned().unwrap_or_default()]
|
||||
} else {
|
||||
vec!["run".into(), "--project".into(), params.get("project").cloned().unwrap_or_default()]
|
||||
};
|
||||
if let Some(framework) = params.get("framework").filter(|s| !s.is_empty()) {
|
||||
args.extend(["--framework".into(), framework.clone()]);
|
||||
}
|
||||
if !test {
|
||||
if let Some(profile) = params.get("launchProfile").filter(|s| !s.is_empty()) {
|
||||
args.extend(["--launch-profile".into(), profile.clone()]);
|
||||
} else {
|
||||
args.push("--no-launch-profile".into());
|
||||
}
|
||||
}
|
||||
args
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
//! Lightweight .NET project discovery; MSBuild remains the authority for build outputs.
|
||||
|
||||
use crate::RunConfig;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use quick_xml::{Reader, XmlVersion, events::Event};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Project {
|
||||
pub executable: bool,
|
||||
pub frameworks: Vec<String>,
|
||||
pub test: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Element {
|
||||
name: String,
|
||||
attrs: BTreeMap<String, String>,
|
||||
text: String,
|
||||
conditional: bool,
|
||||
}
|
||||
|
||||
fn elements(xml: &str) -> Option<Vec<Element>> {
|
||||
let mut reader = Reader::from_str(xml);
|
||||
let mut out: Vec<Element> = Vec::new();
|
||||
let mut stack: Vec<usize> = Vec::new();
|
||||
loop {
|
||||
let event = reader.read_event().ok()?;
|
||||
let empty = matches!(&event, Event::Empty(_));
|
||||
match event {
|
||||
Event::Start(tag) | Event::Empty(tag) => {
|
||||
let attrs: BTreeMap<_, _> = tag
|
||||
.attributes()
|
||||
.map(|a| {
|
||||
let a = a.ok()?;
|
||||
Some((
|
||||
a.key.as_ref().to_owned(),
|
||||
a.normalized_value(XmlVersion::Implicit1_0).ok()?.into_owned(),
|
||||
))
|
||||
})
|
||||
.collect::<Option<_>>()?;
|
||||
let conditional = attrs.contains_key("Condition") || stack.last().is_some_and(|i| out[*i].conditional);
|
||||
out.push(Element {
|
||||
name: tag.local_name().as_ref().to_owned(),
|
||||
attrs,
|
||||
conditional,
|
||||
..Default::default()
|
||||
});
|
||||
// Empty elements have no corresponding End event.
|
||||
if !empty {
|
||||
stack.push(out.len() - 1);
|
||||
}
|
||||
}
|
||||
Event::End(_) => {
|
||||
stack.pop()?;
|
||||
}
|
||||
Event::Text(text) => {
|
||||
if let Some(i) = stack.last() {
|
||||
out[*i].text.push_str(&text.xml_content(XmlVersion::Implicit1_0));
|
||||
}
|
||||
}
|
||||
Event::CData(text) => {
|
||||
if let Some(i) = stack.last() {
|
||||
out[*i].text.push_str(text.as_ref());
|
||||
}
|
||||
}
|
||||
Event::GeneralRef(reference) => {
|
||||
let name = reference.as_ref();
|
||||
let escaped = format!("&{name};");
|
||||
if let Some(i) = stack.last() {
|
||||
out[*i].text.push_str(&quick_xml::escape::unescape(&escaped).ok()?);
|
||||
}
|
||||
}
|
||||
Event::Eof => return stack.is_empty().then_some(out),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_project(xml: &str) -> Option<Project> {
|
||||
let tags = elements(xml)?;
|
||||
if tags.first()?.name != "Project" {
|
||||
return None;
|
||||
}
|
||||
let property = |name: &str| tags.iter().rev().find(|t| t.name == name && !t.conditional).map(|t| t.text.trim());
|
||||
let web = tags.iter().any(|t| {
|
||||
t.attrs
|
||||
.get("Sdk")
|
||||
.or_else(|| (t.name == "Sdk").then(|| t.attrs.get("Name")).flatten())
|
||||
.is_some_and(|s| s.split(';').any(|sdk| sdk.split('/').next() == Some("Microsoft.NET.Sdk.Web")))
|
||||
});
|
||||
let executable = match property("OutputType") {
|
||||
Some(output) => output.eq_ignore_ascii_case("exe") || output.eq_ignore_ascii_case("winexe"),
|
||||
None => web,
|
||||
};
|
||||
let frameworks = property("TargetFramework")
|
||||
.filter(|v| !v.is_empty())
|
||||
.or_else(|| property("TargetFrameworks"))
|
||||
.unwrap_or_default()
|
||||
.split(';')
|
||||
.map(str::trim)
|
||||
.filter(|v| !v.is_empty())
|
||||
.map(str::to_owned)
|
||||
.collect();
|
||||
let test = tags.iter().any(|t| {
|
||||
t.name == "PackageReference"
|
||||
&& t.attrs
|
||||
.get("Include")
|
||||
.or_else(|| t.attrs.get("Update"))
|
||||
.is_some_and(|v| v.eq_ignore_ascii_case("Microsoft.NET.Test.Sdk"))
|
||||
});
|
||||
Some(Project { executable, frameworks, test })
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(rename_all = "camelCase", default)]
|
||||
pub struct Profile {
|
||||
pub command_name: String,
|
||||
pub command_line_args: String,
|
||||
pub working_directory: String,
|
||||
pub application_url: String,
|
||||
pub environment_variables: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
pub fn parse_profiles(json: &str) -> BTreeMap<String, Profile> {
|
||||
let Ok(json) = serde_json::from_str::<serde_json::Value>(&ide_core::jsonc::strip(json)) else {
|
||||
return BTreeMap::new();
|
||||
};
|
||||
json["profiles"]
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|(name, value)| {
|
||||
let profile: Profile = serde_json::from_value(value.clone()).ok()?;
|
||||
(profile.command_name == "Project").then(|| (name.clone(), profile))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn solution_projects(src: &str, xml: bool) -> Vec<PathBuf> {
|
||||
let paths: Vec<String> = if xml {
|
||||
elements(src)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter(|e| e.name == "Project")
|
||||
.filter_map(|mut e| e.attrs.remove("Path"))
|
||||
.collect()
|
||||
} else {
|
||||
src.lines()
|
||||
.filter_map(|line| {
|
||||
let line = line.trim();
|
||||
if !line.starts_with("Project(") {
|
||||
return None;
|
||||
}
|
||||
Some(line.split_once('=')?.1.split('"').nth(3)?.to_owned())
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
paths
|
||||
.into_iter()
|
||||
.filter(|p| p.to_ascii_lowercase().ends_with(".csproj"))
|
||||
.map(|p| PathBuf::from(p.replace('\\', "/")))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn profiles(project: &Path) -> BTreeMap<String, Profile> {
|
||||
project
|
||||
.parent()
|
||||
.and_then(|p| fs::read_to_string(p.join("Properties/launchSettings.json")).ok())
|
||||
.map(|s| parse_profiles(&s))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Resolves the selected profile afresh so changing project/profile never reuses stale values.
|
||||
pub fn resolve(root: &Path, mut config: RunConfig) -> IdeResult<RunConfig> {
|
||||
let params = &config.extras.params;
|
||||
let project = params
|
||||
.get("project")
|
||||
.filter(|s| !s.trim().is_empty())
|
||||
.ok_or_else(|| IdeError::invalid("Select a .NET project"))?;
|
||||
let project = dunce::canonicalize(root.join(project))?;
|
||||
let dir = project.parent().ok_or_else(|| IdeError::invalid("Invalid .NET project path"))?;
|
||||
let profile_name = params.get("launchProfile").cloned().unwrap_or_default();
|
||||
let profile = if profile_name.is_empty() {
|
||||
Profile::default()
|
||||
} else {
|
||||
profiles(&project).remove(&profile_name).ok_or_else(|| {
|
||||
IdeError::invalid(format!(".NET launch profile '{profile_name}' is missing or is not a Project profile"))
|
||||
})?
|
||||
};
|
||||
let mut env = profile.environment_variables;
|
||||
if !profile.application_url.is_empty() {
|
||||
env.insert("ASPNETCORE_URLS".into(), profile.application_url);
|
||||
}
|
||||
if !profile_name.is_empty() {
|
||||
env.insert("DOTNET_LAUNCH_PROFILE".into(), profile_name);
|
||||
}
|
||||
env.extend(config.env);
|
||||
config.env = env;
|
||||
config.cwd = Some(
|
||||
config
|
||||
.cwd
|
||||
.map(|p| root.join(&*p))
|
||||
.unwrap_or_else(|| {
|
||||
if profile.working_directory.is_empty() { dir.into() } else { dir.join(&profile.working_directory) }
|
||||
})
|
||||
.into(),
|
||||
);
|
||||
config.extras.params.insert("project".into(), project.to_string_lossy().into_owned());
|
||||
config.extras.params.insert("profileArgs".into(), profile.command_line_args);
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
/// Queries the evaluated output path, including AssemblyName, OutputPath and imported properties.
|
||||
pub async fn target_path(root: &Path, config: &RunConfig) -> IdeResult<String> {
|
||||
let params = &config.extras.params;
|
||||
let project = params.get("project").ok_or_else(|| IdeError::invalid("Select a .NET project"))?;
|
||||
let mut args = vec![
|
||||
"msbuild".to_owned(),
|
||||
root.join(project).to_string_lossy().into_owned(),
|
||||
"-nologo".into(),
|
||||
"-getProperty:TargetPath".into(),
|
||||
"-p:Configuration=Debug".into(),
|
||||
];
|
||||
if let Some(framework) = params.get("framework").filter(|s| !s.is_empty()) {
|
||||
args.push(format!("-p:TargetFramework={framework}"));
|
||||
}
|
||||
let mut command = std::process::Command::new(&config.command);
|
||||
ide_core::process::host_env(&mut command);
|
||||
command.args(args).current_dir(root);
|
||||
if !config.extras.include_system_env {
|
||||
command.env_clear();
|
||||
} else {
|
||||
command.envs(ide_core::process::shell_env());
|
||||
}
|
||||
command.envs(crate::resolved_env(root, config)?);
|
||||
let mut command = tokio::process::Command::from(command);
|
||||
command.kill_on_drop(true);
|
||||
let output = tokio::time::timeout(std::time::Duration::from_secs(30), command.output())
|
||||
.await
|
||||
.map_err(|_| IdeError::unavailable(".NET output resolution timed out"))??;
|
||||
if !output.status.success() {
|
||||
return Err(IdeError::invalid(format!(
|
||||
".NET output resolution failed: {}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
)));
|
||||
}
|
||||
let target = String::from_utf8_lossy(&output.stdout).trim().to_owned();
|
||||
if target.is_empty() || !Path::new(&target).is_file() {
|
||||
return Err(IdeError::invalid(".NET build output is missing; run dotnet build before debugging"));
|
||||
}
|
||||
Ok(target)
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
mod config;
|
||||
mod detect;
|
||||
pub mod dotnet;
|
||||
pub mod envfile;
|
||||
pub mod go;
|
||||
pub mod gradle_jvm;
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
use ide_run::{
|
||||
detect,
|
||||
dotnet::{parse_profiles, parse_project, resolve, solution_projects},
|
||||
};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const CONSOLE: &str = r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFrameworks>net10.0; net9.0</TargetFrameworks></PropertyGroup></Project>"#;
|
||||
const PROFILES: &str = r#"{
|
||||
// Only Project profiles can be run with dotnet.
|
||||
"profiles": {
|
||||
"http": {"commandName":"Project", "applicationUrl":"http://localhost:5165", "commandLineArgs":"--message \"hello world\"", "workingDirectory":"work", "environmentVariables":{"DEMO":"profile"}},
|
||||
"https": {"commandName":"Project", "environmentVariables":{"DEMO":"https"}},
|
||||
"IIS Express": {"commandName":"IISExpress"},
|
||||
"external": {"commandName":"Executable"},
|
||||
"broken": {"commandName":"Project", "environmentVariables":7}
|
||||
}
|
||||
}"#;
|
||||
|
||||
fn write(root: &std::path::Path, file: &str, src: &str) {
|
||||
let path = root.join(file);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, src).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_properties_and_sdk_defaults() {
|
||||
let p = parse_project(CONSOLE).unwrap();
|
||||
assert!(p.executable && !p.test);
|
||||
assert_eq!(p.frameworks, ["net10.0", "net9.0"]);
|
||||
for (sdk, output, executable) in [
|
||||
("Microsoft.NET.Sdk", "", false),
|
||||
("Microsoft.NET.Sdk", "<OutputType>WinExe</OutputType>", true),
|
||||
("Microsoft.NET.Sdk.Web", "", true),
|
||||
("Microsoft.NET.Sdk.Web", "<OutputType>Library</OutputType>", false),
|
||||
] {
|
||||
let xml = format!(
|
||||
r#"<Project Sdk="{sdk}"><PropertyGroup>{output}<TargetFramework>net10.0</TargetFramework></PropertyGroup></Project>"#
|
||||
);
|
||||
let p = parse_project(&xml).unwrap();
|
||||
assert_eq!(p.executable, executable, "{xml}");
|
||||
assert_eq!(p.frameworks, ["net10.0"]);
|
||||
}
|
||||
let p = parse_project(r#"<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"><Sdk Name="Microsoft.NET.Sdk.Web"/><PropertyGroup><TargetFramework>net10.0</TargetFramework></PropertyGroup><PropertyGroup Condition="'$(Configuration)'=='Release'"><OutputType>Library</OutputType></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0" /></ItemGroup></Project>"#).unwrap();
|
||||
assert!(p.executable && p.test);
|
||||
assert!(parse_project("<Project><PropertyGroup>").is_none());
|
||||
assert!(parse_project("garbage").is_none());
|
||||
assert!(
|
||||
parse_project(
|
||||
r#"<Project><ItemGroup><PackageReference Update="microsoft.net.test.sdk" /></ItemGroup></Project>"#
|
||||
)
|
||||
.unwrap()
|
||||
.test
|
||||
);
|
||||
assert!(
|
||||
!parse_project(r#"<Project><!-- <PackageReference Include="Microsoft.NET.Test.Sdk"/> --></Project>"#)
|
||||
.unwrap()
|
||||
.test
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profiles_filter_and_preserve_launch_properties() {
|
||||
let p = parse_profiles(PROFILES);
|
||||
assert_eq!(p.keys().map(String::as_str).collect::<Vec<_>>(), ["http", "https"]);
|
||||
assert_eq!(p["http"].application_url, "http://localhost:5165");
|
||||
assert_eq!(p["http"].environment_variables["DEMO"], "profile");
|
||||
assert_eq!(p["http"].command_line_args, "--message \"hello world\"");
|
||||
assert_eq!(p["http"].working_directory, "work");
|
||||
assert!(parse_profiles("invalid").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solution_paths_support_windows_separators_folders_and_entities() {
|
||||
let sln = "Project(\"{guid}\") = \"App\", \"src\\App\\App.csproj\", \"{guid}\"\nEndProject\nProject(\"{folder}\") = \"Folder\", \"Folder\", \"{guid}\"\nProject(\"{guid}\") = \"External\", \"..\\other\\Other.csproj\", \"{guid}\"";
|
||||
assert_eq!(
|
||||
solution_projects(sln, false),
|
||||
[PathBuf::from("src/App/App.csproj"), PathBuf::from("../other/Other.csproj")]
|
||||
);
|
||||
let slnx = r#"<Solution><Folder Name="/src/"><Project Path="src\A&B\App.csproj" /></Folder><Project Path="other.vbproj" /></Solution>"#;
|
||||
assert_eq!(solution_projects(slnx, true), [PathBuf::from("src/A&B/App.csproj")]);
|
||||
assert!(solution_projects("<Solution><Project", true).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detection_deduplicates_projects_and_generates_commands() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path();
|
||||
write(root, "src/App/App.csproj", CONSOLE);
|
||||
write(root, "src/App/Properties/launchSettings.json", PROFILES);
|
||||
write(
|
||||
root,
|
||||
"demo.slnx",
|
||||
r#"<Solution><Project Path="src/App/App.csproj"/><Project Path="../external/Missing.csproj"/></Solution>"#,
|
||||
);
|
||||
write(
|
||||
root,
|
||||
"src/Test/Test.csproj",
|
||||
r#"<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net10.0</TargetFramework></PropertyGroup><ItemGroup><PackageReference Include="Microsoft.NET.Test.Sdk"/></ItemGroup></Project>"#,
|
||||
);
|
||||
write(root, "bin/Ignored.csproj", CONSOLE);
|
||||
write(root, "obj/Ignored.csproj", CONSOLE);
|
||||
write(root, "node_modules/Ignored.csproj", CONSOLE);
|
||||
write(root, "Lib.csproj", "<Project Sdk=\"Microsoft.NET.Sdk\" />");
|
||||
let configs = detect(root);
|
||||
assert_eq!(configs.len(), 4);
|
||||
let app = configs.iter().find(|c| c.extras.params.get("launchProfile").is_some_and(|p| p == "http")).unwrap();
|
||||
assert_eq!(
|
||||
app.args,
|
||||
["run", "--project", "src/App/App.csproj", "--framework", "net10.0", "--launch-profile", "http"]
|
||||
);
|
||||
assert_eq!(app.debug_adapter.as_deref(), Some("netcoredbg"));
|
||||
assert_eq!(app.extras.before_launch[0].kind, "dotnetBuild");
|
||||
let test = configs.iter().find(|c| c.is_test).unwrap();
|
||||
assert_eq!(test.kind, "dotnet-test");
|
||||
assert_eq!(test.args, ["test", "src/Test/Test.csproj", "--framework", "net10.0"]);
|
||||
assert!(test.debug_adapter.is_none());
|
||||
let mut edited = app.clone();
|
||||
edited.env.insert("DEMO".into(), "override".into());
|
||||
let resolved = resolve(root, edited.clone()).unwrap();
|
||||
assert_eq!(resolved.env["DEMO"], "override");
|
||||
assert_eq!(resolved.env["ASPNETCORE_URLS"], "http://localhost:5165");
|
||||
assert!(resolved.cwd.unwrap().ends_with("src/App/work"));
|
||||
edited.extras.params.insert("launchProfile".into(), "https".into());
|
||||
let resolved = resolve(root, edited).unwrap();
|
||||
assert!(!resolved.env.contains_key("ASPNETCORE_URLS"));
|
||||
assert!(resolved.cwd.unwrap().ends_with("src/App"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solution_references_can_reach_projects_outside_the_open_directory() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
write(temp.path(), "external/App.csproj", CONSOLE);
|
||||
write(temp.path(), "open/demo.sln", "Project(\"{guid}\") = \"App\", \"..\\external\\App.csproj\", \"{guid}\"");
|
||||
let configs = detect(&temp.path().join("open"));
|
||||
assert_eq!(configs.len(), 1);
|
||||
assert!(configs[0].args[2].ends_with("external/App.csproj"));
|
||||
}
|
||||
@@ -15,6 +15,7 @@ serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
toml.workspace = true
|
||||
toml_edit.workspace = true
|
||||
semver = "1.0.28"
|
||||
parking_lot.workspace = true
|
||||
blake3.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
use super::DependencyVersionSource;
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
const TTL: Duration = Duration::from_secs(3600);
|
||||
const FAILURE_TTL: Duration = Duration::from_secs(30);
|
||||
const MAX_DISK_BYTES: u64 = 2 * 1024 * 1024;
|
||||
type Slot = Arc<Mutex<Option<Cached>>>;
|
||||
|
||||
#[derive(Clone, Serialize, Deserialize)]
|
||||
struct Cached {
|
||||
fetched: u64,
|
||||
versions: Vec<String>,
|
||||
#[serde(skip)]
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
/// Same-package lookups share one lock and fetch. Different packages don't block
|
||||
/// each other; waiting callers can cancel independently of the active fetch.
|
||||
pub struct VersionCache {
|
||||
directory: PathBuf,
|
||||
entries: Mutex<HashMap<String, Slot>>,
|
||||
ttl: Duration,
|
||||
}
|
||||
|
||||
impl VersionCache {
|
||||
pub fn new(directory: PathBuf) -> Self {
|
||||
Self { directory, entries: Mutex::default(), ttl: TTL }
|
||||
}
|
||||
|
||||
pub fn versions(
|
||||
&self,
|
||||
source: &dyn DependencyVersionSource,
|
||||
package: &str,
|
||||
cancel: &CancellationToken,
|
||||
) -> IdeResult<Vec<String>> {
|
||||
let safe = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b));
|
||||
if !safe(source.id()) || !safe(package) || package.len() > 64 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let key = format!("{}-{}", source.id(), package.to_ascii_lowercase());
|
||||
let slot = self.entries.lock().entry(key.clone()).or_default().clone();
|
||||
let mut cached = loop {
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
if let Some(guard) = slot.try_lock_for(Duration::from_millis(50)) {
|
||||
break guard;
|
||||
}
|
||||
};
|
||||
let checked_at = now();
|
||||
let fresh = |c: &Cached| {
|
||||
c.fetched <= checked_at && checked_at - c.fetched < if c.failed { FAILURE_TTL } else { self.ttl }.as_secs()
|
||||
};
|
||||
if let Some(entry) = cached.as_ref().filter(|c| fresh(c)) {
|
||||
return Ok(entry.versions.clone());
|
||||
}
|
||||
let path = self.directory.join(format!("{key}.json"));
|
||||
let disk = std::fs::metadata(&path)
|
||||
.ok()
|
||||
.filter(|m| m.len() <= MAX_DISK_BYTES)
|
||||
.and_then(|_| std::fs::read(&path).ok())
|
||||
.and_then(|bytes| serde_json::from_slice::<Cached>(&bytes).ok())
|
||||
.filter(fresh);
|
||||
if let Some(entry) = disk {
|
||||
let versions = entry.versions.clone();
|
||||
*cached = Some(entry);
|
||||
return Ok(versions);
|
||||
}
|
||||
let result = source.fetch(package, cancel);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(IdeError::cancelled());
|
||||
}
|
||||
let failed = result.is_err();
|
||||
let versions = result.unwrap_or_default();
|
||||
let entry = Cached { fetched: now(), versions: versions.clone(), failed };
|
||||
if !failed
|
||||
&& let Ok(bytes) = serde_json::to_vec(&entry)
|
||||
&& std::fs::create_dir_all(&self.directory).is_ok()
|
||||
{
|
||||
let temporary = path.with_extension("tmp");
|
||||
if std::fs::write(&temporary, bytes).is_ok() {
|
||||
let _ = std::fs::rename(&temporary, &path);
|
||||
let _ = std::fs::remove_file(&temporary);
|
||||
}
|
||||
}
|
||||
*cached = Some(entry);
|
||||
Ok(versions)
|
||||
}
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,97 @@
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct Source {
|
||||
calls: AtomicUsize,
|
||||
fail: bool,
|
||||
}
|
||||
impl DependencyVersionSource for Source {
|
||||
fn id(&self) -> &'static str {
|
||||
"test"
|
||||
}
|
||||
fn fetch(&self, _: &str, _: &CancellationToken) -> IdeResult<Vec<String>> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
if self.fail { Err(IdeError::unavailable("offline")) } else { Ok(vec!["2.0.0".into()]) }
|
||||
}
|
||||
}
|
||||
fn source(fail: bool) -> Source {
|
||||
Source { calls: AtomicUsize::new(0), fail }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_disk_ttl_corruption_and_failed_cache_writes() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let s = source(false);
|
||||
let cancel = CancellationToken::new();
|
||||
let cache = VersionCache::new(dir.path().into());
|
||||
for _ in 0..2 {
|
||||
assert_eq!(cache.versions(&s, "foo", &cancel).unwrap(), ["2.0.0"]);
|
||||
}
|
||||
assert_eq!(s.calls.load(Ordering::SeqCst), 1);
|
||||
VersionCache::new(dir.path().into()).versions(&s, "foo", &cancel).unwrap();
|
||||
assert_eq!(s.calls.load(Ordering::SeqCst), 1, "disk hit after service restart");
|
||||
let mut expired = VersionCache::new(dir.path().into());
|
||||
expired.ttl = Duration::ZERO;
|
||||
expired.versions(&s, "foo", &cancel).unwrap();
|
||||
assert_eq!(s.calls.load(Ordering::SeqCst), 2);
|
||||
std::fs::write(dir.path().join("test-foo.json"), b"corrupt").unwrap();
|
||||
VersionCache::new(dir.path().into()).versions(&s, "foo", &cancel).unwrap();
|
||||
assert_eq!(s.calls.load(Ordering::SeqCst), 3);
|
||||
let file = dir.path().join("not-a-directory");
|
||||
std::fs::write(&file, "x").unwrap();
|
||||
assert_eq!(VersionCache::new(file).versions(&s, "foo", &cancel).unwrap(), ["2.0.0"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concurrent_fetches_coalesce_and_failures_are_silent_and_short_cached() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cache = VersionCache::new(dir.path().into());
|
||||
let s = source(false);
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..8 {
|
||||
scope.spawn(|| assert_eq!(cache.versions(&s, "foo", &CancellationToken::new()).unwrap(), ["2.0.0"]));
|
||||
}
|
||||
});
|
||||
assert_eq!(s.calls.load(Ordering::SeqCst), 1);
|
||||
let s = source(true);
|
||||
for _ in 0..2 {
|
||||
assert!(cache.versions(&s, "offline", &CancellationToken::new()).unwrap().is_empty());
|
||||
}
|
||||
assert_eq!(s.calls.load(Ordering::SeqCst), 1);
|
||||
assert!(!dir.path().join("test-offline.json").exists(), "failures aren't persisted");
|
||||
let slot = cache.entries.lock().get("test-offline").unwrap().clone();
|
||||
slot.lock().as_mut().unwrap().fetched -= 31;
|
||||
cache.versions(&s, "offline", &CancellationToken::new()).unwrap();
|
||||
assert_eq!(s.calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_and_invalid_cache_keys_do_not_fetch() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cache = VersionCache::new(dir.path().into());
|
||||
let s = source(false);
|
||||
let token = CancellationToken::new();
|
||||
token.cancel();
|
||||
assert!(cache.versions(&s, "foo", &token).is_err());
|
||||
assert!(cache.versions(&s, "../foo", &CancellationToken::new()).unwrap().is_empty());
|
||||
assert_eq!(s.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelled_waiter_does_not_cancel_the_shared_fetch() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let cache = VersionCache::new(dir.path().into());
|
||||
let s = source(false);
|
||||
let slot = Arc::new(Mutex::new(None));
|
||||
cache.entries.lock().insert("test-foo".into(), slot.clone());
|
||||
let guard = slot.lock();
|
||||
let token = CancellationToken::new();
|
||||
std::thread::scope(|scope| {
|
||||
let waiter = scope.spawn(|| cache.versions(&s, "foo", &token));
|
||||
token.cancel();
|
||||
assert!(waiter.join().unwrap().is_err());
|
||||
});
|
||||
drop(guard);
|
||||
assert_eq!(cache.versions(&s, "foo", &CancellationToken::new()).unwrap(), ["2.0.0"]);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
use super::{DependencyUpdate, ManifestDependency};
|
||||
use semver::{Op, Version, VersionReq};
|
||||
use serde::Deserialize;
|
||||
use toml_edit::{Document, Item, TableLike};
|
||||
|
||||
/// Cargo's sparse-index path, including the special cases for short names.
|
||||
pub fn index_path(name: &str) -> Option<String> {
|
||||
if name.is_empty()
|
||||
|| name.len() > 64
|
||||
|| !name.bytes().all(|c| c.is_ascii_alphanumeric() || matches!(c, b'-' | b'_'))
|
||||
|| !name.as_bytes()[0].is_ascii_alphabetic()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let name = name.to_ascii_lowercase();
|
||||
Some(match name.len() {
|
||||
1 => format!("1/{name}"),
|
||||
2 => format!("2/{name}"),
|
||||
3 => format!("3/{}/{name}", &name[..1]),
|
||||
_ => format!("{}/{}/{name}", &name[..2], &name[2..4]),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn parse_index(text: &str) -> Option<Vec<String>> {
|
||||
#[derive(Deserialize)]
|
||||
struct Entry {
|
||||
vers: String,
|
||||
#[serde(default)]
|
||||
yanked: bool,
|
||||
}
|
||||
let mut versions = Vec::new();
|
||||
for line in text.lines().filter(|l| !l.trim().is_empty()) {
|
||||
let entry: Entry = serde_json::from_str(line).ok()?;
|
||||
if !entry.yanked {
|
||||
versions.push(Version::parse(&entry.vers).ok()?);
|
||||
}
|
||||
}
|
||||
versions.sort_unstable_by(|a, b| b.cmp(a));
|
||||
versions.dedup();
|
||||
Some(versions.into_iter().map(|v| v.to_string()).collect())
|
||||
}
|
||||
|
||||
/// A complete TOML parser supplies spans, so strings/comments that resemble tables
|
||||
/// never become dependencies. Broken documents are silent until they parse again.
|
||||
pub fn dependencies(text: &str) -> Vec<ManifestDependency> {
|
||||
let Ok(doc) = text.parse::<Document<String>>() else { return Vec::new() };
|
||||
let mut out = Vec::new();
|
||||
sections(doc.as_table(), text, &mut out);
|
||||
if let Some(workspace) = doc.get("workspace").and_then(Item::as_table_like)
|
||||
&& let Some(deps) = workspace.get("dependencies").and_then(Item::as_table_like)
|
||||
{
|
||||
collect(deps, text, &mut out);
|
||||
}
|
||||
if let Some(targets) = doc.get("target").and_then(Item::as_table_like) {
|
||||
for (_, target) in targets.iter() {
|
||||
if let Some(target) = target.as_table_like() {
|
||||
sections(target, text, &mut out);
|
||||
}
|
||||
}
|
||||
}
|
||||
out.sort_unstable_by_key(|d| d.from);
|
||||
out
|
||||
}
|
||||
|
||||
fn sections(table: &dyn TableLike, text: &str, out: &mut Vec<ManifestDependency>) {
|
||||
for section in ["dependencies", "dev-dependencies", "build-dependencies"] {
|
||||
if let Some(deps) = table.get(section).and_then(Item::as_table_like) {
|
||||
collect(deps, text, out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn collect(table: &dyn TableLike, text: &str, out: &mut Vec<ManifestDependency>) {
|
||||
for (name, item) in table.iter() {
|
||||
let (package, value) = if let Some(dep) = item.as_table_like() {
|
||||
if ["path", "git", "registry", "registry-index"].iter().any(|k| dep.contains_key(k))
|
||||
|| dep.get("workspace").and_then(Item::as_bool) == Some(true)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(version) = dep.get("version") else { continue };
|
||||
(dep.get("package").and_then(Item::as_str).unwrap_or(name), version)
|
||||
} else {
|
||||
(name, item)
|
||||
};
|
||||
if index_path(package).is_none() {
|
||||
continue;
|
||||
}
|
||||
let Some(requirement) = value.as_str() else { continue };
|
||||
let Some(span) = value.span() else { continue };
|
||||
let Some(raw) = text.get(span.clone()) else { continue };
|
||||
// Spans cover the encoded TOML string. Replace its entire contents,
|
||||
// including escapes, while retaining the original quote delimiters.
|
||||
let delimiter = if raw.starts_with("\"\"\"") || raw.starts_with("'''") { 3 } else { 1 };
|
||||
out.push(ManifestDependency {
|
||||
package: package.to_owned(),
|
||||
requirement: requirement.to_owned(),
|
||||
from: text[..span.start + delimiter].encode_utf16().count() as u32,
|
||||
to: text[..span.end - delimiter].encode_utf16().count() as u32,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update(requirement: &str, versions: &[String]) -> Option<DependencyUpdate> {
|
||||
let req = VersionReq::parse(requirement).ok()?;
|
||||
let prerelease = req.comparators.iter().any(|c| !c.pre.is_empty());
|
||||
let latest =
|
||||
versions.iter().filter_map(|v| Version::parse(v).ok()).filter(|v| prerelease || v.pre.is_empty()).max()?;
|
||||
if req.matches(&latest) {
|
||||
return None;
|
||||
}
|
||||
// An unavailable future version isn't an invitation to downgrade.
|
||||
if req.comparators.iter().any(|c| {
|
||||
(c.op == Op::Greater
|
||||
&& c.patch.is_none()
|
||||
&& (latest.major < c.major
|
||||
|| (latest.major == c.major && c.minor.is_none_or(|minor| latest.minor <= minor))))
|
||||
|| !matches!(c.op, Op::Less | Op::LessEq)
|
||||
&& latest
|
||||
<= Version {
|
||||
major: c.major,
|
||||
minor: c.minor.unwrap_or(0),
|
||||
patch: c.patch.unwrap_or(0),
|
||||
pre: c.pre.clone(),
|
||||
build: Default::default(),
|
||||
}
|
||||
}) {
|
||||
return None;
|
||||
}
|
||||
let trimmed = requirement.trim();
|
||||
let digits = trimmed.trim_start_matches(['^', '~', '=']).trim_start();
|
||||
let simple = digits.split('.').all(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()));
|
||||
let mut replacement = latest.to_string();
|
||||
if simple && latest.pre.is_empty() {
|
||||
let precision = digits.split('.').count();
|
||||
let version = match precision {
|
||||
1 => latest.major.to_string(),
|
||||
2 => format!("{}.{}", latest.major, latest.minor),
|
||||
_ => latest.to_string(),
|
||||
};
|
||||
let candidate = format!("{}{version}", &trimmed[..trimmed.len() - digits.len()]);
|
||||
if VersionReq::parse(&candidate).is_ok_and(|r| r.matches(&latest)) {
|
||||
replacement = candidate;
|
||||
}
|
||||
}
|
||||
Some(DependencyUpdate { latest: latest.to_string(), replacement })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,143 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sparse_paths_and_input_validation() {
|
||||
for (name, path) in
|
||||
[("A", "1/a"), ("ab", "2/ab"), ("AbC", "3/a/abc"), ("serde", "se/rd/serde"), ("my_crate", "my/_c/my_crate")]
|
||||
{
|
||||
assert_eq!(index_path(name).as_deref(), Some(path));
|
||||
}
|
||||
for name in ["", "../serde", "a/b", "sé", "-foo", "a?b", "1abc"] {
|
||||
assert!(index_path(name).is_none(), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_index_filters_yanked_sorts_semver_and_keeps_prereleases_for_completion() {
|
||||
let text = r#"{"vers":"1.9.0","yanked":false}
|
||||
{"vers":"2.0.0-beta.1","yanked":false}
|
||||
{"vers":"9.0.0","yanked":true}
|
||||
{"vers":"1.10.0","yanked":false}
|
||||
{"vers":"1.10.0"}"#;
|
||||
assert_eq!(parse_index(text).unwrap(), ["2.0.0-beta.1", "1.10.0", "1.9.0"]);
|
||||
assert!(parse_index("{broken").is_none());
|
||||
assert!(parse_index(r#"{"vers":"bogus"}"#).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cargo_requirements_updates_and_precision() {
|
||||
for (req, latest, expected) in [
|
||||
("1", "1.9.0", None),
|
||||
("1.0.100", "1.0.228", None),
|
||||
("^1.2", "1.9.0", None),
|
||||
("0.7", "0.7.9", None),
|
||||
("0.0.1", "0.0.2", Some("0.0.2")),
|
||||
("1", "2.3.4", Some("2")),
|
||||
("1.2", "2.3.4", Some("2.3")),
|
||||
("1.2.3", "2.3.0", Some("2.3.0")),
|
||||
("1.2.3", "1.3.0", None),
|
||||
("0.2", "1.3.0", Some("1.3")),
|
||||
("=1.2.3", "1.3.0", Some("=1.3.0")),
|
||||
("~1.2", "1.3.0", Some("~1.3")),
|
||||
("^0.2", "0.3.1", Some("^0.3")),
|
||||
("1.*", "1.9.0", None),
|
||||
("*", "2.3.4", None),
|
||||
(">=1, <2", "2.3.4", Some("2.3.4")),
|
||||
(">=1, <2", "2.0.0", Some("2.0.0")),
|
||||
("<1", "1.0.0", Some("1.0.0")),
|
||||
(">=1, <3", "2.3.4", None),
|
||||
(">=9", "2.3.4", None),
|
||||
(">1", "1.9.0", None),
|
||||
(">1.2", "1.2.9", None),
|
||||
(">1.2.3", "1.2.3", None),
|
||||
("=9.1.2", "2.3.4", None),
|
||||
("bad", "2.3.4", None),
|
||||
("1.0", "2.0.0-beta.1", None),
|
||||
("1.0.0-beta.1", "1.0.0-beta.2", None),
|
||||
("=1.0.0-beta.1", "1.0.0-beta.2", Some("1.0.0-beta.2")),
|
||||
("1.0.0-beta.1", "2.0.0-beta.1", Some("2.0.0-beta.1")),
|
||||
] {
|
||||
let actual = update(req, &[latest.to_owned()]);
|
||||
assert_eq!(actual.as_ref().map(|u| u.replacement.as_str()), expected, "{req} -> {latest}");
|
||||
if let Some(u) = actual {
|
||||
assert!(VersionReq::parse(&u.replacement).unwrap().matches(&Version::parse(latest).unwrap()));
|
||||
}
|
||||
}
|
||||
let versions = vec!["3.0.0-beta.1".into(), "2.0.0".into(), "1.0.0".into()];
|
||||
assert_eq!(update("1", &versions).unwrap().latest, "2.0.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locates_all_cargo_sections_and_only_replaces_version_contents() {
|
||||
let text = r#"# 中文 😀
|
||||
[package]
|
||||
name = "fixture"
|
||||
version = "1.0.0"
|
||||
[dependencies]
|
||||
serde = "1.0.100" # stays
|
||||
rand = '0.7'
|
||||
tokio = { version = "0.2", features = ["full"] }
|
||||
renamed = { package = "real-crate", version = "1.2" }
|
||||
local = { path = "../local", version = "1" }
|
||||
git = { git = "https://example.com/repo", version = "1" }
|
||||
inherited = { workspace = true }
|
||||
other = { registry = "private", version = "1" }
|
||||
[dev-dependencies]
|
||||
check = "1"
|
||||
[build-dependencies.build]
|
||||
version = "1.2.3"
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
native = "0.1"
|
||||
[target.'cfg(windows)'.dev-dependencies]
|
||||
win = { version = "1" }
|
||||
[target.'cfg(unix)'.build-dependencies]
|
||||
build-native = "2"
|
||||
[workspace.dependencies]
|
||||
shared = { version = "1", features = ["std"] }
|
||||
[package.metadata.dependencies]
|
||||
not-a-dependency = "1"
|
||||
"#;
|
||||
let deps = dependencies(text);
|
||||
assert_eq!(
|
||||
deps.iter().map(|d| d.package.as_str()).collect::<Vec<_>>(),
|
||||
["serde", "rand", "tokio", "real-crate", "check", "build", "native", "win", "build-native", "shared"]
|
||||
);
|
||||
let utf16: Vec<_> = text.encode_utf16().collect();
|
||||
for dep in &deps {
|
||||
assert_eq!(String::from_utf16(&utf16[dep.from as usize..dep.to as usize]).unwrap(), dep.requirement);
|
||||
}
|
||||
let tokio = &deps[2];
|
||||
let mut edited = utf16.clone();
|
||||
edited.splice(tokio.from as usize..tokio.to as usize, "1.3".encode_utf16());
|
||||
assert_eq!(String::from_utf16(&edited).unwrap(), text.replace("version = \"0.2\"", "version = \"1.3\""));
|
||||
let rand = &deps[1];
|
||||
let mut edited = utf16;
|
||||
edited.splice(rand.from as usize..rand.to as usize, "0.9".encode_utf16());
|
||||
assert_eq!(String::from_utf16(&edited).unwrap(), text.replace("'0.7'", "'0.9'"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_toml_and_decoy_tables_are_silent() {
|
||||
assert!(dependencies("[dependencies]\na = \"").is_empty());
|
||||
assert!(dependencies("[package]\ndescription = '''\n[dependencies]\na = \"1\"\n'''\n").is_empty());
|
||||
assert!(dependencies("[dependencies]\na = { version = 1 }\nb = { workspace = true, version = \"1\" }\nc = { version = \"1\", registry-index = \"x\" }").is_empty());
|
||||
let deps = dependencies("[dependencies]\na = \"\"\n");
|
||||
assert_eq!(deps.len(), 1, "empty version strings still offer completion");
|
||||
assert_eq!(deps[0].from, deps[0].to);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_encoded_and_multiline_strings_without_damaging_quotes() {
|
||||
for raw in [r#""0.\u0032""#, "\"\"\"\n0.2\"\"\"", "'''0.2'''"] {
|
||||
let text = format!("[dependencies]\ntokio = {{ version = {raw}, features = [\"full\"] }}\n");
|
||||
let dep = dependencies(&text).pop().unwrap();
|
||||
assert_eq!(dep.requirement, "0.2");
|
||||
let mut encoded: Vec<_> = text.encode_utf16().collect();
|
||||
encoded.splice(dep.from as usize..dep.to as usize, "1.10".encode_utf16());
|
||||
let edited = String::from_utf16(&encoded).unwrap();
|
||||
assert!(edited.contains("features = [\"full\"]"));
|
||||
assert_eq!(dependencies(&edited)[0].requirement, "1.10");
|
||||
assert_eq!(edited.matches('"').count(), text.matches('"').count());
|
||||
assert_eq!(edited.matches('\'').count(), text.matches('\'').count());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//! Manifest dependencies and repository versions, independent of editor and transport.
|
||||
mod cache;
|
||||
pub mod cargo;
|
||||
|
||||
pub use cache::VersionCache;
|
||||
use ide_core::{CancellationToken, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
/// A repository adapter; Maven/npm can use the same cache and editor protocol.
|
||||
pub trait DependencyVersionSource: Send + Sync {
|
||||
/// A filesystem-safe, stable repository identifier.
|
||||
fn id(&self) -> &'static str;
|
||||
/// Non-yanked versions in descending semantic order.
|
||||
fn fetch(&self, package: &str, cancel: &CancellationToken) -> IdeResult<Vec<String>>;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DependencyUpdate {
|
||||
pub latest: String,
|
||||
pub replacement: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ManifestDependency {
|
||||
pub package: String,
|
||||
pub requirement: String,
|
||||
/// UTF-16 offsets of the string's contents (quotes excluded).
|
||||
pub from: u32,
|
||||
pub to: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DependencyVersions {
|
||||
pub dependency: ManifestDependency,
|
||||
pub versions: Vec<String>,
|
||||
pub update: Option<DependencyUpdate>,
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! The project model that ties documents, settings and history together.
|
||||
|
||||
pub mod caches;
|
||||
pub mod dependencies;
|
||||
pub mod devcontainer;
|
||||
pub mod documents;
|
||||
pub mod editorconfig;
|
||||
|
||||
@@ -78,3 +78,11 @@ objc2-core-foundation = { version = "0.3", default-features = false, features =
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] }
|
||||
# Used only by the debug font-restriction override; Cargo dependency cfg cannot test debug_assertions.
|
||||
objc2-web-kit = { version = "0.3", default-features = false, features = ["std", "WKWebViewConfiguration", "WKPreferences"] }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Graphics_Gdi",
|
||||
"Win32_UI_Shell",
|
||||
"Win32_UI_WindowsAndMessaging",
|
||||
] }
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Typed IPC adapters for manifest dependency versions.
|
||||
use crate::state::AppState;
|
||||
use ide_core::{DocId, IdeResult, RequestId};
|
||||
use ide_workspace::dependencies::DependencyVersions;
|
||||
use tauri::{State, Window};
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn dependency_versions(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
doc: DocId,
|
||||
offset: Option<u32>,
|
||||
request: RequestId,
|
||||
) -> IdeResult<Vec<DependencyVersions>> {
|
||||
ide_host::ops::dependencies::dependency_versions(&state.host, window.label(), doc, offset, request).await
|
||||
}
|
||||
@@ -16,6 +16,7 @@ pub mod clipboard;
|
||||
pub mod coverage;
|
||||
pub mod db;
|
||||
pub mod debug;
|
||||
pub mod dependencies;
|
||||
pub mod deploy;
|
||||
pub mod doc;
|
||||
pub mod docker;
|
||||
@@ -190,6 +191,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
nav::fs_resolve_reference,
|
||||
nav::path_completions,
|
||||
nav::web_unresolved_references,
|
||||
dependencies::dependency_versions,
|
||||
spell::spell_check,
|
||||
spell::spell_suggest,
|
||||
search::search_start,
|
||||
@@ -303,6 +305,7 @@ pub fn builder() -> tauri_specta::Builder<tauri::Wry> {
|
||||
term::term_default_shell,
|
||||
term::term_available_shells,
|
||||
run::run_configs,
|
||||
run::run_dotnet_resolve,
|
||||
run::run_save_configs,
|
||||
run::run_templates,
|
||||
run::run_save_templates,
|
||||
|
||||
@@ -8,6 +8,17 @@ use ide_run::{OutputChunk, RunConfig, RunInfo};
|
||||
use tauri::ipc::Channel;
|
||||
use tauri::{State, Window};
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn run_dotnet_resolve(
|
||||
window: Window,
|
||||
state: State<'_, AppState>,
|
||||
config: RunConfig,
|
||||
debug: bool,
|
||||
) -> IdeResult<RunConfig> {
|
||||
ide_host::ops::run::run_dotnet_resolve(&state.host, window.label(), config, debug).await
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub async fn run_application_build(
|
||||
|
||||
@@ -19,6 +19,8 @@ mod theme_frame;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod titlebar;
|
||||
mod window_groups;
|
||||
#[cfg(any(windows, test))]
|
||||
mod window_work_area;
|
||||
mod windows;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
@@ -70,6 +72,9 @@ pub fn run() {
|
||||
// Single instance first: a second launch focuses this one and opens its path argument.
|
||||
// Debug builds have a separate identifier per worktree.
|
||||
let app = app.plugin(tauri_plugin_single_instance::init(windows::on_second_instance));
|
||||
// Install before window-state restores maximized geometry during window creation.
|
||||
#[cfg(windows)]
|
||||
let app = app.plugin(window_work_area::init());
|
||||
let app = app.plugin(tauri_plugin_opener::init()).plugin(tauri_plugin_dialog::init());
|
||||
#[cfg(target_os = "linux")]
|
||||
let app = app.plugin(linux_window_state::plugin());
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//! Native maximize bounds for every Windows frameless window, including state restoration.
|
||||
|
||||
#[cfg(windows)]
|
||||
pub use native::init;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct Rect {
|
||||
left: i32,
|
||||
top: i32,
|
||||
right: i32,
|
||||
bottom: i32,
|
||||
}
|
||||
|
||||
/// All coordinates are physical pixels in the selected monitor's coordinate space.
|
||||
/// Auto-hide needs one exposed pixel, but an already reserved edge needs no extra inset.
|
||||
fn bounds(monitor: Rect, work: Rect, auto_hide: [bool; 4], fullscreen: bool) -> Rect {
|
||||
if fullscreen {
|
||||
return monitor;
|
||||
}
|
||||
let [left, top, right, bottom] = auto_hide;
|
||||
Rect {
|
||||
left: work.left + i32::from(left && work.left == monitor.left),
|
||||
top: work.top + i32::from(top && work.top == monitor.top),
|
||||
right: work.right - i32::from(right && work.right == monitor.right),
|
||||
bottom: work.bottom - i32::from(bottom && work.bottom == monitor.bottom),
|
||||
}
|
||||
}
|
||||
|
||||
fn maximize_geometry(monitor: Rect, area: Rect) -> (i32, i32, i32, i32) {
|
||||
(area.left - monitor.left, area.top - monitor.top, area.right - area.left, area.bottom - area.top)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod native {
|
||||
use super::{Rect, bounds, maximize_geometry};
|
||||
use windows_sys::Win32::{
|
||||
Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM},
|
||||
Graphics::Gdi::{
|
||||
GetMonitorInfoW, HMONITOR, MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromRect, MonitorFromWindow,
|
||||
},
|
||||
UI::{
|
||||
Shell::{
|
||||
ABE_BOTTOM, ABE_LEFT, ABE_RIGHT, ABE_TOP, ABM_GETAUTOHIDEBAREX, APPBARDATA, DefSubclassProc,
|
||||
RemoveWindowSubclass, SHAppBarMessage, SetWindowSubclass,
|
||||
},
|
||||
WindowsAndMessaging::{
|
||||
GWL_STYLE, GetWindowLongPtrW, IsZoomed, MINMAXINFO, NCCALCSIZE_PARAMS, WM_GETMINMAXINFO, WM_NCCALCSIZE,
|
||||
WM_NCDESTROY, WS_CAPTION,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const SUBCLASS: usize = 0x410;
|
||||
|
||||
pub fn init() -> tauri::plugin::TauriPlugin<tauri::Wry> {
|
||||
tauri::plugin::Builder::new("window-work-area")
|
||||
.on_window_ready(|window| {
|
||||
if window.is_decorated().unwrap_or(true) {
|
||||
return;
|
||||
}
|
||||
let install = || -> tauri::Result<()> {
|
||||
let hwnd = window.hwnd()?.0 as usize;
|
||||
window.run_on_main_thread(move || {
|
||||
// Subclasses must be installed and removed on the owning GUI thread.
|
||||
if unsafe { SetWindowSubclass(hwnd as HWND, Some(window_proc), SUBCLASS, 0) } == 0 {
|
||||
tracing::warn!(
|
||||
"cannot install window work area handler: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
}
|
||||
})
|
||||
};
|
||||
if let Err(error) = install() {
|
||||
tracing::warn!("cannot install window work area handler: {error}");
|
||||
}
|
||||
})
|
||||
.build()
|
||||
}
|
||||
|
||||
fn rect(rect: RECT) -> Rect {
|
||||
Rect { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom }
|
||||
}
|
||||
|
||||
fn native_rect(rect: Rect) -> RECT {
|
||||
RECT { left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom }
|
||||
}
|
||||
|
||||
unsafe fn monitor_bounds(monitor: HMONITOR, fullscreen: bool) -> Option<(Rect, Rect)> {
|
||||
let mut info = MONITORINFO { cbSize: size_of::<MONITORINFO>() as u32, ..Default::default() };
|
||||
if unsafe { GetMonitorInfoW(monitor, &mut info) } == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut auto_hide = [false; 4];
|
||||
if !fullscreen {
|
||||
for (index, edge) in [ABE_LEFT, ABE_TOP, ABE_RIGHT, ABE_BOTTOM].into_iter().enumerate() {
|
||||
let mut data = APPBARDATA {
|
||||
cbSize: size_of::<APPBARDATA>() as u32,
|
||||
uEdge: edge,
|
||||
rc: info.rcMonitor,
|
||||
..Default::default()
|
||||
};
|
||||
auto_hide[index] = unsafe { SHAppBarMessage(ABM_GETAUTOHIDEBAREX, &mut data) } != 0;
|
||||
}
|
||||
}
|
||||
let monitor = rect(info.rcMonitor);
|
||||
Some((monitor, bounds(monitor, rect(info.rcWork), auto_hide, fullscreen)))
|
||||
}
|
||||
|
||||
unsafe extern "system" fn window_proc(
|
||||
hwnd: HWND,
|
||||
message: u32,
|
||||
wparam: WPARAM,
|
||||
lparam: LPARAM,
|
||||
_id: usize,
|
||||
_data: usize,
|
||||
) -> LRESULT {
|
||||
// Tao keeps WS_CAPTION on frameless windows and removes it for native fullscreen.
|
||||
// Read native styles here: a Tauri state query from its window procedure can deadlock.
|
||||
let fullscreen = unsafe { GetWindowLongPtrW(hwnd, GWL_STYLE) } as u32 & WS_CAPTION == 0;
|
||||
match message {
|
||||
WM_GETMINMAXINFO if !fullscreen => {
|
||||
// Keep Tao's min/max tracking constraints, then set the outer maximize bounds.
|
||||
let result = unsafe { DefSubclassProc(hwnd, message, wparam, lparam) };
|
||||
let monitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) };
|
||||
if let Some((monitor, area)) = unsafe { monitor_bounds(monitor, false) } {
|
||||
let (x, y, width, height) = maximize_geometry(monitor, area);
|
||||
let info = unsafe { &mut *(lparam as *mut MINMAXINFO) };
|
||||
info.ptMaxPosition.x = x;
|
||||
info.ptMaxPosition.y = y;
|
||||
info.ptMaxSize.x = width;
|
||||
info.ptMaxSize.y = height;
|
||||
}
|
||||
result
|
||||
}
|
||||
WM_NCCALCSIZE if wparam != 0 && (fullscreen || unsafe { IsZoomed(hwnd) } != 0) => {
|
||||
let params = unsafe { &mut *(lparam as *mut NCCALCSIZE_PARAMS) };
|
||||
// Use the proposed rectangle: a move/snap/DPI change can target another monitor.
|
||||
let monitor = unsafe { MonitorFromRect(¶ms.rgrc[0], MONITOR_DEFAULTTONEAREST) };
|
||||
if let Some((_, area)) = unsafe { monitor_bounds(monitor, fullscreen) } {
|
||||
// Replace Tao's client-only clamp and global auto-hide query. Fullscreen
|
||||
// must retain the entire display, even when entered from a maximized window.
|
||||
params.rgrc[0] = native_rect(area);
|
||||
0
|
||||
} else {
|
||||
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
|
||||
}
|
||||
}
|
||||
WM_NCDESTROY => {
|
||||
unsafe { RemoveWindowSubclass(hwnd, Some(window_proc), SUBCLASS) };
|
||||
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
|
||||
}
|
||||
_ => unsafe { DefSubclassProc(hwnd, message, wparam, lparam) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn r(left: i32, top: i32, right: i32, bottom: i32) -> Rect {
|
||||
Rect { left, top, right, bottom }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn taskbars_on_every_edge_and_secondary_displays() {
|
||||
for (monitor, work, expected) in [
|
||||
// Reported case: maximized window must leave the bottom taskbar visible.
|
||||
(r(0, 0, 1920, 1080), r(0, 0, 1920, 1040), (0, 0, 1920, 1040)),
|
||||
(r(0, 0, 1920, 1080), r(48, 0, 1920, 1080), (48, 0, 1872, 1080)),
|
||||
(r(0, 0, 1920, 1080), r(0, 40, 1920, 1080), (0, 40, 1920, 1040)),
|
||||
(r(0, 0, 1920, 1080), r(0, 0, 1872, 1080), (0, 0, 1872, 1080)),
|
||||
// Negative origin, top taskbar, 150% display beside a 100% display.
|
||||
(r(-2560, -1440, 0, 0), r(-2560, -1380, 0, 0), (0, 60, 2560, 1380)),
|
||||
// 250% display: physical bounds must not be scaled with the previous monitor's DPI.
|
||||
(r(1920, 0, 5760, 2160), r(1920, 0, 5760, 2060), (0, 0, 3840, 2060)),
|
||||
] {
|
||||
let area = bounds(monitor, work, [false; 4], false);
|
||||
assert_eq!(area, work);
|
||||
assert_eq!(maximize_geometry(monitor, area), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_hide_leaves_a_physical_pixel_only_on_its_own_monitor_edge() {
|
||||
let monitor = r(-1920, 0, 0, 1080);
|
||||
for (edges, expected) in [
|
||||
([true, false, false, false], r(-1919, 0, 0, 1080)),
|
||||
([false, true, false, false], r(-1920, 1, 0, 1080)),
|
||||
([false, false, true, false], r(-1920, 0, -1, 1080)),
|
||||
([false, false, false, true], r(-1920, 0, 0, 1079)),
|
||||
([false; 4], monitor),
|
||||
([true; 4], r(-1919, 1, -1, 1079)),
|
||||
] {
|
||||
assert_eq!(bounds(monitor, monitor, edges, false), expected);
|
||||
}
|
||||
let reserved = r(-1920, 0, 0, 1040);
|
||||
assert_eq!(bounds(monitor, reserved, [false, false, false, true], false), reserved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fullscreen_covers_taskbars_including_when_entered_from_maximized() {
|
||||
let monitor = r(1920, -100, 5760, 2060);
|
||||
let work = r(1980, -100, 5760, 1960);
|
||||
assert_eq!(bounds(monitor, work, [true; 4], true), monitor);
|
||||
assert_eq!(bounds(monitor, work, [false; 4], false), work);
|
||||
}
|
||||
}
|
||||
@@ -841,9 +841,18 @@ fn fit_settings_window(window: &WebviewWindow, parent: &WebviewWindow) -> tauri:
|
||||
/// scale and its position is given in physical pixels.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
pub(super) fn place_settings_window(window: &WebviewWindow, parent: &WebviewWindow) -> tauri::Result<()> {
|
||||
// Placement setters leave maximized mode. Fit the restored frame, then reapply the saved state.
|
||||
// A restored fullscreen window already covers its display and must not be fitted to the work area.
|
||||
if window.is_fullscreen()? {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(monitor) = parent.current_monitor()?.or(parent.primary_monitor()?) else {
|
||||
return Ok(());
|
||||
};
|
||||
let maximized = window.is_maximized()?;
|
||||
if maximized {
|
||||
window.unmaximize()?;
|
||||
}
|
||||
let scale = monitor.scale_factor();
|
||||
let area = monitor.work_area();
|
||||
let origin = area.position.to_logical::<f64>(scale);
|
||||
@@ -872,6 +881,9 @@ pub(super) fn place_settings_window(window: &WebviewWindow, parent: &WebviewWind
|
||||
)))?;
|
||||
window.set_size(tauri::LogicalSize::new(width, height))?;
|
||||
}
|
||||
if maximized {
|
||||
window.maximize()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -327,6 +327,7 @@ export const commands = {
|
||||
pathCompletions: (from: IpcPath, prefix: string) => typedError<PathCompletion[], IdeError>(__TAURI_INVOKE("path_completions", { from, prefix })),
|
||||
/** Paths in an HTML document or stylesheet that name no existing file. */
|
||||
webUnresolvedReferences: (doc: DocId) => typedError<FileReference[], IdeError>(__TAURI_INVOKE("web_unresolved_references", { doc })),
|
||||
dependencyVersions: (doc: DocId, offset: number | null, request: RequestId) => typedError<DependencyVersions[], IdeError>(__TAURI_INVOKE("dependency_versions", { doc, offset, request })),
|
||||
/**
|
||||
* Misspelt words in the comments, string literals and declared names of
|
||||
* `doc` that `scope` includes (all of its text for prose). Cancel with
|
||||
@@ -564,6 +565,7 @@ export const commands = {
|
||||
termAvailableShells: () => __TAURI_INVOKE<string[]>("term_available_shells"),
|
||||
/** Detected configs followed by user-defined ones (user ids win on conflict). */
|
||||
runConfigs: () => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_configs")),
|
||||
runDotnetResolve: (config: RunConfig_Deserialize, debug: boolean) => typedError<RunConfig_Serialize, IdeError>(__TAURI_INVOKE("run_dotnet_resolve", { config, debug })),
|
||||
runSaveConfigs: (configs: RunConfig_Deserialize[], removedDetectedIds: string[] | null) => typedError<null, IdeError>(__TAURI_INVOKE("run_save_configs", { configs, removedDetectedIds })),
|
||||
/** Configuration templates: per-type defaults applied to new configurations. */
|
||||
runTemplates: () => typedError<RunConfig_Serialize[], IdeError>(__TAURI_INVOKE("run_templates")),
|
||||
@@ -2468,6 +2470,17 @@ export type DeletedBranch = {
|
||||
unmerged: boolean,
|
||||
};
|
||||
|
||||
export type DependencyUpdate = {
|
||||
latest: string,
|
||||
replacement: string,
|
||||
};
|
||||
|
||||
export type DependencyVersions = {
|
||||
dependency: ManifestDependency,
|
||||
versions: string[],
|
||||
update: DependencyUpdate | null,
|
||||
};
|
||||
|
||||
/** Where a local file is deployed. */
|
||||
export type DeployedPath = {
|
||||
server: string,
|
||||
@@ -4289,6 +4302,14 @@ export type MainToolbarSettings = {
|
||||
hidden?: string[],
|
||||
};
|
||||
|
||||
export type ManifestDependency = {
|
||||
package: string,
|
||||
requirement: string,
|
||||
/** UTF-16 offsets of the string's contents (quotes excluded). */
|
||||
from: number,
|
||||
to: number,
|
||||
};
|
||||
|
||||
export type Markup = {
|
||||
/** `markdown` or `plaintext`. */
|
||||
kind: string,
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
Annotation,
|
||||
Compartment,
|
||||
Facet,
|
||||
StateEffect,
|
||||
type EditorState,
|
||||
type Extension,
|
||||
type RangeSet,
|
||||
@@ -332,14 +333,25 @@ export function contributedAt<T>(state: EditorState, key: string, pos: number):
|
||||
return state.languageDataAt<T>(key, pos)[0];
|
||||
}
|
||||
|
||||
/** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵) before the language server's. */
|
||||
/** A context action a feature offers at the caret, listed by Show Context Actions (⌥↵). */
|
||||
export interface ContributedIntention {
|
||||
id: string;
|
||||
label: string;
|
||||
icon?: string;
|
||||
quickFix?: boolean;
|
||||
run: () => void | Promise<void>;
|
||||
}
|
||||
|
||||
/** A background provider has new context actions for the current document. */
|
||||
export const intentionsChanged = StateEffect.define<null>();
|
||||
|
||||
/** Local fixes of a diagnostic range (hover link and Apply Quick Fix). */
|
||||
export const quickFixProviders = Facet.define<(view: EditorView, from: number, to: number) => ContributedIntention[]>();
|
||||
|
||||
export function contributedQuickFixes(view: EditorView, from: number, to: number): ContributedIntention[] {
|
||||
return view.state.facet(quickFixProviders).flatMap((provider) => provider(view, from, to));
|
||||
}
|
||||
|
||||
/** Providers of `ContributedIntention`s for the caret of `view` (cheap and synchronous: also drives the light bulb). */
|
||||
export const intentionProviders = Facet.define<(view: EditorView) => ContributedIntention[]>();
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { Diagnostic, Severity } from "@/bindings";
|
||||
import { commands, ideEventsReady, isTauri, onIdeEvent } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { publishLocalDiagnostics } from "@/platform/localDiagnostics";
|
||||
import { scrollbarMarks, type ScrollbarMark } from "@/editor/api";
|
||||
import { intentionsChanged, scrollbarMarks, type ScrollbarMark } from "@/editor/api";
|
||||
import { rangeToOffsets } from "./positions";
|
||||
import { lspDoc } from "./lsp";
|
||||
import { showHint } from "./hint";
|
||||
@@ -199,7 +199,10 @@ const diagnosticsSync = ViewPlugin.fromClass(
|
||||
if (!path || !this.view.dom.isConnected) return;
|
||||
const lint = toLintDiagnostics(this.view.state.doc, diagnosticsFor(path));
|
||||
const tr = setDiagnostics(this.view.state, lint);
|
||||
this.view.dispatch({ ...tr, effects: [...[tr.effects ?? []].flat(), setMarks.of(diagnosticMarks(lint))] });
|
||||
this.view.dispatch({
|
||||
...tr,
|
||||
effects: [...[tr.effects ?? []].flat(), setMarks.of(diagnosticMarks(lint)), intentionsChanged.of(null)],
|
||||
});
|
||||
});
|
||||
}
|
||||
destroy() {
|
||||
|
||||
@@ -98,7 +98,7 @@ function renderDiagnostics(view: EditorView, diags: PlacedDiagnostic[]): HTMLEle
|
||||
fix.className = "cm-lsp-link-button";
|
||||
const keys = shortcutLabel("code.showIntentions");
|
||||
fix.textContent = keys ? `More actions… ${keys}` : "More actions…";
|
||||
if (d.severity === "error" || d.severity === "warning") offerQuickFix(view, meta, fix, from, to);
|
||||
if (d.severity !== "hint") offerQuickFix(view, meta, fix, from, to);
|
||||
fix.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
fix.addEventListener("click", () => {
|
||||
view.dispatch({ selection: EditorSelection.cursor(from) });
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { setDiagnostics } from "@codemirror/lint";
|
||||
import type { CodeAction } from "@/bindings";
|
||||
|
||||
const resolved: CodeAction = {
|
||||
@@ -35,6 +36,7 @@ const {
|
||||
intentionPreview,
|
||||
lightsBulb,
|
||||
listedCodeActions,
|
||||
listedIntentions,
|
||||
withInspectionControls,
|
||||
} = await import("./intentions");
|
||||
const { setFileDiagnostics } = await import("./diagnostics");
|
||||
@@ -90,6 +92,27 @@ describe("inspection controls in ⌥↵ (issue #42)", () => {
|
||||
setFileDiagnostics("/p/two.py", "ruff", []);
|
||||
expect(withInspectionControls(view, [])).toEqual([]);
|
||||
});
|
||||
|
||||
it.each(["info", "warning", "error"] as const)(
|
||||
"uses the effective %s severity for local and LSP fixes",
|
||||
(severity) => {
|
||||
const path = `/p/severity-${severity}.py`;
|
||||
setFileDiagnostics(path, "ruff", [{ ...unused, severity }]);
|
||||
const view = editorAt(path);
|
||||
view.dispatch(setDiagnostics(view.state, [{ from: 7, to: 9, severity, message: unused.message }]));
|
||||
const items = listedIntentions(view, [
|
||||
{ id: "refactor", label: "Extract method", icon: "bulb", run: vi.fn() },
|
||||
{ id: "local", label: "Local fix", quickFix: true, run: vi.fn() },
|
||||
{ id: "lsp", label: "LSP fix", quickFix: true, emphasis: true, run: vi.fn() },
|
||||
]);
|
||||
expect(items.map((i) => i.id)).toEqual(["lsp", "local", "refactor"]);
|
||||
expect(items.slice(0, 2).map((i) => i.icon)).toEqual(Array(2).fill(severity === "error" ? "bulb-fix" : "bulb"));
|
||||
const controls = withInspectionControls(view, items);
|
||||
expect(controls.slice(0, 2).every((i) => i.submenu?.length === 2)).toBe(true);
|
||||
expect(controls[2]!.submenu).toBeUndefined();
|
||||
setFileDiagnostics(path, "ruff", []);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("intention preview", () => {
|
||||
|
||||
@@ -9,7 +9,13 @@ import { forEachDiagnostic } from "@codemirror/lint";
|
||||
import { indentUnit } from "@codemirror/language";
|
||||
import { diff } from "@codemirror/merge";
|
||||
import { commands, isCancelled, type CodeAction } from "@/platform/ipc";
|
||||
import { contributedIntentions, intentionProviders, whenSynced } from "@/editor/api";
|
||||
import {
|
||||
contributedIntentions,
|
||||
contributedQuickFixes,
|
||||
intentionProviders,
|
||||
intentionsChanged,
|
||||
whenSynced,
|
||||
} from "@/editor/api";
|
||||
import { shortcutLabel } from "@/platform/keymap";
|
||||
import { debounce, docOf, isUnavailable, lspRequest, reportLspError } from "./lsp";
|
||||
import { offsetsToRange } from "./positions";
|
||||
@@ -32,6 +38,27 @@ const codeActionBackoff = featureBackoff();
|
||||
|
||||
const isQuickFix = (a: CodeAction) => !!a.kind && (a.kind === "quickfix" || a.kind.startsWith("quickfix."));
|
||||
|
||||
/** The red bulb is reserved for errors; other inspections use the ordinary bulb. */
|
||||
export function quickFixIcon(view: EditorView): "bulb" | "bulb-fix" {
|
||||
const sel = view.state.selection.main;
|
||||
const line = view.state.doc.lineAt(sel.head);
|
||||
let error = false;
|
||||
forEachDiagnostic(view.state, (d, from, to) => {
|
||||
if (d.severity === "error" && from <= line.to && to >= line.from) error = true;
|
||||
});
|
||||
return error ? "bulb-fix" : "bulb";
|
||||
}
|
||||
|
||||
const isFixItem = (item: ListPopupItem) => item.quickFix ?? item.icon === "bulb-fix";
|
||||
|
||||
/** Local and language-server fixes share icons and the same stable ordering. */
|
||||
export function listedIntentions(view: EditorView, items: ListPopupItem[]): ListPopupItem[] {
|
||||
const rank = (item: ListPopupItem) => (item.disabled ? 4 : 0) + (isFixItem(item) ? 0 : 2) + (item.emphasis ? 0 : 1);
|
||||
return items
|
||||
.map((item) => (isFixItem(item) ? { ...item, quickFix: true, icon: quickFixIcon(view) } : item))
|
||||
.sort((a, b) => rank(a) - rank(b));
|
||||
}
|
||||
|
||||
/** IDEA ordering: quick fixes first, preferred before others, disabled last; stable otherwise. */
|
||||
export function sortCodeActions(actions: readonly CodeAction[]): CodeAction[] {
|
||||
const rank = (a: CodeAction) => (a.disabledReason ? 4 : 0) + (isQuickFix(a) ? 0 : 2) + (a.isPreferred ? 0 : 1);
|
||||
@@ -104,15 +131,23 @@ async function fetchIntentions(view: EditorView): Promise<CodeAction[]> {
|
||||
return actions;
|
||||
}
|
||||
|
||||
/** Enabled quick fixes of the problem at `from..to`, preferred first. */
|
||||
export async function quickFixesAt(view: EditorView, from: number, to: number): Promise<CodeAction[]> {
|
||||
export type EditorQuickFix = CodeAction | { title: string; run: () => void | Promise<void> };
|
||||
|
||||
/** Enabled quick fixes of the problem at `from..to`, including local inspections. */
|
||||
export async function quickFixesAt(view: EditorView, from: number, to: number): Promise<EditorQuickFix[]> {
|
||||
const local = contributedQuickFixes(view, from, to).map((fix) => ({ title: fix.label, run: fix.run }));
|
||||
const doc = docOf(view);
|
||||
if (!doc) return [];
|
||||
await whenSynced(view);
|
||||
const actions = await lspRequest(() =>
|
||||
commands.lspCodeActions(doc.doc, offsetsToRange(view.state.doc, from, to), ["quickfix"]),
|
||||
);
|
||||
return sortCodeActions(actions.filter((a) => isQuickFix(a) && !a.disabledReason));
|
||||
if (!doc) return local;
|
||||
try {
|
||||
await whenSynced(view);
|
||||
const actions = await lspRequest(() =>
|
||||
commands.lspCodeActions(doc.doc, offsetsToRange(view.state.doc, from, to), ["quickfix"]),
|
||||
);
|
||||
return [...local, ...sortCodeActions(actions.filter((a) => isQuickFix(a) && !a.disabledReason))];
|
||||
} catch (e) {
|
||||
if (local.length) return local;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -144,7 +179,8 @@ export async function applyQuickFix(view: EditorView) {
|
||||
showHint(view, "No quick fixes available");
|
||||
}
|
||||
|
||||
export async function applyCodeAction(view: EditorView, action: CodeAction) {
|
||||
export async function applyCodeAction(view: EditorView, action: EditorQuickFix) {
|
||||
if ("run" in action) return action.run();
|
||||
const doc = docOf(view);
|
||||
if (!doc) return;
|
||||
if (action.disabledReason) {
|
||||
@@ -276,9 +312,10 @@ function actionItems(
|
||||
resolved?: Map<CodeAction, Promise<CodeAction>>,
|
||||
): ListPopupItem[] {
|
||||
return listedCodeActions(actions).map((a, i) => ({
|
||||
id: `${i}`,
|
||||
id: `lsp:${i}`,
|
||||
label: a.title,
|
||||
icon: isQuickFix(a) ? "bulb-fix" : "bulb",
|
||||
icon: isQuickFix(a) ? quickFixIcon(view) : "bulb",
|
||||
quickFix: isQuickFix(a),
|
||||
emphasis: a.isPreferred,
|
||||
disabled: a.disabledReason,
|
||||
// The edit the preview already resolved is applied as is.
|
||||
@@ -344,7 +381,7 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[])
|
||||
(i) => i.id !== SPELLING_INSPECTION,
|
||||
);
|
||||
if (!inspections.length) return items;
|
||||
const fixes = items.filter((i) => i.icon === "bulb-fix" && !i.submenu);
|
||||
const fixes = items.filter((i) => isFixItem(i) && !i.submenu);
|
||||
if (inspections.length === 1 && fixes.length) {
|
||||
const submenu = intentionControls(inspections[0]!);
|
||||
return items.map((i) => (fixes.includes(i) ? { ...i, submenu } : i));
|
||||
@@ -364,7 +401,7 @@ export function withInspectionControls(view: EditorView, items: ListPopupItem[])
|
||||
/** ⌥↵ */
|
||||
export async function showIntentions(view: EditorView) {
|
||||
try {
|
||||
// Typo fixes and feature-contributed actions come first and need no language server.
|
||||
// Local inspections need no language server.
|
||||
const local: ListPopupItem[] = [...spellingIntentions(view), ...contributedIntentions(view)];
|
||||
let actions: CodeAction[] = [];
|
||||
let failure: { error: unknown } | null = null;
|
||||
@@ -376,7 +413,9 @@ export async function showIntentions(view: EditorView) {
|
||||
}
|
||||
const sorted = listedCodeActions(actions);
|
||||
const resolved = new Map<CodeAction, Promise<CodeAction>>();
|
||||
const items = withInspectionControls(view, [...local, ...actionItems(view, sorted, resolved)]);
|
||||
const serverItems = actionItems(view, sorted, resolved);
|
||||
const previews = new Map(serverItems.map((item, i) => [item.id, sorted[i]!]));
|
||||
const items = withInspectionControls(view, listedIntentions(view, [...local, ...serverItems]));
|
||||
if (!items.length) {
|
||||
if (failure) throw failure.error;
|
||||
showHint(view, "No intentions available");
|
||||
@@ -388,7 +427,7 @@ export async function showIntentions(view: EditorView) {
|
||||
title: "Intentions",
|
||||
items,
|
||||
preview: (item, signal) => {
|
||||
const action = sorted[items.indexOf(item) - local.length];
|
||||
const action = previews.get(item.id);
|
||||
return action ? intentionPreview(view, action, resolved, signal) : Promise.resolve(null);
|
||||
},
|
||||
});
|
||||
@@ -500,7 +539,13 @@ const bulbPlugin = ViewPlugin.fromClass(
|
||||
this.lookup();
|
||||
}
|
||||
update(u: ViewUpdate) {
|
||||
if (u.docChanged || u.selectionSet || (u.focusChanged && u.view.hasFocus)) this.lookup();
|
||||
if (
|
||||
u.docChanged ||
|
||||
u.selectionSet ||
|
||||
(u.focusChanged && u.view.hasFocus) ||
|
||||
u.transactions.some((tr) => tr.effects.some((e) => e.is(intentionsChanged)))
|
||||
)
|
||||
this.lookup();
|
||||
else if (u.focusChanged) {
|
||||
this.lookup.cancel();
|
||||
// A blur dispatched from inside the update is not allowed.
|
||||
@@ -516,16 +561,16 @@ const bulbPlugin = ViewPlugin.fromClass(
|
||||
if (!doc || doc.readOnly || !this.view.dom.isConnected || !this.view.hasFocus) return;
|
||||
const state = this.view.state;
|
||||
const typoFix = spellingIntentions(this.view).length > 0;
|
||||
const local = typoFix || contributedIntentions(this.view).length > 0;
|
||||
const selection = state.selection.main;
|
||||
const ownFix = contributedQuickFixes(this.view, selection.from, selection.to).length > 0;
|
||||
const local = typoFix || ownFix || contributedIntentions(this.view).length > 0;
|
||||
const backoff = codeActionBackoff.active(doc.doc);
|
||||
if (backoff && !local) return;
|
||||
let actions: CodeAction[] = [];
|
||||
if (!backoff) {
|
||||
try {
|
||||
actions = await fetchIntentions(this.view);
|
||||
} catch (e) {
|
||||
if (isUnavailable(e)) codeActionBackoff.mark(doc.doc);
|
||||
if (!local) return;
|
||||
}
|
||||
}
|
||||
if (this.view.state.doc !== state.doc || !this.view.state.selection.eq(state.selection) || !this.view.hasFocus)
|
||||
@@ -533,7 +578,14 @@ const bulbPlugin = ViewPlugin.fromClass(
|
||||
const line = state.doc.lineAt(state.selection.main.head).number;
|
||||
const any = actions.some(lightsBulb) || local;
|
||||
this.view.dispatch({
|
||||
effects: setBulb.of(any ? { line, quickFix: typoFix || actions.some(isQuickFix) } : null),
|
||||
effects: setBulb.of(
|
||||
any
|
||||
? {
|
||||
line,
|
||||
quickFix: (typoFix || ownFix || actions.some(isQuickFix)) && quickFixIcon(this.view) === "bulb-fix",
|
||||
}
|
||||
: null,
|
||||
),
|
||||
});
|
||||
}
|
||||
destroy() {
|
||||
|
||||
@@ -18,6 +18,8 @@ export interface ListPopupItem {
|
||||
/** Second line / muted text after the label (code preview). */
|
||||
preview?: string;
|
||||
icon?: string;
|
||||
/** Inspection fix, independent of the icon chosen for its severity. */
|
||||
quickFix?: boolean;
|
||||
/** Symbol badge kind (`ui/icons` `SymbolBadge`) shown instead of an icon. */
|
||||
symbol?: string;
|
||||
emphasis?: boolean;
|
||||
|
||||
@@ -321,3 +321,23 @@ describe("Go build configuration fields", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("netcoredbg launches the evaluated DLL with resolved profile arguments, env and cwd", () => {
|
||||
const c = rc({
|
||||
kind: "dotnet",
|
||||
command: "dotnet",
|
||||
debugAdapter: "netcoredbg",
|
||||
cwd: "/repo/work",
|
||||
env: { ASPNETCORE_URLS: "http://localhost:5165", DEMO: "override" },
|
||||
params: { targetPath: "/repo/custom/Renamed.dll", programArgs: "--name 'hello world'", profileArgs: "--profile" },
|
||||
});
|
||||
expect(launchConfigFor(c, "/repo")).toMatchObject({
|
||||
adapter: "netcoredbg",
|
||||
program: "/repo/custom/Renamed.dll",
|
||||
args: ["--name", "hello world"],
|
||||
cwd: "/repo/work",
|
||||
env: c.env,
|
||||
});
|
||||
expect(launchConfigFor({ ...c, params: { ...c.params, programArgs: "" } }, "/repo")?.args).toEqual(["--profile"]);
|
||||
expect(launchConfigFor({ ...c, params: {} }, "/repo")).toBeNull();
|
||||
});
|
||||
@@ -21,6 +21,9 @@ describe("missing debug adapters", () => {
|
||||
expect(
|
||||
missingAdapter("kotlin-debug-adapter", unavailable("debug adapter `kotlin-debug-adapter` not found (x)"))?.tool,
|
||||
).toBe("kotlin-debug-adapter");
|
||||
expect(missingAdapter("netcoredbg", unavailable("debug adapter `netcoredbg` not found (x)"))?.tool).toBe(
|
||||
"netcoredbg",
|
||||
);
|
||||
expect(missingAdapter("delve", unavailable("debug adapter `delve` not found (x)"))?.tool).toBe("delve");
|
||||
});
|
||||
|
||||
|
||||
@@ -297,7 +297,9 @@ async function startConfig(arg: unknown) {
|
||||
await startJavaConfig(config, root, origin ?? config);
|
||||
return;
|
||||
}
|
||||
const launch = launchConfigFor(config, root);
|
||||
const dotnet = config.kind === "dotnet" && config.debugAdapter === "netcoredbg";
|
||||
const prepared = dotnet ? await call(commands.runDotnetResolve(config, true)) : config;
|
||||
const launch = launchConfigFor(prepared, root);
|
||||
if (!launch) {
|
||||
notifications().notify({
|
||||
group: "run",
|
||||
|
||||
@@ -313,6 +313,15 @@ export function launchConfigFor(rc: RunConfig, root: string): LaunchConfig | nul
|
||||
if (adapter === "js-debug") return jsDebugLaunch(rc, cwd);
|
||||
if (adapter === "delve") return delveLaunch(rc, cwd, root);
|
||||
if (adapter === "godot") return godotLaunch(rc, cwd);
|
||||
if (adapter === "netcoredbg" && rc.kind === "dotnet") {
|
||||
if (!rc.params?.targetPath) return null;
|
||||
return {
|
||||
...base(rc, adapter, cwd),
|
||||
program: rc.params.targetPath,
|
||||
args: parseArgs(rc.params.programArgs?.trim() ? rc.params.programArgs : rc.params.profileArgs || ""),
|
||||
extraJson: JSON.stringify({ justMyCode: workflowSettings().debugger.skipLibraryCode }),
|
||||
};
|
||||
}
|
||||
// Adapters without a template (hidden in Edit Configurations): generic arguments.
|
||||
return {
|
||||
...base(rc, adapter, cwd),
|
||||
|
||||
@@ -7,6 +7,7 @@ import { IpcError } from "@/platform/ipc";
|
||||
/** Adapters the tools installer can provide (adapter id → tool name). */
|
||||
const INSTALLABLE: Record<string, { tool: string; title: string }> = {
|
||||
"kotlin-debug-adapter": { tool: "kotlin-debug-adapter", title: "The Kotlin debugger is not installed" },
|
||||
netcoredbg: { tool: "netcoredbg", title: "netcoredbg is not installed" },
|
||||
debugpy: { tool: "debugpy", title: "debugpy is not installed" },
|
||||
"js-debug": { tool: "js-debug", title: "The JavaScript debugger (vscode-js-debug) is not installed" },
|
||||
delve: { tool: "delve", title: "Delve is not installed" },
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { CompletionContext } from "@codemirror/autocomplete";
|
||||
import type { DependencyVersions } from "@/bindings";
|
||||
|
||||
const dependencyVersions = vi.fn();
|
||||
const cancelRequest = vi.fn(async () => {});
|
||||
const lspCodeActions = vi.fn(async () => ({ status: "error", error: { kind: "unavailable", message: "No server" } }));
|
||||
vi.mock("@/platform/ipc", async (orig) => {
|
||||
const actual = await orig<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
isTauri: () => true,
|
||||
commands: { ...actual.commands, dependencyVersions, cancelRequest, lspCodeActions },
|
||||
};
|
||||
});
|
||||
const { activate, versionCompletions } = await import("./index");
|
||||
const { editorContributions, contributedIntentions } = await import("@/editor/api");
|
||||
const { diagnosticsFor } = await import("@/editor/lsp/diagnostics");
|
||||
const { lspDoc } = await import("@/editor/lsp/lsp");
|
||||
const { quickFixesAt, applyCodeAction, showIntentions } = await import("@/editor/lsp/intentions");
|
||||
const { useLspPopup, closePopup } = await import("@/editor/lsp/popupStore");
|
||||
const { useProject } = await import("@/platform/project");
|
||||
const { DEPENDENCY_INSPECTION } = await import("@/platform/inspections");
|
||||
const text = '# 中文 😀\n[dependencies]\ntokio = { version = "0.2", features = ["full"] }\n';
|
||||
const from = text.indexOf('"0.2"') + 1;
|
||||
const item: DependencyVersions = {
|
||||
dependency: { package: "tokio", requirement: "0.2", from, to: from + 3 },
|
||||
versions: ["2.0.0-beta.1", "1.10.0", "1.9.0", "0.2.1"],
|
||||
update: { latest: "1.10.0", replacement: "1.10" },
|
||||
};
|
||||
let deactivate: () => void;
|
||||
const views: EditorView[] = [];
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
dependencyVersions.mockResolvedValue({ status: "ok", data: [item] });
|
||||
useProject.setState({ project: { root: "/p" } as never, settings: {} as never });
|
||||
deactivate = activate();
|
||||
});
|
||||
afterEach(() => {
|
||||
views.splice(0).forEach((view) => view.destroy());
|
||||
deactivate();
|
||||
closePopup();
|
||||
useProject.setState({ project: null, settings: null });
|
||||
vi.clearAllMocks();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
function editor(path = "/p/Cargo.toml", readOnly = false) {
|
||||
const ctx = { doc: 7, path, language: "toml", uiMode: "TOML", readOnly };
|
||||
const contribution = editorContributions().find((c) => c.id === "dependency-versions")!;
|
||||
const view = new EditorView({
|
||||
parent: document.body,
|
||||
state: EditorState.create({
|
||||
doc: text,
|
||||
selection: { anchor: from },
|
||||
extensions: [lspDoc.of(ctx), contribution.extensions(ctx)],
|
||||
}),
|
||||
});
|
||||
views.push(view);
|
||||
return view;
|
||||
}
|
||||
async function settle() {
|
||||
await vi.advanceTimersByTimeAsync(550);
|
||||
}
|
||||
|
||||
describe("Cargo dependency versions", () => {
|
||||
it("publishes a weak warning and fixes only the version through context actions", async () => {
|
||||
const view = editor();
|
||||
await settle();
|
||||
expect(dependencyVersions).toHaveBeenCalledWith(7, null, expect.any(Number));
|
||||
expect(diagnosticsFor("/p/Cargo.toml")).toMatchObject([
|
||||
{
|
||||
severity: "info",
|
||||
message: "A newer version is available: 1.10.0",
|
||||
range: { start: { line: 2, col: 21 }, end: { line: 2, col: 24 } },
|
||||
},
|
||||
]);
|
||||
const [fix] = contributedIntentions(view);
|
||||
expect(fix?.label).toBe("Update to 1.10");
|
||||
await fix!.run();
|
||||
expect(view.state.doc.toString()).toBe(text.replace('"0.2"', '"1.10"'));
|
||||
expect(diagnosticsFor("/p/Cargo.toml")).toEqual([]);
|
||||
});
|
||||
it("provides direct and hover quick fixes even without a language server", async () => {
|
||||
const view = editor();
|
||||
await settle();
|
||||
const [fix] = await quickFixesAt(view, from, from + 3);
|
||||
expect(fix?.title).toBe("Update to 1.10");
|
||||
await applyCodeAction(view, fix!);
|
||||
expect(view.state.doc.toString()).toContain('version = "1.10", features = ["full"]');
|
||||
});
|
||||
it.each(["0.10", "^0.10", "=0.10.3"])(
|
||||
"shows the exact replacement %s with weak-warning inspection controls",
|
||||
async (replacement) => {
|
||||
dependencyVersions.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: [{ ...item, update: { latest: "0.10.3", replacement } }],
|
||||
});
|
||||
const view = editor();
|
||||
await settle();
|
||||
await showIntentions(view);
|
||||
const popup = useLspPopup.getState().popup;
|
||||
expect(popup?.kind).toBe("list");
|
||||
if (popup?.kind !== "list") throw new Error("Missing intentions");
|
||||
expect(popup.title).toBe("Intentions");
|
||||
expect(popup.items).toHaveLength(1);
|
||||
expect(popup.items[0]).toMatchObject({ label: `Update to ${replacement}`, icon: "bulb", quickFix: true });
|
||||
expect(popup.items[0]!.submenu).toHaveLength(2);
|
||||
await popup.items[0]!.run();
|
||||
expect(view.state.doc.toString()).toBe(text.replace('"0.2"', `"${replacement}"`));
|
||||
},
|
||||
);
|
||||
it("keeps diagnostics when one of two split editors closes", async () => {
|
||||
editor();
|
||||
const split = editor();
|
||||
await settle();
|
||||
split.destroy();
|
||||
views.pop();
|
||||
expect(diagnosticsFor("/p/Cargo.toml")).toHaveLength(1);
|
||||
});
|
||||
it("invalidates fixes immediately after edits and rejects a stale fix callback", async () => {
|
||||
const view = editor();
|
||||
await settle();
|
||||
const [fix] = contributedIntentions(view);
|
||||
view.dispatch({ changes: { from: 0, insert: "# edit\n" } });
|
||||
expect(contributedIntentions(view)).toEqual([]);
|
||||
await fix!.run();
|
||||
expect(view.state.doc.toString()).toBe("# edit\n" + text);
|
||||
});
|
||||
it("discards delayed responses after an edit, project switch or editor close", async () => {
|
||||
let resolve!: (value: unknown) => void;
|
||||
dependencyVersions.mockImplementation(
|
||||
() =>
|
||||
new Promise((r) => {
|
||||
resolve = r;
|
||||
}),
|
||||
);
|
||||
const view = editor();
|
||||
await settle();
|
||||
view.dispatch({ changes: { from: 0, insert: "# edit\n" } });
|
||||
resolve({ status: "ok", data: [item] });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(diagnosticsFor("/p/Cargo.toml")).toEqual([]);
|
||||
await settle();
|
||||
useProject.setState({ project: { root: "/other" } as never });
|
||||
resolve({ status: "ok", data: [item] });
|
||||
await settle();
|
||||
expect(diagnosticsFor("/p/Cargo.toml")).toEqual([]);
|
||||
expect(cancelRequest).toHaveBeenCalled();
|
||||
const other = editor("/other/Cargo.toml");
|
||||
await settle();
|
||||
other.destroy();
|
||||
views.pop();
|
||||
resolve({ status: "ok", data: [item] });
|
||||
await settle();
|
||||
expect(diagnosticsFor("/other/Cargo.toml")).toEqual([]);
|
||||
});
|
||||
it("stays silent offline, with compatible versions and for non-Cargo or readonly files", async () => {
|
||||
dependencyVersions.mockRejectedValue(new Error("offline"));
|
||||
editor();
|
||||
await settle();
|
||||
expect(diagnosticsFor("/p/Cargo.toml")).toEqual([]);
|
||||
dependencyVersions.mockResolvedValue({ status: "ok", data: [{ ...item, update: null }] });
|
||||
editor("/p/sub/Cargo.toml");
|
||||
await settle();
|
||||
expect(diagnosticsFor("/p/sub/Cargo.toml")).toEqual([]);
|
||||
dependencyVersions.mockClear();
|
||||
editor("/p/other.toml");
|
||||
editor("/p/readonly/Cargo.toml", true);
|
||||
await settle();
|
||||
expect(dependencyVersions).not.toHaveBeenCalled();
|
||||
});
|
||||
it("honours the inspection profile and cleans up on close", async () => {
|
||||
const view = editor();
|
||||
await settle();
|
||||
useProject.setState({
|
||||
settings: { inspections: { default: { [DEPENDENCY_INSPECTION]: { enabled: false } } } } as never,
|
||||
});
|
||||
expect(diagnosticsFor("/p/Cargo.toml")).toEqual([]);
|
||||
expect(contributedIntentions(view)).toEqual([]);
|
||||
view.destroy();
|
||||
views.pop();
|
||||
await settle();
|
||||
expect(diagnosticsFor("/p/Cargo.toml")).toEqual([]);
|
||||
});
|
||||
it("completes only at a parsed dependency version, preserving descending source order", async () => {
|
||||
const view = editor();
|
||||
const source = view.state.languageDataAt<(ctx: CompletionContext) => Promise<unknown>>(
|
||||
"openideaCompletion",
|
||||
from,
|
||||
)[0]!;
|
||||
const result = await source(new CompletionContext(view.state, from + 3, true, view));
|
||||
expect(result).toMatchObject({
|
||||
from,
|
||||
to: from + 3,
|
||||
filter: false,
|
||||
options: item.versions.map((label) => ({ label })),
|
||||
});
|
||||
expect(dependencyVersions).toHaveBeenLastCalledWith(7, from + 3, expect.any(Number));
|
||||
dependencyVersions.mockResolvedValue({ status: "ok", data: [] });
|
||||
expect(await source(new CompletionContext(view.state, 0, true, view))).toBeNull();
|
||||
});
|
||||
it("replaces the whole version and retains a simple requirement operator", () => {
|
||||
const state = EditorState.create({ doc: "^1.2" });
|
||||
const context = new CompletionContext(state, 4, true);
|
||||
const result = versionCompletions({ ...item, dependency: { ...item.dependency, from: 0, to: 4 } }, context);
|
||||
expect(result.options[0]).toMatchObject({ label: "2.0.0-beta.1", apply: "^2.0.0-beta.1" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import { EditorState, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { ViewPlugin, type EditorView } from "@codemirror/view";
|
||||
import type { CompletionContext, CompletionResult } from "@codemirror/autocomplete";
|
||||
import {
|
||||
intentionProviders,
|
||||
intentionsChanged,
|
||||
quickFixProviders,
|
||||
registerEditorContribution,
|
||||
whenSynced,
|
||||
type ContributedIntention,
|
||||
type EditorDocContext,
|
||||
} from "@/editor/api";
|
||||
import { setFileDiagnostics } from "@/editor/lsp/diagnostics";
|
||||
import { offsetsToRange } from "@/editor/lsp/positions";
|
||||
import { call, commands, isTauri, nextRequestId, type DependencyVersions, type RequestId } from "@/platform/ipc";
|
||||
import {
|
||||
DEPENDENCY_INSPECTION,
|
||||
DEPENDENCY_PRODUCER,
|
||||
inspectionProfile,
|
||||
subscribeInspectionProfile,
|
||||
} from "@/platform/inspections";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { tx } from "@/platform/i18n";
|
||||
|
||||
const setVersions = StateEffect.define<DependencyVersions[]>();
|
||||
const versionsField = StateField.define<DependencyVersions[]>({
|
||||
create: () => [],
|
||||
update(value, tr) {
|
||||
if (tr.docChanged) return [];
|
||||
for (const effect of tr.effects) if (effect.is(setVersions)) return effect.value;
|
||||
return value;
|
||||
},
|
||||
});
|
||||
|
||||
const viewers = new Map<string, number>();
|
||||
|
||||
const enabled = () => inspectionProfile()[DEPENDENCY_INSPECTION]?.enabled !== false;
|
||||
|
||||
export function dependencyFixes(view: EditorView, from: number, to: number): ContributedIntention[] {
|
||||
if (!enabled() || view.state.readOnly) return [];
|
||||
const text = view.state.doc;
|
||||
return (view.state.field(versionsField, false) ?? []).flatMap(({ dependency, update }) => {
|
||||
if (!update || from > dependency.to || to < dependency.from) return [];
|
||||
const { replacement } = update;
|
||||
return [
|
||||
{
|
||||
id: `dependency.update:${dependency.from}`,
|
||||
label: tx`Update to ${replacement}`,
|
||||
quickFix: true,
|
||||
run: () => {
|
||||
if (view.state.doc !== text) return;
|
||||
view.dispatch({
|
||||
changes: { from: dependency.from, to: dependency.to, insert: replacement },
|
||||
userEvent: "input.dependency",
|
||||
});
|
||||
},
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function versionCompletions(item: DependencyVersions, ctx: CompletionContext): CompletionResult {
|
||||
const { dependency, versions } = item;
|
||||
const typed = ctx.state.sliceDoc(dependency.from, ctx.pos);
|
||||
const prefix = /^[\s^~<>=]*/.exec(typed)?.[0] ?? "";
|
||||
const filter = typed.slice(prefix.length);
|
||||
return {
|
||||
from: dependency.from,
|
||||
to: dependency.to,
|
||||
filter: false,
|
||||
options: versions
|
||||
.filter((v) => ctx.explicit || v.startsWith(filter))
|
||||
.map((version) => ({
|
||||
label: version,
|
||||
type: "constant",
|
||||
detail: dependency.package,
|
||||
apply: prefix + version,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function extension(doc: EditorDocContext): Extension {
|
||||
const plugin = ViewPlugin.define((view) => {
|
||||
if (!isTauri()) return {};
|
||||
viewers.set(doc.path, (viewers.get(doc.path) ?? 0) + 1);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let request: RequestId | null = null;
|
||||
let sequence = 0;
|
||||
let disposed = false;
|
||||
const clear = () => setFileDiagnostics(doc.path, DEPENDENCY_PRODUCER, []);
|
||||
const cancel = () => {
|
||||
sequence++;
|
||||
if (request !== null) void commands.cancelRequest(request);
|
||||
request = null;
|
||||
};
|
||||
const run = async () => {
|
||||
if (disposed || !enabled()) return;
|
||||
const mine = sequence;
|
||||
const text = view.state.doc;
|
||||
const root = useProject.getState().project?.root;
|
||||
const id = nextRequestId();
|
||||
request = id;
|
||||
try {
|
||||
await whenSynced(view);
|
||||
if (mine !== sequence || disposed) return;
|
||||
const items = await call(commands.dependencyVersions(doc.doc, null, id));
|
||||
if (mine !== sequence || disposed || view.state.doc !== text || useProject.getState().project?.root !== root)
|
||||
return;
|
||||
view.dispatch({ effects: [setVersions.of(items), intentionsChanged.of(null)] });
|
||||
setFileDiagnostics(
|
||||
doc.path,
|
||||
DEPENDENCY_PRODUCER,
|
||||
items.flatMap(({ dependency, update }) => {
|
||||
if (!update) return [];
|
||||
const { latest } = update;
|
||||
return [
|
||||
{
|
||||
range: offsetsToRange(text, dependency.from, dependency.to),
|
||||
severity: "info",
|
||||
message: tx`A newer version is available: ${latest}`,
|
||||
source: "Cargo",
|
||||
code: null,
|
||||
},
|
||||
];
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// Offline registries and cancelled checks never interrupt editing.
|
||||
} finally {
|
||||
if (request === id) request = null;
|
||||
}
|
||||
};
|
||||
const schedule = () => {
|
||||
cancel();
|
||||
clear();
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => void run(), 500);
|
||||
};
|
||||
schedule();
|
||||
const offProfile = subscribeInspectionProfile(() => {
|
||||
schedule();
|
||||
view.dispatch({ effects: intentionsChanged.of(null) });
|
||||
});
|
||||
const offProject = useProject.subscribe((state, previous) => {
|
||||
if (state.project?.root !== previous.project?.root) {
|
||||
disposed = true;
|
||||
cancel();
|
||||
clearTimeout(timer);
|
||||
clear();
|
||||
}
|
||||
});
|
||||
return {
|
||||
update: (u) => {
|
||||
if (u.docChanged) schedule();
|
||||
},
|
||||
destroy: () => {
|
||||
disposed = true;
|
||||
cancel();
|
||||
clearTimeout(timer);
|
||||
offProfile();
|
||||
offProject();
|
||||
const remaining = (viewers.get(doc.path) ?? 1) - 1;
|
||||
if (remaining) viewers.set(doc.path, remaining);
|
||||
else {
|
||||
viewers.delete(doc.path);
|
||||
clear();
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
const completion = async (ctx: CompletionContext): Promise<CompletionResult | null> => {
|
||||
if (!isTauri()) return null;
|
||||
const id = nextRequestId();
|
||||
const text = ctx.state.doc;
|
||||
const root = useProject.getState().project?.root;
|
||||
ctx.addEventListener("abort", () => void commands.cancelRequest(id));
|
||||
try {
|
||||
// The completion context is immutable; only use it while its document is current.
|
||||
const view = ctx.view;
|
||||
if (!view) return null;
|
||||
await whenSynced(view);
|
||||
if (ctx.aborted || view.state.doc !== text) return null;
|
||||
const items = await call(commands.dependencyVersions(doc.doc, ctx.pos, id));
|
||||
if (ctx.aborted || view.state.doc !== text || useProject.getState().project?.root !== root) return null;
|
||||
const item = items.find(({ dependency }) => dependency.from <= ctx.pos && ctx.pos <= dependency.to);
|
||||
return item ? versionCompletions(item, ctx) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
return [
|
||||
versionsField,
|
||||
plugin,
|
||||
intentionProviders.of((view) => {
|
||||
const selection = view.state.selection.main;
|
||||
return dependencyFixes(view, selection.from, selection.to);
|
||||
}),
|
||||
quickFixProviders.of(dependencyFixes),
|
||||
EditorState.languageData.of(() => [{ openideaCompletion: completion }]),
|
||||
];
|
||||
}
|
||||
|
||||
export function activate(): () => void {
|
||||
return registerEditorContribution({
|
||||
id: "dependency-versions",
|
||||
extensions: (doc) => (!doc.virtual && !doc.readOnly && /(?:^|\/)Cargo\.toml$/.test(doc.path) ? extension(doc) : []),
|
||||
});
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { activate as editorLsp } from "@/editor/lsp";
|
||||
import { activate as welcome } from "./welcome";
|
||||
import { activate as projectTree } from "./project-tree";
|
||||
import { activate as search } from "./search";
|
||||
import { activate as dependencies } from "./dependencies";
|
||||
import { activate as codeInsight } from "./code-insight";
|
||||
import { activate as vcs, activateSettingsPages as vcsPages } from "./vcs";
|
||||
import { activate as terminal } from "./terminal";
|
||||
@@ -55,6 +56,7 @@ const features: Array<[string, Activate]> = [
|
||||
["project-tree", projectTree],
|
||||
["search", search],
|
||||
["code-insight", codeInsight],
|
||||
["dependencies", dependencies],
|
||||
["vcs", vcs],
|
||||
["terminal", terminal],
|
||||
["run", run],
|
||||
|
||||
@@ -48,11 +48,12 @@ import styles from "./Run.module.css";
|
||||
|
||||
/**
|
||||
* Debug adapters with a real launch template (`debugger/launch.ts`, `debugger/java.ts`),
|
||||
* verified against small programs. Others (netcoredbg, dart, php-debug, …) only got
|
||||
* verified against small programs. Others (dart, php-debug, …) only got
|
||||
* generic launch arguments and are left out until they have one; a configuration that
|
||||
* already names one keeps it.
|
||||
*/
|
||||
const ADAPTERS: ReadonlyArray<{ id: string; label: string }> = [
|
||||
{ id: "netcoredbg", label: "netcoredbg (.NET)" },
|
||||
{ id: "java-debug", label: "java-debug (Java)" },
|
||||
{ id: "kotlin-debug-adapter", label: "kotlin-debug-adapter (Kotlin)" },
|
||||
{ id: "debugpy", label: "debugpy (Python)" },
|
||||
@@ -254,6 +255,9 @@ export function ConfigForm({ config, all, type, errors, template, onChange, modi
|
||||
})),
|
||||
},
|
||||
{ label: TASK_LABELS.build, icon: "build-project", run: () => addTask("build") },
|
||||
...(config.kind === "dotnet"
|
||||
? [{ label: TASK_LABELS.dotnetBuild, icon: "build-project", run: () => addTask("dotnetBuild") }]
|
||||
: []),
|
||||
{
|
||||
label: TASK_LABELS.tool,
|
||||
disabled: !externalTools.length,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
* Before launch tasks (IDEA's "Before launch" list): run in order before a
|
||||
* configuration starts; the first failure aborts the launch.
|
||||
*/
|
||||
import { dotnetBuildConfig } from "./dotnetTypes";
|
||||
import { executeAction, getAction } from "@/platform/actions";
|
||||
import { getContext } from "@/platform/context";
|
||||
import { tx, txTemplate } from "@/platform/i18n";
|
||||
@@ -14,11 +15,12 @@ import { startRun, useRun } from "./store";
|
||||
export const BUILD_ACTION = "build.buildProject";
|
||||
const BUILD_STATUS = "build.lastStatus";
|
||||
|
||||
export type BeforeLaunchKind = "run" | "build" | "tool" | "command" | "toolWindow";
|
||||
export type BeforeLaunchKind = "run" | "build" | "tool" | "command" | "toolWindow" | "dotnetBuild";
|
||||
|
||||
export const TASK_LABELS: Record<BeforeLaunchKind, string> = {
|
||||
run: "Run Another Configuration",
|
||||
build: "Build Project",
|
||||
dotnetBuild: "Build .NET project",
|
||||
tool: "Run External Tool",
|
||||
command: "Run Shell Command",
|
||||
toolWindow: "Activate Tool Window",
|
||||
@@ -32,6 +34,8 @@ export function taskLabel(task: BeforeLaunchTask, configs: readonly RunConfig[]
|
||||
return `Run '${configs.find((c) => c.id === target)?.name ?? target}'`;
|
||||
case "build":
|
||||
return "Build Project";
|
||||
case "dotnetBuild":
|
||||
return "Build .NET project";
|
||||
case "tool":
|
||||
return `External tool '${workflowSettings().externalTools.find((t) => t.id === target)?.name ?? target}'`;
|
||||
case "command":
|
||||
@@ -58,6 +62,8 @@ async function runToEnd(config: RunConfig, chain: readonly string[]): Promise<bo
|
||||
async function runTask(task: BeforeLaunchTask, config: RunConfig, chain: readonly string[]): Promise<string | null> {
|
||||
const target = task.target ?? "";
|
||||
switch (task.kind) {
|
||||
case "dotnetBuild":
|
||||
return (await runToEnd(dotnetBuildConfig(config), chain)) ? null : "Build failed";
|
||||
case "build": {
|
||||
if (!getAction(BUILD_ACTION)) return "Building is not available";
|
||||
if (!(await executeAction(BUILD_ACTION, { activate: false }))) return "A build is already running";
|
||||
|
||||
@@ -67,6 +67,9 @@ export function configIcon(config: Pick<RunConfig, "kind" | "isTest">): string {
|
||||
return "file-gradle";
|
||||
case "maven":
|
||||
return "file-maven";
|
||||
case "dotnet":
|
||||
case "dotnet-test":
|
||||
return "file-csharp";
|
||||
case "go":
|
||||
return "file-go";
|
||||
case "node":
|
||||
@@ -220,7 +223,7 @@ export function validateConfig(config: RunConfig, all: readonly RunConfig[] = []
|
||||
for (const t of config.beforeLaunch ?? []) {
|
||||
if (t.kind === "run" && (t.target === config.id || !all.some((c) => c.id === t.target)))
|
||||
errors.beforeLaunch = "A before launch task runs a missing configuration or this one";
|
||||
else if (t.kind !== "build" && t.kind !== "run" && !(t.target ?? "").trim())
|
||||
else if (t.kind !== "build" && t.kind !== "dotnetBuild" && t.kind !== "run" && !(t.target ?? "").trim())
|
||||
errors.beforeLaunch = "A before launch task is incomplete";
|
||||
}
|
||||
for (const key of Object.keys(config.env)) {
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { beforeEach, afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { commands } from "@/platform/ipc";
|
||||
import type { RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { dotnetBuildConfig, dotnetProjectType, dotnetTestType } from "./dotnetTypes";
|
||||
import { ConfigForm } from "./ConfigForm";
|
||||
import { validateConfig } from "./configs";
|
||||
import { newConfigOfType, registerBuiltinTypes, withParams } from "./types";
|
||||
|
||||
const resolveDotnet = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return { ...real, commands: { ...real.commands, runDotnetResolve: resolveDotnet } };
|
||||
});
|
||||
|
||||
const params = {
|
||||
project: "src/My App/App.csproj",
|
||||
framework: "net10.0",
|
||||
frameworks: "net10.0;net9.0",
|
||||
launchProfile: "local web",
|
||||
programArgs: "--name 'hello world'",
|
||||
profiles: JSON.stringify({
|
||||
"local web": { applicationUrl: "http://localhost:5165", environmentVariables: { DEMO: "profile" } },
|
||||
alternate: {},
|
||||
}),
|
||||
};
|
||||
let dispose: () => void;
|
||||
beforeEach(() => {
|
||||
dispose = registerBuiltinTypes();
|
||||
});
|
||||
afterEach(() => dispose());
|
||||
|
||||
function config(): RunConfig {
|
||||
return withParams({ ...newConfigOfType(dotnetProjectType, []), name: "demo" }, params, dotnetProjectType);
|
||||
}
|
||||
|
||||
describe(".NET configurations", () => {
|
||||
it("generates run/test commands with spaces, framework/profile and separated program arguments", () => {
|
||||
const c = config();
|
||||
expect(c.args).toEqual([
|
||||
"run",
|
||||
"--project",
|
||||
"src/My App/App.csproj",
|
||||
"--framework",
|
||||
"net10.0",
|
||||
"--launch-profile",
|
||||
"local web",
|
||||
"--",
|
||||
"--name",
|
||||
"hello world",
|
||||
]);
|
||||
expect(c.debugAdapter).toBe("netcoredbg");
|
||||
expect(c.beforeLaunch).toEqual([{ kind: "dotnetBuild", target: "" }]);
|
||||
expect(validateConfig(c, [c])).toEqual({});
|
||||
const t = withParams(
|
||||
newConfigOfType(dotnetTestType, []),
|
||||
{ project: params.project, framework: "net9.0", programArgs: '--filter "Category=Unit"' },
|
||||
dotnetTestType,
|
||||
);
|
||||
expect(t.isTest).toBe(true);
|
||||
expect(t.debugAdapter).toBeNull();
|
||||
expect(t.args).toEqual(["test", params.project, "--framework", "net9.0", "--filter", "Category=Unit"]);
|
||||
expect(dotnetProjectType.commandLine({ project: "App.csproj" })?.args).toEqual([
|
||||
"run",
|
||||
"--project",
|
||||
"App.csproj",
|
||||
"--no-launch-profile",
|
||||
]);
|
||||
});
|
||||
|
||||
it("builds edited project/framework from the open root instead of a profile cwd", () => {
|
||||
useProject.setState({ project: { root: "/repo" } as never });
|
||||
const c = withParams(
|
||||
{ ...config(), cwd: "profile/work" },
|
||||
{ ...params, project: "other/App.csproj", framework: "net9.0" },
|
||||
);
|
||||
const build = dotnetBuildConfig(c);
|
||||
expect(build.args).toEqual(["build", "other/App.csproj", "--configuration", "Debug", "--framework", "net9.0"]);
|
||||
expect(build.cwd).toBe("/repo");
|
||||
expect(build.beforeLaunch).toEqual([]);
|
||||
});
|
||||
|
||||
it("edits project, framework, profile, arguments and environment in the shared form", () => {
|
||||
const c = config();
|
||||
const change = vi.fn();
|
||||
render(
|
||||
<ConfigForm config={c} all={[c]} type={dotnetProjectType} errors={{}} modifyRequest={0} onChange={change} />,
|
||||
);
|
||||
expect(screen.getByText("http://localhost:5165")).toBeTruthy();
|
||||
expect(screen.getByText("DEMO=profile")).toBeTruthy();
|
||||
for (const [label, value] of [
|
||||
[".NET project", "other/App.csproj"],
|
||||
["Target framework", "net9.0"],
|
||||
["Launch profile", "alternate"],
|
||||
["Program arguments", "--edited"],
|
||||
] as const) {
|
||||
fireEvent.change(screen.getByLabelText(label), { target: { value } });
|
||||
expect(change).toHaveBeenCalled();
|
||||
}
|
||||
fireEvent.change(screen.getByRole("textbox", { name: "Environment variables" }), {
|
||||
target: { value: "DEMO=override" },
|
||||
});
|
||||
expect(change.mock.lastCall?.[0]).toMatchObject({ env: { DEMO: "override" } });
|
||||
});
|
||||
it("prepares Run from the freshly resolved profile while keeping explicit argument overrides", async () => {
|
||||
const c = config();
|
||||
resolveDotnet.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
...c,
|
||||
cwd: "/repo/work",
|
||||
env: { DEMO: "override" },
|
||||
params: { ...params, project: "/repo/App.csproj", profileArgs: "--from-profile" },
|
||||
},
|
||||
});
|
||||
const prepared = await dotnetProjectType.prepareLaunch!(c);
|
||||
expect(commands.runDotnetResolve).toHaveBeenCalledWith(c, false);
|
||||
expect(prepared).toMatchObject({ cwd: "/repo/work", env: { DEMO: "override" } });
|
||||
expect(prepared.args).toContain("--no-launch-profile");
|
||||
expect(prepared.args.slice(-3)).toEqual(["--", "--name", "hello world"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { call, commands, type RunConfig } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import type { RunConfigTypeContribution } from "@/workbench/contributions";
|
||||
import { parseArgs } from "./configs";
|
||||
|
||||
function profile(p: Readonly<Record<string, string>>): {
|
||||
applicationUrl?: string;
|
||||
environmentVariables?: Record<string, string>;
|
||||
} {
|
||||
try {
|
||||
return JSON.parse(p.profiles || "{}")[p.launchProfile || ""] ?? {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
export function dotnetCommand(p: Readonly<Record<string, string>>, test = false) {
|
||||
return {
|
||||
command: p.executable || "dotnet",
|
||||
args: [
|
||||
...(test ? ["test", p.project || ""] : ["run", "--project", p.project || ""]),
|
||||
...(p.framework ? ["--framework", p.framework] : []),
|
||||
...(!test ? (p.launchProfile ? ["--launch-profile", p.launchProfile] : ["--no-launch-profile"]) : []),
|
||||
...(p.programArgs?.trim() ? ["--", ...parseArgs(p.programArgs)] : []),
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Build the current project/framework, independently of the run's profile working directory. */
|
||||
export function dotnetBuildConfig(config: RunConfig): RunConfig {
|
||||
const p = config.params ?? {};
|
||||
return {
|
||||
...config,
|
||||
id: `dotnet-build:${config.id}`,
|
||||
name: `dotnet build (${p.project || ""})`,
|
||||
kind: "shell",
|
||||
args: ["build", p.project || "", "--configuration", "Debug", ...(p.framework ? ["--framework", p.framework] : [])],
|
||||
cwd: useProject.getState().project?.root ?? null,
|
||||
env: {},
|
||||
params: {},
|
||||
isTest: false,
|
||||
debugAdapter: null,
|
||||
beforeLaunch: [],
|
||||
emulateTerminal: false,
|
||||
stdinFile: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export const dotnetProjectType: RunConfigTypeContribution = {
|
||||
id: "dotnet",
|
||||
label: ".NET Project",
|
||||
icon: "file-csharp",
|
||||
description: "Run a .NET project with a launch profile",
|
||||
debugAdapter: "netcoredbg",
|
||||
fields: [
|
||||
{
|
||||
key: "project",
|
||||
label: ".NET project",
|
||||
mono: true,
|
||||
required: true,
|
||||
suggestions: (configs) => [
|
||||
...new Set(
|
||||
configs.filter((c) => c.kind === "dotnet" || c.kind === "dotnet-test").map((c) => c.params?.project || ""),
|
||||
),
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "framework",
|
||||
label: "Target framework",
|
||||
mono: true,
|
||||
suggestions: (_configs, p) => (p.frameworks || "").split(";").filter(Boolean),
|
||||
},
|
||||
{
|
||||
key: "launchProfile",
|
||||
label: "Launch profile",
|
||||
mono: true,
|
||||
hint: "Empty disables launch profiles",
|
||||
suggestions: (_configs, p) => {
|
||||
try {
|
||||
return Object.keys(JSON.parse(p.profiles || "{}"));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
},
|
||||
},
|
||||
{ key: "programArgs", label: "Program arguments", mono: true, hint: "Empty uses the launch profile's arguments" },
|
||||
{
|
||||
key: "applicationUrl",
|
||||
label: "Application URL",
|
||||
control: "output",
|
||||
value: (p) => profile(p).applicationUrl || "",
|
||||
},
|
||||
{
|
||||
key: "profileEnvironment",
|
||||
label: "Profile environment variables",
|
||||
control: "output",
|
||||
value: (p) =>
|
||||
Object.entries(profile(p).environmentVariables ?? {})
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join("; "),
|
||||
hint: "Environment variables below override the profile",
|
||||
},
|
||||
],
|
||||
commandLine: (p) => dotnetCommand(p),
|
||||
async prepareLaunch(config) {
|
||||
const resolved = await call(commands.runDotnetResolve(config, false));
|
||||
const p = resolved.params ?? {};
|
||||
// Materialize the profile so explicit environment/cwd edits also apply on older SDKs.
|
||||
const args = parseArgs(p.programArgs?.trim() ? p.programArgs : p.profileArgs || "");
|
||||
return {
|
||||
...resolved,
|
||||
args: [
|
||||
...dotnetCommand({ ...p, launchProfile: "", programArgs: "" }).args,
|
||||
...(args.length ? ["--", ...args] : []),
|
||||
],
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export const dotnetTestType: RunConfigTypeContribution = {
|
||||
id: "dotnet-test",
|
||||
label: "dotnet test",
|
||||
icon: "file-csharp",
|
||||
description: "Run .NET tests",
|
||||
fields: [...dotnetProjectType.fields.slice(0, 2), { key: "programArgs", label: "Test arguments", mono: true }],
|
||||
commandLine(p) {
|
||||
const line = dotnetCommand({ ...p, programArgs: "" }, true);
|
||||
return { ...line, args: [...line.args, ...parseArgs(p.programArgs || "")] };
|
||||
},
|
||||
async prepareLaunch(config) {
|
||||
const resolved = await call(commands.runDotnetResolve(config, false));
|
||||
return { ...resolved, ...dotnetTestType.commandLine(resolved.params ?? {}) };
|
||||
},
|
||||
};
|
||||
@@ -22,6 +22,8 @@ import { useProject } from "@/platform/project";
|
||||
import { tomcatType } from "./tomcat";
|
||||
import { goBuildType, goTestType } from "./goTypes";
|
||||
|
||||
import { dotnetProjectType, dotnetTestType } from "./dotnetTypes";
|
||||
|
||||
export const COMPOUND = "compound";
|
||||
|
||||
const on = (v: string | undefined) => v === "true";
|
||||
@@ -396,6 +398,8 @@ export const BUILTIN_TYPES: readonly RunConfigTypeContribution[] = [
|
||||
maven,
|
||||
godot,
|
||||
pytest,
|
||||
dotnetProjectType,
|
||||
dotnetTestType,
|
||||
goBuildType,
|
||||
goTestType,
|
||||
applicationType,
|
||||
@@ -444,6 +448,10 @@ export function withParams(config: RunConfig, params: Record<string, string>, ty
|
||||
if (!line) return { ...rest, params, command: "", args: [] };
|
||||
return {
|
||||
...rest,
|
||||
...(config.kind === "dotnet" && config.beforeLaunch === undefined
|
||||
? { beforeLaunch: [{ kind: "dotnetBuild", target: "" }] }
|
||||
: {}),
|
||||
...(config.kind === "dotnet-test" ? { isTest: true } : {}),
|
||||
params: params.goKind ? { ...params, programArgv: JSON.stringify(parseArgs(params.programArgs ?? "")) } : params,
|
||||
...(config.kind === "go-test" && !config.id.startsWith("template:") ? { kind: "go" } : {}),
|
||||
...(params.goKind ? { isTest: params.goKind === "test" } : {}),
|
||||
|
||||
@@ -222,6 +222,9 @@ export interface BuiltinInspection {
|
||||
export const SPELLING_PRODUCER = "spelling";
|
||||
export const SPELLING_INSPECTION = "builtin:spelling";
|
||||
|
||||
export const DEPENDENCY_PRODUCER = "dependency-versions";
|
||||
export const DEPENDENCY_INSPECTION = "builtin:dependency-versions";
|
||||
|
||||
/** IDEA's Typo options: which parts of source files are checked (plain text always is). */
|
||||
export const SPELLING_OPTIONS = {
|
||||
code: "processCode",
|
||||
@@ -231,6 +234,14 @@ export const SPELLING_OPTIONS = {
|
||||
|
||||
/** Checks the IDE runs itself (not a language server). */
|
||||
export const BUILTIN_INSPECTIONS: readonly BuiltinInspection[] = [
|
||||
{
|
||||
id: DEPENDENCY_INSPECTION,
|
||||
producer: DEPENDENCY_PRODUCER,
|
||||
name: "Newer dependency version available",
|
||||
group: "Cargo",
|
||||
description: "Reports newer crate versions that Cargo.toml requirements do not already allow.",
|
||||
defaultLevel: "weakWarning",
|
||||
},
|
||||
{
|
||||
id: "builtin:file-references",
|
||||
producer: "file-references",
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
{
|
||||
"Newer dependency version available": "有更新的依赖版本可用",
|
||||
"Reports newer crate versions that Cargo.toml requirements do not already allow.": "报告 Cargo.toml 版本要求尚未允许的较新 crate 版本。",
|
||||
"Update to {latest}": "更新至 {latest}",
|
||||
"A newer version is available: {latest}": "有新版本可用:{latest}",
|
||||
"Kotlin bridge requires a Maven build root": "Kotlin 桥接需要 Maven 构建根目录",
|
||||
"Kotlin bridge bundle is unavailable": "Kotlin 桥接扩展不可用",
|
||||
"Kotlin bridge command did not acknowledge its library snapshot": "Kotlin 桥接命令未确认类库更新",
|
||||
@@ -5466,5 +5470,25 @@
|
||||
"Build arguments": "构建参数",
|
||||
"CMake default": "CMake 默认",
|
||||
"Quote arguments containing spaces. Build arguments go to cmake --build; use -- before native build tool options.": "包含空格的参数请加引号。构建参数传给 cmake --build;原生构建工具参数前请加 --。",
|
||||
"CMake profile {0}": "CMake 配置 {0}"
|
||||
"CMake profile {0}": "CMake 配置 {0}",
|
||||
".NET Project": ".NET 项目",
|
||||
".NET project": ".NET 项目",
|
||||
"Run a .NET project with a launch profile": "使用启动配置运行 .NET 项目",
|
||||
"Target framework": "目标框架",
|
||||
"Launch profile": "启动配置",
|
||||
"Empty disables launch profiles": "留空则禁用启动配置",
|
||||
"Empty uses the launch profile's arguments": "留空则使用启动配置中的参数",
|
||||
"Application URL": "应用 URL",
|
||||
"Profile environment variables": "启动配置中的环境变量",
|
||||
"Environment variables below override the profile": "下方的环境变量会覆盖启动配置中的值",
|
||||
"Build .NET project": "构建 .NET 项目",
|
||||
"Run .NET tests": "运行 .NET 测试",
|
||||
"Test arguments": "测试参数",
|
||||
"netcoredbg is not installed": "未安装 netcoredbg",
|
||||
".NET Project requires the local machine": ".NET 项目需要在本机运行",
|
||||
"Select a .NET project": "请选择 .NET 项目",
|
||||
"Invalid .NET project path": ".NET 项目路径无效",
|
||||
".NET launch profile '{profile_name}' is missing or is not a Project profile": ".NET 启动配置“{profile_name}”不存在或不是 Project 类型",
|
||||
".NET output resolution timed out": ".NET 构建产物路径查询超时",
|
||||
".NET build output is missing; run dotnet build before debugging": ".NET 构建产物不存在,请在调试前运行 dotnet build"
|
||||
}
|
||||
@@ -79,7 +79,10 @@ const BUILT_AT_RUNTIME = new Set<string>([]);
|
||||
|
||||
/** Text that stays as written in every locale: names, code, formats, shortcuts. */
|
||||
const UNTRANSLATED = new Set<string>([
|
||||
"dotnet test",
|
||||
"netcoredbg (.NET)",
|
||||
// Product names
|
||||
"Cargo",
|
||||
"CMake",
|
||||
"Prettier",
|
||||
"IntelliJ IDEA",
|
||||
@@ -485,6 +488,21 @@ function scanTypeScript(): Scan {
|
||||
return { translated, literals, untranslatable, spliced };
|
||||
}
|
||||
|
||||
/** Read strings without letting a Rust character literal open a string match. */
|
||||
function backendLiterals(source: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const m of source.matchAll(/'(?:\\.|[^'\\\r\n])'|"((?:[^"\\]|\\.)*)"/g)) {
|
||||
if (m[1] !== undefined) out.push(m[1]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
it("reads backend messages after quote character literals", () => {
|
||||
expect(
|
||||
backendLiterals(`let quote = '"'; let message = "Select a .NET project"; let detail = "Expected 'x'";`),
|
||||
).toEqual(["Select a .NET project", "Expected 'x'"]);
|
||||
});
|
||||
|
||||
/** String literals of the Rust crates and language definitions (backend messages). */
|
||||
function scanBackend(literals: Set<string>) {
|
||||
const files = [
|
||||
@@ -493,7 +511,7 @@ function scanBackend(literals: Set<string>) {
|
||||
...walk(`${ROOT}languages`, (p) => p.endsWith(".toml")),
|
||||
];
|
||||
for (const file of files)
|
||||
for (const m of readFileSync(file, "utf8").matchAll(/"((?:[^"\\]|\\.)*)"/g)) literals.add(shape(m[1]!));
|
||||
for (const literal of backendLiterals(readFileSync(file, "utf8"))) literals.add(shape(literal));
|
||||
}
|
||||
|
||||
/** Text that needs no translation: no words, a path / glob / option, or listed in `UNTRANSLATED`. */
|
||||
|
||||
Reference in new issue
Заблокувати користувача