mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-17 16:09:36 +00:00
feat: move configuration, user data and logs with environment variables (#3035)
OPENIDEA_CONFIG_DIR, OPENIDEA_DATA_DIR and OPENIDEA_LOG_DIR take an absolute path, like OPENIDEA_LOCAL_DATA_DIR, and the IDE uses <path>/<identifier> under it. Every place that resolved these directories now goes through ide_host::data_dirs (app state, invalidate caches, window zoom and window state, the MCP stdio bridge, logging, the openidea-plugin CLI), and the frontend takes the user data directory from app_info instead of Tauri's appDataDir. A relative path for the configuration or user data shows an error and exits. Closes #2814
This commit is contained in:
@@ -426,9 +426,9 @@ fn plugins_dir() -> Result<PathBuf, String> {
|
||||
if let Some(dir) = std::env::var_os("OPENIDEA_PLUGINS_DIR") {
|
||||
return Ok(PathBuf::from(dir));
|
||||
}
|
||||
dirs::data_dir()
|
||||
.map(|d| d.join("ai.l0ng.openidea").join("plugins"))
|
||||
.ok_or_else(|| "cannot find the app data directory; set OPENIDEA_PLUGINS_DIR".into())
|
||||
ide_host::data_dirs::data_dir("ai.l0ng.openidea")
|
||||
.map(|d| d.join("plugins"))
|
||||
.map_err(|error| format!("{error}; set OPENIDEA_PLUGINS_DIR"))
|
||||
}
|
||||
|
||||
#[derive(Default, serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -5,9 +5,52 @@ use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Moves the rebuildable local data (tools, language servers, indexes, caches);
|
||||
/// configuration and roaming data keep following the OS.
|
||||
/// Moves the rebuildable local data (tools, language servers, indexes, caches).
|
||||
pub const LOCAL_DATA_ENV: &str = "OPENIDEA_LOCAL_DATA_DIR";
|
||||
/// Moves the configuration (settings, recent projects, language definitions, window state).
|
||||
pub const CONFIG_ENV: &str = "OPENIDEA_CONFIG_DIR";
|
||||
/// Moves the user data (plugins, scratches, Local History, trusted projects).
|
||||
pub const DATA_ENV: &str = "OPENIDEA_DATA_DIR";
|
||||
/// Moves the logs.
|
||||
pub const LOG_ENV: &str = "OPENIDEA_LOG_DIR";
|
||||
|
||||
/// `$OPENIDEA_CONFIG_DIR/<identifier>` when set, else the OS configuration directory
|
||||
/// (Tauri's `app_config_dir`). Like the local data, the identifier keeps release and
|
||||
/// per-worktree debug builds apart under one root; a relative path is an error.
|
||||
pub fn config_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
resolve_env(CONFIG_ENV, std::env::var_os(CONFIG_ENV), dirs::config_dir(), identifier)
|
||||
}
|
||||
|
||||
/// `$OPENIDEA_DATA_DIR/<identifier>` when set, else the OS data directory (Tauri's `app_data_dir`).
|
||||
pub fn data_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
resolve_env(DATA_ENV, std::env::var_os(DATA_ENV), dirs::data_dir(), identifier)
|
||||
}
|
||||
|
||||
/// `$OPENIDEA_LOG_DIR/<identifier>` when set, else `~/Library/Logs/<identifier>` on macOS and
|
||||
/// `<local data>/<identifier>/logs` elsewhere (Tauri's `app_log_dir`).
|
||||
pub fn log_dir(identifier: &str) -> Result<PathBuf, String> {
|
||||
let os = if cfg!(target_os = "macos") {
|
||||
dirs::home_dir().map(|home| home.join("Library/Logs").join(identifier))
|
||||
} else {
|
||||
dirs::data_local_dir().map(|dir| dir.join(identifier).join("logs"))
|
||||
};
|
||||
match std::env::var_os(LOG_ENV).filter(|v| !v.is_empty()) {
|
||||
Some(var) => resolve_env(LOG_ENV, Some(var), None, identifier),
|
||||
None => os.ok_or_else(|| "cannot find the log directory".into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The directory under `$<env>` when set (absolute, not created here), else under the OS directory.
|
||||
fn resolve_env(env: &str, var: Option<OsString>, os: Option<PathBuf>, identifier: &str) -> Result<PathBuf, String> {
|
||||
let Some(root) = var.filter(|v| !v.is_empty()).map(PathBuf::from) else {
|
||||
return os.map(|dir| dir.join(identifier)).ok_or_else(|| format!("cannot find the directory {env} replaces"));
|
||||
};
|
||||
// The working directory depends on how the IDE was launched.
|
||||
if !root.is_absolute() {
|
||||
return Err(format!("{env} must be an absolute path: {}", root.display()));
|
||||
}
|
||||
Ok(root.join(identifier))
|
||||
}
|
||||
|
||||
/// A custom local-data root chosen in Settings › System Settings › Caches,
|
||||
/// stored in the configuration directory. The environment variable still wins.
|
||||
@@ -51,11 +94,11 @@ fn startup_resolve(
|
||||
/// The file holding the custom local-data root, if the platform exposes its
|
||||
/// configuration directory. Both startup and Settings use this one path.
|
||||
pub fn override_path(identifier: &str) -> Option<PathBuf> {
|
||||
dirs::config_dir().map(|dir| dir.join(identifier).join(OVERRIDE_FILE))
|
||||
config_dir(identifier).ok().map(|dir| dir.join(OVERRIDE_FILE))
|
||||
}
|
||||
|
||||
fn migration_path(identifier: &str) -> Option<PathBuf> {
|
||||
dirs::config_dir().map(|dir| dir.join(identifier).join(MIGRATION_FILE))
|
||||
config_dir(identifier).ok().map(|dir| dir.join(MIGRATION_FILE))
|
||||
}
|
||||
|
||||
/// The custom root stored by Settings, if any (validated when it is used).
|
||||
@@ -493,6 +536,25 @@ fn relative_wrapper(text: &str, source: &Path) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn config_data_and_log_dirs_follow_the_os_unless_their_variable_is_set() {
|
||||
let os = Some(PathBuf::from("/os"));
|
||||
for env in [CONFIG_ENV, DATA_ENV, LOG_ENV] {
|
||||
for var in [None, Some(OsString::new())] {
|
||||
assert_eq!(resolve_env(env, var, os.clone(), "id").unwrap(), PathBuf::from("/os/id"));
|
||||
}
|
||||
let root = std::env::temp_dir().join("openidea-moved");
|
||||
assert_eq!(resolve_env(env, Some(root.clone().into()), os.clone(), "id").unwrap(), root.join("id"));
|
||||
// Release and per-worktree debug builds stay apart under one root.
|
||||
assert_ne!(
|
||||
resolve_env(env, Some(root.clone().into()), None, "dev-a").unwrap(),
|
||||
resolve_env(env, Some(root.clone().into()), None, "dev-b").unwrap()
|
||||
);
|
||||
let error = resolve_env(env, Some("relative/dir".into()), os.clone(), "id").unwrap_err();
|
||||
assert!(error.contains(env) && error.contains("absolute"), "{error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_dir_follows_the_os_unless_the_variable_is_set() {
|
||||
let os = Some(PathBuf::from("/os-local"));
|
||||
|
||||
@@ -65,9 +65,23 @@ setx OPENIDEA_LOCAL_DATA_DIR "E:\OpenIDEA"
|
||||
On macOS and Linux, set it in the environment OpenIDEA starts from.
|
||||
|
||||
- If the path is relative or can't be written to, OpenIDEA shows an error and exits instead of falling back to the default location.
|
||||
- Configuration, user data and logs stay where they are. Logs are still written when the variable is wrong, so you can find out why.
|
||||
- Configuration, user data and logs stay where they are unless you move them too (see below). Logs are still written when the variable is wrong, so you can find out why.
|
||||
- Existing data is not moved. Either let OpenIDEA download and rebuild it, or quit OpenIDEA and move only `tools/`, `language-server-runtimes/`, `index/`, `cache/`, `lsp/`, `notebook-runtime/`, `server/`, `logs/`, `agents/tools/`, `agents/registry.json` and the top-level `java-usages-*.jar` / `java-usages-*.tmp` files, keeping their relative paths. Leave everything else in place.
|
||||
|
||||
## Move configuration, user data or logs
|
||||
|
||||
Each of the other directories has its own variable, set the same way as `OPENIDEA_LOCAL_DATA_DIR`: an absolute path, read when OpenIDEA starts. OpenIDEA then uses `<path>/ai.l0ng.openidea` and creates it if missing.
|
||||
|
||||
| Variable | Moves |
|
||||
| --------------------- | ------------- |
|
||||
| `OPENIDEA_CONFIG_DIR` | Configuration |
|
||||
| `OPENIDEA_DATA_DIR` | User data |
|
||||
| `OPENIDEA_LOG_DIR` | Logs |
|
||||
|
||||
- Set only the ones you want to move; the rest keep their default locations. Pointing several variables at the same path is fine.
|
||||
- If the configuration or user data path is relative or can't be used, OpenIDEA shows an error and exits instead of falling back to the default location. A wrong log path only turns off the log file.
|
||||
- Existing files are not moved. To keep your settings, plugins and history, quit OpenIDEA and copy the old folder's contents to the new location first.
|
||||
|
||||
## Logs
|
||||
|
||||
OpenIDEA writes one log file per day, `openidea.<date>.log`, and keeps the last 7. Panics are written to the current log too.
|
||||
|
||||
@@ -65,9 +65,23 @@ setx OPENIDEA_LOCAL_DATA_DIR "E:\OpenIDEA"
|
||||
在 macOS 和 Linux 上,需要在启动 OpenIDEA 的环境中设置这个变量。
|
||||
|
||||
- 如果路径是相对路径或不可写,OpenIDEA 会显示错误并退出,而不会退回默认位置。
|
||||
- 配置、用户数据和日志的位置不变。即使变量设置有误,日志仍会写入,方便排查原因。
|
||||
- 配置、用户数据和日志的位置不变,除非也移动它们(见下文)。即使变量设置有误,日志仍会写入,方便排查原因。
|
||||
- 已有数据不会自动迁移。可以让 OpenIDEA 重新下载和重建;也可以先退出 OpenIDEA,只移动 `tools/`、`language-server-runtimes/`、`index/`、`cache/`、`lsp/`、`notebook-runtime/`、`server/`、`logs/`、`agents/tools/`、`agents/registry.json` 以及顶层的 `java-usages-*.jar` / `java-usages-*.tmp` 文件,并保持相对路径不变。其他内容请留在原处。
|
||||
|
||||
## 移动配置、用户数据或日志
|
||||
|
||||
其他几个目录各有一个变量,设置方法和 `OPENIDEA_LOCAL_DATA_DIR` 相同:设为绝对路径,OpenIDEA 启动时读取。IDE 随后会使用 `<路径>/ai.l0ng.openidea`,不存在时自动创建。
|
||||
|
||||
| 变量 | 移动的目录 |
|
||||
| --------------------- | ---------- |
|
||||
| `OPENIDEA_CONFIG_DIR` | 配置 |
|
||||
| `OPENIDEA_DATA_DIR` | 用户数据 |
|
||||
| `OPENIDEA_LOG_DIR` | 日志 |
|
||||
|
||||
- 只设置想移动的那几个,其余仍在默认位置。几个变量指向同一路径也可以。
|
||||
- 如果配置或用户数据的路径是相对路径或不可用,OpenIDEA 会显示错误并退出,而不会退回默认位置;日志路径有误只会不写日志文件。
|
||||
- 已有文件不会自动迁移。想保留设置、插件和历史记录,先退出 OpenIDEA,把原文件夹里的内容复制到新位置。
|
||||
|
||||
## 日志
|
||||
|
||||
OpenIDEA 每天写一个日志文件 `openidea.<日期>.log`,保留最近 7 个。程序崩溃(panic)的信息也会写入当前日志。
|
||||
|
||||
@@ -16,6 +16,8 @@ pub struct AppInfo {
|
||||
pub platform: String,
|
||||
pub windows_build_number: Option<u32>,
|
||||
pub config_dir: ide_core::IpcPath,
|
||||
/// User data (plugins, scratches, Local History); follows `OPENIDEA_DATA_DIR`.
|
||||
pub data_dir: ide_core::IpcPath,
|
||||
/// Linux on a Wayland display: GTK draws the frameless windows' shadow and resize edges.
|
||||
pub wayland: bool,
|
||||
}
|
||||
@@ -31,6 +33,7 @@ pub fn app_info(state: State<'_, AppState>) -> AppInfo {
|
||||
platform: std::env::consts::OS.into(),
|
||||
windows_build_number: ide_core::platform::windows_build_number(),
|
||||
config_dir: state.config_dir.clone().into(),
|
||||
data_dir: state.data_dir.clone().into(),
|
||||
#[cfg(target_os = "linux")]
|
||||
wayland: crate::linux_window_state::is_wayland(),
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
|
||||
@@ -7,13 +7,13 @@ use ide_host::data_dirs;
|
||||
use ide_workspace::caches::{self, InvalidateCachesOptions};
|
||||
use serde::Serialize;
|
||||
use std::path::PathBuf;
|
||||
use tauri::{AppHandle, Manager, State};
|
||||
use tauri::{AppHandle, State};
|
||||
|
||||
/// Schedules the invalidation for the next start (`None` cancels a pending one).
|
||||
#[tauri::command]
|
||||
#[specta::specta]
|
||||
pub fn caches_schedule_invalidation(app: AppHandle, options: Option<InvalidateCachesOptions>) -> IdeResult<()> {
|
||||
let data_dir = app.path().app_data_dir().map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
|
||||
let data_dir = ide_host::data_dirs::data_dir(&app.config().identifier).map_err(ide_core::IdeError::internal)?;
|
||||
match options {
|
||||
Some(o) => caches::schedule(&data_dir, &o),
|
||||
None => {
|
||||
|
||||
+15
-1
@@ -80,7 +80,7 @@ pub fn run() {
|
||||
#[cfg(debug_assertions)]
|
||||
let context = dev::configure(context);
|
||||
if let Some(project) = ide_mcp::stdio_request(&std::env::args().collect::<Vec<_>>()) {
|
||||
let app_data = dirs::data_dir().unwrap_or_default().join(&context.config().identifier);
|
||||
let app_data = ide_host::data_dirs::data_dir(&context.config().identifier).unwrap_or_default();
|
||||
std::process::exit(ide_mcp::stdio::run(&ide_mcp::discovery_path(&app_data), project));
|
||||
}
|
||||
// The `openidea` command: answer and exit, no UI.
|
||||
@@ -129,6 +129,13 @@ pub fn run() {
|
||||
.with_state_flags(window_state_flags())
|
||||
// One remembered geometry per kind of auxiliary window (all projects' settings windows share one).
|
||||
.map_label(windows::state_key);
|
||||
// The plugin stores its file in the OS configuration directory; an absolute name follows
|
||||
// `OPENIDEA_CONFIG_DIR` instead.
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let window_state = match ide_host::data_dirs::config_dir(&context.config().identifier) {
|
||||
Ok(dir) => window_state.with_filename(dir.join(tauri_plugin_window_state::DEFAULT_FILENAME).to_string_lossy()),
|
||||
Err(_) => window_state,
|
||||
};
|
||||
#[cfg(target_os = "macos")]
|
||||
let window_state = window_state.with_filter(windows::keeps_window_state);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
@@ -187,6 +194,13 @@ pub fn run() {
|
||||
})
|
||||
.setup(move |app| {
|
||||
builder.mount_events(app);
|
||||
// An unusable directory variable stops the start with a message, never a silent fallback.
|
||||
let identifier = app.config().identifier.clone();
|
||||
let local_data_dir = local_data_dir.and_then(|dir| {
|
||||
ide_host::data_dirs::config_dir(&identifier)?;
|
||||
ide_host::data_dirs::data_dir(&identifier)?;
|
||||
Ok(dir)
|
||||
});
|
||||
let local_data_dir = match local_data_dir {
|
||||
Ok(dir) => dir,
|
||||
Err(error) => {
|
||||
|
||||
@@ -419,7 +419,7 @@ mod runtime {
|
||||
|
||||
fn persist(app: &AppHandle) {
|
||||
let write = || -> Result<(), Box<dyn std::error::Error>> {
|
||||
let dir = app.path().app_config_dir()?;
|
||||
let dir = ide_host::data_dirs::config_dir(&app.config().identifier)?;
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let cache = app.state::<Mutex<Cache>>();
|
||||
let data = serde_json::to_vec_pretty(&cache.lock().saved)?;
|
||||
@@ -439,9 +439,7 @@ mod runtime {
|
||||
// Plugins are set up on the main thread once GTK is initialised, before any window exists.
|
||||
use gtk::gdk::prelude::DisplayExtManual;
|
||||
let _ = WAYLAND.set(gtk::gdk::Display::default().is_some_and(|d| d.backend().is_wayland()));
|
||||
let saved = app
|
||||
.path()
|
||||
.app_config_dir()
|
||||
let saved = ide_host::data_dirs::config_dir(&app.config().identifier)
|
||||
.ok()
|
||||
.and_then(|dir| std::fs::read(dir.join(FILE)).ok())
|
||||
.and_then(|data| serde_json::from_slice(&data).ok())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Logging: stdout (as before) plus a daily-rotated file in the app log dir
|
||||
//! (`~/Library/Logs/<identifier>` on macOS, `<local data>/<identifier>/logs`
|
||||
//! elsewhere — the same place as Tauri's `app_log_dir`).
|
||||
//! elsewhere — the same place as Tauri's `app_log_dir` — or under `OPENIDEA_LOG_DIR`).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::io::Write as _;
|
||||
@@ -20,11 +20,7 @@ static LOG_DIR: OnceLock<PathBuf> = OnceLock::new();
|
||||
static GUARD: OnceLock<WorkerGuard> = OnceLock::new();
|
||||
|
||||
pub fn log_dir_for(identifier: &str) -> Option<PathBuf> {
|
||||
if cfg!(target_os = "macos") {
|
||||
dirs::home_dir().map(|h| h.join("Library/Logs").join(identifier))
|
||||
} else {
|
||||
dirs::data_local_dir().map(|d| d.join(identifier).join("logs"))
|
||||
}
|
||||
ide_host::data_dirs::log_dir(identifier).map_err(|error| eprintln!("{error}")).ok()
|
||||
}
|
||||
|
||||
fn filter() -> EnvFilter {
|
||||
|
||||
@@ -5,7 +5,7 @@ use ide_workspace::RecentProjects;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
use tauri::{AppHandle, Manager};
|
||||
use tauri::AppHandle;
|
||||
|
||||
pub use ide_host::{Host, Project};
|
||||
|
||||
@@ -63,8 +63,9 @@ impl AppState {
|
||||
syntax.get_or_init(|| Arc::new(Syntax::new()));
|
||||
})?;
|
||||
}
|
||||
let config_dir = app.path().app_config_dir()?;
|
||||
let data_dir = app.path().app_data_dir()?;
|
||||
// `OPENIDEA_CONFIG_DIR` / `OPENIDEA_DATA_DIR` move these; an unusable value fails the start.
|
||||
let config_dir = ide_host::data_dirs::config_dir(&app.config().identifier)?;
|
||||
let data_dir = ide_host::data_dirs::data_dir(&app.config().identifier)?;
|
||||
std::fs::create_dir_all(&config_dir)?;
|
||||
std::fs::create_dir_all(&data_dir)?;
|
||||
if let Err(error) = std::fs::create_dir_all(&local_data_dir) {
|
||||
|
||||
@@ -96,7 +96,7 @@ fn work_area_of(window: &WebviewWindow, monitor: &Monitor) -> IdeResult<Frame> {
|
||||
}
|
||||
|
||||
fn frames_path(window: &WebviewWindow) -> Option<PathBuf> {
|
||||
window.app_handle().path().app_data_dir().ok().map(|dir| dir.join("window-zoom.json"))
|
||||
ide_host::data_dirs::data_dir(&window.app_handle().config().identifier).ok().map(|dir| dir.join("window-zoom.json"))
|
||||
}
|
||||
|
||||
fn load_frames(path: &Path) -> HashMap<String, Frame> {
|
||||
|
||||
@@ -2276,6 +2276,8 @@ export type AppInfo = {
|
||||
platform: string,
|
||||
windowsBuildNumber: number | null,
|
||||
configDir: IpcPath,
|
||||
/** User data (plugins, scratches, Local History); follows `OPENIDEA_DATA_DIR`. */
|
||||
dataDir: IpcPath,
|
||||
/** Linux on a Wayland display: GTK draws the frameless windows' shadow and resize edges. */
|
||||
wayland: boolean,
|
||||
};
|
||||
|
||||
@@ -2,16 +2,14 @@ import { EditorView } from "@codemirror/view";
|
||||
import { activeEditor, editorsFor, useEditorRegistry, type TextEditorHandle } from "@/editor/api";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { call, commands, emitLocalIdeEvent, IpcError } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
import { editorService } from "@/workbench/contributions";
|
||||
import { appendRequests } from "./spring/request";
|
||||
|
||||
export const GENERATED_REQUESTS = "generated-requests.http";
|
||||
|
||||
async function scratchFile(): Promise<{ path: string; created: boolean }> {
|
||||
const { appDataDir } = await import("@tauri-apps/api/path");
|
||||
// `appDataDir()` is native (`C:\…`): the editor is found by its `/` path.
|
||||
const dir = `${ipcPath(await appDataDir()).replace(/\/+$/, "")}/scratches`;
|
||||
const dir = `${await appDataDir()}/scratches`;
|
||||
const ignoreExisting = (e: unknown) => {
|
||||
if (!(e instanceof IpcError && e.kind === "alreadyExists")) throw e;
|
||||
};
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import { activeEditor, registerEditorContribution, registerLanguageMode } from "@/editor/api";
|
||||
import { executeAction, getAction, registerActions } from "@/platform/actions";
|
||||
import { call, commands, emitLocalIdeEvent, IpcError, isTauri } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
import { useProject } from "@/platform/project";
|
||||
import {
|
||||
editorService,
|
||||
@@ -106,9 +106,7 @@ function directoryArg(arg: unknown): string | null {
|
||||
/** New HTTP Request: `requests[_n].http` in `directory`, else a scratch, with an example request. */
|
||||
async function newRequest(directory?: string) {
|
||||
try {
|
||||
const { appDataDir } = await import("@tauri-apps/api/path");
|
||||
// `appDataDir()` is native (`C:\…`): the UI holds paths `/`-separated.
|
||||
const dir = directory ?? `${ipcPath(await appDataDir()).replace(/\/+$/, "")}/scratches`;
|
||||
const dir = directory ?? `${await appDataDir()}/scratches`;
|
||||
try {
|
||||
await call(commands.fsCreateDir(dir));
|
||||
} catch (e) {
|
||||
|
||||
@@ -4,9 +4,10 @@ import { provideEditorService, provideNotificationService } from "@/workbench/co
|
||||
import { springControllers } from "./endpoints";
|
||||
import { generateRequests } from "./editor";
|
||||
|
||||
// `appDataDir()` is a native path: `\`-separated on Windows.
|
||||
vi.mock("@tauri-apps/api/path", () => ({
|
||||
appDataDir: async () => String.raw`C:\Users\me\AppData\Roaming\ai.l0ng.openidea`,
|
||||
// The backend reports the user data directory `/`-separated on every OS.
|
||||
vi.mock("@/platform/platformInfo", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/platform/platformInfo")>()),
|
||||
appDataDir: async () => "C:/Users/me/AppData/Roaming/ai.l0ng.openidea",
|
||||
}));
|
||||
|
||||
// No backend here: the file commands answer like a project without Spring
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* `scratch[_n].<ext>` name and opens it as a normal document.
|
||||
*/
|
||||
import { IpcError, call, commands, emitLocalIdeEvent, isTauri } from "@/platform/ipc";
|
||||
import { ipcPath } from "@/platform/paths";
|
||||
import { appDataDir } from "@/platform/platformInfo";
|
||||
import { editorService, notifications } from "@/workbench/contributions";
|
||||
import { scratchContent, scratchFileName, scratchLanguages, type ScratchLanguage } from "./model";
|
||||
|
||||
@@ -19,11 +19,7 @@ export interface ScratchBackend {
|
||||
}
|
||||
|
||||
export const tauriScratchBackend: ScratchBackend = {
|
||||
// `appDataDir()` is native (`C:\…`); the scratch paths are used as UI paths.
|
||||
dataDir: async () => {
|
||||
const { appDataDir } = await import("@tauri-apps/api/path");
|
||||
return ipcPath(await appDataDir());
|
||||
},
|
||||
dataDir: appDataDir,
|
||||
listNames: async (dir) => (await call(commands.fsReadDir(dir))).map((e) => e.name),
|
||||
createDir: async (dir) => void (await call(commands.fsCreateDir(dir))),
|
||||
createFile: async (path, text) =>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { loadPlatformInfo, usePlatform } from "./platformInfo";
|
||||
import { appDataDir, loadPlatformInfo, usePlatform } from "./platformInfo";
|
||||
|
||||
const appInfo = vi.hoisted(() => vi.fn());
|
||||
vi.mock("@/platform/ipc", () => ({ isTauri: () => true, commands: { appInfo } }));
|
||||
@@ -23,3 +23,8 @@ it("keeps platform defaults when the query fails", async () => {
|
||||
await loadPlatformInfo();
|
||||
expect(usePlatform.getState()).toEqual(initialPlatform);
|
||||
});
|
||||
|
||||
it("takes the user data directory from the backend, which may have moved it", async () => {
|
||||
appInfo.mockResolvedValue({ platform: "windows", dataDir: "E:/OpenIDEA/ai.l0ng.openidea/" });
|
||||
expect(await appDataDir()).toBe("E:/OpenIDEA/ai.l0ng.openidea");
|
||||
});
|
||||
|
||||
@@ -36,6 +36,14 @@ export const usePlatform = create<PlatformInfo>(() => {
|
||||
};
|
||||
});
|
||||
|
||||
let dataDir: Promise<string> | undefined;
|
||||
|
||||
/** The user data directory (scratches, plugins, Local History), which `OPENIDEA_DATA_DIR` can move. */
|
||||
export function appDataDir(): Promise<string> {
|
||||
dataDir ??= commands.appInfo().then((info) => info.dataDir.replace(/\/+$/, ""));
|
||||
return dataDir;
|
||||
}
|
||||
|
||||
export async function loadPlatformInfo() {
|
||||
if (!isTauri()) return;
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user