feat(welcome): import recent projects and groups from a JetBrains IDE (#6979)

Import Recent Projects from JetBrains IDE (Welcome screen more menu, File > Manage IDE Settings) reads the IDE's options/recentProjects.xml and merges its recent projects and project groups into OpenIDEA's. Entries keep their custom or display name and the later of their open and activation times; hidden (LightEdit) entries are skipped, $USER_HOME$ and $APPLICATION_CONFIG_DIR$ are expanded, and projects whose folder is gone are skipped and counted. Existing entries and groups are kept, a taken group name gets a number, and importing twice adds nothing. Import Settings from JetBrains IDE lists the recent projects as a row of its confirmation and merges them too.

Closes #6970

Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
LU XIANGRUIтаwildcatDownstairs authored and GitHub committed 2026-11-30 20:15:11 +08:00
1 джерело baab92c804
коміт ee9b50179e
18 files changed
+594 -27

No files matched your search

Створено
+1
Переглянути файл
@@ -5116,6 +5116,7 @@ dependencies = [
"ide-text",
"ide-vfs",
"parking_lot 0.12.5",
"quick-xml 0.42.0",
"semver",
"serde",
"serde_json",
+1
Переглянути файл
@@ -277,6 +277,7 @@ pub fn spec(os: Os) -> Vec<Entry> {
act("file.exportSettings", "Export Settings…"),
act("file.importSettings", "Import Settings…"),
act("file.importJetBrainsSettings", "Import Settings from JetBrains IDE…"),
act("file.importJetBrainsRecentProjects", "Import Recent Projects from JetBrains IDE…"),
act("file.syncSettings", "Sync Settings Now"),
],
),
+1
Переглянути файл
@@ -24,6 +24,7 @@ globset.workspace = true
uuid.workspace = true
zip.workspace = true
encoding_rs.workspace = true
quick-xml = "0.42"
[target.'cfg(windows)'.dependencies]
winreg = "0.56"
+344 -5
Переглянути файл
@@ -162,6 +162,127 @@ fn is_missing(path: &Path) -> bool {
path.is_absolute() && !text.contains("://") && !wsl && !path.exists()
}
fn folder_name(path: &Path) -> String {
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string())
}
/// What importing a JetBrains IDE's recent projects did (or, as a preview, would do).
#[derive(Clone, Debug, Default, PartialEq, Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct JetBrainsRecentImport {
/// Projects added to the recent projects.
pub imported: u32,
/// Projects left out because their folder no longer exists.
pub missing: u32,
/// Project groups added.
pub groups: u32,
}
/// A recent project as a JetBrains IDE keeps it in `options/recentProjects.xml`.
#[derive(Debug, Default, PartialEq)]
struct JetBrainsRecent {
path: String,
name: Option<String>,
opened_at_ms: f64,
/// Opened but not listed (LightEdit, a file opened alone): the IDE does not show it.
hidden: bool,
}
#[derive(Debug, Default, PartialEq)]
struct JetBrainsGroup {
name: String,
paths: Vec<String>,
expanded: bool,
}
/// The `RecentProjectsManager` state: `additionalInfo` entries (path → `RecentProjectMetaInfo`) and
/// `groups` (`ProjectGroup` with `name`, `expanded` and its `projects`).
fn parse_jetbrains_recent(xml: &str) -> (Vec<JetBrainsRecent>, Vec<JetBrainsGroup>) {
use quick_xml::{Reader, XmlVersion, events::Event};
let mut reader = Reader::from_str(xml);
let (mut projects, mut groups) = (Vec::new(), Vec::new());
let mut project: Option<JetBrainsRecent> = None;
let mut group: Option<JetBrainsGroup> = None;
loop {
let (tag, empty) = match reader.read_event() {
Ok(Event::Start(tag)) => (tag, false),
Ok(Event::Empty(tag)) => (tag, true),
Ok(Event::End(tag)) => {
match tag.local_name().as_ref() {
"entry" => projects.extend(project.take()),
"ProjectGroup" => groups.extend(group.take()),
_ => {}
}
continue;
}
Ok(Event::Eof) | Err(_) => break,
_ => continue,
};
let attr = |key: &str| {
tag.attributes()
.flatten()
.find(|a| a.key.as_ref() == key)
.and_then(|a| a.normalized_value(XmlVersion::Implicit1_0).ok().map(|v| v.into_owned()))
};
match tag.local_name().as_ref() {
"entry" if !empty && group.is_none() => {
project = attr("key").map(|path| JetBrainsRecent { path, ..Default::default() });
}
"RecentProjectMetaInfo" => {
if let Some(p) = &mut project {
p.hidden = attr("hidden").as_deref() == Some("true");
}
}
"ProjectGroup" if !empty => group = Some(JetBrainsGroup::default()),
"option" => {
let (name, value) = (attr("name"), attr("value"));
if let Some(g) = &mut group {
match (name.as_deref(), value) {
(Some("name"), Some(v)) => g.name = v,
(Some("expanded"), Some(v)) => g.expanded = v == "true",
// `<option name="projects"><list><option value="…"/>`.
(None, Some(v)) => g.paths.push(v),
_ => {}
}
} else if let Some(p) = &mut project {
match (name.as_deref(), value) {
(Some("customProjectName"), Some(v)) => p.name = Some(v),
// Older IDEs.
(Some("displayName"), Some(v)) if p.name.is_none() => p.name = Some(v),
(Some("projectOpenTimestamp" | "activationTimestamp"), Some(v)) => {
p.opened_at_ms = p.opened_at_ms.max(v.parse().unwrap_or(0.0));
}
_ => {}
}
}
}
_ => {}
}
}
(projects, groups)
}
/// A path of `recentProjects.xml`: `$USER_HOME$` is `home`, `$APPLICATION_CONFIG_DIR$` the IDE's settings
/// folder `config`; Windows paths are stored with `/`. `None` for other path variables or a relative path.
fn expand_jetbrains_path(raw: &str, home: Option<&Path>, config: &Path) -> Option<PathBuf> {
let (base, rest) = if let Some(rest) = raw.strip_prefix("$USER_HOME$") {
(Some(home?), rest)
} else if let Some(rest) = raw.strip_prefix("$APPLICATION_CONFIG_DIR$") {
(Some(config), rest)
} else {
(None, raw)
};
if rest.contains('$') {
return None;
}
let rest = if cfg!(windows) { rest.replace('/', "\\") } else { rest.to_owned() };
let path = match base {
Some(base) => base.join(rest.trim_start_matches(['/', '\\'])),
None => PathBuf::from(rest),
};
path.is_absolute().then_some(path)
}
impl RecentProjects {
pub fn load(config_dir: &Path) -> Self {
let file = config_dir.join("recent.json");
@@ -208,8 +329,7 @@ impl RecentProjects {
pub fn touch(&self, path: &Path, branch: Option<String>) -> IdeResult<()> {
let mut items = self.items.lock();
items.retain(|p| p.path != path);
let name =
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string());
let name = folder_name(path);
items.insert(0, RecentProject { path: path.into(), name, opened_at_ms: now_ms(), branch, missing: false });
cap(&mut items, &self.groups.lock());
self.persist(&items)
@@ -219,9 +339,7 @@ impl RecentProjects {
pub fn rename(&self, path: &Path, name: Option<&str>) -> IdeResult<()> {
let mut items = self.items.lock();
let Some(item) = items.iter_mut().find(|p| p.path == path) else { return Ok(()) };
let name = name.map(str::to_owned).unwrap_or_else(|| {
path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| path.display().to_string())
});
let name = name.map(str::to_owned).unwrap_or_else(|| folder_name(path));
if item.name == name {
return Ok(());
}
@@ -247,6 +365,91 @@ impl RecentProjects {
Ok(())
}
/// Adds the recent projects and project groups of a JetBrains IDE (`xml`: its
/// `options/recentProjects.xml`; `config`: its settings folder). Projects already recent keep their
/// entry, folders that are gone are left out, and the groups made here are kept: an imported group
/// whose name is taken gets a number, and one whose projects are all grouped already is not added.
/// `dry_run` only counts.
pub fn import_jetbrains(
&self,
xml: &str,
home: Option<&Path>,
config: &Path,
dry_run: bool,
) -> IdeResult<JetBrainsRecentImport> {
let (projects, jetbrains_groups) = parse_jetbrains_recent(xml);
let mut summary = JetBrainsRecentImport::default();
let mut items = self.items.lock();
let mut groups = self.groups.lock();
let mut new_items = items.clone();
let mut added = Vec::new();
for p in projects.into_iter().filter(|p| !p.hidden) {
let Some(path) = expand_jetbrains_path(&p.path, home, config).filter(|path| !is_missing(path)) else {
summary.missing += 1;
continue;
};
if new_items.iter().any(|i| i.path == path) {
continue;
}
let name = p.name.filter(|n| !n.trim().is_empty()).unwrap_or_else(|| folder_name(&path));
new_items.push(RecentProject {
path: path.as_path().into(),
name,
opened_at_ms: p.opened_at_ms,
branch: None,
missing: false,
});
added.push(path);
}
new_items.sort_by(|a, b| b.opened_at_ms.total_cmp(&a.opened_at_ms));
let mut new_groups = groups.clone();
for g in jetbrains_groups {
let base = g.name.trim().to_owned();
if base.is_empty() {
continue;
}
let mut name = base.clone();
for n in 2.. {
if !new_groups.iter().any(|existing| existing.name == name) {
break;
}
name = format!("{base} {n}");
}
let paths = g
.paths
.iter()
.filter_map(|raw| expand_jetbrains_path(raw, home, config))
.filter(|path| new_items.iter().any(|i| i.path == *path))
.map(|path| path.as_path().into())
.collect();
new_groups.push(RecentProjectGroup { name, paths, expanded: g.expanded });
}
// Existing groups are normalized already, so they keep their place and their projects.
let mut new_groups = normalize(new_groups);
let existing = groups.len();
let mut index = 0;
new_groups.retain(|g| {
index += 1;
index <= existing || !g.paths.is_empty()
});
cap(&mut new_items, &new_groups);
summary.imported = added.iter().filter(|p| new_items.iter().any(|i| i.path == **p)).count() as u32;
summary.groups = (new_groups.len() - existing) as u32;
if dry_run {
return Ok(summary);
}
if summary.imported > 0 {
self.persist(&new_items)?;
*items = new_items;
}
if summary.groups > 0 {
write_json(&self.groups_file, &new_groups)?;
*groups = new_groups;
}
Ok(summary)
}
pub fn paths(&self) -> Vec<PathBuf> {
self.list().into_iter().map(|p| p.path.into_path_buf()).collect()
}
@@ -344,6 +547,142 @@ mod tests {
assert_eq!(recent.list().len(), 1);
}
const JETBRAINS_RECENT: &str = r#"<application>
<component name="RecentProjectsManager">
<option name="additionalInfo">
<map>
<entry key="$USER_HOME$/code/alpha">
<value>
<RecentProjectMetaInfo frameTitle="alpha – main.rs" projectWorkspaceId="w1">
<option name="activationTimestamp" value="1700000005000" />
<option name="colorInfo"><RecentProjectColorInfo associatedIndex="1" /></option>
<option name="customProjectName" value="Alpha Service" />
<option name="projectOpenTimestamp" value="1700000001000" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="$USER_HOME$/code/beta">
<value>
<RecentProjectMetaInfo>
<option name="displayName" value="beta-old-name" />
<option name="projectOpenTimestamp" value="1700000003000" />
</RecentProjectMetaInfo>
</value>
</entry>
<entry key="$USER_HOME$/code/gone">
<value><RecentProjectMetaInfo /></value>
</entry>
<entry key="$APPLICATION_CONFIG_DIR$/light-edit">
<value><RecentProjectMetaInfo hidden="true" /></value>
</entry>
<entry key="$PROJECT_DIR$/x">
<value><RecentProjectMetaInfo /></value>
</entry>
</map>
</option>
<option name="groups">
<list>
<ProjectGroup>
<option name="expanded" value="true" />
<option name="name" value="Work" />
<option name="projects">
<list>
<option value="$USER_HOME$/code/alpha" />
<option value="$USER_HOME$/code/gone" />
</list>
</option>
</ProjectGroup>
<ProjectGroup>
<option name="name" value="Empty" />
</ProjectGroup>
</list>
</option>
<option name="lastOpenedProject" value="$USER_HOME$/code/alpha" />
</component>
</application>"#;
#[test]
fn parses_jetbrains_recent_projects_and_groups() {
let (projects, groups) = parse_jetbrains_recent(JETBRAINS_RECENT);
assert_eq!(projects.len(), 5);
assert_eq!(
projects[0],
JetBrainsRecent {
path: "$USER_HOME$/code/alpha".into(),
name: Some("Alpha Service".into()),
opened_at_ms: 1700000005000.0,
hidden: false,
}
);
assert_eq!(projects[1].name.as_deref(), Some("beta-old-name"));
assert!(projects[3].hidden);
assert_eq!(
groups,
vec![
JetBrainsGroup {
name: "Work".into(),
paths: vec!["$USER_HOME$/code/alpha".into(), "$USER_HOME$/code/gone".into()],
expanded: true,
},
JetBrainsGroup { name: "Empty".into(), paths: vec![], expanded: false },
]
);
}
#[test]
fn expands_jetbrains_path_variables() {
let (home, config) = (Path::new("/home/me"), Path::new("/cfg/IDE"));
assert_eq!(expand_jetbrains_path("$USER_HOME$/a/b", Some(home), config), Some(home.join("a").join("b")));
assert_eq!(expand_jetbrains_path("$APPLICATION_CONFIG_DIR$/x", Some(home), config), Some(config.join("x")));
assert_eq!(expand_jetbrains_path("$USER_HOME$", Some(home), config), Some(home.to_path_buf()));
assert_eq!(expand_jetbrains_path("$USER_HOME$/a", None, config), None);
assert_eq!(expand_jetbrains_path("$PROJECT_DIR$/a", Some(home), config), None);
assert_eq!(expand_jetbrains_path("relative/a", Some(home), config), None);
#[cfg(windows)]
assert_eq!(expand_jetbrains_path("C:/Users/me/a", Some(home), config), Some(PathBuf::from(r"C:\Users\me\a")));
}
#[test]
fn jetbrains_import_merges_without_touching_existing_groups() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
for p in ["code/alpha", "code/beta", "mine"] {
std::fs::create_dir_all(home.join(p)).unwrap();
}
let (alpha, beta, mine) = (home.join("code/alpha"), home.join("code/beta"), home.join("mine"));
let cfg = tmp.path().join("config");
let recent = RecentProjects::load(&cfg);
recent.touch(&mine, None).unwrap();
recent.touch(&beta, None).unwrap();
let own = RecentProjectGroup { name: "Work".into(), paths: vec![mine.as_path().into()], expanded: true };
recent.set_groups(vec![own.clone()]).unwrap();
let ide = tmp.path().join("IDE");
let preview = recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, true).unwrap();
let expected = JetBrainsRecentImport { imported: 1, missing: 2, groups: 1 };
assert_eq!(preview, expected);
assert_eq!(recent.list().len(), 2, "a preview changes nothing");
assert_eq!(recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, false).unwrap(), expected);
let reloaded = RecentProjects::load(&cfg);
let list = reloaded.list();
let item = |p: &Path| list.iter().find(|i| i.path.as_ref() == p).unwrap();
assert_eq!(item(&alpha).name, "Alpha Service");
assert_eq!(item(&alpha).opened_at_ms, 1700000005000.0);
// Already recent: keeps its own entry.
assert_eq!(item(&beta).name, "beta");
assert_eq!(list.len(), 3);
// The group made here stays; the imported one gets a free name and only the imported projects.
let imported =
RecentProjectGroup { name: "Work 2".into(), paths: vec![alpha.as_path().into()], expanded: true };
assert_eq!(reloaded.groups(), vec![own.clone(), imported.clone()]);
// Importing again adds nothing.
let again = recent.import_jetbrains(JETBRAINS_RECENT, Some(&home), &ide, false).unwrap();
assert_eq!(again, JetBrainsRecentImport { imported: 0, missing: 2, groups: 0 });
assert_eq!(RecentProjects::load(&cfg).groups(), vec![own, imported]);
}
fn write_head(git_dir: &Path, contents: &str) {
std::fs::create_dir_all(git_dir).unwrap();
std::fs::write(git_dir.join("HEAD"), contents).unwrap();
+31
Переглянути файл
@@ -382,6 +382,36 @@ pub async fn settings_list_jetbrains_ides() -> IdeResult<Vec<ide_host::plugins::
.map_err(|e| IdeError::internal(e.to_string()))?
}
/// Import Recent Projects from JetBrains IDE: merges the recent projects and project groups of the IDE
/// whose settings folder is `path` (nothing when it has none); `dry_run` only counts them.
#[desktop_command(trust = always)]
#[tauri::command]
#[specta::specta]
pub async fn recent_import_jetbrains(
state: State<'_, AppState>,
path: PathBuf,
dry_run: bool,
) -> IdeResult<ide_workspace::recent::JetBrainsRecentImport> {
let app = state.app.clone();
tauri::async_runtime::spawn_blocking(move || {
let xml = match std::fs::read_to_string(path.join("options").join("recentProjects.xml")) {
Ok(xml) => xml,
Err(e) if matches!(e.kind(), std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory) => {
return Ok(Default::default());
}
Err(e) => return Err(e.into()),
};
let state = app.state::<AppState>();
let summary = state.recent.import_jetbrains(&xml, dirs::home_dir().as_deref(), &path, dry_run)?;
if summary.imported > 0 {
crate::jump_list::refresh(&state.app, state.recent.list());
}
Ok(summary)
})
.await
.map_err(|e| IdeError::internal(e.to_string()))?
}
pub(crate) fn project_current(window: Window) -> Option<ProjectInfo> {
let state = window.state::<AppState>();
state.project(window.label()).ok().filter(|p| !p.light).map(|p| project_info(&p))
@@ -466,6 +496,7 @@ ide_command::desktop_domain!(
log_frontend,
project_rename,
project_trust_add_location,
recent_import_jetbrains,
recent_project_groups,
recent_projects,
remove_recent_project,
+1
Переглянути файл
@@ -1533,6 +1533,7 @@ mod tests {
"file.exportSettings",
"file.importSettings",
"file.importJetBrainsSettings",
"file.importJetBrainsRecentProjects",
"file.syncSettings",
"file.togglePowerSave",
"macro.startRecording",
+1
Переглянути файл
@@ -613,6 +613,7 @@ pypi_search outside_restricted project_host bin
python_requirements trusted project_host bindings async
python_route_sources trusted desktop bindings async
recent_files always project_host bindings sync
recent_import_jetbrains always desktop bindings async
recent_project_groups always desktop bindings sync
recent_projects always desktop bindings async
redo_workspace_edit always project_host bindings async
+15
Переглянути файл
@@ -1744,6 +1744,11 @@ export const commands = {
pythonRouteSources: () => typedError<RouteSource[], IdeError>(__TAURI_INVOKE("python_route_sources")),
/** Recently opened files, most recent first (⌘E). */
recentFiles: () => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("recent_files")),
/**
* Import Recent Projects from JetBrains IDE: merges the recent projects and project groups of the IDE
* whose settings folder is `path` (nothing when it has none); `dry_run` only counts them.
*/
recentImportJetbrains: (path: string, dryRun: boolean) => typedError<JetBrainsRecentImport, IdeError>(__TAURI_INVOKE("recent_import_jetbrains", { path, dryRun })),
/** The welcome screen's project groups. */
recentProjectGroups: () => __TAURI_INVOKE<RecentProjectGroup[]>("recent_project_groups"),
recentProjects: () => __TAURI_INVOKE<RecentProject[]>("recent_projects"),
@@ -10141,6 +10146,16 @@ export type JdkVendor = {
name: string,
};
/** What importing a JetBrains IDE's recent projects did (or, as a preview, would do). */
export type JetBrainsRecentImport = {
/** Projects added to the recent projects. */
imported: number,
/** Projects left out because their folder no longer exists. */
missing: number,
/** Project groups added. */
groups: number,
};
/**
* A JetBrains IDE's settings folder or exported archive: every
* entry name, and the text of the entries OpenIDEA maps (the frontend does the mapping).
+59 -3
Переглянути файл
@@ -7,19 +7,28 @@ import listStyles from "@/ui/List.module.css";
const listIdes = vi.fn();
const importJetBrainsSettings = vi.fn();
const notify = vi.fn();
const importRecent = vi.fn();
const loadRecent = vi.fn();
vi.mock("@/platform/ipc", async (original) => ({
...(await original<typeof import("@/platform/ipc")>()),
call: <T,>(result: Promise<T>) => result,
commands: { settingsListJetbrainsIdes: () => listIdes() },
commands: {
settingsListJetbrainsIdes: () => listIdes(),
recentImportJetbrains: (path: string, dryRun: boolean) => importRecent(path, dryRun),
},
}));
vi.mock("../jetbrainsSettings", () => ({ importJetBrainsSettings: (path: string) => importJetBrainsSettings(path) }));
vi.mock("../jetbrainsSettings", async (original) => ({
...(await original<typeof import("../jetbrainsSettings")>()),
importJetBrainsSettings: (path: string) => importJetBrainsSettings(path),
}));
vi.mock("@/features/welcome/recent", () => ({ loadRecent: () => loadRecent() }));
vi.mock("@/workbench/contributions", async (original) => ({
...(await original<typeof import("@/workbench/contributions")>()),
notifications: () => ({ notify }),
}));
const { importFromJetBrainsIde } = await import("../projectActions");
const { importFromJetBrainsIde, importJetBrainsRecentProjects } = await import("../projectActions");
const idea = {
ide: "IntelliJ IDEA 2025.2",
@@ -110,3 +119,50 @@ describe("Manage IDE Settings › Import Settings from JetBrains IDE…", () =>
expect(importJetBrainsSettings).toHaveBeenCalledExactlyOnceWith(ides[59]!.path);
});
});
describe("Import Recent Projects from JetBrains IDE…", () => {
async function pickFirst(run: () => Promise<void>) {
let done!: Promise<void>;
await act(async () => {
done = run();
});
const list = screen.getByRole("listbox", { name: "Import Recent Projects from JetBrains IDE" });
await act(async () => {
fireEvent.keyDown(list, { key: "Enter" });
await done;
});
}
it("merges the chosen IDE's recent projects, refreshes the list and says what it did", async () => {
listIdes.mockResolvedValue([idea, studio]);
importRecent.mockResolvedValue({ imported: 3, missing: 2, groups: 1 });
await pickFirst(importJetBrainsRecentProjects);
expect(importRecent).toHaveBeenCalledExactlyOnceWith(idea.path, false);
expect(loadRecent).toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
level: "info",
title: "Recent projects imported",
body: "Imported 3 recent projects and 1 project groups, skipped 2 whose folder is missing.",
}),
);
});
it("warns when there is nothing new", async () => {
listIdes.mockResolvedValue([idea]);
importRecent.mockResolvedValue({ imported: 0, missing: 1, groups: 0 });
await pickFirst(importJetBrainsRecentProjects);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "warning", title: "No new recent projects to import" }),
);
});
it("reports a failure", async () => {
listIdes.mockResolvedValue([idea]);
importRecent.mockRejectedValue(new Error("denied"));
await pickFirst(importJetBrainsRecentProjects);
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({ level: "error", title: "Cannot import recent projects" }),
);
});
});
+30
Переглянути файл
@@ -6,6 +6,8 @@ const set = vi.fn();
const notify = vi.fn();
const execute = vi.fn();
const marketCall = vi.fn();
const importRecent = vi.fn();
const loadRecent = vi.fn();
const market = [
{ id: "ruyimg.codeglance-pro", name: "CodeGlance Pro", installed: null, compatible: true },
{ id: "solhovoy.grep-console", name: "Grep Console", installed: null, compatible: true },
@@ -22,9 +24,11 @@ vi.mock("@/platform/ipc", async (original) => {
settingsGetGlobal: async () => ({ editor }),
settingsSet: (scope: string, key: string, value: string) => set(scope, key, value),
pluginMarket: () => marketCall(),
recentImportJetbrains: (path: string, dryRun: boolean) => importRecent(path, dryRun),
},
};
});
vi.mock("@/features/welcome/recent", () => ({ loadRecent: () => loadRecent() }));
vi.mock("@/platform/actions", async (original) => ({
...(await original<typeof import("@/platform/actions")>()),
executeAction: (id: string, arg?: unknown) => execute(id, arg),
@@ -58,6 +62,7 @@ beforeEach(() => {
});
set.mockResolvedValue({ status: "ok", data: { editor } });
marketCall.mockResolvedValue({ status: "ok", data: market });
importRecent.mockResolvedValue({ status: "ok", data: { imported: 0, missing: 0, groups: 0 } });
// jsdom has no canvas: the import falls back to the font size for the line height.
vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
});
@@ -150,3 +155,28 @@ it("says so when the plugin marketplace cannot be reached, without blaming the p
expect(screen.getByText(/Plugins without a counterpart/)).not.toHaveTextContent("CodeGlancePro");
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Cancel" })));
});
it("lists an IDE's recent projects and merges them on Import", async () => {
read.mockResolvedValue({ status: "ok", data: { entries: [], files: {} } });
importRecent.mockResolvedValue({ status: "ok", data: { imported: 4, missing: 1, groups: 2 } });
render(<MessagesHost />);
let done!: Promise<void>;
await act(async () => {
done = importJetBrainsSettings("/settings/IDE");
});
expect(importRecent).toHaveBeenCalledExactlyOnceWith("/settings/IDE", true);
expect(screen.getByText("Recent projects")).toBeInTheDocument();
expect(screen.getByText("4 new, 2 new project groups, 1 skipped (folder missing)")).toBeInTheDocument();
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "Import" }));
await done;
});
expect(importRecent).toHaveBeenLastCalledWith("/settings/IDE", false);
expect(loadRecent).toHaveBeenCalled();
expect(notify).toHaveBeenCalledWith(
expect.objectContaining({
title: "Settings imported",
body: "Imported 4 recent projects and 2 project groups, skipped 1 whose folder is missing.",
}),
);
});
+1
Переглянути файл
@@ -27,6 +27,7 @@ vi.mock("@/platform/ipc", async (original) => {
settingsGetGlobal: async () => ({ editor }),
settingsSet: (scope: string, key: string, value: string) => set(scope, key, value),
languages: async () => [python],
recentImportJetbrains: async () => ({ status: "ok", data: { imported: 0, missing: 0, groups: 0 } }),
},
};
});
+32 -3
Переглянути файл
@@ -6,7 +6,13 @@
* out). The rest is listed as not imported.
*/
import { Fragment, useEffect, useState } from "react";
import type { CustomKeymap, JetBrainsSettings, LanguageCodeStyle, LanguageInfo } from "@/bindings";
import type {
CustomKeymap,
JetBrainsRecentImport,
JetBrainsSettings,
LanguageCodeStyle,
LanguageInfo,
} from "@/bindings";
import { actionToggled, executeAction, getAction } from "@/platform/actions";
import { customSchemes } from "@/platform/colorScheme";
import { createFontProbeCanvas, fontsLoaded, monoFontFamily } from "@/platform/fonts";
@@ -18,6 +24,7 @@ import { guessOs } from "@/platform/platformInfo";
import { useProject } from "@/platform/project";
import { notifications } from "@/workbench/contributions";
import { ask } from "@/workbench/messages";
import { loadRecent } from "@/features/welcome/recent";
import { parseJetBrainsTemplates, type JetBrainsTemplateImport } from "@/features/templates/live/jetbrains";
import { saveImportedTemplates } from "@/features/templates/live/store";
import styles from "./app.module.css";
@@ -480,10 +487,25 @@ function Summary({ plan, pending }: { plan: JetBrainsImportPlan; pending?: Promi
);
}
/** What importing a JetBrains IDE's recent projects did. */
export function recentImportSummary({ imported, groups, missing }: JetBrainsRecentImport): string {
return tx`Imported ${imported} recent projects and ${groups} project groups, skipped ${missing} whose folder is missing.`;
}
/** Reads `path`, asks, then writes the mapped settings to the global layer. */
export async function importJetBrainsSettings(path: string) {
const bundle = await call(commands.settingsReadJetbrains(path));
const plan = await planJetBrainsImport(bundle, await commands.settingsGetGlobal());
// An IDE's settings folder (not an exported archive) has its recent projects.
const recent = await call(commands.recentImportJetbrains(path, true)).catch(() => null);
const hasRecent = !!recent && (recent.imported > 0 || recent.groups > 0);
if (hasRecent) {
const { imported, groups, missing } = recent;
plan.rows.push({
label: tx("Recent projects"),
value: tx`${imported} new, ${groups} new project groups, ${missing} skipped (folder missing)`,
});
}
const plugins = plan.plugins;
// Looked up while the confirmation is open; it shows the answer when it comes.
const pending = plugins?.candidates.length
@@ -491,7 +513,7 @@ export async function importJetBrainsSettings(path: string) {
.then((market) => suggestPlugins(plugins.candidates, market))
.catch(() => null)
: undefined;
if (!plan.writes.length && !plan.liveTemplates?.templates.length && !pending && !plugins?.vim) {
if (!plan.writes.length && !plan.liveTemplates?.templates.length && !pending && !plugins?.vim && !hasRecent) {
const details = [...plan.invalid, ...(plan.liveTemplates?.skipped ?? [])].join(", ");
notifications().notify({
level: "warning",
@@ -515,7 +537,14 @@ export async function importJetBrainsSettings(path: string) {
if (plan.liveTemplates?.templates.length) saveImportedTemplates(plan.liveTemplates.templates);
useProject.setState({ settings });
if (plugins?.vim && !actionToggled(getAction("vim.toggle"))) void executeAction("vim.toggle");
notifications().notify({ level: "info", title: "Settings imported", body: path, key: "app.settingsImport" });
const imported = hasRecent ? await call(commands.recentImportJetbrains(path, false)).catch(() => null) : null;
if (imported) void loadRecent();
notifications().notify({
level: "info",
title: "Settings imported",
body: imported ? recentImportSummary(imported) : path,
key: "app.settingsImport",
});
if (useProject.getState().project && plan.inspectionProfiles?.length)
offerInspectionProfiles(plan.inspectionProfiles);
void pending?.then((s) => s?.install.length && offerPlugins(s.install));
+53 -16
Переглянути файл
@@ -9,7 +9,8 @@ import { call, commands, isTauri } from "@/platform/ipc";
import { useProject } from "@/platform/project";
import { notifications, registerEditorBanner } from "@/workbench/contributions";
import { pickItems, promptInput } from "@/workbench/inputDialogs";
import { importJetBrainsSettings } from "./jetbrainsSettings";
import { loadRecent } from "@/features/welcome/recent";
import { importJetBrainsSettings, recentImportSummary } from "./jetbrainsSettings";
import { showNewProject } from "./NewProject";
import { tx } from "@/platform/i18n";
@@ -114,24 +115,30 @@ async function importSettings() {
}
}
/** The settings folder of the JetBrains IDE the user picks; undefined when none is installed or the pick is cancelled. */
async function pickJetBrainsIde(title: string): Promise<string | undefined> {
const ides = await call(commands.settingsListJetbrainsIdes());
if (!ides.length) {
notifications().notify({
level: "warning",
title: "No JetBrains IDE settings were found on this computer",
key: "app.settingsImport",
});
return;
}
const picked = await pickItems({
title,
items: ides.map((ide) => ({ key: ide.path, label: ide.ide })),
multiple: false,
});
return picked?.[0];
}
/** Import Settings from a JetBrains IDE installed on this computer, without exporting a `settings.zip` first. */
export async function importFromJetBrainsIde() {
try {
const ides = await call(commands.settingsListJetbrainsIdes());
if (!ides.length) {
notifications().notify({
level: "warning",
title: "No JetBrains IDE settings were found on this computer",
key: "app.settingsImport",
});
return;
}
const picked = await pickItems({
title: tx("Import Settings from JetBrains IDE"),
items: ides.map((ide) => ({ key: ide.path, label: ide.ide })),
multiple: false,
});
if (picked?.[0]) await importJetBrainsSettings(picked[0]);
const path = await pickJetBrainsIde(tx("Import Settings from JetBrains IDE"));
if (path) await importJetBrainsSettings(path);
} catch (e) {
notifications().notify({
level: "error",
@@ -142,6 +149,29 @@ export async function importFromJetBrainsIde() {
}
}
/** Adds the recent projects and project groups of a JetBrains IDE to the Welcome screen's. */
export async function importJetBrainsRecentProjects() {
try {
const path = await pickJetBrainsIde(tx("Import Recent Projects from JetBrains IDE"));
if (!path) return;
const result = await call(commands.recentImportJetbrains(path, false));
void loadRecent();
notifications().notify({
level: result.imported || result.groups ? "info" : "warning",
title: result.imported || result.groups ? "Recent projects imported" : "No new recent projects to import",
body: recentImportSummary(result),
key: "app.recentImport",
});
} catch (e) {
notifications().notify({
level: "error",
title: "Cannot import recent projects",
body: errorText(e),
key: "app.recentImport",
});
}
}
async function renameProject() {
const project = useProject.getState().project;
if (!project) return;
@@ -219,6 +249,13 @@ export function projectActions(): Action[] {
keywords: ["intellij", "pycharm", "webstorm", "android studio", "migrate", "manage ide settings"],
run: desktop(importFromJetBrainsIde),
},
{
id: "file.importJetBrainsRecentProjects",
title: "Import Recent Projects from JetBrains IDE…",
category: "File",
keywords: ["intellij", "pycharm", "webstorm", "android studio", "migrate", "project groups"],
run: desktop(importJetBrainsRecentProjects),
},
{
id: "file.togglePowerSave",
title: "Power Save Mode",
+7
Переглянути файл
@@ -70,6 +70,13 @@ function HeaderButtons() {
const secondary: MenuItem[] = [
{ kind: "action", action: "file.newUntitled", label: "New File", disabled: opening },
{ kind: "action", action: "file.openFile", label: "Open File", disabled: opening },
{ kind: "separator" },
{
kind: "action",
action: "file.importJetBrainsRecentProjects",
label: "Import Recent Projects from JetBrains IDE…",
disabled: opening,
},
];
return (
<div className={styles.headerButtons} role="group" aria-label={tx("Project actions")}>
+1
Переглянути файл
@@ -465,6 +465,7 @@
"menu.file.exportSettings": "Export Settings…",
"menu.file.importSettings": "Import Settings…",
"menu.file.importJetBrainsSettings": "Import Settings from JetBrains IDE…",
"menu.file.importJetBrainsRecentProjects": "Import Recent Projects from JetBrains IDE…",
"menu.file.syncSettings": "Sync Settings Now",
"menu.file.togglePowerSave": "Power Save Mode",
"menu.macros": "Macros",
+8
Переглянути файл
@@ -4812,5 +4812,13 @@
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.",
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.",
"Open in Xcode": "Open in Xcode",
"Import Recent Projects from JetBrains IDE": "Import Recent Projects from JetBrains IDE",
"Import Recent Projects from JetBrains IDE…": "Import Recent Projects from JetBrains IDE…",
"Recent projects imported": "Recent projects imported",
"No new recent projects to import": "No new recent projects to import",
"Cannot import recent projects": "Cannot import recent projects",
"Recent projects": "Recent projects",
"Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.": "Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.",
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "{imported} new, {groups} new project groups, {missing} skipped (folder missing)",
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it"
}
+7
Переглянути файл
@@ -11465,5 +11465,12 @@
"xcodebuild doesn't compile it until it's in a target of {name}. Add it in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译它。请在 Xcode 中添加,或把该组转换为文件夹。",
"xcodebuild doesn't compile {files} until they're in a target of {name}. Add them in Xcode or convert the group to a folder.": "在加入 {name} 的某个 target 之前,xcodebuild 不会编译 {files}。请在 Xcode 中添加,或把该组转换为文件夹。",
"Open in Xcode": "在 Xcode 中打开",
"Import Recent Projects from JetBrains IDE": "从 JetBrains IDE 导入最近项目",
"Import Recent Projects from JetBrains IDE…": "从 JetBrains IDE 导入最近项目…",
"Recent projects imported": "已导入最近项目",
"No new recent projects to import": "没有可导入的新最近项目",
"Cannot import recent projects": "无法导入最近项目",
"Imported {imported} recent projects and {groups} project groups, skipped {missing} whose folder is missing.": "已导入 {imported} 个最近项目和 {groups} 个项目分组,跳过 {missing} 个文件夹已不存在的项目。",
"{imported} new, {groups} new project groups, {missing} skipped (folder missing)": "新增 {imported} 个,新增 {groups} 个项目分组,跳过 {missing} 个(文件夹已不存在)",
"Plugin navigation covers {count} of {total} files in {project}; exclude folders to narrow it": "插件导航仅覆盖 {project} 中 {total} 个文件里的 {count} 个;可排除文件夹以缩小范围"
}
+1
Переглянути файл
@@ -465,6 +465,7 @@
"menu.file.exportSettings": "导出设置…",
"menu.file.importSettings": "导入设置…",
"menu.file.importJetBrainsSettings": "从 JetBrains IDE 导入设置…",
"menu.file.importJetBrainsRecentProjects": "从 JetBrains IDE 导入最近项目…",
"menu.file.syncSettings": "立即同步设置",
"menu.file.togglePowerSave": "省电模式",
"menu.macros": "宏",