Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 5451d9fa9f fix(run-targets): apply a published ports edit that hasn't left the field
Published ports and the other list fields of a run target were stored only when the field lost focus, so OK pressed with Enter, or anything that applied the settings while the field still had focus, dropped the edit. The list is now staged on every change; the text stays as typed while the field has focus.
2026-11-30 15:01:14 +08:00
LU XIANGRUIтаwildcatDownstairs 093cf6fdf8 feat(cpp): switch between a header and its source file (#6928)
A Switch Header/Source action (F10; Alt+O in the VS Code keymaps) opens the counterpart of the current C, C++, Objective-C or Objective-C++ file. It asks clangd with textDocument/switchSourceHeader (new lsp_switch_source_header, cancellable), so headers in include/ and sources in src/ are found; without clangd or an answer it opens a project file with the same stem and a counterpart extension, as Related Symbol does.

Closes #6927

Co-authored-by: wildcatDownstairs <[email protected]>

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 12:00:32 +08:00
LU XIANGRUIтаwildcatDownstairs 9b578c2fad feat(run): debug Node.js on SSH, Docker and Compose run targets (#6919)
Debug on a Node.js configuration or a .js / .ts file run whose run target is SSH, Docker or Compose now debugs the program there, extending the Python flow. A js-debug configuration starts node with --inspect-brk on a free port (0.0.0.0 inside the container, published on this machine's loopback only; the host's loopback over the existing SSH forward). The run prints the project folder on the target as a system line, which the frontend reads to map sources before attaching js-debug. tsx is refused for now (it hangs once js-debug attaches); other programs get an error naming the fix.

Closes #6901

Co-authored-by: wildcatDownstairs <[email protected]>

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:52:59 +08:00
LU XIANGRUIтаwildcatDownstairs f5bb97babd feat(js): CSS completion and diagnostics in styled-components and emotion templates (#6917)
Adds the managed tool typescript-styled-plugin (@styled/typescript-styled-plugin, pinned, hosted by vtsls). ide_sdk::apply::configure_styled adds it to vtsls' globalPlugins when it is installed and a package.json at, above or below the server root depends on styled-components or emotion; a tsconfig that declares the plugin keeps one copy. Opening a script that imports one of those libraries offers the install once per project and session. The bounded walk below the root is now shared with CSS Modules Kit.

Closes #6900

Co-authored-by: wildcatDownstairs <[email protected]>

Co-authored-by: wildcatDownstairs <[email protected]>
2026-11-30 11:49:27 +08:00
l0ng-ai e23088d558 fix(vfs): don't cache ignore rules read before an invalidation (#6929)
GitignoreStack::matcher_for read a directory's ignore files outside the cache lock and stored the matcher afterwards, so a watcher-thread lookup racing a command that rewrote .gitignore and invalidated could leave the older rules cached; the next listing then missed the new entry. Invalidations now bump a generation counter under the cache lock and a lookup stores its matcher only when none happened since it started reading. This made rpc::serves_projects_files_documents_search_and_runs fail intermittently on Windows.
2026-11-30 11:48:07 +08:00
50 змінених файлів з 988 додано та 114 видалено

No files matched your search

+21
Переглянути файл
@@ -639,6 +639,26 @@ pub async fn lsp_file_references(
result
}
/// The header of the document's source file or the source of its header (C, C++,
/// Objective-C) as clangd finds it; `None` without clangd or an answer. Cancel with
/// `cancel_request(request)`.
#[command(trust = trusted)]
pub async fn lsp_switch_source_header(
host: &Host,
window: &str,
request: RequestId,
doc: DocId,
) -> IdeResult<Option<String>> {
let lsp = host.project(window)?.lsp.clone();
let cancel = host.begin_request(request);
let result = tokio::select! {
result = lsp.switch_source_header(doc, cancel.clone()) => result,
_ = cancel.cancelled() => Err(ide_core::IdeError::cancelled()),
};
host.end_request(request);
Ok(result?.map(|path| path.to_string_lossy().into_owned()))
}
/// Implementations of the symbols at `positions`, one list per position (the
/// editor's "is implemented / overridden" gutter markers). Cancel with
/// `cancel_request(request)`.
@@ -3294,6 +3314,7 @@ ide_command::domain!(
lsp_hover,
lsp_implementation_locations,
lsp_file_references,
lsp_switch_source_header,
lsp_implementations,
lsp_inlay_hints,
lsp_inline_completion,
+4 -1
Переглянути файл
@@ -454,7 +454,10 @@ async fn start_inner(
if ide_run::is_python_kind(&config.kind) {
container_python_path(&mut config.env, &super::python::paths(&project), &project.root);
}
let config = container::prepare(host, &project.root, target, config).await?;
let (config, note) = container::prepare(host, &project.root, target, config).await?;
if let Some(note) = note {
on_output(OutputChunk::System { text: format!("{note}\n") });
}
let encoding = settings.console.encoding;
let options = StartOptions {
encoding: Some(encoding).filter(|e| !e.trim().is_empty()),
+16 -8
Переглянути файл
@@ -6,8 +6,8 @@ use ide_core::remote_settings::{RunTarget, RunTargetKind};
use ide_core::{IdeError, IdeResult};
use ide_docker::DockerEndpoint;
use ide_remote::docker::{
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, compose_container_root,
compose_service, container_config, container_name, default_container_root,
ComposeService, ContainerDebug, ContainerRun, DEBUG_BOOTSTRAP, DEBUG_BOOTSTRAP_NAME, NODE_DEBUG_FOLDER,
compose_container_root, compose_service, container_config, container_name, default_container_root, node_debug,
};
use ide_remote::target::DEBUG_PARAM;
use ide_run::RunConfig;
@@ -16,15 +16,21 @@ use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
use std::time::SystemTime;
/// `config` rewritten to run in a new container of `target`'s image or service.
pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config: RunConfig) -> IdeResult<RunConfig> {
/// `config` rewritten to run in a new container of `target`'s image or service, and for a
/// Node.js debug run the line telling the debugger the project folder in the container.
pub(super) async fn prepare(
host: &Host,
root: &Path,
target: RunTarget,
config: RunConfig,
) -> IdeResult<(RunConfig, Option<String>)> {
if config.kind == "dotnet" || config.kind == "dotnet-test" {
return Err(IdeError::invalid(".NET Project requires the local machine"));
}
let debug = config.extras.params.get(DEBUG_PARAM).is_some_and(|v| v == "true");
if debug && config.debug_adapter.as_deref() != Some("debugpy") {
if debug && config.debug_adapter.as_deref() != Some("debugpy") && !node_debug(&config) {
return Err(IdeError::invalid(format!(
"'{}' can't be debugged in a container: only Python run configurations can",
"'{}' can't be debugged in a container: only Python and Node.js run configurations can",
config.name
)));
}
@@ -41,7 +47,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
let (service_env, service_ports) = server_context(&data_dir, &root, &target, &config);
let name = container_name(&config.id, &unique());
let debugging = if debug { Some(Debugging::prepare(&data_dir)?) } else { None };
container_config(
let note = (debug && node_debug(&config)).then(|| format!("{NODE_DEBUG_FOLDER}{container_root}"));
let config = container_config(
&config,
&ContainerRun {
target: &target,
@@ -60,7 +67,8 @@ pub(super) async fn prepare(host: &Host, root: &Path, target: RunTarget, config:
debugpy: d.debugpy.as_deref(),
}),
},
)
)?;
Ok((config, note))
})
.await
}
+2
Переглянути файл
@@ -222,6 +222,8 @@ impl Host {
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
let css_modules = ide_tools::managed_npm_plugin(&data_dir, "css-modules-kit");
ide_sdk::apply::configure_css_modules(cfg, server_root, css_modules.as_deref());
let styled = ide_tools::managed_npm_plugin(&data_dir, "typescript-styled-plugin");
ide_sdk::apply::configure_styled(cfg, server_root, styled.as_deref());
// After the global plugins: they keep the IDE's copies.
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
let container_python = effective.languages.python.run_target().is_some();
+1
Переглянути файл
@@ -37,6 +37,7 @@ mod pull;
mod scope;
mod server;
mod source_actions;
mod switch_source_header;
mod tcp;
mod text;
mod ts_file_moves;
+23
Переглянути файл
@@ -0,0 +1,23 @@
//! Switch Header/Source for C, C++ and Objective-C through clangd's
//! `textDocument/switchSourceHeader` extension. The editor falls back to a file with the
//! same name when clangd does not serve the document or finds nothing.
use crate::{DEFAULT_TIMEOUT, LspManager, uri};
use ide_core::{CancellationToken, DocId, IdeResult};
use serde_json::Value;
use std::path::PathBuf;
const SERVER: &str = "clangd";
const METHOD: &str = "textDocument/switchSourceHeader";
impl LspManager {
/// clangd's header for the document's source file, or source for its header; `None`
/// when clangd finds none or does not serve the document.
pub async fn switch_source_header(&self, doc: DocId, cancel: CancellationToken) -> IdeResult<Option<PathBuf>> {
let snap = self.snapshot(doc)?;
let clangd: Vec<_> = snap.servers.iter().filter(|s| s.name == SERVER).cloned().collect();
let Some(t) = self.ready_targets(&clangd, |_| true).await.into_iter().next() else { return Ok(None) };
let found: Value = self.call(&t, METHOD, snap.ident(), Some(&cancel), DEFAULT_TIMEOUT).await?;
Ok(found.as_str().and_then(uri::uri_to_path))
}
}
+24
Переглянути файл
@@ -8800,3 +8800,27 @@ async fn hierarchy_refactorings_use_phoxites_requests_when_the_server_advertises
assert_eq!(e.kind, ide_core::error::ErrorKind::Protocol);
assert_eq!(e.message, "any-name: index out of bounds");
}
#[tokio::test(flavor = "multi_thread")]
async fn switch_source_header_asks_clangd_and_only_clangd() {
let h = harness_for("objective-c", "m", &[("clangd", incremental_caps())], &[]);
let (doc, path) = h.open("Foo.m", "#import \"Foo.h\"\n");
h.wait_status("clangd", ServerStatus::Ready).await;
let s = h.launcher.state("clangd");
let header = h.root.join("Foo.h");
s.respond("textDocument/switchSourceHeader", json!(uri_of(&header)));
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), Some(header));
assert_eq!(s.requested("textDocument/switchSourceHeader"), vec![json!({ "uri": uri_of(&path) })]);
// clangd found nothing: the editor falls back to a file of the same name.
s.respond("textDocument/switchSourceHeader", Value::Null);
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), None);
h.mgr.shutdown_all().await;
// Another server is never sent clangd's extension.
let h = harness_for("objective-c", "m", &[("mock", incremental_caps())], &[]);
let (doc, _) = h.open("Foo.m", "");
h.wait_status("mock", ServerStatus::Ready).await;
assert_eq!(h.mgr.switch_source_header(doc, CancellationToken::new()).await.unwrap(), None);
assert!(h.launcher.state("mock").requested("textDocument/switchSourceHeader").is_empty());
h.mgr.shutdown_all().await;
}
+77
Переглянути файл
@@ -1082,6 +1082,83 @@ async fn css_modules_kit_navigates_between_tsx_and_module_css() {
}
}
/// `@styled/typescript-styled-plugin` on vtsls: CSS diagnostics, completion and hover inside
/// styled-components and emotion templates (#6900), with the settings hook's own plugin
/// configuration. A tsconfig that declares the plugin too still gets one copy: each
/// diagnostic shows once. Set `OPENIDEA_TEST_NPM_TOOLS` to a dir with
/// `npm i @vtsls/language-server typescript@6 @styled/[email protected]`.
#[tokio::test(flavor = "multi_thread")]
#[ignore = "requires @vtsls/language-server and @styled/typescript-styled-plugin (OPENIDEA_TEST_NPM_TOOLS)"]
async fn styled_plugin_checks_and_completes_css_in_templates() {
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
// (library, its import and tag, the tsconfig declares the plugin)
let cases = [
("styled-components", "import styled from 'styled-components';", "styled.div", false),
("@emotion/styled", "import styled from '@emotion/styled';", "styled.div", true),
("@emotion/react", "import { css } from '@emotion/react';", "css", false),
];
for (library, import, tag, declared) in cases {
let dir = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(dir.path()).unwrap();
std::fs::create_dir_all(root.join("src")).unwrap();
std::fs::write(root.join("package.json"), format!(r#"{{"name":"app","dependencies":{{"{library}":"*"}}}}"#))
.unwrap();
let plugins = if declared { r#", "plugins": [{ "name": "@styled/typescript-styled-plugin" }]"# } else { "" };
std::fs::write(
root.join("tsconfig.json"),
format!(r#"{{ "compilerOptions": {{ "strict": true, "module": "ESNext", "moduleResolution": "Bundler"{plugins} }}, "include": ["src"] }}"#),
)
.unwrap();
// The library itself isn't installed: the plugin goes by the tag name.
let types = "declare module 'styled-components' { const styled: any; export default styled; }\n\
declare module '@emotion/styled' { const styled: any; export default styled; }\n\
declare module '@emotion/react' { export const css: any; }\n";
std::fs::write(root.join("src/libs.d.ts"), types).unwrap();
let path = root.join("src/box.ts");
let text = format!("{import}\nexport const box = {tag}`\n color: blue;\n colr: red;\n justify-con\n`;\n");
std::fs::write(&path, &text).unwrap();
let mut vtsls = npm_server(&tools, "vtsls", "vtsls", None);
vtsls.tsserver_project = true;
assert!(ide_sdk::apply::configure_styled(&mut vtsls, &root, Some(&tools)));
let data = tempfile::tempdir().unwrap();
assert!(!ide_sdk::apply::configure_tsconfig_plugins(&mut vtsls, &root, data.path()));
let registry = LanguageRegistry::from_configs(vec![lang("typescript", "ts", vtsls)]);
let (mgr, events) = manager(&root, registry);
let doc = DocId::next();
mgr.did_open(doc, &path, &LanguageId::new("typescript"), 1, &text);
let case = format!("{library}, declared: {declared}");
let unknown = retry("unknown property diagnostic", Duration::from_secs(90), || {
let found = events.lock().iter().rev().find_map(|e| match e {
IdeEvent::Diagnostics { path: p, items, .. } if p == &path => Some(
items.iter().filter(|d| d.message.contains("Unknown property: 'colr'")).map(|d| d.range).collect(),
),
_ => None,
});
async move { found.filter(|v: &Vec<_>| !v.is_empty()) }
})
.await;
assert_eq!(unknown.len(), 1, "{case}: one copy of the plugin, {unknown:?}");
assert_eq!(unknown[0].start.line, 3, "{case}");
let list = retry("CSS property completion", Duration::from_secs(30), || {
let mgr = mgr.clone();
async move {
let list = mgr.completion(doc, Pos::new(4, 13), None, Default::default()).await.ok()?;
list.items.iter().any(|i| i.label == "justify-content").then_some(list)
}
})
.await;
assert!(list.items.iter().any(|i| i.label == "justify-items"), "{case}");
let hover = retry("CSS property hover", Duration::from_secs(30), || {
let mgr = mgr.clone();
async move { mgr.hover(doc, Pos::new(2, 4), Default::default()).await.ok().flatten() }
})
.await;
assert!(hover.contents.value.to_lowercase().contains("color"), "{case}: {}", hover.contents.value);
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
}
}
const MDX_BUTTON: &str =
"export function Button(props: { label: string }) {\n return <button>{props.label}</button>;\n}\n";
const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n<Button label=\"hi\" />\n\n<Button label={count} />\n\n{count.toFixed()}\n";
+103 -4
Переглянути файл
@@ -33,12 +33,13 @@ pub struct ContainerRun<'a> {
pub name: &'a str,
/// `--user uid:gid`; `None` keeps the image's user.
pub user: Option<(u32, u32)>,
/// Runs the Python program under debugpy, for the debugger to attach.
/// Runs the program for the debugger to attach: Python under debugpy, Node.js (a `js-debug`
/// configuration) with its inspector waiting.
pub debug: Option<ContainerDebug<'a>>,
}
/// A debug run: the program starts under [`DEBUG_BOOTSTRAP`], which waits for the
/// debugger on `port` (published on this machine's loopback interface only).
/// A debug run: the program starts under [`DEBUG_BOOTSTRAP`] (Node.js: with `--inspect-brk`),
/// which waits for the debugger on `port` (published on this machine's loopback interface only).
pub struct ContainerDebug<'a> {
pub port: u16,
/// Folder on this machine holding [`DEBUG_BOOTSTRAP`] as [`DEBUG_BOOTSTRAP_NAME`].
@@ -57,6 +58,14 @@ const DEBUG_DIR: &str = "/opt/openidea/debug";
const DEBUGPY_DIR: &str = "/opt/openidea/debugpy-lib";
/// Start of the line the bootstrap prints when the debugger can attach.
pub const DEBUG_READY: &str = "debugpy is waiting for the debugger on port ";
/// Start of the line printed before a Node.js program starts for debugging on a run target,
/// followed by the project folder there. Node prints `Debugger listening on ws://…` itself.
pub const NODE_DEBUG_FOLDER: &str = "Starting Node.js for the debugger, project folder ";
/// Whether a debug run of `config` starts Node.js with its inspector rather than debugpy.
pub fn node_debug(config: &RunConfig) -> bool {
config.debug_adapter.as_deref() == Some("js-debug")
}
/// The container folder of the project when a Docker target sets none.
pub fn default_container_root(root: &Path) -> String {
@@ -243,9 +252,12 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
if let Some((uid, gid)) = run.user {
args.extend(["--user".into(), format!("{uid}:{gid}")]);
}
let node = node_debug(config);
if let Some(debug) = &run.debug {
let port = debug.port;
args.extend(["--publish".into(), format!("127.0.0.1:{port}:{port}")]);
}
if let Some(debug) = run.debug.as_ref().filter(|_| !node) {
args.extend(["--volume".into(), format!("{}:{DEBUG_DIR}:ro", debug.bootstrap_dir.to_string_lossy())]);
if let Some(lib) = debug.debugpy {
args.extend(["--volume".into(), format!("{}:{DEBUGPY_DIR}:ro", lib.to_string_lossy())]);
@@ -262,11 +274,15 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
match (command.shell_line, &run.debug) {
(Some(_), Some(_)) => {
return Err(IdeError::invalid(format!(
"'{}' is a shell command line: only a Python script, module or console script can be debugged in a container. Set Command to the Python executable and put the script or -m module in Arguments",
"'{}' is a shell command line: only a Python or Node.js program can be debugged in a container. Set Command to the Python or Node.js executable and put the script in Arguments",
config.name
)));
}
(Some(line), None) => args.extend(["sh".into(), "-c".into(), line]),
// Inside the container the inspector listens on every interface, for the published port.
(None, Some(debug)) if node => {
args.extend(node_debug_command(&command.program, &command.args, "0.0.0.0", debug.port)?)
}
(None, Some(debug)) => {
let bootstrap = format!("{DEBUG_DIR}/{DEBUG_BOOTSTRAP_NAME}");
args.extend(debug_command(
@@ -347,6 +363,43 @@ fn is_python(program: &str) -> bool {
name == "python" || name == "python2" || name.starts_with("python3")
}
/// Why tsx can't be debugged on a run target yet: js-debug's attach never lets the program start
/// past tsx's loader worker.
const TSX_UNSUPPORTED: &str = "tsx can't be debugged on a run target yet: the program does not start once the debugger attaches. For TypeScript, set the Node interpreter to node and add --experimental-strip-types to the Node options";
/// `program args` (a Node.js command on a run target) with the inspector waiting for the debugger
/// on `host:port`: `--inspect-brk` goes right after `node`, so the configuration's Node options keep
/// applying.
pub(crate) fn node_debug_command(program: &str, args: &[String], host: &str, port: u16) -> IdeResult<Vec<String>> {
let name = |s: &str| s.rsplit(['/', '\\']).next().unwrap_or(s).trim_end_matches(".exe").to_owned();
// `node --import tsx` registers the same loader worker (`--loader tsx` fails on its own).
let tsx_import = |value: &str| value == "tsx" || value.starts_with("tsx/") || value.contains("/tsx/");
let mut imports_tsx = false;
let mut i = 0;
while let Some(a) = args.get(i).filter(|a| a.starts_with('-')) {
if a == "--import" {
imports_tsx |= args.get(i + 1).is_some_and(|v| tsx_import(v));
i += 1;
}
imports_tsx |= a.strip_prefix("--import=").is_some_and(tsx_import);
i += 1;
}
match name(program).as_str() {
"node" if imports_tsx => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
"node" => {}
"tsx" => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
"npx" if args.first().is_some_and(|a| a == "tsx") => return Err(IdeError::invalid(TSX_UNSUPPORTED)),
_ => {
return Err(IdeError::invalid(format!(
"`{program}` can't be debugged on a run target: set the Node interpreter to node"
)));
}
}
let mut line = vec![program.to_owned(), format!("--inspect-brk={host}:{port}")];
line.extend(args.iter().cloned());
Ok(line)
}
/// The command line that runs `program args` under [`DEBUG_BOOTSTRAP`] (at `bootstrap` in the
/// container or on the SSH host): `python [options] <bootstrap> <port> <folder> (script | -m module | -c code) args`.
/// A console script (`pytest`) runs as a module of the interpreter next to it, or of the
@@ -741,6 +794,52 @@ mod tests {
assert!(args.contains("openidea/debug:ro python:3.12") && !args.contains("debugpy-lib"), "{args}");
}
#[cfg(unix)]
#[test]
fn debug_starts_node_with_the_inspector_on_the_published_port() {
let target = RunTarget { kind: RunTargetKind::Docker, image: "node:22".into(), ..Default::default() };
let line = |command: &str, args: &[&str]| {
let c = RunConfig { debug_adapter: Some("js-debug".into()), ..config(command, args) };
let args = debugged(&target, &c).unwrap().join(" ");
assert!(args.contains("--publish 127.0.0.1:41234:41234 node:22"), "{args}");
assert!(!args.contains("openidea/debug"), "no bootstrap for Node.js: {args}");
args.split_once("node:22 ").unwrap().1.to_owned()
};
let inspect = "--inspect-brk=0.0.0.0:41234";
assert_eq!(
line("/usr/local/bin/node", &["--env-file=.env", "/work/proj/main.js", "a"]),
format!("node {inspect} --env-file=.env /workspaces/proj/main.js a"),
"the configuration's Node options stay"
);
assert_eq!(
line("node", &["--import", "./setup.mjs", "main.js", "--import", "tsx"]),
format!("node {inspect} --import ./setup.mjs main.js --import tsx"),
"other imports, and the program's own arguments, don't count"
);
assert_eq!(
line("node", &["--experimental-strip-types", "main.ts"]),
format!("node {inspect} --experimental-strip-types main.ts")
);
// tsx hangs once js-debug attaches: refused, pointing to type stripping.
for (command, args, error) in [
("/work/proj/node_modules/.bin/tsx", &["main.ts"][..], "--experimental-strip-types"),
("npx", &["tsx", "main.ts"][..], "tsx can't be debugged"),
("node", &["--import", "tsx", "main.ts"][..], "tsx can't be debugged"),
("node", &["--import=tsx/esm", "main.ts"][..], "tsx can't be debugged"),
(
"node",
&["--env-file=.env", "--import", "/opt/lib/node_modules/tsx/dist/loader.mjs", "main.ts"][..],
"tsx",
),
("npm", &["run", "dev"][..], "set the Node interpreter to node"),
("node main.js", &[][..], "shell command line"),
] {
let c = RunConfig { debug_adapter: Some("js-debug".into()), ..config(command, args) };
let err = debugged(&target, &c).unwrap_err();
assert!(err.message.contains(error), "{command}: {}", err.message);
}
}
#[test]
fn maps_files_printed_in_the_container_through_the_longest_mount() {
let root = Path::new("project");
+18 -5
Переглянути файл
@@ -5,7 +5,7 @@ use crate::deploy::{Deployment, FileStamp, SyncEntry, SyncStatus, SyncStep, Tran
use crate::mapping::{Excludes, Mappings, ResolvedMapping, posix};
use crate::target::{
DEBUG_PARAM, PROBE_NO_FOLDER, RemoteDebug, RemoteRuns, RemoteStart, SyncFn, debug_interpreter, debugpy_probe,
remote_command, rewrite_external_classpath, ssh_debug_command,
remote_command, rewrite_external_classpath, ssh_debug_command, ssh_node_debug_command,
};
use ide_core::remote_settings::{AutoUpload, DeploymentServer, DeploymentType, RunTarget};
use ide_core::settings::Settings;
@@ -605,14 +605,21 @@ async fn prepare_debug(
remote_root: &str,
debugpy_lib: Option<&Path>,
) -> IdeResult<(RemoteDebug, Option<SyncFn>)> {
if config.debug_adapter.as_deref() != Some("debugpy") {
let node = crate::docker::node_debug(config);
if config.debug_adapter.as_deref() != Some("debugpy") && !node {
return Err(IdeError::invalid(format!(
"'{}' can't be debugged on an SSH run target: only Python run configurations can",
"'{}' can't be debugged on an SSH run target: only Python and Node.js run configurations can",
config.name
)));
}
let dir = join(&fs.home().await?, DEBUG_FOLDER);
let port = std::net::TcpListener::bind(("127.0.0.1", 0))?.local_addr()?.port();
if node {
let command = ssh_node_debug_command(&remote_command(config, target, root, remote_root), port)?;
let tunnel = forward(session, port).await?;
let note = Some(format!("{}{remote_root}", crate::docker::NODE_DEBUG_FOLDER));
return Ok((RemoteDebug { command, tunnel, note }, None));
}
let dir = join(&fs.home().await?, DEBUG_FOLDER);
// Unique among this machine's debug runs; other machines' runs use other temporary names too.
let temp = |path: &str| format!("{path}.{}-{port}.tmp", std::process::id());
// Named after its content and never rewritten: a concurrent run may be reading it.
@@ -671,13 +678,19 @@ async fn prepare_debug(
}));
}
}
let tunnel = forward(session, port).await?;
Ok((RemoteDebug { command, tunnel, note: None }, upload))
}
/// Forwards local `port` to the same port on the host's loopback interface.
async fn forward(session: &Arc<ide_ssh::Session>, port: u16) -> IdeResult<ide_ssh::Tunnel> {
let tunnel = ide_ssh::Tunnel::listen_on(session.clone(), Some(port), "127.0.0.1", port).await?;
if tunnel.port() != port {
return Err(IdeError::unavailable(format!(
"local port {port} for the debugger was taken meanwhile; try again"
)));
}
Ok((RemoteDebug { command, tunnel }, upload))
Ok(tunnel)
}
/// Uploads outside-root classpath entries to their mirrored remote copies,
+37
Переглянути файл
@@ -153,6 +153,18 @@ pub fn ssh_debug_command(
})
}
/// `command` (an SSH target's Node.js command) with the inspector waiting on the host's loopback
/// `port`, which the IDE reaches through an SSH forward.
pub fn ssh_node_debug_command(command: &RemoteCommand, port: u16) -> IdeResult<RemoteCommand> {
if command.shell_line.is_some() {
return Err(IdeError::invalid(
"a shell command line can't be debugged on a run target: set the Node interpreter to node and the JavaScript file to the script",
));
}
let line = crate::docker::node_debug_command(&command.program, &command.args, "127.0.0.1", port)?;
Ok(RemoteCommand { program: line[0].clone(), args: line[1..].to_vec(), shell_line: None, ..command.clone() })
}
/// The interpreter of an [`ssh_debug_command`] (with its options, or behind `uv run`).
pub fn debug_interpreter(debug: &RemoteCommand, bootstrap: &str) -> RemoteCommand {
let end = debug.args.iter().position(|a| a == bootstrap).unwrap_or(debug.args.len());
@@ -358,6 +370,8 @@ pub struct RemoteStart {
pub struct RemoteDebug {
pub command: RemoteCommand,
pub tunnel: ide_ssh::Tunnel,
/// Printed right before the program starts (`docker::NODE_DEBUG_FOLDER`).
pub note: Option<String>,
}
impl RemoteRuns {
@@ -485,6 +499,9 @@ async fn run_remote(
return Err(IdeError::cancelled());
}
on_output(OutputChunk::System { text: format!("{}\n", command.display()) });
if let Some(note) = start.debug.as_ref().and_then(|d| d.note.as_ref()) {
on_output(OutputChunk::System { text: format!("{note}\n") });
}
let out = on_output.clone();
let process = start
.session
@@ -556,6 +573,26 @@ mod tests {
assert_eq!(c.program, "make");
}
#[cfg(unix)]
#[test]
fn debugs_node_on_an_ssh_host_through_its_loopback_port() {
let target = RunTarget { node: "/opt/node/bin/node".into(), ..Default::default() };
let plain = remote_command(
&config("/usr/local/bin/node", &["--enable-source-maps", "/work/proj/src/main.js"], None),
&target,
Path::new("/work/proj"),
"/home/me/proj",
);
let debug = ssh_node_debug_command(&plain, 50123).unwrap();
assert_eq!(debug.program, "/opt/node/bin/node");
assert_eq!(debug.args, ["--inspect-brk=127.0.0.1:50123", "--enable-source-maps", "/home/me/proj/src/main.js"]);
assert_eq!((debug.cwd.as_str(), &debug.env), (plain.cwd.as_str(), &plain.env));
let tsx = RemoteCommand { program: "tsx".into(), ..plain.clone() };
assert!(ssh_node_debug_command(&tsx, 50123).unwrap_err().message.contains("--experimental-strip-types"));
let shell = RemoteCommand { shell_line: Some("node main.js".into()), ..plain };
assert!(ssh_node_debug_command(&shell, 50123).is_err());
}
#[cfg(unix)]
#[test]
fn debugs_python_on_an_ssh_host_through_its_loopback_port() {
+14
Переглянути файл
@@ -1654,6 +1654,20 @@ pub fn configure_css_modules(cfg: &mut LanguageServerConfig, server_root: &Path,
true
}
/// Registers `@styled/typescript-styled-plugin` (installed under `location`) as a vtsls global
/// plugin when a package.json at, above or below `server_root` depends on styled-components or
/// emotion (#6900). No-op elsewhere, and without the plugin (`None`).
pub fn configure_styled(cfg: &mut LanguageServerConfig, server_root: &Path, location: Option<&Path>) -> bool {
if cfg.name != "vtsls" || !cfg.tsserver_project {
return false;
}
let Some(location) = location.filter(|_| crate::styled::used(server_root)) else {
return false;
};
push_global_plugin(cfg, crate::styled::tsserver_plugin(location));
true
}
/// Adds `plugin` to vtsls' `globalPlugins`, replacing an entry of the same name.
fn push_global_plugin(cfg: &mut LanguageServerConfig, plugin: Value) {
insert_global_plugin(cfg, plugin, None);
+10 -9
Переглянути файл
@@ -15,21 +15,22 @@ pub(crate) fn enabled(server_root: &Path) -> bool {
if ide_language::marked_root(None, server_root, &markers).is_some() {
return true;
}
// ponytail: bounded walk, as for the path aliases; deeper workspace members go without.
files_below(server_root, "tsconfig.json")
.any(|p| p.parent().is_some_and(|dir| ide_language::marked_root(Some(dir), dir, &markers).is_some()))
}
/// The files named `name` in `root` and the packages below it, outside `node_modules`.
pub(crate) fn files_below(root: &Path, name: &'static str) -> impl Iterator<Item = std::path::PathBuf> {
// A bounded walk, as for the path aliases; deeper workspace members are not seen.
const MAX_DEPTH: usize = 4;
const MAX_ENTRIES: usize = 50_000;
let mut walker = ignore::WalkBuilder::new(server_root);
let mut walker = ignore::WalkBuilder::new(root);
walker
.max_depth(Some(MAX_DEPTH))
.require_git(ide_core::ignored::inside_git_repo(server_root))
.require_git(ide_core::ignored::inside_git_repo(root))
.follow_links(false)
.filter_entry(|e| e.file_name() != "node_modules");
walker
.build()
.take(MAX_ENTRIES)
.flatten()
.filter(|e| e.file_name() == "tsconfig.json")
.any(|e| e.path().parent().is_some_and(|dir| ide_language::marked_root(Some(dir), dir, &markers).is_some()))
walker.build().take(MAX_ENTRIES).flatten().filter(move |e| e.file_name() == name).map(|e| e.into_path())
}
/// vtsls `globalPlugins` entry of the plugin installed under `location` (the folder holding its
+1
Переглянути файл
@@ -31,6 +31,7 @@ pub mod php;
pub mod pinned;
pub mod python;
pub mod ruby;
mod styled;
mod tsconfig_plugins;
mod vue;
mod zig;
+56
Переглянути файл
@@ -0,0 +1,56 @@
//! `@styled/typescript-styled-plugin`: the tsserver plugin vtsls loads for CSS completion, hover
//! and diagnostics inside styled-components and emotion template literals (#6900). It matches
//! templates by tag name (`styled`, `css`, `createGlobalStyle`, `keyframes`, `injectGlobal`).
use std::path::Path;
/// The package (and tsserver plugin name) the IDE installs as the `typescript-styled-plugin` tool.
pub(crate) const PLUGIN: &str = "@styled/typescript-styled-plugin";
/// The CSS-in-JS libraries whose templates the plugin understands.
const LIBRARIES: &[&str] = &["styled-components", "@emotion/styled", "@emotion/react", "@emotion/css"];
fn depends(manifest: &Path) -> bool {
std::fs::read_to_string(manifest)
.is_ok_and(|text| crate::libraries::package_dependencies(&text).iter().any(|d| LIBRARIES.contains(&d.as_str())))
}
/// A package.json at `server_root`, above it, or in a package below it depends on one of them.
pub(crate) fn used(server_root: &Path) -> bool {
server_root.ancestors().any(|dir| depends(&dir.join("package.json")))
|| crate::css_modules::files_below(server_root, "package.json").any(|p| depends(&p))
}
/// vtsls `globalPlugins` entry of the plugin installed under `location` (the folder holding its
/// `node_modules`).
pub(crate) fn tsserver_plugin(location: &Path) -> serde_json::Value {
serde_json::json!({
"name": PLUGIN,
"location": location.to_string_lossy(),
"enableForWorkspaceTypeScriptVersions": true,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_package_depending_on_styled_components_or_emotion_turns_it_on() {
let tmp = tempfile::tempdir().unwrap();
let root = &dunce::canonicalize(tmp.path()).unwrap();
std::fs::create_dir_all(root.join("apps/web/node_modules/dep")).unwrap();
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "react": "^19.0.0" } }"#).unwrap();
let styled = r#"{ "dependencies": { "styled-components": "^6.1.0" } }"#;
std::fs::write(root.join("apps/web/node_modules/dep/package.json"), styled).unwrap();
assert!(!used(root), "dependencies don't count");
std::fs::write(root.join("apps/web/package.json"), styled).unwrap();
assert!(used(root), "a package below the server root");
assert!(used(&root.join("apps/web/src")), "the package.json above");
std::fs::write(root.join("apps/web/package.json"), r#"{ "devDependencies": { "@emotion/react": "^11" } }"#)
.unwrap();
assert!(used(root), "emotion");
std::fs::write(root.join("apps/web/package.json"), r#"{ "dependencies": { "@emotion/cache": "^11" } }"#)
.unwrap();
assert!(!used(root));
}
}
+52
Переглянути файл
@@ -4037,3 +4037,55 @@ fn css_modules_kit_stays_the_ides_copy_when_the_project_declares_or_installs_it(
assert!(location.join("node_modules/project-plugin").exists());
assert!(!location.join("node_modules/@css-modules-kit").exists());
}
#[test]
fn vtsls_gets_the_styled_plugin_where_a_package_uses_styled_components_or_emotion() {
let tmp = tempfile::tempdir().unwrap();
let (root, tools) = (tmp.path().join("app"), tmp.path().join("tools"));
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "react": "^19.0.0" } }"#).unwrap();
let mut cfg = server("vtsls");
cfg.tsserver_project = true;
assert!(!crate::apply::configure_styled(&mut cfg, &root, Some(&tools)), "no CSS-in-JS library");
assert!(cfg.initialization_options.is_none());
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "@emotion/styled": "^11.14.0" } }"#).unwrap();
assert!(!crate::apply::configure_styled(&mut cfg, &root, None), "plugin not installed");
let mut native = server("vtsls");
assert!(!crate::apply::configure_styled(&mut native, &root, Some(&tools)), "TypeScript 7 hosts no plugins");
for _ in 0..2 {
assert!(crate::apply::configure_styled(&mut cfg, &root, Some(&tools)));
}
let init = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
assert_eq!(
init.pointer("/vtsls/tsserver/globalPlugins").unwrap(),
&serde_json::json!([{
"name": "@styled/typescript-styled-plugin",
"location": tools.to_string_lossy(),
"enableForWorkspaceTypeScriptVersions": true,
}]),
"once"
);
}
#[test]
fn the_styled_plugin_stays_one_ides_copy_when_the_tsconfig_declares_it() {
let tmp = tempfile::tempdir().unwrap();
let (root, tools, data) = (tmp.path().join("app"), tmp.path().join("tools"), tmp.path().join("data"));
std::fs::create_dir_all(root.join("node_modules/@styled/typescript-styled-plugin")).unwrap();
std::fs::write(root.join("package.json"), r#"{ "dependencies": { "styled-components": "^6.1.0" } }"#).unwrap();
std::fs::write(
root.join("tsconfig.json"),
r#"{ "compilerOptions": { "plugins": [{ "name": "@styled/typescript-styled-plugin" }] } }"#,
)
.unwrap();
let mut cfg = server("vtsls");
cfg.tsserver_project = true;
// In the host's order: the global plugins, then the tsconfig's.
assert!(crate::apply::configure_styled(&mut cfg, &root, Some(&tools)));
assert!(!crate::apply::configure_tsconfig_plugins(&mut cfg, &root, &data), "no probe location for it");
let init = serde_json::to_value(cfg.initialization_options.as_ref().unwrap()).unwrap();
let plugins = init.pointer("/vtsls/tsserver/globalPlugins").unwrap().as_array().unwrap();
assert_eq!(plugins.len(), 1);
assert_eq!(plugins[0]["location"], tools.to_string_lossy().as_ref());
assert!(init.pointer("/typescript/tsserver/pluginPaths").is_none());
}
+16 -1
Переглянути файл
@@ -139,6 +139,9 @@ pub const TYPESCRIPT: &str = "typescript@6";
/// new pin here (the installed one then reads as missing and is offered again).
pub const CSS_MODULES_KIT: &str = "@css-modules-kit/[email protected]";
/// The tsserver plugin for CSS in styled-components / emotion templates, pinned likewise.
pub const TYPESCRIPT_STYLED_PLUGIN: &str = "@styled/[email protected]";
pub static TOOLS: &[ToolSpec] = &[
ToolSpec {
name: "unity-debug",
@@ -319,6 +322,17 @@ pub static TOOLS: &[ToolSpec] = &[
homepage: "https://github.com/mizdra/css-modules-kit",
needs: &[],
},
ToolSpec {
name: "typescript-styled-plugin",
display: "typescript-styled-plugin (tsserver plugin)",
kind: Plugin,
commands: &["@styled/typescript-styled-plugin"],
method: Method::Npm { packages: &[TYPESCRIPT_STYLED_PLUGIN] },
fallback: None,
version: V,
homepage: "https://github.com/styled-components/typescript-styled-plugin",
needs: &[],
},
ToolSpec {
name: "typescript-language-server",
display: "typescript-language-server",
@@ -1393,7 +1407,8 @@ pub static TOOLS: &[ToolSpec] = &[
];
/// Plugin tools and the tool that loads them.
pub const PLUGIN_HOSTS: &[(&str, &str)] = &[("lombok", "jdtls"), ("css-modules-kit", "vtsls")];
pub const PLUGIN_HOSTS: &[(&str, &str)] =
&[("lombok", "jdtls"), ("css-modules-kit", "vtsls"), ("typescript-styled-plugin", "vtsls")];
pub fn find(name: &str) -> Option<&'static ToolSpec> {
TOOLS.iter().find(|t| t.name == name)
+56 -6
Переглянути файл
@@ -8,6 +8,7 @@ use parking_lot::{Mutex, RwLock};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant, SystemTime};
/// Exclude globs from settings (`files.exclude`), e.g. `**/node_modules`.
@@ -97,6 +98,11 @@ pub(crate) struct GitignoreStack {
/// `.git/info/exclude` and the global excludes file, rooted at the repo root.
repo_level: RwLock<Vec<Gitignore>>,
cache: Mutex<HashMap<PathBuf, Option<Arc<Gitignore>>>>,
/// Bumped (under the `cache` lock) by every invalidation. A lookup that read the ignore
/// files before an invalidation doesn't store what it read: the watcher thread may be
/// matching a new file while a command rewrites `.gitignore` and invalidates, and its
/// older rules must not land in the cache after that.
generation: AtomicU64,
nested: Mutex<NestedRepos>,
}
@@ -127,7 +133,7 @@ impl GitignoreStack {
pub fn new(near: &Path) -> Self {
let repo_root = find_repo_root(near);
let repo_level = RwLock::new(Self::load_repo_level(repo_root.as_deref()));
Self { repo_root, repo_level, cache: Mutex::default(), nested: Mutex::default() }
Self { repo_root, repo_level, cache: Mutex::default(), generation: AtomicU64::new(0), nested: Mutex::default() }
}
/// [`new`](Self::new) for listing a directory over and over (expanding a tree, a slow share):
@@ -163,6 +169,7 @@ impl GitignoreStack {
repo_root: entry.repo_root.clone(),
repo_level: RwLock::new(entry.rules.clone()),
cache: Mutex::default(),
generation: AtomicU64::new(0),
nested: Mutex::default(),
}
}
@@ -217,6 +224,7 @@ impl GitignoreStack {
}
}
let mut cache = self.cache.lock();
self.generation.fetch_add(1, Ordering::Relaxed);
// Lookups always populate every ancestor, so no key below `dir` exists without `dir`.
if cache.contains_key(dir) {
cache.retain(|k, _| !k.starts_with(dir));
@@ -232,7 +240,9 @@ impl GitignoreStack {
for stack in self.nested.lock().by_root.values() {
stack.invalidate(dir);
}
self.cache.lock().remove(dir);
let mut cache = self.cache.lock();
self.generation.fetch_add(1, Ordering::Relaxed);
cache.remove(dir);
}
/// Returns the shared `GitignoreStack` of the nested repository enclosing `dir`, if any.
@@ -273,6 +283,7 @@ impl GitignoreStack {
repo_root: Some(root),
repo_level,
cache: Mutex::default(),
generation: AtomicU64::new(0),
nested: Mutex::default(),
})
})
@@ -281,9 +292,13 @@ impl GitignoreStack {
}
fn matcher_for(&self, dir: &Path) -> Option<Arc<Gitignore>> {
if let Some(cached) = self.cache.lock().get(dir) {
return cached.clone();
}
let generation = {
let cache = self.cache.lock();
if let Some(cached) = cache.get(dir) {
return cached.clone();
}
self.generation.load(Ordering::Relaxed)
};
let mut builder = GitignoreBuilder::new(dir);
let mut any = false;
for name in [".gitignore", ".ignore"] {
@@ -307,7 +322,10 @@ impl GitignoreStack {
} else {
None
};
self.cache.lock().insert(dir.to_path_buf(), matcher.clone());
let mut cache = self.cache.lock();
if self.generation.load(Ordering::Relaxed) == generation {
cache.insert(dir.to_path_buf(), matcher.clone());
}
matcher
}
@@ -476,6 +494,38 @@ mod tests {
assert!(Arc::ptr_eq(&nested, stack.nested.lock().by_root.get(&repo).unwrap()));
}
#[test]
fn a_lookup_racing_an_invalidation_does_not_cache_the_older_rules() {
// The watcher thread matches new files while a command rewrites `.gitignore` and
// invalidates; whatever it read before the rewrite must not outlive the invalidation.
// A long file keeps the reader busy building its matcher, widening the window.
let tmp = tempfile::tempdir().unwrap();
let root = dunce::canonicalize(tmp.path()).unwrap();
std::fs::create_dir(root.join(".git")).unwrap();
let filler: String = (0..20_000).map(|n| format!("generated-{n}/\n")).collect();
let stack = Arc::new(GitignoreStack::new(&root));
for i in 0..20 {
let name = format!("f{i}.tmp-ignore");
std::fs::write(root.join(".gitignore"), &filler).unwrap();
stack.invalidate(&root);
let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
let reader = {
let (stack, stop, path) = (stack.clone(), stop.clone(), root.join(&name));
std::thread::spawn(move || {
while !stop.load(Ordering::Relaxed) {
stack.is_ignored(&path, false);
}
})
};
std::thread::sleep(Duration::from_millis(5));
std::fs::write(root.join(".gitignore"), format!("{filler}{name}\n")).unwrap();
stack.invalidate(&root);
stop.store(true, Ordering::Relaxed);
reader.join().unwrap();
assert!(stack.is_ignored(&root.join(&name), false), "round {i} kept the older rules");
}
}
#[test]
fn a_repository_created_inside_the_workspace_becomes_a_boundary() {
let tmp = tempfile::tempdir().unwrap();
+1 -1
Переглянути файл
@@ -115,7 +115,7 @@ The debugger adds attach-only types such as **Remote JVM Debug**, **Go Remote**,
### Common fields
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Only Python configurations can be debugged on a run target; see [Python debugging](/en/languages/python#debugging). See [SSH](/en/guide/remote/ssh).
- **Run on**: the local machine, or an SSH host defined in **Settings › Build, Execution, Deployment › Run Targets**. Python and Node.js configurations can be debugged on a run target (Node.js run with tsx not yet); see [Python debugging](/en/languages/python#debugging) and [JavaScript debugging](/en/languages/javascript#debugging). See [SSH](/en/guide/remote/ssh).
- **Working directory**: relative to the project root; empty means the project root. It may use the path macros `$PROJECT_DIR$`, `$ContentRoot$`, `$MODULE_DIR$`, `$MODULE_WORKING_DIR$` and `$USER_HOME$`, expanded when the configuration starts, so a shared configuration works on every machine.
- **Environment variables**: `VAR=value` pairs separated by `;`. The list button opens the **Environment Variables** dialog, where **Include system environment variables** can be turned off.
- **Debug adapter**: which debugger **Debug** uses for this configuration (for example `debugpy`, `js-debug`, `codelldb`, `delve`).
+4
Переглянути файл
@@ -32,6 +32,10 @@ clangd needs the flags each file is compiled with. Without them it guesses, and
clangd looks for `compile_commands.json` in the file's parent directories and in a `build/` subdirectory of each. If your build directory has another name (for example `cmake-build-debug` from a CMake profile), add a `.clangd` file with `CompileFlags: { CompilationDatabase: cmake-build-debug }` or copy or link the file to the project root.
</Tip>
### Header and source
**Switch Header/Source** (in Find Action; `F10`, `⌥O` / `Alt+O` in the VS Code keymaps) opens the counterpart of the current file: `Foo.m` or `Foo.cpp` from `Foo.h`, and back. It asks clangd first (`textDocument/switchSourceHeader`, which also finds a source file in another folder). When clangd is not running for the file or has no answer, it opens a project file with the same name and a counterpart extension, preferring the same folder. **Related Symbol…** (`⌃⌘↑` / `Ctrl+Alt+Home`) lists every match by name instead.
### Apple's clangd
The `clangd` that ships with Xcode and the Command Line Tools does not run clang-tidy. When a project has a `.clang-tidy` file and the IDE is using Apple's clangd, it shows a warning with an **Install** button that installs the LLVM build instead.
+1
Переглянути файл
@@ -121,6 +121,7 @@ Cypress runs report through Cypress's built-in `teamcity` reporter unless the co
Debugging uses the JavaScript Debugger (vscode-js-debug); if it is missing, the first debug session offers to install it.
- **Debug** works for npm script configurations, Node.js files and `deno run` / `deno test`. Child processes are attached automatically.
- A Node.js configuration or a `.js` / `.ts` file run on an SSH, Docker or Compose run target is debugged there: Node starts with `--inspect-brk` on a free port (published from the container on this machine's loopback interface, or forwarded through the SSH connection) and the debugger attaches as **Attach to Node.js** does, with the project folder mapped onto the target's. The interpreter must be `node`, and the configuration's Node options are kept. For TypeScript, add `--experimental-strip-types` to the Node options: tsx (`tsx`, `npx tsx`, `node --import tsx`) can't be debugged on a run target yet, because the program does not start once the debugger attaches. npm script configurations can only be run on a target.
- **Attach to Node.js** is a run configuration type for a process started with `--inspect` on this or another machine (default port 9229), with local and remote root mapping. With **Reconnect automatically** on, the session waits while the process restarts (nodemon, `node --watch`, `tsx watch`) and attaches to it again with the same breakpoints.
- **Attach to Process…** in the Run menu lists running Node.js processes.
- **JavaScript Debug** is a run configuration type that opens a URL in Chrome or Edge and debugs the page's JavaScript and TypeScript through source maps. Start the page's server first (for example with the `dev` npm script); **Web root** is the folder the URL serves, the project root by default.
+1 -1
Переглянути файл
@@ -111,7 +111,7 @@ description: "创建、编辑和启动运行配置,从装订区运行代码,
### 通用字段
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上只能调试 Python 配置,见 [Python 调试](/zh/languages/python#调试)。参见 [SSH](/zh/guide/remote/ssh)。
- **运行于**:本地计算机,或在 **设置 › 构建、执行、部署 › 运行目标** 中添加的 SSH 主机。运行目标上可以调试 Python 和 Node.js 配置(用 tsx 运行的 Node.js 暂不支持),见 [Python 调试](/zh/languages/python#调试) 与 [JavaScript 调试](/zh/languages/javascript#调试)。参见 [SSH](/zh/guide/remote/ssh)。
- **工作目录**:相对于项目根目录,留空即项目根目录。可以使用路径宏 `$PROJECT_DIR$`、`$ContentRoot$`、`$MODULE_DIR$`、`$MODULE_WORKING_DIR$` 和 `$USER_HOME$`,在配置启动时展开,因此共享的配置在每台机器上都能用。
- **环境变量**:`VAR=value` 形式,用 `;` 分隔。点旁边的列表按钮打开“环境变量”对话框,可以关闭 **包括系统环境变量**。
- **调试适配器**:按“调试”时这个配置使用哪个调试器(如 `debugpy`、`js-debug`、`codelldb`、`delve`)。
+4
Переглянути файл
@@ -32,6 +32,10 @@ clangd 需要知道每个文件的编译参数,否则只能猜测,常见的
clangd 会在文件的各级父目录以及这些目录下的 `build/` 子目录里查找 `compile_commands.json`。如果构建目录叫别的名字(例如 CMake 配置生成的 `cmake-build-debug`),在项目根目录添加一个 `.clangd`,写上 `CompileFlags: { CompilationDatabase: cmake-build-debug }`,或者把该文件复制或链接到项目根目录。
</Tip>
### 头文件与源文件
**切换头文件/源文件**(可在“查找操作”中运行;`F10`,VS Code 键位下为 `⌥O` / `Alt+O`)打开当前文件对应的另一半:在 `Foo.h` 中打开 `Foo.m` 或 `Foo.cpp`,反之亦然。它先询问 clangd(`textDocument/switchSourceHeader`,能找到放在其他文件夹里的源文件);clangd 没有为该文件运行或没有给出结果时,打开项目中同名、扩展名对应的文件,优先同一文件夹。**相关符号…**(`⌃⌘↑` / `Ctrl+Alt+Home`)则按名称列出所有匹配。
### Apple 自带的 clangd
Xcode 和 Command Line Tools 自带的 `clangd` 不运行 clang-tidy。如果项目里有 `.clang-tidy`,而 IDE 正在使用 Apple 的 clangd,会弹出提示并提供 **安装** 按钮,改装 LLVM 版本的 clangd。
+1
Переглянути файл
@@ -122,6 +122,7 @@ Cypress 运行时使用 Cypress 内置的 `teamcity` 报告器(配置里指定
调试使用 JavaScript 调试器(vscode-js-debug);未安装时,第一次调试会提示安装。
- **调试** 适用于 npm 脚本配置、Node.js 文件以及 `deno run` / `deno test`,子进程会自动附加。
- 在 SSH、Docker 或 Compose 运行目标上运行的 Node.js 配置或 `.js` / `.ts` 文件,会在目标上调试:Node 以 `--inspect-brk` 在空闲端口上启动(容器中的端口发布到本机回环地址,SSH 主机上的端口经 SSH 连接转发),调试器像 **附加到 Node.js** 一样附加,并把项目文件夹映射到目标上的项目文件夹。解释器须为 `node`,配置中的 Node 选项保持不变。TypeScript 请在 Node 选项中加上 `--experimental-strip-types`:tsx(`tsx`、`npx tsx`、`node --import tsx`)暂时不能在运行目标上调试,因为调试器附加后程序不会开始运行。npm 脚本配置在运行目标上只能运行。
- **附加到 Node.js** 是一种运行配置类型,用于附加到本机或其他机器上以 `--inspect` 启动的进程(默认端口 9229),可设置本地与远程根目录映射。勾选 **自动重新连接** 后,进程重启时(nodemon、`node --watch`、`tsx watch`)会话会等待,并以相同的断点重新附加。
- 运行菜单中的 **附加到进程…** 会列出正在运行的 Node.js 进程。
- **JavaScript 调试** 是一种运行配置类型:在 Chrome 或 Edge 中打开一个 URL,通过 source map 调试页面中的 JavaScript 和 TypeScript。先启动页面的服务(例如 `dev` npm 脚本);**Web 根目录** 是该 URL 对应的文件夹,默认为项目根目录。
+1
Переглянути файл
@@ -459,6 +459,7 @@ lsp_snapshot_completion trusted project_host bin
lsp_snapshot_diagnostics trusted project_host bindings async
lsp_source_action_text trusted project_host bindings async
lsp_stop trusted project_host bindings async
lsp_switch_source_header trusted project_host bindings async
lsp_type_hierarchy trusted project_host bindings async
lsp_virtual_document trusted project_host bindings async
lsp_workspace_symbols trusted project_host bindings async
+6
Переглянути файл
@@ -1210,6 +1210,12 @@ export const commands = {
lspSourceActionText: (path: string, text: string, kind: string, request: RequestId) => typedError<TextEdit[], IdeError>(__TAURI_INVOKE("lsp_source_action_text", { path, text, kind, request })),
/** Stops a language server; it starts again when a file it serves is opened. */
lspStop: (server: ServerId) => typedError<null, IdeError>(__TAURI_INVOKE("lsp_stop", { server })),
/**
* The header of the document's source file or the source of its header (C, C++,
* Objective-C) as clangd finds it; `None` without clangd or an answer. Cancel with
* `cancel_request(request)`.
*/
lspSwitchSourceHeader: (request: RequestId, doc: DocId) => typedError<string | null, IdeError>(__TAURI_INVOKE("lsp_switch_source_header", { request, doc })),
lspTypeHierarchy: (doc: DocId, pos: Pos, direction: HierarchyDirection) => typedError<HierarchyItem[], IdeError>(__TAURI_INVOKE("lsp_type_hierarchy", { doc, pos, direction })),
/**
* Contents of a read-only language-server document, including JDT library
+10 -1
Переглянути файл
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { counterpartNames, headerSourceItems, rankCounterparts } from "./headerSource";
import { counterpartNames, headerSourceItems, rankCounterparts, switchHeaderSource } from "./headerSource";
describe("header / source counterparts", () => {
it("names the other side by stem", () => {
@@ -28,4 +28,13 @@ describe("header / source counterparts", () => {
const items = await headerSourceItems("/p/foo.c", async (n) => files[n] ?? []);
expect(items).toEqual([{ path: "/p/foo.h", group: "Header" }]);
});
it("switches to clangd's answer, else the file of the same name", async () => {
const files: Record<string, string[]> = { "Foo.m": ["/p/Foo.m"] };
const named = async (n: string) => files[n] ?? [];
expect(await switchHeaderSource("/p/Foo.h", async () => "/p/src/Foo.mm", named)).toBe("/p/src/Foo.mm");
expect(await switchHeaderSource("/p/Foo.h", async () => null, named)).toBe("/p/Foo.m");
expect(await switchHeaderSource("/p/Foo.h", () => Promise.reject(new Error("no clangd")), named)).toBe("/p/Foo.m");
expect(await switchHeaderSource("/p/Bar.h", async () => null, named)).toBeNull();
});
});
+14
Переглянути файл
@@ -51,3 +51,17 @@ export async function headerSourceItems(
const found = await Promise.all(counterpart.names.map((n) => findNamed(n).catch(() => [] as string[])));
return rankCounterparts(path, found.flat()).map((p) => ({ path: p, group: counterpart.group }));
}
/**
* Switch Header/Source: `ask` (clangd's `textDocument/switchSourceHeader`) first, else the
* nearest file of the same name on the other side; `null` when there is none.
*/
export async function switchHeaderSource(
path: string,
ask: () => Promise<string | null>,
findNamed: (name: string) => Promise<string[]>,
): Promise<string | null> {
const fromServer = await ask().catch(() => null);
if (fromServer) return fromServer;
return (await headerSourceItems(path, findNamed))[0]?.path ?? null;
}
+24 -3
Переглянути файл
@@ -1,5 +1,6 @@
/**
* Navigate › Test / Test Subject (⇧⌘T), Super Method (⌘U), Related Symbol (⌃⌘↑), Next /
* Navigate › Test / Test Subject (⇧⌘T), Super Method (⌘U), Related Symbol (⌃⌘↑), Header/Source
* (F10, C-family files), Next /
* Previous Method (⌃⇧↓ / ⌃⇧↑). Editor-side like editor/lsp (whose popups it uses);
* the file templates are reached through the `templates.newFromTemplate` action.
*/
@@ -12,7 +13,7 @@ import { caretAnchor, openPopup } from "@/editor/lsp/popupStore";
import { dedupeLocations, locationItems, navigateTo } from "@/editor/lsp/navigation";
import { showHint } from "@/editor/lsp/hint";
import { registerActions, executeAction, type Action } from "@/platform/actions";
import { call, commands, isCancelled, type Location, type OutlineItem, type Pos } from "@/platform/ipc";
import { call, commands, isCancelled, nextRequestId, type Location, type OutlineItem, type Pos } from "@/platform/ipc";
import { basename, relativePath, useProject } from "@/platform/project";
import { currentRoots } from "@/platform/projectRoots";
import { isVirtualUri } from "@/platform/virtualDocs";
@@ -22,7 +23,7 @@ import { registerRelatedProvider, relatedItems } from "@/editor/relatedProviders
import { createTestFor, gotoTestOrSubject, type TestNavDeps } from "./gotoTest";
import { componentFileItems } from "./componentFiles";
import { createPythonTest } from "./pythonCreateTest";
import { headerSourceItems } from "./headerSource";
import { headerSourceItems, switchHeaderSource } from "./headerSource";
import { stubRelatedItems } from "./pythonStubs";
import { projectPythonHierarchy, pythonSuperDeps } from "./pythonHierarchy";
import { baseName, memberAt, methodStop, superMethods, topLevelTypeAt, type SuperDeps } from "./structureNav";
@@ -279,6 +280,21 @@ async function gotoStub(view: EditorView) {
await openCodeLocation(item.path, item.line === undefined ? undefined : { line: item.line, col: item.col ?? 0 });
}
const C_FAMILY = ["c", "cpp", "objective-c", "objective-cpp"].map((id) => `editorLangId == ${id}`).join(" || ");
/** Navigate › Header/Source: clangd's counterpart, else a file of the same name. */
async function gotoHeaderSource(view: EditorView) {
const ctx = docOf(view);
if (!ctx || isVirtualUri(ctx.path)) return;
const target = await switchHeaderSource(
ctx.path,
() => lspRequest(() => commands.lspSwitchSourceHeader(nextRequestId(), ctx.doc)),
findFilesNamed,
);
if (target) await openCodeLocation(target);
else showHint(view, tx("No header or source file found"), { tone: "error" });
}
export function registerNavigationActions(): () => void {
const unregisterHeaders = registerRelatedProvider((ctx) => headerSourceItems(ctx.path, findFilesNamed));
const unregisterComponents = registerRelatedProvider((ctx) => componentFileItems(ctx.path, ctx.text, listFiles));
@@ -310,6 +326,11 @@ export function registerNavigationActions(): () => void {
"stories",
],
}),
editorAction("navigate.headerSource", "Switch Header/Source", gotoHeaderSource, {
when: `${EDITOR_WHEN} && (${C_FAMILY})`,
keyWhen: C_FAMILY,
keywords: ["header", "source", "counterpart", "clangd"],
}),
editorAction("navigate.pythonStub", "Stub / Implementation", gotoStub, {
when: `${EDITOR_WHEN} && editorLangId == python`,
keywords: ["go to stub", "go to implementation", "pyi", "type stub"],
+26 -5
Переглянути файл
@@ -34,8 +34,8 @@ const {
phpRemoteType,
jdwpAgentArgs,
xdebugCommand,
isPythonAttachTarget,
pythonAttachConfig,
isTargetAttach,
targetAttachConfig,
remoteAttachConfig,
remoteJvmTarget,
remoteWaitingNote,
@@ -135,9 +135,9 @@ describe("remote attach requests", () => {
it("a Python program in a container: the project root maps onto its folder there", () => {
const target = { name: "app", adapter: "debugpy" as const, hostName: "127.0.0.1", port: 41234, remoteRoot: "/app" };
expect(isPythonAttachTarget({ ...target, process: 3 })).toBe(true);
expect(isPythonAttachTarget({ name: "app", module: "", hostName: "h", port: 5005 })).toBe(false);
const l = pythonAttachConfig(target, "/p");
expect(isTargetAttach({ ...target, process: 3 })).toBe(true);
expect(isTargetAttach({ name: "app", module: "", hostName: "h", port: 5005 })).toBe(false);
const l = targetAttachConfig(target, "/p");
expect(l).toMatchObject({ name: "app", adapter: "debugpy", request: "attach", cwd: "/p" });
expect(JSON.parse(l.extraJson!)).toMatchObject({
debugServer: "127.0.0.1:41234",
@@ -145,6 +145,27 @@ describe("remote attach requests", () => {
});
});
it("a Node.js program on a run target: js-debug attaches to its inspector like Attach to Node.js", () => {
const target = {
name: "app",
adapter: "js-debug" as const,
hostName: "127.0.0.1",
port: 41234,
remoteRoot: "/app",
};
expect(isTargetAttach(target)).toBe(true);
const l = targetAttachConfig(target, "/p");
expect(l).toMatchObject({ name: "app", adapter: "js-debug", request: "attach", cwd: "/p" });
expect(JSON.parse(l.extraJson!)).toMatchObject({
type: "pwa-node",
address: "127.0.0.1",
port: 41234,
localRoot: "/p",
remoteRoot: "/app",
continueOnAttach: true,
});
});
it("Python remote connects to debugpy --listen with pathMappings", () => {
const l = remoteAttachConfig(
configOf(pythonRemoteType, { host: "::1", localRoot: "svc", remoteRoot: "/app" }),
+5 -5
Переглянути файл
@@ -73,9 +73,9 @@ import { DEVTOOLS_WINDOWS, devToolsUrl, refreshDevTools, WIDGET_PREVIEW_WINDOW }
import { debugUnsupportedReason, launchConfigFor, withEnvFiles } from "./launch";
import { attachConfig } from "./attach";
import {
isPythonAttachTarget,
isTargetAttach,
isRemoteConfig,
pythonAttachConfig,
targetAttachConfig,
REMOTE_JVM,
remoteAttachConfig,
remoteJvmTarget,
@@ -724,8 +724,8 @@ export function registerDebugActions(): () => void {
title: "Attach Debugger",
category: "Debug",
hidden: true,
// Also debugpy to a Python program in a run target's container
// (arg: { name, adapter: "debugpy", hostName, port, remoteRoot, process }).
// Also debugpy or js-debug to a Python or Node.js program on a run target
// (arg: { name, adapter: "debugpy" | "js-debug", hostName, port, remoteRoot, process }).
// Also a process from Attach to Process (arg: { attachable, process, runConfig }).
description:
"Attach the Java debugger to a JVM listening for JDWP (arg: { name, module, hostName, port, process })",
@@ -737,7 +737,7 @@ export function registerDebugActions(): () => void {
if (!root) return;
let launch: LaunchConfig;
if (isAttachableTarget(arg)) launch = await attachConfig(arg.attachable, root);
else if (isPythonAttachTarget(arg)) launch = pythonAttachConfig(arg, root);
else if (isTargetAttach(arg)) launch = targetAttachConfig(arg, root);
else if (isJavaAttachTarget(arg)) launch = await javaAttachConfig(arg, root);
else return;
const process = (arg.process ?? null) as RunId | null;
+22 -12
Переглянути файл
@@ -430,27 +430,37 @@ function debugpyAttach(
});
}
/** A Python program debugged on a run target (SSH host or container), waiting for the debugger (Run's `debugOnTarget`). */
export interface PythonAttachTarget {
/**
* A Python or Node.js program debugged on a run target (SSH host or container), waiting for the
* debugger (Run's `debugOnTarget`): debugpy, or Node's inspector for js-debug.
*/
export interface TargetAttach {
name: string;
adapter: "debugpy";
adapter: "debugpy" | "js-debug";
hostName: string;
port: number;
/** The project folder in the container. */
/** The project folder on the target. */
remoteRoot: string;
}
export function isPythonAttachTarget(
arg: unknown,
): arg is PythonAttachTarget & { process?: number | null; runConfig?: RunConfig } {
export function isTargetAttach(arg: unknown): arg is TargetAttach & { process?: number | null; runConfig?: RunConfig } {
if (!arg || typeof arg !== "object") return false;
const a = arg as Partial<PythonAttachTarget>;
return a.adapter === "debugpy" && typeof a.port === "number" && typeof a.remoteRoot === "string";
const a = arg as Partial<TargetAttach>;
return (
(a.adapter === "debugpy" || a.adapter === "js-debug") &&
typeof a.port === "number" &&
typeof a.remoteRoot === "string"
);
}
/** Attach request of a `PythonAttachTarget`: the project root maps onto the container's folder. */
export function pythonAttachConfig(target: PythonAttachTarget, root: string): LaunchConfig {
return debugpyAttach(target.name, root, target.hostName, target.port, { local: root, remote: target.remoteRoot });
/** Attach request of a `TargetAttach`: the project root maps onto the target's folder, as in Attach to Node.js. */
export function targetAttachConfig(target: TargetAttach, root: string): LaunchConfig {
if (target.adapter === "debugpy")
return debugpyAttach(target.name, root, target.hostName, target.port, { local: root, remote: target.remoteRoot });
const params = { host: target.hostName, port: String(target.port), remoteRoot: target.remoteRoot };
const launch = remoteAttachConfig({ name: target.name, kind: NODE_REMOTE, params } as unknown as RunConfig, root)!;
// The program waits at its first line (`--inspect-brk`) only until the breakpoints are set.
return { ...launch, extraJson: JSON.stringify({ ...JSON.parse(launch.extraJson!), continueOnAttach: true }) };
}
/**
+140 -2
Переглянути файл
@@ -213,7 +213,10 @@ describe("remote debugging", () => {
await executeAction("run.debugConfig", remote.id);
expect(startConfig).not.toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Only Python can be debugged on SSH run targets", level: "warning" }),
expect.objectContaining({
title: "Only Python and Node.js can be debugged on SSH run targets",
level: "warning",
}),
);
});
@@ -251,6 +254,38 @@ describe("remote debugging", () => {
}
});
it("debugs Node.js on an SSH host through the forwarded port, waiting as long as the upload takes", async () => {
const attach = vi.fn();
const off = registerActions([{ id: "debug.attach", title: "Attach", run: ({ arg }) => attach(arg) }]);
vi.useFakeTimers();
try {
const node = cfg("app", {
target: "box",
kind: "node",
command: "node",
args: ["--experimental-strip-types", "main.ts"],
debugAdapter: "js-debug",
});
useRun.setState({ configs: [node], loaded: true });
ipc.runStart.mockResolvedValueOnce(ok);
await executeAction("run.debugConfig", node.id);
await vi.advanceTimersByTimeAsync(300_000);
expect(ipc.runStop).not.toHaveBeenCalled();
const channel = ipc.runStart.mock.calls.at(-1)![1] as { onmessage: (m: unknown) => void };
channel.onmessage({ kind: "system", text: "Starting Node.js for the debugger, project folder /home/me/app\n" });
channel.onmessage({ kind: "stderr", text: "Debugger listening on ws://127.0.0.1:50123/0a1b\n" });
await vi.waitFor(() =>
expect(attach).toHaveBeenCalledWith(
expect.objectContaining({ adapter: "js-debug", port: 50123, remoteRoot: "/home/me/app" }),
),
);
expect(notify).not.toHaveBeenCalled();
} finally {
vi.useRealTimers();
off();
}
});
it("stops an SSH debug run whose program never announces debugpy", async () => {
const off = registerActions([{ id: "debug.attach", title: "Attach", run: () => undefined }]);
vi.useFakeTimers();
@@ -400,13 +435,116 @@ describe("remote debugging", () => {
expect(notify).not.toHaveBeenCalled();
});
it("starts Node.js with its inspector and attaches js-debug with the project folder mapped", async () => {
const node = cfg("app", {
target: "py",
kind: "node",
command: "node",
args: ["main.js"],
debugAdapter: "js-debug",
});
useRun.setState({ configs: [node], loaded: true });
ipc.runStart.mockResolvedValueOnce(ok);
await executeAction("run.debugConfig", node.id);
expect(startConfig).not.toHaveBeenCalled();
expect(ipc.runStart).toHaveBeenCalledWith(
expect.objectContaining({ id: "app", params: { targetDebug: "true" } }),
expect.anything(),
expect.any(Number),
);
const channel = ipc.runStart.mock.calls.at(-1)![1] as { onmessage: (m: unknown) => void };
// Node's line alone, before the IDE's line naming the folder, is not enough.
channel.onmessage({ kind: "stderr", text: "Debugger listening on ws://0.0.0.0:41234/0a1b\n" });
channel.onmessage({ kind: "system", text: "Starting Node.js for the debugger, project folder /app\n" });
expect(attach).not.toHaveBeenCalled();
channel.onmessage({ kind: "stderr", text: "Debugger listening on ws://0.0.0.0:41234/0a1b\n" });
await vi.waitFor(() =>
expect(attach).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
adapter: "js-debug",
hostName: "127.0.0.1",
port: 41234,
remoteRoot: "/app",
process: 3,
}),
),
);
expect(notify).not.toHaveBeenCalled();
});
it("stops a Node.js container that never opens its inspector", async () => {
vi.useFakeTimers();
try {
const node = cfg("app", {
target: "py",
kind: "node",
command: "node",
args: ["main.js"],
debugAdapter: "js-debug",
});
useRun.setState({ configs: [node], loaded: true });
ipc.runStart.mockResolvedValueOnce(ok);
await executeAction("run.debugConfig", node.id);
await vi.advanceTimersByTimeAsync(120_000);
expect(ipc.runStop).toHaveBeenCalledWith(3);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
title: "Cannot start container debugging",
body: "The Node.js inspector did not become ready within 120 seconds. Check the Run console.",
}),
);
} finally {
vi.useRealTimers();
}
});
it("reports a Node.js container that exits before its inspector is ready", async () => {
vi.useFakeTimers();
try {
const node = cfg("app", {
target: "py",
kind: "node",
command: "node",
args: ["main.js"],
debugAdapter: "js-debug",
});
useRun.setState({ configs: [node], loaded: true });
ipc.runStart.mockResolvedValueOnce(ok);
await executeAction("run.debugConfig", node.id);
onRunExited(3, 1);
await vi.advanceTimersByTimeAsync(120_000);
expect(attach).not.toHaveBeenCalled();
expect(notify).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({ body: expect.stringContaining("exited before the Node.js inspector") }),
);
} finally {
vi.useRealTimers();
}
});
it("keeps npm scripts blocked", async () => {
const npm = cfg("app", {
target: "py",
kind: "npm",
command: "npm",
args: ["run", "dev"],
debugAdapter: "js-debug",
});
useRun.setState({ configs: [npm], loaded: true });
await executeAction("run.debugConfig", npm.id);
expect(ipc.runStart).not.toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Only Python and Node.js can be debugged in containers" }),
);
});
it("refuses other debuggers", async () => {
const go = cfg("app", { target: "py", debugAdapter: "delve" });
useRun.setState({ configs: [go], loaded: true });
await executeAction("run.debugConfig", go.id);
expect(ipc.runStart).not.toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ title: "Only Python can be debugged in containers", level: "warning" }),
expect.objectContaining({ title: "Only Python and Node.js can be debugged in containers", level: "warning" }),
);
});
});
+10 -5
Переглянути файл
@@ -78,14 +78,19 @@ export function containerTarget(
return target && inContainer(target) ? target.id : null;
}
/** A Python configuration on an SSH, Docker or Compose target: debugged there (`debugOnTarget`). */
/**
* A Python configuration, or a Node.js one (a Node.js configuration or a `.js` / `.ts` file run; not
* npm scripts, whose child processes would need js-debug's auto attach there), on an SSH, Docker
* or Compose target: debugged there (`debugOnTarget`).
*/
export function targetDebuggable(config: RunConfig, targets: readonly RuntimeRunTarget[] = allRunTargets()): boolean {
const target = targetOf(config, targets);
return !!target && (target.kind === "ssh" || inContainer(target)) && config.debugAdapter === "debugpy";
const supported = config.debugAdapter === "debugpy" || (config.debugAdapter === "js-debug" && config.kind === "node");
return !!target && (target.kind === "ssh" || inContainer(target)) && supported;
}
/**
* Debugging on run targets is supported for Python on SSH and container targets: tells
* Debugging on run targets is supported for Python and Node.js on SSH and container targets: tells
* so (offering Run) and returns true when `config` can't be debugged where it runs.
*/
export function remoteDebugBlocked(config: RunConfig, targets: readonly RuntimeRunTarget[] = allRunTargets()): boolean {
@@ -99,9 +104,9 @@ export function remoteDebugBlocked(config: RunConfig, targets: readonly RuntimeR
key: "run.remoteDebug",
title:
where && inContainer(where)
? "Only Python can be debugged in containers"
? "Only Python and Node.js can be debugged in containers"
: where?.kind === "ssh"
? "Only Python can be debugged on SSH run targets"
? "Only Python and Node.js can be debugged on SSH run targets"
: "Debugging on run targets is not supported",
body: txTemplate(
`'${config.name}' runs on ${target}. Run it, or choose “Local machine” under “Run on” to debug it.`,
+7
Переглянути файл
@@ -144,6 +144,8 @@ interface SessionRuntime {
generation: number;
/** Called with every complete output line (e.g. waiting for a JDWP agent). */
lineListeners: Array<(text: string) => void>;
/** Called with every line the IDE printed itself (`OutputChunk::System`). */
systemListeners: Array<(text: string) => void>;
/** Called with output as shown (the Debug console of a debugger attached to this process). */
outputListeners: Set<OutputListener>;
/** Called once the process exited (run executors: collect a coverage report…). */
@@ -840,6 +842,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
if (pluginTests && kind !== "system") pluginTests.feed(text);
if (parser && tests && kind !== "system" && !(kind === "stdout" && stdout)) applyTests(parser.feed(text));
if (kind !== "system") for (const l of runtime.lineListeners) l(text);
else for (const l of runtime.systemListeners) l(text);
if (kind !== "system") runtime.dotnetReports?.feed(text);
if (kind !== "system") runtime.xcodeReports?.feed(text);
},
@@ -849,6 +852,7 @@ function newRuntime(config: RunConfig): SessionRuntime {
flushedAt: -Infinity,
generation: 0,
lineListeners: [],
systemListeners: [],
outputListeners: new Set(),
input: "",
terminal: null,
@@ -931,6 +935,8 @@ interface StartRunOptions {
launch?: RunConfig;
/** Every output line of this run. */
onLine?: (text: string) => void;
/** Every line the IDE printed in this run's console (the command line, a debug run's notes). */
onSystemLine?: (text: string) => void;
/** The process exited. */
onExit?: (exitCode: number | null, stopped: boolean) => void;
/** Before launch tasks already ran (or must not run). */
@@ -1101,6 +1107,7 @@ async function startRunIn(
check?.own(sessionId);
check?.signal.throwIfAborted();
if (options.onLine) rt.lineListeners.push(options.onLine);
if (options.onSystemLine) rt.systemListeners.push(options.onSystemLine);
let browserOpened = false;
rt.lineListeners.push((line) => {
if (config.kind === "tomcat" && /Server startup in/.test(line)) {
+11 -1
Переглянути файл
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import type { RunConfig } from "@/platform/ipc";
import { debugpyReady, targetDebugLaunch } from "./targetDebug";
import { debugpyReady, inspectorPort, nodeDebugFolder, targetDebugLaunch } from "./targetDebug";
describe("debugging on run targets", () => {
it("reads the port and the project folder from the bootstrap's line", () => {
@@ -13,6 +13,16 @@ describe("debugging on run targets", () => {
expect(debugpyReady("waiting for the debugger on port 41234")).toBeNull();
});
it("reads the project folder from the IDE's line and the port from Node's", () => {
expect(nodeDebugFolder("Starting Node.js for the debugger, project folder /workspaces/my app\r")).toBe(
"/workspaces/my app",
);
expect(nodeDebugFolder("debugpy is starting")).toBeNull();
expect(inspectorPort("Debugger listening on ws://0.0.0.0:41234/9f1c2e3a-0000\r")).toBe(41234);
expect(inspectorPort("Debugger listening on ws://[::1]:9229/abc")).toBe(9229);
expect(inspectorPort("For help, see: https://nodejs.org/en/docs/inspector")).toBeNull();
});
it("asks the backend for a debug run, keeping the configuration's parameters", () => {
const config = { id: "a", params: { module: "app" } } as unknown as RunConfig;
expect(targetDebugLaunch(config).params).toEqual({ module: "app", targetDebug: "true" });
+54 -20
Переглянути файл
@@ -1,9 +1,10 @@
/**
* Debugging Python on run targets: the run starts the program under debugpy (the bootstrap
* of `ide_remote::docker`) in a new container, or on the SSH host with an SSH forward of
* the port, and the bootstrap prints the port once debugpy listens; the debugger then
* attaches like a Python Remote Debug configuration, with the project folder mapped.
* Output stays in the Run tab; stopping the debugger stops the program.
* Debugging Python and Node.js on run targets: the run starts the program under debugpy (the
* bootstrap of `ide_remote::docker`), or Node.js with `--inspect-brk`, in a new container, or on
* the SSH host with an SSH forward of the port. Once debugpy listens the bootstrap prints the
* port; Node prints its own `Debugger listening` line, after the IDE's line naming the project
* folder there. The debugger then attaches like Python Remote Debug or Attach to Node.js, with
* the project folder mapped. Output stays in the Run tab; stopping the debugger stops the program.
*/
import { executeAction } from "@/platform/actions";
import type { RunConfig } from "@/platform/ipc";
@@ -19,6 +20,12 @@ const STARTING = "debugpy is starting";
/** The bootstrap's line (`ide_remote::docker::DEBUG_READY`). */
const READY = /^debugpy is waiting for the debugger on port (\d+), project folder (.+)$/;
/** The IDE's line before a Node.js debug run starts (`ide_remote::docker::NODE_DEBUG_FOLDER`). */
const NODE_FOLDER = "Starting Node.js for the debugger, project folder ";
/** Node's line once the inspector listens (`Debugger listening on ws://0.0.0.0:9229/<id>`). */
const INSPECTOR = /^Debugger listening on ws:\/\/(?:\[[^\]]*\]|[^/:]+):(\d+)\//;
interface Ready {
port: number;
remoteRoot: string;
@@ -30,17 +37,31 @@ export function debugpyReady(line: string): Ready | null {
return m ? { port: Number(m[1]), remoteRoot: m[2]! } : null;
}
/** `config` as the backend runs it for debugging: under debugpy, waiting for the debugger. */
/** The project folder on the target, from the IDE's line before a Node.js debug run. */
export function nodeDebugFolder(line: string): string | null {
const text = line.trim();
return text.startsWith(NODE_FOLDER) ? text.slice(NODE_FOLDER.length) : null;
}
/** The inspector's port, from Node's line once it listens. */
export function inspectorPort(line: string): number | null {
const m = INSPECTOR.exec(line.trim());
return m ? Number(m[1]) : null;
}
/** `config` as the backend runs it for debugging: under debugpy or with Node's inspector, waiting for the debugger. */
export function targetDebugLaunch(config: RunConfig): RunConfig {
return { ...config, params: { ...config.params, targetDebug: "true" } };
}
/** Runs `config` on its run target under debugpy and attaches the debugger. */
/** Runs `config` on its run target under debugpy (Node.js: with its inspector) and attaches the debugger. */
export async function debugOnTarget(config: RunConfig): Promise<void> {
const target = targetOf(config);
const container = !target || inContainer(target);
const node = config.debugAdapter === "js-debug";
let sessionId: string | null = null;
let ready: Ready | null = null;
let nodeFolder: string | null = null;
let done = false;
const pending: { timer?: ReturnType<typeof setTimeout>; unsubscribe?: () => void } = {};
const finish = () => {
@@ -63,7 +84,7 @@ export async function debugOnTarget(config: RunConfig): Promise<void> {
const runId = useRun.getState().sessions.find((s) => s.id === sessionId)?.runId ?? null;
void executeAction("debug.attach", {
name: config.name,
adapter: "debugpy",
adapter: node ? "js-debug" : "debugpy",
hostName: "127.0.0.1",
port,
remoteRoot,
@@ -75,13 +96,15 @@ export async function debugOnTarget(config: RunConfig): Promise<void> {
if (done || pending.timer) return;
pending.timer = setTimeout(() => {
fail(
container
? tx(
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.",
)
: tx(
"debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.",
),
node
? tx("The Node.js inspector did not become ready within 120 seconds. Check the Run console.")
: container
? tx(
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.",
)
: tx(
"debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.",
),
);
if (sessionId) void stopSession(sessionId);
}, 120_000);
@@ -92,12 +115,19 @@ export async function debugOnTarget(config: RunConfig): Promise<void> {
if (done) return;
// Over SSH the project and debugpy may be uploaded first, for as long as the link needs:
// the wait starts with the program.
if (line.trim() === STARTING) startTimer();
const parsed = debugpyReady(line);
if (!node && line.trim() === STARTING) startTimer();
const port = node && nodeFolder !== null ? inspectorPort(line) : null;
const parsed = node ? (port === null ? null : { port, remoteRoot: nodeFolder! }) : debugpyReady(line);
if (!parsed) return;
ready = parsed;
if (sessionId) attach(ready);
},
onSystemLine: (line) => {
const folder = node && !done ? nodeDebugFolder(line) : null;
if (folder === null) return;
nodeFolder = folder;
startTimer();
},
});
if (!session) return;
sessionId = session.id;
@@ -106,9 +136,13 @@ export async function debugOnTarget(config: RunConfig): Promise<void> {
if (!current || current.stopped || current.status === "failed") finish();
else if (!isLive(current))
fail(
container
? tx("The container exited before debugpy was ready. Check the Run console for errors.")
: tx("The program exited before debugpy was ready. Check the Run console for errors."),
node
? container
? tx("The container exited before the Node.js inspector was ready. Check the Run console for errors.")
: tx("The program exited before the Node.js inspector was ready. Check the Run console for errors.")
: container
? tx("The container exited before debugpy was ready. Check the Run console for errors.")
: tx("The program exited before debugpy was ready. Check the Run console for errors."),
);
};
pending.unsubscribe = useRun.subscribe(check);
+15 -6
Переглянути файл
@@ -43,17 +43,26 @@ afterEach(() => {
});
describe("Run Targets detail form", () => {
it("does not commit an uncommitted ports edit to the target selected while it is open", () => {
it("keeps a ports edit with the target it was made to when another target is selected", () => {
mount();
// An edit to odoo110's published ports that ListField has not committed yet.
// An edit to odoo110's published ports, still focused.
fireEvent.change(portsBox(), { target: { value: "8069" } });
// Selecting another target switches selection on mousedown, before the blur commits.
// Selecting another target switches selection on mousedown, before the field loses focus.
fireEvent.mouseDown(screen.getByRole("option", { name: /odoo170/ }));
fireEvent.blur(portsBox());
// odoo170 keeps its own ports; the uncommitted draft is not written over them.
// odoo170 keeps its own ports; the edit is not written over them.
expect(portsBox().value).toBe("9000:9000");
// And odoo110 still holds what it held before the edit was committed anywhere.
// And odoo110 holds the edit.
fireEvent.mouseDown(screen.getByRole("option", { name: /odoo110/ }));
expect(portsBox().value).toBe("8069:8069");
expect(portsBox().value).toBe("8069");
});
it("stages a ports edit before the field loses focus, so OK applies it", () => {
mount();
fireEvent.change(portsBox(), { target: { value: "8069:8069 8070:8070" } });
expect(portsBox().value).toBe("8069:8069 8070:8070");
const change = Object.values(useSettingsDialog.getState().staged).find((c) => c.key === "runTargets");
const targets = change?.value as Array<{ id: string; ports: string[] }> | undefined;
expect(targets?.find((t) => t.id === "odoo110")?.ports).toEqual(["8069:8069", "8070:8070"]);
});
});
+7 -6
Переглянути файл
@@ -263,7 +263,8 @@ function ListField({
hint?: string;
}) {
const id = useId();
// Edited as text; the list is stored once the field loses focus.
// Edited as text, which stays as typed while the field has focus; the list is stored on every change, so OK
// (Enter included) applies an edit that hasn't left the field.
const [draft, setDraft] = useState<string | null>(null);
return (
<Row label={label} htmlFor={id} className={styles.alignedRow} hint={hint}>
@@ -273,11 +274,11 @@ function ListField({
className={styles.wide}
value={draft ?? value.join(" ")}
placeholder={placeholder}
onChange={(e) => setDraft(e.target.value)}
onBlur={() => {
if (draft !== null) onChange(splitList(draft));
setDraft(null);
onChange={(e) => {
setDraft(e.target.value);
onChange(splitList(e.target.value));
}}
onBlur={() => setDraft(null)}
/>
</Row>
);
@@ -571,7 +572,7 @@ export function RunTargetsEditor() {
</T>{" "}
<T>
{
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine."
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine."
}
</T>
</div>
+2
Переглянути файл
@@ -17,6 +17,7 @@ import {
} from "./missing";
import { installCssModulesHint } from "./cssModules";
import { installXcodeBspHint } from "./xcodeBsp";
import { installStyledTemplatesHint } from "./styledTemplates";
import { activateSettingsPages } from "./settingsPages";
import { installTool, refreshTools, SETTINGS_PAGE_ID, toolByName, useTools } from "./store";
@@ -84,6 +85,7 @@ export function activate(): () => void {
installServerWarningPrompts(),
installCssModulesHint(),
installXcodeBspHint(),
installStyledTemplatesHint(),
installExpiredServerPrompts(),
registerJdkActions(),
installJdkPrompts(),
+13
Переглянути файл
@@ -0,0 +1,13 @@
import { describe, expect, it } from "vitest";
import { importsStyled } from "./styledTemplates";
describe("importsStyled", () => {
it("spots styled-components and emotion imports in scripts", () => {
expect(importsStyled("/p/a.tsx", 'import styled from "styled-components";')).toBe(true);
expect(importsStyled("/p/a.js", "import { css } from '@emotion/react'")).toBe(true);
expect(importsStyled("/p/a.ts", 'import styled from "@emotion/styled";')).toBe(true);
expect(importsStyled("/p/a.ts", 'import { cache } from "@emotion/cache";')).toBe(false);
expect(importsStyled("/p/a.css", 'from "styled-components"')).toBe(false);
expect(importsStyled("/p/a.ts", null)).toBe(false);
});
});
+50
Переглянути файл
@@ -0,0 +1,50 @@
/**
* CSS completion, hover and diagnostics in styled-components / emotion templates (#6900) come
* from the `@styled/typescript-styled-plugin` tsserver plugin, which vtsls loads where a
* package.json depends on one of those libraries. Opening a script that imports one offers the
* install, once per project and session, while vtsls serves scripts (typescript-language-server
* doesn't load the plugin).
*/
import { tx } from "@/platform/i18n";
import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { maybeEditorService } from "@/workbench/contributions";
import { promptInstall } from "./missing";
import { refreshTools, toolByName, useTools } from "./store";
const TOOL = "typescript-styled-plugin";
const IMPORT = /from\s*["'](styled-components|@emotion\/(styled|react|css))["']/;
/** The script `path` (with `text`) imports styled-components or emotion. */
export function importsStyled(path: string, text: string | null): boolean {
return /\.[cm]?[jt]sx?$/.test(path) && !!text && IMPORT.test(text);
}
let offered = false;
async function check(path: string | undefined) {
const project = useProject.getState().project;
if (offered || !path || !isTauri() || !project?.trusted || !path.startsWith(`${project.root}/`)) return;
if (!/\.[cm]?[jt]sx?$/.test(path)) return;
const text = await call(commands.fsReadText(path)).catch(() => null);
if (offered || !importsStyled(path, text)) return;
if (!useTools.getState().loaded) await refreshTools();
if (offered || toolByName("vtsls")?.status === "missing") return;
offered = true;
await promptInstall(TOOL, false, new Set(), {
refactoring: tx`CSS completion and checks in styled-components and emotion templates`,
});
}
export function installStyledTemplatesHint(): () => void {
const editor = maybeEditorService();
void check(editor?.activePath() ?? undefined).catch(() => {});
const off = editor?.onActiveInputChange?.((input) => void check(input?.path).catch(() => {}));
const offProject = useProject.subscribe((s, prev) => {
if (s.project?.root !== prev.project?.root) offered = false;
});
return () => {
off?.();
offProject();
};
}
+1
Переглянути файл
@@ -58,6 +58,7 @@ export const intellijMacos: Record<string, string[]> = {
"navigate.gotoTest": ["Meta+Shift+T"],
"navigate.superMethod": ["Meta+U"],
"navigate.relatedSymbol": ["Ctrl+Meta+Up"],
"navigate.headerSource": ["F10"],
"navigate.nextMethod": ["Ctrl+Shift+Down"],
"navigate.previousMethod": ["Ctrl+Shift+Up"],
"navigate.nextOccurrence": ["Meta+Alt+Down"],
+1
Переглянути файл
@@ -59,6 +59,7 @@ export const intellijWindows: Record<string, string[]> = {
"navigate.gotoTest": ["Ctrl+Shift+T"],
"navigate.superMethod": ["Ctrl+U"],
"navigate.relatedSymbol": ["Ctrl+Alt+Home"],
"navigate.headerSource": ["F10"],
"navigate.nextMethod": ["Alt+Down"],
"navigate.previousMethod": ["Alt+Up"],
"navigate.nextOccurrence": ["Ctrl+Alt+Down"],
+2
Переглянути файл
@@ -41,6 +41,8 @@ export const vscodeMacos: Record<string, string[]> = {
"db.exportData": [],
"db.editCell": [],
"navigate.relatedSymbol": [],
// vscode-clangd's clangd.switchheadersource.
"navigate.headerSource": ["Alt+O"],
"navigate.nextError": ["F8"],
"navigate.prevError": ["Shift+F8"],
"navigate.callHierarchy": ["Alt+Shift+H"],
+9 -3
Переглянути файл
@@ -1455,12 +1455,15 @@
"Cannot start debugging on the SSH host": "Cannot start debugging on the SSH host",
"debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.": "debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.",
"The program exited before debugpy was ready. Check the Run console for errors.": "The program exited before debugpy was ready. Check the Run console for errors.",
"Only Python can be debugged on SSH run targets": "Only Python can be debugged on SSH run targets",
"Only Python and Node.js can be debugged on SSH run targets": "Only Python and Node.js can be debugged on SSH run targets",
"Install debugpy": "Install debugpy",
"The container exited before debugpy was ready. Check the Run console for errors.": "The container exited before debugpy was ready. Check the Run console for errors.",
"The Node.js inspector did not become ready within 120 seconds. Check the Run console.": "The Node.js inspector did not become ready within 120 seconds. Check the Run console.",
"The container exited before the Node.js inspector was ready. Check the Run console for errors.": "The container exited before the Node.js inspector was ready. Check the Run console for errors.",
"The program exited before the Node.js inspector was ready. Check the Run console for errors.": "The program exited before the Node.js inspector was ready. Check the Run console for errors.",
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.": "debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.",
"Only Python can be debugged in containers": "Only Python can be debugged in containers",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.",
"Only Python and Node.js can be debugged in containers": "Only Python and Node.js can be debugged in containers",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.",
"Use Project JDK": "Use Project JDK",
"JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.": "JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.",
"Application server": "Application server",
@@ -3134,6 +3137,8 @@
"Choose Inheritance Target ({count} found)": "Choose Inheritance Target ({count} found)",
"Choose Target": "Choose Target",
"No related symbols": "No related symbols",
"Switch Header/Source": "Switch Header/Source",
"No header or source file found": "No header or source file found",
"Header": "Header",
"Source File": "Source File",
"Template": "Template",
@@ -4440,6 +4445,7 @@
"Add {OPTION} to {rel}? CSS Modules Kit is installed if needed.": "Add {OPTION} to {rel}? CSS Modules Kit is installed if needed.",
"Could not enable CSS Modules Kit": "Could not enable CSS Modules Kit",
"Add {OPTION} to {rel} yourself.": "Add {OPTION} to {rel} yourself.",
"CSS completion and checks in styled-components and emotion templates": "CSS completion and checks in styled-components and emotion templates",
"CSS Modules navigation is off": "CSS Modules navigation is off",
"Go to Declaration, completion, Find Usages and Rename for CSS Module class names need {OPTION} in {rel}.": "Go to Declaration, completion, Find Usages and Rename for CSS Module class names need {OPTION} in {rel}.",
"Enable…": "Enable…",
+2 -2
Переглянути файл
@@ -7763,8 +7763,8 @@
"The project is mounted here; paths and the working directory are mapped into it.": "Проект монтируется сюда; пути и рабочий каталог сопоставляются с этой папкой.",
"Published ports": "Опубликованные порты",
"Run as the image's user, not the project folder's owner (Linux)": "Запускать от имени пользователя образа, а не владельца папки проекта (Linux)",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Подключения Docker берутся из окна инструментов «Сервисы». При каждом запуске создаётся новый контейнер, который удаляется после завершения. Там можно отлаживать конфигурации Python; покрытие кода и профилирование остаются на этом компьютере.",
"Only Python can be debugged in containers": "В контейнерах можно отлаживать только Python",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Подключения Docker берутся из окна инструментов «Сервисы». При каждом запуске создаётся новый контейнер, который удаляется после завершения. Там можно отлаживать конфигурации Python и Node.js; покрытие кода и профилирование остаются на этом компьютере.",
"Only Python and Node.js can be debugged in containers": "В контейнерах можно отлаживать только Python и Node.js",
"Service name, e.g. ORCLPDB1": "Имя сервиса, например ORCLPDB1",
"Current schema:": "Текущая схема:",
"HR (ALTER SESSION SET CURRENT_SCHEMA)": "HR (ALTER SESSION SET CURRENT_SCHEMA)",
+2 -2
Переглянути файл
@@ -793,8 +793,8 @@
"Cannot start container debugging": "Kapsayıcı hata ayıklaması başlatılamıyor",
"The container exited before debugpy was ready. Check the Run console for errors.": "debugpy hazır olmadan kapsayıcı sonlandı. Hatalar için Çalıştır konsolunu kontrol edin.",
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.": "debugpy 120 saniye içinde hazır olmadı. Çalıştır konsolunu ve kapsayıcının Python yorumlayıcısını kontrol edin.",
"Only Python can be debugged in containers": "Kapsayıcılarda yalnızca Python hata ayıklaması yapılabilir",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker bağlantıları Hizmetler araç penceresinden alınır. Her çalıştırma için yeni bir kapsayıcı oluşturulur ve tamamlandığında kaldırılır. Python yapılandırmalarında kapsayıcı içinde hata ayıklanabilir; kapsam ve profilleme işlemleri bu bilgisayarda kalır.",
"Only Python and Node.js can be debugged in containers": "Kapsayıcılarda yalnızca Python ve Node.js hata ayıklaması yapılabilir",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Docker bağlantıları Hizmetler araç penceresinden alınır. Her çalıştırma için yeni bir kapsayıcı oluşturulur ve tamamlandığında kaldırılır. Python ve Node.js yapılandırmalarında kapsayıcı içinde hata ayıklanabilir; kapsam ve profilleme işlemleri bu bilgisayarda kalır.",
"Use Project JDK": "Proje JDK'sını Kullan",
"JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.": "Maven eşitlemesi, derlemeler, hedefler ve testlerde kullanılan JDK. Çalıştırma yapılandırmasında açıkça belirtilen JAVA_HOME önceliklidir.",
"Application server": "Uygulama sunucusu",
+2 -2
Переглянути файл
@@ -7283,8 +7283,8 @@
"The project is mounted here; paths and the working directory are mapped into it.": "專案掛載在此處;路徑和工作目錄會對映到其中。",
"Published ports": "釋出的埠",
"Run as the image's user, not the project folder's owner (Linux)": "以映像的使用者執行,而不是專案資料夾的所有者(Linux)",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker 連線來自「服務」工具視窗。每次執行都會使用一個新容器,執行結束後刪除。Python 組態可以在容器中偵錯;覆蓋率和效能分析仍在本機進行。",
"Only Python can be debugged in containers": "容器中只能偵錯 Python",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Docker 連線來自「服務」工具視窗。每次執行都會使用一個新容器,執行結束後刪除。Python 和 Node.js 組態可以在容器中偵錯;覆蓋率和效能分析仍在本機進行。",
"Only Python and Node.js can be debugged in containers": "容器中只能偵錯 Python 和 Node.js",
"Service name, e.g. ORCLPDB1": "服務名,例如 ORCLPDB1",
"Current schema:": "目前模式:",
"HR (ALTER SESSION SET CURRENT_SCHEMA)": "HR(ALTER SESSION SET CURRENT_SCHEMA)",
+9 -3
Переглянути файл
@@ -8178,8 +8178,8 @@
"The project is mounted here; paths and the working directory are mapped into it.": "项目挂载在此处;路径和工作目录会映射到其中。",
"Published ports": "发布的端口",
"Run as the image's user, not the project folder's owner (Linux)": "以镜像的用户运行,而不是项目文件夹的所有者(Linux)",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python configurations can be debugged there; coverage and profiling stay on this machine.": "Docker 连接来自“服务”工具窗口。每次运行都会使用一个新容器,运行结束后删除。Python 配置可以在容器中调试;覆盖率和性能分析仍在本机进行。",
"Only Python can be debugged in containers": "容器中只能调试 Python",
"Docker connections come from the Services tool window. Each run gets a new container, removed when it ends. Python and Node.js configurations can be debugged there; coverage and profiling stay on this machine.": "Docker 连接来自“服务”工具窗口。每次运行都会使用一个新容器,运行结束后删除。Python 和 Node.js 配置可以在容器中调试;覆盖率和性能分析仍在本机进行。",
"Only Python and Node.js can be debugged in containers": "容器中只能调试 Python 和 Node.js",
"Service name, e.g. ORCLPDB1": "服务名,例如 ORCLPDB1",
"Current schema:": "当前模式:",
"HR (ALTER SESSION SET CURRENT_SCHEMA)": "HR(ALTER SESSION SET CURRENT_SCHEMA)",
@@ -8297,9 +8297,12 @@
"Cannot start debugging on the SSH host": "无法在 SSH 主机上启动调试",
"debugpy did not become ready within 120 seconds. Check the Run console and the SSH host's Python interpreter.": "debugpy 在 120 秒内未就绪。请检查运行控制台和 SSH 主机上的 Python 解释器。",
"The program exited before debugpy was ready. Check the Run console for errors.": "程序在 debugpy 就绪前已退出。请检查运行控制台中的错误。",
"Only Python can be debugged on SSH run targets": "SSH 运行目标上只能调试 Python",
"Only Python and Node.js can be debugged on SSH run targets": "SSH 运行目标上只能调试 Python 和 Node.js",
"Install debugpy": "安装 debugpy",
"The container exited before debugpy was ready. Check the Run console for errors.": "容器在 debugpy 就绪前已退出。请检查运行控制台中的错误。",
"The Node.js inspector did not become ready within 120 seconds. Check the Run console.": "Node.js 检查器在 120 秒内未就绪。请检查运行控制台。",
"The container exited before the Node.js inspector was ready. Check the Run console for errors.": "容器在 Node.js 检查器就绪前已退出。请检查运行控制台中的错误。",
"The program exited before the Node.js inspector was ready. Check the Run console for errors.": "程序在 Node.js 检查器就绪前已退出。请检查运行控制台中的错误。",
"debugpy did not become ready within 120 seconds. Check the Run console and the container's Python interpreter.": "debugpy 未在 120 秒内就绪。请检查运行控制台和容器的 Python 解释器。",
"Use Project JDK": "使用项目 SDK",
"JDK used for Maven sync, builds, goals and tests. An explicit JAVA_HOME in a run configuration takes precedence.": "用于 Maven 同步、构建、目标和测试的 JDK。运行配置中显式设置的 JAVA_HOME 优先。",
@@ -9771,6 +9774,8 @@
"Choose Inheritance Target ({count} found)": "选择继承目标(找到 {count} 个)",
"Choose Target": "选择目标",
"No related symbols": "没有相关符号",
"Switch Header/Source": "切换头文件/源文件",
"No header or source file found": "未找到对应的头文件或源文件",
"Header": "头文件",
"Source File": "源文件",
"Template": "模板",
@@ -11013,6 +11018,7 @@
"Add {OPTION} to {rel}? CSS Modules Kit is installed if needed.": "要将 {OPTION} 添加到 {rel} 吗?如有需要,将安装 CSS Modules Kit。",
"Could not enable CSS Modules Kit": "无法启用 CSS Modules Kit",
"Add {OPTION} to {rel} yourself.": "请手动将 {OPTION} 添加到 {rel}。",
"CSS completion and checks in styled-components and emotion templates": "styled-components 和 emotion 模板中的 CSS 补全与检查",
"CSS Modules navigation is off": "CSS Modules 导航未开启",
"Go to Declaration, completion, Find Usages and Rename for CSS Module class names need {OPTION} in {rel}.": "CSS Module 类名的转到声明、补全、查找用法和重命名需要在 {rel} 中设置 {OPTION}。",
"Enable…": "启用…",