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 <localRepository> 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 <[email protected]>
Цей коміт міститься в:
Muuтаmuutot authored and GitHub committed 2026-12-04 02:11:36 +08:00
1 джерело c412491972
коміт 7c9fa1dc3b
5 files changed
+292 -31

No files matched your search

+72 -1
Переглянути файл
@@ -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<BuildModel> {
blocking(move || workspace::load_project(&project, &config)).await
}
/// Settings › Build Tools › Maven: the local repository the field's placeholder shows —
/// the `<localRepository>` 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<String>,
user_settings: Option<String>,
) -> IdeResult<Option<String>> {
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;
+7
Переглянути файл
@@ -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 `<localRepository>` 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<string | null, IdeError>(__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
+122
Переглянути файл
@@ -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<unknown>>());
/** Paths `fsEntryKind` finds. */
const entries = vi.hoisted(() => ({}) as Record<string, "file" | "dir">);
const choosePath = vi.fn<() => Promise<string | null>>();
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<typeof import("@/platform/ipc")>();
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(
<PageContext.Provider value={MAVEN_CONTEXT}>
<MavenSettingsFields />
</PageContext.Provider>,
);
}
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");
});
});
+2 -30
Переглянути файл
@@ -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<boolean>("languages.java.maven.updateSnapshots");
const [threads, setThreads] = useSetting<string>("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<string>("languages.java.maven.activeProfiles");
const id = useId();
return (
@@ -660,33 +658,7 @@ export function MavenPage() {
</Row>
</Section>
<Section title="Environment" stackFields>
<SdkRow
k="languages.java.maven.home"
label="Maven home path"
kind="maven"
emptyLabel="Auto"
emptyDetail="Maven wrapper, else mvn on PATH"
directory
browseTitle="Select Maven Home Directory"
aria-label="Maven home path"
validate={validateMavenHome}
hint="Runs sync, builds and Maven run configurations. A chosen home is used instead of the project's mvnw. Bypassed while the Maven daemon is enabled."
/>
<PathInput
k="languages.java.maven.userSettings"
label="User settings file"
placeholder="~/.m2/settings.xml"
title="Select Maven settings.xml"
file
hint="Passed as -s (mirrors, servers, proxies)."
/>
<PathInput
k="languages.java.maven.localRepository"
label="Local repository"
placeholder="From settings.xml, else ~/.m2/repository"
title="Select Local Repository"
hint="Passed as -Dmaven.repo.local."
/>
<MavenSettingsFields />
<PathInput
k="languages.java.maven.toolchains"
label="Toolchains file"
+89
Переглянути файл
@@ -0,0 +1,89 @@
/**
* Settings › Build Tools › Maven › Environment: the three paths IDEA keeps defaults for.
* Only the user fills the settings file and local repository (both stay empty otherwise);
* the repository's placeholder shows the effective default the backend resolves — the
* user settings file's `<localRepository>`, 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<string> {
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<string>(HOME_KEY);
const [settings] = useSetting<string>(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 (
<>
<Row
label="Maven home path"
hint="Runs sync, builds and Maven run configurations. A chosen home is used instead of the project's mvnw. Bypassed while the Maven daemon is enabled."
>
<SdkField
kind="maven"
value={home}
onChange={setHome}
emptyLabel="Auto"
emptyDetail="Maven wrapper, else mvn on PATH"
directory
browseTitle="Select Maven Home Directory"
aria-label="Maven home path"
validate={validate}
/>
</Row>
<Row label="User settings file" htmlFor={settingsId} hint="Passed as -s (mirrors, servers, proxies).">
<PathField
k={SETTINGS_KEY}
id={settingsId}
placeholder="~/.m2/settings.xml"
title="Select Maven settings.xml"
file
/>
</Row>
<Row label="Local repository" htmlFor={repositoryId} hint="Passed as -Dmaven.repo.local.">
<PathField
k={REPOSITORY_KEY}
id={repositoryId}
placeholder={repositoryPlaceholder}
title="Select Local Repository"
/>
</Row>
</>
);
}