дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 13:32:29 +02:00
Порівняти коміти
67
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
a60826ce52 | ||
|
|
b02f212d3e | ||
|
|
ca7f26f484 | ||
|
|
bf4fff8fcf | ||
|
|
3cbe327a6a | ||
|
|
0311297886 | ||
|
|
a711c991b6 | ||
|
|
698cad2b3f | ||
|
|
581c64f544 | ||
|
|
77d6d81f8a | ||
|
|
ea62941bc6 | ||
|
|
00e044b66b | ||
|
|
1db368d2b4 | ||
|
|
db50b5df5b | ||
|
|
17fe162f6c | ||
|
|
0fc462350b | ||
|
|
ff80b4351a | ||
|
|
af2be518ec | ||
|
|
9f60e9b209 | ||
|
|
1838919f47 | ||
|
|
256d77c3f6 | ||
|
|
7ec2b18b63 | ||
|
|
f8ec222a0d | ||
|
|
aad0573fb9 | ||
|
|
8ea0052a7f | ||
|
|
b20e0b0902 | ||
|
|
e3fca1bb6f | ||
|
|
bfea07a30e | ||
|
|
4d5648c38d | ||
|
|
fbcbfb648c | ||
|
|
bf2478934e | ||
|
|
8f252398fe | ||
|
|
54c7cbc3b0 | ||
|
|
1fd9246ccc | ||
|
|
7b6ac0d5a8 | ||
|
|
d764f9cae1 | ||
|
|
3908b70b61 | ||
|
|
c1f0a85718 | ||
|
|
acdd88f0f7 | ||
|
|
1f8c869293 | ||
|
|
f3928b3553 | ||
|
|
5161d266ab | ||
|
|
b30b30311f | ||
|
|
c9c6d87a14 | ||
|
|
97ffd9aae9 | ||
|
|
5e39650886 | ||
|
|
444c315d57 | ||
|
|
a4bea25ae3 | ||
|
|
84b1770da4 | ||
|
|
88295ecca8 | ||
|
|
e87aee5969 | ||
|
|
84d8be1181 | ||
|
|
27cbdb1ba6 | ||
|
|
1005dc1363 | ||
|
|
3f3cdeba0d | ||
|
|
9b8c88e1ee | ||
|
|
392574fe2a | ||
|
|
41829e74db | ||
|
|
aee21233fb | ||
|
|
17f5889037 | ||
|
|
ff6c6eb13f | ||
|
|
ac015847a3 | ||
|
|
4c774d2e8e | ||
|
|
8adbbd1b05 | ||
|
|
c207e57686 | ||
|
|
ac0a56d1ec | ||
|
|
07cbb560df |
No files matched your search
@@ -28,6 +28,8 @@ on:
|
||||
- "src/workbench/**"
|
||||
- "src/ui/**"
|
||||
- "src/editor/api.ts"
|
||||
- "src/editor/navigationProviders.ts"
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
@@ -98,7 +100,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-http|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|relatedProviders|core/cm/(cornerInset|iconArea)|lsp/(availability|diagnostics|files|hint|lsp|positions))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
@@ -79,6 +79,7 @@ Shared agent skills live in `.agents/skills/` (`.claude/skills/` links to them):
|
||||
`pnpm dev:app` also enables the global Tauri API. `pnpm dev:status` reports
|
||||
this worktree's running MCP bridges and actual ports.
|
||||
- `pnpm build` — typecheck + bundle frontend.
|
||||
- `pnpm dogfood:build` / `pnpm dogfood:install` (or `mise run dogfood:build` / `mise run dogfood:install`) — build and locally install the grey-icon dogfood desktop app sharing release settings and data.
|
||||
- `cargo nextest run --workspace` (or `cargo test`), `cargo clippy --workspace --all-targets -- -D warnings`, `cargo fmt --all`.
|
||||
- `cargo test -p ide-host --test language_smoke -- --ignored --exact <language>` — code intelligence
|
||||
on `fixtures/` with that language's real server installed (CI: `Language smoke`, pinned versions).
|
||||
|
||||
@@ -138,11 +138,19 @@ pub type McpExecutableFn = dyn Fn() -> Option<PathBuf> + Send + Sync;
|
||||
/// The `[agents.skills.<name>]` policies a session resolves against: the user's (global
|
||||
/// `settings.toml`), the workspace's (`.openidea/settings.toml`), and whether the workspace
|
||||
/// is trusted (an untrusted one can only turn skills off).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SkillsPolicy {
|
||||
pub user: BTreeMap<String, AgentSkillPolicy>,
|
||||
pub workspace: BTreeMap<String, AgentSkillPolicy>,
|
||||
pub workspace_trusted: bool,
|
||||
/// All workspace folders (the project root plus any multi-repo workspace members).
|
||||
pub workspace_roots: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for SkillsPolicy {
|
||||
fn default() -> Self {
|
||||
Self { user: BTreeMap::new(), workspace: BTreeMap::new(), workspace_trusted: true, workspace_roots: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the skill policies for this project.
|
||||
@@ -784,20 +792,22 @@ impl AgentManager {
|
||||
}
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
if provider == "hermes" || provider.starts_with("hermes-") {
|
||||
let hermes_home = home.clone();
|
||||
let hermes_provider = provider.clone();
|
||||
let found = blocking(move || {
|
||||
let profile = hermes::root(home.as_deref()).and_then(|root| hermes::profile_home(&root, &provider));
|
||||
let profile =
|
||||
hermes::root(hermes_home.as_deref()).and_then(|root| hermes::profile_home(&root, &hermes_provider));
|
||||
Ok(profile.map(|p| skills::hermes(&p)).unwrap_or_default())
|
||||
})
|
||||
.await?;
|
||||
return Ok(skills::merge(offered, found));
|
||||
}
|
||||
if provider == "claude" || provider == "claude-acp" {
|
||||
offered = skills::merge(offered, found);
|
||||
} else if provider == "claude" || provider == "claude-acp" {
|
||||
let claude_cwd = cwd.clone();
|
||||
let found = blocking(move || Ok(skills::discover(&claude_cwd, home.as_deref()))).await?;
|
||||
offered = skills::merge(offered, found);
|
||||
}
|
||||
// The hub's active skills complete on every agent; its `off` ones drop out here,
|
||||
// which is all the enforcement an ACP agent gets.
|
||||
// The hub's active skills complete on every agent; its `off` ones drop out here
|
||||
// (including entries `offered` already held), which is all the enforcement an ACP agent gets.
|
||||
let holder = self.task_for_commands(&provider, task);
|
||||
let states = match holder {
|
||||
Some(holder) => holder.skill_states().await,
|
||||
@@ -807,10 +817,11 @@ impl AgentManager {
|
||||
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
(policy, shared.paths.project_root.clone())
|
||||
};
|
||||
let roots = if policy.workspace_roots.is_empty() { vec![root] } else { policy.workspace_roots };
|
||||
let home = self.shared.paths.home_dir.clone();
|
||||
blocking(move || {
|
||||
Ok(skills::resolve(
|
||||
skills::discover_skills(&root, home.as_deref()),
|
||||
skills::discover_skills_in(&roots, home.as_deref()),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
@@ -2114,15 +2125,24 @@ impl Task {
|
||||
/// The skills offered in this project: every discovery resolved against the policies
|
||||
/// and the task's overrides.
|
||||
async fn skill_states(&self) -> Vec<AgentSkillState> {
|
||||
let (policy, overrides, home, root) = {
|
||||
let (policy, overrides, home, roots) = {
|
||||
let shared = &self.shared;
|
||||
let policy = shared.skills_policy_hook.read().as_ref().map(|hook| hook()).unwrap_or_default();
|
||||
let overrides = self.state.lock().task.skill_overrides.clone();
|
||||
(policy, overrides, shared.paths.home_dir.clone(), shared.paths.project_root.clone())
|
||||
let (overrides, task_root) = {
|
||||
let s = self.state.lock();
|
||||
(s.task.skill_overrides.clone(), s.task.project_root.as_ref().map(|p| p.0.clone()))
|
||||
};
|
||||
let mut roots = Vec::new();
|
||||
if let Some(tr) = task_root {
|
||||
roots.push(tr);
|
||||
}
|
||||
roots.extend(policy.workspace_roots.iter().cloned());
|
||||
roots.push(shared.paths.project_root.clone());
|
||||
(policy, overrides, shared.paths.home_dir.clone(), roots)
|
||||
};
|
||||
blocking(move || {
|
||||
Ok(skills::resolve(
|
||||
skills::discover_skills(&root, home.as_deref()),
|
||||
skills::discover_skills_in(&roots, home.as_deref()),
|
||||
Some(&overrides),
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
|
||||
@@ -931,9 +931,21 @@ pub struct AgentSkill {
|
||||
/// The frontmatter `name`, else the folder's name.
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
/// Optional `argument-hint` from frontmatter, completed in the `/` menu.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub hint: Option<String>,
|
||||
/// Canonical folder holding `SKILL.md` (symlinks resolved, so duplicates collapse).
|
||||
pub path: IpcPath,
|
||||
pub source: AgentSkillSource,
|
||||
/// Other skill roots whose symlinked entry resolved to this same canonical `path`.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub also_in: Vec<AgentSkillSource>,
|
||||
/// False when frontmatter sets `user-invocable: false` (omitted from `/` completion).
|
||||
#[serde(default = "default_true")]
|
||||
pub user_invocable: bool,
|
||||
/// True when frontmatter sets `disable-model-invocation: true` (defaults to `slashOnly`).
|
||||
#[serde(default)]
|
||||
pub disable_model_invocation: bool,
|
||||
/// The `SKILL.md` passes validation (`name` matches its folder, `description` present).
|
||||
pub valid: bool,
|
||||
/// What validation found (`name` mismatch, missing or over-long description…).
|
||||
|
||||
@@ -240,31 +240,54 @@ const HOME_ROOTS: &[(&str, AgentSkillSource)] = &[
|
||||
/// duplicates collapsed by canonical path: the first of a path wins, and so does the first
|
||||
/// of a name (the higher source), so a session never sees one skill twice.
|
||||
pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill> {
|
||||
discover_skills_in(&[workspace.to_path_buf()], home)
|
||||
}
|
||||
|
||||
/// Every skill found across `workspaces` (a project and any workspace/monorepo member
|
||||
/// folders) and `home`, in source precedence order, symlinked duplicates collapsed by
|
||||
/// canonical path while recording secondary sources in [`AgentSkill::also_in`].
|
||||
pub fn discover_skills_in(workspaces: &[PathBuf], home: Option<&Path>) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let mut seen_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut seen_names: HashSet<String> = HashSet::new();
|
||||
let mut roots: Vec<(PathBuf, AgentSkillSource)> = Vec::new();
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (workspace.join(rel), *source)));
|
||||
let mut plugin_roots = Vec::new();
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
// `copilot install` unpacks plugins under `installed-plugins/<plugin>/`, whose skills
|
||||
// sit in a `skills` folder (or directly in the plugin folder).
|
||||
let plugins = home.join(".copilot/installed-plugins");
|
||||
if let Ok(plugins) = plugins.read_dir() {
|
||||
for plugin in plugins.flatten() {
|
||||
if plugin.path().is_dir() {
|
||||
plugin_roots.push((plugin.path().join("skills"), AgentSkillSource::CopilotUser));
|
||||
plugin_roots.push((plugin.path(), AgentSkillSource::CopilotUser));
|
||||
}
|
||||
let mut seen_workspaces: HashSet<PathBuf> = HashSet::new();
|
||||
let mut all_workspaces: Vec<PathBuf> = Vec::new();
|
||||
for ws in workspaces {
|
||||
let canon = dunce::canonicalize(ws).unwrap_or_else(|_| ws.clone());
|
||||
if seen_workspaces.insert(canon) {
|
||||
all_workspaces.push(ws.clone());
|
||||
}
|
||||
}
|
||||
for ws in &all_workspaces {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (ws.join(rel), *source)));
|
||||
}
|
||||
// Nested monorepo packages (up to two levels below each workspace root, e.g. `apps/web`).
|
||||
for ws in &all_workspaces {
|
||||
for sub in monorepo_subdirs(ws, 2) {
|
||||
let sub_canon = dunce::canonicalize(&sub).unwrap_or_else(|_| sub.clone());
|
||||
if seen_workspaces.insert(sub_canon) {
|
||||
roots.extend(WORKSPACE_ROOTS.iter().map(|(rel, source)| (sub.join(rel), *source)));
|
||||
}
|
||||
}
|
||||
}
|
||||
roots.extend(plugin_roots);
|
||||
if let Some(home) = home {
|
||||
roots.extend(HOME_ROOTS.iter().map(|(rel, source)| (home.join(rel), *source)));
|
||||
roots.extend(copilot_installed_plugin_roots(&home.join(".copilot")));
|
||||
}
|
||||
for (root, source) in roots {
|
||||
for skill in skills_of(&root, source) {
|
||||
let path = dunce::canonicalize(&skill.path.0).unwrap_or_else(|_| skill.path.0.clone());
|
||||
if !seen_paths.insert(path.clone()) || !seen_names.insert(skill.name.clone()) {
|
||||
if !seen_paths.insert(path.clone()) {
|
||||
if let Some(existing) = out.iter_mut().find(|s| s.path.0 == path)
|
||||
&& existing.source != source
|
||||
&& !existing.also_in.contains(&source)
|
||||
{
|
||||
existing.also_in.push(source);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if !seen_names.insert(skill.name.to_ascii_lowercase()) {
|
||||
continue;
|
||||
}
|
||||
out.push(AgentSkill { path: path.into(), ..skill });
|
||||
@@ -273,53 +296,204 @@ pub fn discover_skills(workspace: &Path, home: Option<&Path>) -> Vec<AgentSkill>
|
||||
out
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(root) else { return out };
|
||||
for entry in entries.flatten() {
|
||||
let dir = entry.path();
|
||||
let Some(folder) = dir.file_name().and_then(|n| n.to_str()).map(str::to_owned) else { continue };
|
||||
if !dir.is_dir() || folder.starts_with('.') {
|
||||
const SKIP_MONOREPO_DIRS: &[&str] =
|
||||
&["node_modules", "target", "dist", "build", "out", "vendor", "coverage", ".git", ".openidea", ".idea"];
|
||||
|
||||
fn monorepo_subdirs(root: &Path, max_depth: usize) -> Vec<PathBuf> {
|
||||
if max_depth == 0 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
for dir in sorted(root) {
|
||||
let Some(name) = file_name(&dir) else { continue };
|
||||
if SKIP_MONOREPO_DIRS.contains(&name.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) else { continue };
|
||||
let meta = Frontmatter::parse(&text);
|
||||
let name = meta.get("name").filter(|n| !n.is_empty()).map(str::to_owned).unwrap_or_else(|| folder.clone());
|
||||
let mut warnings = Vec::new();
|
||||
if !valid_name(&name) {
|
||||
warnings.push(format!("`name: {name}` is not 1-64 lowercase letters, digits or hyphens"));
|
||||
let Ok(meta) = std::fs::symlink_metadata(&dir) else { continue };
|
||||
if !meta.file_type().is_dir() {
|
||||
continue;
|
||||
}
|
||||
if name != folder {
|
||||
warnings.push(format!("`name: {name}` does not match the folder `{folder}`"));
|
||||
if WORKSPACE_ROOTS.iter().any(|(rel, _)| dir.join(rel).is_dir()) {
|
||||
out.push(dir.clone());
|
||||
}
|
||||
let description = meta.get("description").unwrap_or_default();
|
||||
let description = strip_ansi(description).trim().to_owned();
|
||||
if description.is_empty() {
|
||||
warnings.push("no `description`: the model never sees when to use it".into());
|
||||
} else if description.chars().count() > MAX_SKILL_DESCRIPTION {
|
||||
warnings.push(format!("`description` is over {MAX_SKILL_DESCRIPTION} characters"));
|
||||
if max_depth > 1 {
|
||||
out.extend(monorepo_subdirs(&dir, max_depth - 1));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Discovers skill roots inside `~/.copilot/installed-plugins`, supporting both Copilot CLI's
|
||||
/// 2-level `<marketplace-or-_direct>/<plugin>` layout (and `config.json` `installedPlugins`
|
||||
/// enablement) and flat 1-level `<plugin>` folders.
|
||||
fn copilot_installed_plugin_roots(copilot_dir: &Path) -> Vec<(PathBuf, AgentSkillSource)> {
|
||||
let mut disabled_paths: HashSet<PathBuf> = HashSet::new();
|
||||
let mut plugin_dirs: Vec<PathBuf> = Vec::new();
|
||||
let mut seen_dirs: HashSet<PathBuf> = HashSet::new();
|
||||
let mut push_plugin = |dir: PathBuf, disabled: &HashSet<PathBuf>| {
|
||||
if !dir.is_dir() {
|
||||
return;
|
||||
}
|
||||
let canon = dunce::canonicalize(&dir).unwrap_or_else(|_| dir.clone());
|
||||
if disabled.contains(&canon) || !seen_dirs.insert(canon) {
|
||||
return;
|
||||
}
|
||||
plugin_dirs.push(dir);
|
||||
};
|
||||
|
||||
if let Ok(text) = std::fs::read_to_string(copilot_dir.join("config.json"))
|
||||
&& let Ok(root) = serde_json::from_str::<serde_json::Value>(&crate::mcp::strip_jsonc(&text))
|
||||
&& let Some(installed) = root.get("installedPlugins").and_then(serde_json::Value::as_array)
|
||||
{
|
||||
for entry in installed {
|
||||
let Some(raw_cache) = entry.get("cache_path").and_then(serde_json::Value::as_str).map(str::trim) else {
|
||||
continue;
|
||||
};
|
||||
if raw_cache.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let dir =
|
||||
if Path::new(raw_cache).is_relative() { copilot_dir.join(raw_cache) } else { PathBuf::from(raw_cache) };
|
||||
if entry.get("enabled").and_then(serde_json::Value::as_bool) == Some(false) {
|
||||
disabled_paths.insert(dunce::canonicalize(&dir).unwrap_or(dir));
|
||||
} else {
|
||||
push_plugin(dir, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let plugins_root = copilot_dir.join("installed-plugins");
|
||||
for entry in sorted(&plugins_root) {
|
||||
if !entry.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if looks_like_plugin_dir(&entry) {
|
||||
push_plugin(entry, &disabled_paths);
|
||||
} else {
|
||||
// 2-level `<marketplace>/<plugin>` or `_direct/<plugin>`.
|
||||
for sub in sorted(&entry) {
|
||||
if sub.is_dir() {
|
||||
push_plugin(sub, &disabled_paths);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut roots = Vec::new();
|
||||
for plugin in plugin_dirs {
|
||||
let skills_sub = plugin.join("skills");
|
||||
if skills_sub.is_dir() {
|
||||
roots.push((skills_sub, AgentSkillSource::CopilotUser));
|
||||
} else {
|
||||
roots.push((plugin, AgentSkillSource::CopilotUser));
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn looks_like_plugin_dir(dir: &Path) -> bool {
|
||||
dir.join("skills").is_dir()
|
||||
|| dir.join("plugin.json").is_file()
|
||||
|| dir.join(".plugin").is_dir()
|
||||
|| dir.join(".claude-plugin").is_dir()
|
||||
|| dir.join(".cursor-plugin").is_dir()
|
||||
|| dir.join("SKILL.md").is_file()
|
||||
}
|
||||
|
||||
/// The skills of one root: `<name>/SKILL.md` folders and `<category>/<name>/SKILL.md`
|
||||
/// category folders, validated.
|
||||
fn skills_of(root: &Path, source: AgentSkillSource) -> Vec<AgentSkill> {
|
||||
let mut out: Vec<AgentSkill> = Vec::new();
|
||||
// Warn when a user drops `SKILL.md` directly inside a `skills/` root instead of `<name>/SKILL.md`.
|
||||
if file_name(root).as_deref() == Some("skills")
|
||||
&& let Ok(text) = std::fs::read_to_string(root.join("SKILL.md"))
|
||||
{
|
||||
let mut misplaced = parse_skill_file(root, "skills", &text, source);
|
||||
misplaced.valid = false;
|
||||
misplaced
|
||||
.warnings
|
||||
.insert(0, "SKILL.md is directly inside `skills/`: move it into a `<name>/SKILL.md` subfolder".into());
|
||||
out.push(misplaced);
|
||||
}
|
||||
for dir in sorted(root) {
|
||||
let Some(folder) = file_name(&dir) else { continue };
|
||||
if !dir.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(text) = std::fs::read_to_string(dir.join("SKILL.md")) {
|
||||
out.push(parse_skill_file(&dir, &folder, &text, source));
|
||||
continue;
|
||||
}
|
||||
// Category folder (`<root>/<category>/<skill>/SKILL.md`): only entered when `<dir>` itself
|
||||
// has no `SKILL.md`, so a skill's own subdirectories remain resources rather than skills.
|
||||
for sub in sorted(&dir) {
|
||||
let Some(sub_folder) = file_name(&sub) else { continue };
|
||||
if !sub.is_dir() {
|
||||
continue;
|
||||
}
|
||||
if let Ok(text) = std::fs::read_to_string(sub.join("SKILL.md")) {
|
||||
out.push(parse_skill_file(&sub, &sub_folder, &text, source));
|
||||
}
|
||||
}
|
||||
out.push(AgentSkill {
|
||||
name,
|
||||
description: truncate(&description),
|
||||
path: dir.into(),
|
||||
source,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
});
|
||||
}
|
||||
out.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
out
|
||||
}
|
||||
|
||||
fn parse_skill_file(dir: &Path, folder: &str, text: &str, source: AgentSkillSource) -> AgentSkill {
|
||||
let meta = Frontmatter::parse(text);
|
||||
let name = meta
|
||||
.get("name")
|
||||
.map(|n| strip_ansi(n).trim().to_owned())
|
||||
.filter(|n| !n.is_empty())
|
||||
.unwrap_or_else(|| folder.to_owned());
|
||||
let mut warnings = Vec::new();
|
||||
if !valid_name(&name) {
|
||||
warnings.push(format!("`name: {name}` is not 1-64 lowercase letters, digits or hyphens"));
|
||||
}
|
||||
if name != folder {
|
||||
warnings.push(format!("`name: {name}` does not match the folder `{folder}`"));
|
||||
}
|
||||
let description = meta.get("description").unwrap_or_default();
|
||||
let description = strip_ansi(description).trim().to_owned();
|
||||
if description.is_empty() {
|
||||
warnings.push("no `description`: the model never sees when to use it".into());
|
||||
} else if description.chars().count() > MAX_SKILL_DESCRIPTION {
|
||||
warnings.push(format!("`description` is over {MAX_SKILL_DESCRIPTION} characters"));
|
||||
}
|
||||
let hint = meta.get("argument-hint").map(|h| strip_ansi(h).trim().to_owned()).filter(|h| !h.is_empty());
|
||||
let user_invocable = !meta.get("user-invocable").is_some_and(|v| v.eq_ignore_ascii_case("false"));
|
||||
let disable_model_invocation = meta.get("disable-model-invocation").is_some_and(|v| v.eq_ignore_ascii_case("true"));
|
||||
AgentSkill {
|
||||
name,
|
||||
description: truncate(&description),
|
||||
hint,
|
||||
path: dir.to_path_buf().into(),
|
||||
source,
|
||||
also_in: Vec::new(),
|
||||
user_invocable,
|
||||
disable_model_invocation,
|
||||
valid: warnings.is_empty(),
|
||||
warnings,
|
||||
}
|
||||
}
|
||||
|
||||
/// A skill's mode, as one policy layer of the settings has it.
|
||||
type Policies = BTreeMap<String, AgentSkillPolicy>;
|
||||
|
||||
fn lookup_mode(map: &BTreeMap<String, AgentSkillMode>, name: &str) -> Option<AgentSkillMode> {
|
||||
map.get(name).copied().or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| *v))
|
||||
}
|
||||
|
||||
fn lookup_policy<'a>(map: &'a Policies, name: &str) -> Option<&'a AgentSkillPolicy> {
|
||||
map.get(name).or_else(|| map.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v))
|
||||
}
|
||||
|
||||
/// Resolves every skill's mode: a session override, then the workspace's and the user's
|
||||
/// `[agents.skills.<name>]` policy, then the default `auto` — with an untrusted workspace
|
||||
/// able to turn skills off only: its own skills stay off (whatever the session chose), and
|
||||
/// its policies hold only when they turn a skill off.
|
||||
/// `[agents.skills.<name>]` policy, then the frontmatter default (`slashOnly` when
|
||||
/// `disable-model-invocation: true`, else `auto`) — with an untrusted workspace able to
|
||||
/// turn skills off only: its own skills stay off (whatever the session chose), and its
|
||||
/// policies hold only when they turn a skill off.
|
||||
pub fn resolve(
|
||||
skills: Vec<AgentSkill>,
|
||||
session: Option<&BTreeMap<String, AgentSkillMode>>,
|
||||
@@ -337,19 +511,21 @@ pub fn resolve(
|
||||
| AgentSkillSource::CodexWorkspace
|
||||
| AgentSkillSource::CursorWorkspace
|
||||
);
|
||||
let default_mode =
|
||||
if skill.disable_model_invocation { AgentSkillMode::SlashOnly } else { AgentSkillMode::Auto };
|
||||
let (mode, origin) = if workspace_skill && !workspace_trusted {
|
||||
// Workspace trust gates the workspace's own skills, whatever else says.
|
||||
(AgentSkillMode::Off, AgentSkillOrigin::Trust)
|
||||
} else if let Some(chosen) = session.and_then(|s| s.get(&skill.name)) {
|
||||
(*chosen, AgentSkillOrigin::Session)
|
||||
} else if let Some(chosen) = session.and_then(|s| lookup_mode(s, &skill.name)) {
|
||||
(chosen, AgentSkillOrigin::Session)
|
||||
} else if let Some(policy) =
|
||||
workspace.get(&skill.name).filter(|p| workspace_trusted || p.mode == AgentSkillMode::Off)
|
||||
lookup_policy(workspace, &skill.name).filter(|p| workspace_trusted || p.mode == AgentSkillMode::Off)
|
||||
{
|
||||
(policy.mode, AgentSkillOrigin::Workspace)
|
||||
} else if let Some(policy) = user.get(&skill.name) {
|
||||
} else if let Some(policy) = lookup_policy(user, &skill.name) {
|
||||
(policy.mode, AgentSkillOrigin::User)
|
||||
} else {
|
||||
(AgentSkillMode::Auto, AgentSkillOrigin::None)
|
||||
(default_mode, AgentSkillOrigin::None)
|
||||
};
|
||||
out.push(AgentSkillState { skill, mode, origin });
|
||||
}
|
||||
@@ -416,16 +592,24 @@ pub fn stage(
|
||||
for state in states {
|
||||
let name = state.skill.name.as_str();
|
||||
let path = state.skill.path.0.as_path();
|
||||
if file_name(path).as_deref() == Some("skills") && !state.skill.valid {
|
||||
continue;
|
||||
}
|
||||
match state.mode {
|
||||
AgentSkillMode::Off => {
|
||||
out.codex_off.push((name.to_owned(), state.skill.path.to_string_lossy().into_owned()));
|
||||
out.codex_off.push((name.to_owned(), codex_skill_md_path(path)));
|
||||
}
|
||||
// Claude Code runs a slash-only skill on `/name`, so it has to see the folder;
|
||||
// Copilot and Codex have no such mode and get it disabled or left out.
|
||||
// Copilot and Codex have no slash-only toggle and disable model auto-loading.
|
||||
AgentSkillMode::SlashOnly => {
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
if state.skill.user_invocable
|
||||
&& let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home))
|
||||
{
|
||||
link_skill(&tree.join(name), path)?;
|
||||
}
|
||||
if native_codex(&state.skill, &cwd, home) {
|
||||
out.codex_off.push((name.to_owned(), codex_skill_md_path(path)));
|
||||
}
|
||||
}
|
||||
AgentSkillMode::Auto => {
|
||||
if let Some(tree) = claude_tree.as_ref().filter(|_| !native_claude(&state.skill, &cwd, home)) {
|
||||
@@ -451,10 +635,16 @@ pub fn stage(
|
||||
}
|
||||
// Claude Code's `skillOverrides` and Copilot's `disabledSkills` take the names of the
|
||||
// off and slash-only skills — the native copies included.
|
||||
let off: Vec<&str> =
|
||||
states.iter().filter(|s| s.mode == AgentSkillMode::Off).map(|s| s.skill.name.as_str()).collect();
|
||||
let slash: Vec<&str> =
|
||||
states.iter().filter(|s| s.mode == AgentSkillMode::SlashOnly).map(|s| s.skill.name.as_str()).collect();
|
||||
let off: Vec<&str> = states
|
||||
.iter()
|
||||
.filter(|s| s.mode == AgentSkillMode::Off || (s.mode == AgentSkillMode::SlashOnly && !s.skill.user_invocable))
|
||||
.map(|s| s.skill.name.as_str())
|
||||
.collect();
|
||||
let slash: Vec<&str> = states
|
||||
.iter()
|
||||
.filter(|s| s.mode == AgentSkillMode::SlashOnly && s.skill.user_invocable)
|
||||
.map(|s| s.skill.name.as_str())
|
||||
.collect();
|
||||
if !off.is_empty() || !slash.is_empty() {
|
||||
let mut overrides = serde_json::Map::new();
|
||||
for (name, mode) in off.iter().map(|n| (*n, "off")).chain(slash.iter().map(|n| (*n, "user-invocable-only"))) {
|
||||
@@ -469,32 +659,93 @@ pub fn stage(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Claude Code sees this skill without the farm: its own `.claude/skills` of the working
|
||||
/// directory (a worktree lacks the untracked originals) or the home.
|
||||
/// Codex `[[skills.config]]` matches `path` against the canonical `SKILL.md` document path.
|
||||
fn codex_skill_md_path(skill_dir: &Path) -> String {
|
||||
let md = skill_dir.join("SKILL.md");
|
||||
dunce::canonicalize(&md)
|
||||
.or_else(|_| dunce::canonicalize(skill_dir).map(|dir| dir.join("SKILL.md")))
|
||||
.unwrap_or(md)
|
||||
.to_string_lossy()
|
||||
.into_owned()
|
||||
}
|
||||
|
||||
fn direct_link_matches(root: &Path, name: &str, target: &Path) -> bool {
|
||||
let candidate = root.join(name);
|
||||
candidate == target || dunce::canonicalize(&candidate).ok().as_deref() == Some(target)
|
||||
}
|
||||
|
||||
/// Claude Code sees this skill without the farm when `<dir>/.claude/skills/<name>` in `cwd`
|
||||
/// (or `~/.claude/skills/<name>`) already resolves to `skill.path` — including when `.claude/skills/<name>`
|
||||
/// is a symlink to `.agents/skills/<name>`. Category-nested skills are not direct children, so
|
||||
/// they still get staged flat into the farm.
|
||||
fn native_claude(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
let target = skill.path.0.as_path();
|
||||
let home_canon = home.map(|h| dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf()));
|
||||
for ancestor in cwd.ancestors() {
|
||||
if home_canon.as_deref().is_some_and(|h| h == ancestor) {
|
||||
break;
|
||||
}
|
||||
if direct_link_matches(&ancestor.join(".claude/skills"), &skill.name, target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(h) = home_canon.as_deref()
|
||||
&& direct_link_matches(&h.join(".claude/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
match skill.source {
|
||||
AgentSkillSource::ClaudeWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::ClaudeUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".claude"))),
|
||||
AgentSkillSource::ClaudeWorkspace => target.parent() == Some(cwd.join(".claude/skills").as_path()),
|
||||
AgentSkillSource::ClaudeUser => {
|
||||
home_canon.as_deref().is_some_and(|h| target.parent() == Some(h.join(".claude/skills").as_path()))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Copilot reads the repository's `.github/skills` and the home's `.copilot` itself.
|
||||
/// Copilot natively scans `.github/skills`, `.agents/skills` and `.claude/skills` in `cwd`,
|
||||
/// plus `~/.copilot` and `~/.agents/skills` in `home`. `.openidea/skills` is NOT native.
|
||||
fn native_copilot(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
match skill.source {
|
||||
AgentSkillSource::GithubWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::CopilotUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".copilot"))),
|
||||
_ => false,
|
||||
let target = skill.path.0.as_path();
|
||||
for rel in [".github/skills", ".agents/skills", ".claude/skills"] {
|
||||
let root = cwd.join(rel);
|
||||
if is_under(target, &root) || direct_link_matches(&root, &skill.name, target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(h) = home {
|
||||
let h = dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf());
|
||||
if is_under(target, &h.join(".copilot"))
|
||||
|| is_under(target, &h.join(".agents/skills"))
|
||||
|| direct_link_matches(&h.join(".copilot/skills"), &skill.name, target)
|
||||
|| direct_link_matches(&h.join(".agents/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Codex reads its own folders itself.
|
||||
/// Codex natively scans `.codex/skills` and `.agents/skills` in `cwd` and `home`.
|
||||
fn native_codex(skill: &AgentSkill, cwd: &Path, home: Option<&Path>) -> bool {
|
||||
match skill.source {
|
||||
AgentSkillSource::CodexWorkspace => is_under(skill.path.0.as_path(), cwd),
|
||||
AgentSkillSource::CodexUser => home.is_some_and(|h| is_under(skill.path.0.as_path(), &h.join(".codex"))),
|
||||
_ => false,
|
||||
let target = skill.path.0.as_path();
|
||||
for rel in [".codex/skills", ".agents/skills"] {
|
||||
let root = cwd.join(rel);
|
||||
if is_under(target, &root) || direct_link_matches(&root, &skill.name, target) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if let Some(h) = home {
|
||||
let h = dunce::canonicalize(h).unwrap_or_else(|_| h.to_path_buf());
|
||||
if is_under(target, &h.join(".codex/skills"))
|
||||
|| is_under(target, &h.join(".agents/skills"))
|
||||
|| direct_link_matches(&h.join(".codex/skills"), &skill.name, target)
|
||||
|| direct_link_matches(&h.join(".agents/skills"), &skill.name, target)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn is_under(path: &Path, root: &Path) -> bool {
|
||||
@@ -553,21 +804,48 @@ fn sanitized(id: &str) -> String {
|
||||
id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-').collect()
|
||||
}
|
||||
|
||||
/// The `/` menu's skills: the active ones as commands (the agent's own listing wins on a
|
||||
/// name clash). `Off` ones drop out everywhere; an ACP agent gets no other enforcement, so
|
||||
/// `slashOnly` ones stay listed — there is nothing to hold them back with.
|
||||
fn bare_skill_name(name: &str) -> String {
|
||||
name.trim_start_matches('$').to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// The `/` menu's skills: active user-invocable skills as commands (the agent's own listing
|
||||
/// wins on a name clash, including Codex's `$name` spelling). `Off` and `user-invocable: false`
|
||||
/// skills are actively stripped from `offered` too, so previously cached or CLI-advertised
|
||||
/// entries cannot leak back into OpenIDEA's `/` completion.
|
||||
pub fn menu_commands(offered: Vec<AgentCommand>, states: &[AgentSkillState]) -> Vec<AgentCommand> {
|
||||
let extra = states
|
||||
let blocked: HashSet<String> = states
|
||||
.iter()
|
||||
.filter(|s| s.mode != AgentSkillMode::Off)
|
||||
.map(|s| AgentCommand {
|
||||
name: s.skill.name.clone(),
|
||||
description: s.skill.description.clone(),
|
||||
hint: None,
|
||||
source: AgentCommandSource::Skill,
|
||||
})
|
||||
.filter(|s| s.mode == AgentSkillMode::Off || !s.skill.user_invocable)
|
||||
.map(|s| bare_skill_name(&s.skill.name))
|
||||
.collect();
|
||||
merge(offered, extra)
|
||||
let mut out: Vec<AgentCommand> =
|
||||
offered.into_iter().filter(|c| !blocked.contains(&bare_skill_name(&c.name))).collect();
|
||||
for state in states {
|
||||
if state.mode == AgentSkillMode::Off
|
||||
|| !state.skill.user_invocable
|
||||
|| (file_name(&state.skill.path.0).as_deref() == Some("skills") && !state.skill.valid)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let target = bare_skill_name(&state.skill.name);
|
||||
if let Some(existing) = out.iter_mut().find(|c| bare_skill_name(&c.name) == target) {
|
||||
existing.source = AgentCommandSource::Skill;
|
||||
if existing.hint.is_none() {
|
||||
existing.hint = state.skill.hint.clone();
|
||||
}
|
||||
if existing.description.is_empty() {
|
||||
existing.description = state.skill.description.clone();
|
||||
}
|
||||
} else {
|
||||
out.push(AgentCommand {
|
||||
name: state.skill.name.clone(),
|
||||
description: state.skill.description.clone(),
|
||||
hint: state.skill.hint.clone(),
|
||||
source: AgentCommandSource::Skill,
|
||||
});
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -708,8 +986,12 @@ mod tests {
|
||||
AgentSkill {
|
||||
name: name.into(),
|
||||
description: format!("{name} does things"),
|
||||
hint: None,
|
||||
path: root.join(name).into(),
|
||||
source,
|
||||
also_in: Vec::new(),
|
||||
user_invocable: true,
|
||||
disable_model_invocation: false,
|
||||
valid: true,
|
||||
warnings: Vec::new(),
|
||||
}
|
||||
@@ -857,7 +1139,16 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
|
||||
// Local (non-worktree) session: the project's GitHub skills are Copilot's own.
|
||||
//For a local session, `.github/skills`, `.agents/skills` and `~/.agents/skills` are
|
||||
// already scanned natively by Copilot; `.openidea/skills` and `~/.codex/skills` are staged.
|
||||
let mut states = states;
|
||||
std::fs::create_dir_all(repo.join(".openidea/skills/ideonly")).unwrap();
|
||||
states.push(AgentSkillState {
|
||||
skill: skill("ideonly", AgentSkillSource::Workspace, &repo.join(".openidea/skills")),
|
||||
mode: AgentSkillMode::Auto,
|
||||
origin: AgentSkillOrigin::None,
|
||||
});
|
||||
|
||||
let farm = farm_dir(&root.join("store"), "task-1");
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(delivery.claude_add_dir.as_deref(), Some(farm.as_path()));
|
||||
@@ -865,7 +1156,7 @@ mod tests {
|
||||
let staged = listed(&claude_tree);
|
||||
assert_eq!(
|
||||
staged,
|
||||
["codexy", "gh", "lint", "muted", "tdd"],
|
||||
["codexy", "gh", "ideonly", "lint", "muted", "tdd"],
|
||||
"everything but the off one: none is native to Claude here, and slash-only needs the folder"
|
||||
);
|
||||
|
||||
@@ -873,18 +1164,31 @@ mod tests {
|
||||
assert_eq!(delivery.copilot_skill_directories, [farm.join("copilot").to_string_lossy().into_owned()]);
|
||||
assert_eq!(delivery.copilot_disabled_skills, ["muted", "off"]);
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert_eq!(copilot_staged, ["codexy", "lint", "tdd"], "`gh` is native to a local Copilot session");
|
||||
assert_eq!(
|
||||
copilot_staged,
|
||||
["codexy", "ideonly"],
|
||||
"`gh` (.github), `tdd` (.agents) and `lint` (~/.agents) are native to Copilot; `.openidea` & `~/.codex` are staged"
|
||||
);
|
||||
assert_eq!(
|
||||
delivery.codex_off,
|
||||
[("off".to_owned(), repo.join(".agents/skills").join("off").to_string_lossy().into_owned())]
|
||||
[
|
||||
(
|
||||
"muted".to_owned(),
|
||||
home.join(".agents").join("skills").join("muted").join("SKILL.md").to_string_lossy().into_owned(),
|
||||
),
|
||||
(
|
||||
"off".to_owned(),
|
||||
repo.join(".agents").join("skills").join("off").join("SKILL.md").to_string_lossy().into_owned(),
|
||||
),
|
||||
]
|
||||
);
|
||||
|
||||
// A worktree task: the repo's skills are untracked, so nothing is native any more.
|
||||
// A worktree task: the repo's skills are untracked, so workspace skills are staged now.
|
||||
let worktree = root.join("wt");
|
||||
std::fs::create_dir_all(&worktree).unwrap();
|
||||
let _ = stage(&farm, "copilot", &states, &worktree, Some(&home)).unwrap();
|
||||
let copilot_staged = listed(&farm.join("copilot"));
|
||||
assert!(copilot_staged.contains(&"gh".to_string()));
|
||||
assert!(copilot_staged.contains(&"gh".to_string()) && copilot_staged.contains(&"tdd".to_string()));
|
||||
|
||||
// Slash-only reaches Claude as `user-invocable-only`, off as `off`.
|
||||
let delivery = stage(&farm, "claude", &states, &repo, Some(&home)).unwrap();
|
||||
@@ -902,7 +1206,7 @@ mod tests {
|
||||
true,
|
||||
);
|
||||
stage(&farm, "claude", &restated, &repo, Some(&home)).unwrap();
|
||||
assert_eq!(listed(&claude_tree), ["codexy", "gh", "muted", "tdd"]);
|
||||
assert_eq!(listed(&claude_tree), ["codexy", "gh", "ideonly", "muted", "tdd"]);
|
||||
assert!(home.join(".agents/skills/lint").is_dir());
|
||||
assert!(farm.join("copilot").is_dir(), "restaging Claude's tree leaves Copilot's alone");
|
||||
|
||||
@@ -918,16 +1222,112 @@ mod tests {
|
||||
#[test]
|
||||
fn hub_menu_filters_off_and_keeps_the_agents_own() {
|
||||
let root = PathBuf::from("/r");
|
||||
let mut hidden = skill("bg-only", AgentSkillSource::Workspace, &root);
|
||||
hidden.user_invocable = false;
|
||||
let mut with_hint = skill("verify", AgentSkillSource::Workspace, &root);
|
||||
with_hint.hint = Some("[flow]".into());
|
||||
with_hint.path = tempfile::tempdir().unwrap().path().to_path_buf().into();
|
||||
write(&with_hint.path.0.join("SKILL.md"), "---\nname: verify\ndescription: v\n---\n");
|
||||
let states = resolve(
|
||||
vec![skill("tdd", AgentSkillSource::Workspace, &root), skill("lint", AgentSkillSource::User, &root)],
|
||||
vec![
|
||||
skill("tdd", AgentSkillSource::Workspace, &root),
|
||||
skill("lint", AgentSkillSource::User, &root),
|
||||
hidden,
|
||||
with_hint,
|
||||
],
|
||||
Some(&BTreeMap::from([("lint".to_owned(), AgentSkillMode::Off)])),
|
||||
&BTreeMap::new(),
|
||||
&BTreeMap::new(),
|
||||
true,
|
||||
);
|
||||
let menu = menu_commands(vec![cmd("tdd", "from the agent itself")], &states);
|
||||
assert_eq!(names(&menu), ["tdd"]);
|
||||
assert_eq!(menu[0].description, "from the agent itself");
|
||||
// Even when the agent itself (or cached `known_commands` / Codex `$lint`) already offered
|
||||
// `lint` or `bg-only`, `menu_commands` strips them, and merges `$tdd` without duplicating `tdd`.
|
||||
let offered = vec![
|
||||
cmd("$tdd", "from codex itself"),
|
||||
AgentCommand { source: AgentCommandSource::Skill, ..cmd("lint", "offered before turning off") },
|
||||
cmd("$lint", "codex offered before turning off"),
|
||||
AgentCommand { source: AgentCommandSource::Skill, ..cmd("bg-only", "model only") },
|
||||
cmd("compact", "Compact context"),
|
||||
];
|
||||
let menu = menu_commands(offered, &states);
|
||||
assert_eq!(names(&menu), ["$tdd", "compact", "verify"]);
|
||||
assert_eq!(menu[0].description, "from codex itself");
|
||||
assert_eq!(menu[0].source, AgentCommandSource::Skill);
|
||||
assert_eq!(menu[2].hint.as_deref(), Some("[flow]"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hub_discovers_copilot_two_level_plugins_categories_monorepos_and_frontmatter_flags() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let home = root.join("home");
|
||||
let ws_a = root.join("ws-a");
|
||||
let ws_b = root.join("ws-b");
|
||||
// Category subfolder in `.agents/skills/testing/coverage/SKILL.md`.
|
||||
write(
|
||||
&ws_a.join(".agents/skills/testing/coverage/SKILL.md"),
|
||||
"---\nname: coverage\ndescription: Coverage workflow\nargument-hint: \"[pkg]\"\ndisable-model-invocation: true\n---\n",
|
||||
);
|
||||
// Nested monorepo subpackage `apps/web/.agents/skills/web-e2e/SKILL.md`.
|
||||
write(
|
||||
&ws_a.join("apps/web/.agents/skills/web-e2e/SKILL.md"),
|
||||
"---\nname: web-e2e\ndescription: Web e2e\n---\n",
|
||||
);
|
||||
// Second workspace member root `ws-b`.
|
||||
write(&ws_b.join(".agents/skills/deploy/SKILL.md"), "---\nname: deploy\ndescription: Deploy\n---\n");
|
||||
// Misplaced top-level `SKILL.md` directly inside `.claude/skills/SKILL.md`.
|
||||
write(&ws_a.join(".claude/skills/SKILL.md"), "---\nname: misplaced\ndescription: Wrong level\n---\n");
|
||||
// Copilot 2-level marketplace & `_direct` plugins + disabled plugin in `config.json`.
|
||||
write(
|
||||
&home.join(".copilot/installed-plugins/awesome-copilot/db-tools/skills/pg-tune/SKILL.md"),
|
||||
"---\nname: pg-tune\ndescription: Tune Postgres\n---\n",
|
||||
);
|
||||
write(
|
||||
&home.join(".copilot/installed-plugins/_direct/muted-plug/skills/secret-op/SKILL.md"),
|
||||
"---\nname: secret-op\ndescription: Disabled plugin skill\n---\n",
|
||||
);
|
||||
write(
|
||||
&home.join(".copilot/config.json"),
|
||||
"// Managed by Copilot CLI\n{\"installedPlugins\":[{\"name\":\"muted-plug\",\"enabled\":false,\"cache_path\":\"installed-plugins/_direct/muted-plug\"}]}\n",
|
||||
);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::fs::create_dir_all(ws_a.join(".claude/skills")).unwrap();
|
||||
std::os::unix::fs::symlink(
|
||||
ws_a.join(".agents/skills/testing/coverage"),
|
||||
ws_a.join(".claude/skills/coverage"),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let found = discover_skills_in(&[ws_a.clone(), ws_b], Some(&home));
|
||||
let by = |n: &str| found.iter().find(|s| s.name == n);
|
||||
let cov = by("coverage").expect("category skill discovered");
|
||||
assert_eq!(cov.hint.as_deref(), Some("[pkg]"));
|
||||
assert!(cov.disable_model_invocation);
|
||||
#[cfg(unix)]
|
||||
assert_eq!(cov.also_in, [AgentSkillSource::ClaudeWorkspace]);
|
||||
assert!(by("web-e2e").is_some(), "nested monorepo subpackage skill discovered");
|
||||
assert!(by("deploy").is_some(), "second workspace member skill discovered");
|
||||
assert!(by("pg-tune").is_some(), "2-level Copilot marketplace plugin skill discovered");
|
||||
assert!(by("secret-op").is_none(), "disabled Copilot plugin skipped");
|
||||
let misplaced = by("misplaced").expect("misplaced top-level SKILL.md surfaced");
|
||||
assert!(!misplaced.valid && misplaced.warnings[0].contains("subfolder"));
|
||||
|
||||
// `disable-model-invocation: true` resolves to `SlashOnly` by default, and because
|
||||
// `.claude/skills/coverage` symlinks to it in `ws_a`, Claude does not stage a duplicate.
|
||||
let states = resolve(found, None, &BTreeMap::new(), &BTreeMap::new(), true);
|
||||
let cov_state = states.iter().find(|s| s.skill.name == "coverage").unwrap();
|
||||
assert_eq!(cov_state.mode, AgentSkillMode::SlashOnly);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let farm = farm_dir(&root.join("store"), "task-symlink");
|
||||
let _ = stage(&farm, "claude", &states, &ws_a, Some(&home)).unwrap();
|
||||
let claude_staged = listed(&farm.join(".claude/skills"));
|
||||
assert!(
|
||||
!claude_staged.contains(&"coverage".to_string()),
|
||||
"symlinked `.claude/skills/coverage` not duplicated"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -986,7 +986,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
wait_for(&mgr_a, &task.id, AgentStatus::NeedsInput).await;
|
||||
assert_eq!(names(mgr_a.commands("claude", None).await.unwrap()), ["review", "triage"]);
|
||||
assert_eq!(names(mgr_a.commands("claude", Some(&task.id)).await.unwrap()), ["review", "triage"]);
|
||||
// Other agents get only what they offered, plus verified native builtins.
|
||||
// Other agents also receive the project's active skills from the skills hub, plus verified native builtins.
|
||||
assert_eq!(
|
||||
names(mgr_a.commands("codex", None).await.unwrap()),
|
||||
[
|
||||
@@ -1001,6 +1001,7 @@ async fn commands_are_remembered_per_project_and_merged_with_skills_on_disk() {
|
||||
"goal",
|
||||
"rename",
|
||||
"logout",
|
||||
"triage",
|
||||
]
|
||||
);
|
||||
mgr_a.cancel(&task.id, None).unwrap();
|
||||
@@ -4443,6 +4444,83 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() {
|
||||
mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn per_session_skill_overrides_filter_commands_persist_and_reload_when_idle() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
std::fs::create_dir_all(root.join(".agents/skills/tdd")).unwrap();
|
||||
std::fs::write(root.join(".agents/skills/tdd/SKILL.md"), "---\nname: tdd\ndescription: TDD\n---\n").unwrap();
|
||||
std::fs::create_dir_all(root.join(".claude/skills/noisy")).unwrap();
|
||||
std::fs::write(root.join(".claude/skills/noisy/SKILL.md"), "---\nname: noisy\ndescription: Noisy\n---\n").unwrap();
|
||||
|
||||
let agent = Arc::new(FakeAgent::default());
|
||||
let mgr = manager(root, agent.clone());
|
||||
mgr.set_skills_policy_hook(Box::new({
|
||||
let root = root.to_path_buf();
|
||||
move || SkillsPolicy {
|
||||
user: BTreeMap::from([("tdd".into(), AgentSkillPolicy { mode: AgentSkillMode::Off })]),
|
||||
workspace: BTreeMap::new(),
|
||||
workspace_trusted: true,
|
||||
workspace_roots: vec![root.clone()],
|
||||
}
|
||||
}));
|
||||
|
||||
// Start task with `tdd` (default off) enabled for this session and `noisy` turned off.
|
||||
let task = mgr
|
||||
.create(NewAgentTask {
|
||||
project_root: None,
|
||||
prompt: text("again"),
|
||||
provider: "claude".into(),
|
||||
config: Vec::new(),
|
||||
isolation: Isolation::Local,
|
||||
base: None,
|
||||
mcp_overrides: BTreeMap::new(),
|
||||
idle: false,
|
||||
skill_overrides: BTreeMap::from([
|
||||
("tdd".into(), AgentSkillMode::Auto),
|
||||
("noisy".into(), AgentSkillMode::Off),
|
||||
]),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
|
||||
let cmd_names: Vec<String> =
|
||||
mgr.commands("claude", Some(&task.id)).await.unwrap().into_iter().map(|c| c.name).collect();
|
||||
assert!(cmd_names.contains(&"tdd".to_string()), "{cmd_names:?}");
|
||||
assert!(
|
||||
!cmd_names.contains(&"noisy".to_string()),
|
||||
"`noisy` offered on disk must be stripped when off: {cmd_names:?}"
|
||||
);
|
||||
|
||||
// Flip overrides while idle -> recycles resumable session so next turn calls `session/load`.
|
||||
let updated = mgr
|
||||
.set_skill_overrides(
|
||||
&task.id,
|
||||
BTreeMap::from([("tdd".into(), AgentSkillMode::Off), ("noisy".into(), AgentSkillMode::Auto)]),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(updated.skill_overrides.get("tdd"), Some(&AgentSkillMode::Off));
|
||||
assert_eq!(updated.skill_overrides.get("noisy"), Some(&AgentSkillMode::Auto));
|
||||
|
||||
let cmd_names_after: Vec<String> =
|
||||
mgr.commands("claude", Some(&task.id)).await.unwrap().into_iter().map(|c| c.name).collect();
|
||||
assert!(!cmd_names_after.contains(&"tdd".to_string()), "{cmd_names_after:?}");
|
||||
assert!(cmd_names_after.contains(&"noisy".to_string()), "{cmd_names_after:?}");
|
||||
|
||||
mgr.prompt(&task.id, text("again"), false).await.unwrap();
|
||||
wait_for(&mgr, &task.id, AgentStatus::Ready).await;
|
||||
assert_eq!(agent.mcp_calls.lock().last().map(|c| c.0.as_str()), Some("session/load"));
|
||||
mgr.shutdown();
|
||||
|
||||
// Persisted task file preserves `skill_overrides` across restart.
|
||||
let restored_mgr = manager(root, Arc::new(FakeAgent::default()));
|
||||
let restored = restored_mgr.subscribe(Arc::new(|_| {})).into_iter().find(|t| t.id == task.id).unwrap();
|
||||
assert_eq!(restored.skill_overrides.get("tdd"), Some(&AgentSkillMode::Off));
|
||||
assert_eq!(restored.skill_overrides.get("noisy"), Some(&AgentSkillMode::Auto));
|
||||
restored_mgr.shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn copilot_falls_back_to_acp_when_headless_probe_session_or_prompt_fails() {
|
||||
#[derive(Clone, Copy)]
|
||||
|
||||
@@ -72,6 +72,16 @@ impl WindowButtonLayout {
|
||||
let right = side(parts.next());
|
||||
(!left.is_empty() || !right.is_empty()).then_some(Self { left, right })
|
||||
}
|
||||
|
||||
/// The layout on Linux: the desktop's `gtk-decoration-layout` when a desktop session is running.
|
||||
/// Without one (WSLg, a bare compositor) GTK reports its built-in fallback, close only, which
|
||||
/// leaves no way to minimise or maximise the frameless window, so the default applies.
|
||||
pub fn for_linux(gtk_layout: Option<&str>, var: impl Fn(&str) -> Option<String>) -> Self {
|
||||
let desktop = ["XDG_CURRENT_DESKTOP", "XDG_SESSION_DESKTOP", "DESKTOP_SESSION"]
|
||||
.iter()
|
||||
.any(|key| var(key).is_some_and(|value| !value.trim().is_empty()));
|
||||
gtk_layout.filter(|_| desktop).and_then(Self::from_gtk_decoration_layout).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -118,6 +128,25 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linux_layout_needs_a_desktop_session() {
|
||||
let env = |vars: &'static [(&'static str, &'static str)]| {
|
||||
move |key: &str| vars.iter().find(|(k, _)| *k == key).map(|(_, v)| v.to_string())
|
||||
};
|
||||
let gnome = env(&[("XDG_CURRENT_DESKTOP", "ubuntu:GNOME")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(Some("appmenu:close"), gnome), layout(&[], &[Close]).unwrap());
|
||||
let kde = env(&[("DESKTOP_SESSION", "plasma")]);
|
||||
assert_eq!(
|
||||
WindowButtonLayout::for_linux(Some("close,maximize,minimize:icon"), kde),
|
||||
layout(&[Close, Maximize, Minimize], &[]).unwrap()
|
||||
);
|
||||
// WSLg: no desktop session, GTK's fallback layout.
|
||||
let wslg = env(&[("WAYLAND_DISPLAY", "wayland-0"), ("XDG_CURRENT_DESKTOP", " ")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(Some("menu:close"), wslg), WindowButtonLayout::default());
|
||||
let gnome = env(&[("XDG_SESSION_DESKTOP", "gnome")]);
|
||||
assert_eq!(WindowButtonLayout::for_linux(None, gnome), WindowButtonLayout::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_layout_is_on_the_right() {
|
||||
assert_eq!(WindowButtonLayout::default(), layout(&[], &[Minimize, Maximize, Close]).unwrap());
|
||||
|
||||
@@ -34,7 +34,7 @@ use std::path::{Component, Path, PathBuf};
|
||||
|
||||
pub const MANIFEST_FILE: &str = "plugin.toml";
|
||||
/// The plugin API (engine) version this host implements.
|
||||
pub const ENGINE_VERSION: &str = "1.14.0";
|
||||
pub const ENGINE_VERSION: &str = "1.15.0";
|
||||
/// The 0.1 API, still accepted for contribution-only packages and 0.1 components.
|
||||
pub const LEGACY_API: &str = "0.1";
|
||||
/// Marketplace categories, in the order they are shown.
|
||||
@@ -164,6 +164,7 @@ pub const EVENT_KINDS: &[&str] = &[
|
||||
"file-saved",
|
||||
"files-changed",
|
||||
"editor-focused",
|
||||
"caret-moved",
|
||||
"action-performed",
|
||||
"vcs-changed",
|
||||
"problems-changed",
|
||||
|
||||
@@ -345,7 +345,7 @@ impl Host {
|
||||
}
|
||||
if let Some(plugins) = plugins::editor_plugin_host() {
|
||||
plugins.invalidate_client_navigation(&project.root, Some(window), None);
|
||||
plugins.set_active_file(window, None);
|
||||
plugins.set_active_file(window, None, None);
|
||||
}
|
||||
if !project.light {
|
||||
self.environment.project_closed();
|
||||
|
||||
@@ -1045,11 +1045,10 @@ pub fn agent_set_skill_overrides(
|
||||
#[command(trust = always)]
|
||||
pub async fn agent_skills_list(host: &Host, window: &str) -> IdeResult<Vec<AgentSkillState>> {
|
||||
let project = host.project(window)?;
|
||||
let root = project.root.clone();
|
||||
let (policy, home) = (skills_policy(&project), dirs::home_dir());
|
||||
tokio::task::spawn_blocking(move || {
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills(&root, home.as_deref()),
|
||||
ide_agent::skills::discover_skills_in(&policy.workspace_roots, home.as_deref()),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
@@ -1103,11 +1102,10 @@ pub fn agent_skills_set_mode(
|
||||
}
|
||||
match project {
|
||||
Some(project) => {
|
||||
let root = project.root.clone();
|
||||
let policy = skills_policy(&project);
|
||||
let home = dirs::home_dir();
|
||||
Ok(ide_agent::skills::resolve(
|
||||
ide_agent::skills::discover_skills(&root, home.as_deref()),
|
||||
ide_agent::skills::discover_skills_in(&policy.workspace_roots, home.as_deref()),
|
||||
None,
|
||||
&policy.workspace,
|
||||
&policy.user,
|
||||
@@ -1162,12 +1160,26 @@ fn persist_skills_map(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Workspace folders to scan for skills: the project root plus any multi-repo workspace members.
|
||||
pub(crate) fn workspace_skill_roots(root: &std::path::Path) -> Vec<std::path::PathBuf> {
|
||||
let mut roots = vec![root.to_path_buf()];
|
||||
if let Ok(Some(ws)) = ide_workspace::workspace::Workspace::load(root) {
|
||||
for member in ws.projects {
|
||||
if member.exists() && !roots.contains(&member) {
|
||||
roots.push(member);
|
||||
}
|
||||
}
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
/// The skill policies a session of `project` resolves against.
|
||||
fn skills_policy(project: &crate::Project) -> SkillsPolicy {
|
||||
SkillsPolicy {
|
||||
user: project.settings.layer(ide_workspace::settings::SettingsScope::Global).agents.skills.clone(),
|
||||
workspace: project.settings.layer(ide_workspace::settings::SettingsScope::Project).agents.skills.clone(),
|
||||
workspace_trusted: project.trusted.load(std::sync::atomic::Ordering::Acquire),
|
||||
workspace_roots: workspace_skill_roots(&project.root),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1092,7 +1092,8 @@ pub async fn lsp_resolve_code_action(
|
||||
#[command(trust = trusted)]
|
||||
pub async fn lsp_apply_code_action(host: &Host, window: &str, doc: DocId, action: CodeAction) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
let action = if action.edit.is_none() && action.command.is_none() {
|
||||
// A lazy action may carry a follow-up command beside its unresolved edit (vtsls' refactorings).
|
||||
let action = if action.edit.is_none() && (action.command.is_none() || action.data.is_some()) {
|
||||
let documents = project.documents.clone();
|
||||
let version = blocking(move || documents.version(doc)).await?;
|
||||
let action = resolve_action(host, window, doc, action).await?;
|
||||
|
||||
@@ -110,10 +110,16 @@ pub fn plugin_answer_commit(plugins: &Arc<PluginHost>, request_id: String, answe
|
||||
plugins.answer_commit(&request_id, answer)
|
||||
}
|
||||
|
||||
/// The UI reports the focused editor's file (`editor-focused` events).
|
||||
/// The UI reports the focused editor's file (`editor-focused` events), with its
|
||||
/// caret so plugins can scope line labels without re-reading the document.
|
||||
#[command(trust = always)]
|
||||
pub fn plugin_set_active_file(plugins: &Arc<PluginHost>, window: &str, path: Option<String>) {
|
||||
plugins.set_active_file(window, path);
|
||||
pub fn plugin_set_active_file(
|
||||
plugins: &Arc<PluginHost>,
|
||||
window: &str,
|
||||
path: Option<String>,
|
||||
#[default] editor: Option<PluginEditor>,
|
||||
) {
|
||||
plugins.set_active_file(window, path, editor);
|
||||
}
|
||||
|
||||
/// The invoking window's reply to a plugin command request.
|
||||
|
||||
@@ -1729,8 +1729,9 @@ impl PluginHost {
|
||||
}
|
||||
|
||||
/// The UI reports which file its focused editor shows (`editor-focused`).
|
||||
pub fn set_active_file(&self, client: &str, path: Option<String>) {
|
||||
self.post_events(Some(client), vec![WorkbenchEvent::EditorFocused(path)]);
|
||||
/// The editor snapshot carries the caret so line-scoped features stay current.
|
||||
pub fn set_active_file(&self, client: &str, path: Option<String>, editor: Option<PluginEditor>) {
|
||||
self.post_window_events(client, vec![WorkbenchEvent::EditorFocused(path)], editor);
|
||||
}
|
||||
|
||||
/// Where plugin secrets are kept (default: files under the plugins
|
||||
|
||||
@@ -4,7 +4,8 @@ use super::theme::ThemeDef;
|
||||
use ide_extension::package::PluginIcon;
|
||||
use ide_extension::{CapabilityInfo, ContributionInfo, UiContribution};
|
||||
pub use ide_plugin::{
|
||||
ActionPerformed, ActionSource, EventKind, NotificationLevel, PickItem, Prompt, StatusItem, WorkbenchEvent,
|
||||
ActionPerformed, ActionSource, CaretMoved, EventKind, NotificationLevel, PickItem, Prompt, StatusItem,
|
||||
WorkbenchEvent,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
|
||||
@@ -770,7 +770,8 @@ impl Host {
|
||||
ide_agent::SkillsPolicy {
|
||||
user: layer(ide_workspace::settings::SettingsScope::Global),
|
||||
workspace: layer(ide_workspace::settings::SettingsScope::Project),
|
||||
workspace_trusted: trust.trusted(&skill_root).unwrap_or(false),
|
||||
workspace_trusted: trust.window_trusted(&skill_root).unwrap_or(false),
|
||||
workspace_roots: crate::ops::agent::workspace_skill_roots(&skill_root),
|
||||
}
|
||||
}));
|
||||
agents.set_mcp_servers_hook(Box::new(move || {
|
||||
|
||||
@@ -824,6 +824,11 @@ fn plugin_processes_end_with_their_owner() {
|
||||
String::from_utf8_lossy(&ps.stdout).lines().any(|line| line.contains(&marker))
|
||||
};
|
||||
f.run("misbehave", "childkeep", marker.strip_prefix("--path=")).unwrap();
|
||||
// fork+exec is not atomic: `ps` can still report the owner until the child execs.
|
||||
let started = Instant::now() + Duration::from_secs(5);
|
||||
while !alive() && Instant::now() < started {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
assert!(alive(), "{mode}: the process started");
|
||||
match mode {
|
||||
"disable" => f.host.set_enabled("misbehave", false).unwrap(),
|
||||
@@ -6466,6 +6471,7 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
|
||||
mode: "visual".into(),
|
||||
sub: Some("linewise".into()),
|
||||
}),
|
||||
E::CaretMoved(ide_plugin::CaretMoved { path: path.clone(), line: 4, col: 2, settled: true }),
|
||||
],
|
||||
Some(PluginEditor {
|
||||
path: path.clone(),
|
||||
@@ -6477,7 +6483,7 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
|
||||
assert!(f.host.wait_events(Duration::from_secs(5)));
|
||||
let received: serde_json::Value = serde_json::from_str(&f.run("api14", "events", None).unwrap().unwrap()).unwrap();
|
||||
let events = received.as_array().unwrap();
|
||||
assert_eq!(events.len(), 4, "{received}");
|
||||
assert_eq!(events.len(), 5, "{received}");
|
||||
// The first synthetic post hands over the current keys ("enabled": false);
|
||||
// the second is a real diff to true. Keys come from the recomputed
|
||||
// snapshot, never from the event payload ("another-plugin-key").
|
||||
@@ -6486,6 +6492,14 @@ fn api14_settings_and_input_events_use_other_and_capture_the_editor() {
|
||||
assert_eq!(events[1]["kind"], "settings-changed");
|
||||
assert_eq!(events[1]["data"], "[\"enabled\"]");
|
||||
assert_eq!(events[3]["kind"], "input-mode-changed");
|
||||
assert_eq!(events[4]["kind"], "caret-moved");
|
||||
let caret: serde_json::Value =
|
||||
serde_json::from_str(events[4]["data"].as_str().expect("caret data is JSON")).unwrap();
|
||||
assert_eq!(caret["path"], path.as_str());
|
||||
assert_eq!(caret["line"], 4);
|
||||
assert_eq!(caret["col"], 2);
|
||||
assert_eq!(caret["settled"], true);
|
||||
assert_eq!(events[4]["editor"][0], path.as_str());
|
||||
assert_eq!(events[2]["editor"][0], path);
|
||||
assert_eq!(events[2]["editor"][1][0], serde_json::json!([0, 0, 0, 0]));
|
||||
}
|
||||
|
||||
@@ -1081,6 +1081,53 @@ async fn cancelling_one_request_does_not_interrupt_another_running_command() {
|
||||
plugins.host().shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn remote_focus_preserves_the_editor_for_following_plugin_events() {
|
||||
let (tmp, plugins, peer, _client) = command_rpc_fixture().await;
|
||||
plugins.host().install_from_dir(&fixture("api14"), &Consent::all()).unwrap();
|
||||
let path = tmp.path().join("project/notes.txt").to_string_lossy().into_owned();
|
||||
let selection = json!({"start":{"line":4,"col":2},"end":{"line":4,"col":5}});
|
||||
invoke(
|
||||
&peer,
|
||||
"plugin_set_active_file",
|
||||
json!({"path":path,"editor":{"path":path,"language":"text","selections":[selection]}}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for focused in [true, false] {
|
||||
if !focused {
|
||||
invoke(&peer, "plugin_set_active_file", json!({"path":null,"editor":null})).await.unwrap();
|
||||
}
|
||||
plugins.host().post_events(
|
||||
Some("main"),
|
||||
vec![WorkbenchEvent::InputModeChanged(ide_plugin::InputMode {
|
||||
path: path.clone(),
|
||||
mode: "visual".into(),
|
||||
sub: None,
|
||||
})],
|
||||
);
|
||||
plugins.host().flush_events_at(std::time::Instant::now() + Duration::from_secs(2));
|
||||
assert!(plugins.host().wait_events(Duration::from_secs(5)));
|
||||
let received = invoke(
|
||||
&peer,
|
||||
"plugin_run_command",
|
||||
json!({"pluginId":"api14","commandId":"events","arg":null,"editor":null}),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let events: Value = serde_json::from_str(received.as_str().unwrap()).unwrap();
|
||||
let event = events.as_array().unwrap().iter().rev().find(|e| e["kind"] == "input-mode-changed").unwrap();
|
||||
if focused {
|
||||
assert_eq!(event["editor"], json!([path, [[4, 2, 4, 5]]]));
|
||||
} else {
|
||||
assert!(event["editor"].is_null(), "lost focus must clear the previous editor: {event}");
|
||||
}
|
||||
}
|
||||
// Older callers may omit the optional editor payload.
|
||||
invoke(&peer, "plugin_set_active_file", json!({"path":path})).await.unwrap();
|
||||
plugins.host().shutdown();
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn a_remote_command_reads_the_clipboard_of_the_desktop_window() {
|
||||
let (_tmp, plugins, peer, client) = command_rpc_fixture().await;
|
||||
|
||||
@@ -670,21 +670,34 @@ pub fn workspace_edit(conv: &Conv, e: lsp::WorkspaceEdit) -> WorkspaceEdit {
|
||||
for op in ops {
|
||||
match op {
|
||||
lsp::DocumentChangeOperation::Edit(e) => doc_edit(&mut files, e),
|
||||
// An operation its `ignoreIfExists` / `ignoreIfNotExists` makes a no-op is
|
||||
// left out (vtsls' extractions "create" the file they then edit).
|
||||
lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(c)) => {
|
||||
if let Some(path) = uri_path(&c.uri) {
|
||||
let overwrite = c.options.and_then(|o| o.overwrite).unwrap_or(false);
|
||||
files.push(FileEdit::Create { path: path.into(), overwrite });
|
||||
let overwrite = c.options.as_ref().and_then(|o| o.overwrite).unwrap_or(false);
|
||||
let ignore = c.options.and_then(|o| o.ignore_if_exists).unwrap_or(false);
|
||||
if !(ignore && !overwrite && path.exists()) {
|
||||
files.push(FileEdit::Create { path: path.into(), overwrite });
|
||||
}
|
||||
}
|
||||
}
|
||||
lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(r)) => {
|
||||
if let (Some(from), Some(to)) = (uri_path(&r.old_uri), uri_path(&r.new_uri)) {
|
||||
files.push(FileEdit::Rename { from: from.into(), to: to.into() });
|
||||
let o = r.options.as_ref();
|
||||
let overwrite = o.and_then(|o| o.overwrite).unwrap_or(false);
|
||||
let ignore = o.and_then(|o| o.ignore_if_exists).unwrap_or(false);
|
||||
if !(ignore && !overwrite && to.exists()) {
|
||||
files.push(FileEdit::Rename { from: from.into(), to: to.into() });
|
||||
}
|
||||
}
|
||||
}
|
||||
lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(d)) => {
|
||||
if let Some(path) = uri_path(&d.uri) {
|
||||
let recursive = d.options.and_then(|o| o.recursive).unwrap_or(false);
|
||||
files.push(FileEdit::Delete { path: path.into(), recursive });
|
||||
let recursive = d.options.as_ref().and_then(|o| o.recursive).unwrap_or(false);
|
||||
let ignore = d.options.and_then(|o| o.ignore_if_not_exists).unwrap_or(false);
|
||||
if !(ignore && !path.exists()) {
|
||||
files.push(FileEdit::Delete { path: path.into(), recursive });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1426,6 +1439,34 @@ mod tests {
|
||||
assert_eq!(out[1].name, "f");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_edit_leaves_out_operations_their_ignore_options_make_no_ops() {
|
||||
let conv = Conv::utf16();
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let existing = dir.path().join("e.ts");
|
||||
std::fs::write(&existing, "").unwrap();
|
||||
let missing = dir.path().join("m.ts");
|
||||
let uri = |p: &Path| crate::uri::path_to_uri_string(p);
|
||||
let e: lsp::WorkspaceEdit = serde_json::from_value(json!({
|
||||
"documentChanges": [
|
||||
{ "kind": "create", "uri": uri(&existing), "options": { "ignoreIfExists": true } },
|
||||
{ "kind": "create", "uri": uri(&missing), "options": { "ignoreIfExists": true } },
|
||||
{ "kind": "rename", "oldUri": uri(&missing), "newUri": uri(&existing), "options": { "ignoreIfExists": true } },
|
||||
{ "kind": "delete", "uri": uri(&dir.path().join("gone.ts")), "options": { "ignoreIfNotExists": true } },
|
||||
{ "kind": "delete", "uri": uri(&existing), "options": { "ignoreIfNotExists": true } }
|
||||
]
|
||||
}))
|
||||
.unwrap();
|
||||
let w = workspace_edit(&conv, e);
|
||||
assert_eq!(
|
||||
w.files,
|
||||
[
|
||||
FileEdit::Create { path: missing.into(), overwrite: false },
|
||||
FileEdit::Delete { path: existing.into(), recursive: false },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_edit_document_changes() {
|
||||
let conv = Conv::utf16();
|
||||
|
||||
@@ -58,7 +58,7 @@ use views_bindings::exports::openidea::plugin::view_provider as wit_view;
|
||||
use views_bindings::openidea::plugin::view_types as wit_vt;
|
||||
|
||||
/// The API version of the world above, `major.minor` of [`host_api`].
|
||||
pub const API_VERSION: &str = "1.14";
|
||||
pub const API_VERSION: &str = "1.15";
|
||||
const EPOCH_TICK: Duration = Duration::from_millis(10);
|
||||
pub(crate) const MAX_TEXT: usize = 1 << 20;
|
||||
/// The most text, and the most PNG bytes, `ui.read-clipboard` returns.
|
||||
@@ -1109,6 +1109,16 @@ fn event_to_wit(e: WorkbenchEvent) -> wit_events::Event {
|
||||
kind: "input-mode-changed".into(),
|
||||
data: serde_json::to_string(&mode).expect("mode serializes"),
|
||||
}),
|
||||
WorkbenchEvent::CaretMoved(caret) => wit_events::Event::Other(wit_types::Extension {
|
||||
kind: "caret-moved".into(),
|
||||
data: serde_json::json!({
|
||||
"path": caret.path,
|
||||
"line": caret.line,
|
||||
"col": caret.col,
|
||||
"settled": caret.settled,
|
||||
})
|
||||
.to_string(),
|
||||
}),
|
||||
WorkbenchEvent::FileOpened(p) => wit_events::Event::FileOpened(p),
|
||||
WorkbenchEvent::FileSaved(p) => wit_events::Event::FileSaved(p),
|
||||
WorkbenchEvent::FilesChanged(batch) => wit_events::Event::Other(wit_types::Extension {
|
||||
|
||||
@@ -155,6 +155,7 @@ pub enum EventKind {
|
||||
FileSaved,
|
||||
FilesChanged,
|
||||
EditorFocused,
|
||||
CaretMoved,
|
||||
ActionPerformed,
|
||||
VcsChanged,
|
||||
/// Problems of the window's files changed (a language server or a report).
|
||||
@@ -163,7 +164,7 @@ pub enum EventKind {
|
||||
}
|
||||
|
||||
impl EventKind {
|
||||
pub const ALL: [Self; 17] = [
|
||||
pub const ALL: [Self; 18] = [
|
||||
Self::DocumentChanged,
|
||||
Self::WebsocketReady,
|
||||
Self::FileClosed,
|
||||
@@ -177,6 +178,7 @@ impl EventKind {
|
||||
Self::FileSaved,
|
||||
Self::FilesChanged,
|
||||
Self::EditorFocused,
|
||||
Self::CaretMoved,
|
||||
Self::ActionPerformed,
|
||||
Self::VcsChanged,
|
||||
Self::ProblemsChanged,
|
||||
@@ -198,6 +200,7 @@ impl EventKind {
|
||||
Self::FileSaved => "file-saved",
|
||||
Self::FilesChanged => "files-changed",
|
||||
Self::EditorFocused => "editor-focused",
|
||||
Self::CaretMoved => "caret-moved",
|
||||
Self::ActionPerformed => "action-performed",
|
||||
Self::VcsChanged => "vcs-changed",
|
||||
Self::ProblemsChanged => "problems-changed",
|
||||
@@ -275,6 +278,19 @@ pub struct InputMode {
|
||||
pub sub: Option<String>,
|
||||
}
|
||||
|
||||
/// The caret moved in the focused editor. Positions are 0-based; `col` counts
|
||||
/// UTF-16 code units, as everywhere in the plugin API.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CaretMoved {
|
||||
pub path: String,
|
||||
pub line: u32,
|
||||
pub col: u32,
|
||||
/// The caret came to rest at this position; plugins may load what a hover needs.
|
||||
#[serde(default)]
|
||||
pub settled: bool,
|
||||
}
|
||||
|
||||
/// One UTF-16 replacement in a locally edited editor document.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
pub struct DocumentTextChange {
|
||||
@@ -337,6 +353,7 @@ pub enum WorkbenchEvent {
|
||||
FileSaved(String),
|
||||
FilesChanged(FilesChanged),
|
||||
EditorFocused(Option<String>),
|
||||
CaretMoved(CaretMoved),
|
||||
ActionPerformed(ActionPerformed),
|
||||
VcsChanged(String),
|
||||
/// Problems of the window's files changed; plugins re-read `problems`.
|
||||
@@ -360,6 +377,7 @@ impl WorkbenchEvent {
|
||||
Self::FileSaved(_) => EventKind::FileSaved,
|
||||
Self::FilesChanged(_) => EventKind::FilesChanged,
|
||||
Self::EditorFocused(_) => EventKind::EditorFocused,
|
||||
Self::CaretMoved(_) => EventKind::CaretMoved,
|
||||
Self::ActionPerformed(_) => EventKind::ActionPerformed,
|
||||
Self::VcsChanged(_) => EventKind::VcsChanged,
|
||||
Self::ProblemsChanged => EventKind::ProblemsChanged,
|
||||
|
||||
@@ -93,7 +93,7 @@ fn the_sdk_carries_the_hosts_wit() {
|
||||
|
||||
#[test]
|
||||
fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
let host = v("1.14.0");
|
||||
let host = v("1.15.0");
|
||||
for ok in [
|
||||
"1.0.0",
|
||||
"1.3.0",
|
||||
@@ -108,15 +108,16 @@ fn the_version_check_runs_compatible_components_and_explains_the_rest() {
|
||||
"1.12.0",
|
||||
"1.13.0",
|
||||
"1.14.0",
|
||||
"1.15.0",
|
||||
"1.0.0-rc.1",
|
||||
] {
|
||||
assert_eq!(check_api(&v(ok), &host), Ok(()), "{ok}");
|
||||
}
|
||||
let newer = check_api(&v("1.15.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.15") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
let newer = check_api(&v("1.16.0"), &host).unwrap_err();
|
||||
assert!(newer.contains("1.16") && newer.contains("update OpenIDEA"), "{newer}");
|
||||
assert!(check_api(&v("2.0.0"), &host).unwrap_err().contains("update OpenIDEA"));
|
||||
let older = check_api(&v("0.2.0"), &host).unwrap_err();
|
||||
assert!(older.contains("rebuild it with the 1.14 SDK"), "{older}");
|
||||
assert!(older.contains("rebuild it with the 1.15 SDK"), "{older}");
|
||||
// 0.x: every minor is its own API.
|
||||
assert_eq!(check_api(&v("0.2.0"), &v("0.2.5")), Ok(()));
|
||||
assert!(check_api(&v("0.1.0"), &v("0.2.0")).is_err());
|
||||
@@ -144,14 +145,17 @@ fn shipped_components_are_built_for_this_api() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_1_14_component_exports_the_optional_hover_actions_world() {
|
||||
fn the_hover_actions_component_exports_the_optional_hover_actions_world() {
|
||||
let engine = PluginEngine::new().unwrap();
|
||||
let component =
|
||||
engine.compile(&repo().join("crates/ide-plugin/tests/fixtures/hover-actions/dist/plugin.wasm")).unwrap();
|
||||
let exports: Vec<String> =
|
||||
component.component_type().exports(engine.engine()).map(|(name, _)| name.to_owned()).collect();
|
||||
assert!(exports.iter().any(|name| name.starts_with("openidea:plugin/[email protected]")), "{exports:?}");
|
||||
// A 1.13-compatible plugin that does not export the new world stays valid.
|
||||
assert!(
|
||||
exports.iter().any(|name| name.starts_with(&format!("openidea:plugin/hover-actions@{API_VERSION}.0"))),
|
||||
"{exports:?}"
|
||||
);
|
||||
// A plugin that does not export the optional world stays valid.
|
||||
let old = engine.compile(&repo().join("plugins/official/test-runner/dist/plugin.wasm")).unwrap();
|
||||
let old_exports: Vec<String> =
|
||||
old.component_type().exports(engine.engine()).map(|(name, _)| name.to_owned()).collect();
|
||||
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
d442e600d82cab0f79ad6decf95ca9d06c89dcd3119c500a11f48cdc54a5d5f4
|
||||
476dff19159556f8afc8ba4e7d1757d7faebb79046fc08e1601563a7cf9ad3d1
|
||||
@@ -3,7 +3,7 @@ name = "API 1.4 host tests"
|
||||
version = "0.1.0"
|
||||
engines.openidea = "^1.5"
|
||||
wasm = "dist/plugin.wasm"
|
||||
activation = ["on-command:*", "on-event:file-closed", "on-event:settings-changed", "on-event:input-mode-changed"]
|
||||
activation = ["on-command:*", "on-event:file-closed", "on-event:settings-changed", "on-event:input-mode-changed", "on-event:caret-moved"]
|
||||
|
||||
[capabilities]
|
||||
required = ["storage"]
|
||||
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
af048639f57e86262543c3dcd18bca27d384b6ad99a625af869f0812bf8ac93c
|
||||
988eeaa480210cef8d733f8305a7441f4d51699d756ac2e1cfd4728ff57bbc84
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
95b7263ca584c6b1b035be4dde64c7ae57b407c6a86b5ab6fe2736134e1d7754
|
||||
c82d541d5c1c7e9ab595e33cf206fe065fa9b4bd6e94d19b181b78049ffc60a9
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
1e5b10e8e77bdc7ed6bf002a415458caef7eee9a98123229dddf0d148af58f73
|
||||
c5dd0424fc7f3043139577e64de4b4a4e5e73913453b42ccde6ee9f0d878bc57
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
5b3d4ad737cde32fc808bcd8c93d9cdd7d53961985db0428ab567b4e97ed4ffb
|
||||
fb95d2b21ca4c0ffe8c9b359999d2bc80a37a2aaf389f4290b62c2bc7e0657eb
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
04b1cbc2148cff8c0fa2d6a4f127a6a3c8ade5a7dc1541c1a16a656def299f33
|
||||
9e68d2e72a85c4b2491ebf3ca31e0ebedd47941db1dd8e1b69a418e1dfacbb71
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
918c44ee3a58a073dd65e2f7e32501cf9e84a59f24452c166e75457f7c232c89
|
||||
9f56d68a45f3508ba89bab5af935986da1bd01ee3df5f045283ec82911409edf
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
c980260c235249186f754e16597de9d49663771d711ce6873bf83ebaf2a0fc34
|
||||
1f39c7829190e563f8145bd08385b595dab3bd5bd493182681126d3e17ef5035
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
df5729d63b83fbc511e0ba8509f9d370c5124b5af4c70f286c8965d2b0d890ef
|
||||
e5cc283d9df974bce79bcab1ddfba19b0d50702251176f7c1f71a0894319fc95
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
305965c6cbf2fd2b331bf9e2c473cfa9a543ab39ff0d47317ee9e28be9ea5b0f
|
||||
73a29153c691351dfaf3f37e2ba420d0d4ca9ee2f1c102616e64d5eb0532bde3
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
a1bb95a8a23ddd2d55bf64c724f73debfb503f252f57d8ae46afda8a0717fc20
|
||||
01b33569f711f50f1114b718ba9ff5a9d4f0ac8e9e8e84d1cccd001ca2f46d20
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
b8be3120a468190aebb473c8f5d2e13889210241c9ab43c89cbf703c00366c8e
|
||||
ae86f8929ac9fed59b511b64c9fc6409143d9ec6e4d84e9109bbdd849c4a4cf5
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
9b345dec001bcb7c0d8e6e214099d597b02976f20c2449af9847e8b69d0a5ab7
|
||||
8ae3c039570329a8b9f59b20450be8f96f1a125cb65f8b404419d20e6cd9b43f
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
23e0c2ab39ba83aa332b57046b0b8c1bf236e3e61a14874ed82d20ce388873b6
|
||||
60ed7b2c7c67e9d5fa3e2f6692619ad7406bd540c32fd178e5986f413e3e948c
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
e2d2afeb53f0af478963cde0c97fb016b1a424bf97952c7474a18e38e9e9ed55
|
||||
48f755d33198a9bc7dfeeadedaa64fdfc8426cc6b697532e78e9093775d587b4
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
6bff7a7521a4a969aa8d9bd1363ef5efd544e079e77e55e51b19fff13b586b3a
|
||||
1a619dad978cadaeab8f181adc63cdb731aa392297cdbce894feadcc488bf8ca
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
27bb4c06b18703c43155e1a45c9edfb249a19443a68e87441babeeb71cb127d9
|
||||
007592c7adb4353cab3f2d748a511d073d9ca1523aa235fab8d3f063ade149e0
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
deb7995931cf8e344a486fbab275fd3ec7ddff73b05a841593e5521c4a514084
|
||||
25a975ae7a81ef34e4635fd34dca2cf747d11bbdec206e1e9c5f27cea9b888e6
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
dc6670ff6373d148430f5c9c13d1ec5407b2d94c74c2209562737076468ca79d
|
||||
75bff3c38b179cc98d2c24e8d6add56077c69756e436d3b1ee3a064e6d566d94
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
9e111c4c541312dc231bac5a4fd1120b59191ecadce2dca73c77f4bff2a9d0e8
|
||||
76641b6954d59c30dac9b08c3c5dacbcaa7632af517f403b14b7f7987c61d5f8
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
caa4053cd7f0135ab14a8c5c56abe198394e370549fea6d9df4d4c11c38fcabf
|
||||
a307fedfeb01bc3dbdc3ac425b3f23dc7280f594e654c696902deaa0790f889f
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
8beb151f14b062438c4024b13bbdedbf5d65099415ad9d055fe63a4b1d64d010
|
||||
30e0f0782782ce4d0e697e026343708c44a1d53db2b9d44e063fff540850b471
|
||||
@@ -5,9 +5,9 @@ wit_bindgen::generate!({
|
||||
inline: "
|
||||
package fixture:misbehave;
|
||||
world misbehave {
|
||||
include openidea:plugin/plugin-syntax@1.14.0;
|
||||
export openidea:plugin/providers@1.14.0;
|
||||
export openidea:plugin/file-actions@1.14.0;
|
||||
include openidea:plugin/plugin-syntax@1.15.0;
|
||||
export openidea:plugin/providers@1.15.0;
|
||||
export openidea:plugin/file-actions@1.15.0;
|
||||
}
|
||||
",
|
||||
path: "../../../../../wit",
|
||||
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
fa6a660890e0beee7599726e9c30142601fbcd6f82a519b1b5952ef30f450bfb
|
||||
d2a3db92d7e1c39ce797013a04745abd918fb3f79bc581894e8820d5ce247557
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
a7c1ec4814e4268fe185ae493413532528970264e84f717087b57a303ebe3591
|
||||
2b58e78383ccc2e4134f60fdbdb40ceaeeadd594b5f6f530d1598e3a84eecf1c
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
450d1e698882257d6c75b16984a6086259acce2c66a92b96c76ed3d6e15a0b4d
|
||||
f8170b78126576f7bfcd25cfe97b55a12d9741e34ad743f5d3b78a36fa97bc67
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
738791aa00d63961fa7e8ed6ac7601f46848ecc0d25a498b6019eb151bf9169e
|
||||
355d2a93b11c3ca487c8008c4f3f36cb6eeb41f80af58c42b5762976c6d905aa
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
957d02e3d72673ca4a9ca80eb7c3e63087a6d8377411fc820d3808f024326b2e
|
||||
1b63cc55968a8f748063e7c5a7055e37308746070b1252cacc162fde448eea0c
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
f0a57acc6ca29b0dc2803596a0a39ceb1e2185b59a44f5533e8f9b19bf214afd
|
||||
a0c4d4e8f4906255e5775e4fb5313c566119689ea81bf3ff4facf36c8eabebf8
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
7890cfd9a08b67b47ae098ce24e02551935337b8501636e29164ff4ca6244e7e
|
||||
76105de451dd79c18e04ac8ec4d7e93fcd1ef3f1e72cb339434d10da811c9e4d
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
769f873adfa7ed3752a059dac89e60f2203b8ce91b36fe0a7cb9c724e0cf895b
|
||||
db0f738e7b25735e0d856500674106834ee02025b063ee659f4d6270dbce12aa
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
ea31cbeefee7f219f86fc7e65315aea7efebe3b91c9cec6e12d4f551b9655d95
|
||||
13ef23569704549fe7274270ec4f77c9aee9206a4f0491273fdd5f84279fa9c5
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
bb30795e7d62b19b237759beeab9da6f6028fea7862d8fa83c6b3238a26f540d
|
||||
9866f44c883bee81012e33ed1927cb6467a26aae6b5af7d9ad9217165e215328
|
||||
Бінарний файл не відображається.
@@ -1 +1 @@
|
||||
65725512c8a8d3ad6cb02a4f947541dd1688a3208e37fa4ed0474ca8197f2340
|
||||
d6dee51c4b07a8c08bde9c618736bf7667f55fdc628e89d6aaeacab2c5f4aa5c
|
||||
@@ -28,6 +28,9 @@ pub(crate) enum Redeclaration {
|
||||
pub(crate) struct LangKinds {
|
||||
pub grammars: &'static [&'static str],
|
||||
pub blocks: &'static [&'static str],
|
||||
/// Branches of a `switch` / `when` (`case 1:` with its statements): moved as one statement,
|
||||
/// among their sibling branches only.
|
||||
pub clauses: &'static [&'static str],
|
||||
pub members: &'static [&'static str],
|
||||
/// A block whose parent has one of these kinds is a member container (Python class bodies).
|
||||
pub member_parents: &'static [&'static str],
|
||||
@@ -59,6 +62,7 @@ const NONE: &[&str] = &[];
|
||||
pub(crate) const DEFAULT: LangKinds = LangKinds {
|
||||
grammars: NONE,
|
||||
blocks: &["block", "statement_block", "compound_statement", "statement_list", "statements"],
|
||||
clauses: NONE,
|
||||
members: &["class_body", "declaration_list", "field_declaration_list", "enum_body", "interface_body"],
|
||||
member_parents: NONE,
|
||||
expressions: NONE,
|
||||
@@ -157,6 +161,7 @@ static TABLES: &[LangKinds] = &[
|
||||
LangKinds {
|
||||
grammars: &["kotlin"],
|
||||
blocks: &["block", "statements", "control_structure_body"],
|
||||
clauses: &["when_entry"],
|
||||
members: &["class_body", "enum_class_body"],
|
||||
expressions: &["this_expression", "super_expression", "string_literal", "lambda_literal", "object_literal"],
|
||||
labels: &[("value_argument", "=")],
|
||||
@@ -168,6 +173,7 @@ static TABLES: &[LangKinds] = &[
|
||||
LangKinds {
|
||||
grammars: &["go"],
|
||||
blocks: &["statement_list", "block", "expression_case", "default_case", "type_case", "communication_case"],
|
||||
clauses: &["expression_case", "default_case", "type_case", "communication_case"],
|
||||
members: &["field_declaration_list"],
|
||||
expressions: &["func_literal", "composite_literal", "true", "false", "nil", "iota"],
|
||||
not_expressions: &["expression_list", "literal_value", "keyed_element", "literal_element"],
|
||||
@@ -509,6 +515,10 @@ impl Kinds {
|
||||
self.table.redeclaration
|
||||
}
|
||||
|
||||
pub(crate) fn is_clause(&self, node: &Node) -> bool {
|
||||
self.table.clauses.contains(&node.kind())
|
||||
}
|
||||
|
||||
pub(crate) fn is_block(&self, node: &Node) -> bool {
|
||||
node.parent().is_none() || self.table.blocks.contains(&node.kind())
|
||||
}
|
||||
|
||||
@@ -133,10 +133,15 @@ fn enclosing_expression<'t>(cx: &Ctx, node: Node<'t>) -> Option<Node<'t>> {
|
||||
|
||||
/// Nearest ancestor-or-self that is a direct named child of a block.
|
||||
fn statement_of<'t>(cx: &Ctx, node: Node<'t>) -> Option<Node<'t>> {
|
||||
statement_or_clause_of(cx, node, false)
|
||||
}
|
||||
|
||||
/// Like [`statement_of`], but a `switch` / `when` branch reached from its header counts too.
|
||||
fn statement_or_clause_of<'t>(cx: &Ctx, node: Node<'t>, clauses: bool) -> Option<Node<'t>> {
|
||||
let mut cur = Some(node);
|
||||
while let Some(n) = cur {
|
||||
let parent = n.parent()?;
|
||||
if n.is_named() && !n.is_extra() && cx.kinds.is_block(&parent) {
|
||||
if n.is_named() && !n.is_extra() && (cx.kinds.is_block(&parent) || clauses && cx.kinds.is_clause(&n)) {
|
||||
return Some(n);
|
||||
}
|
||||
cur = Some(parent);
|
||||
@@ -144,6 +149,12 @@ fn statement_of<'t>(cx: &Ctx, node: Node<'t>) -> Option<Node<'t>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// The neighbouring statement; a branch's neighbours are the other branches (not the `switch` subject).
|
||||
fn statement_sibling<'t>(cx: &Ctx, node: Node<'t>, next: bool) -> Option<Node<'t>> {
|
||||
let s = sibling(node, next)?;
|
||||
(!cx.kinds.is_clause(&node) || cx.kinds.is_clause(&s)).then_some(s)
|
||||
}
|
||||
|
||||
/// Nearest ancestor-or-self that is a direct named child of a class body or the file.
|
||||
fn declaration_of<'t>(cx: &Ctx, node: Node<'t>) -> Option<Node<'t>> {
|
||||
let mut cur = Some(node);
|
||||
@@ -188,12 +199,12 @@ pub(crate) fn structural_ranges(cx: &Ctx, pos: Pos) -> StructuralRanges {
|
||||
let root = cx.tree.root_node();
|
||||
let end = (b + text[b..].chars().next().map_or(0, char::len_utf8)).min(text.len());
|
||||
let Some(node) = root.descendant_for_byte_range(b, end) else { return StructuralRanges::default() };
|
||||
let statement = statement_of(cx, node);
|
||||
let statement = statement_or_clause_of(cx, node, true);
|
||||
let declaration = declaration_of(cx, node);
|
||||
StructuralRanges {
|
||||
selection: Vec::new(),
|
||||
prev_statement: statement.and_then(|s| sibling(s, false)).map(|n| cx.node(&n)),
|
||||
next_statement: statement.and_then(|s| sibling(s, true)).map(|n| cx.node(&n)),
|
||||
prev_statement: statement.and_then(|s| statement_sibling(cx, s, false)).map(|n| cx.node(&n)),
|
||||
next_statement: statement.and_then(|s| statement_sibling(cx, s, true)).map(|n| cx.node(&n)),
|
||||
block: statement.and_then(|s| s.parent()).map(|n| cx.node(&n)),
|
||||
statement: statement.map(|n| cx.node(&n)),
|
||||
prev_declaration: declaration.and_then(|s| sibling(s, false)).map(|n| cx.node(&n)),
|
||||
|
||||
@@ -407,3 +407,24 @@ fn web_script_queries_preserve_parse_size_errors() {
|
||||
assert_eq!(service().locals(&snap, Pos::new(0, 0), &none()), Err(StructureError::TooLarge));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_ranges_switch_and_when_branches() {
|
||||
let go = lang("go");
|
||||
let src = "package main\n\nfunc f(x int) {\n\tswitch x {\n\tcase 1:\n\t\tprintln(\"one\")\n\tcase 2:\n\t\tprintln(\"two\")\n\t}\n}\n";
|
||||
// On `case 1:` the whole branch moves, among the branches only (not past the subject `x`).
|
||||
let r = service().structural_ranges(&snap(&go, src), Pos::new(4, 1), &none()).unwrap();
|
||||
assert_eq!(r.statement.unwrap().kind, "expression_case");
|
||||
assert!(r.prev_statement.is_none());
|
||||
assert_eq!(r.next_statement.unwrap().range.start, Pos::new(6, 1));
|
||||
// A statement inside the branch is still the statement.
|
||||
let r = service().structural_ranges(&snap(&go, src), Pos::new(5, 2), &none()).unwrap();
|
||||
assert_eq!(r.statement.unwrap().range, span(src, "println(\"one\")"));
|
||||
|
||||
let kt = lang("kotlin");
|
||||
let src = "fun f(x: Int) {\n when (x) {\n 1 -> println(\"one\")\n 2 -> println(\"two\")\n else -> println(\"other\")\n }\n}\n";
|
||||
let r = service().structural_ranges(&snap(&kt, src), Pos::new(2, 9), &none()).unwrap();
|
||||
assert_eq!(r.statement.unwrap().range, span(src, "1 -> println(\"one\")"));
|
||||
assert!(r.prev_statement.is_none());
|
||||
assert_eq!(r.next_statement.unwrap().range, span(src, "2 -> println(\"two\")"));
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
//! .NET tool installs: the SDKs `dotnet` offers, the target framework a tool package on
|
||||
//! nuget.org needs, and NuGet errors in `dotnet tool install` output. Parsing is pure;
|
||||
//! network access goes through the `fetch` callback.
|
||||
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::Deserialize;
|
||||
|
||||
pub const SDK_DOWNLOAD_URL: &str = "https://dotnet.microsoft.com/download";
|
||||
|
||||
/// Catalog entries read before giving up on finding an older compatible version.
|
||||
const MAX_VERSIONS_CHECKED: usize = 20;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Sdk {
|
||||
pub major: u32,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// The newest SDK in `dotnet --list-sdks` output (`6.0.300 [/usr/local/share/dotnet/sdk]`).
|
||||
pub fn newest_sdk(list_sdks: &str) -> Option<Sdk> {
|
||||
list_sdks
|
||||
.lines()
|
||||
.filter_map(|l| l.split_whitespace().next())
|
||||
.filter_map(|v| {
|
||||
let release = v.split('-').next()?;
|
||||
let parts: Vec<u32> = release.split('.').map(str::parse).collect::<Result<_, _>>().ok()?;
|
||||
Some((parts, v))
|
||||
})
|
||||
.max_by(|(a, _), (b, _)| a.cmp(b))
|
||||
.and_then(|(parts, v)| Some(Sdk { major: *parts.first()?, version: v.to_string() }))
|
||||
}
|
||||
|
||||
/// Major .NET version of a target framework folder: `net11.0`, `netcoreapp3.1`, `net8.0-windows`.
|
||||
/// .NET Framework monikers (`net48`) have no dot and give `None`.
|
||||
pub fn tfm_major(tfm: &str) -> Option<u32> {
|
||||
let rest = tfm.strip_prefix("netcoreapp").or_else(|| tfm.strip_prefix("net"))?;
|
||||
rest.split_once('.')?.0.parse().ok()
|
||||
}
|
||||
|
||||
/// `error NUxxxx: …` lines of `dotnet tool install` output, without the restore project path
|
||||
/// that precedes them, each once.
|
||||
pub fn nuget_errors(output: &str) -> Vec<String> {
|
||||
let mut found: Vec<String> = Vec::new();
|
||||
for line in output.lines() {
|
||||
let Some(at) = line.find("error NU") else { continue };
|
||||
let error = line[at..].trim().to_string();
|
||||
if !found.contains(&error) {
|
||||
found.push(error);
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
pub fn registration_url(package: &str) -> String {
|
||||
format!("https://api.nuget.org/v3/registration5-semver1/{}/index.json", package.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Registration {
|
||||
items: Vec<RegistrationPage>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RegistrationPage {
|
||||
#[serde(rename = "@id")]
|
||||
id: String,
|
||||
/// Left out when the package has many versions; the page URL then lists them.
|
||||
#[serde(default)]
|
||||
items: Option<Vec<RegistrationLeaf>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct RegistrationLeaf {
|
||||
#[serde(rename = "catalogEntry")]
|
||||
catalog_entry: CatalogSummary,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CatalogSummary {
|
||||
#[serde(rename = "@id")]
|
||||
id: String,
|
||||
version: String,
|
||||
#[serde(default = "listed_default")]
|
||||
listed: bool,
|
||||
}
|
||||
|
||||
fn listed_default() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CatalogEntry {
|
||||
#[serde(default, rename = "packageEntries")]
|
||||
package_entries: Vec<PackageEntry>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PackageEntry {
|
||||
#[serde(rename = "fullName")]
|
||||
full_name: String,
|
||||
}
|
||||
|
||||
fn proto(what: &str, e: serde_json::Error) -> IdeError {
|
||||
IdeError::new(ErrorKind::Protocol, format!("unexpected NuGet {what}: {e}"))
|
||||
}
|
||||
|
||||
/// The lowest .NET major a tool package runs on, from its `tools/<tfm>/` folders.
|
||||
pub fn catalog_framework_major(json: &str) -> IdeResult<Option<u32>> {
|
||||
let entry: CatalogEntry = serde_json::from_str(json).map_err(|e| proto("catalog entry", e))?;
|
||||
Ok(entry
|
||||
.package_entries
|
||||
.iter()
|
||||
.filter_map(|e| e.full_name.strip_prefix("tools/")?.split('/').next())
|
||||
.filter_map(tfm_major)
|
||||
.min())
|
||||
}
|
||||
|
||||
/// Which version of a .NET tool to install with the SDK at hand.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ToolPick {
|
||||
/// The latest version runs on the SDK, or its framework is unknown: install without `--version`.
|
||||
Latest,
|
||||
/// The latest version needs a newer SDK; `version` is the newest one that does not.
|
||||
Older { version: String, latest: String, needs: u32 },
|
||||
/// No checked version runs on the SDK.
|
||||
Incompatible { latest: String, needs: u32 },
|
||||
}
|
||||
|
||||
/// Walks the package's stable, listed versions on nuget.org from the newest down until one
|
||||
/// targets a framework the SDK supports.
|
||||
pub fn pick_tool_version(
|
||||
package: &str,
|
||||
sdk_major: u32,
|
||||
mut fetch: impl FnMut(&str) -> IdeResult<String>,
|
||||
) -> IdeResult<ToolPick> {
|
||||
let index: Registration =
|
||||
serde_json::from_str(&fetch(®istration_url(package))?).map_err(|e| proto("registration", e))?;
|
||||
let mut latest: Option<(String, u32)> = None;
|
||||
let mut checked = 0;
|
||||
for page in index.items.into_iter().rev() {
|
||||
let leaves = match page.items {
|
||||
Some(items) => items,
|
||||
None => serde_json::from_str::<RegistrationPage>(&fetch(&page.id)?)
|
||||
.map_err(|e| proto("registration page", e))?
|
||||
.items
|
||||
.unwrap_or_default(),
|
||||
};
|
||||
for leaf in leaves.into_iter().rev() {
|
||||
let entry = leaf.catalog_entry;
|
||||
if !entry.listed || entry.version.contains('-') {
|
||||
continue;
|
||||
}
|
||||
let Some(major) = catalog_framework_major(&fetch(&entry.id)?)? else {
|
||||
if latest.is_none() {
|
||||
return Ok(ToolPick::Latest);
|
||||
}
|
||||
continue;
|
||||
};
|
||||
match &latest {
|
||||
None if major <= sdk_major => return Ok(ToolPick::Latest),
|
||||
None => latest = Some((entry.version.clone(), major)),
|
||||
Some((latest, needs)) if major <= sdk_major => {
|
||||
return Ok(ToolPick::Older { version: entry.version, latest: latest.clone(), needs: *needs });
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
checked += 1;
|
||||
if checked >= MAX_VERSIONS_CHECKED {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if checked >= MAX_VERSIONS_CHECKED {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(match latest {
|
||||
Some((latest, needs)) => ToolPick::Incompatible { latest, needs },
|
||||
None => ToolPick::Latest,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[test]
|
||||
fn newest_sdk_compares_numerically() {
|
||||
let out = "6.0.300 [/usr/local/share/dotnet/sdk]\n10.0.100-rc.2.25502.107 [/usr/local/share/dotnet/sdk]\n9.0.306 [/usr/local/share/dotnet/sdk]\n";
|
||||
assert_eq!(newest_sdk(out), Some(Sdk { major: 10, version: "10.0.100-rc.2.25502.107".into() }));
|
||||
assert_eq!(newest_sdk("6.0.300 [/x]\n6.0.1000 [/x]\n").unwrap().version, "6.0.1000");
|
||||
assert_eq!(newest_sdk(""), None);
|
||||
assert_eq!(newest_sdk("not an sdk\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framework_monikers() {
|
||||
assert_eq!(tfm_major("net11.0"), Some(11));
|
||||
assert_eq!(tfm_major("netcoreapp3.1"), Some(3));
|
||||
assert_eq!(tfm_major("net8.0-windows"), Some(8));
|
||||
assert_eq!(tfm_major("net48"), None);
|
||||
assert_eq!(tfm_major("netstandard2.0"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nuget_errors_drop_the_project_path_and_repeats() {
|
||||
let out = "\
|
||||
1>/var/folders/T/abc/restore.csproj : error NU1202: Package csharp-ls 0.29.0 is not compatible with net6.0 (.NETCoreApp,Version=v6.0) / any. Package csharp-ls 0.29.0 supports: net11.0 (.NETCoreApp,Version=v11.0) / any
|
||||
The tool package could not be restored.
|
||||
/var/folders/T/abc/restore.csproj : error NU1202: Package csharp-ls 0.29.0 is not compatible with net6.0 (.NETCoreApp,Version=v6.0) / any. Package csharp-ls 0.29.0 supports: net11.0 (.NETCoreApp,Version=v11.0) / any
|
||||
* The required NuGet feed cannot be accessed, perhaps because of an Internet connection problem.
|
||||
";
|
||||
assert_eq!(
|
||||
nuget_errors(out),
|
||||
[
|
||||
"error NU1202: Package csharp-ls 0.29.0 is not compatible with net6.0 (.NETCoreApp,Version=v6.0) / any. Package csharp-ls 0.29.0 supports: net11.0 (.NETCoreApp,Version=v11.0) / any"
|
||||
]
|
||||
);
|
||||
assert!(nuget_errors("Tool 'x' failed to install.").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_framework_is_the_lowest_tools_folder() {
|
||||
let json = r#"{"packageEntries":[
|
||||
{"fullName":"tools/net10.0/any/fsautocomplete.dll"},
|
||||
{"fullName":"tools/net8.0/any/fsautocomplete.dll"},
|
||||
{"fullName":"README.md"}
|
||||
]}"#;
|
||||
assert_eq!(catalog_framework_major(json).unwrap(), Some(8));
|
||||
assert_eq!(catalog_framework_major(r#"{"packageEntries":[]}"#).unwrap(), None);
|
||||
}
|
||||
|
||||
fn leaf(version: &str, listed: bool) -> String {
|
||||
format!(
|
||||
r#"{{"catalogEntry":{{"@id":"https://catalog/{version}.json","version":"{version}","listed":{listed}}}}}"#
|
||||
)
|
||||
}
|
||||
|
||||
fn catalog(tfm: &str) -> String {
|
||||
format!(r#"{{"packageEntries":[{{"fullName":"tools/{tfm}/any/tool.dll"}}]}}"#)
|
||||
}
|
||||
|
||||
/// csharp-ls's history: 0.20.0 on net9.0, 0.28.0 on net10.0, 0.29.0 on net11.0.
|
||||
fn feed() -> HashMap<String, String> {
|
||||
let page2 = format!(
|
||||
r#"{{"@id":"https://reg/page2","items":[{},{},{}]}}"#,
|
||||
leaf("0.28.0", true),
|
||||
leaf("0.29.0-beta", true),
|
||||
leaf("0.29.0", true)
|
||||
);
|
||||
HashMap::from([
|
||||
(registration_url("csharp-ls"), format!(r#"{{"items":[{{"@id":"https://reg/page1"}},{}]}}"#, page2)),
|
||||
(
|
||||
"https://reg/page1".into(),
|
||||
format!(
|
||||
r#"{{"@id":"https://reg/page1","items":[{},{}]}}"#,
|
||||
leaf("0.20.0", true),
|
||||
leaf("0.21.0", false)
|
||||
),
|
||||
),
|
||||
("https://catalog/0.20.0.json".into(), catalog("net9.0")),
|
||||
("https://catalog/0.21.0.json".into(), catalog("net8.0")),
|
||||
("https://catalog/0.28.0.json".into(), catalog("net10.0")),
|
||||
("https://catalog/0.29.0-beta.json".into(), catalog("net9.0")),
|
||||
("https://catalog/0.29.0.json".into(), catalog("net11.0")),
|
||||
])
|
||||
}
|
||||
|
||||
fn pick(sdk_major: u32) -> (ToolPick, Vec<String>) {
|
||||
let feed = feed();
|
||||
let mut fetched = Vec::new();
|
||||
let pick = pick_tool_version("csharp-ls", sdk_major, |url| {
|
||||
fetched.push(url.to_string());
|
||||
feed.get(url).cloned().ok_or_else(|| IdeError::not_found(url.to_string()))
|
||||
})
|
||||
.unwrap();
|
||||
(pick, fetched)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latest_version_on_a_new_enough_sdk() {
|
||||
let (p, fetched) = pick(11);
|
||||
assert_eq!(p, ToolPick::Latest);
|
||||
assert_eq!(fetched.len(), 2, "{fetched:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn newest_compatible_older_version_skips_prereleases() {
|
||||
let (p, _) = pick(10);
|
||||
assert_eq!(p, ToolPick::Older { version: "0.28.0".into(), latest: "0.29.0".into(), needs: 11 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn older_versions_on_a_page_that_is_not_inline_skip_unlisted_ones() {
|
||||
let (p, fetched) = pick(9);
|
||||
assert_eq!(p, ToolPick::Older { version: "0.20.0".into(), latest: "0.29.0".into(), needs: 11 });
|
||||
assert!(fetched.contains(&"https://reg/page1".to_string()));
|
||||
assert!(!fetched.contains(&"https://catalog/0.21.0.json".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_compatible_version_reports_what_the_latest_needs() {
|
||||
let (p, _) = pick(6);
|
||||
assert_eq!(p, ToolPick::Incompatible { latest: "0.29.0".into(), needs: 11 });
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
pub mod archive;
|
||||
mod bundled;
|
||||
mod dotnet;
|
||||
pub mod formatter;
|
||||
pub mod jdk;
|
||||
pub mod mirror;
|
||||
@@ -36,11 +37,11 @@ use ide_language::LanguageConfig;
|
||||
use parking_lot::Mutex;
|
||||
use platform::{Os, Platform};
|
||||
pub use process::progress_event;
|
||||
use process::run_collect;
|
||||
pub use process::{
|
||||
Emit, Http, PUBLIC_NPM_REGISTRY, is_npm_registry_miss, npm_public_registry_args, run_npm_with_public_fallback,
|
||||
run_quiet, run_streamed,
|
||||
};
|
||||
use process::{run_collect, run_streamed_picking};
|
||||
pub use registry::{Method, ReleaseSource, TOOLS, ToolKind, ToolSpec};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
@@ -1190,9 +1191,13 @@ impl Tools {
|
||||
let tool = dir.join("tool");
|
||||
std::fs::create_dir_all(&tool)?;
|
||||
let dotnet = self.which("dotnet").expect("checked");
|
||||
let version = self.dotnet_tool_version(spec, package, &dotnet, cancel, emit)?;
|
||||
let mut c = self.command(&dotnet);
|
||||
c.args(["tool", "install", package, "--tool-path"]).arg(&tool);
|
||||
let result = run_streamed(c, cancel, emit).and_then(|_| {
|
||||
c.args(["tool", "install", package, "--tool-path"]).arg(&tool).args(["--verbosity", "normal"]);
|
||||
if let Some(version) = &version {
|
||||
c.args(["--version", version]);
|
||||
}
|
||||
let result = run_streamed_picking(c, cancel, emit, dotnet::nuget_errors).and_then(|_| {
|
||||
// The tool's apphost looks for .NET in the default location only; a
|
||||
// Homebrew / user-local SDK must be named through DOTNET_ROOT.
|
||||
let root = self.dotnet_root(&dotnet);
|
||||
@@ -1224,6 +1229,58 @@ impl Tools {
|
||||
self.write_manifest(spec.name, &Manifest { version, source: Some(format!("nuget:{package}")) })
|
||||
}
|
||||
|
||||
/// The `--version` to install `package` with: `None` for the latest, or the newest version
|
||||
/// the installed SDK supports. Fails when there is no SDK, or no version runs on it.
|
||||
fn dotnet_tool_version(
|
||||
&self,
|
||||
spec: &ToolSpec,
|
||||
package: &str,
|
||||
dotnet: &Path,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<Option<String>> {
|
||||
let mut c = self.command(dotnet);
|
||||
c.arg("--list-sdks");
|
||||
let Some((true, out)) = run_quiet(c, Duration::from_secs(20)) else { return Ok(None) };
|
||||
let Some(sdk) = dotnet::newest_sdk(&out) else {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{} needs the .NET SDK, but `dotnet --list-sdks` lists none. Install it from {}",
|
||||
spec.display,
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
};
|
||||
let pick = Http::new(&self.system_path)
|
||||
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
|
||||
match pick {
|
||||
Ok(dotnet::ToolPick::Latest) => Ok(None),
|
||||
Ok(dotnet::ToolPick::Older { version, latest, needs }) => {
|
||||
emit(InstallEvent::Line {
|
||||
text: format!(
|
||||
"{package} {latest} needs the .NET {needs} SDK, found {}; installing {version}, the newest version that runs on it",
|
||||
sdk.version
|
||||
),
|
||||
});
|
||||
Ok(Some(version))
|
||||
}
|
||||
Ok(dotnet::ToolPick::Incompatible { latest, needs }) => Err(IdeError::unavailable(format!(
|
||||
"{} {latest} requires the .NET {needs} SDK; found {}. Install it from {}",
|
||||
spec.display,
|
||||
sdk.version,
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
))),
|
||||
Err(e) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
Err(e) => {
|
||||
emit(InstallEvent::Line {
|
||||
text: format!(
|
||||
"Could not check which {package} version runs on .NET {}: {}",
|
||||
sdk.version, e.message
|
||||
),
|
||||
});
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The .NET install `dotnet` runs from: `Microsoft.NETCore.App 9.0.1 [<root>/shared/Microsoft.NETCore.App]`.
|
||||
fn dotnet_root(&self, dotnet: &Path) -> Option<PathBuf> {
|
||||
let mut c = self.command(dotnet);
|
||||
|
||||
@@ -28,11 +28,16 @@ pub const PUBLIC_NPM_REGISTRY: &str = "https://registry.npmjs.org/";
|
||||
fn failed_command(label: &str, output: &str, status: &str) -> IdeError {
|
||||
let tail: Vec<&str> = output.lines().rev().filter(|l| !l.trim().is_empty()).take(3).collect();
|
||||
let tail: Vec<&str> = tail.into_iter().rev().collect();
|
||||
failed_with(label, &tail, status)
|
||||
}
|
||||
|
||||
fn failed_with(label: &str, lines: &[impl AsRef<str>], status: &str) -> IdeError {
|
||||
let lines: Vec<&str> = lines.iter().map(AsRef::as_ref).collect();
|
||||
IdeError::new(
|
||||
ErrorKind::Io,
|
||||
format!(
|
||||
"`{label}` failed ({status}){}",
|
||||
if tail.is_empty() { String::new() } else { format!(": {}", tail.join(" / ")) }
|
||||
if lines.is_empty() { String::new() } else { format!(": {}", lines.join(" / ")) }
|
||||
),
|
||||
)
|
||||
}
|
||||
@@ -85,6 +90,25 @@ pub fn run_streamed(cmd: Command, cancel: &CancellationToken, emit: Emit) -> Ide
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
/// Like [`run_streamed`], but a failure quotes the lines `pick` finds in the output instead of
|
||||
/// the last three, when it finds any.
|
||||
pub fn run_streamed_picking(
|
||||
cmd: Command,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
pick: fn(&str) -> Vec<String>,
|
||||
) -> IdeResult<String> {
|
||||
let label = describe(&cmd);
|
||||
let (ok, output, status) = run_collect(cmd, cancel, emit)?;
|
||||
if ok {
|
||||
return Ok(output);
|
||||
}
|
||||
match pick(&output) {
|
||||
picked if picked.is_empty() => Err(failed_command(&label, &output, &status)),
|
||||
picked => Err(failed_with(&label, &picked, &status)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an `npm` / `pnpm` command against the user's configured registry first (preserving
|
||||
/// corporate mirrors, proxies, and CAs), and retries once against [`PUBLIC_NPM_REGISTRY`] when
|
||||
/// the configured registry misses the package/version or rejects auth. Preserves the primary
|
||||
|
||||
@@ -797,9 +797,14 @@ esac"#,
|
||||
assert!(!env.root.join("ruby-lsp").exists());
|
||||
}
|
||||
|
||||
/// Installs of one tool name share a slot, so parallel csharp-ls tests would join each other's install.
|
||||
#[cfg(unix)]
|
||||
static CSHARP_LS_INSTALL: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_install_into_tool_path() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
env.script(
|
||||
&env.sys,
|
||||
@@ -809,6 +814,7 @@ install) /bin/mkdir -p "$5"; printf '#!/bin/sh\necho "$DOTNET_ROOT"\n' > "$5/csh
|
||||
list) printf 'Package Id Version Commands\n----\ncsharp-ls 0.15.0 csharp-ls\n' ;;
|
||||
esac
|
||||
[ "$1" = --list-runtimes ] && echo 'Microsoft.NETCore.App 9.0.1 [/opt/dotnet/shared/Microsoft.NETCore.App]'
|
||||
[ "$1" = --list-sdks ] && echo '9.0.100 [/opt/dotnet/sdk]'
|
||||
exit 0"#,
|
||||
);
|
||||
let info = env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
@@ -820,6 +826,159 @@ exit 0"#,
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "/opt/dotnet");
|
||||
}
|
||||
|
||||
/// A fake `dotnet` with SDK `sdk` that logs `tool install` arguments to `calls`, and a fake
|
||||
/// `curl` serving csharp-ls 0.28.0 (net10.0) and 0.29.0 (net11.0) as nuget.org would.
|
||||
#[cfg(unix)]
|
||||
fn dotnet_with_nuget(env: &Env, sdk: &str, install: &str) -> PathBuf {
|
||||
let calls = env.root.parent().unwrap().join("dotnet-calls");
|
||||
env.script(
|
||||
&env.sys,
|
||||
"dotnet",
|
||||
&format!(
|
||||
r#"case "$1 $2" in
|
||||
"tool install") echo "$@" >> '{calls}'; {install} ;;
|
||||
"tool list") printf 'Package Id Version Commands\n----\ncsharp-ls 0.28.0 csharp-ls\n' ;;
|
||||
"--list-sdks ") [ -n '{sdk}' ] && echo '{sdk} [/opt/dotnet/sdk]' ;;
|
||||
esac
|
||||
exit 0"#,
|
||||
calls = calls.display(),
|
||||
),
|
||||
);
|
||||
let leaf = |v: &str| {
|
||||
format!(
|
||||
r#"{{"catalogEntry":{{"@id":"https://api.nuget.org/v3/catalog0/data/x/csharp-ls.{v}.json","version":"{v}","listed":true}}}}"#
|
||||
)
|
||||
};
|
||||
let fixtures = env.root.parent().unwrap().join("nuget");
|
||||
fs::create_dir_all(&fixtures).unwrap();
|
||||
let index = fixtures.join("index.json");
|
||||
fs::write(
|
||||
&index,
|
||||
format!(r#"{{"items":[{{"@id":"https://reg/page","items":[{},{}]}}]}}"#, leaf("0.28.0"), leaf("0.29.0")),
|
||||
)
|
||||
.unwrap();
|
||||
for (v, tfm) in [("0.28.0", "net10.0"), ("0.29.0", "net11.0")] {
|
||||
fs::write(
|
||||
fixtures.join(format!("{v}.json")),
|
||||
format!(r#"{{"packageEntries":[{{"fullName":"tools/{tfm}/any/CSharpLanguageServer.dll"}}]}}"#),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
env.script(
|
||||
&env.sys,
|
||||
"curl",
|
||||
&format!(
|
||||
r#"url=""
|
||||
while [ $# -gt 0 ]; do case "$1" in -o|-A|-H|--retry|--connect-timeout|--speed-limit|--speed-time) shift 2;; -*) shift;; *) url="$1"; shift;; esac; done
|
||||
case "$url" in
|
||||
*/registration5-semver1/csharp-ls/index.json) /bin/cat '{dir}/index.json';;
|
||||
*/csharp-ls.0.28.0.json) /bin/cat '{dir}/0.28.0.json';;
|
||||
*/csharp-ls.0.29.0.json) /bin/cat '{dir}/0.29.0.json';;
|
||||
*) exit 22;;
|
||||
esac"#,
|
||||
dir = fixtures.display()
|
||||
),
|
||||
);
|
||||
calls
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const FAKE_TOOL_INSTALL: &str =
|
||||
r#"/bin/mkdir -p "$5"; printf '#!/bin/sh\n' > "$5/csharp-ls"; /bin/chmod +x "$5/csharp-ls""#;
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_too_new_for_every_sdk_names_the_sdk_it_needs() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(&env, "6.0.300", FAKE_TOOL_INSTALL);
|
||||
let err = env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unavailable);
|
||||
assert_eq!(
|
||||
err.message,
|
||||
"csharp-ls 0.29.0 requires the .NET 11 SDK; found 6.0.300. Install it from https://dotnet.microsoft.com/download"
|
||||
);
|
||||
assert!(!calls.exists(), "dotnet tool install ran");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_falls_back_to_the_newest_version_the_sdk_runs() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(&env, "10.0.403", FAKE_TOOL_INSTALL);
|
||||
let events = Mutex::new(Vec::new());
|
||||
let emit = |e: InstallEvent| events.lock().push(e);
|
||||
let info = env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &emit).unwrap();
|
||||
assert_eq!(info.status, ToolStatus::Installed);
|
||||
assert_eq!(info.version.as_deref(), Some("0.28.0"));
|
||||
let call = fs::read_to_string(&calls).unwrap();
|
||||
assert!(call.trim_end().ends_with("--verbosity normal --version 0.28.0"), "{call}");
|
||||
let said = events.into_inner().into_iter().any(|e| {
|
||||
matches!(e, InstallEvent::Line { text } if text == "csharp-ls 0.29.0 needs the .NET 11 SDK, found 10.0.403; installing 0.28.0, the newest version that runs on it")
|
||||
});
|
||||
assert!(said);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_installs_the_latest_on_a_new_enough_sdk() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(&env, "11.0.100", FAKE_TOOL_INSTALL);
|
||||
env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let call = fs::read_to_string(&calls).unwrap();
|
||||
assert!(!call.contains("--version"), "{call}");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_without_an_sdk_is_reported_before_installing() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(&env, "", FAKE_TOOL_INSTALL);
|
||||
let err = env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert!(
|
||||
err.message.starts_with("csharp-ls needs the .NET SDK, but `dotnet --list-sdks` lists none"),
|
||||
"{}",
|
||||
err.message
|
||||
);
|
||||
assert!(!calls.exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn dotnet_tool_failure_quotes_the_nuget_error_not_the_generic_hint() {
|
||||
let _serial = CSHARP_LS_INSTALL.lock();
|
||||
let env = Env::new();
|
||||
let calls = dotnet_with_nuget(
|
||||
&env,
|
||||
"6.0.300",
|
||||
r#"echo ' 1>/tmp/x/restore.csproj : error NU1202: Package csharp-ls 0.29.0 is not compatible with net6.0 (.NETCoreApp,Version=v6.0) / any.'
|
||||
echo "Tool 'csharp-ls' failed to install. This failure may have been caused by:"
|
||||
echo '* You mistyped the name of the tool.'
|
||||
echo 'For more reasons, including package naming enforcement, visit https://aka.ms/failure-installing-tool'
|
||||
exit 1"#,
|
||||
);
|
||||
// nuget.org unreachable: the version check is skipped and the install itself fails.
|
||||
env.script(&env.sys, "curl", "exit 6");
|
||||
let events = Mutex::new(Vec::new());
|
||||
let emit = |e: InstallEvent| events.lock().push(e);
|
||||
let err = env.tools().install("csharp-ls", &langs(), &CancellationToken::new(), &emit).unwrap_err();
|
||||
assert!(calls.exists());
|
||||
assert!(
|
||||
err.message.ends_with(
|
||||
"failed (exit status: 1): error NU1202: Package csharp-ls 0.29.0 is not compatible with net6.0 (.NETCoreApp,Version=v6.0) / any."
|
||||
),
|
||||
"{}",
|
||||
err.message
|
||||
);
|
||||
let skipped = events.into_inner().into_iter().any(
|
||||
|e| matches!(e, InstallEvent::Line { text } if text.starts_with("Could not check which csharp-ls version runs on .NET 6.0.300")),
|
||||
);
|
||||
assert!(skipped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kotlin_debugger_uses_existing_release_recipe_and_language_definition() {
|
||||
let spec = registry::find("kotlin-debug-adapter").unwrap();
|
||||
|
||||
@@ -3,9 +3,45 @@ use ide_core::{IdeError, IdeResult, project_dir};
|
||||
use parking_lot::RwLock;
|
||||
use serde_json::Value as Json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{self, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use toml_edit::{DocumentMut, Item, Table, TableLike};
|
||||
|
||||
/// The UI languages the frontend ships (`LOCALES` in `src/platform/i18n.ts`).
|
||||
pub const UI_LOCALES: &[&str] = &["en", "zh", "zh-TW", "ko", "fr", "pl", "pt", "es", "tr"];
|
||||
|
||||
/// Maps an OS language tag (`tr-TR`, `fr_CA.UTF-8`, `zh-Hant-HK`) to one of [`UI_LOCALES`], English otherwise.
|
||||
pub fn ui_locale_for(language: &str) -> &'static str {
|
||||
let normalized = language.trim().to_ascii_lowercase();
|
||||
let mut parts = normalized.split(['-', '_', '.', '@']);
|
||||
let base = parts.next().unwrap_or_default();
|
||||
if base == "zh" {
|
||||
return if matches!(parts.next(), Some("tw" | "hk" | "mo" | "hant")) { "zh-TW" } else { "zh" };
|
||||
}
|
||||
UI_LOCALES.iter().copied().find(|locale| *locale == base).unwrap_or("en")
|
||||
}
|
||||
|
||||
/// Seeds `appearance.locale` from the OS language when the profile has no global settings yet.
|
||||
pub fn initialize_global_locale(config_dir: &Path, system_language: impl FnOnce() -> Option<String>) -> io::Result<()> {
|
||||
let file = config_dir.join(PROJECT_FILE);
|
||||
match std::fs::symlink_metadata(&file) {
|
||||
Ok(_) => return Ok(()),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
let mut settings = tempfile::NamedTempFile::new_in(config_dir)?;
|
||||
let mut appearance = Table::new();
|
||||
appearance["locale"] = toml_edit::value(ui_locale_for(&system_language().unwrap_or_default()));
|
||||
let mut document = DocumentMut::new();
|
||||
document["appearance"] = Item::Table(appearance);
|
||||
settings.write_all(document.to_string().as_bytes())?;
|
||||
match settings.persist_noclobber(file) {
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => Ok(()),
|
||||
Err(error) => Err(error.error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Layered settings: defaults → `<app-config>/settings.toml` → `<project>/.openidea/settings.toml`.
|
||||
/// Writes go through `toml_edit` so user comments survive.
|
||||
///
|
||||
@@ -257,7 +293,7 @@ fn set_in_document(doc: &mut DocumentMut, segments: &[&str], value: Option<toml_
|
||||
impl SettingsStore {
|
||||
pub fn load(config_dir: &Path, project_root: Option<&Path>) -> Self {
|
||||
let store = Self {
|
||||
global_file: config_dir.join("settings.toml"),
|
||||
global_file: config_dir.join(PROJECT_FILE),
|
||||
project_file: project_root.map(|r| project_dir::path(r, PROJECT_FILE)),
|
||||
effective: RwLock::new(Settings::default()),
|
||||
};
|
||||
@@ -577,6 +613,37 @@ mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn initializes_global_locale_once() {
|
||||
let config = tempfile::tempdir().unwrap();
|
||||
initialize_global_locale(config.path(), || Some("tr-TR".into())).unwrap();
|
||||
let written = std::fs::read_to_string(config.path().join("settings.toml")).unwrap();
|
||||
assert_eq!(written, "[appearance]\nlocale = \"tr\"\n");
|
||||
let store = SettingsStore::load(config.path(), None);
|
||||
assert_eq!(store.effective().appearance.locale, "tr");
|
||||
store.set(SettingsScope::Global, "appearance.locale", Json::from("en")).unwrap();
|
||||
initialize_global_locale(config.path(), || panic!("existing profiles must skip detection")).unwrap();
|
||||
assert_eq!(store.reload().appearance.locale, "en");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maps_os_languages_to_ui_locales() {
|
||||
for (language, expected) in [
|
||||
("tr-TR", "tr"),
|
||||
("fr_CA.UTF-8", "fr"),
|
||||
("pt-BR", "pt"),
|
||||
("zh-Hant-HK", "zh-TW"),
|
||||
("zh_TW.UTF-8", "zh-TW"),
|
||||
("zh-Hans-HK", "zh"),
|
||||
("zh-Hans-CN", "zh"),
|
||||
("xx-XX", "en"),
|
||||
("C", "en"),
|
||||
("", "en"),
|
||||
] {
|
||||
assert_eq!(ui_locale_for(language), expected, "{language}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_theme_named_in_a_settings_file_is_reported_for_the_notice() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -67,7 +67,7 @@ mise run dev
|
||||
|
||||
`setup` runs `pnpm install` in this worktree. `dev` and `dev:app` use the same worktree-aware launchers as the direct commands. No shell activation is needed for `mise run`.
|
||||
|
||||
Run `mise tasks` to list all six tasks. `mise run build` builds the frontend (not a desktop installer). `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
|
||||
Run `mise tasks` to list all tasks. `mise run build` builds the frontend (not a desktop installer); `mise run dogfood:build` and `mise run dogfood:install` build and locally install a grey-icon dogfood desktop app that shares settings and data with the release app. Only one of the two apps runs at a time, since they share one instance; settings written by the newer dogfood build can make an older release ignore the settings file. The dogfood app never updates itself: run `dogfood:install` again to pick up new changes. `mise run test` runs Vitest and `cargo test --workspace`; `mise run check` runs the format, lint, type and unused-code checks, then both test suites. Neither requires nextest or the plugin WASM target.
|
||||
|
||||
## Worktrees
|
||||
|
||||
|
||||
@@ -30,6 +30,8 @@ When a server is missing, opening a C# or F# file shows a "csharp-ls is not inst
|
||||
| FsAutoComplete | `dotnet tool install --tool-path` into the IDE's tools folder |
|
||||
| netcoredbg | Downloaded from the `Samsung/netcoredbg` GitHub releases. Prebuilt for macOS arm64, Linux x64 and arm64, and Windows x64. |
|
||||
|
||||
Before it installs csharp-ls or FsAutoComplete, the IDE compares the newest SDK in `dotnet --list-sdks` with the .NET version the tool's latest release on nuget.org targets. When the SDK is older, it installs the newest release that runs on it, or tells you which SDK to install.
|
||||
|
||||
A `csharp-ls`, `fsautocomplete` or `netcoredbg` already on your `PATH` (for example a global `dotnet tool install --global csharp-ls`) is used as is.
|
||||
|
||||
## The .NET tool window
|
||||
|
||||
@@ -67,7 +67,7 @@ mise run dev
|
||||
|
||||
`setup` 在当前 worktree 中执行 `pnpm install`。`dev` 和 `dev:app` 都沿用原来的启动脚本,保留 worktree 隔离。使用 `mise run` 不需要在 shell 中激活 mise。
|
||||
|
||||
运行 `mise tasks` 可以查看全部六个任务。`mise run build` 构建前端,不生成桌面安装包。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
|
||||
运行 `mise tasks` 可以查看全部任务。`mise run build` 构建前端,不生成桌面安装包;`mise run dogfood:build` 和 `mise run dogfood:install` 用于构建并在本地安装灰色图标的 dogfood 桌面版(与正式版共享设置和数据)。两者共用同一个实例,同一时间只能运行一个;较新的 dogfood 版写入的设置可能让较旧的正式版忽略整个设置文件。dogfood 版不会自动更新,需要更新时重新运行 `dogfood:install`。`mise run test` 运行 Vitest 和 `cargo test --workspace`;`mise run check` 先检查格式、代码规范、类型和未使用的代码,再运行这两套测试。两者都不需要 nextest 或插件的 WASM 目标。
|
||||
|
||||
## Worktree
|
||||
|
||||
|
||||
Loaded 100 of 353 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача