From 7c9fa1dc3b659d976ce83852874471dd75c3bb3e Mon Sep 17 00:00:00 2001 From: Muu Date: Fri, 4 Dec 2026 02:11:36 +0800 Subject: [PATCH] feat(settings): show the effective Maven local repository from the Maven home and settings file (#7719) Closes #7654 The Local repository field of Settings > Build Tools > Maven now shows, as its placeholder, the repository a build actually reads: the of the user settings file (the configured one, else ~/.m2/settings.xml), then of the Maven home's global conf/settings.xml, then ~/.m2/repository. It is recomputed when the Maven home or the settings file changes. Neither setting is written, so -s and -Dmaven.repo.local stay as the user left them. The resolution runs on the backend in a read-only maven_local_repository command that reuses ide-build's settings helpers, so under Remote Development the remote host's paths and Maven home are used. A home that names bin or the mvn executable is reduced to the installation root, with either path separator. Co-authored-by: muutot <92625353+muutot@users.noreply.github.com> --- crates/ide-host/src/ops/build.rs | 73 ++++++++++- src/bindings.ts | 7 + .../__tests__/mavenSettingsFields.test.tsx | 122 ++++++++++++++++++ .../settings/languages/LanguagePages.tsx | 32 +---- .../languages/MavenSettingsFields.tsx | 89 +++++++++++++ 5 files changed, 292 insertions(+), 31 deletions(-) create mode 100644 src/features/settings/__tests__/mavenSettingsFields.test.tsx create mode 100644 src/features/settings/languages/MavenSettingsFields.tsx diff --git a/crates/ide-host/src/ops/build.rs b/crates/ide-host/src/ops/build.rs index b7928f63bf..a15cf869f7 100644 --- a/crates/ide-host/src/ops/build.rs +++ b/crates/ide-host/src/ops/build.rs @@ -12,7 +12,9 @@ use ide_build::compile::{self, BuildEvent, BuildKind, BuildResult}; use ide_build::jbuild::Target; use ide_build::maven::completion::{PomCompletion, PomCompletionOption}; use ide_build::maven::sources; -use ide_build::maven::{PomGoto, PomManagedDeclaration, PomNavigationOptions}; +use ide_build::maven::{ + PomGoto, PomManagedDeclaration, PomNavigationOptions, default_local_repo, local_repository_of, user_settings_file, +}; use ide_build::pom_edit::{ArtifactKey, Exclusion}; use ide_build::{BuildModel, BuildTool, SyncOptions, SyncProgress}; use ide_core::settings::Settings; @@ -237,6 +239,57 @@ pub async fn build_model(host: &Host, window: &str) -> IdeResult { blocking(move || workspace::load_project(&project, &config)).await } +/// Settings › Build Tools › Maven: the local repository the field's placeholder shows — +/// the `` of the user settings file (the configured one, else +/// `~/.m2/settings.xml`), then of the Maven home's global `conf/settings.xml`, then +/// `~/.m2/repository`. Reads files only; `home` may name `bin` or the `mvn` executable. +#[command(trust = always)] +pub async fn maven_local_repository( + host: &Host, + window: &str, + home: Option, + user_settings: Option, +) -> IdeResult> { + let root = host.project(window)?.root.clone(); + let settings = + ide_core::settings::MavenSettings { user_settings: user_settings.unwrap_or_default(), ..Default::default() }; + blocking(move || { + let user = user_settings_file(&root, &settings); + let global = home + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(maven_installation_root) + .map(|h| h.join("conf").join("settings.xml")); + let repository = user + .and_then(|settings| local_repository_of(&settings)) + .or_else(|| global.and_then(|settings| local_repository_of(&settings))) + .or_else(default_local_repo); + Ok(repository.map(|p| ide_core::ipc_path::to_ipc(&p))) + }) + .await +} + +/// The Maven installation `home` names: a path to `bin`, `bin/mvn(.cmd|.bat)` or `mvn` +/// itself is reduced to the installation root. Either separator is accepted, so a Windows +/// path is reduced on any host. +fn maven_installation_root(home: &str) -> PathBuf { + let mut root = home.trim().trim_end_matches(['/', '\\']); + fn last(s: &str) -> String { + s.rsplit(['/', '\\']).next().unwrap_or(s).to_ascii_lowercase() + } + fn parent(s: &str) -> &str { + s.rfind(['/', '\\']).map_or("", |i| &s[..i]) + } + if matches!(last(root).as_str(), "bin" | "mvn" | "mvn.cmd" | "mvn.bat") { + root = parent(root); + if last(root) == "bin" { + root = parent(root); + } + } + PathBuf::from(root) +} + /// Settings › CMake and the toolbar switcher: every profile, saved ones then presets (with /// whether each is enabled), and why the presets file cannot be read, if it cannot. #[derive(Clone, Debug, serde::Serialize, specta::Type)] @@ -2013,11 +2066,29 @@ ide_command::domain!( maven_dependency_declaration, maven_exclude_dependency, maven_goto_declaration, + maven_local_repository, maven_managed_declarations, toolchain_check, toolchains_detect, ); +#[cfg(test)] +mod maven_installation_root_tests { + use super::maven_installation_root; + + #[test] + fn reduces_bin_and_mvn_paths_to_the_installation_root() { + assert_eq!(maven_installation_root("/opt/maven-3.9"), std::path::PathBuf::from("/opt/maven-3.9")); + assert_eq!(maven_installation_root("/opt/maven-3.9/bin"), std::path::PathBuf::from("/opt/maven-3.9")); + assert_eq!(maven_installation_root("/opt/maven-3.9/bin/mvn"), std::path::PathBuf::from("/opt/maven-3.9")); + assert_eq!( + maven_installation_root("C:\\tools\\maven\\bin\\mvn.cmd"), + std::path::PathBuf::from("C:\\tools\\maven") + ); + assert_eq!(maven_installation_root(" /opt/maven-3.9/ "), std::path::PathBuf::from("/opt/maven-3.9")); + } +} + #[cfg(test)] mod cmake_reset_tests { use super::reset_cmake_cache; diff --git a/src/bindings.ts b/src/bindings.ts index 340bd0865b..b5a2ae2010 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1382,6 +1382,13 @@ export const commands = { /** The declaration as named for the user (`example.version`, `com.example:example-lib`). */ label: string, } | null, IdeError>(__TAURI_INVOKE("maven_goto_declaration", { pom, pos })), + /** + * Settings › Build Tools › Maven: the local repository the field's placeholder shows — + * the `` of the user settings file (the configured one, else + * `~/.m2/settings.xml`), then of the Maven home's global `conf/settings.xml`, then + * `~/.m2/repository`. Reads files only; `home` may name `bin` or the `mvn` executable. + */ + mavenLocalRepository: (home: string | null, userSettings: string | null) => typedError(__TAURI_INVOKE("maven_local_repository", { home, userSettings })), /** * Gutter targets of the unversioned dependencies and plugins in a Maven POM: * the management declarations that actually supply their versions, including diff --git a/src/features/settings/__tests__/mavenSettingsFields.test.tsx b/src/features/settings/__tests__/mavenSettingsFields.test.tsx new file mode 100644 index 0000000000..b7af389056 --- /dev/null +++ b/src/features/settings/__tests__/mavenSettingsFields.test.tsx @@ -0,0 +1,122 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react"; +import { PageContext } from "../components/context"; +import { DEFAULT_SETTINGS } from "../model/schema"; +import { stage, stagedValue, useSettingsDialog } from "../model/staging"; + +/** What `mavenLocalRepository` resolves, per (home, userSettings). */ +const resolve = vi.hoisted(() => vi.fn<(home: string | null, settings: string | null) => Promise>()); +/** Paths `fsEntryKind` finds. */ +const entries = vi.hoisted(() => ({}) as Record); +const choosePath = vi.fn<() => Promise>(); + +const ok = (data: unknown) => ({ status: "ok" as const, data }); +const err = { status: "error" as const, error: { kind: "notFound", message: "missing", data: null } }; + +vi.mock("@/platform/ipc", async (importOriginal) => { + const real = await importOriginal(); + return { + ...real, + isTauri: () => true, + commands: { + ...real.commands, + sdkDetect: async () => ok([]), + mavenLocalRepository: (home: string | null, settings: string | null) => resolve(home, settings), + fsEntryKind: async (path: string) => (entries[path] ? ok(entries[path]) : err), + }, + }; +}); +vi.mock("@/platform/choosePath", () => ({ choosePath: () => choosePath() })); + +const { MavenSettingsFields } = await import("../languages/MavenSettingsFields"); + +const SETTINGS_KEY = "languages.java.maven.userSettings"; +const REPOSITORY_KEY = "languages.java.maven.localRepository"; + +const staged = (key: string) => stagedValue(useSettingsDialog.getState(), "project", key); + +const MAVEN_CONTEXT = { pageId: "build.maven", scope: "project" } as const; + +function renderFields() { + return render( + + + , + ); +} + +const home = () => screen.getByRole("combobox", { name: "Maven home path" }) as HTMLInputElement; +const settingsInput = () => screen.getByRole("textbox", { name: "User settings file" }) as HTMLInputElement; +const repositoryInput = () => screen.getByRole("textbox", { name: "Local repository" }) as HTMLInputElement; + +/** Types a home into IDEA's editable combo and commits it with Enter. */ +function enterHome(path: string) { + fireEvent.change(home(), { target: { value: path } }); + fireEvent.keyDown(home(), { key: "Enter" }); +} + +beforeEach(() => { + useSettingsDialog.setState({ + base: structuredClone(DEFAULT_SETTINGS), + globalBase: structuredClone(DEFAULT_SETTINGS), + staged: {}, + query: "", + }); + entries["/opt/maven-3.9"] = "dir"; + entries["/opt/maven-3.9/bin/mvn"] = "file"; + resolve.mockReset(); + resolve.mockResolvedValue(ok("/data/m2/repository")); + choosePath.mockReset(); +}); +afterEach(cleanup); + +describe("Maven settings paths", () => { + it("resolves the local repository placeholder without writing any setting", async () => { + renderFields(); + await waitFor(() => expect(repositoryInput().placeholder).toBe("/data/m2/repository")); + expect(resolve).toHaveBeenCalledWith(null, null); + expect(staged(SETTINGS_KEY)).toBe(""); + expect(staged(REPOSITORY_KEY)).toBe(""); + }); + + it("recomputes the placeholder when the Maven home is entered", async () => { + renderFields(); + await waitFor(() => expect(repositoryInput().placeholder).toBe("/data/m2/repository")); + resolve.mockResolvedValue(ok("/opt/maven-3.9/repository")); + + enterHome("/opt/maven-3.9"); + + await waitFor(() => expect(resolve).toHaveBeenLastCalledWith("/opt/maven-3.9", null)); + await waitFor(() => expect(repositoryInput().placeholder).toBe("/opt/maven-3.9/repository")); + // Entering a home fills nothing: IDEA leaves both fields to the user. + expect(settingsInput().value).toBe(""); + expect(staged(SETTINGS_KEY)).toBe(""); + }); + + it("recomputes the placeholder when the user settings file changes", async () => { + renderFields(); + await waitFor(() => expect(repositoryInput().placeholder).toBe("/data/m2/repository")); + resolve.mockResolvedValue(ok("/custom/repository")); + + fireEvent.change(settingsInput(), { target: { value: "/custom/settings.xml" } }); + + await waitFor(() => expect(resolve).toHaveBeenLastCalledWith(null, "/custom/settings.xml")); + await waitFor(() => expect(repositoryInput().placeholder).toBe("/custom/repository")); + expect(repositoryInput().value).toBe(""); + }); + + it("falls back to the static hint when the backend cannot resolve a default", async () => { + resolve.mockResolvedValue(ok(null)); + renderFields(); + await act(async () => {}); + expect(repositoryInput().placeholder).toBe("From settings.xml, else ~/.m2/repository"); + }); + + it("keeps a user-set repository untouched", async () => { + stage("build.maven", "project", REPOSITORY_KEY, "/custom/repository"); + renderFields(); + await waitFor(() => expect(repositoryInput().placeholder).toBe("/data/m2/repository")); + expect(repositoryInput().value).toBe("/custom/repository"); + expect(staged(REPOSITORY_KEY)).toBe("/custom/repository"); + }); +}); diff --git a/src/features/settings/languages/LanguagePages.tsx b/src/features/settings/languages/LanguagePages.tsx index 5e0d93e5ed..7ec05c94ea 100644 --- a/src/features/settings/languages/LanguagePages.tsx +++ b/src/features/settings/languages/LanguagePages.tsx @@ -16,7 +16,7 @@ import { choosePath } from "@/platform/choosePath"; import { usePageContext, useSetting } from "../components/context"; import { SdkField, tildify, useDetected, useJdtlsJdk } from "./components"; import { isMavenThreadCount } from "./mavenThreads"; -import { mavenHomeProblem } from "./mavenHome"; +import { MavenSettingsFields } from "./MavenSettingsFields"; import { PathField, PathInput } from "./PathInput"; import styles from "./Sdk.module.css"; @@ -618,8 +618,6 @@ export function MavenPage() { const [updateSnapshots, setUpdateSnapshots] = useSetting("languages.java.maven.updateSnapshots"); const [threads, setThreads] = useSetting("languages.java.maven.threads"); const threadsInvalid = !!threads?.trim() && !isMavenThreadCount(threads); - const root = useProject((s) => s.project?.root); - const validateMavenHome = useCallback((path: string) => mavenHomeProblem(path, root), [root]); const [activeProfiles, setActiveProfiles] = useSetting("languages.java.maven.activeProfiles"); const id = useId(); return ( @@ -660,33 +658,7 @@ export function MavenPage() {
- - - + `, then the Maven home's global + * `conf/settings.xml`, then `~/.m2/repository` — recomputed when either path changes. + */ +import { useCallback, useEffect, useId, useState } from "react"; +import { call, commands } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { Row } from "../components/Form"; +import { useSetting } from "../components/context"; +import { SdkField } from "./components"; +import { mavenHomeProblem } from "./mavenHome"; +import { PathField } from "./PathInput"; + +const HOME_KEY = "languages.java.maven.home"; +const SETTINGS_KEY = "languages.java.maven.userSettings"; +const REPOSITORY_KEY = "languages.java.maven.localRepository"; + +/** Shown until the backend's answer arrives, and where it has no default. */ +const FALLBACK_PLACEHOLDER = "From settings.xml, else ~/.m2/repository"; + +/** The local repository a build with this home and user settings reads. */ +async function resolveLocalRepository(home: string, userSettings: string): Promise { + const resolved = await call(commands.mavenLocalRepository(home.trim() || null, userSettings.trim() || null)).catch( + () => null, + ); + return resolved ?? FALLBACK_PLACEHOLDER; +} + +export function MavenSettingsFields() { + const [home, setHome] = useSetting(HOME_KEY); + const [settings] = useSetting(SETTINGS_KEY); + const [repositoryPlaceholder, setRepositoryPlaceholder] = useState(FALLBACK_PLACEHOLDER); + const root = useProject((s) => s.project?.root); + const validate = useCallback((path: string) => mavenHomeProblem(path, root), [root]); + const settingsId = useId(); + const repositoryId = useId(); + + // IDEA recomputes the repository default when the home or the settings file changes. + useEffect(() => { + let live = true; + void resolveLocalRepository(home, settings).then((resolved) => { + if (live) setRepositoryPlaceholder(resolved); + }); + return () => { + live = false; + }; + }, [home, settings]); + + return ( + <> + + + + + + + + + + + ); +}