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

...
19 Коміти
Автор SHA1 Повідомлення Дата
farmer_timmm fe04de3862 fix(syntax): share the memoized outline/folding instead of cloning it (#8309)
SyntaxCache::memoized stored each result behind an Arc but deep-cloned the Vec out of it on every cache hit, which for the outline (a tree of Strings) cost milliseconds on a 2 MB file. memoized now returns the Arc, and outline() and folding() return Arc<Vec<_>>; the two IPC commands that own and extend their result take it out once with Arc::unwrap_or_clone. Results are unchanged; outline_cached_hit went from 4.68 ms to 80 ns and folding_cached_hit from 21.7 µs to 72 ns in the criterion benches.

Co-authored-by: Ttimmahlax <[email protected]>
2026-12-06 07:52:52 +08:00
l0ng-ai 0ca4c7a21b feat(vcs): show the selected file's diff in the Commit dialog (#8312)
The modal commit interface's Commit Changes dialog shows the diff of the file selected in its changes tree below the changes and the message, with the embedded diff viewer used by the Commit tool window's preview. Preview Diff in the tree toolbar hides or shows it (remembered, shown by default); the dialog is larger while it is shown.
2026-12-06 07:48:01 +08:00
l0ng-ai 6324bbb865 fix(project-trust): answer a remote open's trust prompt while the project opens (#8311)
A remote open sets the opening state before it asks Trust and Open Project?, and every action except quitting and window switching is disabled while a project opens, so the prompt's answers were refused and the open hung. Actions gain whileProjectOpens; Trust Project, Preview in Restricted Mode and Don't Open set it.
2026-12-06 07:42:52 +08:00
audichuang 6789f5abc7 test(editor): destroy every focused-cell editor after each focusedCell test (#8301)
Some focusedCell tests never destroyed their focused cell editor, and two cleaned up inside try rather than finally. Focusing a CodeMirror view schedules a 10 ms timer; when the file ended inside it, the timer called requestAnimationFrame on the torn-down jsdom window, failing the Frontend job with an unhandled error. Every cell editor is now destroyed in afterEach.

Co-authored-by: audichuang <[email protected]>
2026-12-06 06:46:34 +08:00
audichuang 6c41918675 fix(build): build WAR artifacts and update Spring Boot resources through Gradle when a build enables Isolated Projects (#8304)
The WAR build for a Tomcat deployment and the Spring Boot resource update looked the module up from the root in projectsEvaluated and registered a task on it, which Isolated Projects rejects. When the build enables it and Gradle is 8.8 or later, each script registers its task on its one target project of the main build from gradle.lifecycle.afterProject (in an afterEvaluate added there); other builds and older Gradle keep projectsEvaluated. The Isolated Projects check is shared in ide-build/src/gradle.rs.

Co-authored-by: audichuang <[email protected]>
2026-12-06 06:45:55 +08:00
audichuang b24b45c2d8 fix(run): run, test, debug and cover through Gradle when a build enables Isolated Projects (#8296)
With org.gradle.isolated-projects=true, running, debugging, testing or covering through Gradle failed: the IDE's init scripts read every project from the root (allprojects, projectsEvaluated), which Isolated Projects rejects. When the build enables it and Gradle is 8.8 or later, the scripts (application run, bootRun, test events/debug, VM options, UTF-8 charset, coverage) configure each project on its own through gradle.lifecycle.beforeProject / afterProject, reading the setting from Gradle's public BuildFeatures; other builds and older Gradle run the previous code.

Co-authored-by: audichuang <[email protected]>
2026-12-06 06:44:25 +08:00
audichuang df03de46ed test(ssh): read the command's line, not the PTY reply, in the remote-folder session test (#8306)
ssh_session_in_a_directory_starts_the_login_shell_there read only up to the first newline, which on Linux is the test server's separate pty 80x24 reply, so it failed there every time. It now reads up to the end of the command's line.

Co-authored-by: audichuang <[email protected]>
2026-12-06 06:41:40 +08:00
Michał DobaczewskiтаMDobak 7a05e2aab0 fix(agents): expand a leading ~ in agent environment values (#8299)
Sessions from other apps stayed empty when Claude Code's environment set CLAUDE_CONFIG_DIR=~/.claude-work: the value was used literally, so transcripts were looked up (and the agent launched) with a folder named ~. A leading ~ in an agent's environment value (alone or before a path separator) is now the user's home, when the agent is launched or signed in and when Claude Code's or Copilot's configuration directory is read. An empty CLAUDE_CONFIG_DIR or COPILOT_HOME counts as unset.

Co-authored-by: MDobak <[email protected]>
2026-12-06 05:30:30 +08:00
audichuang febbff46bd test(settings): wait for the .NET SDK list instead of the unpinned placeholder (#8295)
The .NET settings test waited for the SDK combo to read Not pinned, the placeholder shown before sdkDotnetStatus answers, so it read the SDK list whenever the answer happened to have rendered. It now waits for the list and checks the placeholder after.

Co-authored-by: audichuang <[email protected]>
2026-12-06 05:28:46 +08:00
l0ng-ai e811d633b9 fix(editor): keep the caret on the cut line's number after cutting a whole line (#8303)
Cut without a selection removes the caret line, but the caret was mapped into the line above, so a second Cut removed that line instead of the one that moved up. As IntelliJ's CutHandler does, the caret now goes to the start of the line that takes the cut line's place; after the last line, to the start of the line before it. Multiple carets follow the same rule.
2026-12-06 05:27:39 +08:00
l0ng-ai 7abf1d2ac7 test(vcs): close the blame popup inside act in teardown (#8300)
closeBlamePopup renders null into the popup's React root; called outside act in afterEach, React sometimes ran that work after the test environment was torn down, failing the Frontend job with an unhandled window-is-not-defined error. Both blame test files now close it inside act.
2026-12-06 05:04:48 +08:00
Vadim LazukтаInf1mum ca6efe197c fix(updates): keep the cause chain in updater errors (#8285)
The Update check failed notification showed only reqwest's top-level message (error sending request for url …), hiding what failed, such as a refused connection to a manual HTTP proxy that isn't running. ide_http::client::describe now takes any error and follows its sources, and the update check, the pre-download check and the download request/body reads use it. Endpoints, proxy routing and timeouts are unchanged.

Co-authored-by: Inf1mum <[email protected]>
2026-12-06 05:03:21 +08:00
l0ng-ai bdc4b1ef98 fix(scaffold): use a discovered Go for New Project when none is on PATH (#8298)
New Project › Go still reported go is not installed when GOROOT was on Default and go wasn't on the app's PATH (started from the Dock or Finder), although Settings › Languages › Go lists the Go installs it finds. With no GOROOT chosen and no go on PATH, the wizard now uses the first detected Go install for the requirement check and the generator steps; a go on PATH still wins. Detection runs only for generators that run go.
2026-12-06 04:57:15 +08:00
audichuang b4f4b103c6 fix(scaffold): find the Go chosen in Settings when creating a project (#8269)
New Project › Go said go is not installed and kept Create disabled whenever go wasn't on the login-shell PATH, even with Settings › Languages › Go › GOROOT pointing at a Go: the wizard searched only the host PATH, while Run and gopls use the GOROOT setting. For generators that require go, the requirement check and the generator steps now put <GOROOT>/bin ahead of PATH and set GOROOT, when that GOROOT holds a runnable go.

Co-authored-by: audichuang <[email protected]>
2026-12-06 04:48:50 +08:00
audichuang d592e5e154 fix(vcs): tell a tag from a branch of the same name in the Git Log filter (#8277)
With a tag and a local branch both named release, picking either in the Git Log Branches pane filtered by release, which git resolves to the tag, and the pane highlighted the branch row for both. The filter now takes git's own unambiguous name for the picked ref among the repository's refs (git rev-parse --abbrev-ref=strict): tags/release and heads/release, the full ref when another ref takes those, the plain name otherwise. The pane maps a filter back to the row of the ref git resolves it to; a plain name that is both selects the branch. Renaming a branch also renames a heads/ or refs/heads/ filter.

Co-authored-by: audichuang <[email protected]>
2026-12-06 04:42:59 +08:00
tongkangwangтаchiyanking ad311ce0bb feat(usages): Show Import Statements filter and an icon for Open in Find Tool Window (#8280)
Show Usages and the Find tool window gain the Show Import Statements toggle next to the read/write access filters: a usage on a line that begins an import statement (import ..., from ... import ...) is hidden when it is off. The option defaults to on and persists with read/write; saved settings without it keep showing imports. The popup's Open in Find Tool Window is an icon button with its shortcut in the tooltip. The icon is vendored from intellij-community (Apache-2.0).

Co-authored-by: chiyanking <[email protected]>
2026-12-06 04:36:14 +08:00
l0ng-ai 1806c60a7c feat(vcs): get files from the revision in the Compare tool window (#8292)
A working-tree comparison in the Compare tool window (Branches › Show Diff with Working Tree) now has Get next to Jump to Source: the selected file takes its content from the compared revision after a confirmation, and the list reloads.
2026-12-06 04:34:11 +08:00
l0ng-ai d6067dbd14 fix(scaffold): drop the previous generator's missing-tool warning when another generator is chosen (#8294)
The New Project dialog showed the last generator's requirement check until the next one returned. Check results now carry their generator and only the chosen generator's are shown.
2026-12-06 04:26:24 +08:00
Vadim LazukтаInf1mum d1afd0ae9f feat(vcs): build the commit message field on the editor so Vim works in it (#8283)
The commit message field was a textarea, outside Vim mode, and its Esc always blurred. It is now a reusable editor-based TextField (src/editor/TextField.tsx) carrying the embedded editor contributions, so Vim attaches when Vim mode is on. Margin guide, wrap at margin, subject counter, blank-line inspection, message history, Meta+Enter and the activation focus keep working. Vim claims Escape in a tool window's Vim field outside Normal mode, so Esc leaves Insert or Visual mode before the tool window's Focus Editor runs; in Normal mode Esc moves the focus as before. The field sets data-autofocus before paint and ignores the blur of a view being destroyed. The Commit dialog shares the field.

Co-authored-by: Inf1mum <[email protected]>
2026-12-06 04:25:56 +08:00
85 змінених файлів з 2526 додано та 412 видалено

No files matched your search

+5
Переглянути файл
@@ -75,6 +75,11 @@ The read/write usage filter assets (`actions/showReadAccess{,_dark}.svg` and
[`e992ff4750b4c36afe2caadfa8b191a8f36fb7a2`](https://github.com/JetBrains/intellij-community/tree/e992ff4750b4c36afe2caadfa8b191a8f36fb7a2/platform/icons/src/expui/actions).
Their original copyright headers and Apache-2.0 licensing are retained.
The `actions/showImportStatements{,_dark}.svg` asset is copied unmodified from
`platform/icons/src/expui/actions/` at intellij-community commit
[`71290c3174`](https://github.com/JetBrains/intellij-community/tree/71290c3174/platform/icons/src).
Its original copyright headers and Apache-2.0 licensing are retained.
- [intellij-rust](https://github.com/intellij-rust/intellij-rust) (MIT):
`src/main/resources/icons/expui/rustFile{,_dark}.svg` →
`src/ui/expui/fileTypes/rust{,_dark}.svg`;
+20 -4
Переглянути файл
@@ -134,13 +134,14 @@ impl Cli for Process {
}
}
/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`).
/// Claude Code's configuration directory (`CLAUDE_CONFIG_DIR`, else `~/.claude`); an empty value counts as
/// unset, and a leading `~` is the user's home.
pub(crate) fn config_dir(env: &[(String, String)]) -> Option<PathBuf> {
let set = env
.iter()
.find(|(k, _)| k == "CLAUDE_CONFIG_DIR")
.map(|(_, v)| PathBuf::from(v))
.or_else(|| std::env::var_os("CLAUDE_CONFIG_DIR").map(PathBuf::from));
.find(|(k, v)| k == "CLAUDE_CONFIG_DIR" && !v.is_empty())
.map(|(_, v)| PathBuf::from(crate::provider::expand_home(v)))
.or_else(|| std::env::var_os("CLAUDE_CONFIG_DIR").filter(|v| !v.is_empty()).map(PathBuf::from));
set.or_else(|| {
std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(|h| Path::new(&h).join(".claude"))
})
@@ -160,4 +161,19 @@ mod tests {
"--resume a --fork-session --session-id b"
);
}
#[test]
fn an_empty_config_dir_is_unset() {
let dir = config_dir(&[("CLAUDE_CONFIG_DIR".into(), String::new())]);
assert!(dir.is_some_and(|d| d.is_absolute()));
let set = config_dir(&[("CLAUDE_CONFIG_DIR".into(), "/home/me/.claude-work".into())]);
assert_eq!(set, Some(PathBuf::from("/home/me/.claude-work")));
}
#[test]
fn a_config_dir_under_the_home_folder_can_start_with_a_tilde() {
let home = crate::home_dir().unwrap();
let dir = config_dir(&[("CLAUDE_CONFIG_DIR".into(), "~/.claude-work".into())]);
assert_eq!(dir, Some(home.join(".claude-work")));
}
}
+5 -4
Переглянути файл
@@ -37,12 +37,13 @@ const DISCOVER_TIMEOUT: Duration = if cfg!(test) { Duration::from_secs(5) } else
const EARLY_CANCEL: Duration = Duration::from_secs(2);
const EXIT_GRACE: Duration = Duration::from_millis(100);
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`).
/// Copilot's configuration directory (`COPILOT_HOME`, otherwise `<home>/.copilot`); an empty value counts as
/// unset, and a leading `~` is the user's home.
pub(crate) fn config_dir(env: &[(String, String)], home: Option<&Path>) -> Option<PathBuf> {
env.iter()
.find(|(key, _)| key == "COPILOT_HOME")
.map(|(_, value)| PathBuf::from(value))
.or_else(|| std::env::var_os("COPILOT_HOME").map(PathBuf::from))
.find(|(key, value)| key == "COPILOT_HOME" && !value.is_empty())
.map(|(_, value)| PathBuf::from(crate::provider::expand_home(value)))
.or_else(|| std::env::var_os("COPILOT_HOME").filter(|v| !v.is_empty()).map(PathBuf::from))
.or_else(|| home.map(|home| home.join(".copilot")))
}
+10
Переглянути файл
@@ -124,7 +124,17 @@ fn resolves_copilot_home_from_agent_env_or_user_home() {
);
if std::env::var_os("COPILOT_HOME").is_none() {
assert_eq!(super::config_dir(&[], Some(home)), Some(home.join(".copilot")));
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), String::new())], Some(home)),
Some(home.join(".copilot"))
);
}
assert!(super::config_dir(&[("COPILOT_HOME".into(), String::new())], Some(home)).is_some_and(|d| d.is_absolute()));
let user_home = crate::home_dir().unwrap();
assert_eq!(
super::config_dir(&[("COPILOT_HOME".into(), "~/.copilot-work".into())], Some(home)),
Some(user_home.join(".copilot-work"))
);
}
#[test]
+33 -1
Переглянути файл
@@ -194,6 +194,9 @@ impl ProviderSpec {
}
fn resolve_for_launch_base(mut self, cwd: &Path, strip_ambient_tokens: bool) -> Self {
for (_, value) in &mut self.env {
*value = expand_home(value);
}
if let Some(program) = self.managed_cli.take() {
self.command = program;
} else if self.driver != Driver::Acp {
@@ -235,7 +238,7 @@ impl ProviderSpec {
return Some(LoginLaunch {
program,
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
env: self.env.iter().cloned().collect(),
env: self.env.iter().map(|(name, value)| (name.clone(), expand_home(value))).collect(),
});
}
@@ -1201,6 +1204,21 @@ pub(crate) fn load(custom_dir: Option<&Path>, secrets: Option<&dyn EnvSecrets>)
specs
}
/// `value` with a leading `~` (alone or before a path separator) replaced by the user's home,
/// as a shell does for `NAME=~/path`.
pub(crate) fn expand_home(value: &str) -> String {
let rest = match value.strip_prefix('~') {
Some("") => "",
Some(rest) if rest.starts_with('/') || rest.starts_with('\\') => &rest[1..],
_ => return value.to_owned(),
};
match crate::home_dir() {
Some(home) if rest.is_empty() => home.to_string_lossy().into_owned(),
Some(home) => home.join(rest).to_string_lossy().into_owned(),
None => value.to_owned(),
}
}
/// Whether `command` resolves to an executable (a path, or a name on [`ide_core::tool_path::search_path`]).
#[cfg(test)]
pub(crate) fn installed(command: &str) -> bool {
@@ -1647,6 +1665,20 @@ mod tests {
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
}
#[test]
fn a_leading_tilde_in_the_environment_is_the_home_folder() {
let home = crate::home_dir().unwrap();
let mut spec = builtin_spec("claude").unwrap();
for (name, value) in [("A", "~/.claude-work"), ("B", "~"), ("C", "a~/b"), ("D", "~user/x"), ("E", "/abs")] {
spec.env.push((name.into(), value.into()));
}
let resolved = spec.resolve_for_launch(Path::new("."));
let value = |name: &str| resolved.env.iter().find(|(n, _)| n == name).map(|(_, v)| v.clone()).unwrap();
assert_eq!(value("A"), home.join(".claude-work").to_string_lossy());
assert_eq!(value("B"), home.to_string_lossy());
assert_eq!((value("C"), value("D"), value("E")), ("a~/b".into(), "~user/x".into(), "/abs".into()));
}
#[test]
fn acp_adapters_of_native_agents_are_unlisted_until_customized() {
let dir = tempfile::tempdir().unwrap();
+45 -5
Переглянути файл
@@ -49,9 +49,8 @@ pub fn plan(root: &Path, model: &BuildModel, module: &Path, cache: &Path) -> Ide
&script,
format!(
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
{}
def register = {{ p ->
def update = {{ t ->
t.dependsOn 'processResources'
// Resolved here so the action holds no task or project (configuration cache).
@@ -63,9 +62,14 @@ gradle.projectsEvaluated {{
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaUpdateResources', update)
else p.tasks.create('openideaUpdateResources', update)
}}
// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`; init scripts also
// run in included builds, which may have a project at the same path.
if (isolated) gradle.lifecycle.afterProject {{ p -> if (p.path == {path} && p.gradle.parent == null) p.afterEvaluate {{ register(p) }} }}
else gradle.projectsEvaluated {{ register(gradle.rootProject.project({path})) }}
"#,
literal(&p.path),
literal(&manifest.to_string_lossy())
crate::gradle::ISOLATED_PROJECTS_SCRIPT,
literal(&manifest.to_string_lossy()),
path = literal(&p.path),
),
)?;
return Ok(ResourceBuild {
@@ -204,6 +208,42 @@ mod tests {
assert!(!script.contains("build/resources/main")); // The task owns custom output locations.
}
/// The resource-update task's init script on a real Gradle, with and without Isolated Projects (#8261).
#[test]
fn gradle_resources_update_with_and_without_isolated_projects() {
let Some((gradle, version)) = crate::gradle::test_gradle() else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let builds = crate::gradle::write_test_builds(
&base,
// The build realizes tasks early and moves the resources in `afterEvaluate`.
"plugins { id 'java' }\ntasks.all {}\nafterEvaluate { sourceSets.main.output.resourcesDir = file('build/custom') }\n",
"plugins { java }\ntasks.all {}\nafterEvaluate { sourceSets[\"main\"].output.setResourcesDir(file(\"build/custom\")) }\n",
&[("src/main/resources/static/index.html", "after")],
);
for (root, isolated) in builds {
// Before Gradle 8.8 the script keeps reading the project from the root, as before.
if isolated && version < (8, 8) {
continue;
}
let cache = root.join("cache");
let mut model = crate::load(&root, &cache, None);
model.gradle[0].command = gradle.to_string_lossy().into_owned();
for pass in if isolated { &["miss", "hit"][..] } else { &["run"][..] } {
let plan = plan(&root, &model, Path::new("app"), &cache).unwrap();
let out = crate::gradle::run_test_gradle(&root, &plan.cwd, &plan.command, &plan.args)
.unwrap_or_else(|e| panic!("{pass}:\n{e}"));
assert_eq!(out.contains("Reusing configuration cache."), *pass == "hit", "{out}");
let dir = fs::read_to_string(cache.join("resource-output.txt")).unwrap();
assert_eq!(Path::new(&dir), root.join("app/build/custom"));
assert_eq!(fs::read_to_string(Path::new(&dir).join("static/index.html")).unwrap(), "after");
}
}
}
#[test]
fn publishes_maven_and_gradle_resource_outputs_to_the_runtime_classpath() {
for layout in ["target/classes", "build/resources/main", "custom resource output"] {
+82
Переглянути файл
@@ -54,6 +54,24 @@ fn isolated_projects(dir: &Path, user_home: Option<&Path>) -> bool {
values.contains(&true) && !values.contains(&false)
}
/// Groovy for init scripts that add a task to one project (needs `GradleVersion` imported): `isolated`
/// is whether the build enables Isolated Projects on Gradle 8.8+, where such a script must register
/// it from `gradle.lifecycle` instead of reading the project from the root. `BuildFeatures` (8.5+) is
/// only injected, so a class compiled at run time reads it.
pub(crate) const ISOLATED_PROJECTS_SCRIPT: &str = r#"def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
"#;
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct GradleModel {
@@ -1166,6 +1184,70 @@ pub(crate) fn has_war_plugin(script: &str) -> bool {
script.split(|c: char| !c.is_alphanumeric() && c != '_').any(|word| word == "war")
}
/// A real Gradle for tests (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path) and its
/// version as (major, minor); `None` without it or without `JAVA_HOME`.
#[cfg(test)]
pub(crate) fn test_gradle() -> Option<(PathBuf, (u32, u32))> {
std::env::var_os("JAVA_HOME")?;
let gradle = std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()))?;
let out = std::process::Command::new(&gradle).arg("--version").output().ok()?;
let text = String::from_utf8_lossy(&out.stdout).into_owned();
let version = text.lines().find_map(|l| l.strip_prefix("Gradle "))?.trim().to_owned();
let mut parts = version.split('.').map(|p| p.parse::<u32>().unwrap_or(0));
Some((gradle.clone(), (parts.next()?, parts.next().unwrap_or(0))))
}
/// Runs a planned Gradle command in `root`; its output, or the failure with it.
#[cfg(test)]
pub(crate) fn run_test_gradle(root: &Path, cwd: &str, command: &str, args: &[String]) -> Result<String, String> {
let out = std::process::Command::new(command).args(args).current_dir(root.join(cwd)).output().unwrap();
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
if out.status.success() { Ok(text) } else { Err(text) }
}
/// Two builds for init-script tests, each with `files` under `app`: one in the Groovy DSL without
/// Isolated Projects, one in the Kotlin DSL with it (and so the configuration cache).
#[cfg(test)]
pub(crate) fn write_test_builds(
base: &Path,
groovy: &str,
kotlin: &str,
files: &[(&str, &str)],
) -> [(PathBuf, bool); 2] {
let plain = base.join("plain");
let isolated = base.join("isolated");
let mut all = vec![
(plain.join("gradle.properties"), "org.gradle.daemon=false\n".to_owned()),
(plain.join("settings.gradle"), "rootProject.name = 'plain'\ninclude 'app'\n".to_owned()),
(plain.join("app/build.gradle"), groovy.to_owned()),
(
isolated.join("gradle.properties"),
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\n\
org.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n"
.to_owned(),
),
(
isolated.join("settings.gradle.kts"),
"rootProject.name = \"isolated\"\ninclude(\"app\")\nincludeBuild(\"inc\")\n".to_owned(),
),
// An included build with a project at the same path, whose tasks are realized early.
(isolated.join("inc/settings.gradle.kts"), "rootProject.name = \"inc\"\ninclude(\"app\")\n".to_owned()),
(isolated.join("inc/app/build.gradle.kts"), "plugins { java }\ntasks.all {}\n".to_owned()),
(isolated.join("app/build.gradle.kts"), kotlin.to_owned()),
];
for (rel, text) in files {
all.push((plain.join("app").join(rel), text.to_string()));
all.push((isolated.join("app").join(rel), text.to_string()));
}
for (path, text) in all {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
[(plain, false), (isolated, true)]
}
#[cfg(test)]
mod tests {
#[test]
+45 -5
Переглянути файл
@@ -161,9 +161,8 @@ pub fn build(root: &Path, model: &BuildModel, id: &str, cache: &Path) -> IdeResu
&script,
format!(
r#"import org.gradle.util.GradleVersion
gradle.projectsEvaluated {{
def p = gradle.rootProject.project({})
{}
def register = {{ p ->
def artifact = {{ t ->
t.dependsOn 'war'
// Resolved here so the action holds no task or project (configuration cache).
@@ -180,9 +179,14 @@ gradle.projectsEvaluated {{
if (GradleVersion.current() >= GradleVersion.version('4.9')) p.tasks.register('openideaTomcatArtifact', artifact)
else p.tasks.create('openideaTomcatArtifact', artifact)
}}
// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`; init scripts also
// run in included builds, which may have a project at the same path.
if (isolated) gradle.lifecycle.afterProject {{ p -> if (p.path == {path} && p.gradle.parent == null) p.afterEvaluate {{ register(p) }} }}
else gradle.projectsEvaluated {{ register(gradle.rootProject.project({path})) }}
"#,
groovy_literal(path),
groovy_literal(&manifest.to_string_lossy())
crate::gradle::ISOLATED_PROJECTS_SCRIPT,
groovy_literal(&manifest.to_string_lossy()),
path = groovy_literal(path),
),
)?;
let task = format!("{}:openideaTomcatArtifact", path.trim_end_matches(':'));
@@ -274,6 +278,42 @@ mod tests {
assert!(!crate::gradle::has_war_plugin("// plugins { war }"));
}
/// The WAR task's init script on a real Gradle, with and without Isolated Projects (#8261).
#[test]
fn gradle_war_artifact_builds_with_and_without_isolated_projects() {
let Some((gradle, version)) = crate::gradle::test_gradle() else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let tmp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(tmp.path()).unwrap();
let builds = crate::gradle::write_test_builds(
&base,
// The build realizes tasks early and applies the WAR plugin in `afterEvaluate`.
"plugins { id 'java' }\ntasks.all {}\nafterEvaluate { apply plugin: 'war' }\n",
"plugins { java }\ntasks.all {}\nafterEvaluate { apply(plugin = \"war\") }\n",
&[("src/main/webapp/index.html", "war")],
);
for (root, isolated) in builds {
// Before Gradle 8.8 the script keeps reading the project from the root, as before.
if isolated && version < (8, 8) {
continue;
}
let cache = root.join("cache");
let mut model = crate::load(&root, &cache, None);
model.gradle[0].command = gradle.to_string_lossy().into_owned();
let id = artifacts(&root, &model).into_iter().find(|a| a.id.contains(":app")).expect("the app WAR").id;
for pass in if isolated { &["miss", "hit"][..] } else { &["run"][..] } {
let plan = build(&root, &model, &id, &cache).unwrap();
let out = crate::gradle::run_test_gradle(&root, &plan.cwd, &plan.command, &plan.args)
.unwrap_or_else(|e| panic!("{pass}:\n{e}"));
assert_eq!(out.contains("Reusing configuration cache."), *pass == "hit", "{out}");
let war = fs::read_to_string(cache.join("artifact-path.txt")).unwrap();
assert!(Path::new(&war).is_file() && war.ends_with(".war"), "{war}");
}
}
}
#[test]
fn gradle_manifest_paths_preserve_windows_characters() {
for path in [r"C:\工作 区\Tomcat's cache\artifact-path.txt", r"\\server\share\artifact-path.txt"] {
+19 -3
Переглянути файл
@@ -170,8 +170,24 @@ pub const GRADLE_FILE_ENCODING_SCRIPT: &str = "\
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects {
each(tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
eachProject { p ->
each(p.tasks.withType(JavaExec)) { t -> t.defaultCharacterEncoding = 'UTF-8' }
}
";
@@ -622,7 +638,7 @@ mod tests {
#[test]
fn gradle_script_respects_the_builds_own_file_encoding() {
let s = GRADLE_FILE_ENCODING_SCRIPT;
assert!(s.contains("each(tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("each(p.tasks.withType(JavaExec))"), "{s}");
assert!(s.contains("t.defaultCharacterEncoding = 'UTF-8'"), "{s}");
assert!(!s.contains("doFirst"), "the build must be able to override the default: {s}");
assert!(!s.contains("withType(Test)") && !s.contains("JavaCompile"), "{s}");
+110 -1
Переглянути файл
@@ -9,7 +9,23 @@ const GRADLE_INIT: &str = r#"// Written by OpenIDEA for Run with Coverage.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
allprojects { p ->
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
eachProject { p ->
p.plugins.withId('java') {
p.apply plugin: 'jacoco'
each(p.tasks.withType(Test)) { t -> t.finalizedBy('jacocoTestReport') }
@@ -582,4 +598,97 @@ mod tests {
CoveragePrepared::Unsupported { .. }
));
}
/// The coverage init script on a real Gradle, with and without Isolated Projects (#8261).
/// Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else `gradle` on the search path).
#[test]
fn gradle_init_script_configures_each_project() {
let gradle = std::env::var_os("JAVA_HOME").and_then(|_| {
std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(std::path::PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()))
});
let Some(gradle) = gradle else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let version = std::process::Command::new(&gradle).arg("--version").output().unwrap();
let version =
String::from_utf8_lossy(&version.stdout).lines().find_map(|l| l.strip_prefix("Gradle ").map(str::to_owned));
let mut parts = version
.expect("a `Gradle x.y` line")
.trim()
.split('.')
.map(|p| p.parse::<u32>().unwrap_or(0))
.collect::<Vec<_>>();
parts.resize(2, 0);
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let script = base.join("coverage.init.gradle");
std::fs::write(&script, GRADLE_INIT).unwrap();
for (name, props) in [
("plain", ""),
(
"isolated",
"org.gradle.configuration-cache=true\norg.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
] {
if name == "isolated" && (parts[0], parts[1]) < (8, 8) {
// Before Gradle 8.8 the script keeps reading every project, as the plain build checked.
continue;
}
let root = base.join(name);
for (rel, text) in [
("gradle.properties", format!("org.gradle.daemon=false\n{props}")),
("settings.gradle", "include 'lib'\n".to_owned()),
("build.gradle", String::new()),
(
"lib/build.gradle",
"plugins { id 'java' }\nrepositories { mavenCentral() }\n\
dependencies { testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'; \
testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }\n\
test { useJUnitPlatform() }\n"
.to_owned(),
),
(
"lib/src/main/java/l/L.java",
"package l;\npublic class L { public static int one() { return 1; } }\n".to_owned(),
),
(
"lib/src/test/java/l/LTest.java",
"package l;\nclass LTest { @org.junit.jupiter.api.Test void one() { L.one(); } }\n".to_owned(),
),
] {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
let report = root.join("lib/build/reports/jacoco/test/jacocoTestReport.xml");
// With Isolated Projects the configuration cache is on: a miss, then a hit.
for pass in if name == "isolated" { &["miss", "hit"][..] } else { &["run"][..] } {
// Fresh test results and execution data, so each pass runs the tests under the agent.
for dir in ["lib/build/jacoco", "lib/build/test-results", "lib/build/reports"] {
let _ = std::fs::remove_dir_all(root.join(dir));
}
let out = std::process::Command::new(&gradle)
.args(["--console=plain", "--init-script"])
.arg(&script)
.arg(":lib:test")
.current_dir(&root)
.output()
.unwrap();
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
assert!(out.status.success(), "{name} {pass}:\n{text}");
let xml =
std::fs::read_to_string(&report).unwrap_or_else(|_| panic!("{name} {pass}: no report\n{text}"));
assert_eq!(text.contains("Reusing configuration cache."), *pass == "hit", "{name} {pass}:\n{text}");
let method =
xml.split(r#"<method name="one" desc="()I""#).nth(1).and_then(|m| m.split("</method>").next());
assert!(
method.is_some_and(|m| m.contains(r#"<counter type="LINE" missed="0" covered="1"/>"#)),
"{name} {pass}: {xml}"
);
}
}
}
}
+3 -2
Переглянути файл
@@ -8,6 +8,7 @@ use ide_text::LineEnding;
use ide_workspace::settings::SettingsScope;
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
use std::path::{Path, PathBuf};
use std::sync::Arc;
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
/// editor buffer, so syntax features and language-server requests work in it.
@@ -165,7 +166,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
items
}
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
None => syntax(),
None => Arc::unwrap_or_clone(syntax()),
})
})
.await
@@ -186,7 +187,7 @@ pub async fn doc_folding(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
if snap.large {
return Ok(Vec::new());
}
let mut folds = project.syntax.folding(doc, &snap.language, snap.version, &snap.text);
let mut folds = Arc::unwrap_or_clone(project.syntax.folding(doc, &snap.language, snap.version, &snap.text));
if let Some(plugins) = crate::plugins::editor_providers_for(crate::plugins::ProviderKind::Folding) {
let d = ide_plugin::ProviderDocument {
path: project.documents.identity(doc)?.0,
+32 -3
Переглянути файл
@@ -33,8 +33,35 @@ pub async fn scaffold_options(
/// The programs a generator needs for `values`, and whether they are installed.
#[command(trust = always)]
pub async fn scaffold_requirements(generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
blocking(move || ide_scaffold::requirements(&generator, &values)).await
pub async fn scaffold_requirements(host: &Host, generator: String, values: Values) -> IdeResult<Vec<Requirement>> {
let configured = configured_goroot(host);
blocking(move || {
let goroot = goroot(configured, &generator, &values);
ide_scaffold::requirements(&generator, &values, goroot.as_deref())
})
.await
}
/// The GOROOT chosen in the global settings (those of new projects).
fn configured_goroot(host: &Host) -> Option<PathBuf> {
host.global_settings.read_effective(|s| ide_sdk::apply::absolute_setting_path(&s.languages.go.goroot))
}
/// The Go a generator that needs `go` runs: the GOROOT chosen in Settings; else `go` from `PATH`,
/// where a version manager picks it for the target folder; else, with no `go` on `PATH` (an app
/// started from the Dock or Finder), the first Go install found on this machine, as listed in
/// Settings › Languages › Go. Blocking: detection runs `go version`.
fn goroot(configured: Option<PathBuf>, generator: &str, values: &Values) -> Option<PathBuf> {
configured.or_else(|| {
if !ide_scaffold::needs_program(generator, values, "go") {
return None;
}
let path = ide_core::process::host_var_os("PATH").unwrap_or_default();
if ide_core::process::find_executable("go", &path).is_some() {
return None;
}
ide_sdk::detect(ide_sdk::SdkKind::Go, None).into_iter().find_map(|sdk| sdk.home.map(IpcPath::into_path_buf))
})
}
/// Whether a project named `name` cannot be created in `location`: something other than an
@@ -61,8 +88,10 @@ pub async fn scaffold_create(
) -> IdeResult<IpcPath> {
// Trusted because the user just created it; a failed or cancelled run leaves no files behind.
let cancel = host.begin_request(request);
let configured = configured_goroot(host);
let result = blocking(move || {
ide_scaffold::create(&req, &cancel, &|e| {
let goroot = goroot(configured, &req.generator, &req.values);
ide_scaffold::create(&req, goroot.as_deref(), &cancel, &|e| {
let _ = on_event.send(e);
})
})
+2 -1
Переглянути файл
@@ -148,7 +148,8 @@ async fn ssh_session_in_a_directory_starts_the_login_shell_there() {
)
.await
.unwrap();
let out = read_until(&output, "\n");
// The server answers the PTY request ("pty 80x24") first, in its own packet on Linux.
let out = read_until(&output, "-l\n");
assert!(out.contains(r#"ran: cd -- ~/'my app'\''s'; exec "${SHELL:-/bin/sh}" -l"#), "{out:?}");
host.shutdown().await;
}
+48 -3
Переглянути файл
@@ -174,9 +174,9 @@ pub async fn check_connection(proxy: &ProxySettings, url: &str, cancel: &Cancell
Ok(format!("{} {}", status.as_u16(), status.canonical_reason().unwrap_or("")).trim_end().to_owned())
}
/// reqwest errors with their causes ("error sending request: … connection refused").
pub fn describe(e: &reqwest::Error) -> String {
use std::error::Error;
/// An error with its causes ("error sending request: … connection refused"), so
/// messages surfaced to the user keep the step that actually failed.
pub fn describe(e: &(dyn std::error::Error + 'static)) -> String {
let mut msg = e.to_string();
let mut source = e.source();
while let Some(s) = source {
@@ -194,6 +194,51 @@ pub fn describe(e: &reqwest::Error) -> String {
mod tests {
use super::*;
/// The updater wraps reqwest in its own error type (`tauri-plugin-updater`'s
/// `#[error(transparent)]` variant), so `describe` must follow `source` through
/// any error, not just `reqwest::Error`.
#[derive(Debug)]
struct ConnectRefused;
impl std::fmt::Display for ConnectRefused {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "tcp connect error: connection refused 127.0.0.1:55134")
}
}
impl std::error::Error for ConnectRefused {}
#[derive(Debug)]
struct WrappedRequest {
source: ConnectRefused,
}
impl std::fmt::Display for WrappedRequest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"error sending request for url (https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json)"
)
}
}
impl std::error::Error for WrappedRequest {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.source)
}
}
#[test]
fn describe_keeps_the_causes_behind_a_wrapped_error() {
let error = WrappedRequest { source: ConnectRefused };
assert_eq!(
describe(&error),
"error sending request for url (https://cnb.cool/l0ng-ai/openidea/-/releases/latest/download/latest.json): \
tcp connect error: connection refused 127.0.0.1:55134"
);
}
#[test]
fn describe_of_an_error_without_causes_is_unchanged() {
assert_eq!(describe(&ConnectRefused), "tcp connect error: connection refused 127.0.0.1:55134");
}
#[test]
fn auto_mode_rebuilds_the_shared_client_when_the_system_proxy_changes() {
static SYSTEM: Mutex<String> = Mutex::new(String::new());
+27 -14
Переглянути файл
@@ -186,7 +186,8 @@ impl SyntaxCache {
stats
}
pub fn outline(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Vec<OutlineItem> {
/// The memoized outline, shared: a cache hit clones none of its `String`s.
pub fn outline(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Arc<Vec<OutlineItem>> {
self.memoized(
doc,
lang,
@@ -211,7 +212,8 @@ impl SyntaxCache {
)
}
pub fn folding(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Vec<FoldRange> {
/// The memoized folding ranges, shared like [`Self::outline`].
pub fn folding(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> Arc<Vec<FoldRange>> {
self.memoized(
doc,
lang,
@@ -230,7 +232,7 @@ impl SyntaxCache {
/// Highlighting from the grammar's own query; empty without one.
pub fn highlights(&self, doc: DocId, lang: &LanguageId, version: u32, text: &str) -> SyntaxHighlights {
SyntaxHighlights::new(self.memoized(
SyntaxHighlights::new(Arc::unwrap_or_clone(self.memoized(
doc,
lang,
version,
@@ -241,10 +243,12 @@ impl SyntaxCache {
})
.or_else(|| super::external::highlights(lang, text))
},
))
)))
}
/// `compute()` once per document version; `None` (no grammar / query) is not memoized.
/// Returns the `Arc` the memo holds; a caller that must own the result uses
/// `Arc::unwrap_or_clone`.
fn memoized<T: Clone>(
&self,
doc: DocId,
@@ -252,7 +256,7 @@ impl SyntaxCache {
version: u32,
slot: impl Fn(&mut Memo) -> &mut Option<Arc<Vec<T>>>,
compute: impl FnOnce() -> Option<Vec<T>>,
) -> Vec<T> {
) -> Arc<Vec<T>> {
let entry = self.entries.lock().get(&doc).cloned();
if let Some(e) = &entry {
let mut e = e.lock();
@@ -260,10 +264,11 @@ impl SyntaxCache {
&& let Some(hit) = slot(&mut e.memo).clone()
{
self.hits.fetch_add(1, Ordering::Relaxed);
return (*hit).clone();
return hit;
}
}
let Some(result) = compute() else { return Vec::new() };
let Some(result) = compute() else { return Arc::new(Vec::new()) };
let result = Arc::new(result);
if let Some(e) = &entry {
let mut e = e.lock();
// Containers without their own grammar memoize their web outline too.
@@ -271,7 +276,7 @@ impl SyntaxCache {
if e.version == version
&& (e.tree.is_some() || (e.lang == *lang && self.syntax.web_grammar_name(lang) == Some("html")))
{
*slot(e.memo.at(version, lang)) = Some(Arc::new(result.clone()));
*slot(e.memo.at(version, lang)) = Some(result.clone());
}
}
result
@@ -426,7 +431,7 @@ mod tests {
let mut doc = Document::new(SRC);
cache.open(id, &rust(), doc.version());
let first = cache.outline(id, &rust(), 0, &doc.text());
assert_eq!(first, cache.syntax().outline(&rust(), SRC));
assert_eq!(first.as_ref(), &cache.syntax().outline(&rust(), SRC));
assert_eq!(cache.stats().full_parses, 1);
cache.folding(id, &rust(), 0, &doc.text());
assert_eq!(cache.stats().hits, 1);
@@ -444,8 +449,16 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let text = doc.text();
let v = doc.version();
assert_eq!(cache.outline(id, &rust(), v, &text), cache.syntax().outline(&rust(), &text), "round {round}");
assert_eq!(cache.folding(id, &rust(), v, &text), cache.syntax().folding(&rust(), &text), "round {round}");
assert_eq!(
cache.outline(id, &rust(), v, &text).as_ref(),
&cache.syntax().outline(&rust(), &text),
"round {round}"
);
assert_eq!(
cache.folding(id, &rust(), v, &text).as_ref(),
&cache.syntax().folding(&rust(), &text),
"round {round}"
);
let off = seed % (doc.len_utf16() + 1);
assert_eq!(
cache.selection_ranges(id, &rust(), v, &text, off),
@@ -481,7 +494,7 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let text = doc.text();
let edited = cache.outline(id, &rust(), 1, &text);
assert_eq!(edited, cache.syntax().outline(&rust(), &text));
assert_eq!(edited.as_ref(), &cache.syntax().outline(&rust(), &text));
assert_ne!(edited, outline);
// Another language at the same version is not answered from the memo.
assert!(cache.outline(id, &LanguageId::new("plaintext"), 1, &text).is_empty());
@@ -504,7 +517,7 @@ mod tests {
cache.edit(id, doc.version(), &edits);
let second = cache.outline(id, &lang, doc.version(), &doc.text());
assert_ne!(second, first);
assert_eq!(second, cache.syntax().outline(&lang, &doc.text()));
assert_eq!(second.as_ref(), &cache.syntax().outline(&lang, &doc.text()));
// An older query must not replace the current version's memo.
cache.outline(id, &lang, 0, "<script>const old = 0;</script>");
let hits = cache.stats().hits;
@@ -528,7 +541,7 @@ mod tests {
let edits = edit(&mut doc, 0, 0, "// y\n");
cache.edit(id, doc.version(), &edits);
let text = doc.text();
assert_eq!(cache.outline(id, &rust(), 2, &text), cache.syntax().outline(&rust(), &text));
assert_eq!(cache.outline(id, &rust(), 2, &text).as_ref(), &cache.syntax().outline(&rust(), &text));
assert_eq!(cache.stats().full_parses, 2, "dropped tree re-parses from scratch");
// A query for a version the cache has not reached is answered but not stored.
+4 -4
Переглянути файл
@@ -2033,9 +2033,9 @@ fn cached_outline_matches_syntax_outline_for_web_documents() {
let id = DocId::next();
let src = "<template><div/></template>\n<script lang=\"ts\">\nconst app = 1;\n</script>\n";
cache.open(id, &lang("vue"), 0);
assert_eq!(cache.outline(id, &lang("vue"), 0, src), syntax().outline(&lang("vue"), src));
assert_eq!(cache.outline(id, &lang("vue"), 0, src).as_ref(), &syntax().outline(&lang("vue"), src));
cache.open(id, &lang("html"), 0);
assert_eq!(cache.outline(id, &lang("html"), 0, src), syntax().outline(&lang("html"), src));
assert_eq!(cache.outline(id, &lang("html"), 0, src).as_ref(), &syntax().outline(&lang("html"), src));
}
#[test]
@@ -2137,7 +2137,7 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() {
let cache = SyntaxCache::new(Arc::new(Syntax::new()));
cache.open(id, &language, 0);
let items = cache.outline(id, &language, 0, src);
assert_eq!(items, syntax().outline(&language, src));
assert_eq!(items.as_ref(), &syntax().outline(&language, src));
assert_eq!(items[0].name, "中文😀");
assert_eq!(items[0].selection_range, Range::new(Pos::new(1, 1), Pos::new(1, 5)));
assert_eq!(items[0].children[0].name, "子章节");
@@ -2146,7 +2146,7 @@ fn outline_restructuredtext_unicode_crlf_and_cached_edits() {
assert_eq!(items[0].children[1].name, "Other");
let edited = src.replace("子章节", "新章节😀");
let updated = cache.outline(id, &language, 1, &edited);
assert_eq!(updated, syntax().outline(&language, &edited));
assert_eq!(updated.as_ref(), &syntax().outline(&language, &edited));
assert_eq!(updated[0].children[0].selection_range.end, Pos::new(4, 5));
assert_ne!(items, updated);
}
+27 -10
Переглянути файл
@@ -21,18 +21,35 @@ fn groovy_string(s: &str) -> String {
out
}
const HEADER: &str = r#"// Written by OpenIDEA: VM options of the run configuration.
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
"#;
/// The init script adding `jvm_args` (one argument each) to the forked JVMs.
pub fn init_script(jvm_args: &[String]) -> String {
let list = jvm_args.iter().map(|a| groovy_string(a)).collect::<Vec<_>>().join(", ");
format!(
"// Written by OpenIDEA: VM options of the run configuration.\n\
import org.gradle.util.GradleVersion\n\
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.\n\
def each = {{ tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? \
tasks.configureEach(action) : tasks.all(action) }}\n\
allprojects {{\n \
each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
each(tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
"{HEADER}eachProject {{ p ->\n \
each(p.tasks.withType(JavaExec)) {{ t -> t.jvmArgs([{list}]) }}\n \
each(p.tasks.withType(Test)) {{ t -> t.jvmArgs([{list}]) }}\n\
}}\n"
)
}
@@ -79,8 +96,8 @@ mod tests {
fn adds_each_argument_to_java_exec_and_test_tasks() {
let script = init_script(&args(&["-Ddemo.flag=on", "--add-opens", "java.base/java.lang=ALL-UNNAMED"]));
let list = "['-Ddemo.flag=on', '--add-opens', 'java.base/java.lang=ALL-UNNAMED']";
assert!(script.contains(&format!("each(tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(p.tasks.withType(JavaExec)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
assert!(script.contains(&format!("each(p.tasks.withType(Test)) {{ t -> t.jvmArgs({list}) }}")), "{script}");
// Gradle before 4.9 has no `configureEach` (#3864).
assert!(script.contains("? tasks.configureEach(action) : tasks.all(action)"), "{script}");
}
+201
Переглянути файл
@@ -0,0 +1,201 @@
//! The init scripts of Gradle run, debug and test launches on a real Gradle, with and without
//! Isolated Projects (#8261). Needs `JAVA_HOME` and Gradle (`OPENIDEA_TEST_GRADLE`, else
//! `gradle` on the search path); skipped without them, like ide-build's Gradle tests.
use std::path::{Path, PathBuf};
use std::process::Command;
const RUN: &str = include_str!("../../../../src/features/run/gradleRun.gradle");
const BOOT: &str = include_str!("../../../../src/features/run/gradleBoot.gradle");
const TESTS: &str = include_str!("../../../../src/features/run/gradleTests.gradle");
const MAIN: &str = r#"package a;
public class Main {
public static void main(String[] args) {
String token = "";
for (String a : java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments())
if (a.startsWith("-Dopenidea.")) token += " " + a;
System.out.println("APP " + String.join(",", args) + " enc=" + System.getProperty("file.encoding") + " vm=" + System.getProperty("openidea.vm") + token);
}
}
"#;
const TEST: &str = r#"package l;
class LTest {
@org.junit.jupiter.api.Test
void ok() {
System.out.println("TEST vm=" + System.getProperty("openidea.vm") + " late=" + System.getProperty("openidea.late"));
}
}
"#;
const JUNIT: &str = "org.junit.jupiter:junit-jupiter:5.11.0";
fn gradle() -> Option<PathBuf> {
std::env::var_os("JAVA_HOME")?;
std::env::var_os("OPENIDEA_TEST_GRADLE")
.map(PathBuf::from)
.or_else(|| ide_core::process::find_executable("gradle", &ide_core::tool_path::search_path()))
}
fn write(root: &Path, files: &[(&str, &str)]) {
for (rel, text) in files {
let path = root.join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, text).unwrap();
}
}
/// Runs `tasks` with every init script; the output, or the failure with it.
fn run(gradle: &Path, root: &Path, tasks: &[&str]) -> Result<String, String> {
let scripts = root.parent().unwrap().join("scripts");
let mut args = vec!["--console=plain".to_owned()];
for name in ["jvm", "encoding", "run", "boot", "tests"] {
args.extend(["--init-script".to_owned(), scripts.join(format!("{name}.init.gradle")).display().to_string()]);
}
args.extend(
[
"-Dopenidea.run.project=:app",
"-Dopenidea.run.main=a.Main",
r#"-Dopenidea.run.args=["openidea"]"#,
"-Dopenidea.run.token=t1",
]
.map(String::from),
);
args.extend(tasks.iter().map(|t| t.to_string()));
let out = Command::new(gradle).args(&args).current_dir(root).output().unwrap();
let text = format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr));
if out.status.success() { Ok(text) } else { Err(text) }
}
/// The test-events script reported the test, with its output, from a test JVM given the VM options.
fn assert_test_events(out: &str) {
for event in [
"##teamcity[testStarted name='ok()' className='l.LTest'",
"##teamcity[testStdOut name='ok()' className='l.LTest' reportName='ok()' out='TEST vm=1",
"##teamcity[testFinished name='ok()' className='l.LTest'",
] {
assert!(out.contains(event), "no `{event}`:\n{out}");
}
}
fn app_line<'a>(out: &'a str, arg: &str) -> &'a str {
let prefix = format!("APP {arg} ");
out.lines().find(|l| l.starts_with(&prefix)).unwrap_or_else(|| panic!("no `{prefix}` line:\n{out}"))
}
/// Gradle's version, as (major, minor).
fn version(gradle: &Path) -> (u32, u32) {
let out = Command::new(gradle).arg("--version").output().unwrap();
let text = String::from_utf8_lossy(&out.stdout);
let v = text.lines().find_map(|l| l.strip_prefix("Gradle ")).expect("a `Gradle x.y` line");
let mut parts = v.trim().split('.').map(|p| p.parse::<u32>().unwrap_or(0));
(parts.next().unwrap(), parts.next().unwrap_or(0))
}
#[test]
fn run_debug_and_test_scripts_configure_each_project() {
let Some(gradle) = gradle() else {
eprintln!("skipped: needs JAVA_HOME and gradle (OPENIDEA_TEST_GRADLE)");
return;
};
let temp = tempfile::tempdir().unwrap();
let base = dunce::canonicalize(temp.path()).unwrap();
let jvm = ide_run::gradle_jvm::init_script(&["-Dopenidea.vm=1".to_owned()]);
write(
&base,
&[
("scripts/jvm.init.gradle", &jvm),
("scripts/encoding.init.gradle", ide_core::output_encoding::GRADLE_FILE_ENCODING_SCRIPT),
("scripts/run.init.gradle", RUN),
("scripts/boot.init.gradle", BOOT),
("scripts/tests.init.gradle", TESTS),
],
);
// Without Isolated Projects, in the Groovy DSL: the build's own setting still wins over the
// scripts' UTF-8 default, also when the root configures its subprojects.
let plain = base.join("plain");
write(
&plain,
&[
("gradle.properties", "org.gradle.daemon=false\n"),
("settings.gradle", "rootProject.name = 'plain'\ninclude 'app', 'lib'\n"),
(
"build.gradle",
"subprojects { tasks.withType(JavaExec).configureEach { defaultCharacterEncoding = 'ISO-8859-1' } }\n",
),
(
"app/build.gradle",
"plugins { id 'application' }\napplication { mainClass = 'a.Main' }\ntasks.named('run') { args 'run' }\n\
tasks.register('bootRun', JavaExec) { mainClass = 'a.Main'; classpath = sourceSets.main.runtimeClasspath; args 'boot' }\n",
),
("app/src/main/java/a/Main.java", MAIN),
(
"lib/build.gradle",
&format!(
"plugins {{ id 'java' }}\nrepositories {{ mavenCentral() }}\n\
dependencies {{ testImplementation '{JUNIT}'; testRuntimeOnly 'org.junit.platform:junit-platform-launcher' }}\n\
test {{ useJUnitPlatform() }}\n"
),
),
("lib/src/test/java/l/LTest.java", TEST),
],
);
let out = run(&gradle, &plain, &[":app:run", ":app:bootRun", ":app:openideaRun", ":lib:test"]).unwrap();
assert_eq!(app_line(&out, "run"), "APP run enc=ISO-8859-1 vm=1 -Dopenidea.vm=1");
assert_eq!(app_line(&out, "boot"), "APP boot enc=ISO-8859-1 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1");
assert_eq!(app_line(&out, "openidea"), "APP openidea enc=ISO-8859-1 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1");
assert_test_events(&out);
// With Isolated Projects, in the Kotlin DSL, on a configuration cache miss and then a hit.
let isolated = base.join("isolated");
write(
&isolated,
&[
(
"gradle.properties",
"org.gradle.daemon=false\norg.gradle.configuration-cache=true\n\
org.gradle.isolated-projects=true\norg.gradle.unsafe.isolated-projects=true\n",
),
("settings.gradle.kts", "rootProject.name = \"isolated\"\ninclude(\"app\", \"lib\")\n"),
("build.gradle.kts", ""),
(
"app/build.gradle.kts",
"plugins { application }\napplication { mainClass.set(\"a.Main\") }\n\
tasks.named<JavaExec>(\"run\") { args(\"run\"); defaultCharacterEncoding = \"ISO-8859-1\"; jvmArgs(\"-Dopenidea.vm=build\") }\n\
tasks.register<JavaExec>(\"bootRun\") { mainClass.set(\"a.Main\"); classpath = sourceSets[\"main\"].runtimeClasspath; args(\"boot\") }\n\
afterEvaluate { tasks.named<JavaExec>(\"bootRun\") { setJvmArgs(listOf(\"-Dopenidea.late=1\")) } }\n",
),
("app/src/main/java/a/Main.java", MAIN),
(
"lib/build.gradle.kts",
&format!(
"plugins {{ java }}\nrepositories {{ mavenCentral() }}\n\
dependencies {{ testImplementation(\"{JUNIT}\"); testRuntimeOnly(\"org.junit.platform:junit-platform-launcher\") }}\n\
tasks.test {{ useJUnitPlatform() }}\n\
afterEvaluate {{ tasks.named<Test>(\"test\") {{ systemProperty(\"openidea.late\", \"1\") }} }}\n"
),
),
("lib/src/test/java/l/LTest.java", TEST),
],
);
let tasks = [":app:run", ":app:bootRun", ":app:openideaRun", ":lib:test"];
if version(&gradle) < (8, 8) {
// Before Gradle 8.8 the scripts keep reading every project, as the build above checked.
return;
}
for pass in ["miss", "hit"] {
let out = run(&gradle, &isolated, &tasks).unwrap_or_else(|e| panic!("cache {pass}:\n{e}"));
assert_eq!(out.contains("Reusing configuration cache."), pass == "hit", "{out}");
// The build's own charset and VM option win over the scripts' values.
let run = app_line(&out, "run");
assert!(run.starts_with("APP run enc=ISO-8859-1 vm=build "), "{run}");
// The token comes after the build's own `afterEvaluate`, which replaced the JVM arguments.
assert_eq!(app_line(&out, "boot"), "APP boot enc=UTF-8 vm=null -Dopenidea.late=1 -Dopenidea.run.token=t1");
assert_eq!(app_line(&out, "openidea"), "APP openidea enc=UTF-8 vm=1 -Dopenidea.run.token=t1 -Dopenidea.vm=1");
// Test tasks always run, also on a cache hit.
assert_test_events(&out);
// The test task the build configures in its own `afterEvaluate` ran with that setting.
assert!(out.contains("out='TEST vm=1 late=1"), "{out}");
}
}
+1
Переглянути файл
@@ -2,6 +2,7 @@ mod config;
mod detect;
mod dotnet;
mod dotnet_cli;
mod gradle_init_scripts;
mod import_jetbrains;
mod import_vscode;
#[cfg(unix)]
+65 -17
Переглянути файл
@@ -44,6 +44,39 @@ fn search_path() -> OsString {
ide_core::process::host_var_os("PATH").unwrap_or_default()
}
/// Where a generator's programs are found, and what they run with.
pub(crate) struct Toolchain {
search: OsString,
goroot: Option<PathBuf>,
}
impl Toolchain {
/// The host `PATH`. A generator that needs `go` gets the GOROOT chosen in Settings first on
/// it and as `GOROOT`, as Run and gopls do, while that GOROOT still holds a `go`.
fn new(def: &Def, values: &Values, goroot: Option<&Path>) -> Self {
let search = search_path();
let needs_go = needs(def, values, "go");
let usable = |g: &&Path| ide_core::tool_path::find_command("go", g.join("bin").as_os_str(), g).is_some();
match goroot.filter(|_| needs_go).filter(usable) {
Some(goroot) => Toolchain {
search: std::env::join_paths(std::iter::once(goroot.join("bin")).chain(std::env::split_paths(&search)))
.unwrap_or(search),
goroot: Some(goroot.to_path_buf()),
},
None => Toolchain { search, goroot: None },
}
}
fn command(&self, program: &Path) -> Command {
let mut cmd = Command::new(program);
cmd.env("PATH", &self.search);
if let Some(goroot) = &self.goroot {
cmd.env("GOROOT", goroot);
}
cmd
}
}
/// `values` plus every field's rendered default it lacks, `name` included.
fn with_defaults(def: &Def, name: &str, values: &Values) -> Values {
let mut out = values.clone();
@@ -96,16 +129,16 @@ pub(crate) fn version_at_least(a: &str, b: &str) -> bool {
true
}
fn requirement(r: &RequireDef, values: &Values, search: &OsString) -> Requirement {
fn requirement(r: &RequireDef, values: &Values, tools: &Toolchain) -> Requirement {
let program = render(&r.program, values);
let min = r.min.clone();
let found_path = ide_core::process::find_executable(&program, search);
let found_path = ide_core::process::find_executable(&program, &tools.search);
let found = found_path.as_ref().and_then(|path| {
if r.version_args.is_empty() {
return Some(String::new());
}
let mut cmd = Command::new(path);
cmd.args(&r.version_args).env("PATH", search);
let mut cmd = tools.command(path);
cmd.args(&r.version_args);
let (ok, out) = run_quiet(cmd, std::time::Duration::from_secs(20))?;
// A failing version command (`dotnet` without an SDK) reports no version.
Some(if ok { parse_version(&out).unwrap_or_default() } else { String::new() })
@@ -118,14 +151,23 @@ fn requirement(r: &RequireDef, values: &Values, search: &OsString) -> Requiremen
Requirement { program, min, found: found.filter(|v| !v.is_empty()), satisfied, hint: r.hint.clone() }
}
fn needs(def: &Def, values: &Values, program: &str) -> bool {
def.requires.iter().any(|r| matches(&r.when, values) && render(&r.program, values) == program)
}
/// Whether generator `id` runs `program` for `values`.
pub fn needs_program(id: &str, values: &Values, program: &str) -> bool {
def(id).is_some_and(|def| needs(def, &with_defaults(def, "app", values), program))
}
/// The programs `id` needs for `values`, and whether this machine has them.
pub fn requirements(id: &str, values: &Values) -> IdeResult<Vec<Requirement>> {
pub fn requirements(id: &str, values: &Values, goroot: Option<&Path>) -> IdeResult<Vec<Requirement>> {
let def = def(id).ok_or_else(|| unknown(id))?;
let values = with_defaults(def, "app", values);
let search = search_path();
let tools = Toolchain::new(def, &values, goroot);
let mut out: Vec<Requirement> = Vec::new();
for r in def.requires.iter().filter(|r| matches(&r.when, &values)) {
let req = requirement(r, &values, &search);
let req = requirement(r, &values, &tools);
if !out.iter().any(|o| o.program == req.program) {
out.push(req);
}
@@ -243,13 +285,13 @@ fn run_step(
step: &StepDef,
values: &Values,
project: &Path,
search: &OsString,
tools: &Toolchain,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<()> {
let argv = argv(step, values);
emit(ScaffoldEvent::Step { text: step.label.clone() });
let Some(program) = ide_core::process::find_executable(&argv[0], search) else {
let Some(program) = ide_core::process::find_executable(&argv[0], &tools.search) else {
if step.optional {
emit(ScaffoldEvent::Line { text: format!("`{}` is not installed; skipped", argv[0]) });
return Ok(());
@@ -260,8 +302,8 @@ fn run_step(
Cwd::Project => project.to_path_buf(),
Cwd::Parent => project.parent().unwrap_or(project).to_path_buf(),
};
let mut cmd = Command::new(program);
cmd.args(&argv[1..]).current_dir(cwd).env("PATH", search);
let mut cmd = tools.command(&program);
cmd.args(&argv[1..]).current_dir(cwd);
// Official CLIs take their defaults instead of asking when they see a CI run.
cmd.env("CI", "1").env("NO_COLOR", "1").env("FORCE_COLOR", "0").env("npm_config_yes", "true");
for (key, value) in &step.env {
@@ -396,14 +438,20 @@ fn download_service(
}
/// Creates the project `req` describes and returns its directory.
pub fn create(req: &CreateRequest, cancel: &CancellationToken, emit: Emit) -> IdeResult<PathBuf> {
pub fn create(
req: &CreateRequest,
goroot: Option<&Path>,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<PathBuf> {
let def = def(&req.generator).ok_or_else(|| unknown(&req.generator))?;
create_with(def, req, cancel, emit)
create_with(def, req, goroot, cancel, emit)
}
pub(crate) fn create_with(
def: &Def,
req: &CreateRequest,
goroot: Option<&Path>,
cancel: &CancellationToken,
emit: Emit,
) -> IdeResult<PathBuf> {
@@ -431,12 +479,12 @@ pub(crate) fn create_with(
return Err(IdeError::invalid(format!("{} already exists and is not empty", target.display())));
}
let search = search_path();
let tools = Toolchain::new(def, &values, goroot);
let mut missing = def
.requires
.iter()
.filter(|r| matches(&r.when, &values))
.map(|r| requirement(r, &values, &search))
.map(|r| requirement(r, &values, &tools))
.filter(|r| !r.satisfied);
if let Some(r) = missing.next() {
let need = r.min.as_ref().map(|m| format!(" {m} or later")).unwrap_or_default();
@@ -460,7 +508,7 @@ pub(crate) fn create_with(
if step.cwd == Cwd::Project {
std::fs::create_dir_all(&project)?;
}
run_step(step, &values, &project, &search, cancel, emit)?;
run_step(step, &values, &project, &tools, cancel, emit)?;
}
if !project.is_dir() {
return Err(IdeError::internal(format!("the generator did not create {}", project.display())));
@@ -474,7 +522,7 @@ pub(crate) fn create_with(
if cancel.is_cancelled() {
return Err(IdeError::cancelled());
}
run_step(step, &values, &project, &search, cancel, emit)?;
run_step(step, &values, &project, &tools, cancel, emit)?;
}
let git_dir = project.join(".git");
if !(req.git && def.git) && git_dir.is_dir() {
+83 -10
Переглянути файл
@@ -43,7 +43,7 @@ fn create_template(generator: &str, name: &str, values: &[(&str, &str)]) -> (tem
def.after.clear();
def.requires.clear();
let req = request(generator, tmp.path(), name, values);
let path = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
let path = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap();
(tmp, path)
}
@@ -92,7 +92,8 @@ fn php_namespace_is_escaped_in_json() {
def.requires.clear();
def.after.clear();
let tmp = tempfile::tempdir().unwrap();
let dir = create_with(&def, &request("php", tmp.path(), "shop", &[]), &CancellationToken::new(), &|_| {}).unwrap();
let dir =
create_with(&def, &request("php", tmp.path(), "shop", &[]), None, &CancellationToken::new(), &|_| {}).unwrap();
let composer: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(dir.join("composer.json")).unwrap()).unwrap();
assert_eq!(composer.pointer("/autoload/psr-4/Acme\\Shop\\").unwrap(), "src/");
@@ -244,13 +245,13 @@ fn dotnet_templates_see_the_selected_sdk_before_running() {
step.program = def.requires[0].program.clone();
}
let req = request("dotnet", tmp.path(), "Shop", &[("sdk", "10.0.400")]);
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
let project = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap();
let pin: serde_json::Value = serde_json::from_slice(&std::fs::read(project.join("global.json")).unwrap()).unwrap();
assert_eq!(pin["sdk"]["version"], "10.0.400");
assert_eq!(std::fs::read_to_string(parent_pin).unwrap(), inherited);
// A solution named apart from the project names the folder.
let req = request("dotnet", tmp.path(), "Api", &[("sdk", "10.0.400"), ("solution-name", "Store")]);
let project = create_with(&def, &req, &CancellationToken::new(), &|_| {}).unwrap();
let project = create_with(&def, &req, None, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(project, tmp.path().join("Store"));
assert!(project.join("global.json").is_file());
}
@@ -264,7 +265,7 @@ fn a_failing_version_command_does_not_meet_a_minimum() {
let tool = bin.path().join("fake-dotnet");
std::fs::write(&tool, "#!/bin/sh\necho 'No .NET SDKs were found. Install 8.0 from the site.'\nexit 145\n").unwrap();
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
let search = bin.path().as_os_str().to_owned();
let search = Toolchain { search: bin.path().as_os_str().to_owned(), goroot: None };
let def = |min: &str| -> RequireDef { toml::from_str(&format!("program = \"fake-dotnet\"\n{min}")).unwrap() };
let req = requirement(&def(r#"min = "8.0""#), &Values::new(), &search);
assert!(!req.satisfied);
@@ -299,7 +300,8 @@ label = "Fail"
program = "definitely-not-a-program-openidea"
"#,
);
let err = create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|_| {}).unwrap_err();
let err =
create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|_| {}).unwrap_err();
assert!(err.message.contains("not installed"), "{}", err.message);
assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0);
}
@@ -316,7 +318,7 @@ optional = true
"#,
);
let lines = Mutex::new(Vec::new());
let dir = create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|e| {
let dir = create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|e| {
lines.lock().unwrap().push(format!("{e:?}"))
})
.unwrap();
@@ -330,7 +332,7 @@ fn cancelling_leaves_nothing_behind() {
let cancel = CancellationToken::new();
cancel.cancel();
let def = failing_def("");
let err = create_with(&def, &request("t", tmp.path(), "p", &[]), &cancel, &|_| {}).unwrap_err();
let err = create_with(&def, &request("t", tmp.path(), "p", &[]), None, &cancel, &|_| {}).unwrap_err();
assert_eq!(err.kind, ErrorKind::Cancelled);
assert_eq!(std::fs::read_dir(tmp.path()).unwrap().count(), 0);
}
@@ -341,14 +343,14 @@ fn refuses_a_non_empty_target_and_bad_names() {
std::fs::create_dir(tmp.path().join("p")).unwrap();
std::fs::write(tmp.path().join("p/x"), "").unwrap();
let def = failing_def("");
assert!(create_with(&def, &request("t", tmp.path(), "p", &[]), &CancellationToken::new(), &|_| {}).is_err());
assert!(create_with(&def, &request("t", tmp.path(), "p", &[]), None, &CancellationToken::new(), &|_| {}).is_err());
assert!(std::fs::read_dir(tmp.path().join("p")).unwrap().count() == 1);
for bad in ["", " ", "a/b", "..", ".hidden"] {
assert!(name_error(bad).is_some(), "{bad:?}");
}
// An existing empty folder is used.
std::fs::create_dir(tmp.path().join("q")).unwrap();
let dir = create_with(&def, &request("t", tmp.path(), "q", &[]), &CancellationToken::new(), &|_| {}).unwrap();
let dir = create_with(&def, &request("t", tmp.path(), "q", &[]), None, &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(tree(&dir), ["a.txt"]);
}
@@ -637,3 +639,74 @@ fn xcode_builds_and_tests_apple_projects() {
}
}
}
/// A GOROOT holding a fake `go` that fails, like a real one, under another installation's GOROOT.
#[cfg(unix)]
fn fake_goroot(dir: &Path) -> PathBuf {
use std::os::unix::fs::PermissionsExt;
let goroot = dir.join("go-sdk");
std::fs::create_dir_all(goroot.join("bin")).unwrap();
let go = goroot.join("bin/go");
std::fs::write(
&go,
format!(
"#!/bin/sh\n[ \"$GOROOT\" = '{}' ] || exit 2\n\
if [ \"$1\" = version ]; then echo 1.99.0; exit 0; fi\n\
printf 'module %s\\n' \"$3\" > go.mod\n",
goroot.display()
),
)
.unwrap();
std::fs::set_permissions(&go, std::fs::Permissions::from_mode(0o755)).unwrap();
goroot
}
/// Go installed outside the login shell's `PATH`, chosen as GOROOT in Settings.
#[cfg(unix)]
#[test]
fn the_go_chosen_in_settings_is_found_and_runs_the_steps() {
let tmp = tempfile::tempdir().unwrap();
let goroot = fake_goroot(tmp.path());
let reqs = requirements("go", &Values::new(), Some(&goroot)).unwrap();
assert_eq!(reqs[0].found.as_deref(), Some("1.99.0"));
// A Go on `PATH` would write a `go` line too.
let req = request("go", tmp.path(), "hello", &[]);
let project = create(&req, Some(&goroot), &CancellationToken::new(), &|_| {}).unwrap();
assert_eq!(std::fs::read_to_string(project.join("go.mod")).unwrap(), "module example.com/hello\n");
}
#[cfg(unix)]
#[test]
fn the_go_chosen_in_settings_stays_out_of_other_generators() {
let tmp = tempfile::tempdir().unwrap();
let goroot = fake_goroot(tmp.path());
let node = source_def("node");
let tools = Toolchain::new(&node, &with_defaults(&node, "app", &Values::new()), Some(&goroot));
assert_eq!(tools.search, search_path());
assert_eq!(tools.goroot, None);
}
/// A GOROOT whose `go` was removed, or lost its execute bit, leaves the `go` on `PATH` to run
/// on its own.
#[cfg(unix)]
#[test]
fn an_unusable_go_chosen_in_settings_is_ignored() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let go = source_def("go");
let values = with_defaults(&go, "app", &Values::new());
let tools = Toolchain::new(&go, &values, Some(&tmp.path().join("go1.25")));
assert_eq!((tools.search, tools.goroot), (search_path(), None));
let goroot = fake_goroot(tmp.path());
std::fs::set_permissions(goroot.join("bin/go"), std::fs::Permissions::from_mode(0o644)).unwrap();
let tools = Toolchain::new(&go, &values, Some(&goroot));
assert_eq!((tools.search, tools.goroot), (search_path(), None));
}
/// New Project asks for a discovered Go only for the generators that run `go`.
#[test]
fn only_go_generators_need_go() {
assert!(needs_program("go", &Values::new(), "go"));
assert!(!needs_program("node", &Values::new(), "go"));
assert!(!needs_program("no-such-generator", &Values::new(), "go"));
}
+1 -1
Переглянути файл
@@ -10,7 +10,7 @@ mod providers;
mod template;
pub use catalog::catalog;
pub use engine::{Emit, create, free_name, name_error, options, requirements, target_taken};
pub use engine::{Emit, create, free_name, name_error, needs_program, options, requirements, target_taken};
pub use model::{
ChoiceOption, CreateRequest, Dependency, DependencyGroup, Field, FieldKind, GeneratorInfo, Requirement,
ScaffoldEvent, Values,
+1 -1
Переглянути файл
@@ -17,7 +17,7 @@ fn smoke(generator: &str, values: &[(&str, &str)], build: &[&str]) {
git: true,
values: values.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),
};
let dir = create(&req, &CancellationToken::new(), &|e| match e {
let dir = create(&req, None, &CancellationToken::new(), &|e| match e {
ScaffoldEvent::Step { text } => eprintln!("== {text}"),
ScaffoldEvent::Line { text } => eprintln!(" {text}"),
})
+27
Переглянути файл
@@ -739,6 +739,33 @@ mod tests {
assert!(cmd.status().unwrap().success(), "{cmd:?}");
}
/// The Git Log filters a short name that is both a tag and a local branch by git's own
/// disambiguated forms (`git rev-parse --abbrev-ref=strict`): `tags/<name>`, `heads/<name>`,
/// or the full ref when another ref takes those.
#[test]
fn resolves_disambiguated_short_names_of_a_tag_and_branch_sharing_a_name() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().join("repo");
run(Command::new("git").args(["init", "-q", "-b", "main"]).arg(&root));
let git = |args: &[&str]| {
let out = Command::new("git").current_dir(&root).args(args).output().unwrap();
assert!(out.status.success(), "{args:?}");
String::from_utf8(out.stdout).unwrap().trim().to_owned()
};
for message in ["one", "two"] {
git(&["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", message]);
}
git(&["tag", "release"]);
git(&["branch", "release", "HEAD~1"]);
let tag = git(&["rev-parse", "refs/tags/release"]);
let branch = git(&["rev-parse", "refs/heads/release"]);
assert_ne!(tag, branch);
let repo = discover(&root).unwrap().unwrap().gix().unwrap();
assert_eq!(resolve(&repo, "tags/release").unwrap().to_string(), tag);
assert_eq!(resolve(&repo, "heads/release").unwrap().to_string(), branch);
assert_eq!(resolve(&repo, "refs/heads/release").unwrap().to_string(), branch);
}
/// More pack indices than the 32 slots `gix` gives a repository another user owns (#7138). The
/// owner can't be changed in a test, so this pins that discovery opens with slots sized by the
/// pack directory: objects in every pack stay readable through the cached handle.
+1 -1
Переглянути файл
@@ -110,7 +110,7 @@ For SSH, the list shows the keys ssh-agent holds, then the public keys in `~/.ss
### Modal commit
With **Use non-modal commit interface** turned off (**Settings › Version Control › Commit**), there is no Commit tool window: **Local Changes**, **Shelf** and **Stash** become tabs of the Git tool window, and **Commit…** opens a **Commit Changes** dialog.
With **Use non-modal commit interface** turned off (**Settings › Version Control › Commit**), there is no Commit tool window: **Local Changes**, **Shelf** and **Stash** become tabs of the Git tool window, and **Commit…** opens a **Commit Changes** dialog. The dialog shows the selected file's diff below the message; **Preview Diff** in its toolbar hides or shows it.
## Changes in the editor
+1 -1
Переглянути файл
@@ -108,7 +108,7 @@ OpenIDEA 会找到包含项目的仓库,以及向下最多四层的嵌套仓
### 模态提交
在 **设置 › 版本控制 › 提交** 中关闭 **使用非模态提交界面** 后,就没有提交工具窗口了:**本地更改**、**搁置** 和 **贮藏** 变成 Git 工具窗口的标签页,**提交…** 会打开 **提交更改** 对话框。
在 **设置 › 版本控制 › 提交** 中关闭 **使用非模态提交界面** 后,就没有提交工具窗口了:**本地更改**、**搁置** 和 **贮藏** 变成 Git 工具窗口的标签页,**提交…** 会打开 **提交更改** 对话框。对话框在提交消息下方显示所选文件的差异,工具栏中的 **预览差异** 可以隐藏或显示它。
## 编辑器中的更改标记
+1 -1
Переглянути файл
@@ -561,7 +561,7 @@ test("usage locations and preview stay readable as the available space changes",
await page.keyboard.press("Meta+Alt+F7");
const popup = page.getByRole("dialog", { name: "Usages" });
const scope = popup.getByRole("button", { name: "Scope" });
const openWindow = popup.getByRole("button", { name: /^Open in Find Window/ });
const openWindow = popup.getByRole("button", { name: "Open in Find Tool Window" });
await expect(popup.getByTestId("usage-row")).toHaveCount(3);
await popup.getByRole("button", { name: "Show Preview" }).click();
const code = popup.getByRole("region", { name: "Preview" });
+20 -19
Переглянути файл
@@ -4,7 +4,7 @@
*/
import type { Page } from "@playwright/test";
import type { PartialCommitFile } from "../src/bindings";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
@@ -357,7 +357,7 @@ test("Commit reviews a paused cherry-pick without collecting unrelated changes o
await expect(author).toHaveValue("Original Author <[email protected]>");
await expect(review.getByRole("list", { name: "Staged Changes" }).getByRole("button")).toHaveText("build.gradle.kts");
await review.getByRole("button", { name: "Cancel", exact: true }).click();
await expect(draft).toHaveValue("Unrelated and shared draft");
await expect.poll(() => fieldText(draft)).toBe("Unrelated and shared draft");
await local.click();
await draft.fill("Commit panel draft for the pick");
await panel.getByRole("button", { name: "Commit Options", exact: true }).click();
@@ -392,7 +392,7 @@ test("Commit reviews a paused cherry-pick without collecting unrelated changes o
},
]);
expect(await ipcCalls(page, "vcs_commit")).toEqual([]);
await expect(draft).toHaveValue("");
await expect.poll(() => fieldText(draft)).toBe("");
});
test("continuing a resolved operation applies commit modifications to the reviewed staging snapshot", async ({
@@ -965,7 +965,7 @@ test("opening a TODO review from the modal commit leaves the draft available", a
const todo = page.getByRole("region", { name: "TODO", exact: true });
await expect(todo.getByRole("tree").getByText("TODO from the commit dialog")).toBeVisible();
await page.keyboard.press("Meta+k");
await expect(dialog.getByRole("textbox", { name: "Commit message" })).toHaveValue("Keep this draft");
await expect.poll(() => fieldText(dialog.getByRole("textbox", { name: "Commit message" }))).toBe("Keep this draft");
expect(await ipcCalls(page, "vcs_commit")).toEqual([]);
});
@@ -1132,7 +1132,7 @@ test("the Commit tool window restores the draft and author options for the inclu
await page.keyboard.press("Escape");
await base.click();
await feature.click();
await expect(message).toHaveValue("Message from the changelist");
await expect.poll(() => fieldText(message)).toBe("Message from the changelist");
await message.fill("Feature draft");
await gear.click();
await expect(author).toHaveValue("");
@@ -1141,13 +1141,13 @@ test("the Commit tool window restores the draft and author options for the inclu
await date.fill(featureDate);
await page.keyboard.press("Escape");
await feature.click();
await expect(message).toHaveValue("Default draft");
await expect.poll(() => fieldText(message)).toBe("Default draft");
await gear.click();
await expect(author).toHaveValue("Default Author <[email protected]>");
await expect(date).toHaveValue(baseDate);
await page.keyboard.press("Escape");
await feature.click();
await expect(message).toHaveValue("Feature draft");
await expect.poll(() => fieldText(message)).toBe("Feature draft");
await panel.getByRole("button", { name: "Commit", exact: true }).click();
await expect
.poll(() => ipcCalls(page, "vcs_commit"))
@@ -1155,7 +1155,7 @@ test("the Commit tool window restores the draft and author options for the inclu
const [committed] = await ipcCalls(page, "vcs_commit");
const expectedDate = await page.evaluate((local) => new Date(local).toISOString(), featureDate);
expect(new Date((committed!.options as { authorDate: string }).authorDate).toISOString()).toBe(expectedDate);
await expect(message).toHaveValue("Default draft");
await expect.poll(() => fieldText(message)).toBe("Default draft");
});
test("commit message history shows compact message previews above the editor", async ({ workbench: page }) => {
@@ -1181,7 +1181,8 @@ test("commit message history shows compact message previews above the editor", a
const menu = page.getByRole("menu", { name: "Recent commit messages" });
const row = menu.getByRole("menuitem", { name: /Update inventory.*Review settlement totals/ });
await expect(row).toBeVisible();
const messageBox = (await message.boundingBox())!;
// The field's box: the editor's host, around its content.
const messageBox = (await message.locator("xpath=ancestor::div[contains(@class, 'cm-editor')]/..").boundingBox())!;
const menuBox = (await menu.locator("..").boundingBox())!;
const rowBox = (await row.boundingBox())!;
expect(messageBox.y - menuBox.y - menuBox.height).toBeCloseTo(3, 0);
@@ -1193,7 +1194,7 @@ test("commit message history shows compact message previews above the editor", a
await row.press("Escape");
await expect(menu).toBeHidden();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await history.click();
await row.press("Home");
await expect(row).toBeFocused();
@@ -1201,7 +1202,7 @@ test("commit message history shows compact message previews above the editor", a
const second = menu.getByRole("menuitem", { name: /Update inventory.*Reconcile export records/ });
await expect(second).toBeFocused();
await page.keyboard.press("Enter");
await expect(message).toHaveValue("Update inventory\n\nReconcile export records");
await expect.poll(() => fieldText(message)).toBe("Update inventory\n\nReconcile export records");
await expect(message).toBeFocused();
});
@@ -1364,7 +1365,7 @@ test("Amend sizes the chooser for long subjects while keeping the last commit ac
await expect(list).toBeHidden();
await page.setViewportSize({ width: 1040, height: 700 });
await page.keyboard.press("Meta+k");
await expect(panel.getByRole("textbox", { name: "Commit message" })).toHaveValue(earlier);
await expect.poll(() => fieldText(panel.getByRole("textbox", { name: "Commit message" }))).toBe(earlier);
});
test("Amend can select an earlier commit before protected history", async ({ workbench: page }) => {
@@ -1381,14 +1382,14 @@ test("Amend can select an earlier commit before protected history", async ({ wor
await expect(picker.getByText("Published commit", { exact: true })).toHaveCount(0);
await expect(picker.getByText("Before published commit", { exact: true })).toHaveCount(0);
await earlier.click();
await expect(message).toHaveValue("Earlier local commit");
await expect.poll(() => fieldText(message)).toBe("Earlier local commit");
await expect(panel.getByRole("treeitem", { name: /Earlier local commit 1 file/ })).toBeVisible();
await expect(panel.getByRole("treeitem", { name: "earlier.txt", exact: true })).toBeVisible();
await choose.click();
await picker.getByRole("option", { name: /^Amend Last Commit/ }).click();
await expect(message).toHaveValue("Last local commit");
await expect.poll(() => fieldText(message)).toBe("Last local commit");
await panel.getByRole("checkbox", { name: "Amend", exact: true }).uncheck();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await choose.click();
await earlier.click();
@@ -1454,7 +1455,7 @@ test("Amend filters commit subjects while loading and supports keyboard selectio
await search.press("Escape");
await expect(picker).toBeHidden();
await expect(choose).toBeFocused();
await expect(message).toHaveValue("Draft");
await expect.poll(() => fieldText(message)).toBe("Draft");
await choose.press("ArrowDown");
await expect(search).toHaveValue("");
@@ -1470,7 +1471,7 @@ test("Amend filters commit subjects while loading and supports keyboard selectio
await search.dispatchEvent("keydown", { key: "Enter", isComposing: true });
await expect(search).toBeFocused();
await search.press("Enter");
await expect(message).toHaveValue("Improve local docs");
await expect.poll(() => fieldText(message)).toBe("Improve local docs");
await choose.press("ArrowDown");
await expect(docs).toHaveAttribute("aria-selected", "true");
@@ -1503,7 +1504,7 @@ for (const editDraft of [false, true]) {
await panel.getByRole("button", { name: "Choose Commit to Amend", exact: true }).click();
await page.getByRole("option", { name: "Earlier local commit", exact: true }).click();
const message = panel.getByRole("textbox", { name: "Commit message" });
await expect(message).toHaveValue("Earlier local commit");
await expect.poll(() => fieldText(message)).toBe("Earlier local commit");
await panel.getByRole("button", { name: "Amend Commit", exact: true }).click();
const keep = page.getByRole("button", { name: "Create Amend Commit Anyway", exact: true });
@@ -1514,7 +1515,7 @@ for (const editDraft of [false, true]) {
await expect.poll(() => ipcCalls(page, "vcs_keep_amend_commit")).toEqual([{ repo: ROOT, commit: "prepared" }]);
await expect(page.getByText("Amend commit created", { exact: true })).toBeVisible();
expect(await ipcCalls(page, "vcs_commit")).toHaveLength(1);
await expect(message).toHaveValue(editDraft ? "New draft after conflict" : "Earlier local commit");
await expect.poll(() => fieldText(message)).toBe(editDraft ? "New draft after conflict" : "Earlier local commit");
await expect(panel.getByRole("checkbox", { name: "Amend", exact: true })).not.toBeChecked();
if (editDraft)
await expect
+20
Переглянути файл
@@ -132,3 +132,23 @@ test("F4 in the changes tree opens the source file even where activation opens t
await expect(sourceTab(page)).toHaveAttribute("aria-selected", "true");
await expect(diffTab(page)).toHaveCount(0);
});
test("modal Commit dialog shows the selected file's diff below the message, and Preview Diff hides it", async ({
workbench: page,
}, info) => {
await stubRepository(page);
await stubSettingsWrites(page);
await setCommitSetting(page, "nonModal", false);
await page.keyboard.press("Meta+k");
const dialog = page.getByRole("dialog", { name: "Commit Changes" });
const diff = dialog.getByRole("region", { name: "Diff", exact: true });
await expect(diff.getByText("Select a file to preview its changes")).toBeVisible();
await dialog.getByRole("tree", { name: "Changes" }).getByText(FILE, { exact: true }).click();
await expect(diff.locator(".cm-content").first()).toContainText("plugins {}");
await expect(page.getByRole("tab", { name: FILE })).toHaveCount(0);
await page.screenshot({ path: info.outputPath("commit-dialog-diff.png"), animations: "disabled" });
await dialog.getByRole("button", { name: "Preview Diff", exact: true }).click();
await expect(diff).toHaveCount(0);
await dialog.getByRole("button", { name: "Preview Diff", exact: true }).click();
await expect(diff.locator(".cm-content").first()).toContainText("plugins {}");
});
+4 -4
Переглянути файл
@@ -3,7 +3,7 @@
* latest task write the message. The agent and git are stubbed at the IPC layer.
*/
import type { Page } from "@playwright/test";
import { expect, ipcCalls, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, stubDesktop, test } from "./fixtures";
const ROOT = "/dev/acme-api";
const PATCH =
@@ -110,11 +110,11 @@ test("the agent of the latest task writes the commit message of the included cha
await page.keyboard.press("Meta+k");
const panel = page.getByRole("region", { name: "Commit", exact: true });
const message = panel.getByRole("textbox", { name: "Commit message" });
await expect(message).toHaveValue("");
await expect.poll(() => fieldText(message)).toBe("");
await panel.getByRole("button", { name: "Generate Commit Message with Agent" }).click();
await expect(message).toHaveValue("Update the Gradle build\n\nBump the Kotlin plugin.");
await expect.poll(() => fieldText(message)).toBe("Update the Gradle build\n\nBump the Kotlin plugin.");
const [request] = await ipcCalls(page, "agent_create");
const created = request!.request as {
provider: string;
@@ -153,5 +153,5 @@ test("a message typed while the agent works is not overwritten", async ({ workbe
await message.fill("My own message");
await expect(page.getByText("Commit message not replaced")).toBeVisible();
await expect(message).toHaveValue("My own message");
await expect.poll(() => fieldText(message)).toBe("My own message");
});
+3 -3
Переглянути файл
@@ -44,7 +44,7 @@ test("Find Usages places read and write filters with the other actions", async (
}
await actions.getByRole("button", write).click();
await expect(popup.getByRole("option")).toHaveCount(1);
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
await popup.getByRole("button", { name: "Open in Find Tool Window" }).click();
const view = page.getByRole("region", { name: "Find Usages", exact: true });
const toolbar = view.getByRole("toolbar", { name: "Usages actions", exact: true });
@@ -174,7 +174,7 @@ for (const theme of ["light", "dark"] as const) {
await expect(popup.getByRole("region", { name: "Preview", exact: true })).toBeVisible();
await preview.click();
await expect(popup.getByRole("region", { name: "Preview", exact: true })).toHaveCount(0);
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
await popup.getByRole("button", { name: "Open in Find Tool Window" }).click();
const usages = page.getByRole("region", { name: "Find Usages", exact: true });
const usageTree = usages.getByRole("tree", { name: "Usages", exact: true });
@@ -258,7 +258,7 @@ test("Find Usages lines use the tree font and keep line numbers beside the snipp
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
const popupMatch = popup.getByRole("option").first().locator("mark");
const popupFont = await popupMatch.evaluate((node) => getComputedStyle(node).fontFamily);
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
await popup.getByRole("button", { name: "Open in Find Tool Window" }).click();
const usages = page.getByRole("region", { name: "Find Usages", exact: true });
await expect(usages.locator("mark")).toHaveCount(3);
+14 -1
Переглянути файл
@@ -1,5 +1,5 @@
/** Shared helpers: open the workbench with the injected sample project and fail on page errors. */
import { expect, test as base, type Page } from "@playwright/test";
import { expect, test as base, type Locator, type Page } from "@playwright/test";
export const PROJECT = "acme-api";
@@ -146,6 +146,19 @@ export async function stubSettingsWrites(page: Page) {
}
/** The commands the page has invoked so far under `stubDesktop`, by name. */
/** The text of an editor-based field (`src/editor/TextField.tsx`), as a textarea's value: one line per row, placeholder left out. */
export async function fieldText(field: Locator): Promise<string> {
return field.evaluate((el) =>
[...el.querySelectorAll(".cm-line")]
.map((line) => {
const copy = line.cloneNode(true) as Element;
for (const hint of copy.querySelectorAll(".cm-placeholder")) hint.remove();
return copy.textContent ?? "";
})
.join("\n"),
);
}
export async function ipcCalls(page: Page, cmd: string): Promise<Record<string, unknown>[]> {
return page.evaluate((cmd) => window.__ipc.calls.filter((c) => c.cmd === cmd).map((c) => c.args), cmd);
}
+1 -1
Переглянути файл
@@ -88,7 +88,7 @@ test("the Usages preview match covers the whole row", async ({ workbench: page }
});
const popup = page.getByRole("dialog", { name: "Usages", exact: true });
await expect(popup.getByRole("option")).toHaveCount(2);
await popup.getByRole("button", { name: /Open in Find Window/ }).click();
await popup.getByRole("button", { name: "Open in Find Tool Window" }).click();
const view = page.getByRole("region", { name: "Find Usages", exact: true });
const mark = view.locator("mark").first();
await expect(mark).toHaveText("settlement");
+3 -3
Переглянути файл
@@ -1,6 +1,6 @@
import type { Page } from "@playwright/test";
import type { EditorView } from "@codemirror/view";
import { expect, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
import { expect, fieldText, ipcCalls, openFromTree, stubDesktop, test } from "./fixtures";
test("edits the staged version and keeps an unsaved draft when the index changes", async ({ workbench: page }) => {
const root = "/dev/acme-api";
@@ -907,7 +907,7 @@ test("Amend previews the original commit independently of the staged changes", a
const changes = panel.getByRole("tree", { name: "Changes", exact: true });
await message.fill("Unsent draft");
await amend.check();
await expect(message).toHaveValue("Original commit\n\nDescription");
await expect.poll(() => fieldText(message)).toBe("Original commit\n\nDescription");
await expect(changes.getByRole("treeitem", { name: /Original commit 1 file/ })).toHaveAttribute(
"aria-expanded",
"true",
@@ -930,5 +930,5 @@ test("Amend previews the original commit independently of the staged changes", a
await expect(await ipcCalls(page, "vcs_commit")).toHaveLength(0);
await amend.uncheck();
await expect(changes.getByText("Original commit", { exact: true })).toHaveCount(0);
await expect(message).toHaveValue("Unsent draft");
await expect.poll(() => fieldText(message)).toBe("Unsent draft");
});
+1 -1
Переглянути файл
@@ -111,7 +111,7 @@ function showAt(x: number, y: number, scenario: Scenario) {
clearTimeout(pendingLoad);
// A fresh mount also resets any position chosen by the previous drag.
flushSync(() => dismissUsagesPopup());
useUsageAccessOptions.setState({ read: true, write: true });
useUsageAccessOptions.setState({ read: true, write: true, imports: true });
useUsagesPopup.setState({
open: true,
anchor: { x, y },
+2 -2
Переглянути файл
@@ -1,4 +1,4 @@
import { expect, openFromTree, test } from "./fixtures";
import { expect, fieldText, openFromTree, test } from "./fixtures";
test("VCS Operations keeps its centered title visible in a short window", async ({ workbench: page }) => {
await page.setViewportSize({ width: 640, height: 320 });
@@ -45,7 +45,7 @@ test("VCS Operations keeps its centered title visible in a short window", async
await expect(commitWindow).toBeVisible();
const message = commitWindow.getByRole("textbox", { name: "Commit message" });
await expect(message).toBeFocused();
expect(await message.evaluate((el) => (el instanceof HTMLTextAreaElement ? el.value : el.textContent))).toBe("");
expect(await fieldText(message)).toBe("");
});
test("VCS Operations offers repository setup and Local History outside Git", async ({ workbench: page }) => {
+1 -1
Переглянути файл
@@ -755,7 +755,7 @@ pub(crate) async fn check_update(app: &AppHandle, source: UpdateSource) -> IdeRe
let update = tokio::time::timeout(std::time::Duration::from_secs(60), updater.check())
.await
.map_err(|e| IdeError::unavailable(e.to_string()))?
.map_err(|e| IdeError::unavailable(e.to_string()))?;
.map_err(|e| IdeError::unavailable(ide_http::client::describe(&e)))?;
Ok(UpdateCheck {
enabled: true,
update: update.map(|u| UpdateInfo {
+5 -4
Переглянути файл
@@ -195,10 +195,11 @@ pub(crate) async fn download_update(
mut progress: impl FnMut(u64, Option<u64>),
) -> IdeResult<DownloadedUpdate> {
let updater = updater(app, source)?.ok_or_else(|| IdeError::unavailable("updates are not configured"))?;
let update =
cancellable(token, async { updater.check().await.map_err(|error| IdeError::unavailable(error.to_string())) })
.await?
.ok_or_else(|| IdeError::not_found("no update available"))?;
let update = cancellable(token, async {
updater.check().await.map_err(|error| IdeError::unavailable(ide_http::client::describe(&error)))
})
.await?
.ok_or_else(|| IdeError::not_found("no update available"))?;
let directory = app
.path()
.app_cache_dir()
+3 -2
Переглянути файл
@@ -47,7 +47,8 @@ pub(crate) async fn fetch(
if offset > 0 {
request = request.header(RANGE, format!("bytes={offset}-"));
}
let response = request.send().await.map_err(|error| IdeError::unavailable(error.to_string()))?;
let response =
request.send().await.map_err(|error| IdeError::unavailable(ide_http::client::describe(&error)))?;
let status = response.status();
if status == StatusCode::RANGE_NOT_SATISFIABLE && offset > 0 {
@@ -171,7 +172,7 @@ async fn append_body(
progress(downloaded, total);
}
Ok(None) => break Ok(()),
Err(error) => break Err(IdeError::unavailable(error.to_string())),
Err(error) => break Err(IdeError::unavailable(ide_http::client::describe(&error))),
}
};
// tokio writes in the background: flush even when the body broke off, so the bytes
+161
Переглянути файл
@@ -0,0 +1,161 @@
/** The editor-based text field: Vim goes first on Escape, the field stays controlled. */
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render } from "@testing-library/react";
import { useRef, useState } from "react";
import { EditorView } from "@codemirror/view";
import { activate as activateVim } from "@/features/vim";
import { useVimSettings } from "@/features/vim/settings";
import { TextField, type TextFieldHandle } from "./TextField";
const contentOf = (label: string) => {
const el = document.querySelector<HTMLElement>(`[aria-label="${label}"]`);
if (!el) throw new Error("field not rendered");
return el;
};
const viewOf = (label: string): EditorView => {
const view = EditorView.findFromDOM(contentOf(label));
if (!view) throw new Error("not an editor field");
return view;
};
/** Waits until Vim mode's contribution has reached the field (the engine loads lazily). */
const untilVim = async (label: string): Promise<EditorView> => {
const view = viewOf(label);
await vi.waitFor(() => expect(view.dom.getAttribute("data-openidea-vim")).toBeTruthy(), { timeout: 5000 });
return view;
};
/** Parent stores the text, like the commit message store does. */
function renderControlled(label: string, initial: string) {
const onChange = vi.fn();
function Holder() {
const [text, setText] = useState(initial);
return (
<TextField
path="test://field"
ariaLabel={label}
value={text}
onChange={(t) => {
onChange(t);
setText(t);
}}
/>
);
}
render(<Holder />);
return { onChange };
}
/** Parent owns the value outright: rerender replaces it from the outside. */
function renderStatic(label: string, initial: string) {
const onChange = vi.fn();
function Holder({ text }: { text: string }) {
return <TextField path="test://field" ariaLabel={label} value={text} onChange={onChange} />;
}
const { rerender } = render(<Holder text={initial} />);
return { rerender: (next: string) => rerender(<Holder text={next} />) };
}
/** A controlled field exposing the handle, for focus and view assertions. */
function renderHandleField(label: string, initial: string) {
function Holder() {
const [text, setText] = useState(initial);
const ref = useRef<TextFieldHandle>(null);
return (
<>
<TextField path="test://field" ariaLabel={label} value={text} onChange={setText} ref={ref} />
<button onClick={() => ref.current?.focus()}>focus field</button>
</>
);
}
render(<Holder />);
}
afterEach(() => {
useVimSettings.setState({ enabled: false, handlers: {} }, true);
});
describe("TextField", () => {
it("is a focusable editor textbox that reports typed text", () => {
const { onChange } = renderControlled("Field", "");
const view = viewOf("Field");
expect(contentOf("Field").getAttribute("role")).toBe("textbox");
act(() => {
view.focus();
view.dispatch(view.state.replaceSelection("typed"), { userEvent: "input.type" });
});
expect(view.state.doc.toString()).toBe("typed");
expect(onChange).toHaveBeenLastCalledWith("typed");
});
it("follows an external value change", () => {
const { rerender } = renderStatic("Field", "first");
const view = viewOf("Field");
expect(view.state.doc.toString()).toBe("first");
rerender("second");
expect(view.state.doc.toString()).toBe("second");
});
it("keeps the focus in the field while Vim is off and Esc still leaves it", () => {
renderHandleField("Field", "text");
const view = viewOf("Field");
act(() => view.focus());
expect(document.activeElement).toBe(view.contentDOM);
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
});
it("with Vim mode on, Esc leaves Insert mode and keeps the focus in the field", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
renderHandleField("Field", "hello");
const view = await untilVim("Field");
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("insert");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
expect(document.activeElement).toBe(view.contentDOM);
} finally {
disposeVim();
}
});
it("with Vim mode on, a further Esc in Normal mode returns the focus (explicit)", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
renderHandleField("Field", "hello");
const view = await untilVim("Field");
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
} finally {
disposeVim();
}
});
it("with Vim mode on, operators edit the field's text (dd)", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const disposeVim = activateVim();
try {
const { onChange } = renderControlled("Field", "subject\nbody");
const view = await untilVim("Field");
act(() => {
view.focus();
view.dispatch({ selection: { anchor: 0 } });
});
fireEvent.keyDown(view.contentDOM, { key: "d" });
fireEvent.keyDown(view.contentDOM, { key: "d" });
expect(view.state.doc.toString()).toBe("body");
expect(onChange).toHaveBeenLastCalledWith("body");
} finally {
disposeVim();
}
});
});
+194
Переглянути файл
@@ -0,0 +1,194 @@
/**
* A multi-line text field built on the code editor: Vim and every other `embedded`
* editor contribution apply through the shared embedded-editor mechanism
* (`embeddedEditorExtensions`) and are reconfigured live, so with Vim mode on
* `Esc` goes to Vim first and only moves the focus when Vim does not use it.
* The commit message field is the first user (#7024).
*/
import { forwardRef, useImperativeHandle, useLayoutEffect, useRef, type CSSProperties, type RefObject } from "react";
import { Annotation, Compartment, EditorState } from "@codemirror/state";
import { EditorView, keymap, placeholder as cmPlaceholder } from "@codemirror/view";
import { defaultKeymap, history } from "@codemirror/commands";
import { embeddedEditorExtensions } from "./api";
/** Marks a transaction the field itself made (an external value or a host echo): no `onChange`. */
export const fieldEcho = Annotation.define<boolean>();
/** Created once: every `EditorView.theme` call mounts new CSS rules into the document. */
const FIELD_THEME = EditorView.theme({
"&": { height: "100%", backgroundColor: "transparent" },
".cm-scroller": {
backgroundColor: "transparent",
fontFamily: "inherit",
fontWeight: "inherit",
lineHeight: "inherit",
},
".cm-content": { padding: "6px var(--pad, 10px)" },
".cm-line": { padding: "0" },
".cm-placeholder": {
color: "var(--fg-subtle)",
fontFamily: "var(--font-ui)",
fontSize: "var(--fs-ui)",
},
});
export interface TextFieldHandle {
focus(): void;
/** The live editor view, null before mount and after unmount. */
view(): EditorView | null;
}
export interface TextFieldProps {
value: string;
/** Text typed or deleted in the field; not called for the field's own echo transactions. */
onChange: (text: string, view: EditorView) => void;
/** A stable pseudo document path; embedded editor contributions and their events use it. */
path: string;
placeholder?: string;
ariaLabel?: string;
spellCheck?: boolean;
/** Marks the editor as its tool window's late-focus target (`data-autofocus`). */
autoFocus?: boolean;
/** Whether long lines wrap (a textarea-like field always does). */
wrap?: boolean;
/** Reported on the editor as `aria-invalid` (a failed check at the field). */
invalid?: boolean;
/** The editor's content lost the focus. */
onBlur?: () => void;
/** Runs after Vim has had the key; return true when the key was handled. */
onKeyDown?: (event: KeyboardEvent, view: EditorView) => boolean | void;
className?: string;
style?: CSSProperties;
/** Receives the host element, to anchor popups at the field. */
hostRef?: RefObject<HTMLDivElement | null>;
}
/** A controlled editor field; see the module comment. */
export const TextField = forwardRef<TextFieldHandle, TextFieldProps>(function TextField(
{
value,
onChange,
path,
placeholder,
ariaLabel,
spellCheck,
autoFocus,
wrap = true,
invalid,
onBlur,
onKeyDown,
className,
style,
hostRef,
},
ref,
) {
const host = useRef<HTMLDivElement>(null);
const view = useRef<EditorView | null>(null);
const wrapCompartment = useRef(new Compartment());
// The handlers change every render; the view is built once and reads them through refs.
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const onKeyDownRef = useRef(onKeyDown);
onKeyDownRef.current = onKeyDown;
const onBlurRef = useRef(onBlur);
onBlurRef.current = onBlur;
const valueRef = useRef(value);
valueRef.current = value;
useLayoutEffect(() => {
if (!host.current) return;
const editor = new EditorView({
parent: host.current,
state: EditorState.create({
doc: valueRef.current,
extensions: [
FIELD_THEME,
history(),
keymap.of(defaultKeymap),
wrapCompartment.current.of(wrap ? EditorView.lineWrapping : []),
...(placeholder ? [cmPlaceholder(placeholder)] : []),
embeddedEditorExtensions(path),
EditorView.updateListener.of((update) => {
if (!update.docChanged) return;
if (update.transactions.some((tr) => tr.annotation(fieldEcho))) return;
onChangeRef.current?.(update.state.doc.toString(), update.view);
}),
EditorView.domEventHandlers({
keydown(event, current) {
if (onKeyDownRef.current && onKeyDownRef.current(event, current) === true) return true;
// Vim had the key first (its handlers run at highest precedence);
// only an Escape Vim does not use moves the focus, as the textarea's did.
if (event.key === "Escape" && !event.defaultPrevented && !current.composing) {
current.contentDOM.blur();
return true;
}
return false;
},
blur(_event, current) {
// A view being destroyed (unmount, or React re-running the effect) blurs on removal:
// only the live field's blur counts.
if (view.current === current) onBlurRef.current?.();
return false;
},
}),
EditorView.contentAttributes.of({
"aria-label": ariaLabel ?? "",
"aria-multiline": "true",
role: "textbox",
spellcheck: spellCheck ? "true" : "false",
}),
],
}),
});
view.current = editor;
return () => {
view.current = null;
editor.destroy();
};
// The field is created once; `path` identifies it for its lifetime.
// eslint-disable-next-line react-hooks/exhaustive-deps -- placeholder/aria are stable per field
}, []);
useLayoutEffect(() => {
view.current?.dispatch({ effects: wrapCompartment.current.reconfigure(wrap ? EditorView.lineWrapping : []) });
}, [wrap]);
useLayoutEffect(() => {
const editor = view.current;
if (!editor || editor.state.doc.toString() === value) return;
editor.dispatch({
changes: { from: 0, to: editor.state.doc.length, insert: value },
selection: { anchor: value.length },
annotations: fieldEcho.of(true),
});
}, [value]);
// `data-autofocus` moves at runtime (the Commit window takes the activation focus
// only when Commit… asked for the message), like the textarea attribute did. Set before
// paint: the tool window looks for it in the next animation frame.
useLayoutEffect(() => {
const el = view.current?.contentDOM;
if (!el) return;
if (invalid) el.setAttribute("aria-invalid", "true");
else el.removeAttribute("aria-invalid");
if (autoFocus) el.setAttribute("data-autofocus", "true");
else el.removeAttribute("data-autofocus");
}, [invalid, autoFocus]);
useImperativeHandle(ref, () => ({
focus: () => view.current?.focus(),
view: () => view.current,
}));
return (
<div
ref={(el) => {
host.current = el;
if (hostRef) hostRef.current = el;
}}
className={className}
style={style}
/>
);
});
+13 -7
Переглянути файл
@@ -96,7 +96,12 @@ function selectCopiedLines(view: EditorView, lines: ReturnType<typeof distinctCa
});
}
/** Delete whole caret lines, merging adjacent lines and keeping one caret per surviving position. */
/**
* Delete whole caret lines, merging adjacent lines and keeping one caret per surviving position.
* As in IntelliJ (`CutHandler`), each caret goes to the start of the line that takes the cut
* line's place, so repeated cuts take the following lines; after the last line, to the start of
* the line before it.
*/
function cutCaretLines(view: EditorView, lines: ReturnType<typeof distinctCaretLines>) {
const state = view.state;
const spans: Array<[first: number, last: number]> = [];
@@ -113,12 +118,13 @@ function cutCaretLines(view: EditorView, lines: ReturnType<typeof distinctCaretL
}),
);
const doc = changes.apply(state.doc);
const mapped = lines.map(({ line, pos }) => {
const target = doc.lineAt(changes.mapPos(line.from, -1));
return {
line: line.number,
range: EditorSelection.cursor(target.from + Math.min(pos - line.from, target.length)),
};
const mapped = lines.map(({ line }) => {
const last = spans.find(([first, end]) => line.number >= first && line.number <= end)![1];
const target =
last < state.doc.lines
? changes.mapPos(state.doc.line(last + 1).from, 1)
: doc.lineAt(changes.mapPos(line.from, -1)).from;
return { line: line.number, range: EditorSelection.cursor(target) };
});
const unique = mapped.filter(({ range }, i) => mapped.findIndex((other) => other.range.head === range.head) === i);
const mainLine = state.doc.lineAt(state.selection.main.head).number;
+12 -3
Переглянути файл
@@ -360,7 +360,7 @@ describe("line-wise paste", () => {
const view = make("one\ntwo", [5]);
expect(copy(view, "cut")).toBe("two");
expect(view.state.doc.toString()).toBe("one");
expect(view.state.selection.main.head).toBe(1);
expect(view.state.selection.main.head).toBe(0);
expect(clipboardHistory()[0]).toEqual({ text: "two", linewise: true });
});
@@ -401,7 +401,7 @@ describe("line-wise paste", () => {
const view = make("one\ntwo\nthree\nfour\nfive", [1, 2, 15]);
expect(copy(view, "cut")).toBe("one\nfour");
expect(view.state.doc.toString()).toBe("two\nthree\nfive");
expect(view.state.selection.ranges.map((range) => range.head)).toEqual([1, 5]);
expect(view.state.selection.ranges.map((range) => range.head)).toEqual([0, 10]);
expect(clipboardHistory()[0]).toEqual({ text: "one\nfour", linewise: true });
});
@@ -409,7 +409,16 @@ describe("line-wise paste", () => {
const view = make("one\ntwo\nthree\nfour", [1, 2, 5, 9]);
expect(copy(view, "cut")).toBe("one\ntwo\nthree");
expect(view.state.doc.toString()).toBe("four");
expect(view.state.selection.ranges.map((range) => range.head)).toEqual([1]);
expect(view.state.selection.ranges.map((range) => range.head)).toEqual([0]);
});
it("keeps the caret on the cut line's number, at the start of the line moved up, so repeated cuts go down", () => {
const view = make("one\n two\nthree", [6]);
expect(copy(view, "cut")).toBe(" two");
expect(view.state.doc.toString()).toBe("one\nthree");
expect(view.state.selection.main.head).toBe(4);
expect(copy(view, "cut")).toBe("three");
expect(view.state.doc.toString()).toBe("one");
});
it("allows line copy but not deletion in a read-only editor", () => {
+27 -43
Переглянути файл
@@ -16,6 +16,7 @@ vi.mock("./fileAttributes", async (original) => ({
}));
const ctrl = editorController();
const cells: EditorView[] = [];
let disposeActions: () => void;
beforeAll(() => {
disposeActions = registerEditorActions();
@@ -30,6 +31,12 @@ afterEach(() => {
useEditorStatus.setState({ status: null });
useContextKeys.setState({}, true);
_setFocusedCellEditor(null);
// A live view's pending focus timer would run after jsdom is torn down.
for (const view of cells.splice(0)) {
const host = view.dom.parentElement;
view.destroy();
host?.remove();
}
toggleReadOnlyMock.mockClear();
});
@@ -39,32 +46,23 @@ function focusedCell(doc = "x = 1\n"): { view: EditorView; clear: () => void } {
document.body.appendChild(host);
// `columnModeField`: what a cell editor carries through its own extension list.
const view = new EditorView({ doc, parent: host, extensions: columnModeField });
cells.push(view);
view.focus();
if (!view.hasFocus) throw new Error("the jsdom view did not take focus");
_setFocusedCellEditor(view);
return { view, clear: () => _setFocusedCellEditor(null) };
}
function disposeView(cell: { view: EditorView }): void {
cell.view.destroy();
cell.view.dom.remove();
}
describe("editor context keys with a focused notebook cell", () => {
it("keeps the keys on while a cell editor has focus, with no text editor open", () => {
const cell = focusedCell();
try {
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
expect(getContext().editorTextFocus).toBe(true);
// Republishing (tab churn, pane focus) must not drop the keys.
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
expect(getContext().editorTextFocus).toBe(true);
} finally {
cell.clear();
disposeView(cell);
}
focusedCell();
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
expect(getContext().editorTextFocus).toBe(true);
// Republishing (tab churn, pane focus) must not drop the keys.
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
expect(getContext().editorTextFocus).toBe(true);
});
it("lets a focused cell editor win over the mounted but unfocused text editor", async () => {
@@ -75,12 +73,10 @@ describe("editor context keys with a focused notebook cell", () => {
try {
const textView = slot.mount(host);
ctrl.onMounted(slot);
const cell = focusedCell();
focusedCell();
ctrl.publishContext();
expect(getContext().editorTextFocus).toBe(true);
expect(textView.hasFocus).toBe(false);
cell.clear();
disposeView(cell);
} finally {
host.remove();
}
@@ -88,16 +84,12 @@ describe("editor context keys with a focused notebook cell", () => {
it("drops the keys once no cell editor has focus", () => {
const cell = focusedCell();
try {
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
cell.clear();
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(false);
expect(getContext().editorTextFocus).toBe(false);
} finally {
disposeView(cell);
}
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(true);
cell.clear();
ctrl.publishContext();
expect(getContext().textEditorActive).toBe(false);
expect(getContext().editorTextFocus).toBe(false);
});
it("keeps a text tab's own keys when no cell editor is focused", async () => {
@@ -132,8 +124,6 @@ describe("editor actions in a focused notebook cell", () => {
await executeAction("editor.toggleColumnSelection");
expect(isColumnMode(cell.view.state)).toBe(true);
expect(isColumnMode(textView.state)).toBe(false);
cell.clear();
disposeView(cell);
} finally {
host.remove();
}
@@ -183,8 +173,6 @@ describe("editor actions in a focused notebook cell", () => {
} finally {
uninstall();
disposeStub();
cell.clear();
disposeView(cell);
}
});
});
@@ -211,13 +199,9 @@ describe("Copy Path with a notebook tab", () => {
},
},
}));
const cell = focusedCell();
try {
ctrl.publishContext();
expect(ctrl.activePath()).toBe("/p/a.ipynb");
expect(evaluateWhen("textEditorActive", getContext())).toBe(true);
} finally {
cell.clear();
}
focusedCell();
ctrl.publishContext();
expect(ctrl.activePath()).toBe("/p/a.ipynb");
expect(evaluateWhen("textEditorActive", getContext())).toBe(true);
});
});
+8 -4
Переглянути файл
@@ -351,7 +351,11 @@ export function NewProjectDialog({
const [edited, setEdited] = useState<Record<string, Values>>({});
const [dynamic, setDynamic] = useState<{ id: string; key: string; fields: Field[] } | null>(null);
const [dynamicError, setDynamicError] = useState<string | null>(null);
const [requirements, setRequirements] = useState<Requirement[]>([]);
// Tagged with their generator, so another generator's warnings don't linger until its own check returns.
const [requirements, setRequirements] = useState<{ generator: string; list: Requirement[] }>({
generator: "",
list: [],
});
/** Installed SDKs by kind, once detected. */
const [sdks, setSdks] = useState<Partial<Record<string, Sdk[]>>>({});
const detecting = useRef(new Set<string>());
@@ -427,8 +431,8 @@ export function NewProjectDialog({
let live = true;
const timer = setTimeout(() => {
call(commands.scaffoldRequirements(generator.id, JSON.parse(valuesKey) as Values))
.then((r) => live && setRequirements(r))
.catch(() => live && setRequirements([]));
.then((list) => live && setRequirements({ generator: generator.id, list }))
.catch(() => live && setRequirements({ generator: generator.id, list: [] }));
}, 300);
return () => {
live = false;
@@ -492,7 +496,7 @@ export function NewProjectDialog({
}, [path]);
const visibleFields = fields.filter((f) => isVisible(f, values));
const invalidField = visibleFields.find((f) => fieldError(f, values[f.id] ?? ""));
const missing = requirements.filter((r) => !r.satisfied);
const missing = requirements.generator === generator?.id ? requirements.list.filter((r) => !r.satisfied) : [];
const loadingDynamic = !!generator?.dynamic && !dynamicFields.length && !dynamicError;
const invalid =
!generator || !!nameError || !location.trim() || !!invalidField || missing.length > 0 || loadingDynamic;
+20 -1
Переглянути файл
@@ -11,6 +11,7 @@ const mocks = vi.hoisted(() => ({
detect: vi.fn(),
tauri: false,
xcodeIcon: vi.fn(),
requirements: vi.fn(),
}));
const empty: GeneratorInfo = {
id: "empty",
@@ -93,7 +94,7 @@ vi.mock("@/platform/ipc", async (original) => {
...actual.commands,
scaffoldCatalog: () => Promise.resolve([empty, dotnet, appleApp, appleFramework]),
sdkDetect: mocks.detect,
scaffoldRequirements: () => Promise.resolve({ status: "ok", data: [] }),
scaffoldRequirements: mocks.requirements,
scaffoldFreeName: mocks.freeName,
scaffoldTargetTaken: mocks.taken,
scaffoldCreate: mocks.create,
@@ -107,6 +108,9 @@ vi.mock("../windows", async (original) => ({
}));
const ok = <T,>(data: T) => Promise.resolve({ status: "ok" as const, data });
beforeEach(() => {
mocks.requirements.mockImplementation(() => ok([]));
});
const nameInput = () => screen.getByLabelText("Name:");
const createButton = () => screen.getByRole("button", { name: "Create" });
@@ -124,6 +128,21 @@ describe("File › New Project… name and location", () => {
localStorage.clear();
});
it("drops the previous generator's missing-tool warning as soon as another generator is chosen", async () => {
let pending = false;
mocks.requirements.mockImplementation((id: string) => {
if (id !== "dotnet") return pending ? new Promise(() => {}) : ok([]);
return ok([{ program: "dotnet", min: null, found: null, satisfied: false, hint: "" }]);
});
render(<NewProjectOverlay />);
act(() => showNewProject());
fireEvent.click(await screen.findByRole("option", { name: ".NET" }));
expect(await screen.findByText(/dotnet is not installed/)).toBeInTheDocument();
pending = true;
fireEvent.click(screen.getByRole("option", { name: "Empty Project" }));
expect(screen.queryByText(/dotnet is not installed/)).toBeNull();
});
it("starts where the last project was created, named after the first free untitled folder", async () => {
render(<NewProjectOverlay />);
act(() => showNewProject());
+44 -20
Переглянути файл
@@ -8,18 +8,20 @@ import styles from "./UsageAccessFilter.module.css";
export interface UsageAccessOptions {
read: boolean;
write: boolean;
imports: boolean;
}
const STORAGE_KEY = "openidea.usages.accessFilter.v1";
const ALL: UsageAccessOptions = { read: true, write: true, imports: true };
export function loadAccessOptions(): UsageAccessOptions {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "null") as UsageAccessOptions | null;
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? "null") as Partial<UsageAccessOptions> | null;
if (saved && typeof saved.read === "boolean" && typeof saved.write === "boolean" && (saved.read || saved.write))
return saved;
return { read: saved.read, write: saved.write, imports: saved.imports !== false };
} catch {
/* unavailable or invalid storage: show everything */
}
return { read: true, write: true };
return ALL;
}
export const useUsageAccessOptions = create<UsageAccessOptions>(() => loadAccessOptions());
@@ -36,8 +38,13 @@ export function toggleUsageAccess(which: keyof UsageAccessOptions) {
}
}
/** A usage on a line that begins an import statement (`import a.b.C;`, `from a import C`). */
const IMPORT_LINE = /^\s*(?:import(?![\w$])|from\b.*\bimport\b)/;
export const isImportStatement = (u: Usage) => IMPORT_LINE.test(u.text);
export function filterUsageAccess(items: readonly Usage[], options: UsageAccessOptions): Usage[] {
return items.filter((u) => {
if (isImportStatement(u) && !options.imports) return false;
// Old categories and ordinary LSP locations are unclassified. Never infer
// access from an accessor name/category or silently hide unknown entries.
if (!u.access || u.access === "unknown" || u.access === "readWrite") return true;
@@ -46,33 +53,50 @@ export function filterUsageAccess(items: readonly Usage[], options: UsageAccessO
}
export const supportsUsageAccess = (items: readonly Usage[]) => items.some((u) => u.access && u.access !== "unknown");
export const hasImportStatements = (items: readonly Usage[]) => items.some(isImportStatement);
export function UsageAccessFilter({ items, vertical }: { items: readonly Usage[]; vertical?: boolean }) {
const tx = useTx();
const options = useUsageAccessOptions();
if (!supportsUsageAccess(items)) return null;
const access = supportsUsageAccess(items);
const imports = hasImportStatements(items);
if (!access && !imports) return null;
return (
<div
className={clsx(styles.toolbar, vertical && styles.vertical)}
role={vertical ? "group" : "toolbar"}
aria-label={tx("Usage access filters")}
>
<IconButton
icon="show-read-access"
size="small"
iconSize={16}
title="Show read accesses"
pressed={options.read}
onClick={() => toggleUsageAccess("read")}
/>
<IconButton
icon="show-write-access"
size="small"
iconSize={16}
title="Show write accesses"
pressed={options.write}
onClick={() => toggleUsageAccess("write")}
/>
{access && (
<>
<IconButton
icon="show-read-access"
size="small"
iconSize={16}
title="Show read accesses"
pressed={options.read}
onClick={() => toggleUsageAccess("read")}
/>
<IconButton
icon="show-write-access"
size="small"
iconSize={16}
title="Show write accesses"
pressed={options.write}
onClick={() => toggleUsageAccess("write")}
/>
</>
)}
{imports && (
<IconButton
icon="show-import-statements"
size="small"
iconSize={16}
title="Show import statements"
pressed={options.imports}
onClick={() => toggleUsageAccess("imports")}
/>
)}
</div>
);
}
-14
Переглянути файл
@@ -58,20 +58,6 @@
font-size: var(--fs-small);
color: var(--fg-subtle);
}
.link {
max-width: 100%;
border: none;
background: none;
padding: 0;
font: inherit;
color: var(--link);
text-align: left;
cursor: pointer;
}
.link:hover {
color: var(--link-hover);
text-decoration: underline;
}
.body {
flex: 1 1 0;
display: flex;
+8 -5
Переглянути файл
@@ -1,6 +1,6 @@
/**
* ⌥⌘F7 Show Usages: popup list at the caret with speed search (typing
* filters), an optional code preview and "Open in Find Window", which moves
* filters), an optional code preview and "Open in Find Tool Window", which moves
* the found usages to the Find Usages tool window.
*/
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent } from "react";
@@ -506,10 +506,13 @@ function UsagesPopupInner() {
setUsagesPopupPreview(!preview);
}}
/>
<button type="button" className={styles.link} onClick={openInFindWindow}>
{tx("Open in Find Window")}
{keys ? ` ${keys}` : ""}
</button>
<IconButton
icon="open-in-tool-window"
size="small"
title="Open in Find Tool Window"
shortcut={keys}
onClick={openInFindWindow}
/>
</div>
</div>
{note && (
+64 -13
Переглянути файл
@@ -1,5 +1,12 @@
import { afterEach, describe, expect, it } from "vitest";
import { filterUsageAccess, loadAccessOptions, toggleUsageAccess, useUsageAccessOptions } from "./UsageAccessFilter";
import {
filterUsageAccess,
hasImportStatements,
isImportStatement,
loadAccessOptions,
toggleUsageAccess,
useUsageAccessOptions,
} from "./UsageAccessFilter";
import type { Usage } from "./usages";
const rows: Usage[] = ["read", "write", "readWrite", "unknown", undefined].map((access, line) => ({
path: "/Bean.java",
@@ -9,29 +16,73 @@ const rows: Usage[] = ["read", "write", "readWrite", "unknown", undefined].map((
text: "x",
access: access as Usage["access"],
}));
const statement = (text: string): Usage => ({ path: "/Bean.java", line: 9, col: 7, endCol: 11, text });
afterEach(() => {
localStorage.clear();
useUsageAccessOptions.setState({ read: true, write: true });
useUsageAccessOptions.setState({ read: true, write: true, imports: true });
});
describe("read/write visibility", () => {
it("matches all three reachable states and retains unknown/legacy rows", () => {
expect(filterUsageAccess(rows, { read: true, write: true })).toHaveLength(5);
expect(filterUsageAccess(rows, { read: true, write: false }).map((u) => u.line)).toEqual([0, 2, 3, 4]);
expect(filterUsageAccess(rows, { read: false, write: true }).map((u) => u.line)).toEqual([1, 2, 3, 4]);
expect(filterUsageAccess([{ ...rows[4]!, kind: "getter" }], { read: false, write: true })).toHaveLength(1);
expect(filterUsageAccess(rows, { read: true, write: true, imports: true })).toHaveLength(5);
expect(filterUsageAccess(rows, { read: true, write: false, imports: true }).map((u) => u.line)).toEqual([
0, 2, 3, 4,
]);
expect(filterUsageAccess(rows, { read: false, write: true, imports: true }).map((u) => u.line)).toEqual([
1, 2, 3, 4,
]);
expect(
filterUsageAccess([{ ...rows[4]!, kind: "getter" }], { read: false, write: true, imports: true }),
).toHaveLength(1);
});
it("turns the other button on when the last visible access is turned off", () => {
toggleUsageAccess("write");
expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: false });
expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: false, imports: true });
toggleUsageAccess("read");
expect(useUsageAccessOptions.getState()).toEqual({ read: false, write: true });
expect(useUsageAccessOptions.getState()).toEqual({ read: false, write: true, imports: true });
toggleUsageAccess("write");
expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: false });
expect(loadAccessOptions()).toEqual({ read: true, write: false });
expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: false, imports: true });
expect(loadAccessOptions()).toEqual({ read: true, write: false, imports: true });
});
it("starts with both on and repairs invalid persisted state", () => {
expect(loadAccessOptions()).toEqual({ read: true, write: true });
it("starts with everything on and repairs invalid persisted state", () => {
expect(loadAccessOptions()).toEqual({ read: true, write: true, imports: true });
localStorage.setItem("openidea.usages.accessFilter.v1", '{"read":false,"write":false}');
expect(loadAccessOptions()).toEqual({ read: true, write: true });
expect(loadAccessOptions()).toEqual({ read: true, write: true, imports: true });
// Settings saved before the import filter existed.
localStorage.setItem("openidea.usages.accessFilter.v1", '{"read":true,"write":false}');
expect(loadAccessOptions()).toEqual({ read: true, write: false, imports: true });
});
});
describe("import statements", () => {
it("recognises the lines that begin an import statement", () => {
for (const text of [
"import com.baomidou.mybatisplus.core.mapper.BaseMapper;",
" import static java.util.Objects.requireNonNull;",
'import { Bean } from "./bean";',
"from myapp.models import Bean",
"import lombok.Data",
])
expect(isImportStatement(statement(text))).toBe(true);
for (const text of ["Bean bean = new Bean();", 'const m = await import("./mod");', "important(1)", ""])
expect(isImportStatement(statement(text))).toBe(false);
expect(hasImportStatements(rows)).toBe(false);
expect(hasImportStatements([...rows, statement("import a.B;")])).toBe(true);
});
it("hides only import statements when turned off, whatever their access", () => {
const items = [
statement("import a.Bean;"),
{ ...statement("import a.Bean;"), kind: "field" as const, access: "read" as const },
{ ...statement("Bean b;"), kind: "field" as const, access: "read" as const },
statement("Bean b;"),
];
expect(filterUsageAccess(items, { read: true, write: true, imports: false })).toEqual([items[2], items[3]]);
expect(filterUsageAccess(items, { read: false, write: true, imports: true })).toEqual([items[0], items[3]]);
expect(filterUsageAccess(items, { read: false, write: true, imports: false })).toEqual([items[3]]);
});
it("toggles independently of the read/write buttons and persists", () => {
toggleUsageAccess("imports");
expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: true, imports: false });
expect(loadAccessOptions()).toEqual({ read: true, write: true, imports: false });
toggleUsageAccess("imports");
expect(useUsageAccessOptions.getState()).toEqual({ read: true, write: true, imports: true });
});
});
+2 -2
Переглянути файл
@@ -35,7 +35,7 @@ it("shows a plain count for unclassified searches after a Java access mode was s
const { useUsages } = await import("./usages");
const { useUsageAccessOptions } = await import("./UsageAccessFilter");
const rows = [0, 1].map((line) => ({ path: "/p/a.ts", line, col: 0, endCol: 3, text: "foo()" }));
useUsageAccessOptions.setState({ read: true, write: false });
useUsageAccessOptions.setState({ read: true, write: false, imports: true });
useUsages.setState({
tabs: [
{
@@ -55,6 +55,6 @@ it("shows a plain count for unclassified searches after a Java access mode was s
expect(screen.getByText("2 results")).toBeInTheDocument();
expect(screen.queryByRole("group", { name: "Usage access filters" })).toBeNull();
view.unmount();
useUsageAccessOptions.setState({ read: true, write: true });
useUsageAccessOptions.setState({ read: true, write: true, imports: true });
useUsages.setState({ tabs: [], active: null });
});
+4 -4
Переглянути файл
@@ -26,7 +26,7 @@ const { useUsages } = await import("./usages");
const { useUsageAccessOptions } = await import("./UsageAccessFilter");
const { useProject } = await import("@/platform/project");
const ALL = { read: true, write: true };
const ALL = { read: true, write: true, imports: true };
const usage = (path: string, line: number, text: string, access?: Usage["access"]): Usage => ({
path,
line,
@@ -96,7 +96,7 @@ describe("usagesReportText", () => {
});
it("applies the access filter and drops files it empties", () => {
const text = usagesReportText(search(), "/p", { read: false, write: true }, new Set());
const text = usagesReportText(search(), "/p", { read: false, write: true, imports: true }, new Set());
expect(text).toBe(
[
"Usages of 'total' in Project Files",
@@ -181,7 +181,7 @@ describe("exportUsagesToTextFile", () => {
show(search({ loading: true }));
expect(canExportUsages()).toBe(false);
show(search({ groups: [{ path: "/p/a.ts", usages: [usage("/p/a.ts", 0, "total = 1", "write")] }] }));
useUsageAccessOptions.setState({ read: true, write: false });
useUsageAccessOptions.setState({ read: true, write: false, imports: true });
expect(canExportUsages()).toBe(false);
await exportUsagesToTextFile();
expect(save).not.toHaveBeenCalled();
@@ -215,7 +215,7 @@ describe("toolbar", () => {
expect(button).toBeDisabled();
expect(canExportUsages()).toBe(false);
act(() => show(search({ groups: [{ path: "/p/a.ts", usages: [usage("/p/a.ts", 0, "total = 1", "write")] }] })));
act(() => useUsageAccessOptions.setState({ read: true, write: false }));
act(() => useUsageAccessOptions.setState({ read: true, write: false, imports: true }));
expect(screen.getByRole("button", { name: "Export to Text File…" })).toBeDisabled();
view.unmount();
});
+28 -3
Переглянути файл
@@ -67,7 +67,7 @@ const { useUsageAccessOptions } = await import("./UsageAccessFilter");
afterEach(() =>
act(() => {
dismissUsagesPopup();
useUsageAccessOptions.setState({ read: true, write: true });
useUsageAccessOptions.setState({ read: true, write: true, imports: true });
localStorage.removeItem("openidea.usages.accessFilter.v1");
localStorage.removeItem("openidea.usages.popupSize.v1");
}),
@@ -96,7 +96,7 @@ describe("Show Usages popup", () => {
it("Open in Find Window moves the found usages instead of searching again", () => {
open();
fireEvent.click(screen.getByText(/Open in Find Window/));
fireEvent.click(screen.getByRole("button", { name: "Open in Find Tool Window" }));
expect(useUsagesPopup.getState().open).toBe(false);
expect(showUsageResults).toHaveBeenCalledWith({
symbol: "foo",
@@ -213,7 +213,7 @@ describe("semantic usage categories", () => {
fireEvent.click(screen.getByRole("button", { name: "Show read accesses" }));
expect(screen.getByRole("button", { name: "Show write accesses" })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByText("3 of 4 found")).toBeInTheDocument();
fireEvent.click(screen.getByText(/Open in Find Window/));
fireEvent.click(screen.getByRole("button", { name: "Open in Find Tool Window" }));
expect(showUsageResults).toHaveBeenLastCalledWith(
expect.objectContaining({
classified: expect.arrayContaining([
@@ -242,6 +242,31 @@ it("keeps unknown results visible after classified results are replaced", () =>
expect(screen.getAllByRole("option")).toHaveLength(3);
});
it("filters import statements of a target without read/write classification", () => {
open();
act(() =>
useUsagesPopup.setState({
groups: [
{
path: "/p/Service.java",
usages: [
usage("/p/Service.java", 0, "import com.baomidou.mybatisplus.core.mapper.BaseMapper;"),
usage("/p/Service.java", 5, "public interface Service extends BaseMapper<Entity> {}"),
],
},
],
}),
);
expect(screen.queryByRole("button", { name: "Show read accesses" })).toBeNull();
expect(screen.getAllByRole("option")).toHaveLength(2);
fireEvent.click(screen.getByRole("button", { name: "Show import statements" }));
expect(screen.getByRole("button", { name: "Show import statements" })).toHaveAttribute("aria-pressed", "false");
expect(screen.getByText("1 of 2 found")).toBeInTheDocument();
expect(screen.getAllByRole("option")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Show import statements" }));
expect(screen.getAllByRole("option")).toHaveLength(2);
});
it("preserves an exact multiline semantic range when transferring to Find", () => {
const sourceLocation = { path: "/Bean.java", range: { start: { line: 1, col: 0 }, end: { line: 2, col: 10 } } };
expect(
+4
Переглянути файл
@@ -324,12 +324,15 @@ export function activate(): () => void {
id: "project.trust",
title: "Trust Project",
category: "Project",
// A remote open asks while it is already opening.
whileProjectOpens: true,
run: trustProject,
},
{
id: "project.previewRestricted",
title: "Preview in Restricted Mode",
category: "Project",
whileProjectOpens: true,
hidden: true,
run: () => decide(false),
},
@@ -337,6 +340,7 @@ export function activate(): () => void {
id: "project.dontOpen",
title: "Don't Open",
category: "Project",
whileProjectOpens: true,
hidden: true,
run: () => usePrompt.getState().finish?.(false),
},
+24
Переглянути файл
@@ -84,6 +84,30 @@ it("asks in a remote window when only the server has a trust decision, and recor
expect(remoteDecide).toHaveBeenCalledWith(false, false);
});
it("answers a remote open's prompt while the window is already opening the project (#8302)", async () => {
remoteSession();
useProject.setState({ openingPath: "/srv/app" });
try {
render(<OverlayHost />);
const trusted = confirmProjectTrust("/srv/app");
await screen.findByRole("dialog");
fireEvent.click(screen.getByRole("button", { name: "Trust Project" }));
await act(async () => trusted);
expect(remoteDecide).toHaveBeenCalledWith(true, false);
const preview = confirmProjectTrust("/srv/app");
await screen.findByRole("dialog");
fireEvent.click(screen.getByRole("button", { name: "Preview in Restricted Mode" }));
await act(async () => preview);
expect(remoteDecide).toHaveBeenLastCalledWith(false, false);
const cancelled = confirmProjectTrust("/srv/app").catch(() => "cancelled");
await screen.findByRole("dialog");
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
expect(await cancelled).toBe("cancelled");
} finally {
useProject.setState({ openingPath: null });
}
});
it("trusts a remote project's folder on this machine too", async () => {
remoteSession();
render(<OverlayHost />);
+28 -13
Переглянути файл
@@ -4,19 +4,34 @@
import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
gradle.projectsEvaluated {
allprojects {
each(tasks.matching { it.name == 'bootRun' }) { task ->
def token = System.getProperty('openidea.run.token')
if (token) task.jvmArgs('-Dopenidea.run.token=' + token)
if (System.getProperty('openidea.run.debug') == 'true') {
task.debug = false
task.doFirst {
task.setJvmArgs(task.jvmArgs.findAll {
!it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:')
})
task.jvmArgs('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0')
}
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`.
def afterProjects = { Closure action -> isolated ? gradle.lifecycle.afterProject { p -> p.afterEvaluate(action) } : gradle.projectsEvaluated { allprojects(action) } }
afterProjects { p ->
each(p.tasks.matching { it.name == 'bootRun' }) { task ->
def token = System.getProperty('openidea.run.token')
if (token) task.jvmArgs('-Dopenidea.run.token=' + token)
if (System.getProperty('openidea.run.debug') == 'true') {
task.debug = false
task.doFirst {
task.setJvmArgs(task.jvmArgs.findAll {
!it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:')
})
task.jvmArgs('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0')
}
}
}
+17 -1
Переглянути файл
@@ -6,10 +6,26 @@ import groovy.json.JsonSlurper
import org.gradle.util.GradleVersion
def lazyTasks = GradleVersion.current() >= GradleVersion.version('4.9')
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
// Gradle 7.0 and older give a build JVM with its own `org.gradle.jvmargs` the command line's
// `-D` values only once the settings load, after init scripts run: read them in project actions (#4093).
allprojects { p ->
eachProject { p ->
// An identity path (`:lib:core` for a project of an included build); none: not a delegated run.
def id = { try { p.identityPath.toString() } catch (ignored) { p.path } }
if (id() != System.getProperty('openidea.run.project')) return
+1 -1
Переглянути файл
@@ -296,7 +296,7 @@ describe("Build and run using: Gradle", () => {
const run = delegatedGradleConfig(app, module, { ...ctx, configurationCache: false })!;
expect(run.args).toContain(`-Dopenidea.run.project=${project}`);
expect(run.args.at(-1)).toBe(task);
// The init script compares each project's identity path with it inside `allprojects`.
// The init script compares each project's identity path with it.
expect(RUN_SCRIPT).toContain("if (id() != System.getProperty('openidea.run.project')) return");
});
+29 -13
Переглянути файл
@@ -6,6 +6,24 @@ import org.gradle.util.GradleVersion
// `configureEach` (lazy) is Gradle 4.9+; older ones configure each task as it is added.
def each = { tasks, Closure action -> GradleVersion.current() >= GradleVersion.version('4.9') ? tasks.configureEach(action) : tasks.all(action) }
// Isolated Projects forbids reading other projects (`allprojects`, `projectsEvaluated`): there
// (Gradle 8.8+) each project is configured on its own instead. Its `BuildFeatures` (8.5+) is
// only injected, so a class compiled here reads it.
def isolated = false
// When that fails, the build is treated as one without Isolated Projects.
if (GradleVersion.current() >= GradleVersion.version('8.8')) try {
def features = new GroovyClassLoader(Gradle.classLoader).parseClass('''
abstract class OpenideaIsolatedProjects implements org.gradle.api.Plugin<org.gradle.api.invocation.Gradle> {
@javax.inject.Inject abstract org.gradle.api.configuration.BuildFeatures getFeatures()
boolean active
void apply(org.gradle.api.invocation.Gradle gradle) { active = features.isolatedProjects.active.getOrElse(false) }
}''')
gradle.pluginManager.apply(features)
isolated = gradle.plugins.getPlugin(features).active
} catch (Throwable ignored) {}
def eachProject = { Closure action -> isolated ? gradle.lifecycle.beforeProject(action) : allprojects(action) }
// After the project's own `afterEvaluate` callbacks, as with `projectsEvaluated`.
def afterProjects = { Closure action -> isolated ? gradle.lifecycle.afterProject { p -> p.afterEvaluate(action) } : gradle.projectsEvaluated { allprojects(action) } }
def tc = { String s ->
s == null ? '' : s.replace('|', '||').replace("'", "|'").replace('\n', '|n').replace('\r', '|r')
@@ -25,8 +43,8 @@ def id = { TestDescriptor test ->
"${own} invocation='${tc(shown)}'"
}
allprojects {
each(tasks.withType(Test)) { Test task ->
eachProject { p ->
each(p.tasks.withType(Test)) { Test task ->
task.outputs.upToDateWhen { false }
task.addTestListener(new TestListener() {
void beforeSuite(TestDescriptor suite) {}
@@ -63,17 +81,15 @@ allprojects {
}
// Replace build-configured agents only for this debug launch, after project configuration.
gradle.projectsEvaluated {
allprojects {
each(tasks.withType(Test)) { Test task ->
if (System.getProperty('openidea.run.debug') == 'true') {
task.debug = false
task.doFirst {
task.setJvmArgs(task.jvmArgs.findAll {
!it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:')
})
task.jvmArgs('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0')
}
afterProjects { p ->
each(p.tasks.withType(Test)) { Test task ->
if (System.getProperty('openidea.run.debug') == 'true') {
task.debug = false
task.doFirst {
task.setJvmArgs(task.jvmArgs.findAll {
!it.startsWith('-agentlib:jdwp=') && !it.startsWith('-Xrunjdwp:')
})
task.jvmArgs('-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:0')
}
}
}
+2 -2
Переглянути файл
@@ -52,12 +52,12 @@ afterEach(() => {
describe(".NET settings page", () => {
it("shows the SDK in use, every installed one, and offers each version once", async () => {
page({});
await waitFor(() => expect(combo()).toHaveTextContent("Not pinned"));
expect(screen.getAllByRole("listitem").map((item) => item.textContent)).toEqual([
expect((await screen.findAllByRole("listitem")).map((item) => item.textContent)).toEqual([
"11.0.100-rc.1.26425.101 · /usr/local/share/dotnet/sdk",
"10.0.401 · /usr/local/share/dotnet/sdk",
"10.0.401 · /work/app/.dotnet/sdk",
]);
expect(combo()).toHaveTextContent("Not pinned");
expect(alerts()).toEqual([]);
fireEvent.click(combo());
expect(await screen.findAllByRole("option")).toHaveLength(2);
+11
Переглянути файл
@@ -8,10 +8,21 @@
border-radius: var(--radius-small);
overflow: hidden;
}
/* With the diff below, the dialog is taller, as IDEA's with its Diff details shown. */
.withDiff {
height: min(860px, 82vh);
}
.split {
flex: 1;
min-height: 0;
}
.diff {
height: 100%;
min-height: 0;
display: flex;
flex-direction: column;
border-top: 1px solid var(--border);
}
.options {
height: 100%;
overflow: auto;
+54 -33
Переглянути файл
@@ -6,6 +6,7 @@
* the Commit tool window.
*/
import { useEffect } from "react";
import clsx from "clsx";
import type { FileStatus } from "@/bindings";
import { tx } from "@/platform/i18n";
import { Dialog, Select, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui";
@@ -15,6 +16,7 @@ import { useCommit } from "./commitStore";
import {
ChangesTree,
CommitMessageField,
DialogDiffPreview,
commitAndPushLabel,
commitLabel,
useCommitRunner,
@@ -109,12 +111,13 @@ function CommitDialog({ onClose }: { onClose: () => void }) {
const remoteBusy = useVcs((s) => s.remoteBusy);
const git = useCommitTargetsGit();
const runner = useCommitRunner(included, onClose);
const diff = useCommit((s) => s.dialogDiffPreview);
return (
<Dialog
open
title="Commit Changes"
onClose={onClose}
width={880}
width={diff ? 1040 : 880}
buttons={[
{
label: commitLabel(amend, blocked),
@@ -138,45 +141,63 @@ function CommitDialog({ onClose }: { onClose: () => void }) {
{ label: "Cancel", role: "cancel" },
]}
>
<div className={styles.body}>
<SplitGroup orientation="vertical" className={styles.split} storageKey="openidea.vcs.commitDialogSplit">
<SplitPanel id="top" defaultSize="58%" minSize="25%">
<SplitGroup
orientation="horizontal"
className={styles.split}
storageKey="openidea.vcs.commitDialogOptionsSplit"
>
<SplitPanel id="changes" defaultSize="64%" minSize="35%">
<div className={styles.changes}>
<ChangelistChooser />
<div className={styles.tree}>
<ChangesTree mode="dialog" />
</div>
{legend.length > 0 && (
<div className={styles.legend} role="status" aria-label={tx("Included changes")}>
{legend.map(({ kind, text }) => (
<span key={kind} className={styles[kind]}>
{text}
</span>
))}
<div className={clsx(styles.body, diff && styles.withDiff)}>
<SplitGroup
orientation="vertical"
className={styles.split}
storageKey={diff ? "openidea.vcs.commitDialogDiffSplit" : undefined}
>
<SplitPanel id="main" defaultSize={diff ? "60%" : "100%"} minSize="45%">
<SplitGroup orientation="vertical" className={styles.split} storageKey="openidea.vcs.commitDialogSplit">
<SplitPanel id="top" defaultSize="58%" minSize="25%">
<SplitGroup
orientation="horizontal"
className={styles.split}
storageKey="openidea.vcs.commitDialogOptionsSplit"
>
<SplitPanel id="changes" defaultSize="64%" minSize="35%">
<div className={styles.changes}>
<ChangelistChooser />
<div className={styles.tree}>
<ChangesTree mode="dialog" />
</div>
{legend.length > 0 && (
<div className={styles.legend} role="status" aria-label={tx("Included changes")}>
{legend.map(({ kind, text }) => (
<span key={kind} className={styles[kind]}>
{text}
</span>
))}
</div>
)}
</div>
)}
</div>
</SplitPanel>
<SplitHandle />
<SplitPanel id="options" defaultSize="36%" minSize="200px">
<div className={styles.options} role="group" aria-label={tx("Commit Options")}>
<CommitOptionsBody />
</div>
</SplitPanel>
</SplitGroup>
</SplitPanel>
<SplitHandle />
<SplitPanel id="options" defaultSize="36%" minSize="200px">
<div className={styles.options} role="group" aria-label={tx("Commit Options")}>
<CommitOptionsBody />
<SplitPanel id="message" defaultSize="42%" minSize="120px">
<div className={viewStyles.commit}>
<CommitMessageField runner={runner} onOpenToolWindow={onClose} />
</div>
</SplitPanel>
</SplitGroup>
</SplitPanel>
<SplitHandle />
<SplitPanel id="message" defaultSize="42%" minSize="120px">
<div className={viewStyles.commit}>
<CommitMessageField runner={runner} onOpenToolWindow={onClose} />
</div>
</SplitPanel>
{diff && (
<>
<SplitHandle />
<SplitPanel id="diff" defaultSize="40%" minSize="120px">
<div className={styles.diff} role="region" aria-label={tx("Diff")}>
<DialogDiffPreview />
</div>
</SplitPanel>
</>
)}
</SplitGroup>
</div>
</Dialog>
+2 -10
Переглянути файл
@@ -193,16 +193,13 @@
flex: 1;
min-height: 40px;
margin: 0;
padding: 6px var(--pad);
resize: none;
border: 0;
border-top: 1px solid var(--border);
outline: none;
color: var(--fg-strong);
line-height: var(--lh-code);
-webkit-user-select: text;
user-select: text;
/* Right margin guide at the subject length limit. */
/* Right margin guide at the subject length limit; the editor's content
carries the same 6px / var(--pad) padding (src/editor/TextField.tsx). */
background:
linear-gradient(
to right,
@@ -214,11 +211,6 @@
no-repeat,
var(--bg-island, var(--bg-app));
}
.message::placeholder {
color: var(--fg-subtle);
font-family: var(--font-ui);
font-size: var(--fs-ui);
}
.commitAuthor {
display: flex;
align-items: baseline;
+59 -30
Переглянути файл
@@ -18,6 +18,8 @@ import {
} from "react";
import { tx, txPart, txTemplate } from "@/platform/i18n";
import clsx from "clsx";
import { EditorSelection } from "@codemirror/state";
import { TextField, fieldEcho, type TextFieldHandle } from "@/editor/TextField";
import { executeAction } from "@/platform/actions";
import { fontWeightOf } from "@/platform/editorSettings";
import { resolveMonoFont } from "@/platform/fonts";
@@ -116,6 +118,7 @@ import {
pendingFixup,
setAmend,
setCommitDiffPreview,
setDialogDiffPreview,
setDiffPreview,
setGroupByDir,
setGroupByModule,
@@ -816,6 +819,19 @@ function ChangesPanel() {
);
}
/** The Commit dialog's diff of the selected file, below the changes and the message. */
export function DialogDiffPreview() {
const path = useCommit((s) => (s.selection.length === 1 ? s.selection[0] : null));
const preview = usePreviewDiff("dialog", path);
return preview.data ? (
<DiffEditor input={diffInput(preview.data)} onNeighbour={preview.onNeighbour} />
) : (
<EmptyState>
<T>Select a file to preview its changes</T>
</EmptyState>
);
}
/**
* The Git window's Local Changes tab: a diff preview beside the tree when
* bottom-docked, below it when side-docked (off via View Options › Show Diff Preview).
@@ -875,7 +891,7 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
const groupByModule = useCommit((s) => s.groupByModule);
const showUnversionedSeparately = useCommit((s) => s.showUnversionedSeparately);
const diffPreview = useCommit((s) => s.diffPreview);
const commitDiffPreview = useCommit((s) => s.commitDiffPreview);
const commitDiffPreview = useCommit((s) => (mode === "dialog" ? s.dialogDiffPreview : s.commitDiffPreview));
const doubleClickOpensDiff = useWorkflowSettings((s) => s.vcs.commit.doubleClickOpensDiff);
const changelists = useChangelists((s) => s.state);
// The Commit Changes dialog shows the changelist chosen above it, and the unversioned files.
@@ -977,17 +993,16 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
);
// The embedded diff preview walks this tree's files and asks it to select the one it moved to.
const previewTree = dialogMode ? null : mode;
const previewTree: PreviewTree = mode;
const previewFiles = useMemo(
() => [...new Set(changeFileNodes(roots).flatMap((n) => (n.historicalDiff || !n.path ? [] : [n.path])))],
[roots],
);
useEffect(() => {
if (previewTree) publishPreviewFiles(previewTree, previewFiles);
publishPreviewFiles(previewTree, previewFiles);
}, [previewTree, previewFiles]);
useEffect(() => () => void (previewTree && publishPreviewFiles(previewTree, undefined)), [previewTree]);
useEffect(() => () => publishPreviewFiles(previewTree, undefined), [previewTree]);
useEffect(() => {
if (!previewTree) return;
return useChangesPreview.subscribe(({ moved }, prev) => {
if (!moved || moved === prev.moved || moved.tree !== previewTree) return;
const node = [...byKey.values()].find((n) => n.type === "file" && n.path === moved.path && !n.historicalDiff);
@@ -1155,13 +1170,15 @@ export function ChangesTree({ mode, amended }: { mode: "commit" | "local" | "dia
}
/>
{/* WebStorm's Preview Diff: an embedded diff of the selection beside the changes (#1599). */}
{mode === "commit" && (
{mode !== "local" && (
<IconButton
icon="editor-preview"
title="Preview Diff"
size="small"
pressed={commitDiffPreview}
onClick={() => setCommitDiffPreview(!commitDiffPreview)}
onClick={() =>
mode === "dialog" ? setDialogDiffPreview(!commitDiffPreview) : setCommitDiffPreview(!commitDiffPreview)
}
/>
)}
</div>
@@ -1562,7 +1579,8 @@ export function CommitMessageField({
const amend = useCommit((s) => s.amend);
const focusTick = useCommit((s) => s.focusTick);
const messageFocus = useCommit((s) => s.messageFocus);
const ref = useRef<HTMLTextAreaElement>(null);
const field = useRef<TextFieldHandle>(null);
const fieldAnchor = useRef<HTMLDivElement>(null);
const [historyOpen, setHistoryOpen] = useState(false);
const historyTick = useCommit((s) => s.historyTick);
const { emptyError } = runner;
@@ -1570,7 +1588,7 @@ export function CommitMessageField({
const hasAvailableRepo = useVcs((s) => s.roots.length > 0 || s.unavailableRoots.length === 0);
useEffect(() => {
if (focusTick) ref.current?.focus();
if (focusTick) field.current?.focus();
}, [focusTick]);
// Show Commit Message History (⌃M) asks through the store.
const [seenHistoryTick, setSeenHistoryTick] = useState(historyTick);
@@ -1613,7 +1631,7 @@ export function CommitMessageField({
<Popup
open={historyOpen}
onClose={() => setHistoryOpen(false)}
anchor={ref}
anchor={fieldAnchor}
placement="top-start"
offset={3}
role="presentation"
@@ -1631,7 +1649,7 @@ export function CommitMessageField({
verbatim: true,
run: () => {
useCommit.setState({ message: m });
ref.current?.focus();
field.current?.focus();
},
}))}
/>
@@ -1644,14 +1662,12 @@ export function CommitMessageField({
</span>
)}
</div>
<textarea
ref={ref}
data-autofocus={!focusOnRequest || messageFocus || undefined}
onBlur={() => {
if (useCommit.getState().messageFocus) useCommit.setState({ messageFocus: false });
}}
<TextField
ref={field}
hostRef={fieldAnchor}
path="openidea://commit-message"
className={clsx(styles.message, !showMargin && styles.noMargin, emptyError && styles.messageError)}
aria-invalid={emptyError || undefined}
invalid={emptyError}
style={{
["--guide" as string]: `${margin}ch`,
...messageFont,
@@ -1659,23 +1675,34 @@ export function CommitMessageField({
}}
value={message}
placeholder={tx("Commit Message")}
aria-label={tx("Commit message")}
ariaLabel={tx("Commit message")}
spellCheck
onChange={(e) => {
const el = e.target;
autoFocus={!focusOnRequest || messageFocus || false}
onBlur={() => {
if (useCommit.getState().messageFocus) useCommit.setState({ messageFocus: false });
}}
wrap
onChange={(text, view) => {
const wrapped =
cfg.limitBody && cfg.wrapAtMargin ? wrapAtMargin(el.value, el.selectionStart, cfg.bodyLimit) : null;
useCommit.setState({ message: wrapped?.text ?? el.value });
cfg.limitBody && cfg.wrapAtMargin
? wrapAtMargin(text, view.state.selection.main.head, cfg.bodyLimit)
: null;
useCommit.setState({ message: wrapped?.text ?? text });
runner.clearEmptyError();
if (wrapped) requestAnimationFrame(() => el.setSelectionRange(wrapped.caret, wrapped.caret));
if (wrapped)
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: wrapped.text },
selection: EditorSelection.cursor(wrapped.caret),
annotations: fieldEcho.of(true),
});
}}
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
e.preventDefault();
if (runner.canCommit) void runner.run(e.altKey);
} else if (e.key === "Escape") {
e.currentTarget.blur();
return true;
}
return false;
}}
/>
{emptyError && (
@@ -1694,12 +1721,14 @@ export function CommitMessageField({
type="button"
className={styles.inspectionFix}
onClick={() => {
const el = ref.current;
const caret = el ? el.selectionStart + (el.selectionStart > first.length ? 1 : 0) : 0;
const view = field.current?.view();
const head = view?.state.selection.main.head ?? 0;
const caret = head + (head > first.length ? 1 : 0);
useCommit.setState({ message: addBlankLineAfterSubject(message) });
requestAnimationFrame(() => {
el?.focus();
el?.setSelectionRange(caret, caret);
field.current?.focus();
const editor = field.current?.view();
editor?.dispatch({ selection: EditorSelection.cursor(Math.min(caret, editor.state.doc.length)) });
});
}}
>
+2 -1
Переглянути файл
@@ -94,7 +94,8 @@ beforeEach(() => {
});
afterEach(() => {
closeBlamePopup();
// Inside act: the popup's root renders the close now, not after the test environment is gone.
act(() => closeBlamePopup());
view?.destroy();
view = undefined;
vi.useRealTimers();
+50
Переглянути файл
@@ -12,7 +12,9 @@ import {
isFavoriteBranch,
preferredBranchRow,
pushRecent,
resolveRefName,
scopedExpansion,
shortRefName,
type BranchRow,
type BranchTreeNode,
} from "../branches";
@@ -461,3 +463,51 @@ describe("scopedExpansion", () => {
expect([...scopedExpansion(all, "")]).toEqual([["group:remote", false]]);
});
});
describe("git's short ref names", () => {
// `git rev-parse --abbrev-ref=strict` in a repository with these refs.
const refs = new Set([
"refs/heads/main",
"refs/heads/release",
"refs/tags/release",
"refs/heads/heads/release",
"refs/heads/tags/x",
"refs/tags/x",
"refs/remotes/origin/main",
]);
it("shortens each ref as git does", () => {
expect(Object.fromEntries([...refs].map((full) => [full, shortRefName(full, refs)]))).toEqual({
"refs/heads/main": "main",
"refs/heads/release": "refs/heads/release",
"refs/tags/release": "tags/release",
"refs/heads/heads/release": "heads/heads/release",
"refs/heads/tags/x": "heads/tags/x",
"refs/tags/x": "x",
"refs/remotes/origin/main": "origin/main",
});
});
it("resolves short names in git's order, the tag before the branch", () => {
expect(resolveRefName("release", refs)).toBe("refs/tags/release");
expect(resolveRefName("heads/release", refs)).toBe("refs/heads/release");
expect(resolveRefName("tags/x", refs)).toBe("refs/tags/x");
expect(resolveRefName("origin/main", refs)).toBe("refs/remotes/origin/main");
expect(resolveRefName("nope", refs)).toBeUndefined();
});
it("resolves every short name back to its own ref", () => {
const names = ["x", "heads/x", "tags/x", "remotes/x", "heads/heads/x", "tags/heads/x", "o/x", "refs/heads/x"];
const kinds = ["refs/heads/", "refs/tags/", "refs/remotes/"];
const all = names.flatMap((n) => kinds.map((k) => k + n));
// Every subset of up to four of these refs.
for (let a = 0; a < all.length; a++)
for (let b = a; b < all.length; b++)
for (let c = b; c < all.length; c++)
for (let d = c; d < all.length; d++) {
const set = new Set([all[a]!, all[b]!, all[c]!, all[d]!]);
for (const full of set)
expect(resolveRefName(shortRefName(full, set), set), `${full} in ${[...set]}`).toBe(full);
}
});
});
+111
Переглянути файл
@@ -0,0 +1,111 @@
/** The commit message field on an editor: Vim works in it, Esc goes to Vim first (#7024). */
import { act, fireEvent, render } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { EditorView } from "@codemirror/view";
import { activate as activateVim } from "@/features/vim";
import { useVimSettings } from "@/features/vim/settings";
import { CommitMessageField, type CommitRunner } from "../CommitView";
import { useCommit } from "../commitStore";
import { useVcs } from "../store";
const runnerOf = (): CommitRunner & { run: (push: boolean) => Promise<void> } => ({
emptyError: false,
clearEmptyError: vi.fn(),
canCommit: true,
run: vi.fn(async () => {}),
});
const contentOf = () => {
const el = document.querySelector<HTMLElement>('[aria-label="Commit message"]');
if (!el) throw new Error("message field not rendered");
return el;
};
const viewOf = (): EditorView => {
const view = EditorView.findFromDOM(contentOf());
if (!view) throw new Error("message field is not an editor");
return view;
};
/** Waits until Vim mode's contribution has reached the field (the engine loads lazily). */
const untilVim = async (): Promise<EditorView> => {
const view = viewOf();
await vi.waitFor(() => expect(view.dom.getAttribute("data-openidea-vim")).toBeTruthy(), { timeout: 5000 });
return view;
};
describe("Commit message field on an editor (#7024)", () => {
beforeEach(() => {
localStorage.clear();
useVcs.setState({ available: true, root: "/p", repo: "/p", roots: ["/p"], status: [] });
useCommit.setState({ message: "", amend: false, amendPreview: null, author: "" });
});
afterEach(() => {
useVimSettings.setState({ enabled: false, handlers: {} }, true);
});
it("is an editor textbox with the field's name and placeholder", () => {
render(<CommitMessageField runner={runnerOf()} />);
expect(contentOf().getAttribute("role")).toBe("textbox");
expect(contentOf().getAttribute("placeholder")).toBeNull();
expect(document.querySelector(".cm-placeholder")?.textContent).toBe("Commit Message");
});
it("with Vim mode off, Esc leaves the field for the editor, as before", () => {
const runner = runnerOf();
render(<CommitMessageField runner={runner} />);
const view = viewOf();
act(() => view.focus());
expect(document.activeElement).toBe(view.contentDOM);
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
});
it("Meta+Enter commits from the field", () => {
const runner = runnerOf();
render(<CommitMessageField runner={runner} />);
const view = viewOf();
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "Enter", metaKey: true });
expect(runner.run).toHaveBeenCalledWith(false);
});
it("with Vim mode on, Esc leaves Insert mode in the field and keeps the focus", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const dispose = activateVim();
try {
act(() => useCommit.setState({ message: "hello" }));
render(<CommitMessageField runner={runnerOf()} />);
const view = await untilVim();
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("insert");
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(view.dom.getAttribute("data-vim-mode")).toBe("normal");
expect(document.activeElement).toBe(view.contentDOM);
// An operator acts on the message itself (dd deletes the first line).
fireEvent.keyDown(view.contentDOM, { key: "d" });
fireEvent.keyDown(view.contentDOM, { key: "d" });
expect(useCommit.getState().message).toBe("");
} finally {
dispose();
}
});
it("with Vim mode on, a further Esc in Normal mode returns the focus to the editor", async () => {
useVimSettings.setState({ enabled: true, handlers: {} }, true);
const dispose = activateVim();
try {
render(<CommitMessageField runner={runnerOf()} />);
const view = await untilVim();
act(() => view.focus());
fireEvent.keyDown(view.contentDOM, { key: "i" });
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).toBe(view.contentDOM);
fireEvent.keyDown(view.contentDOM, { key: "Escape" });
expect(document.activeElement).not.toBe(view.contentDOM);
} finally {
dispose();
}
});
});
+5 -3
Переглянути файл
@@ -94,7 +94,7 @@ describe("Commit tool window Preview Diff (#1599)", () => {
// Side by side with the changes: the splitter between the panels is vertical.
expect(previewHandle()).toBeTruthy();
expect(screen.getByTestId("diff-preview")).toHaveAttribute("data-path", "/p/a.ts");
expect(screen.getByPlaceholderText("Commit Message")).toBeTruthy();
expect(screen.getByText("Commit Message")).toBeTruthy();
});
it("previews the selected file and follows the selection", () => {
@@ -118,7 +118,7 @@ describe("Commit tool window Preview Diff (#1599)", () => {
act(() => setCommitDiffPreview(true));
expect(screen.getByTestId("diff-preview")).toBeTruthy();
expect(screen.getByRole("tree", { name: "Changes" })).toBeTruthy();
expect(screen.getByPlaceholderText("Commit Message")).toBeTruthy();
expect(screen.getByText("Commit Message")).toBeTruthy();
expect(screen.getByRole("button", { name: "Commit" })).toBeTruthy();
});
@@ -181,7 +181,9 @@ it("follows the active working diff without following other revisions or taking
status: [modified("/p/a.ts"), modified("/p/b.ts")],
});
render(<CommitToolWindow />);
const message = screen.getByPlaceholderText("Commit Message");
// The field is an editor; its focusable element is the CodeMirror content.
const message = document.querySelector<HTMLElement>('[aria-label="Commit message"]');
if (!message) throw new Error("message field not rendered");
message.focus();
act(() => editor.follow?.(diffInput(workingDiffData("/p/b.ts"))));
expect(useCommit.getState().selection).toEqual(["/p/b.ts"]);
+37
Переглянути файл
@@ -12,6 +12,11 @@ const mocks = vi.hoisted(() => ({
diffWindow: vi.fn(),
openComparison: vi.fn(),
comparePaths: vi.fn(),
getFiles: vi.fn(),
}));
vi.mock("../logChanges", async (original) => ({
...(await original<typeof import("../logChanges")>()),
getFilesFromRevision: mocks.getFiles,
}));
vi.mock("../DiffWindow", () => ({ showDiffWindow: mocks.diffWindow }));
vi.mock("@/platform/ipc", async (original) => {
@@ -286,6 +291,38 @@ describe("CompareToolWindow", () => {
expect(mocks.openDiff).toHaveBeenLastCalledWith(expect.objectContaining({ path: "/workspace/client/src/app.ts" }));
});
it("gets the selected file from the compared revision and reloads the list", async () => {
mocks.getFiles.mockResolvedValue(true);
render(<CompareToolWindow />);
const get = screen.getByRole("button", { name: "Get" });
expect(get).toBeDisabled();
fireEvent.mouseDown(await screen.findByText("app.ts"), { button: 0 });
expect(get).toBeEnabled();
expect(mocks.worktree).toHaveBeenCalledTimes(1);
fireEvent.click(get);
await waitFor(() => expect(mocks.worktree).toHaveBeenCalledTimes(2));
expect(mocks.getFiles).toHaveBeenCalledWith([
{ path: "/workspace/client/src/app.ts", from: { path: "/workspace/client/src/app.ts", rev: "main" } },
]);
expect(screen.getByRole("button", { name: "Get" })).toBeDisabled();
});
it("keeps the list when Get is cancelled, and has no Get between two revisions", async () => {
mocks.getFiles.mockResolvedValue(false);
render(<CompareToolWindow />);
fireEvent.mouseDown(await screen.findByText("app.ts"), { button: 0 });
fireEvent.click(screen.getByRole("button", { name: "Get" }));
await waitFor(() => expect(mocks.getFiles).toHaveBeenCalledOnce());
expect(mocks.worktree).toHaveBeenCalledTimes(1);
expect(screen.getByRole("button", { name: "Get" })).toBeEnabled();
cleanup();
mocks.revisions.mockResolvedValue({ status: "ok", data: [modified] });
act(() => useCompareTool.getState().show(from, { rev: "next", label: "next" }));
render(<CompareToolWindow />);
expect(await screen.findByText("app.ts")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Get" })).toBeNull();
});
it("has no Jump to Source for a file deleted from the working tree", async () => {
render(<CompareToolWindow />);
fireEvent.mouseDown(await screen.findByText("old.ts"), { button: 0 });
+3 -1
Переглянути файл
@@ -5,6 +5,7 @@
// change) is crates/ide-svn/tests/ij_history.rs.
import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { act } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { BlameLine } from "@/bindings";
import { useI18n } from "@/platform/i18n";
@@ -78,7 +79,8 @@ beforeEach(() => {
});
afterEach(() => {
closeBlamePopup();
// Inside act: the popup's root renders the close now, not after the test environment is gone.
act(() => closeBlamePopup());
view?.destroy();
view = undefined;
vi.useRealTimers();
+17
Переглянути файл
@@ -127,6 +127,23 @@ describe("renameBranchInLogFilters", () => {
expect(rememberedLogBranches("/mem-rename")).toEqual(["renamed"]);
});
it("renames heads/<name>, the filter of a branch a tag shares its name with", () => {
project("/mem-rename-heads");
useGitLog.setState({
filters: {
...emptyFilters(),
branches: ["heads/feature", "refs/heads/feature", "tags/feature", "heads/heads/feature"],
},
});
renameBranchInLogFilters("/mem-rename-heads", "feature", "renamed");
expect(useGitLog.getState().filters.branches).toEqual([
"heads/renamed",
"refs/heads/renamed",
"tags/feature",
"heads/heads/feature",
]);
});
it("rewrites parked views and Log: branch tabs, leaving other branches alone", () => {
project("/mem-rename-tabs");
openLogTab("branch", "feature");
+301 -2
Переглянути файл
@@ -13,6 +13,8 @@ const repoData = vi.hoisted(() => ({
/** Roots whose tags cannot be read (a working copy: Git's tags are not its). */
noTags: new Set<string>(),
branchReads: [] as string[],
/** Holds back every branch list until it resolves. */
branchGate: null as Promise<void> | null,
}));
vi.mock("@/platform/ipc", async (importOriginal) => {
const real = await importOriginal<typeof import("@/platform/ipc")>();
@@ -22,7 +24,8 @@ vi.mock("@/platform/ipc", async (importOriginal) => {
...real.commands,
vcsBranches: (root: string) => {
repoData.branchReads.push(root);
return Promise.resolve({ status: "ok", data: repoData.branches[root] ?? [] });
const data = repoData.branches[root] ?? [];
return (repoData.branchGate ?? Promise.resolve()).then(() => ({ status: "ok", data }));
},
vcsTags: (root: string) =>
Promise.resolve(
@@ -48,7 +51,7 @@ import { BranchesPanel } from "../log/BranchesPanel";
import { FilterBar } from "../log/FilterBar";
import { setLogOptions } from "../logOptions";
import { useBranchesPane } from "../logPaneActions";
import { emptyFilters, useGitLog } from "../logStore";
import { emptyFilters, setLogBranches, setLogFilters, useGitLog } from "../logStore";
import { useVcs } from "../store";
const b = (name: string, opts: Partial<Branch> = {}): Branch => ({
@@ -129,6 +132,135 @@ describe("Git Log branches pane", () => {
}
});
describe("a tag named like a branch", () => {
beforeEach(() => {
useVcs.setState({ branches: [...branches, b("release", { commit: "3" })] });
repoData.tags = { "/p": ["release", "v1"] };
});
afterEach(() => {
setLogOptions({ branchClickFilters: false });
repoData.tags = {};
});
/** The branch and tag rows named `release` and the tag `v1`, with Tags expanded. */
const rows = async () => {
await waitFor(() => fireEvent.mouseDown(screen.getByText("Tags")));
fireEvent.keyDown(screen.getByRole("tree", { name: "Branches" }), { key: "ArrowRight" });
await waitFor(() => expect(screen.getAllByText("release")).toHaveLength(2));
const [branch, tag] = screen.getAllByText("release").map((el) => el.closest("[data-row]")!);
return { branch: branch!, tag: tag!, v1: screen.getByText("v1").closest("[data-row]")! };
};
const deleteBranch = () => screen.getByRole("button", { name: "Delete Branch" });
it("filters by tags/<name> and keeps the tag selected, so Delete Branch is disabled", async () => {
setLogOptions({ branchClickFilters: true });
render(<BranchesPanel />);
const { branch, tag } = await rows();
fireEvent.mouseDown(tag);
expect(useGitLog.getState().filters.branches).toEqual(["tags/release"]);
expect(tag).toHaveAttribute("aria-selected", "true");
expect(branch).toHaveAttribute("aria-selected", "false");
expect(deleteBranch()).toBeDisabled();
});
it("filters by heads/<name> on a double click of the branch", async () => {
render(<BranchesPanel />);
const { branch, tag } = await rows();
fireEvent.mouseDown(tag);
fireEvent.doubleClick(tag);
expect(useGitLog.getState().filters.branches).toEqual(["tags/release"]);
expect(deleteBranch()).toBeDisabled();
fireEvent.mouseDown(branch);
fireEvent.doubleClick(branch);
expect(useGitLog.getState().filters.branches).toEqual(["heads/release"]);
expect(branch).toHaveAttribute("aria-selected", "true");
expect(tag).toHaveAttribute("aria-selected", "false");
expect(deleteBranch()).toBeEnabled();
});
it("selects the row a filter set elsewhere names: tags/, heads/, else the branch", async () => {
render(<BranchesPanel />);
const { branch, tag } = await rows();
act(() => setLogBranches(["tags/release"]));
expect(tag).toHaveAttribute("aria-selected", "true");
expect(branch).toHaveAttribute("aria-selected", "false");
act(() => setLogBranches(["release"]));
expect(branch).toHaveAttribute("aria-selected", "true");
expect(tag).toHaveAttribute("aria-selected", "false");
act(() => setLogBranches(["tags/release"]));
act(() => setLogBranches(["heads/release"]));
expect(branch).toHaveAttribute("aria-selected", "true");
expect(tag).toHaveAttribute("aria-selected", "false");
});
it("keeps a tag with no branch of its name by its plain name, selected", async () => {
render(<BranchesPanel />);
const { v1 } = await rows();
fireEvent.mouseDown(v1);
fireEvent.doubleClick(v1);
expect(useGitLog.getState().filters.branches).toEqual(["v1"]);
expect(v1).toHaveAttribute("aria-selected", "true");
expect(deleteBranch()).toBeDisabled();
});
it("spells out a tag whose own name starts with heads/", async () => {
repoData.tags = { "/p": ["heads/release"] };
render(<BranchesPanel />);
await waitFor(() => fireEvent.mouseDown(screen.getByText("Tags")));
fireEvent.keyDown(screen.getByRole("tree", { name: "Branches" }), { key: "ArrowRight" });
const tag = (await screen.findByText("heads/release")).closest("[data-row]")!;
fireEvent.mouseDown(tag);
fireEvent.doubleClick(tag);
expect(useGitLog.getState().filters.branches).toEqual(["tags/heads/release"]);
expect(tag).toHaveAttribute("aria-selected", "true");
expect(screen.getByText("release").closest("[data-row]")).toHaveAttribute("aria-selected", "false");
expect(deleteBranch()).toBeDisabled();
});
it("keeps a remote-tracking heads/<name> apart from the local branch <name>", async () => {
repoData.tags = {};
useVcs.setState({
branches: [...branches, b("release", { commit: "3" }), b("heads/release", { remote: true, commit: "4" })],
});
render(<BranchesPanel />);
const [local, remote] = (await screen.findAllByText("release")).map((el) => el.closest("[data-row]")!);
fireEvent.mouseDown(remote!);
fireEvent.doubleClick(remote!);
expect(useGitLog.getState().filters.branches).toEqual(["remotes/heads/release"]);
expect(remote).toHaveAttribute("aria-selected", "true");
expect(local).toHaveAttribute("aria-selected", "false");
});
it("spells out a tag named like a full branch ref, refs/heads/<name>", async () => {
repoData.tags = { "/p": ["refs/heads/release"] };
render(<BranchesPanel />);
await waitFor(() => fireEvent.mouseDown(screen.getByText("Tags")));
fireEvent.keyDown(screen.getByRole("tree", { name: "Branches" }), { key: "ArrowRight" });
const tag = (await screen.findByText("refs/heads/release")).closest("[data-row]")!;
fireEvent.mouseDown(tag);
fireEvent.doubleClick(tag);
expect(useGitLog.getState().filters.branches).toEqual(["tags/refs/heads/release"]);
expect(tag).toHaveAttribute("aria-selected", "true");
expect(screen.getByText("release").closest("[data-row]")).toHaveAttribute("aria-selected", "false");
expect(deleteBranch()).toBeDisabled();
});
it("lists the tags once the branches are read", async () => {
useVcs.setState({ branchesLoaded: false });
render(<BranchesPanel />);
await act(() => new Promise((resolve) => setTimeout(resolve, 0)));
expect(screen.queryByText("Tags")).toBeNull();
act(() => useVcs.setState({ branchesLoaded: true }));
expect(await screen.findByText("Tags")).toBeInTheDocument();
});
it("filters an unambiguous branch by its plain name", async () => {
render(<BranchesPanel />);
await rows();
fireEvent.doubleClick(screen.getByText("feature"));
expect(useGitLog.getState().filters.branches).toEqual(["feature"]);
});
});
it("right click selects the branch without changing the log filter when branchClickFilters is enabled", () => {
setLogOptions({ branchClickFilters: true });
try {
@@ -417,6 +549,173 @@ describe("Git Log branches pane with several repositories", () => {
expect(useGitLog.getState().filters.repositories ?? []).toEqual([]);
});
describe("a tag named like a branch", () => {
/** Every `release` row, Tags included (a search opens every group). */
const releaseRows = async (count: number) => {
fireEvent.change(screen.getByLabelText("Filter branches and tags"), { target: { value: "release" } });
await waitFor(() => expect(screen.getAllByText("release")).toHaveLength(count));
return screen.getAllByText("release").map((el) => el.closest("[data-row]")!);
};
const deleteBranch = () => screen.getByRole("button", { name: "Delete Branch" });
it("keeps one repository's tag apart from another repository's branch of that name", async () => {
repoData.branches = { "/p/a": aBranches, "/p/b": [...bBranches, b("release")] };
repoData.tags = { "/p/a": ["release"] };
render(<BranchesPanel />);
const [branch, tag] = await releaseRows(2);
fireEvent.mouseDown(tag!);
fireEvent.doubleClick(tag!);
expect(useGitLog.getState().filters.branches).toEqual(["release"]);
expect(tag).toHaveAttribute("aria-selected", "true");
expect(branch).toHaveAttribute("aria-selected", "false");
expect(deleteBranch()).toBeDisabled();
});
it("names the tag tags/<name> in the repository where its name is also a branch", async () => {
repoData.branches = { "/p/a": [...aBranches, b("release")], "/p/b": bBranches };
repoData.tags = { "/p/a": ["release"], "/p/b": ["release"] };
render(<BranchesPanel />);
const [branch, tag] = await releaseRows(2);
fireEvent.mouseDown(tag!);
fireEvent.doubleClick(tag!);
expect(useGitLog.getState().filters).toMatchObject({
branches: ["tags/release", "release"],
branchTargets: [
{ ref: "tags/release", repo: "/p/a" },
{ ref: "release", repo: "/p/b" },
],
});
expect(tag).toHaveAttribute("aria-selected", "true");
expect(branch).toHaveAttribute("aria-selected", "false");
// Grouped, each repository keeps its tag selected.
fireEvent.click(screen.getByRole("button", { name: "Group by Repository" }));
const [inA, tagInA, tagInB] = await releaseRows(3);
expect(tagInA).toHaveAttribute("aria-selected", "true");
expect(tagInB).toHaveAttribute("aria-selected", "true");
expect(inA).toHaveAttribute("aria-selected", "false");
expect(tag).toHaveAttribute("aria-selected", "true");
expect(branch).toHaveAttribute("aria-selected", "false");
expect(deleteBranch()).toBeDisabled();
});
it("lists a repository's tags only once its branches are read, so a shared name is never picked half-known", async () => {
let release!: () => void;
repoData.branchGate = new Promise((resolve) => (release = resolve));
repoData.branches = { "/p/a": [...aBranches, b("release")], "/p/b": bBranches };
repoData.tags = { "/p/a": ["release"] };
try {
render(<BranchesPanel />);
fireEvent.change(screen.getByLabelText("Filter branches and tags"), { target: { value: "release" } });
await act(() => Promise.resolve());
expect(screen.queryAllByText("release")).toHaveLength(0);
await act(async () => release());
const [, tag] = await releaseRows(2);
fireEvent.mouseDown(tag!);
fireEvent.doubleClick(tag!);
expect(useGitLog.getState().filters.branches).toEqual(["tags/release"]);
} finally {
repoData.branchGate = null;
}
});
it("keeps Show in Git Log of an external log to the branch's repositories", async () => {
repoData.branches = { "/p/a": [...aBranches, b("release")], "/p/b": bBranches };
repoData.tags = { "/p/a": ["release"] };
useGitLog.setState({
logTabs: [{ id: "ext", kind: "external", target: "/p", repositories: ["/p/a", "/p/b"], readOnly: true }],
shownLog: "ext",
});
try {
render(
<>
<BranchesPanel />
<ContextMenuHost />
</>,
);
const [branch] = await releaseRows(2);
fireEvent.contextMenu(branch!);
fireEvent.click(await screen.findByRole("menuitem", { name: "Show in Git Log" }));
expect(useGitLog.getState().filters).toMatchObject({
branches: ["heads/release"],
branchTargets: [{ ref: "heads/release", repo: "/p/a" }],
});
} finally {
useGitLog.setState({ logTabs: [], shownLog: "log" });
}
});
it("selects a branch named heads/<name> for that name, not another repository's <name>", async () => {
repoData.branches = { "/p/a": [...aBranches, b("heads/release")], "/p/b": [...bBranches, b("release")] };
render(<BranchesPanel />);
const [inA, inB] = await releaseRows(2);
act(() => setLogBranches(["heads/release"]));
expect(inA).toHaveAttribute("aria-selected", "true");
expect(inB).toHaveAttribute("aria-selected", "false");
});
it("keeps a tag selected across grouping when another repository has a branch named tags/<name>", async () => {
repoData.branches = { "/p/a": [...aBranches, b("release")], "/p/b": [...bBranches, b("tags/release")] };
repoData.tags = { "/p/a": ["release"], "/p/b": ["release"] };
render(<BranchesPanel />);
fireEvent.change(screen.getByLabelText("Filter branches and tags"), { target: { value: "release" } });
const tag = await waitFor(() => {
const rows = screen.getAllByText("release").map((el) => el.closest("[data-row]")!);
expect(rows).toHaveLength(3);
return rows[2]!;
});
fireEvent.mouseDown(tag);
fireEvent.doubleClick(tag);
fireEvent.click(screen.getByRole("button", { name: "Group by Repository" }));
// Local: A's release, B's tags › release; Tags: A's, B's.
const rows = await releaseRows(4);
expect(rows.map((row) => row.getAttribute("aria-selected"))).toEqual(["false", "false", "true", "true"]);
expect(deleteBranch()).toBeDisabled();
});
it("keeps a filter on heads/<name> on the branch git resolves it to", async () => {
repoData.branches = { "/p/a": [...aBranches, b("heads/release")], "/p/b": [...bBranches, b("release")] };
repoData.tags = { "/p/b": ["release"] };
render(<BranchesPanel />);
fireEvent.change(screen.getByLabelText("Filter branches and tags"), { target: { value: "release" } });
await waitFor(() => expect(screen.getAllByText("release")).toHaveLength(3));
const [inA, inB] = screen.getAllByText("release").map((el) => el.closest("[data-row]")!);
act(() => setLogBranches(["heads/release"]));
expect(inA).toHaveAttribute("aria-selected", "true");
expect(inB).toHaveAttribute("aria-selected", "false");
});
it("highlights, grouped, only the repositories the log queries for a name from the filter bar", async () => {
repoData.branches = { "/p/a": [...aBranches, b("release")], "/p/b": bBranches };
repoData.tags = { "/p/b": ["release"] };
render(<BranchesPanel />);
fireEvent.click(await screen.findByRole("button", { name: "Group by Repository" }));
const [branchInA, tagInB] = await releaseRows(2);
act(() => setLogBranches(["release"]));
expect(branchInA).toHaveAttribute("aria-selected", "true");
expect(tagInB).toHaveAttribute("aria-selected", "false");
});
it("selects only the picked repository's tag when grouped by repository", async () => {
repoData.branches = { "/p/a": [...aBranches, b("release")], "/p/b": [...bBranches, b("release")] };
repoData.tags = { "/p/a": ["release"], "/p/b": ["release"] };
render(<BranchesPanel />);
fireEvent.click(await screen.findByRole("button", { name: "Group by Repository" }));
const [inA, inB, tagInA, tagInB] = await releaseRows(4);
fireEvent.mouseDown(tagInA!);
fireEvent.doubleClick(tagInA!);
expect(useGitLog.getState().filters).toMatchObject({
branches: ["tags/release"],
branchTargets: [{ ref: "tags/release", repo: "/p/a" }],
});
expect(tagInA).toHaveAttribute("aria-selected", "true");
for (const row of [inA, inB, tagInB]) expect(row).toHaveAttribute("aria-selected", "false");
expect(deleteBranch()).toBeDisabled();
act(() => setLogFilters({ branches: ["release"], branchTargets: [{ ref: "release", repo: "/p/b" }] }));
expect(inB).toHaveAttribute("aria-selected", "true");
for (const row of [inA, tagInA, tagInB]) expect(row).toHaveAttribute("aria-selected", "false");
});
});
it("keeps the current marker ahead of the repository names, which may be cut off", async () => {
repoData.branches = { "/p/a": [b("main", { current: true }), b("dev")], "/p/b": [b("dev", { current: true })] };
render(<BranchesPanel />);
+32
Переглянути файл
@@ -453,6 +453,38 @@ export function buildLineTree(lines: readonly Branch[], favorites: readonly stri
return [...top.map((b) => leaf(b, b.name)), ...folder("branches"), ...folder("tags")];
}
// git's rules for a short ref name, in the order `git rev-parse` tries them after a full ref name
// (its `%s` rule, which also reads files such as HEAD).
const REF_RULES: readonly [string, string][] = [
["refs/", ""],
["refs/tags/", ""],
["refs/heads/", ""],
["refs/remotes/", ""],
["refs/remotes/", "/HEAD"],
];
/** The full ref the short name `name` resolves to among `refs` (full names), as `git rev-parse` does. */
export function resolveRefName(name: string, refs: { has(name: string): boolean }): string | undefined {
if (name.startsWith("refs/") && refs.has(name)) return name;
for (const [prefix, suffix] of REF_RULES) if (refs.has(prefix + name + suffix)) return prefix + name + suffix;
return undefined;
}
/**
* git's shortest name for the full ref `full` that no other ref of `refs` takes
* (`git rev-parse --abbrev-ref=strict`): `main`, or `tags/release` beside a branch `release`.
*/
export function shortRefName(full: string, refs: { has(name: string): boolean }): string {
for (let i = REF_RULES.length - 1; i >= 0; i--) {
const [prefix, suffix] = REF_RULES[i]!;
if (!full.startsWith(prefix) || !full.endsWith(suffix) || full.length <= prefix.length + suffix.length) continue;
const short = full.slice(prefix.length, full.length - suffix.length);
// A short name that is itself a full ref (a tag `refs/heads/x`) resolves to that ref first.
if (!refs.has(short) && REF_RULES.every(([p, s], j) => j === i || !refs.has(p + short + s))) return short;
}
return full;
}
/** A Subversion line that is a tag (`tags/…`): shown with the tag icon. */
export function isTagLine(name: string | null | undefined): boolean {
return !!name?.startsWith("tags/");
+1 -1
Переглянути файл
@@ -3,7 +3,7 @@ import type { FileStatus } from "@/bindings";
import { type DiffData, withChain, workingDiffData } from "./diffInput";
/** The changes trees whose selection an embedded diff preview shows. */
export type PreviewTree = "commit" | "local";
export type PreviewTree = "commit" | "local" | "dialog";
interface ChangesPreviewState {
/** Each tree's files in tree order: the preview's F7 chain. */
+12
Переглянути файл
@@ -62,6 +62,8 @@ interface CommitState extends CommitAuthorDetails {
diffPreview: boolean;
/** Whether the Commit tool window previews the selection's diff beside the changes (#1599). */
commitDiffPreview: boolean;
/** Whether the Commit dialog shows the selection's diff below the changes and message. */
dialogDiffPreview: boolean;
/** User overrides of the inclusion checkboxes (absolute path → state). */
checks: Map<string, CheckState>;
/** Staged repositories the user unchecked for this commit. */
@@ -119,6 +121,7 @@ export const useCommit = create<CommitState>(() => ({
ignoredVisibility: new Map(),
diffPreview: readBool("openidea.vcs.diffPreview", true),
commitDiffPreview: readBool("openidea.vcs.commitDiffPreview", false),
dialogDiffPreview: readBool("openidea.vcs.commitDialogDiffPreview", true),
checks: new Map(),
excludedStagedRepos: new Set(),
dialogList: null,
@@ -245,6 +248,15 @@ export function setDiffPreview(v: boolean) {
}
}
export function setDialogDiffPreview(v: boolean) {
useCommit.setState({ dialogDiffPreview: v });
try {
localStorage.setItem("openidea.vcs.commitDialogDiffPreview", String(v));
} catch {
// ignore
}
}
export function setCommitDiffPreview(v: boolean) {
useCommit.setState({ commitDiffPreview: v });
try {
+18 -3
Переглянути файл
@@ -1,6 +1,6 @@
/**
* The Compare tool window: `Show Diff with Working Tree` shows the worktree diff
* in the sidebar instead of a dialog, with Jump to Source and Swap Sides (#2442).
* in the sidebar instead of a dialog, with Jump to Source, Get and Swap Sides (#2442).
* Branch and revision comparisons open here too (one closable tab per comparison,
* titled after what is compared, as in IDEA's VCS changes tool window): Compare with
* Branch…/Revision… on a folder or multi-selection, two-commit Compare Versions from
@@ -8,7 +8,7 @@
* file keeps its diff editor tab, and Compare with Current keeps the two-pane
* BranchComparisonEditor.
*/
import { useCallback, useEffect, useRef } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { create } from "zustand";
import { Button, Tabs, showContextMenu } from "@/ui";
import { tx } from "@/platform/i18n";
@@ -17,9 +17,11 @@ import { maybeEditorService, notifications, registerToolWindow, type OpenEditorT
import { showToolWindow } from "@/workbench/toolwindows/store";
import { COMBINED_DIFF_KIND, type CombinedDiffData } from "./allInOneDiff";
import { combinedDiffInput, DIFF_KIND, diffInput, openVcsDiff, withChain, type DiffData } from "./diffInput";
import { getFilesFromRevision } from "./logChanges";
import {
ChangesBetweenDialog,
comparisonDiffData,
comparisonRevisionFiles,
type ComparisonFile,
type Revision,
type ScopedComparison,
@@ -190,6 +192,8 @@ export function CompareToolWindow() {
const close = useCompareTool((s) => s.close);
const active = tabs.find((tab) => tab.id === activeId) ?? null;
const filesRef = useRef<readonly ComparisonFile[]>([]);
// Bumped after Get so the list reloads without the files that now match the revision.
const [reloads, setReloads] = useState(0);
const handleFiles = useCallback((files: readonly ComparisonFile[]) => {
filesRef.current = files;
}, []);
@@ -201,6 +205,12 @@ export function CompareToolWindow() {
if (!current || current.kind === "deleted") return;
void maybeEditorService()?.openFile(repositoryPath(current.root, current.path), { focus: true });
};
// Against the working tree only: the selected file takes its content from the compared revision.
const getFile = async () => {
if (!current || !(await getFilesFromRevision(comparisonRevisionFiles(current)))) return;
select(null);
setReloads((n) => n + 1);
};
const showDiff = (data: DiffData) => {
void openVcsDiff(data).catch((error) =>
notifications().notify({ level: "error", title: "Could not show diff", body: String(error) }),
@@ -269,13 +279,18 @@ export function CompareToolWindow() {
<Button size="small" onClick={jumpToSource} disabled={!current || current.kind === "deleted"}>
Jump to Source
</Button>
{!active.to && (
<Button size="small" onClick={() => void getFile()} disabled={!current}>
Get
</Button>
)}
<Button size="small" variant={swapped ? "primary" : "secondary"} onClick={handleSwapSides}>
Swap Sides
</Button>
</div>
<div className={styles.comparisonWindowBody}>
<ChangesBetweenDialog
key={active.id}
key={`${active.id}:${reloads}`}
from={active.from}
to={active.to}
scope={active.scope}
+95 -43
Переглянути файл
@@ -18,6 +18,8 @@ import {
isFavoriteBranch,
isTagLine,
mergedRefTooltip,
resolveRefName,
shortRefName,
type BranchTreeNode,
} from "../branches";
import { branchMenu, inRepo, mergedBranchMenu, showTagContextMenu } from "../branchMenu";
@@ -196,7 +198,12 @@ export function BranchesPanel() {
const lines = useVcsKind(listedRepo ?? scopedRepo ?? currentRepository) === "subversion" && repositories.length < 2;
const allRoots = useMemo(() => {
if (allUnavailable || (!repositories.length && availableRepositories.length)) return [];
const shownTags = scopedRepo ? (allTags[scopedRepo] ?? []) : tags;
// Tags wait for their repository's branches, so a name shared by both is never picked half-known.
const shownTags = (listedRepo ? !allBranches[listedRepo] : !branchesLoaded)
? []
: scopedRepo
? (allTags[scopedRepo] ?? [])
: tags;
if (repositories.length < 2)
return lines
? buildLineTree(branches, favoritesOf(listedRepo))
@@ -205,7 +212,7 @@ export function BranchesPanel() {
root: repo,
name: repoName(branchRoots[repo] ?? repo),
branches: allBranches[repo] ?? [],
tags: allTags[repo] ?? [],
tags: allBranches[repo] ? (allTags[repo] ?? []) : [],
}));
return grouped
? buildRepositoryBranchTree(list, favoritesOf)
@@ -229,6 +236,7 @@ export function BranchesPanel() {
currentRepository,
scopedRepo,
lines,
branchesLoaded,
]);
const roots = useMemo(() => filterBranchTree(allRoots, query), [allRoots, query]);
// A new search shows every match expanded; within that search the user can still collapse and
@@ -277,24 +285,83 @@ export function BranchesPanel() {
walk(roots);
return { keys, parents };
}, [roots]);
// Refs in tree order, for Copy: full refs, so the folder path comes along
// (`feat/x`, `origin/main`).
const refs = useMemo(() => {
const out: { key: string; kind: BranchTreeNode["kind"]; ref: string; branch?: Branch; repo?: string }[] = [];
const walk = (nodes: readonly BranchTreeNode[]) => {
for (const n of nodes) {
if (n.ref) for (const t of expand(n, scopedRepo)) out.push({ key: n.key, kind: n.kind, ...t });
walk(n.children ?? []);
}
};
walk(allRoots);
return out;
}, [allRoots, scopedRepo]);
// Each Git repository's refs by full name (`refs/tags/x`), with the row that lists each one.
const fullRef = (r: (typeof refs)[number]) =>
r.kind === "tag" ? `refs/tags/${r.ref}` : r.branch?.remote ? `refs/remotes/${r.ref}` : `refs/heads/${r.ref}`;
const refRows = useMemo(() => {
const byRepo = new Map<string, Map<string, string>>();
for (const r of refs) {
if (r.kind === "head" || !isGit(r.repo ?? currentRepository)) continue;
const rows = byRepo.get(r.repo ?? "") ?? new Map<string, string>();
byRepo.set(r.repo ?? "", rows.set(fullRef(r), r.key));
}
return byRepo;
}, [refs, isGit, currentRepository]);
// git's own unambiguous name in the row's repository: `tags/release` beside a branch `release`.
const filterRef = (r: (typeof refs)[number]) => {
const rows = refRows.get(r.repo ?? "");
return rows?.has(fullRef(r)) ? shortRefName(fullRef(r), rows) : r.ref;
};
const filterTo = (picked: readonly (typeof refs)[number][]) => {
const branchTargets = picked.map((r) => ({ ref: filterRef(r), repo: r.repo }));
if (!branchTargets.length) return;
setLogFilters({
branches: [...new Set(branchTargets.map(({ ref }) => ref))],
branchTargets: branchTargets.some(({ repo }) => repo) ? branchTargets : undefined,
});
};
// Highlighted rows: a click only selects (IDEA), and only a double click or
// Enter switches the log, so the selection is the pane's own state. It still
// follows the filter when something else changes it (Show Log, the filter bar).
const filterKeys = useMemo(
() =>
filterBranches.flatMap((b) => {
if (b === "HEAD") return ["head"];
if (repositories.length < 2 || merged) return [`b:${b}`];
return repositories
.filter(
(repo) =>
!branchTargets ||
branchTargets.some((target) => target.ref === b && (!target.repo || target.repo === repo)),
)
.map((repo) => `${repo}:b:${b}`);
}),
[filterBranches, branchTargets, repositories, merged],
);
const filterKeys = useMemo(() => {
// The row of the ref git resolves `b` to in `repo`; a plain name that is both a tag and a
// branch selects the branch.
const keyIn = (repo: string, b: string) => {
const rows = refRows.get(repo);
if (!rows) return undefined;
const full = resolveRefName(b, rows);
return rows.get(full === `refs/tags/${b}` && rows.has(`refs/heads/${b}`) ? `refs/heads/${b}` : (full ?? ""));
};
// Without targets the log queries `b` only in the repositories with a branch of that name,
// when there is one (logStore's own rule).
const withBranch = (b: string) => [
...new Set(refs.filter((r) => r.kind === "branch" && r.ref === b).map((r) => r.repo ?? "")),
];
const queried = (b: string) => {
const targets = branchTargets?.filter((target) => target.ref === b);
if (targets?.length && targets.every((target) => target.repo)) return targets.map((target) => target.repo!);
const named = withBranch(b);
return named.length ? named : [...refRows.keys()];
};
return filterBranches.flatMap((b) => {
if (b === "HEAD") return ["head"];
if (repositories.length < 2 || merged) {
const keys = [...new Set(queried(b).flatMap((repo) => keyIn(repo, b) ?? []))];
return keys.length ? keys : [`b:${b}`];
}
const named = withBranch(b);
return repositories
.filter((repo) =>
branchTargets
? branchTargets.some((target) => target.ref === b && (!target.repo || target.repo === repo))
: !named.length || named.includes(repo),
)
.map((repo) => keyIn(repo, b) ?? `${repo}:b:${b}`);
});
}, [filterBranches, branchTargets, repositories, merged, refRows, refs]);
const filterKey = filterKeys.join("\n");
const [shownKey, setShownKey] = useState(filterKey);
const [selected, setSelected] = useState<ReadonlySet<string>>(() => new Set(filterKeys));
@@ -303,19 +370,6 @@ export function BranchesPanel() {
setShownKey(filterKey);
setSelected(new Set(filterKeys));
}
// Refs in tree order, for Copy: full refs, so the folder path comes along
// (`feat/x`, `origin/main`).
const refs = useMemo(() => {
const out: { key: string; ref: string; branch?: Branch; repo?: string }[] = [];
const walk = (nodes: readonly BranchTreeNode[]) => {
for (const n of nodes) {
if (n.ref) for (const t of expand(n, scopedRepo)) out.push({ key: n.key, ...t });
walk(n.children ?? []);
}
};
walk(allRoots);
return out;
}, [allRoots, scopedRepo]);
const targets = useMemo(
(): BranchTarget[] =>
refs.filter((r) => selected.has(r.key)).map(({ ref, branch, repo }) => ({ ref, branch, repo })),
@@ -480,28 +534,26 @@ export function BranchesPanel() {
onSelectionChange={(sel, _lead, reason) => {
setSelected(sel);
if (!branchClickFilters || reason === "contextMenu") return;
const branchTargets = refs.filter((r) => sel.has(r.key)).map(({ ref, repo }) => ({ ref, repo }));
if (!branchTargets.length) return;
setLogFilters({
branches: [...new Set(branchTargets.map(({ ref }) => ref))],
branchTargets: branchTargets.some(({ repo }) => repo) ? branchTargets : undefined,
});
filterTo(refs.filter((r) => sel.has(r.key)));
}}
onActivate={(n) => {
if (!n.ref) return;
const activated = selected.has(n.key) ? targets : expand(n, scopedRepo);
const branchTargets = activated.map(({ ref, repo }) => ({ ref, repo }));
setLogFilters({
branches: [...new Set(branchTargets.map(({ ref }) => ref))],
branchTargets: branchTargets.some(({ repo }) => repo) ? branchTargets : undefined,
});
const activated = selected.has(n.key) ? selected : new Set([n.key]);
filterTo(refs.filter((r) => activated.has(r.key)));
}}
onContextMenu={(n, _sel, e) => {
if (readOnly) {
if (!n?.ref) return;
e.preventDefault();
showContextMenu(e, [
{ label: "Show in Git Log", run: () => setLogBranches([n.ref!]) },
{
label: "Show in Git Log",
run: () => {
const picked = refs.filter((r) => r.key === n.key);
if (picked.every((r) => filterRef(r) === r.ref)) setLogBranches([n.ref!]);
else filterTo(picked);
},
},
{ label: "Copy", run: () => void copyText(n.ref!) },
]);
return;
+4 -2
Переглянути файл
@@ -317,7 +317,9 @@ export function setLogBranches(branches: readonly string[]) {
* other repositories keeps its branch of the same name.
*/
export function renameBranchInLogFilters(repo: string, from: string, to: string) {
const rename = (branches: readonly string[]) => branches.map((b) => (b === from ? to : b));
// git's longer names for the branch where another ref shares its name (the Branches pane's filter).
const forms = (name: string) => [name, `heads/${name}`, `refs/heads/${name}`];
const rename = (branches: readonly string[]) => branches.map((b) => forms(to)[forms(from).indexOf(b)] ?? b);
const remembered = rememberedLogBranches(repo);
if (remembered?.includes(from)) rememberLogBranches(repo, rename(remembered));
// Linked worktrees share their main repository's branches. A repository the project does not
@@ -331,7 +333,7 @@ export function renameBranchInLogFilters(repo: string, from: string, to: string)
const tabRoots = (tab: LogTab | undefined) =>
tab?.repositories?.length ? tab.repositories : tab?.repo ? [tab.repo] : [];
const renamed = (filters: LogFilters, tab: LogTab | undefined): LogFilters | null => {
if (!filters.branches.includes(from)) return null;
if (!filters.branches.some((b) => forms(from).includes(b))) return null;
// The repositories the view queries, as logRepositoryScope picks them.
const roots = tabRoots(tab).length ? tabRoots(tab) : (filters.repositories ?? []);
const queried = filters.repositories?.length ? roots.filter((r) => filters.repositories!.includes(r)) : roots;
+12
Переглянути файл
@@ -166,4 +166,16 @@ describe("keyboard dispatcher with Vim mode", () => {
expect(esc).toHaveBeenCalledOnce();
expect(e.defaultPrevented).toBe(false);
});
it("leaves Escape to a Vim field of a tool window until it is in Normal mode", async () => {
document.body.innerHTML = `<section data-toolwindow="commit"><div class="cm-editor" ${VIM_EDITOR_ATTR}="true" ${VIM_MODE_ATTR}="insert"><div class="cm-content" tabindex="0"></div></div></section>`;
const field = document.querySelector<HTMLElement>(".cm-content")!;
press(field, "Escape", { key: "Escape" });
await Promise.resolve();
expect(esc).not.toHaveBeenCalled();
field.parentElement!.setAttribute(VIM_MODE_ATTR, "normal");
press(field, "Escape", { key: "Escape" });
await Promise.resolve();
expect(esc).toHaveBeenCalledOnce();
});
});
+12 -1
Переглянути файл
@@ -167,6 +167,16 @@ function lookupStroke(
return !!view && completionStatus(view.state) === "active";
}
/**
* Escape in a Vim field of a tool window (the commit message) outside Normal mode: Vim leaves
* Insert or Visual mode, as in the editor, before the tool window's Escape (Focus Editor) can move
* the focus. In Normal mode the tool window keeps it.
*/
function toolWindowEscape(e: KeyboardEvent, stroke: string, mode: string | null): boolean {
if (normalizeBinding(stroke) !== "Escape" || !mode || mode === "normal") return false;
return !!(e.target as Element | null)?.closest?.("[data-toolwindow]");
}
/**
* Dispatcher claim: keystrokes whose handler is Vim go to a focused Vim editor. A stroke the
* mode gives to the IDE is claimed too: the editor runs that IDE action itself, so an unrelated
@@ -181,7 +191,8 @@ export function vimKeyClaim(settings: () => VimSettings): KeyClaim {
inVimEditor(e.target) &&
(handlerFor(stroke, s.handlers, mode) === "vim" ||
modeMovedToIde(stroke, s.handlers, mode) ||
lookupStroke(e, stroke, s.handlers, mode))
lookupStroke(e, stroke, s.handlers, mode) ||
toolWindowEscape(e, stroke, mode))
);
};
}
+6
Переглянути файл
@@ -43,6 +43,11 @@ export interface Action {
visibleWhen?: string;
/** Additional enablement for a parameterised action or the current selection. */
enabled?: (c: ActionContext) => boolean;
/**
* Stays enabled while a project opens (`projectOpening`), when every other action is off:
* the answers to a prompt the open itself waits for (Trust and Open Project?).
*/
whileProjectOpens?: boolean;
/**
* Extra condition for keyboard shortcuts only (menus and Find Action ignore
* it), e.g. to yield a shared shortcut to an editor action while typing.
@@ -256,6 +261,7 @@ export function isActionEnabled(action: Action, ctx: ContextKeys = getContext(),
ctx = contextFor(arg, ctx);
if (
ctx.projectOpening &&
!action.whileProjectOpens &&
!["app.quit", "window.next", "window.previous", "window.toggleFullScreen"].includes(action.id)
)
return false;
+1
Переглянути файл
@@ -7668,6 +7668,7 @@
"Usage access filters": "引用读写筛选",
"Show read accesses": "显示读取引用",
"Show write accesses": "显示写入引用",
"Show import statements": "显示导入语句",
"No usages match the access filters": "没有符合读写筛选条件的引用",
"On 'Update' action": "执行“更新”操作时",
"Show chooser": "显示选择菜单",
+7
Переглянути файл
@@ -0,0 +1,7 @@
<!-- Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="7" y="2" width="2" height="2" rx="1" fill="#6C707E"/>
<rect x="8" y="6" width="1" height="8" rx="0.5" fill="#6C707E"/>
<rect x="5" y="6" width="4" height="1" rx="0.5" fill="#6C707E"/>
<rect x="4" y="13" width="8" height="1" rx="0.5" fill="#6C707E"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 489 B

+7
Переглянути файл
@@ -0,0 +1,7 @@
<!-- Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. -->
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect x="7" y="2" width="2" height="2" rx="1" fill="#CED0D6"/>
<rect x="8" y="6" width="1" height="8" rx="0.5" fill="#CED0D6"/>
<rect x="5" y="6" width="4" height="1" rx="0.5" fill="#CED0D6"/>
<rect x="4" y="13" width="8" height="1" rx="0.5" fill="#CED0D6"/>
</svg>

Після

Ширина:  |  Висота:  |  Розмір: 489 B

+1
Переглянути файл
@@ -400,6 +400,7 @@ const ICONS = {
eye: "general/show",
"show-read-access": "actions/showReadAccess",
"show-write-access": "actions/showWriteAccess",
"show-import-statements": "actions/showImportStatements",
lock: "general/locked",
unlock: "openidea/general/unlocked",
scratches: "fileTypes/scratches",