дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-11-28 05:22:23 +02:00
Порівняти коміти
90
Коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
dddef44d56 | ||
|
|
7ecccb3b75 | ||
|
|
7cbf17b10e | ||
|
|
cb0d02620d | ||
|
|
d6ca43cba4 | ||
|
|
165d4f7d76 | ||
|
|
5785ebadd8 | ||
|
|
0c67a4eea2 | ||
|
|
5e2deed81e | ||
|
|
cae7c05fb1 | ||
|
|
be83458161 | ||
|
|
661124d0d4 | ||
|
|
0dae111b2d | ||
|
|
61d269045b | ||
|
|
266d85fa1a | ||
|
|
f964d79e10 | ||
|
|
4a3eacff62 | ||
|
|
aebc2fe02d | ||
|
|
9b63aa9526 | ||
|
|
df07073886 | ||
|
|
3433ee951b | ||
|
|
8f5b281486 | ||
|
|
43aee8058c | ||
|
|
4016c3c905 | ||
|
|
e6cb7df653 | ||
|
|
2a26c82357 | ||
|
|
66f0bce92f | ||
|
|
dfbd13e2af | ||
|
|
944b57dead | ||
|
|
5bcb37492f | ||
|
|
d5bde9af67 | ||
|
|
5b3e2b7a3d | ||
|
|
dbb6fa51c3 | ||
|
|
3d1769ef00 | ||
|
|
c966429f92 | ||
|
|
dfcc05dd41 | ||
|
|
d41feefc07 | ||
|
|
f0fe910017 | ||
|
|
b932220b41 | ||
|
|
bcad8f61cb | ||
|
|
2cdcb888cf | ||
|
|
9ed0fd9fa7 | ||
|
|
fe76dc4573 | ||
|
|
45a75f782a | ||
|
|
bd1fd011e4 | ||
|
|
b44015b2ce | ||
|
|
0cce0a9840 | ||
|
|
db8224f74e | ||
|
|
b075f5de2a | ||
|
|
3240164840 | ||
|
|
f70f362a3d | ||
|
|
806bb4c78d | ||
|
|
57094bc285 | ||
|
|
a5e0c41663 | ||
|
|
77071238a0 | ||
|
|
64097d3c20 | ||
|
|
cf0e57e5df | ||
|
|
703cf23296 | ||
|
|
a88073d6fb | ||
|
|
4b5745c1b6 | ||
|
|
4667c81e6b | ||
|
|
cea9d863f9 | ||
|
|
5fa953eddd | ||
|
|
031f1acd07 | ||
|
|
add23fe97f | ||
|
|
3d2b0946de | ||
|
|
6c7282b442 | ||
|
|
1f79a7f805 | ||
|
|
3d1eaf71e4 | ||
|
|
138209c627 | ||
|
|
b283d352b7 | ||
|
|
f7f9dabe2b | ||
|
|
787d4fbcfa | ||
|
|
3fbd0e05a5 | ||
|
|
2d021a3414 | ||
|
|
cd7582c5e5 | ||
|
|
d16b852054 | ||
|
|
06223d9bd7 | ||
|
|
dcd81d601b | ||
|
|
762ebecd86 | ||
|
|
fd4efff6e3 | ||
|
|
8968974f42 | ||
|
|
5f083ae47c | ||
|
|
83b14b4329 | ||
|
|
74eefd6116 | ||
|
|
a96c70f2a7 | ||
|
|
304503b9f1 | ||
|
|
06cf8fb16a | ||
|
|
521e00d075 | ||
|
|
b4cad6ec1b |
No files matched your search
@@ -3,7 +3,8 @@ name: Homebrew
|
||||
# Updates the cask in the project tap, l0ng-ai/homebrew-tap (scripts/homebrew-cask.ts), so
|
||||
# `brew install --cask l0ng-ai/tap/openidea` installs the new release. Release runs it after
|
||||
# publishing; run it by hand to write the cask of an existing tag again. Skipped for prereleases
|
||||
# and without the HOMEBREW_TAP_TOKEN secret (contents: write on l0ng-ai/homebrew-tap).
|
||||
# and without the HOMEBREW_TAP_DEPLOY_KEY secret (the private half of a write deploy key on
|
||||
# l0ng-ai/homebrew-tap).
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
@@ -27,17 +28,17 @@ jobs:
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
TAP: l0ng-ai/homebrew-tap
|
||||
HOMEBREW_TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
HOMEBREW_TAP_DEPLOY_KEY: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- name: Check tag and token
|
||||
- name: Check tag and deploy key
|
||||
id: check
|
||||
run: |
|
||||
if [[ ! "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "::notice::$TAG is not a stable release: the cask stays as is"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
elif [ -z "$HOMEBREW_TAP_TOKEN" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_TOKEN unset: not updating the cask for $TAG"
|
||||
elif [ -z "$HOMEBREW_TAP_DEPLOY_KEY" ]; then
|
||||
echo "::notice::HOMEBREW_TAP_DEPLOY_KEY unset: not updating the cask for $TAG"
|
||||
echo "skip=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- uses: actions/checkout@v5
|
||||
@@ -47,7 +48,7 @@ jobs:
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
with:
|
||||
repository: ${{ env.TAP }}
|
||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
||||
ssh-key: ${{ secrets.HOMEBREW_TAP_DEPLOY_KEY }}
|
||||
path: tap
|
||||
- uses: actions/setup-node@v5
|
||||
if: steps.check.outputs.skip != 'true'
|
||||
|
||||
@@ -179,7 +179,7 @@ jobs:
|
||||
with: { tag: "${{ github.event.inputs.tag || github.ref_name }}" }
|
||||
secrets: inherit
|
||||
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_TOKEN.
|
||||
# The cask in l0ng-ai/homebrew-tap; skipped for prereleases and without HOMEBREW_TAP_DEPLOY_KEY.
|
||||
homebrew:
|
||||
needs: publish
|
||||
uses: ./.github/workflows/homebrew.yml
|
||||
|
||||
Створено
+247
-197
File diff suppressed because it is too large.
Load diff
+2
-2
@@ -5,7 +5,7 @@ members = ["crates/*", "src-tauri"]
|
||||
exclude = ["sdk", "plugins"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.53"
|
||||
version = "0.1.54"
|
||||
edition = "2024"
|
||||
rust-version = "1.96"
|
||||
license = "Apache-2.0"
|
||||
@@ -108,7 +108,7 @@ jupyter-zmq-client = { version = "=2.0.0", default-features = false, features =
|
||||
jupyter-protocol = "=2.0.3"
|
||||
zeromq = { version = "0.6", default-features = false, features = ["tokio-runtime", "tcp-transport"] }
|
||||
lsp-types = "0.97"
|
||||
gix = { version = "0.89", default-features = false }
|
||||
gix = { version = "0.90", default-features = false }
|
||||
portable-pty = "0.9"
|
||||
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "http2", "charset", "socks", "gzip", "deflate", "brotli"] }
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
|
||||
@@ -25,7 +25,7 @@ pub(crate) async fn run(shared: &Arc<Shared>, spec: &ProviderSpec, model: Option
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
&& crate::provider::is_copilot_provider(&spec.id)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env)
|
||||
&& crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &shared.paths.project_root)
|
||||
&& super::auth_required(0, &err) =>
|
||||
{
|
||||
let retry = run_once(shared, spec, true, model).await;
|
||||
|
||||
@@ -283,6 +283,20 @@ impl AgentCatalogs {
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears a failed discovery cooldown so a fresh sign-in can immediately load models.
|
||||
pub(crate) fn clear_failed_cooldown(&self, shared: &Shared, provider: &str) {
|
||||
let key = Self::key(shared, provider);
|
||||
let mut state = self.state.lock();
|
||||
if let Some(entry) = state.entries.get_mut(&key)
|
||||
&& entry.flight.is_none()
|
||||
&& entry.error.is_some()
|
||||
{
|
||||
entry.completed = None;
|
||||
entry.retry_at_ms = None;
|
||||
entry.error = None;
|
||||
}
|
||||
}
|
||||
|
||||
fn snapshot(&self, shared: &Shared, provider: &str, entry: &Entry) -> AgentModelCatalog {
|
||||
let catalog = entry.catalog.clone().unwrap_or_default();
|
||||
let model_failure = entry.requested_model.as_ref().and_then(|model| entry.model_failures.get(model));
|
||||
@@ -613,6 +627,40 @@ impl crate::AgentManager {
|
||||
let spec = self.shared.spec(provider).ok_or_else(|| IdeError::invalid(format!("unknown agent {provider}")))?;
|
||||
Ok(self.shared.paths.catalogs.request(&self.shared, spec, force, model).0)
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged `account` selection (`""` = Copilot CLI
|
||||
/// default) without mutating `models.json` or broadcasting to active sessions before Apply.
|
||||
pub async fn preview_copilot_models(&self, account: &str, model: Option<&str>) -> IdeResult<AgentModelCatalog> {
|
||||
let mut spec = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets())
|
||||
.into_iter()
|
||||
.find(|p| p.id == "copilot")
|
||||
.ok_or_else(|| IdeError::not_found("unknown agent 'copilot'"))?;
|
||||
spec.env.retain(|(name, _)| name != provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
let account = account.trim();
|
||||
if !account.is_empty() {
|
||||
spec.env.push((provider::COPILOT_GITHUB_ACCOUNT_ENV.into(), account.to_owned()));
|
||||
}
|
||||
match discover(&self.shared, spec, model).await {
|
||||
Ok(found) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: self.shared.config_for_new_task(found.config, "copilot"),
|
||||
thought_levels: self.shared.thought_levels_for_new_task(found.levels, "copilot"),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: Some(self.shared.paths.catalogs.epoch_ms()),
|
||||
retry_at_ms: None,
|
||||
error: None,
|
||||
}),
|
||||
Err(error) => Ok(AgentModelCatalog {
|
||||
provider: "copilot".into(),
|
||||
config: Vec::new(),
|
||||
thought_levels: BTreeMap::new(),
|
||||
refreshing: false,
|
||||
refreshed_at_ms: None,
|
||||
retry_at_ms: None,
|
||||
error: Some(error),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn discover(
|
||||
|
||||
@@ -33,6 +33,7 @@ pub use catalogs::AgentCatalogs;
|
||||
pub use cli_update::{AgentCliOffer, AgentCliUpdateResult};
|
||||
pub use external::ExternalSession;
|
||||
pub use model::*;
|
||||
pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch};
|
||||
pub use skill_installer::{
|
||||
InstallRemoteSkillRequest, RemoteSkillBrowseResult, RemoteSkillCandidate, RemoteSkillFile, RemoteSkillPreview,
|
||||
SkillScanWarning, SkillScanWarningKind,
|
||||
@@ -53,6 +54,49 @@ use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Resolves agent `id`'s interactive sign-in command without an open project.
|
||||
pub fn login_launch_without_project(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
id: &str,
|
||||
) -> IdeResult<LoginLaunch> {
|
||||
let spec = provider::load(custom_agents_dir, secrets)
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
spec.login_launch(cwd, None)
|
||||
.ok_or_else(|| IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name)))
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status_with(
|
||||
custom_agents_dir: Option<&Path>,
|
||||
secrets: Option<&dyn EnvSecrets>,
|
||||
cwd: &Path,
|
||||
) -> CopilotAuthStatus {
|
||||
let copilot_spec = provider::load(custom_agents_dir, secrets).into_iter().find(|p| p.id == "copilot");
|
||||
let cwd_buf = cwd.to_path_buf();
|
||||
let cli_fut = async move {
|
||||
let spec = copilot_spec?;
|
||||
native::copilot::probe_auth_status(spec, cwd_buf).await
|
||||
};
|
||||
let gh_fut = tokio::task::spawn_blocking(provider::gh_authenticated_accounts);
|
||||
let (cli, gh) = tokio::join!(cli_fut, gh_fut);
|
||||
let (gh_installed, gh_accounts) = gh.unwrap_or((false, Vec::new()));
|
||||
match cli {
|
||||
Some(cli) => CopilotAuthStatus {
|
||||
authenticated: cli.authenticated,
|
||||
login: cli.login,
|
||||
auth_type: cli.auth_type,
|
||||
status_message: cli.status_message,
|
||||
gh_installed,
|
||||
gh_accounts,
|
||||
},
|
||||
None => CopilotAuthStatus { gh_installed, gh_accounts, ..CopilotAuthStatus::default() },
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives the events of one project's tasks.
|
||||
pub type AgentSink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
|
||||
@@ -201,6 +245,8 @@ struct Shared {
|
||||
providers: RwLock<Vec<provider::ProviderSpec>>,
|
||||
/// Last probe of each provider.
|
||||
probes: Mutex<HashMap<String, AgentProbe>>,
|
||||
/// `type: "terminal"` login arguments reported during `initialize`, by provider id.
|
||||
terminal_auth_args: RwLock<HashMap<String, Vec<String>>>,
|
||||
/// Copilot CLI installs where `--headless` failed and fell back to `--acp`.
|
||||
copilot_acp_fallback: Mutex<HashSet<CopilotBinaryKey>>,
|
||||
/// [`IDLE_RELEASE`], in milliseconds (shorter in tests).
|
||||
@@ -706,6 +752,7 @@ impl AgentManager {
|
||||
known,
|
||||
providers,
|
||||
probes: Mutex::new(HashMap::new()),
|
||||
terminal_auth_args: RwLock::new(HashMap::new()),
|
||||
copilot_acp_fallback: Mutex::new(HashSet::new()),
|
||||
idle_release_ms: AtomicU64::new(IDLE_RELEASE.as_millis() as u64),
|
||||
mcp_servers_hook: RwLock::new(None),
|
||||
@@ -785,16 +832,24 @@ impl AgentManager {
|
||||
*self.shared.git_executable.write() = Some(hook);
|
||||
}
|
||||
|
||||
/// Directory holding linked Git worktrees created for agent tasks of this project.
|
||||
pub fn worktrees_dir(&self) -> &Path {
|
||||
&self.shared.paths.worktrees_dir
|
||||
}
|
||||
|
||||
/// The agents (custom ones re-read), whether each is installed, and what they offered last time.
|
||||
pub fn providers(&self) -> Vec<AgentProvider> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let in_use: std::collections::HashSet<String> =
|
||||
self.tasks.read().values().map(|t| t.state.lock().task.provider.clone()).collect();
|
||||
let terminal_auth = self.shared.terminal_auth_args.read();
|
||||
let list = specs
|
||||
.iter()
|
||||
.filter(|p| !provider::is_unlisted(p) || in_use.contains(&p.id))
|
||||
.map(|p| {
|
||||
let mut info = provider::describe(p);
|
||||
info.can_sign_in =
|
||||
p.can_sign_in(&self.shared.paths.project_root, terminal_auth.get(&p.id).map(Vec::as_slice));
|
||||
let catalog = self.shared.paths.catalogs.cached(&self.shared, &p.id);
|
||||
info.config = self.shared.config_for_new_task(catalog.config, &p.id);
|
||||
info.thought_levels = self.shared.thought_levels_for_new_task(catalog.thought_levels, &p.id);
|
||||
@@ -802,6 +857,7 @@ impl AgentManager {
|
||||
info
|
||||
})
|
||||
.collect();
|
||||
drop(terminal_auth);
|
||||
let mut prev = self.shared.providers.write();
|
||||
let mut probes = self.shared.probes.lock();
|
||||
probes.retain(|id, _| {
|
||||
@@ -815,6 +871,35 @@ impl AgentManager {
|
||||
list
|
||||
}
|
||||
|
||||
/// Resolves the interactive sign-in command for agent `id`.
|
||||
pub fn login_launch(&self, id: &str) -> IdeResult<LoginLaunch> {
|
||||
let specs = provider::load(self.shared.paths.custom_agents_dir.as_deref(), self.shared.env_secrets());
|
||||
let spec = specs
|
||||
.into_iter()
|
||||
.find(|p| p.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("unknown agent '{id}'")))?;
|
||||
let terminal_args = self.shared.terminal_auth_args.read().get(id).cloned();
|
||||
let launch = spec.login_launch(&self.shared.paths.project_root, terminal_args.as_deref()).ok_or_else(|| {
|
||||
IdeError::unavailable(format!("{} cannot be signed in directly from OpenIDEA", spec.name))
|
||||
})?;
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, id);
|
||||
Ok(launch)
|
||||
}
|
||||
|
||||
/// Queries Copilot's default CLI sign-in status alongside authenticated `gh` accounts.
|
||||
pub async fn copilot_auth_status(&self) -> CopilotAuthStatus {
|
||||
let status = copilot_auth_status_with(
|
||||
self.shared.paths.custom_agents_dir.as_deref(),
|
||||
self.shared.env_secrets(),
|
||||
&self.shared.paths.project_root,
|
||||
)
|
||||
.await;
|
||||
if status.authenticated || !status.gh_accounts.is_empty() {
|
||||
self.shared.paths.catalogs.clear_failed_cooldown(&self.shared, "copilot");
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// Overrides built-in `id`'s command with `command` (the driver and arguments stay
|
||||
/// the built-in's) through its agent file, or returns it to auto-detection with `None`.
|
||||
pub fn set_builtin_command(&self, id: &str, command: Option<String>) -> IdeResult<()> {
|
||||
@@ -837,7 +922,9 @@ impl AgentManager {
|
||||
let Some(dir) = self.shared.paths.custom_agents_dir.clone() else {
|
||||
return Err(IdeError::unavailable("there is no custom agents directory"));
|
||||
};
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)
|
||||
provider::set_builtin_env(&dir, self.shared.env_secrets(), id, env)?;
|
||||
self.shared.paths.catalogs.evict_if_idle(&self.shared, id);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
@@ -3509,6 +3596,14 @@ impl Task {
|
||||
let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message));
|
||||
SessionOpenError { message: self.describe(e), allow_acp_fallback: !is_auth }
|
||||
})?;
|
||||
if let Some(args) = init.auth_methods.iter().find_map(|method| {
|
||||
if method.get("type").and_then(Value::as_str) != Some("terminal") {
|
||||
return None;
|
||||
}
|
||||
method.get("args")?.as_array()?.iter().map(|v| v.as_str().map(str::to_owned)).collect::<Option<Vec<_>>>()
|
||||
}) {
|
||||
self.shared.terminal_auth_args.write().insert(provider_id.to_owned(), args);
|
||||
}
|
||||
let sign_in_message = spec.sign_in_message(&init.auth_methods);
|
||||
let can_load = init.load_session();
|
||||
let (capabilities, embedded) = capabilities_of(&init);
|
||||
|
||||
@@ -623,6 +623,9 @@ pub struct AgentProvider {
|
||||
pub command_read_only_reason: Option<AgentCommandReadOnlyReason>,
|
||||
/// Whether the command was found (on `PATH`).
|
||||
pub installed: bool,
|
||||
/// Whether OpenIDEA can run this agent's sign-in flow directly in an embedded terminal.
|
||||
#[serde(default)]
|
||||
pub can_sign_in: bool,
|
||||
/// The built-in command can be owned by a global npm package.
|
||||
#[serde(default)]
|
||||
pub can_check_cli_update: bool,
|
||||
@@ -647,6 +650,34 @@ pub enum AgentCommandReadOnlyReason {
|
||||
CustomAgent,
|
||||
}
|
||||
|
||||
/// An authenticated `github.com` account stored in GitHub CLI (`gh`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhAuthAccount {
|
||||
pub login: String,
|
||||
pub active: bool,
|
||||
}
|
||||
|
||||
/// GitHub Copilot's default sign-in status alongside the accounts available through `gh`.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CopilotAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
pub gh_installed: bool,
|
||||
pub gh_accounts: Vec<GhAuthAccount>,
|
||||
}
|
||||
|
||||
/// Output and completion of an interactive sign-in PTY started by the IDE.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum AgentLoginEvent {
|
||||
Output { data: String },
|
||||
Exited { code: Option<i32> },
|
||||
}
|
||||
|
||||
/// Where an agent comes from.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
|
||||
@@ -1481,14 +1481,13 @@ fn stop_reason(turn: &Value, last_error: Option<Value>, rate_limits: Option<&Val
|
||||
let e = turn.get("error").filter(|e| !e.is_null()).cloned().or(last_error).unwrap_or(json!({}));
|
||||
let message = translate::error_message(&e);
|
||||
return match translate::classify(&e, rate_limits) {
|
||||
Failure::Refusal => Ok(json!({ "stopReason": "refusal" })),
|
||||
Failure::UsageLimit(resets) => Err(ResponseError {
|
||||
code: codes::INTERNAL_ERROR,
|
||||
message,
|
||||
data: Some(json!({ "openidea": { "usageLimit": { "resetsAtMs": resets } } })),
|
||||
}),
|
||||
Failure::Auth => Err(error(AUTH_REQUIRED, format!("Codex authentication failed: {message}"))),
|
||||
Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
Failure::Refusal | Failure::Other => Err(error(codes::INTERNAL_ERROR, message)),
|
||||
};
|
||||
}
|
||||
_ => "end_turn",
|
||||
|
||||
@@ -455,6 +455,90 @@ fn failures_are_classified() {
|
||||
assert_eq!(stop_reason(&json!({"status": "interrupted"}), None, None).unwrap(), json!({"stopReason": "cancelled"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turns_preserve_codex_error_diagnostics() {
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
let expected = "This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy";
|
||||
for (turn_error, last_error) in [(policy.clone(), None), (Value::Null, Some(policy.clone()))] {
|
||||
let failure = stop_reason(&json!({ "status": "failed", "error": turn_error }), last_error, None).unwrap_err();
|
||||
assert_eq!(failure.code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
// A completed turn's own error wins over an older error notification.
|
||||
let failure = stop_reason(
|
||||
&json!({ "status": "failed", "error": policy }),
|
||||
Some(json!({ "message": "An earlier retry failed.", "codexErrorInfo": "other" })),
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(failure.message, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_turn_diagnostics_include_string_and_structured_error_codes() {
|
||||
for (value, expected) in [
|
||||
(
|
||||
json!({ "message": "Context is full.", "codexErrorInfo": "contextWindowExceeded" }),
|
||||
"Context is full.\nCodex error: contextWindowExceeded",
|
||||
),
|
||||
(
|
||||
json!({ "message": "The stream disconnected.", "codexErrorInfo": { "responseStreamDisconnected": { "httpStatusCode": 502 } } }),
|
||||
"The stream disconnected.\nCodex error: responseStreamDisconnected (HTTP 502)",
|
||||
),
|
||||
(
|
||||
json!({ "message": "Failed\nbecause", "additionalDetails": "because", "codexErrorInfo": null }),
|
||||
"Failed\nbecause",
|
||||
),
|
||||
(
|
||||
json!({ "message": " ", "additionalDetails": " Details ", "codexErrorInfo": "cyberPolicy" }),
|
||||
"Codex failed\nDetails\nCodex error: cyberPolicy",
|
||||
),
|
||||
(json!({ "message": "Failed", "codexErrorInfo": "" }), "Failed"),
|
||||
(json!({}), "Codex failed"),
|
||||
] {
|
||||
assert_eq!(error_message(&value), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn policy_failure_is_forwarded_over_acp_with_its_original_diagnostics() {
|
||||
for notification_only in [false, true] {
|
||||
let mut transcript = load(Scenario::UsageLimit.file());
|
||||
let policy = json!({
|
||||
"message": "This content was flagged for possible cybersecurity risk.",
|
||||
"additionalDetails": "Contact support if this is unexpected.",
|
||||
"codexErrorInfo": "cyberPolicy"
|
||||
});
|
||||
for (out, frame) in &mut transcript.frames {
|
||||
if *out {
|
||||
continue;
|
||||
}
|
||||
match frame["method"].as_str() {
|
||||
Some("error") => frame["params"]["error"] = policy.clone(),
|
||||
Some("turn/completed") => {
|
||||
frame["params"]["turn"]["error"] = if notification_only { Value::Null } else { policy.clone() }
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (results, _client, _frames, _meta, _codex) = replay_transcript(Scenario::Simple, transcript).await;
|
||||
match result(&results, "prompt") {
|
||||
Err(RpcError::Server { code, message, .. }) => {
|
||||
assert_eq!(*code, codes::INTERNAL_ERROR);
|
||||
assert_eq!(
|
||||
message,
|
||||
"This content was flagged for possible cybersecurity risk.\nContact support if this is unexpected.\nCodex error: cyberPolicy"
|
||||
);
|
||||
}
|
||||
response => panic!("the failed turn must reach the task as an error, got {response:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approvals_offer_what_codex_offers_and_always_a_decline() {
|
||||
let params = json!({"availableDecisions": ["accept",
|
||||
|
||||
@@ -740,7 +740,7 @@ pub(super) enum Failure {
|
||||
UsageLimit(Option<f64>),
|
||||
/// Signed out or refused.
|
||||
Auth,
|
||||
/// The model declined.
|
||||
/// The server blocked the turn under a safety policy.
|
||||
Refusal,
|
||||
Other,
|
||||
}
|
||||
@@ -780,13 +780,27 @@ fn resets_at(rate_limits: Option<&Value>) -> Option<f64> {
|
||||
exhausted.map(|s| s * 1000.0)
|
||||
}
|
||||
|
||||
/// The text a failed turn reports: codex's message, with its details.
|
||||
/// The text a failed turn reports: Codex's message, details and diagnostic code.
|
||||
pub(super) fn error_message(error: &Value) -> String {
|
||||
let message = error.get("message").and_then(Value::as_str).unwrap_or("Codex failed").trim();
|
||||
match error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty()) {
|
||||
Some(details) if !message.contains(details) => format!("{message}\n{details}"),
|
||||
_ => message.to_owned(),
|
||||
let original =
|
||||
error.get("message").and_then(Value::as_str).map(str::trim).filter(|m| !m.is_empty()).unwrap_or("Codex failed");
|
||||
let mut message = original.to_owned();
|
||||
if let Some(details) =
|
||||
error.get("additionalDetails").and_then(Value::as_str).map(str::trim).filter(|d| !d.is_empty())
|
||||
&& !original.contains(details)
|
||||
{
|
||||
message.push('\n');
|
||||
message.push_str(details);
|
||||
}
|
||||
let info = error.get("codexErrorInfo").unwrap_or(&Value::Null);
|
||||
let code = info.as_str().or_else(|| info.as_object()?.keys().next().map(String::as_str));
|
||||
if let Some(code) = code.map(str::trim).filter(|c| !c.is_empty()) {
|
||||
message.push_str(&format!("\nCodex error: {code}"));
|
||||
if let Some(status) = info.get(code).and_then(|details| details.get("httpStatusCode")).and_then(Value::as_u64) {
|
||||
message.push_str(&format!(" (HTTP {status})"));
|
||||
}
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// One choice of an approval: what ACP shows and what codex gets back.
|
||||
|
||||
@@ -114,7 +114,7 @@ pub(crate) fn is_missing_binary_error(err: &std::io::Error) -> bool {
|
||||
pub(crate) async fn discover(spec: ProviderSpec, cwd: PathBuf) -> Result<Discovered, DiscoverError> {
|
||||
tokio::time::timeout(DISCOVER_TIMEOUT, async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env);
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
match discover_once(spec.clone(), cwd.clone(), prefer_stored).await {
|
||||
Err(err)
|
||||
if !prefer_stored
|
||||
@@ -185,6 +185,78 @@ async fn discover_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) ->
|
||||
res
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct CliAuthStatus {
|
||||
pub authenticated: bool,
|
||||
pub login: Option<String>,
|
||||
pub auth_type: Option<String>,
|
||||
pub status_message: Option<String>,
|
||||
}
|
||||
|
||||
/// Queries `auth.getStatus` on Copilot's headless server (ignoring any IDE-selected `gh`
|
||||
/// account override so the UI can show what the "Default" account resolves to).
|
||||
pub(crate) async fn probe_auth_status(mut spec: ProviderSpec, cwd: PathBuf) -> Option<CliAuthStatus> {
|
||||
spec.env.retain(|(name, _)| name != crate::provider::COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let prefer_stored = crate::provider::prefer_stored_copilot_auth();
|
||||
let has_ambient = crate::provider::has_unconfigured_copilot_ambient_token(&spec.env, &cwd);
|
||||
let first = probe_auth_once(spec.clone(), cwd.clone(), prefer_stored).await;
|
||||
if !prefer_stored
|
||||
&& has_ambient
|
||||
&& first.as_ref().is_none_or(|s| !s.authenticated)
|
||||
&& let Some(retry) = probe_auth_once(spec, cwd, true).await
|
||||
{
|
||||
if retry.authenticated {
|
||||
crate::provider::mark_prefer_stored_copilot_auth();
|
||||
}
|
||||
return Some(retry);
|
||||
}
|
||||
first
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
async fn probe_auth_once(spec: ProviderSpec, cwd: PathBuf, strip_ambient: bool) -> Option<CliAuthStatus> {
|
||||
let launch = tokio::task::spawn_blocking({
|
||||
let cwd = cwd.clone();
|
||||
move || spec.resolve_for_launch_with_copilot_env(&cwd, strip_ambient)
|
||||
})
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
let cwd = dunce::canonicalize(&cwd).unwrap_or(cwd);
|
||||
let args = headless_args(&launch.args);
|
||||
let peer = Peer::spawn_framed(
|
||||
&launch.command,
|
||||
&args,
|
||||
&cwd,
|
||||
&launch.env,
|
||||
Arc::new(ide_jsonrpc::NoopHandler),
|
||||
Box::new(|_| {}),
|
||||
Framing::ContentLength,
|
||||
)
|
||||
.ok()?;
|
||||
let res = async {
|
||||
handshake(&peer).await.ok()?;
|
||||
let auth: Value = peer.request("auth.getStatus", json!({}), None).await.ok()?;
|
||||
let authenticated = auth.get("isAuthenticated").and_then(Value::as_bool).unwrap_or(false);
|
||||
let str_field = |key: &str| {
|
||||
auth.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)
|
||||
};
|
||||
Some(CliAuthStatus {
|
||||
authenticated,
|
||||
login: str_field("login"),
|
||||
auth_type: str_field("authType"),
|
||||
status_message: str_field("statusMessage"),
|
||||
})
|
||||
}
|
||||
.await;
|
||||
peer.kill();
|
||||
res
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn attach(
|
||||
client: Arc<dyn Handler>,
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
//! `<config>/agents/<id>.toml` (written by hand, or by installing one from the ACP
|
||||
//! Registry, see `registry`).
|
||||
|
||||
use crate::{AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets};
|
||||
use crate::{
|
||||
AcpImportOutcome, AgentCommandReadOnlyReason, AgentProvider, AgentSource, CustomAgentInput, EnvSecrets,
|
||||
GhAuthAccount,
|
||||
};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
@@ -73,7 +76,7 @@ const BUILTIN: &[(&str, &str, Driver, &[&str], &str)] = &[
|
||||
"GitHub Copilot",
|
||||
Driver::Copilot,
|
||||
&["copilot", "--headless", "--no-auto-update", "--stdio"],
|
||||
"Run `copilot` in a terminal and sign in.",
|
||||
"Run `copilot login` in a terminal.",
|
||||
),
|
||||
("cursor", "Cursor", Driver::Acp, &["cursor-agent", "acp"], "Run `cursor-agent login` in a terminal."),
|
||||
("opencode", "OpenCode", Driver::Acp, &["opencode", "acp"], "Run `opencode auth login` in a terminal."),
|
||||
@@ -151,12 +154,26 @@ impl ProviderSpec {
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Result<Self, String> {
|
||||
let account = is_copilot_provider(&self.id).then(|| copilot_github_account(&self.env)).flatten();
|
||||
let is_copilot = is_copilot_provider(&self.id);
|
||||
let account = is_copilot.then(|| copilot_github_account(&self.env)).flatten();
|
||||
let explicit_copilot_token =
|
||||
self.env.iter().any(|(name, value)| name == "COPILOT_GITHUB_TOKEN" && !value.is_empty());
|
||||
let mut resolved = self.resolve_for_launch_base(cwd, strip_ambient_tokens || account.is_some());
|
||||
if let Some(account) = account {
|
||||
let token = github_token_for_account(&account)?;
|
||||
// Keep any project-scoped `GH_TOKEN` untouched so `gh` commands inside Copilot's
|
||||
// shell use the project's GitHub account while `COPILOT_GITHUB_TOKEN` bills `account`.
|
||||
resolved.env.retain(|(name, _)| !AMBIENT_COPILOT_AUTH_VARS.contains(&name.as_str()));
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), token));
|
||||
} else if is_copilot
|
||||
&& !strip_ambient_tokens
|
||||
&& !explicit_copilot_token
|
||||
&& ide_core::project_env::github_token(cwd).is_some()
|
||||
&& let Some(default_token) = default_github_token()
|
||||
{
|
||||
// A project-scoped `GH_TOKEN` targets repository/PR commands, not Copilot model
|
||||
// billing: pin `COPILOT_GITHUB_TOKEN` to the user's global `gh` account when present.
|
||||
resolved.env.push(("COPILOT_GITHUB_TOKEN".into(), default_token));
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
@@ -166,7 +183,7 @@ impl ProviderSpec {
|
||||
self.command = crate::native::newest_install(&self.command);
|
||||
}
|
||||
if is_copilot_provider(&self.id) {
|
||||
self.env = sanitized_copilot_env(&self.env, strip_ambient_tokens);
|
||||
self.env = sanitized_copilot_env(&self.env, cwd, strip_ambient_tokens);
|
||||
self.env.retain(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV);
|
||||
}
|
||||
let program = ide_jsonrpc::resolve_spawn_program(&self.command, &self.env);
|
||||
@@ -176,6 +193,80 @@ impl ProviderSpec {
|
||||
.into_owned();
|
||||
self
|
||||
}
|
||||
|
||||
/// Resolves the executable, arguments, and environment to run this agent's interactive
|
||||
/// sign-in flow directly in an IDE PTY without shell quoting.
|
||||
pub(crate) fn login_launch(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> Option<LoginLaunch> {
|
||||
let search = ide_core::tool_path::search_path();
|
||||
let resolve_exe = |cmd: &str, env: &[(String, String)]| -> Option<PathBuf> {
|
||||
let spawned = ide_jsonrpc::resolve_spawn_program(cmd, env);
|
||||
let candidate =
|
||||
if spawned.components().count() > 1 && !spawned.is_absolute() { cwd.join(&spawned) } else { spawned };
|
||||
if candidate.is_absolute() && is_executable(&candidate) {
|
||||
return Some(candidate);
|
||||
}
|
||||
ide_core::tool_path::find_command(&candidate.to_string_lossy(), &search, cwd)
|
||||
};
|
||||
|
||||
if let Some((separate_cmd, separate_args)) = match self.id.as_str() {
|
||||
"claude-acp" => Some(("claude", &[][..])),
|
||||
"codex-acp" => Some(("codex", &["login"][..])),
|
||||
"vibe" => Some(("vibe", &[][..])),
|
||||
_ => None,
|
||||
} {
|
||||
let program = resolve_exe(separate_cmd, &self.env)?;
|
||||
return Some(LoginLaunch {
|
||||
program,
|
||||
args: separate_args.iter().map(|s| (*s).to_owned()).collect(),
|
||||
env: self.env.iter().cloned().collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(builtin) = builtin_spec(&self.id) {
|
||||
let args = terminal_auth_args
|
||||
.filter(|_| matches!(self.source, AgentSource::Registry { .. }))
|
||||
.map(<[String]>::to_vec)
|
||||
.or_else(|| builtin_login_args(&builtin))?;
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
let mut env: BTreeMap<String, String> = resolved.env.into_iter().collect();
|
||||
if is_copilot_provider(&self.id) {
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
}
|
||||
return Some(LoginLaunch { program, args, env });
|
||||
}
|
||||
|
||||
let args = terminal_auth_args?.to_vec();
|
||||
let resolved = self.clone().resolve_for_launch_base(cwd, true);
|
||||
let program = resolve_exe(&resolved.command, &resolved.env)?;
|
||||
Some(LoginLaunch { program, args, env: resolved.env.into_iter().collect() })
|
||||
}
|
||||
|
||||
pub(crate) fn can_sign_in(&self, cwd: &Path, terminal_auth_args: Option<&[String]>) -> bool {
|
||||
self.login_launch(cwd, terminal_auth_args).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct LoginLaunch {
|
||||
pub program: PathBuf,
|
||||
pub args: Vec<String>,
|
||||
pub env: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
fn builtin_login_args(builtin: &ProviderSpec) -> Option<Vec<String>> {
|
||||
let prefix = format!("Run `{}", builtin.command);
|
||||
let rest = builtin.login_hint.strip_prefix(&prefix)?.strip_prefix([' ', '`']);
|
||||
match rest {
|
||||
Some(after_space) if builtin.login_hint[prefix.len()..].starts_with(' ') => {
|
||||
let (args, _) = after_space.split_once('`')?;
|
||||
Some(args.split_whitespace().map(str::to_owned).collect())
|
||||
}
|
||||
Some(_) => Some(Vec::new()),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
const AMBIENT_COPILOT_AUTH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
@@ -194,16 +285,26 @@ pub(crate) fn copilot_github_account(env: &[(String, String)]) -> Option<String>
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn is_valid_github_login(account: &str) -> bool {
|
||||
let bytes = account.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
let path = ide_core::process::shell_env()
|
||||
.find(|(name, _)| name == "PATH")
|
||||
.map(|(_, value)| value)
|
||||
.or_else(|| ide_core::process::host_var_os("PATH"));
|
||||
let program = path
|
||||
.as_deref()
|
||||
.and_then(|path| ide_core::process::find_executable("gh", path))
|
||||
if !is_valid_github_login(account) {
|
||||
return Err(format!("Invalid GitHub account login: {account}"));
|
||||
}
|
||||
let program = find_gh_executable()
|
||||
.ok_or_else(|| "GitHub CLI (`gh`) is required to select a Copilot GitHub account".to_owned())?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com", "--user", account]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
@@ -229,6 +330,140 @@ fn github_token_for_account(account: &str) -> Result<String, String> {
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
/// Interactive `gh auth login` launch for adding/switching GitHub CLI accounts in-IDE,
|
||||
/// with ambient `GITHUB_TOKEN` / `GH_TOKEN` cleared so `gh` does not refuse to run.
|
||||
pub fn gh_login_launch() -> IdeResult<LoginLaunch> {
|
||||
let program = find_gh_executable().ok_or_else(|| IdeError::unavailable("GitHub CLI (`gh`) is not installed"))?;
|
||||
let mut env = BTreeMap::new();
|
||||
for key in AMBIENT_COPILOT_AUTH_VARS {
|
||||
env.insert(key.to_owned(), String::new());
|
||||
}
|
||||
Ok(LoginLaunch {
|
||||
program,
|
||||
args: vec!["auth".into(), "login".into(), "--hostname".into(), "github.com".into()],
|
||||
env,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns `(gh_installed, authenticated_accounts)` for `github.com` from `gh auth status`,
|
||||
/// ignoring ambient token environment variables so keyring accounts remain visible.
|
||||
pub fn gh_authenticated_accounts() -> (bool, Vec<GhAuthAccount>) {
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return (false, Vec::new());
|
||||
};
|
||||
let run_gh = |args: &[&str]| -> Option<std::process::Output> {
|
||||
let mut command = std::process::Command::new(&program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command
|
||||
.args(args)
|
||||
.envs(ide_core::process::shell_env())
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1");
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
command.output().ok()
|
||||
};
|
||||
if let Some(output) = run_gh(&["auth", "status", "--json", "hosts"]) {
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
if let Some(accounts) = parse_gh_auth_status_json(&stdout) {
|
||||
return (true, accounts);
|
||||
}
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.contains("unknown flag: --json") {
|
||||
return (true, Vec::new());
|
||||
}
|
||||
}
|
||||
let fallback = run_gh(&["auth", "status", "--hostname", "github.com"])
|
||||
.map(|out| format!("{}\n{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
|
||||
.map(|text| parse_gh_auth_status_text(&text))
|
||||
.unwrap_or_default();
|
||||
(true, fallback)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_json(text: &str) -> Option<Vec<GhAuthAccount>> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Entry {
|
||||
#[serde(default)]
|
||||
state: Option<String>,
|
||||
#[serde(default)]
|
||||
active: bool,
|
||||
#[serde(default)]
|
||||
login: String,
|
||||
#[serde(default)]
|
||||
token_source: Option<String>,
|
||||
}
|
||||
#[derive(Deserialize)]
|
||||
struct Response {
|
||||
#[serde(default)]
|
||||
hosts: BTreeMap<String, Vec<Entry>>,
|
||||
}
|
||||
let parsed: Response = serde_json::from_str(text.trim()).ok()?;
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
if let Some(entries) = parsed.hosts.get("github.com") {
|
||||
for entry in entries {
|
||||
let login = entry.login.trim();
|
||||
if login.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if entry.state.as_deref().is_some_and(|s| s != "success") {
|
||||
continue;
|
||||
}
|
||||
// Tokens from the environment (`GH_TOKEN`, `GITHUB_TOKEN`, …) are not keyring accounts.
|
||||
if entry.token_source.as_deref().is_some_and(|source| source.ends_with("_TOKEN") || source == "env") {
|
||||
continue;
|
||||
}
|
||||
if let Some(existing) = accounts.iter_mut().find(|a| a.login == login) {
|
||||
existing.active |= entry.active;
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: entry.active });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(accounts)
|
||||
}
|
||||
|
||||
fn parse_gh_auth_status_text(text: &str) -> Vec<GhAuthAccount> {
|
||||
let mut accounts: Vec<GhAuthAccount> = Vec::new();
|
||||
let mut current: Option<usize> = None;
|
||||
for line in text.lines() {
|
||||
let trimmed = line.trim();
|
||||
if let Some((_, rest)) = trimmed.split_once("Logged in to github.com account ") {
|
||||
let login = rest.split_whitespace().next().unwrap_or("").trim();
|
||||
current = None;
|
||||
if !login.is_empty() && !rest.contains("_TOKEN") {
|
||||
if let Some(idx) = accounts.iter().position(|a| a.login == login) {
|
||||
current = Some(idx);
|
||||
} else {
|
||||
accounts.push(GhAuthAccount { login: login.to_owned(), active: false });
|
||||
current = Some(accounts.len() - 1);
|
||||
}
|
||||
}
|
||||
} else if trimmed.starts_with("- Active account: true")
|
||||
&& let Some(idx) = current
|
||||
{
|
||||
accounts[idx].active = true;
|
||||
}
|
||||
}
|
||||
accounts
|
||||
}
|
||||
|
||||
fn default_github_token() -> Option<String> {
|
||||
let program = find_gh_executable()?;
|
||||
let mut command = std::process::Command::new(program);
|
||||
ide_core::process::prepare(&mut command);
|
||||
command.args(["auth", "token", "--hostname", "github.com"]).envs(ide_core::process::shell_env());
|
||||
for name in AMBIENT_COPILOT_AUTH_VARS {
|
||||
command.env_remove(name);
|
||||
}
|
||||
let output = command.output().ok().filter(|out| out.status.success())?;
|
||||
let token = String::from_utf8(output.stdout).ok()?;
|
||||
let token = token.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
pub(crate) fn prefer_stored_copilot_auth() -> bool {
|
||||
PREFER_STORED_COPILOT_AUTH.load(std::sync::atomic::Ordering::Acquire)
|
||||
}
|
||||
@@ -237,18 +472,17 @@ pub(crate) fn mark_prefer_stored_copilot_auth() {
|
||||
PREFER_STORED_COPILOT_AUTH.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)]) -> bool {
|
||||
pub(crate) fn has_unconfigured_copilot_ambient_token(spec_env: &[(String, String)], cwd: &Path) -> bool {
|
||||
AMBIENT_COPILOT_AUTH_VARS.iter().any(|&key| {
|
||||
!spec_env.iter().any(|(k, v)| k == key && !v.is_empty())
|
||||
&& ambient_copilot_env_value(key).is_some_and(|v| !v.is_empty())
|
||||
&& ambient_copilot_env_value(key, cwd).is_some_and(|v| !v.is_empty())
|
||||
})
|
||||
}
|
||||
|
||||
fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
ide_core::process::shell_env()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
.or_else(|| ide_core::process::host_var_os(key).map(|v| v.to_string_lossy().into_owned()))
|
||||
fn ambient_copilot_env_value(key: &str, cwd: &Path) -> Option<String> {
|
||||
ide_core::process::host_var_os_in(cwd, key).map(|v| v.to_string_lossy().into_owned()).or_else(|| {
|
||||
ide_core::process::shell_env().find(|(k, _)| *k == key).map(|(_, v)| v.to_string_lossy().into_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Builds child environment overrides for `copilot`:
|
||||
@@ -259,9 +493,10 @@ fn ambient_copilot_env_value(key: &str) -> Option<String> {
|
||||
/// while preserving any token explicitly configured in OpenIDEA's agent `spec_env`.
|
||||
pub(crate) fn sanitized_copilot_env(
|
||||
spec_env: &[(String, String)],
|
||||
cwd: &Path,
|
||||
strip_ambient_tokens: bool,
|
||||
) -> Vec<(String, String)> {
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, ambient_copilot_env_value)
|
||||
sanitize_copilot_env_with(spec_env, strip_ambient_tokens, |key| ambient_copilot_env_value(key, cwd))
|
||||
}
|
||||
|
||||
pub(crate) fn sanitize_copilot_env_with(
|
||||
@@ -389,6 +624,7 @@ pub(crate) fn describe(spec: &ProviderSpec) -> AgentProvider {
|
||||
command_editable: reason.is_none(),
|
||||
command_read_only_reason: reason,
|
||||
installed: installed(&spec.command),
|
||||
can_sign_in: spec.can_sign_in(Path::new("."), None),
|
||||
can_check_cli_update: spec.source == AgentSource::Builtin && crate::cli_update::package(&spec.id).is_some(),
|
||||
env: spec.env.iter().cloned().collect(),
|
||||
config: vec![],
|
||||
@@ -901,6 +1137,22 @@ mod tests {
|
||||
assert_eq!(reset.env, custom.env);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_builtin_login_hint_yields_the_arguments_sign_in_runs() {
|
||||
// Sign In runs the arguments in the hint's backticks: rewording a hint must keep that form.
|
||||
for spec in builtins() {
|
||||
if matches!(spec.id.as_str(), "claude-acp" | "codex-acp" | "vibe") {
|
||||
continue;
|
||||
}
|
||||
assert!(builtin_login_args(&spec).is_some(), "{}: {}", spec.id, spec.login_hint);
|
||||
}
|
||||
let args = |id: &str| builtin_login_args(&builtin_spec(id).unwrap()).unwrap();
|
||||
assert_eq!(args("copilot"), ["login"]);
|
||||
assert_eq!(args("goose"), ["configure"]);
|
||||
assert_eq!(args("hermes"), ["model"]);
|
||||
assert!(args("qwen").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_hints_cover_all_builtin_commands_and_preserve_separate_login_tools() {
|
||||
for spec in builtins() {
|
||||
@@ -1160,12 +1412,12 @@ mod tests {
|
||||
"copilot",
|
||||
BTreeMap::from([
|
||||
("REGISTRY_SETTING".into(), "kept".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()),
|
||||
(COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()),
|
||||
]),
|
||||
)
|
||||
.unwrap();
|
||||
let spec = load(Some(dir.path()), None).into_iter().find(|spec| spec.id == "copilot").unwrap();
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("dengliu_microsoft"));
|
||||
assert_eq!(copilot_github_account(&spec.env).as_deref(), Some("alice-work"));
|
||||
|
||||
set_builtin_env(dir.path(), None, "copilot", BTreeMap::from([("REGISTRY_SETTING".into(), "changed".into())]))
|
||||
.unwrap_err();
|
||||
@@ -1174,7 +1426,7 @@ mod tests {
|
||||
#[test]
|
||||
fn launch_metadata_never_passes_the_github_account_control_to_copilot() {
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "dengliu_microsoft".into()));
|
||||
spec.env.push((COPILOT_GITHUB_ACCOUNT_ENV.into(), "alice-work".into()));
|
||||
let resolved = spec.resolve_for_launch(Path::new("."));
|
||||
assert!(resolved.env.iter().all(|(name, _)| name != COPILOT_GITHUB_ACCOUNT_ENV));
|
||||
}
|
||||
@@ -1458,4 +1710,68 @@ mod tests {
|
||||
vec![("GITHUB_TOKEN".into(), String::new()), ("GH_TOKEN".into(), "github_pat_custom".into())]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_gh_auth_status_json_and_text_without_ambient_token_entries() {
|
||||
let raw = r#"{
|
||||
"hosts": {
|
||||
"github.com": [
|
||||
{"state": "failed", "active": true, "login": "bad", "tokenSource": "GITHUB_TOKEN"},
|
||||
{"state": "success", "active": true, "login": "alice", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "alice-work", "tokenSource": "keyring"},
|
||||
{"state": "success", "active": false, "login": "env_user", "tokenSource": "GH_TOKEN"}
|
||||
],
|
||||
"ghe.example.com": [
|
||||
{"state": "success", "active": true, "login": "corp", "tokenSource": "keyring"}
|
||||
]
|
||||
}
|
||||
}"#;
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_json(raw),
|
||||
Some(vec![
|
||||
GhAuthAccount { login: "alice".into(), active: true },
|
||||
GhAuthAccount { login: "alice-work".into(), active: false },
|
||||
])
|
||||
);
|
||||
|
||||
let text = "\
|
||||
github.com
|
||||
✓ Logged in to github.com account env_user (GH_TOKEN)
|
||||
- Active account: true
|
||||
✓ Logged in to github.com account alice (keyring)
|
||||
- Active account: false
|
||||
✓ Logged in to github.com account alice-work (keyring)
|
||||
- Active account: true
|
||||
";
|
||||
assert_eq!(
|
||||
parse_gh_auth_status_text(text),
|
||||
vec![
|
||||
GhAuthAccount { login: "alice".into(), active: false },
|
||||
GhAuthAccount { login: "alice-work".into(), active: true },
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn login_launch_resolves_paths_with_spaces_and_clears_ambient_copilot_tokens() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let app_support = dir.path().join("Application Support/copilot");
|
||||
std::fs::create_dir_all(&app_support).unwrap();
|
||||
let bin = app_support.join(if cfg!(windows) { "copilot.cmd" } else { "copilot" });
|
||||
std::fs::write(&bin, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let mut spec = builtin_spec("copilot").unwrap();
|
||||
spec.command = bin.to_string_lossy().into_owned();
|
||||
spec.source = AgentSource::Registry { version: "1.0.115".into(), update: None };
|
||||
let launch = spec.login_launch(dir.path(), None).unwrap();
|
||||
assert_eq!(launch.program, bin);
|
||||
assert_eq!(launch.args, ["login"]);
|
||||
assert_eq!(launch.env.get("GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("GH_TOKEN").map(String::as_str), Some(""));
|
||||
assert_eq!(launch.env.get("COPILOT_GITHUB_TOKEN").map(String::as_str), Some(""));
|
||||
}
|
||||
}
|
||||
@@ -443,7 +443,15 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
|
||||
/// Installs (or updates to) the registry's current version of `id`, streaming progress
|
||||
/// through `emit`, and points the agent file at it.
|
||||
pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit: Emit) -> IdeResult<()> {
|
||||
/// Installs agent `id`; an npm package retries against the public npm registry when the
|
||||
/// configured one misses it only with `public_npm_fallback`.
|
||||
pub fn install(
|
||||
paths: &RegistryPaths,
|
||||
id: &str,
|
||||
public_npm_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let id = canonical_id(id);
|
||||
// The saved index is what the user picked from; fetch only when there is none.
|
||||
let text = match fs::read_to_string(&paths.cache_file) {
|
||||
@@ -455,9 +463,14 @@ pub fn install(paths: &RegistryPaths, id: &str, cancel: &CancellationToken, emit
|
||||
.iter()
|
||||
.find(|e| e.id == id)
|
||||
.ok_or_else(|| IdeError::not_found(format!("{id} is not in the ACP Registry")))?;
|
||||
install_entry(paths, entry, Platform::current(), &on_path, cancel, emit)
|
||||
let npm_installer =
|
||||
move |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, public_npm_fallback, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, Platform::current(), &on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn install_entry(
|
||||
paths: &RegistryPaths,
|
||||
entry: &Entry,
|
||||
@@ -466,7 +479,10 @@ fn install_entry(
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
install_entry_with(paths, entry, platform, on_path, &install_npm, cancel, emit)
|
||||
let npm_installer = |p: &Package, entry: &Entry, dir: &Path, platform, cancel: &CancellationToken, emit: Emit| {
|
||||
install_npm(p, entry, dir, platform, true, cancel, emit)
|
||||
};
|
||||
install_entry_with(paths, entry, platform, on_path, &npm_installer, cancel, emit)
|
||||
}
|
||||
|
||||
type NpmInstaller = dyn Fn(&Package, &Entry, &Path, Platform, &CancellationToken, Emit) -> IdeResult<PathBuf>;
|
||||
@@ -663,20 +679,23 @@ fn install_npm(
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
let (name, _) = split_npm_spec(&p.package);
|
||||
let npm = which::which("npm").map_err(|_| IdeError::unavailable(format!("npm is required to install {name}")))?;
|
||||
install_npm_with(&npm, p, entry, dir, platform, cancel, emit)
|
||||
install_npm_with(&npm, p, entry, dir, platform, public_fallback, cancel, emit)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn install_npm_with(
|
||||
npm: &Path,
|
||||
p: &Package,
|
||||
entry: &Entry,
|
||||
dir: &Path,
|
||||
platform: Platform,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<PathBuf> {
|
||||
@@ -704,6 +723,7 @@ fn install_npm_with(
|
||||
},
|
||||
&specs,
|
||||
false,
|
||||
public_fallback,
|
||||
cancel,
|
||||
emit,
|
||||
)?;
|
||||
@@ -1004,7 +1024,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss() {
|
||||
fn npm_registry_agent_retries_against_public_npmjs_on_mirror_miss_unless_registries_are_configured_only() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let install_dir = dir.path().join("acme/1.2.0");
|
||||
fs::create_dir_all(&install_dir).unwrap();
|
||||
@@ -1043,8 +1063,8 @@ esac
|
||||
]}"#;
|
||||
let entry = parse(index).unwrap().remove(0);
|
||||
let pkg = entry.distribution.npx.as_ref().unwrap();
|
||||
let exe =
|
||||
install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, &CancellationToken::new(), &|_| {}).unwrap();
|
||||
let exe = install_npm_with(&npm, pkg, &entry, &install_dir, MAC_ARM, true, &CancellationToken::new(), &|_| {})
|
||||
.unwrap();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 2, "{calls:?}");
|
||||
assert!(!calls[0].contains("--registry="), "{calls:?}");
|
||||
@@ -1052,6 +1072,15 @@ esac
|
||||
assert!(calls[1].contains("--@acme:registry=https://registry.npmjs.org/"), "{calls:?}");
|
||||
assert_eq!(exe, install_dir.join("node_modules/.bin/agent-acp"));
|
||||
assert!(exe.is_file());
|
||||
// Only the configured registries: the miss is the error, and npmjs is never asked.
|
||||
let only = dir.path().join("acme-only/1.2.0");
|
||||
fs::create_dir_all(&only).unwrap();
|
||||
let err =
|
||||
install_npm_with(&npm, pkg, &entry, &only, MAC_ARM, false, &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
let calls: Vec<String> = fs::read_to_string(&log).unwrap().lines().map(str::to_owned).collect();
|
||||
assert_eq!(calls.len(), 3, "{calls:?}");
|
||||
assert!(!calls[2].contains("--registry="), "{calls:?}");
|
||||
assert!(err.message.contains("notarget"), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1183,7 +1212,7 @@ esac
|
||||
write_atomic(&p.cache_file, index.as_bytes()).unwrap();
|
||||
let spec = provider::load(Some(&p.agents_dir), None).into_iter().find(|s| s.id == "copilot").unwrap();
|
||||
assert_eq!(spec.name, "GitHub Copilot");
|
||||
assert_eq!(spec.login_hint, "Run `copilot` in a terminal and sign in.");
|
||||
assert_eq!(spec.login_hint, "Run `copilot login` in a terminal.");
|
||||
assert_eq!(spec.source, AgentSource::Registry { version: "1.0.104".into(), update: None });
|
||||
|
||||
let mut providers = vec![provider::describe(&spec)];
|
||||
|
||||
@@ -486,6 +486,16 @@ pub struct LanguageCodeStyle {
|
||||
/// SQL › Case › Identifiers (unquoted names): `upper` | `lower` | `keep`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub identifier_case: Option<String>,
|
||||
/// Java: organize imports switches to a wildcard import once this many
|
||||
/// classes of one package are used (jdtls `starThreshold`; IDEA's default
|
||||
/// 5; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub class_count_to_use_import_with_star: Option<u32>,
|
||||
/// Java: organize imports switches to a wildcard static import once this
|
||||
/// many statically imported names are used (jdtls `staticStarThreshold`;
|
||||
/// IDEA's default 3; unset keeps the language server's default).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub names_count_to_use_static_import_with_star: Option<u32>,
|
||||
/// JavaScript / TypeScript › Punctuation › Semicolons: `ignore` | `insert` | `remove`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub semicolons: Option<String>,
|
||||
@@ -495,6 +505,19 @@ pub struct LanguageCodeStyle {
|
||||
/// JavaScript / TypeScript › Spaces, by tsserver format option (`insertSpaceAfterCommaDelimiter`).
|
||||
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub spaces: BTreeMap<String, bool>,
|
||||
/// JavaScript / TypeScript › Imports › Import paths:
|
||||
/// `shortest` | `relative` | `non-relative` | `project-relative`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Import path ending: `auto` | `minimal` | `index` | `js`.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub import_module_specifier_ending: Option<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import from (globs).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_file_exclude_patterns: Vec<String>,
|
||||
/// JavaScript / TypeScript › Imports › Do not auto-import specifiers matching (regexes).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub auto_import_specifier_exclude_regexes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Editor › Code Style (General tab + per-language overrides).
|
||||
@@ -552,6 +575,25 @@ pub struct EncodingSettings {
|
||||
pub native_to_ascii: bool,
|
||||
/// Create UTF-8 files: `never` (no BOM) | `always` (with BOM) | `windows` (with BOM on Windows).
|
||||
pub utf8_bom: String,
|
||||
/// Encoding (WHATWG label) of a file or of the files in a folder, by its path
|
||||
/// relative to the project with `/` separators. The status bar's choice is kept here.
|
||||
#[serde(deserialize_with = "labels")]
|
||||
#[specta(type = BTreeMap<String, String>)]
|
||||
pub mappings: BTreeMap<String, String>,
|
||||
}
|
||||
|
||||
/// A hand-edited entry that is not a label is left out, rather than failing the whole settings file.
|
||||
fn labels<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BTreeMap<String, String>, D::Error> {
|
||||
let serde_json::Value::Object(entries) = serde_json::Value::deserialize(d)? else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
Ok(entries
|
||||
.into_iter()
|
||||
.filter_map(|(path, label)| match label {
|
||||
serde_json::Value::String(label) => Some((path, label)),
|
||||
_ => None,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
impl Default for EncodingSettings {
|
||||
@@ -562,10 +604,30 @@ impl Default for EncodingSettings {
|
||||
properties: "iso-8859-1".into(),
|
||||
native_to_ascii: false,
|
||||
utf8_bom: "never".into(),
|
||||
mappings: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod encoding_mappings_tests {
|
||||
use super::EncodingSettings;
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_keep_the_entries_that_are_labels() {
|
||||
let json = serde_json::json!({
|
||||
"project": "gbk",
|
||||
"mappings": { "src/main/java": "iso-8859-15", "count": 5, "nested": { "a": "utf-8" } },
|
||||
});
|
||||
let settings: EncodingSettings = serde_json::from_value(json).unwrap();
|
||||
assert_eq!(settings.project, "gbk");
|
||||
assert_eq!(settings.mappings.into_iter().collect::<Vec<_>>(), [("src/main/java".into(), "iso-8859-15".into())]);
|
||||
let not_a_table: EncodingSettings = serde_json::from_value(serde_json::json!({ "mappings": 5 })).unwrap();
|
||||
assert!(not_a_table.mappings.is_empty());
|
||||
assert!(EncodingSettings::default().mappings.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod auto_import_tests {
|
||||
use super::{AutoImportSettings, ImportsOnPaste};
|
||||
|
||||
@@ -14,10 +14,33 @@ pub type Changes = Arc<Vec<(OsString, Option<OsString>)>>;
|
||||
|
||||
struct Entry {
|
||||
root: PathBuf,
|
||||
direnv: Vec<(OsString, Option<OsString>)>,
|
||||
github_token: Option<OsString>,
|
||||
changes: Changes,
|
||||
loading: bool,
|
||||
}
|
||||
|
||||
impl Entry {
|
||||
fn new(root: PathBuf) -> Self {
|
||||
Self { root, direnv: Vec::new(), github_token: None, changes: Changes::default(), loading: false }
|
||||
}
|
||||
|
||||
fn rebuild(&mut self) {
|
||||
let mut combined = Vec::with_capacity(self.direnv.len() + usize::from(self.github_token.is_some()));
|
||||
if let Some(token) = &self.github_token {
|
||||
combined.push(("GH_TOKEN".into(), Some(token.clone())));
|
||||
}
|
||||
// `.envrc` entries override the project GitHub token when both define `GH_TOKEN`.
|
||||
combined.retain(|(k, _)| !self.direnv.iter().any(|(dk, _)| dk == k));
|
||||
combined.extend(self.direnv.iter().cloned());
|
||||
self.changes = Arc::new(combined);
|
||||
}
|
||||
|
||||
fn is_idle_empty(&self) -> bool {
|
||||
!self.loading && self.direnv.is_empty() && self.github_token.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
static ENTRIES: Mutex<Vec<Entry>> = Mutex::new(Vec::new());
|
||||
static SETTLED: Condvar = Condvar::new();
|
||||
|
||||
@@ -31,35 +54,103 @@ pub fn begin_loading(root: &Path) {
|
||||
let mut entries = entries();
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => entry.loading = true,
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes: Changes::default(), loading: true }),
|
||||
None => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.loading = true;
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What children started in `root` (or below it) get on top of the IDE's own environment
|
||||
/// (`None`: removed). Ends a [`begin_loading`].
|
||||
/// What children started in `root` (or below it) get from direnv on top of the IDE's own
|
||||
/// environment (`None`: removed). Ends a [`begin_loading`].
|
||||
pub fn set(root: &Path, changes: Vec<(OsString, Option<OsString>)>) {
|
||||
let mut entries = entries();
|
||||
let changes = Arc::new(changes);
|
||||
match entries.iter_mut().find(|e| e.root == root) {
|
||||
Some(entry) => {
|
||||
entry.changes = changes;
|
||||
match entries.iter_mut().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv = changes;
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
None => entries.push(Entry { root: root.to_path_buf(), changes, loading: false }),
|
||||
None if !changes.is_empty() => {
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.direnv = changes;
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Ends a [`begin_loading`] that read nothing new (an error): the last environment stays.
|
||||
pub fn settle(root: &Path) {
|
||||
if let Some(entry) = entries().iter_mut().find(|e| e.root == root) {
|
||||
entry.loading = false;
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
entries[idx].loading = false;
|
||||
if entries[idx].is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// `root` has no environment of its own any more (closed, or not trusted).
|
||||
/// `root` has no direnv environment of its own any more (no `.envrc`, closed, or not trusted).
|
||||
/// Preserves any project-scoped GitHub token until [`remove_all`] or [`set_github_token`].
|
||||
pub fn remove(root: &Path) {
|
||||
let mut entries = entries();
|
||||
if let Some(idx) = entries.iter().position(|e| e.root == root) {
|
||||
let entry = &mut entries[idx];
|
||||
entry.direnv.clear();
|
||||
entry.loading = false;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
}
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
|
||||
/// Sets or clears the project-scoped `GH_TOKEN` injected for children started in `root`
|
||||
/// (unless overridden by `root`'s direnv `.envrc`). Returns whether the effective token changed.
|
||||
pub fn set_github_token(root: &Path, token: Option<OsString>) -> bool {
|
||||
let token = token.filter(|t| !t.is_empty());
|
||||
let mut entries = entries();
|
||||
match entries.iter().position(|e| e.root == root) {
|
||||
Some(idx) => {
|
||||
if entries[idx].github_token == token {
|
||||
return false;
|
||||
}
|
||||
let entry = &mut entries[idx];
|
||||
entry.github_token = token;
|
||||
entry.rebuild();
|
||||
if entry.is_idle_empty() {
|
||||
entries.remove(idx);
|
||||
}
|
||||
true
|
||||
}
|
||||
None => {
|
||||
let Some(token) = token else { return false };
|
||||
let mut entry = Entry::new(root.to_path_buf());
|
||||
entry.github_token = Some(token);
|
||||
entry.rebuild();
|
||||
entries.push(entry);
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The project-scoped `GH_TOKEN` configured for the innermost project holding `dir`, if any.
|
||||
pub fn github_token(dir: &Path) -> Option<OsString> {
|
||||
find(&entries(), dir).and_then(|e| e.github_token.clone())
|
||||
}
|
||||
|
||||
/// Removes both direnv and project GitHub token entries for `root` (project closed or untrusted).
|
||||
pub fn remove_all(root: &Path) {
|
||||
entries().retain(|e| e.root != root);
|
||||
SETTLED.notify_all();
|
||||
}
|
||||
@@ -135,4 +226,26 @@ mod tests {
|
||||
assert_eq!(*for_dir(root), [change("NEW", Some("2"))]);
|
||||
remove(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn github_token_survives_direnv_absence_and_yields_to_explicit_envrc_override() {
|
||||
let root = Path::new("/openidea-test-env/gh-project");
|
||||
let worktrees = Path::new("/openidea-test-env/gh-project.worktrees");
|
||||
assert!(set_github_token(root, Some("gho_work".into())));
|
||||
assert!(!set_github_token(root, Some("gho_work".into())), "idempotent");
|
||||
assert!(set_github_token(worktrees, Some("gho_work".into())));
|
||||
remove(root); // no `.envrc` in `root`
|
||||
assert_eq!(*for_dir(&root.join("src")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(*for_dir(&worktrees.join("task-1")), [change("GH_TOKEN", Some("gho_work"))]);
|
||||
assert_eq!(github_token(&worktrees.join("task-1")), Some("gho_work".into()));
|
||||
|
||||
// An explicit `.envrc` GH_TOKEN overrides the project GitHub account token.
|
||||
set(root, vec![change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
assert_eq!(*for_dir(root), [change("GH_TOKEN", Some("gho_from_envrc")), change("FOO", Some("bar"))]);
|
||||
|
||||
remove_all(root);
|
||||
remove_all(worktrees);
|
||||
assert!(for_dir(root).is_empty());
|
||||
assert!(for_dir(worktrees).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -432,6 +432,12 @@ pub struct ToolDownloadSettings {
|
||||
/// commas or whitespace and tried in order before the official host; empty keeps every
|
||||
/// download on its official host.
|
||||
pub github_mirror: String,
|
||||
/// Package registries only as configured (a company Nexus or Artifactory): npm and pnpm
|
||||
/// installs and update checks never retry against the public npm registry, and the IDE
|
||||
/// fetches nothing from public package registries itself (the JUnit Platform launcher from
|
||||
/// Maven Central, dependency version completion from Maven Central, npm, PyPI and
|
||||
/// crates.io). Off by default.
|
||||
pub configured_registries_only: bool,
|
||||
}
|
||||
|
||||
/// Absent profiles retain automatic discovery for existing projects.
|
||||
@@ -1420,6 +1426,9 @@ pub struct PythonSettings {
|
||||
/// Folders the user added to an interpreter's `sys.path` (All Interpreters › Show Paths),
|
||||
/// by interpreter executable; absolute or `~/`.
|
||||
pub interpreter_paths: BTreeMap<String, Vec<String>>,
|
||||
/// Default test runner (Settings › Python › Testing): `auto` (pytest when the project uses
|
||||
/// it, else unittest), `pytest` or `unittest`.
|
||||
pub test_runner: String,
|
||||
}
|
||||
|
||||
impl Default for PythonSettings {
|
||||
@@ -1432,6 +1441,7 @@ impl Default for PythonSettings {
|
||||
hide_other_project_interpreters: false,
|
||||
show_interpreter_paths: true,
|
||||
interpreter_paths: BTreeMap::new(),
|
||||
test_runner: "auto".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +73,38 @@ pub fn find_command(command: &str, search: &OsStr, root: &Path) -> Option<PathBu
|
||||
dirs.into_iter().find_map(|dir| names.iter().map(|name| dir.join(name)).find(|p| is_executable(p)))
|
||||
}
|
||||
|
||||
const GH_FALLBACK_PATHS: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
|
||||
/// Locates `gh` across `OPENIDEA_GH`, [`search_path`] (which includes IDE-managed tools
|
||||
/// only when installed, then the user's `PATH`), and standard OS install locations.
|
||||
pub fn find_gh_executable() -> Option<PathBuf> {
|
||||
let explicit = std::env::var_os("OPENIDEA_GH").map(PathBuf::from);
|
||||
find_gh_in(explicit.as_deref(), &search_path(), GH_FALLBACK_PATHS)
|
||||
}
|
||||
|
||||
/// Locates a pre-installed `gh` outside [`search_path`] (`OPENIDEA_GH`, Windows Program Files,
|
||||
/// Linux Snap) so tool detection reports it as available without prompting for a duplicate install.
|
||||
pub fn find_gh_outside_search_path() -> Option<PathBuf> {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| is_executable(p)) {
|
||||
return Some(explicit);
|
||||
}
|
||||
GH_FALLBACK_PATHS.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
pub fn find_gh_in(explicit: Option<&Path>, search: &OsStr, fallbacks: &[&str]) -> Option<PathBuf> {
|
||||
if let Some(explicit) = explicit.filter(|p| is_executable(p)) {
|
||||
return Some(explicit.to_path_buf());
|
||||
}
|
||||
if let Some(found) = find_command("gh", search, Path::new("")) {
|
||||
return Some(found);
|
||||
}
|
||||
fallbacks.iter().map(PathBuf::from).find(|p| is_executable(p))
|
||||
}
|
||||
|
||||
fn is_executable(path: &Path) -> bool {
|
||||
let Ok(metadata) = path.metadata() else { return false };
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -25,6 +25,17 @@ pub struct VcsSettings {
|
||||
pub issue_navigation: Vec<IssueLink>,
|
||||
/// Directory Mappings: repository roots added to or excluded from the detected ones.
|
||||
pub mappings: VcsMappings,
|
||||
/// Settings › Version Control › GitHub: per-project GitHub CLI account selection.
|
||||
pub github: GithubSettings,
|
||||
}
|
||||
|
||||
/// Settings › Version Control › GitHub (`vcs.github`).
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GithubSettings {
|
||||
/// GitHub CLI (`gh`) account login on `github.com` explicitly chosen for this project.
|
||||
/// Empty means automatic (`gh`'s own active account, with no `GH_TOKEN` injected).
|
||||
pub account: String,
|
||||
}
|
||||
|
||||
/// Directory Mappings on top of repository detection. Paths are relative to the project
|
||||
@@ -68,6 +79,7 @@ impl Default for VcsSettings {
|
||||
shelf: ShelfSettings::default(),
|
||||
issue_navigation: Vec::new(),
|
||||
mappings: VcsMappings::default(),
|
||||
github: GithubSettings::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +157,10 @@ pub struct ColumnInfo {
|
||||
pub nullable: bool,
|
||||
pub default: Option<String>,
|
||||
pub primary_key: bool,
|
||||
/// `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -172,6 +176,10 @@ pub struct IndexInfo {
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[serde(rename = "DbTableDetails")]
|
||||
pub struct TableDetails {
|
||||
/// The table's comment; `None` when it has none, or the engine keeps no comments.
|
||||
#[serde(default)]
|
||||
#[specta(optional)]
|
||||
pub comment: Option<String>,
|
||||
pub columns: Vec<ColumnInfo>,
|
||||
pub indexes: Vec<IndexInfo>,
|
||||
pub foreign_keys: Vec<ForeignKey>,
|
||||
@@ -1119,11 +1127,18 @@ impl DbManager {
|
||||
let nullable = flag(&it.next().flatten());
|
||||
let default = it.next().flatten();
|
||||
let primary_key = flag(&it.next().flatten());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key })
|
||||
let comment = it.next().flatten().filter(|c| !c.is_empty());
|
||||
Some(ColumnInfo { name, data_type, nullable, default, primary_key, comment })
|
||||
})
|
||||
.collect();
|
||||
if driver == DbDriver::Jdbc {
|
||||
return Ok(TableDetails { columns, indexes: vec![], foreign_keys: vec![], triggers: vec![] });
|
||||
return Ok(TableDetails {
|
||||
comment: None,
|
||||
columns,
|
||||
indexes: vec![],
|
||||
foreign_keys: vec![],
|
||||
triggers: vec![],
|
||||
});
|
||||
}
|
||||
let mut indexes: Vec<IndexInfo> = Vec::new();
|
||||
for r in pool.rows(&sql::indexes(driver, schema, table), MAX_META_ROWS).await? {
|
||||
@@ -1175,7 +1190,17 @@ impl DbManager {
|
||||
Some(TriggerInfo { name, timing, events })
|
||||
})
|
||||
.collect();
|
||||
Ok(TableDetails { columns, indexes, foreign_keys, triggers })
|
||||
let comment = match sql::table_comment(driver, schema, table) {
|
||||
Some(q) => pool.rows(&q, 1).await.map_or_else(
|
||||
|e| {
|
||||
tracing::warn!("table comment: {}", e.message);
|
||||
None
|
||||
},
|
||||
|rows| rows.into_iter().next().and_then(|r| r.into_iter().next().flatten()).filter(|c| !c.is_empty()),
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes, foreign_keys, triggers })
|
||||
}
|
||||
|
||||
/// The object privileges granted on `table`; empty, without a query, on the engines
|
||||
|
||||
@@ -132,6 +132,7 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
nullable: yes(r.get("null?")),
|
||||
default: r.get("default").filter(|d| !d.is_empty()).map(str::to_owned),
|
||||
primary_key: yes(r.get("primary key")),
|
||||
comment: r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
@@ -140,7 +141,16 @@ pub(crate) async fn table_details(pool: &SnowflakePool, schema: &str, table: &st
|
||||
Ok(keys) => foreign_keys(&keys),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
Ok(TableDetails { columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
// `LIKE` matches without case and with wildcards: the exact name picks the row.
|
||||
let like = format!("SHOW TABLES LIKE {} IN SCHEMA {}", quote_literal(DRIVER, table), schema_path(pool, schema));
|
||||
let comment = match show(pool, &like).await {
|
||||
Ok(shown) => shown
|
||||
.records()
|
||||
.find(|r| r.get("name") == Some(table))
|
||||
.and_then(|r| r.get("comment").filter(|c| !c.is_empty()).map(str::to_owned)),
|
||||
Err(_) => None,
|
||||
};
|
||||
Ok(TableDetails { comment, columns, indexes: Vec::new(), foreign_keys, triggers: Vec::new() })
|
||||
}
|
||||
|
||||
fn foreign_keys(shown: &Shown) -> Vec<ForeignKey> {
|
||||
|
||||
@@ -145,7 +145,8 @@ const SNOWFLAKE_TYPE: &str = "CASE WHEN data_type = 'NUMBER' THEN 'NUMBER(' || n
|
||||
WHEN data_type = 'TEXT' THEN 'VARCHAR(' || character_maximum_length || ')' \
|
||||
WHEN data_type LIKE 'TIME%' THEN data_type || '(' || datetime_precision || ')' ELSE data_type END";
|
||||
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`.
|
||||
/// Rows: `name, type, nullable (YES/NO or 0/1), default, is_pk (0/1)`, and the column's
|
||||
/// comment on the engines that keep one (PostgreSQL, MySQL, Oracle, ClickHouse).
|
||||
pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
@@ -153,7 +154,7 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
DbDriver::Clickhouse => format!(
|
||||
"SELECT name, type, CASE WHEN startsWith(type, 'Nullable(') \
|
||||
OR startsWith(type, 'LowCardinality(Nullable(') THEN 'YES' ELSE 'NO' END, \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key \
|
||||
if(default_kind = '', NULL, default_expression), is_in_primary_key, comment \
|
||||
FROM system.columns WHERE database = {s} AND table = {t} ORDER BY position"
|
||||
),
|
||||
DbDriver::Sqlite => format!(
|
||||
@@ -166,13 +167,14 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
JOIN information_schema.key_column_usage k ON k.constraint_name = tc.constraint_name \
|
||||
AND k.table_schema = tc.table_schema AND k.table_name = tc.table_name \
|
||||
WHERE tc.constraint_type = 'PRIMARY KEY' AND tc.table_schema = c.table_schema \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END \
|
||||
AND tc.table_name = c.table_name AND k.column_name = c.column_name) THEN 1 ELSE 0 END, \
|
||||
col_description(format('%I.%I', c.table_schema, c.table_name)::regclass, c.ordinal_position::int) \
|
||||
FROM information_schema.columns c WHERE c.table_schema = {s} AND c.table_name = {t} \
|
||||
ORDER BY c.ordinal_position"
|
||||
),
|
||||
DbDriver::Mysql => format!(
|
||||
"SELECT column_name, column_type, is_nullable, column_default, \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END \
|
||||
CASE WHEN column_key = 'PRI' THEN 1 ELSE 0 END, column_comment \
|
||||
FROM information_schema.columns WHERE table_schema = {s} AND table_name = {t} \
|
||||
ORDER BY ordinal_position"
|
||||
),
|
||||
@@ -192,8 +194,10 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
),
|
||||
DbDriver::Oracle => format!(
|
||||
"SELECT c.column_name, c.data_type, DECODE(c.nullable, 'Y', 'YES', 'NO'), c.data_default, \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END \
|
||||
CASE WHEN k.column_name IS NOT NULL THEN 1 ELSE 0 END, cc.comments \
|
||||
FROM all_tab_columns c \
|
||||
LEFT JOIN all_col_comments cc ON cc.owner = c.owner AND cc.table_name = c.table_name \
|
||||
AND cc.column_name = c.column_name \
|
||||
LEFT JOIN (SELECT kc.column_name FROM all_constraints con \
|
||||
JOIN all_cons_columns kc ON kc.owner = con.owner AND kc.table_name = con.table_name \
|
||||
AND kc.constraint_name = con.constraint_name \
|
||||
@@ -204,6 +208,28 @@ pub fn columns(driver: DbDriver, schema: &str, table: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// One row, one column: the table's comment (`NULL` or empty for none). `None` for the
|
||||
/// engines whose comments the IDE doesn't read here (Snowflake reads it with `SHOW`).
|
||||
pub fn table_comment(driver: DbDriver, schema: &str, table: &str) -> Option<String> {
|
||||
let (s, t) = (quote_literal(driver, schema), quote_literal(driver, table));
|
||||
match driver {
|
||||
DbDriver::Postgres => Some(format!(
|
||||
"SELECT obj_description(c.oid, 'pg_class') FROM pg_class c \
|
||||
JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = {s} AND c.relname = {t}"
|
||||
)),
|
||||
// A view's `table_comment` is the word `VIEW`.
|
||||
DbDriver::Mysql => Some(format!(
|
||||
"SELECT CASE WHEN table_type = 'VIEW' THEN NULL ELSE table_comment END \
|
||||
FROM information_schema.tables WHERE table_schema = {s} AND table_name = {t}"
|
||||
)),
|
||||
DbDriver::Oracle => {
|
||||
Some(format!("SELECT comments FROM all_tab_comments WHERE owner = {s} AND table_name = {t}"))
|
||||
}
|
||||
DbDriver::Clickhouse => Some(format!("SELECT comment FROM system.tables WHERE database = {s} AND name = {t}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows: `index name, unique (0/1), column` (one row per indexed column, in order).
|
||||
// Key columns are paired from one series up to `max_index_keys` (the server's INDEX_MAX_KEYS, the
|
||||
// most columns an index or key has): unlike a series per catalog row, it lets the planner find the
|
||||
@@ -956,6 +982,22 @@ mod tests {
|
||||
assert_eq!(quote_literal(DbDriver::Mysql, "it's \\"), "'it''s \\\\'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_are_read_where_the_engine_keeps_them() {
|
||||
assert!(columns(DbDriver::Postgres, "public", "t").contains("col_description("));
|
||||
assert!(columns(DbDriver::Mysql, "db", "t").contains("column_comment"));
|
||||
assert!(columns(DbDriver::Oracle, "S", "T").contains("all_col_comments"));
|
||||
assert!(columns(DbDriver::Clickhouse, "db", "t").contains("is_in_primary_key, comment"));
|
||||
let pg = table_comment(DbDriver::Postgres, "public", "o'rders").unwrap();
|
||||
assert!(pg.contains("obj_description(c.oid, 'pg_class')") && pg.contains("'o''rders'"), "{pg}");
|
||||
assert!(table_comment(DbDriver::Mysql, "db", "t").unwrap().contains("table_comment"));
|
||||
assert!(table_comment(DbDriver::Oracle, "S", "T").unwrap().contains("all_tab_comments"));
|
||||
assert!(table_comment(DbDriver::Clickhouse, "db", "t").unwrap().contains("system.tables"));
|
||||
for driver in [DbDriver::Sqlite, DbDriver::SqlServer, DbDriver::Snowflake] {
|
||||
assert_eq!(table_comment(driver, "s", "t"), None);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clickhouse_escapes_backslashes_and_delimiters() {
|
||||
let driver = DbDriver::Clickhouse;
|
||||
|
||||
@@ -40,7 +40,8 @@ async fn create_schemas(db: &DbManager) {
|
||||
format!("DROP DATABASE IF EXISTS `{s}`"),
|
||||
format!("CREATE DATABASE `{s}` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"),
|
||||
format!(
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin, raw VARBINARY(4))"
|
||||
"CREATE TABLE `{s}`.`用户` (id INT PRIMARY KEY, name VARCHAR(20) COLLATE utf8mb4_bin COMMENT '名字', \
|
||||
raw VARBINARY(4)) COMMENT = '用户表'"
|
||||
),
|
||||
format!("CREATE INDEX `名字` ON `{s}`.`用户` (name)"),
|
||||
format!("INSERT INTO `{s}`.`用户` VALUES (1, 'ann', 0xCAFE)"),
|
||||
@@ -59,6 +60,9 @@ async fn assert_metadata_is_text(db: &DbManager) -> IdeResult<()> {
|
||||
let d = db.table_details("m", s, "用户").await?;
|
||||
let cols: Vec<_> = d.columns.iter().map(|c| c.name.as_str()).collect();
|
||||
assert_eq!(cols, ["id", "name", "raw"]);
|
||||
assert_eq!(d.comment.as_deref(), Some("用户表"));
|
||||
let comments: Vec<_> = d.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, Some("名字"), None]);
|
||||
assert!(d.indexes.iter().any(|i| i.name == "名字"), "{:?}", d.indexes);
|
||||
assert!(db.ddl("m", s, "用户").await?.contains("CREATE TABLE `用户`"));
|
||||
}
|
||||
|
||||
@@ -338,6 +338,8 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
"CREATE TABLE oi_meta.lines (n INT PRIMARY KEY, o_region INT, o_id INT, \
|
||||
FOREIGN KEY (o_region, o_id) REFERENCES oi_meta.orders (region, id))",
|
||||
"CREATE INDEX lines_order ON oi_meta.lines (o_id, o_region)",
|
||||
"COMMENT ON TABLE oi_meta.orders IS 'Customer''s orders'",
|
||||
"COMMENT ON COLUMN oi_meta.orders.note IS 'Free text'",
|
||||
"CREATE FUNCTION oi_meta.twice(v INT) RETURNS INT AS 'SELECT v * 2' LANGUAGE sql",
|
||||
] {
|
||||
db.execute("p", stmt, 10, &c).await?;
|
||||
@@ -350,6 +352,10 @@ async fn table_details_routines_and_completion_on_older_catalogs() -> IdeResult<
|
||||
assert_eq!(details.foreign_keys[0].columns, ["o_region", "o_id"]);
|
||||
assert_eq!(details.foreign_keys[0].ref_columns, ["region", "id"]);
|
||||
let orders = db.table_details("p", "oi_meta", "orders").await?;
|
||||
assert_eq!(orders.comment.as_deref(), Some("Customer's orders"));
|
||||
let comments: Vec<_> = orders.columns.iter().map(|c| c.comment.as_deref()).collect();
|
||||
assert_eq!(comments, [None, None, Some("Free text")]);
|
||||
assert_eq!(details.comment, None);
|
||||
let key = orders.indexes.iter().find(|i| i.unique).expect("primary key index");
|
||||
assert_eq!(key.columns, ["region", "id"]);
|
||||
|
||||
|
||||
@@ -12,4 +12,3 @@ serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
tracing.workspace = true
|
||||
which = "8"
|
||||
@@ -16,30 +16,15 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::Duration;
|
||||
|
||||
/// API calls normally answer within a few seconds.
|
||||
const QUICK: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Locates the gh executable once per process (GUI apps on macOS have a minimal `PATH`).
|
||||
/// Locates the gh executable (GUI apps on macOS have a minimal `PATH`, and the IDE can
|
||||
/// install or remove a managed copy in its tools directory at runtime).
|
||||
pub fn gh_executable() -> Option<PathBuf> {
|
||||
static GH: OnceLock<Option<PathBuf>> = OnceLock::new();
|
||||
GH.get_or_init(|| {
|
||||
if let Some(explicit) = std::env::var_os("OPENIDEA_GH").map(PathBuf::from).filter(|p| p.is_file()) {
|
||||
return Some(explicit);
|
||||
}
|
||||
if let Ok(found) = which::which("gh") {
|
||||
return Some(found);
|
||||
}
|
||||
let candidates: &[&str] = if cfg!(windows) {
|
||||
&[r"C:\Program Files\GitHub CLI\gh.exe"]
|
||||
} else {
|
||||
&["/opt/homebrew/bin/gh", "/usr/local/bin/gh", "/usr/bin/gh", "/snap/bin/gh"]
|
||||
};
|
||||
candidates.iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
})
|
||||
.clone()
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn command(root: &Path, args: &[&str]) -> IdeResult<Command> {
|
||||
@@ -386,3 +371,37 @@ pub fn prepare_diff(
|
||||
let files = repo.diff_files(&base, head_oid)?;
|
||||
Ok(PrDiffRevisions { base, head: head_oid.to_owned(), files, root: ide_core::IpcPath(repo.root().to_path_buf()) })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn gh_executable_picks_up_newly_installed_binary_without_restart() {
|
||||
let dir = std::env::temp_dir().join(format!("openidea-gh-test-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let search = std::env::join_paths([&dir]).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
|
||||
let gh = dir.join(if cfg!(windows) { "gh.exe" } else { "gh" });
|
||||
std::fs::write(&gh, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), Some(gh.clone()));
|
||||
|
||||
let explicit = dir.join(if cfg!(windows) { "custom-gh.exe" } else { "custom-gh" });
|
||||
std::fs::write(&explicit, "#!/bin/sh\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&explicit, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(Some(&explicit), &search, &[]), Some(explicit));
|
||||
|
||||
std::fs::remove_file(&gh).unwrap();
|
||||
assert_eq!(ide_core::tool_path::find_gh_in(None, &search, &[]), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,11 @@ impl Environment {
|
||||
}
|
||||
}
|
||||
|
||||
/// True on `openidea-server`, where the backend runs on a remote/headless host rather than the desktop shell.
|
||||
pub fn is_remote(&self) -> bool {
|
||||
self.project_env
|
||||
}
|
||||
|
||||
/// A trusted project at `root` opened or became trusted: loads its direnv environment in
|
||||
/// the background, unless another window of it already did. Its language servers wait.
|
||||
pub(crate) fn direnv_opened(&self, root: &Path, sink: &SharedSink) {
|
||||
|
||||
@@ -261,6 +261,12 @@ fn supports_external_format(language: &LanguageConfig, tool: ExternalFormatter)
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry of the formatters' language lists that covers `language`. MDX was part of Markdown
|
||||
/// and follows its entry, so lists saved before it had its own language keep formatting it.
|
||||
fn formatter_language(language: &str) -> &str {
|
||||
if language == "mdx" { "markdown" } else { language }
|
||||
}
|
||||
|
||||
/// The external formatter of a file, for a language with an external formatter.
|
||||
/// `forced` names the tool (Reformat with Prettier, oxfmt, Biome, Ruff, or Black). Ruff is
|
||||
/// the base formatter for Python, replaced by Black when configured or selected; Biome,
|
||||
@@ -295,7 +301,8 @@ fn external_tool(
|
||||
)))
|
||||
};
|
||||
}
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == language.id.as_str());
|
||||
let id = formatter_language(language.id.as_str());
|
||||
let enabled = |tool| settings.formatter(tool).languages.iter().any(|l| l == id);
|
||||
if language.formatter.as_ref().is_some_and(|f| f.tool == "ruff") {
|
||||
return Ok(if enabled(Black) && (settings.black.prefer || black_configured(file)) {
|
||||
Some(Black)
|
||||
@@ -897,6 +904,24 @@ mod tests {
|
||||
external_tool(forced, language.as_ref(), file, settings)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mdx_follows_the_markdown_entry_of_saved_language_lists() {
|
||||
// Saved before MDX had its own language: the whole list, with no `mdx` in it.
|
||||
let old: ide_core::settings::Settings = serde_json::from_str(
|
||||
r#"{"languages":{"prettier":{"languages":["markdown","css"]},"oxfmt":{"languages":["css"]}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let file = Path::new("/project/docs/intro.mdx");
|
||||
assert_eq!(tool(None, "mdx", file, &old.languages).unwrap(), Some(Prettier));
|
||||
let mut no_markdown = old.languages.clone();
|
||||
no_markdown.prettier.languages.retain(|l| l != "markdown");
|
||||
assert_eq!(tool(None, "mdx", file, &no_markdown).unwrap(), None);
|
||||
let mut oxfmt = old.languages.clone();
|
||||
oxfmt.oxfmt.languages.push("markdown".into());
|
||||
oxfmt.oxfmt.prefer = true;
|
||||
assert_eq!(tool(None, "mdx", file, &oxfmt).unwrap(), Some(Oxfmt));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_settings_use_ruff_for_python_and_prettier_for_the_web() {
|
||||
let settings = LanguagesSettings::default();
|
||||
|
||||
@@ -0,0 +1,340 @@
|
||||
//! Project-scoped GitHub CLI (`gh`) account selection and opt-in `GH_TOKEN` injection.
|
||||
//!
|
||||
//! Each project may pin a GitHub login in `vcs.github.account` (`.openidea/settings.toml`) or
|
||||
//! leave it empty (`Automatic`). `Automatic` leaves `gh`'s own behaviour untouched—no `GH_TOKEN`
|
||||
//! is injected into [`ide_core::project_env`] and opening a project makes no GitHub API calls.
|
||||
//! When the user inspects GitHub settings or Pull Requests with multiple `gh` keyring accounts,
|
||||
//! OpenIDEA probes the repository remote (`owner/repo`) to suggest a matching non-active account
|
||||
//! ("Use <login> for this project"). Only when an account is explicitly chosen does OpenIDEA
|
||||
//! resolve its token into [`ide_core::project_env`] (for both `project.root` and `.worktrees`).
|
||||
|
||||
use crate::Project;
|
||||
use ide_agent::GhAuthAccount;
|
||||
use ide_core::cli_process::{CliTool, Decoding};
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::LazyLock;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const AMBIENT_GH_VARS: [&str; 3] = ["COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"];
|
||||
const GH_TOOL: CliTool = CliTool::new("gh", Decoding::Utf8Lossy);
|
||||
const LOCAL_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const PROBE_TIMEOUT: Duration = Duration::from_secs(6);
|
||||
const CACHE_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
|
||||
/// GitHub CLI accounts available on this machine and which one applies to the project.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct GhProjectAccountStatus {
|
||||
pub gh_installed: bool,
|
||||
pub accounts: Vec<GhAuthAccount>,
|
||||
/// Value of `vcs.github.account` (`""` = Automatic).
|
||||
pub configured_account: String,
|
||||
/// Account login currently used (`configured_account` if signed in, else `gh`'s active account).
|
||||
pub effective_account: Option<String>,
|
||||
/// Non-active `gh` account with access to this project's GitHub remote when `configured_account` is empty.
|
||||
pub suggested_account: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedAutoAccount {
|
||||
login: Option<String>,
|
||||
at: Instant,
|
||||
}
|
||||
|
||||
type AutoCacheMap = HashMap<(String, Vec<String>), CachedAutoAccount>;
|
||||
static AUTO_CACHE: LazyLock<Mutex<AutoCacheMap>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
pub(crate) fn is_valid_github_login(login: &str) -> bool {
|
||||
let bytes = login.as_bytes();
|
||||
!bytes.is_empty()
|
||||
&& bytes.len() <= 39
|
||||
&& bytes[0].is_ascii_alphanumeric()
|
||||
&& bytes.iter().all(|b| b.is_ascii_alphanumeric() || *b == b'-' || *b == b'_')
|
||||
}
|
||||
|
||||
fn find_gh_executable() -> Option<PathBuf> {
|
||||
ide_core::tool_path::find_gh_executable()
|
||||
}
|
||||
|
||||
fn clean_gh_command(program: &Path, args: &[&str]) -> Command {
|
||||
let mut cmd = Command::new(program);
|
||||
cmd.current_dir(std::env::temp_dir())
|
||||
.args(args)
|
||||
.env("GH_PROMPT_DISABLED", "1")
|
||||
.env("GH_NO_UPDATE_NOTIFIER", "1")
|
||||
.env("NO_COLOR", "1")
|
||||
.env("CLICOLOR", "0");
|
||||
// Strip ambient tokens by setting empty then removing after `prepare`: `CliTool::run` calls
|
||||
// `ide_core::process::prepare`, which skips keys already present in `cmd.get_envs()`.
|
||||
for key in AMBIENT_GH_VARS {
|
||||
cmd.env_remove(key);
|
||||
}
|
||||
cmd
|
||||
}
|
||||
|
||||
fn gh_token_for_account(program: &Path, login: &str) -> Option<String> {
|
||||
if !is_valid_github_login(login) {
|
||||
return None;
|
||||
}
|
||||
let cmd = clean_gh_command(program, &["auth", "token", "--hostname", "github.com", "--user", login]);
|
||||
let out = GH_TOOL.run(cmd, LOCAL_TIMEOUT, None).ok().filter(|o| o.success)?;
|
||||
let token = out.stdout.trim();
|
||||
(!token.is_empty()).then(|| token.to_owned())
|
||||
}
|
||||
|
||||
/// Access level of an account for a specific `owner/repo` on `github.com`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum RepoAccess {
|
||||
None = 0,
|
||||
Read = 1,
|
||||
Push = 2,
|
||||
}
|
||||
|
||||
fn probe_repo_access(program: &Path, token: &str, owner: &str, name: &str) -> RepoAccess {
|
||||
let endpoint = format!("repos/{owner}/{name}");
|
||||
let mut cmd =
|
||||
clean_gh_command(program, &["api", "--hostname", "github.com", &endpoint, "--jq", ".permissions.push"]);
|
||||
cmd.env("GH_TOKEN", token);
|
||||
let Ok(out) = GH_TOOL.run(cmd, PROBE_TIMEOUT, None) else {
|
||||
return RepoAccess::None;
|
||||
};
|
||||
if !out.success {
|
||||
return RepoAccess::None;
|
||||
}
|
||||
if out.stdout.trim() == "true" { RepoAccess::Push } else { RepoAccess::Read }
|
||||
}
|
||||
|
||||
fn pick_best_account(candidates: &[(GhAuthAccount, RepoAccess)]) -> Option<(&GhAuthAccount, bool)> {
|
||||
let active_access =
|
||||
candidates.iter().find(|(a, _)| a.active).map(|(_, access)| *access).unwrap_or(RepoAccess::None);
|
||||
// Prefer higher RepoAccess; break ties in favor of the globally active account.
|
||||
let (best, best_access) = candidates.iter().max_by_key(|(acc, access)| (*access, acc.active))?;
|
||||
if *best_access == RepoAccess::None {
|
||||
// Nobody could reach the repo (offline or SSO required): keep the active account.
|
||||
return candidates.iter().find(|(a, _)| a.active).or_else(|| candidates.first()).map(|(a, _)| (a, false));
|
||||
}
|
||||
let auto_detected = !best.active && *best_access > active_access;
|
||||
Some((best, auto_detected))
|
||||
}
|
||||
|
||||
/// Parses `github.com` `(owner, repo)` from HTTPS, SSH, or SCP-style remote URLs.
|
||||
pub(crate) fn parse_github_owner_repo(url: &str) -> Option<(String, String)> {
|
||||
let url = url.trim();
|
||||
let path = if let Some(rest) =
|
||||
url.strip_prefix("https://github.com/").or_else(|| url.strip_prefix("http://github.com/"))
|
||||
{
|
||||
rest
|
||||
} else if let Some(rest) = url.strip_prefix("ssh://") {
|
||||
rest.strip_prefix("[email protected]/").or_else(|| rest.strip_prefix("github.com/"))?
|
||||
} else {
|
||||
url.strip_prefix("[email protected]:")?
|
||||
};
|
||||
let path = path.trim_matches('/');
|
||||
let (owner, rest) = path.split_once('/')?;
|
||||
let repo = rest.split('/').next()?;
|
||||
let repo = repo.strip_suffix(".git").unwrap_or(repo);
|
||||
if owner.is_empty() || repo.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some((owner.to_owned(), repo.to_owned()))
|
||||
}
|
||||
|
||||
fn primary_github_repo(project: &Project) -> Option<(String, String)> {
|
||||
let repos = project.repos();
|
||||
let mut ordered = Vec::new();
|
||||
if let Some(primary) = repos.primary() {
|
||||
ordered.push(primary);
|
||||
}
|
||||
for repo in repos.all() {
|
||||
if ordered.first().is_none_or(|p| p.root() != repo.root()) {
|
||||
ordered.push(repo);
|
||||
}
|
||||
}
|
||||
for repo in ordered {
|
||||
let Ok(mut remotes) = repo.remotes() else { continue };
|
||||
remotes.sort_by_key(|r| r.name != "origin");
|
||||
for remote in remotes {
|
||||
let url = remote.resolved_url.as_deref().unwrap_or(&remote.url);
|
||||
if let Some(coords) = parse_github_owner_repo(url) {
|
||||
return Some(coords);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn auto_detect_account(program: &Path, accounts: &[GhAuthAccount], owner: &str, repo: &str) -> Option<(String, bool)> {
|
||||
// Fast path: the repository owner matches one of the signed-in accounts directly.
|
||||
if let Some(matched) = accounts.iter().find(|a| a.login.eq_ignore_ascii_case(owner)) {
|
||||
return Some((matched.login.clone(), !matched.active));
|
||||
}
|
||||
let key_repo = format!("{}/{}", owner.to_ascii_lowercase(), repo.to_ascii_lowercase());
|
||||
let key_logins: Vec<String> = accounts.iter().map(|a| format!("{}:{}", a.login, a.active)).collect();
|
||||
let cache_key = (key_repo, key_logins);
|
||||
if let Some(cached) = AUTO_CACHE.lock().get(&cache_key).cloned()
|
||||
&& cached.at.elapsed() < CACHE_TTL
|
||||
{
|
||||
if let Some(login) = cached.login {
|
||||
let is_active = accounts.iter().any(|a| a.login == login && a.active);
|
||||
return Some((login, !is_active));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
|
||||
let tokens: Vec<(GhAuthAccount, Option<String>)> =
|
||||
accounts.iter().map(|acc| (acc.clone(), gh_token_for_account(program, &acc.login))).collect();
|
||||
let results: Vec<(GhAuthAccount, RepoAccess)> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = tokens
|
||||
.into_iter()
|
||||
.map(|(acc, token)| {
|
||||
s.spawn(move || {
|
||||
let access = match token {
|
||||
Some(tok) => probe_repo_access(program, &tok, owner, repo),
|
||||
None => RepoAccess::None,
|
||||
};
|
||||
(acc, access)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles.into_iter().filter_map(|h| h.join().ok()).collect()
|
||||
});
|
||||
let picked = pick_best_account(&results).map(|(acc, auto)| (acc.login.clone(), auto));
|
||||
AUTO_CACHE
|
||||
.lock()
|
||||
.insert(cache_key, CachedAutoAccount { login: picked.as_ref().map(|(l, _)| l.clone()), at: Instant::now() });
|
||||
picked
|
||||
}
|
||||
|
||||
/// Resolves global status when no project is open.
|
||||
pub fn global_status(configured_account: String) -> GhProjectAccountStatus {
|
||||
let configured_account = configured_account.trim().to_owned();
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone())
|
||||
};
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account: None }
|
||||
}
|
||||
|
||||
/// Applies the project's explicit `vcs.github.account` setting to [`ide_core::project_env`]
|
||||
/// without making any network requests. `Automatic` (`""`) clears any injected `GH_TOKEN` so
|
||||
/// processes use `gh`'s own behaviour.
|
||||
pub fn apply_to_project(project: &Project) {
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return;
|
||||
}
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if configured_account.is_empty() {
|
||||
set_project_token(project, None);
|
||||
return;
|
||||
}
|
||||
let token = find_gh_executable().and_then(|program| gh_token_for_account(&program, &configured_account));
|
||||
set_project_token(project, token);
|
||||
}
|
||||
|
||||
/// Applies the project's explicit account setting and returns the full account status,
|
||||
/// probing the project's GitHub remote to suggest a matching non-active `gh` account when
|
||||
/// `vcs.github.account` is `Automatic` (`""`) and multiple `gh` accounts are signed in.
|
||||
pub fn project_status(project: &Project) -> GhProjectAccountStatus {
|
||||
let configured_account = project.settings.effective().vcs.github.account.trim().to_owned();
|
||||
if project.light || !project.is_trusted() {
|
||||
clear_project_env(project);
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
}
|
||||
apply_to_project(project);
|
||||
let Some(program) = find_gh_executable() else {
|
||||
return GhProjectAccountStatus { configured_account, ..GhProjectAccountStatus::default() };
|
||||
};
|
||||
let (gh_installed, accounts) = ide_agent::gh_authenticated_accounts();
|
||||
let active_login = accounts.iter().find(|a| a.active).or_else(|| accounts.first()).map(|a| a.login.clone());
|
||||
|
||||
let effective_account = if !configured_account.is_empty() {
|
||||
accounts.iter().any(|a| a.login == configured_account).then(|| configured_account.clone())
|
||||
} else {
|
||||
active_login
|
||||
};
|
||||
|
||||
let suggested_account = if configured_account.is_empty() && accounts.len() >= 2 {
|
||||
primary_github_repo(project)
|
||||
.and_then(|(owner, repo)| auto_detect_account(&program, &accounts, &owner, &repo))
|
||||
.and_then(|(login, non_active_match)| non_active_match.then_some(login))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
GhProjectAccountStatus { gh_installed, accounts, configured_account, effective_account, suggested_account }
|
||||
}
|
||||
|
||||
fn set_project_token(project: &Project, token: Option<String>) {
|
||||
let os_tok = token.map(std::ffi::OsString::from);
|
||||
let changed_root = ide_core::project_env::set_github_token(&project.root, os_tok.clone());
|
||||
let changed_wt = ide_core::project_env::set_github_token(project.agents.worktrees_dir(), os_tok);
|
||||
if changed_root || changed_wt {
|
||||
project.agents.notify_mcp_servers_changed();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear_project_env(project: &Project) {
|
||||
ide_core::project_env::remove_all(&project.root);
|
||||
ide_core::project_env::remove_all(project.agents.worktrees_dir());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_github_owner_repo_across_https_ssh_and_scp_remotes() {
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("https://github.com/l0ng-ai/openidea.git"),
|
||||
Some(("l0ng-ai".into(), "openidea".into()))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_github_owner_repo("[email protected]:acme-corp/payments.git"),
|
||||
Some(("acme-corp".into(), "payments".into()))
|
||||
);
|
||||
assert_eq!(parse_github_owner_repo("ssh://[email protected]/alice/demo/"), Some(("alice".into(), "demo".into())));
|
||||
assert_eq!(parse_github_owner_repo("https://gitlab.com/foo/bar.git"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_github_logins_against_flag_injection() {
|
||||
assert!(is_valid_github_login("alice"));
|
||||
assert!(is_valid_github_login("alice-work"));
|
||||
assert!(is_valid_github_login("l0ng-ai"));
|
||||
assert!(!is_valid_github_login(""));
|
||||
assert!(!is_valid_github_login("--hostname"));
|
||||
assert!(!is_valid_github_login("bad space"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picks_account_with_push_or_private_access_and_preserves_active_on_ties() {
|
||||
let personal = GhAuthAccount { login: "alice".into(), active: true };
|
||||
let work = GhAuthAccount { login: "alice-work".into(), active: false };
|
||||
|
||||
// Private org repo: personal gets 404 (None), work gets Push -> auto-detects work.
|
||||
let private_org = vec![(personal.clone(), RepoAccess::None), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&private_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Public org repo: personal gets Read, work gets Push -> auto-detects work.
|
||||
let public_org = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Push)];
|
||||
let (picked, auto) = pick_best_account(&public_org).unwrap();
|
||||
assert_eq!(picked.login, "alice-work");
|
||||
assert!(auto);
|
||||
|
||||
// Third-party public repo: both get Read -> keeps active personal account without auto flag.
|
||||
let oss = vec![(personal.clone(), RepoAccess::Read), (work.clone(), RepoAccess::Read)];
|
||||
let (picked, auto) = pick_best_account(&oss).unwrap();
|
||||
assert_eq!(picked.login, "alice");
|
||||
assert!(!auto);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ pub mod diagnostics_store;
|
||||
mod direnv;
|
||||
pub mod environment;
|
||||
mod formatter;
|
||||
pub mod github_auth;
|
||||
mod java_runtime;
|
||||
mod kotlin_bridge;
|
||||
pub mod mcp;
|
||||
@@ -419,6 +420,7 @@ impl Host {
|
||||
self.environment.project_closed();
|
||||
if self.windows_for_root(&project.root).is_empty() {
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
}
|
||||
}
|
||||
if let Some(bridge) = &project.kotlin_bridge {
|
||||
@@ -701,6 +703,12 @@ impl Host {
|
||||
self.requests.begin(id)
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: nothing
|
||||
/// is fetched from public package registries the user's tools weren't pointed at.
|
||||
pub fn configured_registries_only(&self) -> bool {
|
||||
self.global_settings.effective().tool_downloads.configured_registries_only
|
||||
}
|
||||
|
||||
pub fn begin_project_request(&self, window: &str, id: RequestId) -> CancellationToken {
|
||||
let token = self.begin_project_read_request(window, id);
|
||||
if self.project(window).is_ok_and(|p| !p.is_trusted()) {
|
||||
|
||||
@@ -493,7 +493,7 @@ fn test_kinds(rel: &str) -> &'static [&'static str] {
|
||||
if JS_FILE.is_match(rel) {
|
||||
&["npm", "deno", "bun"]
|
||||
} else if rel.ends_with(".py") {
|
||||
&["pytest", "python"]
|
||||
&["pytest", "unittest", "python"]
|
||||
} else if rel.ends_with(".go") {
|
||||
&["go"]
|
||||
} else if rel.ends_with(".rs") {
|
||||
@@ -644,6 +644,11 @@ fn test_config_for(root: &Path, rel: &str, configs: &[RunConfig]) -> Option<RunC
|
||||
"npm" | "bun" if base.args.iter().any(|a| a == "--") => derived(&base, rel, with(&[file])),
|
||||
"npm" | "bun" => derived(&base, rel, with(&["--".into(), file])),
|
||||
"deno" | "pytest" | "python" => derived(&base, rel, with(&[file])),
|
||||
// `python -m unittest <file>`; a `discover` selection gives way to the file.
|
||||
"unittest" => {
|
||||
let end = base.args.iter().position(|a| a == "discover").unwrap_or(base.args.len());
|
||||
derived(&base, rel, [base.args[..end].to_vec(), vec![file]].concat())
|
||||
}
|
||||
"go" => {
|
||||
let dir = dir_of(&file);
|
||||
let target = if dir.is_empty() { ".".to_owned() } else { format!("./{dir}") };
|
||||
@@ -790,6 +795,11 @@ pub fn target_config(
|
||||
"pytest" | "python" => {
|
||||
Some(named(replace_last(file.args.clone(), |f| format!("{f}::{}", target.path.join("::")))))
|
||||
}
|
||||
// unittest names tests by dotted module path: `tests.test_calc.TestCalc.test_add`.
|
||||
"unittest" => Some(named(replace_last(file.args.clone(), |f| {
|
||||
let module = f.strip_suffix(".py").unwrap_or(f).replace(['/', '\\'], ".");
|
||||
format!("{module}.{}", target.path.join("."))
|
||||
}))),
|
||||
"go" => {
|
||||
let pattern = format!("^{}$", target.path.iter().map(|p| escape_regexp(p)).collect::<Vec<_>>().join("$/^"));
|
||||
let benchmark = target.path.first().is_some_and(|p| p.starts_with("Benchmark"));
|
||||
@@ -921,6 +931,30 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_unittest_configs_to_files_and_dotted_tests() {
|
||||
let root = Path::new("/p");
|
||||
let mut unittest =
|
||||
blank("unittest".into(), "unittest", "unittest", "python3".into(), vec!["-m".into(), "unittest".into()]);
|
||||
unittest.is_test = true;
|
||||
let mut discover = unittest.clone();
|
||||
discover.args.extend(["discover".into(), "-s".into(), "tests".into()]);
|
||||
let src = "import unittest\n\nclass TestCalc(unittest.TestCase):\n def test_add(self):\n pass\n";
|
||||
let rel = "tests/test_calc.py";
|
||||
for configs in [vec![unittest], vec![discover]] {
|
||||
let c = context_config(root, rel, &configs, src).unwrap();
|
||||
assert_eq!(
|
||||
(c.kind.as_str(), c.args.as_slice()),
|
||||
("unittest", ["-m", "unittest", rel].map(String::from).as_slice())
|
||||
);
|
||||
let ts = detect(src, rel);
|
||||
let c = target_config(root, &ts[1], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc.test_add"]);
|
||||
let c = target_config(root, &ts[0], rel, &configs, src).unwrap();
|
||||
assert_eq!(c.args, ["-m", "unittest", "tests.test_calc.TestCalc"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrows_cargo_test_configs() {
|
||||
let root = Path::new("/p");
|
||||
|
||||
@@ -754,6 +754,8 @@ pub fn spec(os: Os) -> Vec<Entry> {
|
||||
));
|
||||
|
||||
let mut tools = vec![
|
||||
act("code.saveAsLiveTemplate", "Save as Live Template…"),
|
||||
SEP,
|
||||
act("http.newRequest", "New HTTP Request"),
|
||||
act("http.showToolWindow", "HTTP Client"),
|
||||
SEP,
|
||||
|
||||
@@ -6,11 +6,11 @@ use crate::agent_secrets::{AgentSecrets, Kept};
|
||||
use ide_agent::registry::{AgentRegistry, RegistryPaths};
|
||||
use ide_agent::{
|
||||
AcpImportOutcome, AgentAcceptOutcome, AgentChange, AgentChanges, AgentChangesView, AgentCliOffer,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentModelCatalog, AgentProbe,
|
||||
AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, McpExternalSource, McpImportSelection,
|
||||
McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, RemoteSkillBrowseResult,
|
||||
RemoteSkillPreview, SkillsPolicy,
|
||||
AgentCliUpdateResult, AgentCommand, AgentContextUsage, AgentEntry, AgentEvent, AgentLoginEvent, AgentModelCatalog,
|
||||
AgentProbe, AgentPrompt, AgentProvider, AgentQueued, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask,
|
||||
CopilotAuthStatus, CustomAgentInput, ExternalSession, InstallRemoteSkillRequest, LoginLaunch, McpExternalSource,
|
||||
McpImportSelection, McpProbeResult, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask,
|
||||
RemoteSkillBrowseResult, RemoteSkillPreview, SkillsPolicy,
|
||||
};
|
||||
use ide_command::command;
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -80,6 +80,19 @@ pub fn agent_refresh_models(
|
||||
host.project(window)?.agents.refresh_models(&provider, force, model.as_deref())
|
||||
}
|
||||
|
||||
/// Probes Copilot's model catalog for a staged GitHub account without persisting until Apply.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn agent_preview_copilot_models(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
account: String,
|
||||
model: Option<String>,
|
||||
) -> IdeResult<AgentModelCatalog> {
|
||||
host.require_trust(window)?;
|
||||
let agents = host.project(window)?.agents.clone();
|
||||
agents.preview_copilot_models(&account, model.as_deref()).await
|
||||
}
|
||||
|
||||
/// Overrides built-in agent `id`'s command with `command` (its agent file keeps the
|
||||
/// built-in's driver and arguments), or returns it to auto-detection with `None`.
|
||||
#[command(trust = trusted)]
|
||||
@@ -108,6 +121,141 @@ pub fn agent_set_env(
|
||||
host.project(window)?.agents.set_builtin_env(&id, env)
|
||||
}
|
||||
|
||||
/// Default Copilot CLI sign-in status alongside authenticated `github.com` accounts in `gh`.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_copilot_auth_status(host: &Host, window: &str) -> IdeResult<CopilotAuthStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
match host.project(window) {
|
||||
Ok(project) => Ok(project.agents.copilot_auth_status().await),
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
Ok(ide_agent::copilot_auth_status_with(Some(&custom_dir), None, &cwd).await)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const REMOTE_SESSION_ENV_VARS: [&str; 5] =
|
||||
["SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "CODESPACES", "REMOTE_CONTAINERS"];
|
||||
|
||||
fn prepare_login_launch_env(
|
||||
is_remote: bool,
|
||||
target_is_gh: bool,
|
||||
env: &mut std::collections::BTreeMap<String, String>,
|
||||
host_has: impl Fn(&str) -> bool,
|
||||
) {
|
||||
if !is_remote {
|
||||
return;
|
||||
}
|
||||
let has_non_empty = |env: &std::collections::BTreeMap<String, String>, key: &str| {
|
||||
env.get(key).is_some_and(|v| !v.is_empty()) || host_has(key)
|
||||
};
|
||||
// `openidea-server` spawns sign-in commands in a real PTY even inside WSL, dev containers,
|
||||
// and `--web`, where `SSH_*` variables are absent; mark the session remote so CLIs such as
|
||||
// `copilot login` choose OAuth device-code sign-in over a remote-only loopback server.
|
||||
if !REMOTE_SESSION_ENV_VARS.iter().any(|key| has_non_empty(env, key)) {
|
||||
env.insert("REMOTE_CONTAINERS".into(), "1".into());
|
||||
}
|
||||
if target_is_gh && !has_non_empty(env, "GH_BROWSER") && !has_non_empty(env, "BROWSER") {
|
||||
env.insert("GH_BROWSER".into(), "true".into());
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_remote_login_env(host: &Host, cwd: &std::path::Path, target_is_gh: bool, launch: &mut LoginLaunch) {
|
||||
let cwd = if cwd.is_dir() { cwd.to_path_buf() } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
prepare_login_launch_env(host.environment.is_remote(), target_is_gh, &mut launch.env, |key| {
|
||||
ide_core::process::host_var_os_in(&cwd, key).is_some_and(|v| !v.is_empty())
|
||||
});
|
||||
}
|
||||
|
||||
fn spawn_login_pty(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cwd: std::path::PathBuf,
|
||||
launch: LoginLaunch,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
crate::ops::term::apply_output_rate(host, window);
|
||||
let cwd = if cwd.is_dir() { cwd } else { dirs::home_dir().unwrap_or_else(std::env::temp_dir) };
|
||||
let options = ide_terminal::TerminalOptions {
|
||||
cwd: cwd.into(),
|
||||
shell: Some(launch.program.to_string_lossy().into_owned()),
|
||||
args: launch.args,
|
||||
env: launch.env,
|
||||
cols: if cols == 0 { 80 } else { cols },
|
||||
rows: if rows == 0 { 20 } else { rows },
|
||||
shell_integration: false,
|
||||
};
|
||||
let exit_channel = on_event.clone();
|
||||
host.terminals.spawn_program(
|
||||
options,
|
||||
format!("agent-login:{window}"),
|
||||
host.window_sink(window),
|
||||
Box::new(move |data| {
|
||||
let _ = on_event.send(AgentLoginEvent::Output { data });
|
||||
}),
|
||||
Some(std::sync::Arc::new(move |code| {
|
||||
let _ = exit_channel.send(AgentLoginEvent::Exited { code });
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// Starts agent `id`'s interactive sign-in flow in an IDE-managed PTY and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
id: String,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let (cwd, mut launch) = match host.project(window) {
|
||||
Ok(project) => {
|
||||
let root = project.root.clone();
|
||||
let agents = project.agents.clone();
|
||||
let launch = host.blocking(move || agents.login_launch(&id)).await?;
|
||||
(root, launch)
|
||||
}
|
||||
Err(_) => {
|
||||
let custom_dir = host.config_dir.join("agents");
|
||||
let cwd = dirs::home_dir().unwrap_or_else(std::env::temp_dir);
|
||||
let cwd_for_lookup = cwd.clone();
|
||||
let launch = host
|
||||
.blocking(move || {
|
||||
ide_agent::login_launch_without_project(Some(&custom_dir), None, &cwd_for_lookup, &id)
|
||||
})
|
||||
.await?;
|
||||
(cwd, launch)
|
||||
}
|
||||
};
|
||||
apply_remote_login_env(host, &cwd, false, &mut launch);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Starts `gh auth login --hostname github.com` in an IDE-managed PTY (with ambient token
|
||||
/// variables cleared) and streams its output and exit code.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn agent_gh_login_spawn(
|
||||
host: &Host,
|
||||
window: &str,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
on_event: Channel<AgentLoginEvent>,
|
||||
) -> IdeResult<ide_terminal::TerminalInfo> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let cwd = host
|
||||
.project(window)
|
||||
.map(|p| p.root.clone())
|
||||
.unwrap_or_else(|_| dirs::home_dir().unwrap_or_else(std::env::temp_dir));
|
||||
let mut launch = host.blocking(ide_agent::gh_login_launch).await?;
|
||||
apply_remote_login_env(host, &cwd, true, &mut launch);
|
||||
spawn_login_pty(host, window, cwd, launch, cols, rows, on_event)
|
||||
}
|
||||
|
||||
/// Saves a new custom ACP agent through its agent file.
|
||||
pub fn save_custom_agent(host: &Host, window: &str, input: CustomAgentInput) -> IdeResult<()> {
|
||||
host.require_trust(window)?;
|
||||
@@ -185,6 +333,7 @@ pub async fn agent_registry_install(
|
||||
) -> IdeResult<()> {
|
||||
// The agent then shows in `agent_providers`.
|
||||
let paths = registry_paths(host);
|
||||
let public_npm_fallback = !host.configured_registries_only();
|
||||
let installing = Installing::begin(&id)?;
|
||||
let cancel = host.begin_request(request);
|
||||
// Also a background task of every project window, so it stays visible and can be
|
||||
@@ -211,7 +360,7 @@ pub async fn agent_registry_install(
|
||||
move || cancel.cancel()
|
||||
});
|
||||
report(None, None, false);
|
||||
let result = ide_agent::registry::install(&paths, &id, &cancel, &|e| {
|
||||
let result = ide_agent::registry::install(&paths, &id, public_npm_fallback, &cancel, &|e| {
|
||||
match &e {
|
||||
InstallEvent::Line { text } => report(Some(text.clone()), None, false),
|
||||
InstallEvent::Progress { fraction, message } => {
|
||||
@@ -1448,6 +1597,29 @@ mod tests {
|
||||
assert!(reloaded.approved(&root, "extra", &extra));
|
||||
assert!(!reloaded.approved(&tmp.path().join("other"), "extra", &extra));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prepare_login_launch_env_marks_remote_sessions_for_device_code_auth() {
|
||||
let mut desktop_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(false, true, &mut desktop_env, |_| false);
|
||||
assert!(desktop_env.is_empty());
|
||||
|
||||
let mut remote_agent_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, false, &mut remote_agent_env, |_| false);
|
||||
assert_eq!(remote_agent_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert!(!remote_agent_env.contains_key("GH_BROWSER"));
|
||||
|
||||
let mut remote_gh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut remote_gh_env, |_| false);
|
||||
assert_eq!(remote_gh_env.get("REMOTE_CONTAINERS").map(String::as_str), Some("1"));
|
||||
assert_eq!(remote_gh_env.get("GH_BROWSER").map(String::as_str), Some("true"));
|
||||
|
||||
// Preserves existing SSH/remote indicators and explicit browser settings.
|
||||
let mut ssh_env = std::collections::BTreeMap::new();
|
||||
prepare_login_launch_env(true, true, &mut ssh_env, |k| matches!(k, "SSH_CONNECTION" | "BROWSER"));
|
||||
assert!(!ssh_env.contains_key("REMOTE_CONTAINERS"));
|
||||
assert!(!ssh_env.contains_key("GH_BROWSER"));
|
||||
}
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
@@ -1462,15 +1634,18 @@ ide_command::domain!(
|
||||
agent_cli_update,
|
||||
agent_cli_update_check,
|
||||
agent_commands,
|
||||
agent_copilot_auth_status,
|
||||
agent_create,
|
||||
agent_delete,
|
||||
agent_entries,
|
||||
agent_external_sessions,
|
||||
agent_fork,
|
||||
agent_fork_session,
|
||||
agent_gh_login_spawn,
|
||||
agent_grouped_changes,
|
||||
agent_hermes_profiles,
|
||||
agent_import_session,
|
||||
agent_login_spawn,
|
||||
agent_mcp_discover_sources,
|
||||
agent_mcp_import,
|
||||
agent_mcp_import_selected,
|
||||
@@ -1480,6 +1655,7 @@ ide_command::domain!(
|
||||
agent_mcp_save_json,
|
||||
agent_mcp_set_enabled,
|
||||
agent_mcp_test,
|
||||
agent_preview_copilot_models,
|
||||
agent_probe,
|
||||
agent_prompt,
|
||||
agent_providers,
|
||||
|
||||
@@ -767,6 +767,7 @@ pub async fn maven_dependency_completion(
|
||||
use ide_build::maven::completion::{PomCompletionKind, local_options};
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let central = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -785,7 +786,10 @@ pub async fn maven_dependency_completion(
|
||||
// The local repository answers at once: Central gets `CENTRAL_WAIT`, then the
|
||||
// lookup finishes in the background and fills the cache for the next request.
|
||||
// Offline, behind a proxy or rate-limited, a failed fetch never fails completion.
|
||||
let remote = {
|
||||
// Only the configured package registries: the local repository alone.
|
||||
let remote = if !central {
|
||||
Vec::new()
|
||||
} else {
|
||||
let (cache, target) = (cache.clone(), target.clone());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
|
||||
@@ -212,6 +212,8 @@ pub async fn dependency_versions(
|
||||
let project = host.project(window)?;
|
||||
let cache = host.dependency_versions.clone();
|
||||
let config_dir = host.config_dir.clone();
|
||||
// npm and crates.io are asked directly; `go` goes through the configured GOPROXY.
|
||||
let public_registries = !host.configured_registries_only();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -228,6 +230,9 @@ pub async fn dependency_versions(
|
||||
let versions = cache.versions(&source, &dependency.package, &cancel)?;
|
||||
return Ok(vec![DependencyVersions { dependency, versions, update: None }]);
|
||||
}
|
||||
if !public_registries {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
if snap.path.file_name().is_some_and(|name| name == "package.json") {
|
||||
let Some(dependency) = offset.and_then(|offset| npm::dependency_at(&snap.text, offset)) else {
|
||||
return Ok(Vec::new());
|
||||
@@ -310,6 +315,9 @@ pub async fn pypi_package(
|
||||
request: RequestId,
|
||||
) -> IdeResult<Option<pypi::PypiPackage>> {
|
||||
let url = pypi::project_url(name.trim()).ok_or_else(|| IdeError::invalid("not a package name"))?;
|
||||
if host.configured_registries_only() {
|
||||
return Ok(None);
|
||||
}
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
.blocking(move || {
|
||||
@@ -334,6 +342,9 @@ pub async fn pypi_package(
|
||||
/// PyPI's name list, which the first search downloads and a search a day later refreshes.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn pypi_search(host: &Host, window: &str, query: String, request: RequestId) -> IdeResult<Vec<String>> {
|
||||
if host.configured_registries_only() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let names = host.pypi_names.clone();
|
||||
let cancel = host.begin_project_read_request(window, request);
|
||||
let result = host
|
||||
|
||||
@@ -67,7 +67,12 @@ pub async fn doc_edit(host: &Host, window: &str, doc: DocId, base_version: u32,
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save(doc)).await?;
|
||||
host.blocking(move || {
|
||||
project.documents.save(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(())
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
@@ -83,7 +88,13 @@ pub async fn doc_reload_from_disk(host: &Host, window: &str, doc: DocId) -> IdeR
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bool> {
|
||||
let project = host.project(window)?;
|
||||
let saved = host.blocking(move || project.documents.autosave(doc)).await?;
|
||||
let saved = host
|
||||
.blocking(move || {
|
||||
let saved = project.documents.autosave(doc)?;
|
||||
remember_saved_encodings(&project);
|
||||
Ok(saved)
|
||||
})
|
||||
.await?;
|
||||
if saved {
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await?;
|
||||
}
|
||||
@@ -93,7 +104,12 @@ pub async fn doc_autosave(host: &Host, window: &str, doc: DocId) -> IdeResult<bo
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_save_all(host: &Host, window: &str) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || project.documents.save_all()).await?;
|
||||
host.blocking(move || {
|
||||
let saved = project.documents.save_all();
|
||||
remember_saved_encodings(&project);
|
||||
saved
|
||||
})
|
||||
.await?;
|
||||
host.debugger.refresh_source_mirrors(host.owner_window(window)).await
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
use crate::Host;
|
||||
use crate::ops::blocking;
|
||||
use crate::project::Project;
|
||||
use ide_command::command;
|
||||
use ide_core::{DocId, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_core::{DocId, IdeEvent, IdeResult, OutlineItem, Range, TextEdit};
|
||||
use ide_language::{FoldRange, SyntaxHighlights};
|
||||
use ide_text::LineEnding;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, HistoryEntry};
|
||||
use std::path::PathBuf;
|
||||
use ide_workspace::settings::SettingsScope;
|
||||
use ide_workspace::{DocumentEncoding, DocumentInfo, DocumentLanguage, FileDefaults, HistoryEntry};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Opens a read-only virtual document (see `lsp_virtual_document`) as an
|
||||
/// editor buffer, so syntax features and language-server requests work in it.
|
||||
@@ -66,6 +68,49 @@ pub async fn doc_set_encoding(
|
||||
host.blocking(move || project.documents.set_encoding(doc, &encoding, reload)).await
|
||||
}
|
||||
|
||||
/// Keeps the encoding the user chose for a project file in the project's File Encodings
|
||||
/// mappings, so the file opens in it again. A converted document is kept once it is saved:
|
||||
/// until then its file is still in the old encoding. Nothing is kept for a document without
|
||||
/// a file in the project.
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_remember_encoding(host: &Host, window: &str, doc: DocId) -> IdeResult<()> {
|
||||
let project = host.project(window)?;
|
||||
blocking(move || {
|
||||
let info = project.documents.snapshot(doc)?;
|
||||
if info.uri.is_some() || project.documents.keep_encoding_when_saved(doc)? {
|
||||
return Ok(());
|
||||
}
|
||||
remember_encoding(&project, &info.path, &info.encoding)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Keeps the encodings of the converted documents a save has just written.
|
||||
pub(super) fn remember_saved_encodings(project: &Project) {
|
||||
for (path, encoding) in project.documents.take_saved_encodings() {
|
||||
if let Err(e) = remember_encoding(project, &path, &encoding) {
|
||||
tracing::warn!("the encoding of {} was not kept: {e}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remember_encoding(project: &Project, path: &Path, encoding: &str) -> IdeResult<()> {
|
||||
const MAPPINGS: &str = "editor.encodings.mappings";
|
||||
if project.light {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(file) = ide_workspace::file_defaults::mapping_key(&project.root, path) else {
|
||||
return Ok(());
|
||||
};
|
||||
if project.settings.effective().editor.encodings.mappings.get(&file).is_some_and(|kept| kept == encoding) {
|
||||
return Ok(());
|
||||
}
|
||||
let settings = project.settings.set_map_entry(SettingsScope::Project, MAPPINGS, &file, encoding.into())?;
|
||||
project.documents.set_file_defaults(FileDefaults::from_settings(&settings, Some(&project.root)));
|
||||
project.sink.emit(IdeEvent::SettingsChanged { key: MAPPINGS.into() });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn doc_set_bom(host: &Host, window: &str, doc: DocId, has_bom: bool) -> IdeResult<DocumentEncoding> {
|
||||
// Adds or removes the BOM on a UTF-8 document; the change is written on save.
|
||||
@@ -118,7 +163,7 @@ pub async fn doc_outline(host: &Host, window: &str, doc: DocId) -> IdeResult<Vec
|
||||
}
|
||||
items
|
||||
}
|
||||
None if snap.large && snap.language.as_str() != "markdown" => Vec::new(),
|
||||
None if snap.large && !matches!(snap.language.as_str(), "markdown" | "mdx") => Vec::new(),
|
||||
None => syntax(),
|
||||
})
|
||||
})
|
||||
@@ -263,6 +308,7 @@ ide_command::domain!(
|
||||
doc_outline,
|
||||
doc_python_facts,
|
||||
doc_rearrange,
|
||||
doc_remember_encoding,
|
||||
doc_selection_ranges,
|
||||
doc_set_bom,
|
||||
doc_set_encoding,
|
||||
|
||||
@@ -221,3 +221,98 @@ async fn rearrange_returns_utf16_edits_that_put_methods_in_order() {
|
||||
f.sync().await;
|
||||
assert!(doc_rearrange(&f.host, "main", doc).await.unwrap().is_empty());
|
||||
}
|
||||
|
||||
const MAPPINGS_CHANGED: &str = "editor.encodings.mappings";
|
||||
|
||||
impl Fixture {
|
||||
fn project_settings(&self) -> PathBuf {
|
||||
self.project.settings.file(ide_workspace::settings::SettingsScope::Project).unwrap().to_path_buf()
|
||||
}
|
||||
|
||||
fn mappings_changed(&self) -> usize {
|
||||
let events = self.events.lock();
|
||||
events.iter().filter(|e| matches!(e, IdeEvent::SettingsChanged { key } if key == MAPPINGS_CHANGED)).count()
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn remembered_encoding_is_written_once_and_used_when_the_file_is_reopened() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
// Changing the encoding alone (Reload from Disk, an RPC client) keeps nothing.
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
assert!(!settings.exists());
|
||||
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
let written = std::fs::read_to_string(&settings).unwrap();
|
||||
assert_eq!(written, "[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n");
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
// The same choice again leaves the file alone.
|
||||
let stamp = std::fs::metadata(&settings).unwrap().modified().unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
assert_eq!(std::fs::metadata(&settings).unwrap().modified().unwrap(), stamp);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
|
||||
// A file outside the project has no place in the project's settings.
|
||||
let outside = f.open(&f.outside).await;
|
||||
doc_set_encoding(&f.host, "main", outside.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", outside.id).await.unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), written);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn converted_encoding_is_remembered_once_the_file_is_saved_in_it() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::write(&f.path, "ação\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", doc.id).await.unwrap();
|
||||
// The file is still UTF-8 on disk: closing without saving must not leave it mapped.
|
||||
assert!(!settings.exists());
|
||||
doc_close(&f.host, "main", doc.id).await.unwrap();
|
||||
let reopened = f.open(&f.path).await;
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("utf-8", "ação\n"));
|
||||
|
||||
doc_set_encoding(&f.host, "main", reopened.id, "iso-8859-15".into(), false).await.unwrap();
|
||||
doc_remember_encoding(&f.host, "main", reopened.id).await.unwrap();
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(std::fs::read(&f.path).unwrap(), b"a\xe7\xe3o\n");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&settings).unwrap(),
|
||||
"[editor.encodings.mappings]\n\"node_modules/file.txt\" = \"iso-8859-15\"\n"
|
||||
);
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
// Later saves keep nothing more.
|
||||
doc_save(&f.host, "main", reopened.id).await.unwrap();
|
||||
assert_eq!(f.mappings_changed(), 1);
|
||||
|
||||
doc_close(&f.host, "main", reopened.id).await.unwrap();
|
||||
let again = f.open(&f.path).await;
|
||||
assert_eq!((again.encoding.as_str(), again.text.as_str()), ("iso-8859-15", "ação\n"));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn encoding_stays_changed_when_it_cannot_be_remembered() {
|
||||
let f = Fixture::new();
|
||||
let settings = f.project_settings();
|
||||
std::fs::create_dir_all(settings.parent().unwrap()).unwrap();
|
||||
std::fs::write(&settings, "[editor\n").unwrap();
|
||||
let doc = f.open(&f.path).await;
|
||||
doc_set_encoding(&f.host, "main", doc.id, "iso-8859-15".into(), true).await.unwrap();
|
||||
|
||||
let err = doc_remember_encoding(&f.host, "main", doc.id).await.unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
assert_eq!(std::fs::read_to_string(&settings).unwrap(), "[editor\n");
|
||||
assert_eq!(f.project.documents.snapshot(doc.id).unwrap().encoding, "iso-8859-15");
|
||||
assert_eq!(f.mappings_changed(), 0);
|
||||
}
|
||||
@@ -142,7 +142,8 @@ pub(crate) async fn resolve_launch(
|
||||
};
|
||||
if let Some(outputs) = built {
|
||||
progress("Resolving the classpath");
|
||||
let mut info = project.lsp.java_launch(&module, test, false, false, false, cancel).await?;
|
||||
let server = project.lsp.java_launch(&module, test, false, false, false, cancel);
|
||||
let mut info = server_launch_extras(server, SERVER_EXTRAS_WAIT).await?;
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let cancel = cancel.clone();
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
@@ -393,6 +394,33 @@ fn is_maven_aggregator(root: &Path, model: &BuildModel, module: &Path) -> bool {
|
||||
/// Whether the IDE's Java build builds the module holding `path` (#4078): a Maven module unless
|
||||
/// Settings › Maven › Delegate IDE build/run actions to Maven asks for Maven; a Gradle module
|
||||
/// when Settings › Gradle › Build and run using asks for the IDE.
|
||||
/// How long a launch whose classpath the IDE's Java build resolved waits for what jdtls adds
|
||||
/// (the JDK it compiles against, the Java project root). jdtls can be busy for minutes importing
|
||||
/// a Maven project (resolving plugin dependencies), and the run doesn't need it:
|
||||
/// [`finish_launch`] picks the project's JDK or an installed one.
|
||||
const SERVER_EXTRAS_WAIT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
|
||||
/// jdtls' launch info, or an empty one when it doesn't answer within `wait` or fails.
|
||||
async fn server_launch_extras(
|
||||
server: impl std::future::Future<Output = IdeResult<JavaLaunchInfo>>,
|
||||
wait: std::time::Duration,
|
||||
) -> IdeResult<JavaLaunchInfo> {
|
||||
let fallback =
|
||||
|| JavaLaunchInfo { path_list_separator: if cfg!(windows) { ";" } else { ":" }.into(), ..Default::default() };
|
||||
match tokio::time::timeout(wait, server).await {
|
||||
Ok(Ok(info)) => Ok(info),
|
||||
Ok(Err(e)) if e.kind == ErrorKind::Cancelled => Err(e),
|
||||
Ok(Err(e)) => {
|
||||
tracing::warn!("Java launch without the language server's JDK: {}", e.message);
|
||||
Ok(fallback())
|
||||
}
|
||||
Err(_) => {
|
||||
tracing::info!(wait_ms = wait.as_millis(), "Java language server busy; launching without its JDK");
|
||||
Ok(fallback())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn served_by_service(root: &Path, model: &BuildModel, settings: &Settings, path: &Path) -> bool {
|
||||
let maven = model.maven.iter().flat_map(|m| m.projects.iter().map(|p| (root.join(&p.dir), true)));
|
||||
let gradle = model.gradle.iter().flat_map(|g| g.projects.iter().map(|p| (root.join(&p.dir), false)));
|
||||
@@ -922,7 +950,7 @@ pub async fn java_build_workspace(
|
||||
/// The JVM of OpenIDEA's JUnit runner for the module at `module`, given its resolved test classpath:
|
||||
/// the classpath with the runner and `junit-platform-launcher` of the engine's version (unless the
|
||||
/// classpath has one, or has JUnit 4 alone; from the engine's repository, else downloaded once from
|
||||
/// Maven Central), and,
|
||||
/// Maven Central unless only the configured package registries are allowed), and,
|
||||
/// for a Maven module, what its Surefire configuration gives the forked test JVM.
|
||||
#[command(trust = trusted)]
|
||||
pub async fn java_junit_runner(
|
||||
@@ -935,6 +963,7 @@ pub async fn java_junit_runner(
|
||||
let project = host.project(window)?;
|
||||
let module = ide_core::project_roots::resolve(&project.root, &module);
|
||||
let data_dir = host.local_data_dir.clone();
|
||||
let registries_only = host.configured_registries_only();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let scope = workspace::scope_for(&project, &module)?;
|
||||
let model = load_launch_model(&scope);
|
||||
@@ -948,7 +977,9 @@ pub async fn java_junit_runner(
|
||||
let launcher = match ide_sdk::java::junit_launcher(&class_paths) {
|
||||
ide_sdk::java::JunitLauncher::OnClasspath | ide_sdk::java::JunitLauncher::Junit4 => None,
|
||||
ide_sdk::java::JunitLauncher::Found(path) => Some(path),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => Some(download_junit_launcher(&data_dir, &version)?),
|
||||
ide_sdk::java::JunitLauncher::Missing(version) => {
|
||||
Some(download_junit_launcher(&data_dir, &version, registries_only)?)
|
||||
}
|
||||
ide_sdk::java::JunitLauncher::NoPlatform => {
|
||||
return Err(IdeError::unavailable(
|
||||
"Neither JUnit 5 (junit-platform-engine) nor JUnit 4 is on the test classpath. To run these tests \
|
||||
@@ -1017,7 +1048,9 @@ fn junit_launch(
|
||||
}
|
||||
}
|
||||
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf> {
|
||||
/// The launcher jar downloaded once from Maven Central; with only the configured package
|
||||
/// registries allowed (Settings › Tools › Download Mirrors), only one downloaded before.
|
||||
fn download_junit_launcher(data_dir: &Path, version: &str, registries_only: bool) -> IdeResult<PathBuf> {
|
||||
if version.is_empty() || !version.chars().all(|c| c.is_ascii_alphanumeric() || "._-".contains(c)) {
|
||||
return Err(IdeError::invalid(format!("Unexpected JUnit Platform version '{version}'")));
|
||||
}
|
||||
@@ -1026,6 +1059,14 @@ fn download_junit_launcher(data_dir: &Path, version: &str) -> IdeResult<PathBuf>
|
||||
if dest.is_file() {
|
||||
return Ok(dest);
|
||||
}
|
||||
if registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{name} is not on the test classpath, and Settings › Tools › Download Mirrors allows only the \
|
||||
configured package registries, so it is not downloaded from Maven Central. Add \
|
||||
org.junit.platform:junit-platform-launcher to the test dependencies, or set Settings › Build Tools › \
|
||||
Maven › Run tests using to Maven."
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(dest.parent().expect("has a parent"))?;
|
||||
let url = format!("https://repo1.maven.org/maven2/org/junit/platform/junit-platform-launcher/{version}/{name}");
|
||||
let partial = dest.with_extension("jar.part");
|
||||
@@ -1060,6 +1101,22 @@ fn drop_processor_recreate_errors(info: &mut JavaLaunchInfo) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_busy_or_failing_language_server_does_not_block_a_resolved_launch() {
|
||||
let wait = std::time::Duration::from_secs(5);
|
||||
// jdtls importing a Maven project: no answer for minutes (#6122).
|
||||
let busy = server_launch_extras(std::future::pending(), wait).await.unwrap();
|
||||
assert!(busy.java_home.is_none() && busy.class_paths.is_empty());
|
||||
assert!(!busy.path_list_separator.is_empty());
|
||||
let failed = server_launch_extras(async { Err(IdeError::unavailable("timed out")) }, wait).await.unwrap();
|
||||
assert!(failed.java_home.is_none());
|
||||
let home = JavaLaunchInfo { java_home: Some(PathBuf::from("/jdk").into()), ..Default::default() };
|
||||
let answered = server_launch_extras(async { Ok(home) }, wait).await.unwrap();
|
||||
assert!(answered.java_home.is_some());
|
||||
let cancelled = server_launch_extras(async { Err(IdeError::cancelled()) }, wait).await;
|
||||
assert_eq!(cancelled.unwrap_err().kind, ErrorKind::Cancelled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn junit_launch_applies_the_surefire_configuration() {
|
||||
let surefire = ide_build::surefire::SurefireConfig {
|
||||
|
||||
@@ -110,6 +110,22 @@ pub fn settings_removed_theme(host: &Host, window: &str) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// What a changed setting `key` starts or stops right away. Both `settings_set` commands (this
|
||||
/// crate's and the desktop's) call it after writing the value.
|
||||
pub fn apply_setting(host: &Arc<Host>, window: &str, key: &str) {
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` is JSON text, e.g. `14` or `"dark"`. Every window (for a project
|
||||
/// value: that project's windows) is told (`IdeEvent::SettingsChanged`) so it
|
||||
/// re-reads its effective settings.
|
||||
@@ -122,17 +138,7 @@ pub fn settings_set(
|
||||
value: String,
|
||||
) -> IdeResult<Settings> {
|
||||
let applied = set_settings(host, window, scope, &key, &value)?;
|
||||
if key == "mcpServer" || key.starts_with("mcpServer.") {
|
||||
host.mcp.apply(host);
|
||||
}
|
||||
if key == "terminal" || key.starts_with("terminal.") {
|
||||
super::term::apply_output_rate(host, window);
|
||||
}
|
||||
if "languages.typescript.watchProblems".starts_with(&key)
|
||||
&& let Some(watch) = host.project(window).ok().and_then(|p| p.tsc_watch.clone())
|
||||
{
|
||||
watch.apply(&host.runtime);
|
||||
}
|
||||
apply_setting(host, window, &key);
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key });
|
||||
if let Some(root) = applied.roots_changed {
|
||||
@@ -448,6 +454,14 @@ pub fn set_settings(
|
||||
if key == "vcs" || key == "vcs.git" || key == "vcs.git.executable" {
|
||||
host.apply_git_executable();
|
||||
}
|
||||
if key == "vcs" || key == "vcs.github" || key.starts_with("vcs.github.") {
|
||||
let affected = affected();
|
||||
host.runtime.spawn_blocking(move || {
|
||||
for project in affected {
|
||||
crate::github_auth::apply_to_project(&project);
|
||||
}
|
||||
});
|
||||
}
|
||||
// `flutter daemon` and DevTools run on the Flutter SDK; the next request starts DevTools again.
|
||||
if ["languages", "languages.flutter", "languages.flutter.sdk"].contains(&key) {
|
||||
for project in affected() {
|
||||
@@ -524,11 +538,56 @@ pub fn set_settings(
|
||||
Ok(SettingsApplied { settings: host.with_proxy_password(settings), project_scope, roots_changed })
|
||||
}
|
||||
|
||||
/// Reads the GitHub CLI (`gh`) keyring accounts and which account applies to `window`'s project.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_project_account_status(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let current = host.project(window).ok().filter(|p| !p.light);
|
||||
let global_account = host.global_settings.effective().vcs.github.account;
|
||||
host.blocking(move || match current {
|
||||
Some(project) => Ok(crate::github_auth::project_status(&project)),
|
||||
None => Ok(crate::github_auth::global_status(global_account)),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Sets `vcs.github.account` for `window`'s project (or globally when no project is open),
|
||||
/// updates the project's `GH_TOKEN` environment immediately, and returns the updated status.
|
||||
#[command(trust = outside_restricted)]
|
||||
pub async fn gh_set_project_account(
|
||||
host: &Arc<Host>,
|
||||
window: &str,
|
||||
account: String,
|
||||
) -> IdeResult<crate::github_auth::GhProjectAccountStatus> {
|
||||
host.require_trust_if_project(window)?;
|
||||
let trimmed = account.trim().to_owned();
|
||||
if !trimmed.is_empty() && !crate::github_auth::is_valid_github_login(&trimmed) {
|
||||
return Err(ide_core::IdeError::invalid(format!("invalid GitHub account login: {trimmed}")));
|
||||
}
|
||||
let current = host.project(window).ok().filter(|p| !p.light);
|
||||
let scope = if current.is_some() { SettingsScope::Project } else { SettingsScope::Global };
|
||||
let json = serde_json::to_string(&trimmed).map_err(|e| ide_core::IdeError::internal(e.to_string()))?;
|
||||
set_settings(host, window, scope, "vcs.github.account", &json)?;
|
||||
let sink = host.window_sink(window);
|
||||
sink.emit(IdeEvent::SettingsChanged { key: "vcs.github.account".into() });
|
||||
let global_account = host.global_settings.effective().vcs.github.account;
|
||||
host.blocking(move || match current {
|
||||
Some(project) => Ok(crate::github_auth::project_status(&project)),
|
||||
None => Ok(crate::github_auth::global_status(global_account)),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
ide_command::domain!(
|
||||
project:
|
||||
cancel_request,
|
||||
cancel_task,
|
||||
close_project,
|
||||
gh_project_account_status,
|
||||
gh_set_project_account,
|
||||
open_project,
|
||||
project_current,
|
||||
project_roots,
|
||||
|
||||
@@ -493,7 +493,7 @@ async fn start_inner(
|
||||
}
|
||||
// A Python configuration pointing at a missing interpreter fails in the depth of
|
||||
// process spawn otherwise; name the cause and the fix like PyCharm's "Invalid SDK".
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "django-test");
|
||||
let is_python = matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test");
|
||||
if is_python && Path::new(&config.command).components().count() > 1 {
|
||||
let cwd = project.root.join(config.cwd.as_deref().unwrap_or(Path::new("")));
|
||||
let executable = ide_core::project_roots::resolve(&cwd, Path::new(&config.command));
|
||||
|
||||
@@ -110,8 +110,8 @@ pub(crate) fn search_project(
|
||||
_ => true,
|
||||
};
|
||||
let literals = |path: &Path, text: &str| literals_of(project, syntax, path, text);
|
||||
let defaults = project.documents.file_defaults();
|
||||
let fallback = |path: &Path| defaults.fallback_for(path).map(|f| f.encoding.to_owned());
|
||||
// Search's UTF-8 fast path does not need to resolve the configured encoding.
|
||||
let fallback = |path: &Path| project.documents.configured_encoding_for(path);
|
||||
let mut total = SearchSummary::default();
|
||||
for dir in std::iter::once(root).filter(|_| include_root).chain(&content_roots) {
|
||||
let mut remaining = query.clone();
|
||||
|
||||
@@ -11,7 +11,7 @@ use ide_spell::{Region, RegionKind, SpellScope, Speller, Typo};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Languages checked as prose (all text but code spans).
|
||||
const PROSE: &[&str] = &["plaintext", "markdown", "restructuredtext", "asciidoc", "latex"];
|
||||
const PROSE: &[&str] = &["plaintext", "markdown", "mdx", "restructuredtext", "asciidoc", "latex"];
|
||||
|
||||
/// Custom dictionary paths: `~/…` from home, relative ones from the project root.
|
||||
fn dictionary_paths(settings: &SpellingSettings, root: &Path) -> Vec<PathBuf> {
|
||||
|
||||
@@ -29,15 +29,19 @@ fn tools(host: &Host, window: &str) -> IdeResult<Tools> {
|
||||
&root,
|
||||
&settings,
|
||||
));
|
||||
// Godot is usually an app bundle / Flatpak outside the search path.
|
||||
let found = ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p));
|
||||
// Godot and GitHub CLI can live in app bundles / MSI / Snap folders outside the search path.
|
||||
let mut found: std::collections::BTreeMap<_, _> =
|
||||
ide_sdk::godot::find(None).map(|p| (ide_sdk::godot::COMMAND.to_owned(), p)).into_iter().collect();
|
||||
if let Some(gh) = ide_core::tool_path::find_gh_outside_search_path() {
|
||||
found.insert("gh".to_owned(), gh);
|
||||
}
|
||||
let runtime = ide_sdk::apply::tool_install_environment(&root, &settings);
|
||||
let work_dir = (!root.as_os_str().is_empty()).then_some(root);
|
||||
Ok(Tools::new(&data)
|
||||
.with_downloads(settings.tool_downloads.clone())
|
||||
.with_runtime(runtime.commands, runtime.env)
|
||||
.with_custom_paths(custom)
|
||||
.with_found_paths(found.into_iter().collect())
|
||||
.with_found_paths(found)
|
||||
.with_work_dir(work_dir))
|
||||
}
|
||||
|
||||
|
||||
@@ -217,6 +217,61 @@ impl SecretStore for FileSecretStore {
|
||||
}
|
||||
}
|
||||
|
||||
/// Plugin secrets in the OS credential store (Secret Service, Windows Credential
|
||||
/// Manager), like saved SSH and agent values. Without a credential store a value
|
||||
/// stays in the owner-only [`FileSecretStore`] file, which also still answers for
|
||||
/// values saved there by an older version until they are set again.
|
||||
pub struct CredentialSecretStore {
|
||||
store: ide_ssh::secrets::SecretFile,
|
||||
fallback: FileSecretStore,
|
||||
}
|
||||
|
||||
impl CredentialSecretStore {
|
||||
/// `dir`: the plugins' data directory (the index file and the fallback files live there).
|
||||
pub fn new(dir: PathBuf) -> Self {
|
||||
Self::with_store(ide_ssh::secrets::SecretFile::new(dir.join("plugin-secrets.json")), dir)
|
||||
}
|
||||
|
||||
fn with_store(store: ide_ssh::secrets::SecretFile, dir: PathBuf) -> Self {
|
||||
Self { store, fallback: FileSecretStore { dir } }
|
||||
}
|
||||
|
||||
fn key(plugin: &str, name: &str) -> String {
|
||||
format!("{plugin}/{name}")
|
||||
}
|
||||
|
||||
/// Drops a value from the fallback file, writing it only when it held one.
|
||||
fn forget_fallback(&self, plugin: &str, name: &str) -> Result<(), String> {
|
||||
if self.fallback.get(plugin, name).is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
self.fallback.set(plugin, name, None)
|
||||
}
|
||||
}
|
||||
|
||||
impl SecretStore for CredentialSecretStore {
|
||||
fn get(&self, plugin: &str, name: &str) -> Option<String> {
|
||||
self.store.get(&Self::key(plugin, name)).or_else(|| self.fallback.get(plugin, name))
|
||||
}
|
||||
|
||||
fn set(&self, plugin: &str, name: &str, value: Option<&str>) -> Result<(), String> {
|
||||
let key = Self::key(plugin, name);
|
||||
match value {
|
||||
Some(v) => match self.store.set(&key, v) {
|
||||
Ok(()) => self.forget_fallback(plugin, name),
|
||||
Err(e) => {
|
||||
tracing::warn!("plugin secrets: {key} is kept in the plugin's data directory: {}", e.message);
|
||||
self.fallback.set(plugin, name, Some(v))
|
||||
}
|
||||
},
|
||||
None => {
|
||||
self.store.delete(&key);
|
||||
self.forget_fallback(plugin, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Largest response body a plugin receives.
|
||||
const MAX_RESPONSE: usize = 16 << 20;
|
||||
/// Largest stdout / stderr kept from a process by default.
|
||||
@@ -4210,6 +4265,67 @@ mod tests {
|
||||
assert_eq!(std::fs::read_to_string(&outside).unwrap(), "unchanged");
|
||||
}
|
||||
|
||||
/// Plugin secrets go to the credential store; a value an older version left in
|
||||
/// the owner-only file keeps working until it is set again, and then leaves the file.
|
||||
#[test]
|
||||
fn plugin_secrets_go_to_the_credential_store() {
|
||||
ide_ssh::secrets::testing::use_memory_store();
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plugins");
|
||||
FileSecretStore { dir: dir.clone() }.set("acme.lint", "old", Some("legacy-3f9a")).unwrap();
|
||||
let secrets = CredentialSecretStore::new(dir.clone());
|
||||
assert_eq!(secrets.get("acme.lint", "old").as_deref(), Some("legacy-3f9a"));
|
||||
|
||||
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
|
||||
secrets.set("acme.lint", "old", Some("moved-5d2b")).unwrap();
|
||||
let on_disk = ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e");
|
||||
assert_eq!(on_disk, Vec::<PathBuf>::new());
|
||||
assert_eq!(ide_ssh::secrets::testing::files_containing(tmp.path(), "legacy-3f9a"), Vec::<PathBuf>::new());
|
||||
let again = CredentialSecretStore::new(dir);
|
||||
assert_eq!(again.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
|
||||
assert_eq!(again.get("acme.lint", "old").as_deref(), Some("moved-5d2b"));
|
||||
assert_eq!(again.get("other.plugin", "token"), None);
|
||||
|
||||
again.set("acme.lint", "token", None).unwrap();
|
||||
assert_eq!(again.get("acme.lint", "token"), None);
|
||||
}
|
||||
|
||||
/// Without a credential store a value stays in the owner-only file.
|
||||
#[test]
|
||||
fn plugin_secrets_without_a_credential_store_stay_in_the_file() {
|
||||
struct NoStore;
|
||||
impl ide_ssh::secrets::Vault for NoStore {
|
||||
fn available(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn get(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<String> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
fn set(&self, _: &str, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
fn delete(&self, _: &str, _: &str) -> ide_ssh::secrets::StoreResult<()> {
|
||||
Err(ide_ssh::secrets::StoreError::NoDefaultStore)
|
||||
}
|
||||
}
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dir = tmp.path().join("plugins");
|
||||
let store = ide_ssh::secrets::SecretFile::with_vault(
|
||||
dir.join("plugin-secrets.json"),
|
||||
|v| serde_json::from_value(v).ok(),
|
||||
Arc::new(NoStore),
|
||||
);
|
||||
let secrets = CredentialSecretStore::with_store(store, dir.clone());
|
||||
secrets.set("acme.lint", "token", Some("value-7c1e")).unwrap();
|
||||
assert_eq!(
|
||||
ide_ssh::secrets::testing::files_containing(tmp.path(), "value-7c1e"),
|
||||
[dir.join("acme.lint").join("secrets.json")]
|
||||
);
|
||||
assert_eq!(secrets.get("acme.lint", "token").as_deref(), Some("value-7c1e"));
|
||||
secrets.set("acme.lint", "token", None).unwrap();
|
||||
assert_eq!(secrets.get("acme.lint", "token"), None);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn storage_and_secrets_refuse_symlinked_private_directories() {
|
||||
|
||||
@@ -700,7 +700,10 @@ mod tests {
|
||||
// tampered package — and the official host must still be asked.
|
||||
let candidates = mirror::candidates(
|
||||
"https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let asked: std::cell::RefCell<Vec<usize>> = std::cell::RefCell::new(Vec::new());
|
||||
let picked = try_sources(&candidates, |index, candidate| {
|
||||
@@ -731,7 +734,10 @@ mod tests {
|
||||
let url = "https://github.com/acme/hello/releases/download/v1/acme.hello-1.0.0.oiplugin";
|
||||
let through = mirror::candidates(
|
||||
url,
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(through.len(), 2);
|
||||
assert_eq!(through[0].url, format!("https://gh-proxy.com/{url}"));
|
||||
@@ -741,7 +747,10 @@ mod tests {
|
||||
// A local index's own package is not on GitHub: no prefix may carry it.
|
||||
let local = mirror::candidates(
|
||||
"/srv/market/a.oiplugin",
|
||||
&ide_core::settings::ToolDownloadSettings { github_mirror: "https://gh-proxy.com/".into() },
|
||||
&ide_core::settings::ToolDownloadSettings {
|
||||
github_mirror: "https://gh-proxy.com/".into(),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(local.len(), 1);
|
||||
assert_eq!(local[0].url, "/srv/market/a.oiplugin");
|
||||
|
||||
@@ -63,7 +63,7 @@ pub mod views;
|
||||
pub mod web;
|
||||
mod websocket;
|
||||
|
||||
pub use api::{FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use api::{CredentialSecretStore, FileSecretStore, HostWorkspace, PluginWorkspace, SecretStore};
|
||||
pub use build_graph::{BuildGraph, GradleModule};
|
||||
pub(crate) use hover::merge as merge_hover;
|
||||
pub use icons::{
|
||||
@@ -1949,6 +1949,12 @@ impl PluginHost {
|
||||
*self.shared.secrets.write() = store;
|
||||
}
|
||||
|
||||
/// Keeps plugin secrets in the OS credential store, with the owner-only
|
||||
/// files under the plugins directory as the fallback.
|
||||
pub fn use_credential_store(&self) {
|
||||
self.set_secret_store(Arc::new(CredentialSecretStore::new(self.shared.data_dir.clone())));
|
||||
}
|
||||
|
||||
/// Stores (or, with `None`, deletes) a secret the plugin declares under
|
||||
/// `[[contributes.secrets]]`.
|
||||
pub fn set_secret(&self, id: &str, name: &str, value: Option<&str>) -> IdeResult<()> {
|
||||
|
||||
@@ -211,6 +211,8 @@ impl Host {
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
// After the global plugins: they keep the IDE's copies.
|
||||
ide_sdk::apply::configure_tsconfig_plugins(cfg, server_root, &data_dir);
|
||||
let container_python = effective.languages.python.run_target().is_some();
|
||||
crate::ops::sdk::container_python::configure_server(cfg, &data_dir, root, &effective);
|
||||
// Attached dependency projects are source, so basedpyright/Pyright should
|
||||
@@ -452,7 +454,9 @@ impl Host {
|
||||
phpstan.files_removed(batch.removed.iter());
|
||||
lsp.project_files_changed(batch.created.iter().chain(&batch.removed));
|
||||
lsp.watched_files_changed(&batch.created, &batch.modified, &batch.removed, &batch.excluded_dirs);
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
|| ts_config_changed(changed.iter().chain(&batch.removed))
|
||||
{
|
||||
lsp.reconfigure_soon();
|
||||
}
|
||||
// Not while loading: a first `use flake` may write `flake.lock` itself.
|
||||
@@ -762,6 +766,12 @@ impl Host {
|
||||
if let Some(cmd) = post_start {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
if project.is_trusted() {
|
||||
let p = project.clone();
|
||||
self.runtime.spawn_blocking(move || {
|
||||
crate::github_auth::apply_to_project(&p);
|
||||
});
|
||||
}
|
||||
crate::ops::sdk::container_python::ensure(self, &project);
|
||||
Ok(project)
|
||||
}
|
||||
@@ -1524,8 +1534,7 @@ impl Project {
|
||||
}
|
||||
|
||||
pub fn staged_file_encoding(&self, path: &Path, bytes: &[u8]) -> ide_vcs::TextEncoding {
|
||||
let defaults = self.documents.file_defaults();
|
||||
let charset = ide_vfs::detect_encoding(bytes, defaults.fallback_for(path));
|
||||
let charset = self.documents.detect_encoding(path, bytes);
|
||||
self.vcs_text_encoding(path, charset)
|
||||
}
|
||||
|
||||
@@ -1884,7 +1893,9 @@ fn content_root_watcher(
|
||||
index.ignore_rules_changed(&batch.ignore_rules);
|
||||
index.update(&[&changed[..], &ignored].concat(), &[&batch.removed[..], &ignored_gone].concat());
|
||||
// A workspace member's PHP language level follows its own composer.json.
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed)) {
|
||||
if composer_changed(&root, changed.iter().chain(&batch.removed))
|
||||
|| ts_config_changed(changed.iter().chain(&batch.removed))
|
||||
{
|
||||
lsp.reconfigure_soon();
|
||||
}
|
||||
if let Some(bridge) = &kotlin_bridge {
|
||||
@@ -1906,6 +1917,17 @@ fn content_root_watcher(
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// A tsconfig.json / jsconfig.json (or a `tsconfig.*.json` one extends) changed: the tsserver
|
||||
/// plugins it declares are part of vtsls' configuration.
|
||||
fn ts_config_changed<'a>(mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
|
||||
paths.any(|p| {
|
||||
let name = p.file_name().map(|n| n.to_string_lossy()).unwrap_or_default();
|
||||
!p.components().any(|c| c.as_os_str() == "node_modules")
|
||||
&& (name.starts_with("tsconfig") || name.starts_with("jsconfig"))
|
||||
&& name.ends_with(".json")
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the `composer.json` of `root` is among `paths`: the PHP language level follows it
|
||||
/// (`ide_sdk::php`).
|
||||
fn composer_changed<'a>(root: &Path, mut paths: impl Iterator<Item = &'a PathBuf>) -> bool {
|
||||
@@ -2015,7 +2037,9 @@ fn independent_eclipse_projects(root: &Path) -> Vec<PathBuf> {
|
||||
|
||||
/// The detected roots with the last Gradle sync's source sets first: Gradle evaluated what
|
||||
/// static detection guesses. Folders outside the project keep their absolute path, which
|
||||
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`).
|
||||
/// `normalize` turns into the same form the UI compares (`Users/me/svc/src/main/java`);
|
||||
/// their `detected_from` owner keeps its leading `/` or drive (`<project>/Gradle`) so
|
||||
/// module lists still address them as absolute paths.
|
||||
fn with_gradle_roots(
|
||||
root: &Path,
|
||||
build_cache: &Path,
|
||||
@@ -2039,12 +2063,22 @@ fn with_gradle_roots(
|
||||
};
|
||||
if !out.iter().any(|f| f.path == path) {
|
||||
// `<module>/Gradle`, like the `<module>/build.gradle` static detection reports, so the
|
||||
// UI still finds the module after a sync. Projects outside the root stay `Gradle`:
|
||||
// the UI reads the folder as project-relative.
|
||||
// UI still finds the module after a sync. Projects outside the root keep their
|
||||
// absolute owner (without `normalize`, which strips a leading `/`), except an ancestor
|
||||
// of the root (opened from a subproject) or a filesystem/drive root, which stay
|
||||
// `Gradle` so they cannot shadow in-project modules or collapse to a bare drive `D:`.
|
||||
let project = dunce::canonicalize(&project).unwrap_or(project);
|
||||
let detected_from = match project.strip_prefix(root) {
|
||||
Ok(rel) if !rel.as_os_str().is_empty() => {
|
||||
format!("{}/Gradle", ide_workspace::roots::normalize(&rel.to_string_lossy()))
|
||||
}
|
||||
Err(_) if !root.starts_with(&project) && project.parent().is_some() => {
|
||||
let raw = project.to_string_lossy().replace('\\', "/");
|
||||
let owner = raw.trim_end_matches('/');
|
||||
let drive_root =
|
||||
owner.len() == 2 && owner.as_bytes()[0].is_ascii_alphabetic() && owner.as_bytes()[1] == b':';
|
||||
if owner.is_empty() || drive_root { "Gradle".into() } else { format!("{owner}/Gradle") }
|
||||
}
|
||||
_ => "Gradle".into(),
|
||||
};
|
||||
out.push(SourceFolder { path, kind, detected_from: Some(detected_from) });
|
||||
@@ -2492,18 +2526,109 @@ mod gradle_roots_tests {
|
||||
std::fs::write(root.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&root, &cache, &Default::default(), &[guessed, other.clone()]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let owner = format!("{}/Gradle", svc.to_string_lossy().replace('\\', "/"));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.kind, f.detected_from.as_deref())).collect();
|
||||
// A project outside the root is not a module the UI could address.
|
||||
// A project outside the root keeps its absolute owner so module lists still address it.
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
("src/it/java".into(), RootKind::Test, Some("Gradle")),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source, Some("Gradle")),
|
||||
(abs(svc.join("build")), RootKind::Excluded, Some("Gradle")),
|
||||
(abs(svc.join("src/main/java")), RootKind::Source, Some(owner.as_str())),
|
||||
(abs(svc.join("build")), RootKind::Excluded, Some(owner.as_str())),
|
||||
("web".into(), RootKind::Source, None),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradle_sync_roots_keep_plain_gradle_for_ancestors_and_fs_roots() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let composite = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let app = composite.join("app");
|
||||
let lib = app.join("lib");
|
||||
let cache = composite.join("cache");
|
||||
let ext_posix = composite.join("ext-posix/src/main/java");
|
||||
let ext_win = composite.join("ext-win/src/main/java");
|
||||
for d in [
|
||||
composite.join("src/main/java"),
|
||||
app.join("src/main/java"),
|
||||
lib.join("src/main/java"),
|
||||
ext_posix.clone(),
|
||||
ext_win.clone(),
|
||||
cache.clone(),
|
||||
] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let s = |p: PathBuf| p.to_string_lossy().into_owned();
|
||||
// Opened at `composite/app` while Gradle discovers parent `composite/settings.gradle`
|
||||
// (so `composite` is an ancestor of `root`), plus external roots owned by `/` or `D:/`.
|
||||
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
|
||||
{ "path": ":", "dir": s(composite.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(composite.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app", "dir": s(app.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app:lib", "dir": s(lib.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":posix-root", "dir": "/", "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(ext_posix.clone())], "res": [] } ] },
|
||||
{ "path": ":win-drive", "dir": "D:/", "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(ext_win.clone())], "res": [] } ] },
|
||||
]});
|
||||
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
|
||||
std::fs::write(app.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(abs(composite.join("src/main/java")), Some("Gradle")),
|
||||
("src/main/java".into(), Some("Gradle")),
|
||||
("lib/src/main/java".into(), Some("lib/Gradle")),
|
||||
(abs(ext_posix), Some("Gradle")),
|
||||
(abs(ext_win), Some("Gradle")),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn gradle_sync_roots_canonicalize_symlinked_project_dirs() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let ws = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let real = ws.join("real");
|
||||
let link = ws.join("link");
|
||||
let app = real.join("app");
|
||||
let lib = app.join("lib");
|
||||
let cache = ws.join("cache");
|
||||
for d in [real.join("src/main/java"), app.join("src/main/java"), lib.join("src/main/java"), cache.clone()] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
std::os::unix::fs::symlink(&real, &link).unwrap();
|
||||
let s = |p: PathBuf| p.to_string_lossy().into_owned();
|
||||
// Opened at canonical `real/app`, while Gradle reports projects through the symlink `link`.
|
||||
let json = serde_json::json!({ "hash": "", "at_ms": 1.0, "error": null, "tasks": [], "projects": [
|
||||
{ "path": ":", "dir": s(link.clone()), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(real.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app", "dir": s(link.join("app")), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(app.join("src/main/java"))], "res": [] } ] },
|
||||
{ "path": ":app:lib", "dir": s(link.join("app/lib")), "sourceSets": [
|
||||
{ "name": "main", "test": false, "src": [s(lib.join("src/main/java"))], "res": [] } ] },
|
||||
]});
|
||||
std::fs::write(cache.join("gradle.json"), json.to_string()).unwrap();
|
||||
std::fs::write(app.join("build.gradle"), "").unwrap();
|
||||
let out = with_gradle_roots(&app, &cache, &Default::default(), &[]);
|
||||
let abs = |p: PathBuf| ide_workspace::roots::normalize(&s(p));
|
||||
let got: Vec<_> = out.iter().map(|f| (f.path.clone(), f.detected_from.as_deref())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[
|
||||
(abs(real.join("src/main/java")), Some("Gradle")),
|
||||
("src/main/java".into(), Some("Gradle")),
|
||||
("lib/src/main/java".into(), Some("lib/Gradle")),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -2628,9 +2753,20 @@ mod agent_worktree_tests {
|
||||
|
||||
#[cfg(test)]
|
||||
mod composer_tests {
|
||||
use super::composer_changed;
|
||||
use super::{composer_changed, ts_config_changed};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[test]
|
||||
fn tsconfig_and_jsconfig_files_count_outside_node_modules() {
|
||||
let changed = |p: &str| ts_config_changed([PathBuf::from(p)].iter());
|
||||
for yes in ["/p/tsconfig.json", "/p/apps/web/jsconfig.json", "/p/tsconfig.base.json"] {
|
||||
assert!(changed(yes), "{yes}");
|
||||
}
|
||||
for no in ["/p/package.json", "/p/tsconfig.ts", "/p/node_modules/x/tsconfig.json"] {
|
||||
assert!(!changed(no), "{no}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_roots_own_composer_json_counts() {
|
||||
let root = Path::new("/work/app");
|
||||
|
||||
@@ -282,11 +282,18 @@ impl crate::Host {
|
||||
self.environment.spawn_post_start(cmd, project.root.clone(), project.sink.clone());
|
||||
}
|
||||
self.environment.direnv_opened(&project.root, &project.sink);
|
||||
{
|
||||
let p = project.clone();
|
||||
self.runtime.spawn_blocking(move || {
|
||||
crate::github_auth::apply_to_project(&p);
|
||||
});
|
||||
}
|
||||
project.lsp.set_execution_allowed(true);
|
||||
project.lsp.prewarm_java_configuration();
|
||||
} else {
|
||||
self.environment.project_closed();
|
||||
self.environment.direnv_closed(&project.root);
|
||||
crate::github_auth::clear_project_env(&project);
|
||||
project.agents.shutdown();
|
||||
project.flutter.stop();
|
||||
project.devtools.stop();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation) as the TypeScript
|
||||
//! Editor › Code Style › JavaScript / TypeScript (Spaces, Punctuation, Imports) as the TypeScript
|
||||
//! servers' `typescript.format.*` / `typescript.preferences.*` settings (`javascript.*` for
|
||||
//! JavaScript and JSX). tsserver applies them to Reformat Code and to the code it writes:
|
||||
//! quick fixes, auto-imports, refactorings and organize imports.
|
||||
@@ -48,12 +48,7 @@ pub fn configure(cfg: &mut LanguageServerConfig, server_root: &Path, settings: &
|
||||
.and_then(|e| e.resolve_pairs(&server_root.join(format!("index.{ext}"))))
|
||||
.unwrap_or_default();
|
||||
let section = section(language, code_style.languages.get(language), &pairs);
|
||||
if !section.is_empty() {
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
}
|
||||
if layer.is_empty() {
|
||||
return;
|
||||
layer.insert(language.into(), Value::Object(section));
|
||||
}
|
||||
let mut merged = Value::Object(layer);
|
||||
if let Some(own) = cfg.settings.take() {
|
||||
@@ -96,10 +91,30 @@ fn section(
|
||||
if !format.is_empty() {
|
||||
section.insert("format".into(), Value::Object(format));
|
||||
}
|
||||
// vtsls reads `quoteStyle` (VS Code's name), typescript-language-server tsserver's `quotePreference`.
|
||||
// vtsls reads VS Code's names (`quoteStyle`, `importModuleSpecifier`), typescript-language-server
|
||||
// tsserver's (`quotePreference`, `importModuleSpecifierPreference`).
|
||||
let mut preferences = Map::new();
|
||||
if let Some(quotes) = quotes {
|
||||
section.insert("preferences".into(), json!({ "quoteStyle": quotes, "quotePreference": quotes }));
|
||||
preferences.insert("quoteStyle".into(), json!(quotes));
|
||||
preferences.insert("quotePreference".into(), json!(quotes));
|
||||
}
|
||||
let paths = ["shortest", "relative", "non-relative", "project-relative"];
|
||||
if let Some(paths) = pick(style.and_then(|s| s.import_module_specifier.as_ref()), &paths) {
|
||||
preferences.insert("importModuleSpecifier".into(), json!(paths));
|
||||
preferences.insert("importModuleSpecifierPreference".into(), json!(paths));
|
||||
}
|
||||
let endings = ["auto", "minimal", "index", "js"];
|
||||
if let Some(ending) = pick(style.and_then(|s| s.import_module_specifier_ending.as_ref()), &endings) {
|
||||
preferences.insert("importModuleSpecifierEnding".into(), json!(ending));
|
||||
}
|
||||
// Sent even when empty: vtsls has no default for these, so a list left out keeps tsserver's
|
||||
// previous one, and clearing it would only apply after a restart. `[]` excludes nothing.
|
||||
let none = Vec::new();
|
||||
let patterns = style.map_or(&none, |s| &s.auto_import_file_exclude_patterns);
|
||||
let regexes = style.map_or(&none, |s| &s.auto_import_specifier_exclude_regexes);
|
||||
preferences.insert("autoImportFileExcludePatterns".into(), json!(patterns));
|
||||
preferences.insert("autoImportSpecifierExcludeRegexes".into(), json!(regexes));
|
||||
section.insert("preferences".into(), Value::Object(preferences));
|
||||
section
|
||||
}
|
||||
|
||||
@@ -133,9 +148,17 @@ mod tests {
|
||||
"typescript": {
|
||||
"format": { "semicolons": "remove", "insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": false },
|
||||
// The server's own settings win.
|
||||
"preferences": { "quoteStyle": "double", "quotePreference": "single" },
|
||||
"preferences": {
|
||||
"quoteStyle": "double",
|
||||
"quotePreference": "single",
|
||||
"autoImportFileExcludePatterns": [],
|
||||
"autoImportSpecifierExcludeRegexes": [],
|
||||
},
|
||||
},
|
||||
"javascript": {
|
||||
"format": { "semicolons": "insert" },
|
||||
"preferences": { "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] },
|
||||
},
|
||||
"javascript": { "format": { "semicolons": "insert" } },
|
||||
})
|
||||
);
|
||||
|
||||
@@ -144,7 +167,52 @@ mod tests {
|
||||
assert_eq!(eslint.settings, None);
|
||||
let mut untouched = server("vtsls");
|
||||
configure(&mut untouched, dir.path(), &Settings::default());
|
||||
assert_eq!(untouched.settings, None, "nothing set: the server's defaults");
|
||||
// Nothing set: the server's defaults, and empty exclusion lists so that clearing one reaches
|
||||
// a running server.
|
||||
let empty = json!({ "autoImportFileExcludePatterns": [], "autoImportSpecifierExcludeRegexes": [] });
|
||||
let empty = json!({ "typescript": { "preferences": empty }, "javascript": { "preferences": empty } });
|
||||
assert_eq!(untouched.settings, Some(empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_style_reaches_the_preferences_of_each_language() {
|
||||
let mut settings = Settings::default();
|
||||
let ts = LanguageCodeStyle {
|
||||
import_module_specifier: Some("relative".into()),
|
||||
import_module_specifier_ending: Some("index".into()),
|
||||
auto_import_file_exclude_patterns: vec!["**/index.ts".into()],
|
||||
auto_import_specifier_exclude_regexes: vec!["^node:".into()],
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("typescript".into(), ts);
|
||||
let js = LanguageCodeStyle {
|
||||
import_module_specifier: Some("non-relative".into()),
|
||||
// Not a tsserver value: left out.
|
||||
import_module_specifier_ending: Some("ts".into()),
|
||||
..Default::default()
|
||||
};
|
||||
settings.editor.code_style.languages.insert("javascript".into(), js);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let mut cfg = server("vtsls");
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
assert_eq!(
|
||||
cfg.settings.unwrap(),
|
||||
json!({
|
||||
"typescript": { "preferences": {
|
||||
"importModuleSpecifier": "relative",
|
||||
"importModuleSpecifierPreference": "relative",
|
||||
"importModuleSpecifierEnding": "index",
|
||||
"autoImportFileExcludePatterns": ["**/index.ts"],
|
||||
"autoImportSpecifierExcludeRegexes": ["^node:"],
|
||||
} },
|
||||
"javascript": { "preferences": {
|
||||
"importModuleSpecifier": "non-relative",
|
||||
"importModuleSpecifierPreference": "non-relative",
|
||||
"autoImportFileExcludePatterns": [],
|
||||
"autoImportSpecifierExcludeRegexes": [],
|
||||
} },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -178,6 +246,6 @@ mod tests {
|
||||
configure(&mut cfg, dir.path(), &settings);
|
||||
let s = cfg.settings.unwrap();
|
||||
assert_eq!(s["typescript"]["format"], json!({ "semicolons": "insert" }));
|
||||
assert_eq!(s.get("javascript"), None);
|
||||
assert_eq!(s["javascript"].get("format"), None);
|
||||
}
|
||||
}
|
||||
@@ -211,7 +211,7 @@ fn write_index(
|
||||
|
||||
/// The download sources setting with `mirror` as the GitHub proxy prefix (Tools › Download sources).
|
||||
fn download_sources(mirror: &str) -> ide_core::settings::ToolDownloadSettings {
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
ide_core::settings::ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
/// Security audit lead 5: an index entry's id and version name the download file,
|
||||
|
||||
@@ -542,6 +542,23 @@ impl Smoke {
|
||||
self.restore(doc, &before).await;
|
||||
}
|
||||
|
||||
/// Completion at the end of the typed line, once it offers the auto-import `control`, has
|
||||
/// none labelled `label`.
|
||||
async fn not_offered(&self, typed: Typed, label: &str, control: &str) {
|
||||
let (doc, pos, before) = self.type_line(typed).await;
|
||||
self.retry("completion without the item", self.warm_up, || async {
|
||||
let list = ops::lsp::lsp_completion(&self.host, WINDOW, RequestId(7), doc, pos, None).await;
|
||||
let labels: Vec<String> = match list {
|
||||
Ok(l) => l.items.into_iter().map(|i| i.label).collect(),
|
||||
Err(e) => vec![e.to_string()],
|
||||
};
|
||||
let has = |name: &str| labels.iter().any(|l| l == name);
|
||||
if has(control) && !has(label) { Ok(()) } else { Err(labels) }
|
||||
})
|
||||
.await;
|
||||
self.restore(doc, &before).await;
|
||||
}
|
||||
|
||||
async fn organize_imports(&self, import: Typed, expect: Imports) {
|
||||
let (doc, _, before) = self.type_line(import).await;
|
||||
let typed = import.text.trim();
|
||||
@@ -696,7 +713,73 @@ async fn typescript() {
|
||||
smoke("typescript", TYPESCRIPT).await;
|
||||
}
|
||||
|
||||
/// Code Style › TypeScript › Imports (#6072): each change reaches the running vtsls, and its
|
||||
/// auto-imports follow it: relative or path alias, `/index` or not, and excluded files and
|
||||
/// specifiers left out.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
#[ignore = "language smoke: needs vtsls"]
|
||||
async fn typescript_import_style() {
|
||||
let checks = Checks {
|
||||
files: &[
|
||||
(
|
||||
"tsconfig.json",
|
||||
r#"{"compilerOptions": {"module": "ESNext", "moduleResolution": "Bundler", "strict": true,
|
||||
"noEmit": true, "allowImportingTsExtensions": true, "paths": {"@/*": ["./src/*"]}},
|
||||
"include": ["src"]}"#,
|
||||
),
|
||||
("src/lib/alpha.ts", "export function alphaHelper(): number {\n return 1;\n}\n"),
|
||||
// Never excluded, and matching what is typed (tsserver offers only those): the
|
||||
// auto-import candidates are in the completion list.
|
||||
("src/lib/betaWord.ts", "export function betaWord(): number {\n return 3;\n}\n"),
|
||||
("src/lib/hints.ts", "export function alphaHint(): number {\n return 4;\n}\n"),
|
||||
("src/app/components/index.ts", "export function betaWidget(): number {\n return 2;\n}\n"),
|
||||
("src/app/main.ts", "export const ready = true;\n"),
|
||||
("src/app/other.ts", "export const other = true;\n"),
|
||||
("src/app/third.ts", "export const third = true;\n"),
|
||||
("src/app/fourth.ts", "export const fourth = true;\n"),
|
||||
("src/app/fifth.ts", "export const fifth = true;\n"),
|
||||
],
|
||||
..TYPESCRIPT
|
||||
};
|
||||
let smoke = Smoke::start("typescript", &checks).await;
|
||||
let set = |key: &str, value: &str| {
|
||||
let scope = ide_workspace::settings::SettingsScope::Project;
|
||||
let key = format!("editor.codeStyle.languages.typescript.{key}");
|
||||
ops::project::settings_set(&smoke.host, WINDOW, scope, key, value.into()).unwrap();
|
||||
};
|
||||
let alpha = typed("src/app/main.ts", "export const ready", "alphaH");
|
||||
let beta = typed("src/app/main.ts", "export const ready", "betaW");
|
||||
let import = |typed, label, result| AutoImport { typed, label, result };
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
set("importModuleSpecifier", r#""non-relative""#);
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "@/lib/alpha""#)).await;
|
||||
|
||||
set("importModuleSpecifier", r#""relative""#);
|
||||
set("importModuleSpecifierEnding", r#""index""#);
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components/index""#)).await;
|
||||
set("importModuleSpecifierEnding", r#""minimal""#);
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
|
||||
// tsserver keeps the auto-import candidates of the file it last completed in until the
|
||||
// program changes; other files see an exclusion at once.
|
||||
set("autoImportFileExcludePatterns", r#"["**/index.ts"]"#);
|
||||
smoke.not_offered(typed("src/app/other.ts", "export const other", "betaW"), "betaWidget", "betaWord").await;
|
||||
set("autoImportSpecifierExcludeRegexes", r#"["lib/alpha$"]"#);
|
||||
smoke.not_offered(typed("src/app/third.ts", "export const third", "alphaH"), "alphaHelper", "alphaHint").await;
|
||||
|
||||
// Emptied lists reach the server too: the symbols are offered again.
|
||||
set("autoImportFileExcludePatterns", "[]");
|
||||
let beta = typed("src/app/fourth.ts", "export const fourth", "betaW");
|
||||
smoke.auto_import(import(beta, "betaWidget", r#"from "./components""#)).await;
|
||||
set("autoImportSpecifierExcludeRegexes", "[]");
|
||||
let alpha = typed("src/app/fifth.ts", "export const fifth", "alphaH");
|
||||
smoke.auto_import(import(alpha, "alphaHelper", r#"from "../lib/alpha""#)).await;
|
||||
}
|
||||
|
||||
/// The latest `tsc` diagnostics of `path` (Problems › TypeScript Project Errors), `None` before any.
|
||||
#[cfg(unix)]
|
||||
fn tsc_errors(events: &Events, path: &Path) -> Option<Vec<String>> {
|
||||
events.lock().unwrap().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path: p, source, items } if source == "tsc" && **p == *path => {
|
||||
|
||||
@@ -6,7 +6,6 @@ use ide_host::{Host, HostConfig};
|
||||
use ide_plugin::TextQuery;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
struct Harness {
|
||||
host: Arc<Host>,
|
||||
@@ -510,6 +509,7 @@ async fn plugin_run_output_mode_executes_pty_and_pipes_with_input_exit_and_stop(
|
||||
use ide_host::plugins::{Consent, PluginEvent, PluginHost, WindowRequest};
|
||||
use ide_plugin::{Invocation, Limits};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::time::Duration;
|
||||
|
||||
let f = Harness::new();
|
||||
f.host.set_project_trust(&f.root, true, false).await.unwrap();
|
||||
|
||||
@@ -6794,6 +6794,8 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
let mut req = vec![0; len];
|
||||
let _ = reader.read_exact(&mut req);
|
||||
let body = "plain ok";
|
||||
// Recorded before the reply: the client may assert as soon as it reads it.
|
||||
seen.lock().push("served".into());
|
||||
let _ = writer.write_all(
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\ncontent-type: text/plain\r\ncontent-length: {}\r\n\r\n{body}",
|
||||
@@ -6801,7 +6803,6 @@ fn net_http_setting_grants_reach_plain_http_per_transport() {
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
seen.lock().push("served".into());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -50,3 +50,25 @@ async fn find_in_files_decodes_closed_files_with_the_project_encoding() {
|
||||
project.documents.set_file_defaults(defaults);
|
||||
assert!(find(&host, "中文搜索验证").await.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn find_in_files_decodes_closed_files_with_the_editorconfig_charset() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let base = dunce::canonicalize(temp.path()).unwrap();
|
||||
let root = base.join("project");
|
||||
std::fs::create_dir(&root).unwrap();
|
||||
std::fs::write(root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
|
||||
std::fs::write(root.join("A.java"), b"// a\xe7\xe3o \xa4 needle\n").unwrap();
|
||||
let host = Host::new(common::host_config(&base));
|
||||
host.trust.decide(&root, true, false).unwrap();
|
||||
let project = host.open_project("main", &root).unwrap();
|
||||
let mut defaults = project.documents.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
project.documents.set_file_defaults(defaults);
|
||||
|
||||
let files = find(&host, "ação €").await;
|
||||
|
||||
assert_eq!(files.len(), 1);
|
||||
assert_eq!(files[0].matches[0].text, "// ação € needle", "the text the editor shows");
|
||||
assert_eq!(find(&host, "needle").await[0].matches[0].text, "// ação € needle");
|
||||
}
|
||||
@@ -63,6 +63,7 @@ const BUILTIN: &[(&str, &str)] = &[
|
||||
("lua", include_str!("../../../languages/lua.toml")),
|
||||
("makefile", include_str!("../../../languages/makefile.toml")),
|
||||
("markdown", include_str!("../../../languages/markdown.toml")),
|
||||
("mdx", include_str!("../../../languages/mdx.toml")),
|
||||
("nix", include_str!("../../../languages/nix.toml")),
|
||||
("objective-c", include_str!("../../../languages/objective-c.toml")),
|
||||
("objective-cpp", include_str!("../../../languages/objective-cpp.toml")),
|
||||
@@ -1281,6 +1282,7 @@ mod tests {
|
||||
("Views/MainWindow.axaml", "axaml"),
|
||||
("MainWindow.xaml", "xml"),
|
||||
("README.md", "markdown"),
|
||||
("Intro.mdx", "mdx"),
|
||||
("Dockerfile", "dockerfile"),
|
||||
("Dockerfile.dev", "dockerfile"),
|
||||
("Makefile", "makefile"),
|
||||
@@ -1362,6 +1364,22 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indented_sass_has_its_own_server() {
|
||||
let reg = reg();
|
||||
let names = |lang: &str| -> Vec<String> {
|
||||
reg.get(&LanguageId::new(lang)).unwrap().language_servers.iter().map(|s| s.name.clone()).collect()
|
||||
};
|
||||
assert_eq!(names("sass"), ["some-sass-language-server"]);
|
||||
let sass = ®.get(&LanguageId::new("sass")).unwrap().language_servers[0];
|
||||
assert_eq!(sass.settings.as_ref().and_then(|s| s.get("somesass")), Some(&serde_json::json!({})));
|
||||
for lang in ["scss", "css", "less"] {
|
||||
let names = names(lang);
|
||||
assert_eq!(names[0], "vscode-css-language-server", "{lang}");
|
||||
assert!(!names.iter().any(|n| n == "some-sass-language-server"), "{lang}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn astro_server_leaves_typescript_sdk_resolution_to_the_launcher() {
|
||||
let reg = reg();
|
||||
|
||||
@@ -28,6 +28,7 @@ percent-encoding = "2"
|
||||
zip.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
ide-sdk.workspace = true
|
||||
tempfile.workspace = true
|
||||
encoding_rs.workspace = true
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "macros", "test-util"] }
|
||||
|
||||
@@ -34,6 +34,20 @@ fn indent_settings(style: &LanguageCodeStyle) -> Option<Vec<(&'static str, Strin
|
||||
Some(settings)
|
||||
}
|
||||
|
||||
/// Java organize-imports thresholds as jdtls settings (IDEA's "Class count to use import with
|
||||
/// '*'" and "Names count to use static import with '*'"). Unset ones are IDEA's defaults, 5 and 3:
|
||||
/// jdtls' own are 99 (single imports), and it keeps a value it was sent until another one comes.
|
||||
/// A threshold the server configuration sets explicitly is kept.
|
||||
fn organize_imports_settings(style: Option<&LanguageCodeStyle>, inherited: &serde_json::Value) -> serde_json::Value {
|
||||
let explicit = |key: &str| inherited.pointer(&format!("/java/sources/organizeImports/{key}")).cloned();
|
||||
let class_count = style.and_then(|s| s.class_count_to_use_import_with_star).unwrap_or(5);
|
||||
let static_count = style.and_then(|s| s.names_count_to_use_static_import_with_star).unwrap_or(3);
|
||||
json!({
|
||||
"starThreshold": explicit("starThreshold").unwrap_or(json!(class_count)),
|
||||
"staticStarThreshold": explicit("staticStarThreshold").unwrap_or(json!(static_count)),
|
||||
})
|
||||
}
|
||||
|
||||
fn patch_profile_xml(mut xml: String, settings: &[(&'static str, String)]) -> String {
|
||||
for (id, value) in settings {
|
||||
let marker = format!(r#"<setting id="{id}" value=""#);
|
||||
@@ -84,6 +98,7 @@ pub fn configure_formatter(
|
||||
});
|
||||
let mut settings = cfg.settings.take().unwrap_or_else(|| json!({}));
|
||||
settings["java"]["format"]["settings"] = formatter_overrides(defaults, overrides);
|
||||
settings["java"]["sources"]["organizeImports"] = organize_imports_settings(style, &inherited);
|
||||
cfg.settings = Some(settings);
|
||||
let Some(style) = style else { return Ok(()) };
|
||||
let indent = indent_settings(style);
|
||||
@@ -300,6 +315,44 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn organize_imports_thresholds_default_to_idea_and_keep_explicit_server_settings() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().join("project");
|
||||
std::fs::create_dir_all(&root).unwrap();
|
||||
let imports = |cfg: &LanguageServerConfig| {
|
||||
crate::handler::all_settings(cfg)["java"]["sources"]["organizeImports"].clone()
|
||||
};
|
||||
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle {
|
||||
class_count_to_use_import_with_star: Some(7),
|
||||
names_count_to_use_static_import_with_star: Some(4),
|
||||
..Default::default()
|
||||
};
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 7, "staticStarThreshold": 4}));
|
||||
|
||||
// Unset: IDEA's 5 and 3, not jdtls' 99 (#6026).
|
||||
let mut cfg = config("jdtls");
|
||||
let style = LanguageCodeStyle { names_count_to_use_static_import_with_star: Some(2), ..Default::default() };
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 2}));
|
||||
let mut cfg = config("jdtls");
|
||||
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 5, "staticStarThreshold": 3}));
|
||||
|
||||
// A threshold set in the server configuration wins.
|
||||
let mut cfg = config("jdtls");
|
||||
cfg.settings = Some(json!({"java": {"sources": {"organizeImports": {"starThreshold": 99}}}}));
|
||||
configure_formatter(&mut cfg, Some(&style), &root, dir.path(), None).unwrap();
|
||||
assert_eq!(imports(&cfg), json!({"starThreshold": 99, "staticStarThreshold": 2}));
|
||||
|
||||
let mut cfg = config("rust-analyzer");
|
||||
configure_formatter(&mut cfg, None, &root, dir.path(), None).unwrap();
|
||||
assert!(crate::handler::all_settings(&cfg)["java"].is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_keeps_explicit_server_configuration_and_custom_accepts_absolute_paths() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -969,6 +969,145 @@ async fn bundler_path_aliases_resolve_below_tsconfig_paths() {
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
const MDX_BUTTON: &str =
|
||||
"export function Button(props: { label: string }) {\n return <button>{props.label}</button>;\n}\n";
|
||||
const MDX_DOC: &str = "import { Button } from \"./Button\"\n\nexport const count = 2\n\n# Hello\n\n<Button label=\"hi\" />\n\n<Button label={count} />\n\n{count.toFixed()}\n";
|
||||
|
||||
/// The MDX Language Server with the `typescript.tsdk` the launcher adds. Set
|
||||
/// `OPENIDEA_TEST_NPM_TOOLS` to a dir with `npm i @mdx-js/language-server
|
||||
/// typescript@6 @types/react`; the project is created inside it, so that it
|
||||
/// resolves the React types.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @mdx-js/language-server, typescript and @types/react (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn mdx_language_server_end_to_end() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir_in(&tools).unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
std::fs::write(
|
||||
root.join("tsconfig.json"),
|
||||
"{\"compilerOptions\":{\"strict\":true,\"jsx\":\"react-jsx\",\"moduleResolution\":\"bundler\",\"module\":\"esnext\"},\"mdx\":{\"checkMdx\":true}}",
|
||||
)
|
||||
.unwrap();
|
||||
let (button, file) = (root.join("Button.tsx"), root.join("doc.mdx"));
|
||||
std::fs::write(&button, MDX_BUTTON).unwrap();
|
||||
std::fs::write(&file, MDX_DOC).unwrap();
|
||||
|
||||
let mut mdx = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("mdx")).unwrap();
|
||||
let server = &mut mdx.language_servers[0];
|
||||
server.command = tools.join("node_modules/.bin/mdx-language-server").to_string_lossy().into_owned();
|
||||
let tsdk = tools.join("node_modules/typescript/lib").to_string_lossy().into_owned();
|
||||
server.initialization_options.as_mut().unwrap()["typescript"]
|
||||
.as_table_mut()
|
||||
.unwrap()
|
||||
.insert("tsdk".into(), toml::Value::String(tsdk));
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![mdx]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &file, &LanguageId::new("mdx"), 1, MDX_DOC);
|
||||
|
||||
// `Button` in `<Button label="hi" />`.
|
||||
let hover = retry("hover", Duration::from_secs(90), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.hover(doc, Pos::new(6, 3), Default::default()).await.ok().flatten() }
|
||||
})
|
||||
.await;
|
||||
assert!(hover.contents.value.contains("label: string"), "{}", hover.contents.value);
|
||||
let defs = mgr.goto(doc, Pos::new(6, 3), GotoKind::Definition).await.unwrap();
|
||||
assert!(defs.iter().any(|d| d.path == button), "{defs:?}");
|
||||
|
||||
// Members of `count` inside `{…}`, and the imported component in JSX.
|
||||
for (pos, label) in [(Pos::new(10, 7), "toFixed"), (Pos::new(6, 3), "Button")] {
|
||||
retry(label, Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move {
|
||||
let list = mgr.completion(doc, pos, None, Default::default()).await.ok()?;
|
||||
list.items.iter().any(|i| i.label == label).then_some(())
|
||||
}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
// Markdown headings come from the server too (marksman skips `.mdx` by default).
|
||||
let symbols = mgr.document_symbols(doc).await.unwrap().unwrap();
|
||||
assert!(symbols.iter().any(|s| s.name.contains("Hello")), "{symbols:?}");
|
||||
|
||||
// `label={count}`: number is not assignable to string.
|
||||
retry("prop type error", Duration::from_secs(60), || {
|
||||
let found = events.lock().iter().any(|e| {
|
||||
matches!(e, IdeEvent::Diagnostics { path, items, .. }
|
||||
if path == &file && items.iter().any(|d| d.range.start.line == 8 && d.message.contains("string")))
|
||||
});
|
||||
async move { found.then_some(()) }
|
||||
})
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// A tsserver plugin reporting `from <name>` at the start of every file.
|
||||
const DIAGNOSTIC_PLUGIN: &str = "module.exports = () => ({ create(info) {\n const ls = info.languageService;\n const proxy = Object.create(null);\n for (const k of Object.keys(ls)) proxy[k] = (...a) => ls[k](...a);\n proxy.getSemanticDiagnostics = (f) => [...ls.getSemanticDiagnostics(f), { file: ls.getProgram().getSourceFile(f), start: 0, length: 1, messageText: 'from ' + NAME, category: 1, code: 99001 }];\n return proxy;\n} });\n";
|
||||
|
||||
/// tsconfig `compilerOptions.plugins` load from the project's `node_modules` with vtsls' own
|
||||
/// TypeScript through the probe location `configure_tsconfig_plugins` writes (#6336); one that
|
||||
/// isn't installed is skipped, and the IDE's global plugins keep loading their own copies,
|
||||
/// also when the project has a package of the same name. Set `OPENIDEA_TEST_NPM_TOOLS` to a
|
||||
/// dir with `npm i @vtsls/language-server typescript@5`.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires @vtsls/language-server (OPENIDEA_TEST_NPM_TOOLS)"]
|
||||
async fn tsconfig_plugins_load_from_the_project_with_the_bundled_typescript() {
|
||||
let tools = std::path::PathBuf::from(std::env::var("OPENIDEA_TEST_NPM_TOOLS").expect("OPENIDEA_TEST_NPM_TOOLS"));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dunce::canonicalize(dir.path()).unwrap();
|
||||
// Outside the project: a probe location resolves plugins from its ancestors' node_modules too.
|
||||
let ide = tempfile::tempdir().unwrap();
|
||||
let ide = dunce::canonicalize(ide.path()).unwrap();
|
||||
let plugin = |dir: &Path, name: &str, says: &str| {
|
||||
let dir = dir.join("node_modules").join(name);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("index.js"), DIAGNOSTIC_PLUGIN.replace("NAME", &format!("'{says}'"))).unwrap();
|
||||
};
|
||||
plugin(&root, "project-plugin", "project-plugin");
|
||||
plugin(&root, "global-plugin", "the project's global-plugin");
|
||||
plugin(&ide, "global-plugin", "global-plugin");
|
||||
std::fs::write(root.join("package.json"), "{\"name\":\"app\",\"private\":true}").unwrap();
|
||||
let plugins = r#"[{"name":"not-installed"},{"name":"project-plugin"}]"#;
|
||||
std::fs::write(root.join("tsconfig.json"), format!("{{\"compilerOptions\":{{\"plugins\":{plugins}}}}}")).unwrap();
|
||||
let main = root.join("main.ts");
|
||||
let text = "export const n: number = 1;\n";
|
||||
std::fs::write(&main, text).unwrap();
|
||||
let global = serde_json::json!({ "vtsls": { "tsserver": { "globalPlugins": [{
|
||||
"name": "global-plugin",
|
||||
"location": ide.to_string_lossy(),
|
||||
"enableForWorkspaceTypeScriptVersions": true,
|
||||
}] } } });
|
||||
|
||||
for configured in [false, true] {
|
||||
let mut server = npm_server(&tools, "vtsls", "vtsls", Some(global.clone()));
|
||||
server.tsserver_project = true;
|
||||
if configured {
|
||||
assert!(ide_sdk::apply::configure_tsconfig_plugins(&mut server, &root, &ide.join("data")));
|
||||
}
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![lang("typescript", "ts", server)]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &main, &LanguageId::new("typescript"), 1, text);
|
||||
let mut messages = retry("the plugins' diagnostics", Duration::from_secs(90), || {
|
||||
let found = events.lock().iter().rev().find_map(|e| match e {
|
||||
IdeEvent::Diagnostics { path, items, .. } if path == &main && !items.is_empty() => {
|
||||
Some(items.iter().map(|d| d.message.clone()).collect::<Vec<_>>())
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
messages.sort();
|
||||
let expected: &[&str] =
|
||||
if configured { &["from global-plugin", "from project-plugin"] } else { &["from global-plugin"] };
|
||||
assert_eq!(messages, expected);
|
||||
let crashed = matches!(last_status(&events, "vtsls"), Some((ServerStatus::Crashed, _)));
|
||||
assert!(!crashed, "{:?}", last_status(&events, "vtsls"));
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
const NG_APP_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.html',\n})\nexport class App {\n title = 'demo';\n}\n";
|
||||
const NG_APP_HTML: &str = "<h1>{{ title }}</h1>\n<p>{{ missing }}</p>\n";
|
||||
const NG_INLINE_TS: &str = "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-inline',\n template: `<b>{{ count }}</b>`,\n})\nexport class Inline {\n count = 1;\n}\n";
|
||||
@@ -1425,3 +1564,81 @@ async fn jdtls_build_reports_cross_module_errors_in_open_and_closed_files() {
|
||||
.await;
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
|
||||
/// Indented Sass through the built-in `sass` definition: completion, Go to
|
||||
/// Declaration and hover across `@use`, and syntax errors as diagnostics.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[ignore = "requires some-sass-language-server on PATH"]
|
||||
async fn some_sass_indented_end_to_end() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path().canonicalize().unwrap();
|
||||
let theme = root.join("_theme.sass");
|
||||
std::fs::write(
|
||||
&theme,
|
||||
"/// Brand colour\n$brand: #336699\n\n/// Rounded corners\n@mixin rounded($r: 4px)\n border-radius: $r\n",
|
||||
)
|
||||
.unwrap();
|
||||
let main = root.join("main.sass");
|
||||
let source = "@use \"theme\"\n\n.button\n color: theme.$brand\n +theme.rounded(2px)\n";
|
||||
std::fs::write(&main, source).unwrap();
|
||||
let sass = LanguageRegistry::load(None).unwrap().get(&LanguageId::new("sass")).unwrap();
|
||||
let (mgr, events) = manager(&root, LanguageRegistry::from_configs(vec![sass]));
|
||||
let doc = DocId::next();
|
||||
mgr.did_open(doc, &main, &LanguageId::new("sass"), 1, source);
|
||||
let name = "some-sass-language-server";
|
||||
retry("some-sass ready", Duration::from_secs(30), || {
|
||||
let status = last_status(&events, name);
|
||||
if let Some((ServerStatus::Crashed | ServerStatus::Missing | ServerStatus::Misconfigured, msg)) = &status {
|
||||
panic!("some-sass failed: {msg:?}");
|
||||
}
|
||||
async move { matches!(status, Some((ServerStatus::Ready | ServerStatus::Busy, _))).then_some(()) }
|
||||
})
|
||||
.await;
|
||||
|
||||
// `theme.$brand` and the `+theme.rounded` mixin, both in `_theme.sass`.
|
||||
for (pos, line) in [(Pos::new(3, 17), 1), (Pos::new(4, 10), 4)] {
|
||||
let defs = retry("definition", Duration::from_secs(30), || {
|
||||
let mgr = mgr.clone();
|
||||
async move { mgr.goto(doc, pos, GotoKind::Definition).await.ok().filter(|d| !d.is_empty()) }
|
||||
})
|
||||
.await;
|
||||
assert_eq!((defs[0].path.to_path_buf(), defs[0].range.start.line), (theme.clone(), line), "{pos:?}");
|
||||
}
|
||||
// The `@use` path is a document link, which Go to Declaration follows.
|
||||
let links = mgr.document_links(doc).await.unwrap();
|
||||
assert!(
|
||||
links
|
||||
.iter()
|
||||
.any(|l| l.range.start.line == 0 && l.path.as_ref().map(|p| p.to_path_buf()) == Some(theme.clone())),
|
||||
"{links:?}"
|
||||
);
|
||||
let hover = mgr.hover(doc, Pos::new(3, 17), Default::default()).await.unwrap().unwrap();
|
||||
assert!(hover.contents.value.contains("#336699") && hover.contents.value.contains("Brand colour"));
|
||||
let hover = mgr.hover(doc, Pos::new(4, 10), Default::default()).await.unwrap().unwrap();
|
||||
assert!(hover.contents.value.contains("Rounded corners"), "{}", hover.contents.value);
|
||||
|
||||
// `$` lists the module's variables, `+` its mixins.
|
||||
let edited = format!("{source} margin: theme.$\n +theme.\n");
|
||||
mgr.did_change(
|
||||
doc,
|
||||
2,
|
||||
&[AppliedChange { range: Range::point(Pos::new(5, 0)), text: edited[source.len()..].into() }],
|
||||
&|| unreachable!(),
|
||||
);
|
||||
let labels = |list: ide_lsp::types::CompletionList| list.items.into_iter().map(|i| i.label).collect::<Vec<_>>();
|
||||
let vars = labels(mgr.completion(doc, Pos::new(5, 16), Some("$".into()), Default::default()).await.unwrap());
|
||||
assert!(vars.iter().any(|l| l.contains("$brand")), "{vars:?}");
|
||||
let mixins = labels(mgr.completion(doc, Pos::new(6, 9), Some(".".into()), Default::default()).await.unwrap());
|
||||
assert!(mixins.iter().any(|l| l.contains("rounded")), "{mixins:?}");
|
||||
|
||||
let errors = retry("diagnostics", Duration::from_secs(30), || {
|
||||
let found = events.lock().iter().rev().find_map(|event| match event {
|
||||
IdeEvent::Diagnostics { source, items, .. } if source == name && !items.is_empty() => Some(items.clone()),
|
||||
_ => None,
|
||||
});
|
||||
async move { found }
|
||||
})
|
||||
.await;
|
||||
assert!(errors.iter().any(|d| d.range.start.line >= 5), "{errors:?}");
|
||||
tokio::time::timeout(Duration::from_secs(10), mgr.shutdown_all()).await.unwrap();
|
||||
}
|
||||
Бінарний файл не відображається.
+1
-1
@@ -1 +1 @@
|
||||
04c8f881e25aae1b7298f554f3c4ab38251eec48e8d88656d73cad019eb1644c
|
||||
db06d81fb37a51711e2b76ab0192eb23293ef498e8ff6e5e46e0b5099d6ba038
|
||||
@@ -78,7 +78,7 @@ pub fn container_config(config: &RunConfig, run: &ContainerRun) -> IdeResult<Run
|
||||
// Variables go by name (`-e NAME`) so their values stay out of the command line
|
||||
// echoed in the console; the docker CLI reads them from its own environment.
|
||||
let mut env: BTreeMap<String, String> = run.file_env.clone();
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test")
|
||||
&& !command.env.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
env.insert("PYTHONUNBUFFERED".into(), "1".into());
|
||||
|
||||
@@ -1227,7 +1227,10 @@ fn uses_pytest(root: &Path) -> bool {
|
||||
if read(&root.join("setup.cfg")).is_some_and(|s| s.contains("[tool:pytest]")) {
|
||||
return true;
|
||||
}
|
||||
if read(&root.join("pyproject.toml")).is_some_and(|py| py.contains("pytest") || root.join("tests").is_dir()) {
|
||||
// A `tests` folder alone means pytest unless its tests are the standard library's unittest.
|
||||
if read(&root.join("pyproject.toml"))
|
||||
.is_some_and(|py| py.contains("pytest") || (root.join("tests").is_dir() && !uses_unittest(root)))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
["requirements.txt", "requirements-dev.txt", "requirements_dev.txt", "dev-requirements.txt"]
|
||||
@@ -1235,6 +1238,34 @@ fn uses_pytest(root: &Path) -> bool {
|
||||
.any(|f| read(&root.join(f)).is_some_and(|s| s.contains("pytest")))
|
||||
}
|
||||
|
||||
/// Whether the project's test modules (`test*.py` at the root and in `tests/` / `test/`) use the
|
||||
/// standard library's unittest and none of them pytest.
|
||||
fn uses_unittest(root: &Path) -> bool {
|
||||
let mut found = false;
|
||||
for dir in [root.to_path_buf(), root.join("tests"), root.join("test")] {
|
||||
let Ok(entries) = fs::read_dir(&dir) else { continue };
|
||||
// ponytail: the first 50 modules of each folder decide; enough to tell a project's style.
|
||||
for entry in entries.flatten().take(50) {
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if !name.starts_with("test") || !name.ends_with(".py") {
|
||||
continue;
|
||||
}
|
||||
let Some(text) = read(&entry.path()) else { continue };
|
||||
if text
|
||||
.lines()
|
||||
.any(|l| l.trim_start().starts_with("import pytest") || l.trim_start().starts_with("from pytest"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
found |= text.lines().any(|l| {
|
||||
let l = l.trim_start();
|
||||
l.starts_with("import unittest") || l.starts_with("from unittest")
|
||||
});
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Python configurations of the project at `root`, a folder of the opened project `top`.
|
||||
fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let markers = ["pyproject.toml", "setup.py", "setup.cfg", "requirements.txt", "pytest.ini", "tox.ini", "manage.py"];
|
||||
@@ -1280,6 +1311,11 @@ fn detect_python(top: &Path, root: &Path, out: &mut Vec<RunConfig>) {
|
||||
let own_pytest = matches!(env, PyEnv::Venv(ref v) if !v.starts_with("../")) && env.has_tool(root, "pytest");
|
||||
if uses_pytest(root) || own_pytest {
|
||||
out.push(py_config("pytest".into(), "pytest".into(), "pytest", env.tool(root, "pytest"), &[]).test());
|
||||
} else if !root.join("manage.py").is_file() && uses_unittest(root) {
|
||||
out.push(
|
||||
py_config("unittest".into(), "python -m unittest".into(), "unittest", env.python(), &["-m", "unittest"])
|
||||
.test(),
|
||||
);
|
||||
}
|
||||
// After pytest: a project set up for pytest (pytest-django) keeps it as the default test runner.
|
||||
if root.join("manage.py").is_file() {
|
||||
|
||||
@@ -341,6 +341,7 @@ impl Cx<'_> {
|
||||
DJANGO_SERVER => self.django_server(name, c, &mut ignored)?,
|
||||
DJANGO_TESTS => self.django_tests(name, c, &mut ignored)?,
|
||||
PYTHON_TESTS if matches!(factory, "py.test" | "pytest") => self.pytest(name, c, &mut ignored)?,
|
||||
PYTHON_TESTS if factory == "Unittests" => self.unittest(name, c, &mut ignored)?,
|
||||
NPM => self.npm(name, c, &mut ignored)?,
|
||||
JEST | VITEST => self.js_tests(name, c, ty == VITEST, &mut ignored)?,
|
||||
NODE => self.node(name, c, &mut ignored)?,
|
||||
@@ -667,6 +668,38 @@ impl Cx<'_> {
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// PyCharm's Unittests: a Python target (`tests.test_money.TestRound`) as unittest's name, a
|
||||
/// file as its path, a folder discovered (`discover -s`, with the configuration's pattern).
|
||||
fn unittest(&self, name: &str, c: &El, ignored: &mut Vec<String>) -> Res<RunConfig> {
|
||||
let (exe, mut args, dir, cwd) = self.interpreter(c, ignored)?;
|
||||
args.extend(["-m".to_owned(), "unittest".to_owned()]);
|
||||
let field = |key: &str| c.option(key).map(json_string).filter(|v| !v.trim().is_empty());
|
||||
if let Some(target) = field("_new_target") {
|
||||
let target = self.expand(&target)?;
|
||||
match field("_new_targetType").as_deref() {
|
||||
Some("PYTHON") => args.push(target),
|
||||
Some("CUSTOM") => {}
|
||||
_ => {
|
||||
let path = path_from(self.root, file_url_path(&target), &dir);
|
||||
if path.ends_with(".py") {
|
||||
args.push(path);
|
||||
} else {
|
||||
args.extend(["discover".to_owned(), "-s".to_owned(), path]);
|
||||
if let Some(pattern) = field("_new_pattern") {
|
||||
args.extend(["-p".to_owned(), strip_quotes(&pattern).to_owned()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
args.extend(self.args_quoted(field("_new_additionalArguments").as_deref(), Quotes::Single, &dir)?);
|
||||
let mut rc = config(name, "unittest", exe, args, Some("debugpy"));
|
||||
rc.cwd = cwd.map(Into::into);
|
||||
rc.is_test = true;
|
||||
self.python_env(c, &mut rc, ignored)?;
|
||||
Ok(rc)
|
||||
}
|
||||
|
||||
/// A pytest Python target (`tests.test_money.TestRound.test_eur`) as the node id PyCharm
|
||||
/// passes (`tests/test_money.py::TestRound::test_eur`, intellij-community `PyTestsShared.kt:366-400`):
|
||||
/// the longest prefix that is a module on disk (`a/b.py` or `a/b/__init__.py`, from the working
|
||||
|
||||
@@ -426,7 +426,7 @@ impl ProcessManager {
|
||||
return Err(IdeError::invalid("input cannot be redirected from a file when emulating a terminal"));
|
||||
}
|
||||
let mut env = launch_env(root, config)?;
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test") {
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") {
|
||||
crate::python_path::extend(&mut env.vars, &options.python_paths, !env.clear)?;
|
||||
}
|
||||
if let Some(dir) = options.ruby_reporter.as_deref().filter(|_| crate::ruby_reporter::applies(config)) {
|
||||
@@ -1087,7 +1087,7 @@ fn launch_env(root: &Path, config: &RunConfig) -> IdeResult<LaunchEnv> {
|
||||
let paths: Vec<PathBuf> = extras.env_files.iter().map(|f| resolve_cwd(root, Some(Path::new(f)))).collect();
|
||||
crate::envfile::load(&paths, &base).map_err(|e| IdeError::not_found(format!("cannot read .env file: {e}")))?
|
||||
};
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "django-test")
|
||||
if matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test")
|
||||
&& !config.env.contains_key("PYTHONUNBUFFERED")
|
||||
&& !vars.contains_key("PYTHONUNBUFFERED")
|
||||
{
|
||||
|
||||
@@ -676,6 +676,34 @@ fn python_projects() {
|
||||
assert_eq!(ids(&c), ["python:module:app"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn python_unittest_projects() {
|
||||
const UNITTEST: &str = "import unittest\n\nclass T(unittest.TestCase):\n pass\n";
|
||||
// The standard library's unittest and no pytest: `python -m unittest`.
|
||||
let dir = project(&[("pyproject.toml", "[project]\nname = 'x'\n"), ("tests/test_x.py", UNITTEST)]);
|
||||
let c = detect(dir.path());
|
||||
assert_eq!(ids(&c), ["unittest"]);
|
||||
let unittest = find(&c, "unittest");
|
||||
let python = if cfg!(windows) { "python" } else { "python3" };
|
||||
assert_eq!(cmdline(unittest), format!("{python} -m unittest"));
|
||||
assert!(unittest.is_test);
|
||||
assert_eq!(unittest.debug_adapter.as_deref(), Some("debugpy"));
|
||||
let dir = project(&[("requirements.txt", ""), ("test_app.py", UNITTEST)]);
|
||||
assert_eq!(ids(&detect(dir.path())), ["unittest"]);
|
||||
// A module that imports pytest, a `tests` folder of pytest-style tests, or Django: as before.
|
||||
let dir = project(&[
|
||||
("pyproject.toml", "[project]\nname = 'x'\n"),
|
||||
("tests/test_x.py", UNITTEST),
|
||||
("tests/test_y.py", "import pytest\n"),
|
||||
]);
|
||||
assert_eq!(ids(&detect(dir.path())), ["pytest"]);
|
||||
let dir =
|
||||
project(&[("pyproject.toml", "[project]\nname = 'x'\n"), ("tests/test_x.py", "def test_x():\n assert 1\n")]);
|
||||
assert_eq!(ids(&detect(dir.path())), ["pytest"]);
|
||||
let dir = project(&[("manage.py", ""), ("shop/tests.py", UNITTEST), ("test_x.py", UNITTEST)]);
|
||||
assert_eq!(ids(&detect(dir.path())), ["django:runserver", "django:test"]);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn python_virtualenv() {
|
||||
|
||||
@@ -299,7 +299,16 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
</configuration>
|
||||
<configuration name="Unittests in tests" type="tests" factoryName="Unittests">
|
||||
{PY_COMMON}
|
||||
<option name="_new_target" value=""tests"" />
|
||||
<option name="_new_pattern" value=""check_*.py"" />
|
||||
<option name="_new_target" value=""$PROJECT_DIR$/tests"" />
|
||||
<option name="_new_targetType" value=""PATH"" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="Unittest case" type="tests" factoryName="Unittests">
|
||||
{PY_COMMON}
|
||||
<option name="_new_additionalArguments" value=""-f"" />
|
||||
<option name="_new_target" value=""tests.test_money.RoundTests"" />
|
||||
<option name="_new_targetType" value=""PYTHON"" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration name="dev" type="js.build_tools.npm">
|
||||
@@ -319,7 +328,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
);
|
||||
let r = import_from(dir.path(), &[]);
|
||||
let names: Vec<&str> = r.imported.iter().map(|c| c.config.name.as_str()).collect();
|
||||
assert_eq!(names, ["App", "Unit", "Case", "Path params", "Custom", "dev"]);
|
||||
assert_eq!(names, ["App", "Unit", "Case", "Path params", "Custom", "Unittests in tests", "Unittest case", "dev"]);
|
||||
|
||||
let app = get(&r, "App");
|
||||
// `$USER_HOME$` is this machine's: the configuration goes to run.local.toml.
|
||||
@@ -343,7 +352,11 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
assert_eq!(get(&r, "Path params").args, s(&["-m", "pytest", "tests/test_money.py", "-k", "slow or fast"]));
|
||||
assert_eq!(get(&r, "Custom").args, s(&["-m", "pytest", "tests/a.py", "--maxfail=2"]));
|
||||
|
||||
assert_eq!(reason(&r, "Unittests in tests"), &SkipReason::UnsupportedType { type_: "tests (Unittests)".into() });
|
||||
let unittests = get(&r, "Unittests in tests");
|
||||
assert_eq!(unittests.kind, "unittest");
|
||||
assert!(unittests.is_test);
|
||||
assert_eq!(unittests.args, s(&["-m", "unittest", "discover", "-s", "tests", "-p", "check_*.py"]));
|
||||
assert_eq!(get(&r, "Unittest case").args, s(&["-m", "unittest", "tests.test_money.RoundTests", "-f"]));
|
||||
assert_eq!(reason(&r, "Main"), &SkipReason::UnsupportedType { type_: "JUnit".into() });
|
||||
|
||||
let dev = get(&r, "dev");
|
||||
@@ -366,7 +379,7 @@ fn workspace_run_manager_skips_templates_and_temporary_configurations() {
|
||||
);
|
||||
assert_eq!(ignored(&r, "dev"), ["scripts"]);
|
||||
// Neither the template nor the temporary `build` is listed as skipped.
|
||||
assert_eq!(r.skipped.len(), 2);
|
||||
assert_eq!(r.skipped.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -35,6 +35,9 @@ pub(crate) const SOURCES: &[(&str, &str)] = generators![
|
||||
"astro",
|
||||
"nestjs",
|
||||
"express",
|
||||
"vue",
|
||||
"expo",
|
||||
"electron",
|
||||
// Systems
|
||||
"go",
|
||||
"rust",
|
||||
|
||||
@@ -20,8 +20,13 @@ dotnet:
|
||||
- "dotnet new console --name my-app --output my-app --language C#"
|
||||
- dotnet sln add my-app
|
||||
- dotnet new gitignore
|
||||
electron:
|
||||
- npx --yes create-electron-app@latest init my-app --skip-git --package-manager npm --template vite --typescript
|
||||
elixir:
|
||||
- mix new . --app my_app
|
||||
expo:
|
||||
- npx --yes create-expo-app@latest my-app --template blank-typescript --no-install --yes
|
||||
- npm install
|
||||
express:
|
||||
- npm install
|
||||
fastapi:
|
||||
@@ -77,5 +82,8 @@ symfony:
|
||||
vite:
|
||||
- npx --yes create-vite@latest my-app --template react-ts --no-interactive
|
||||
- npm install
|
||||
vue:
|
||||
- npx --yes create-vue@latest my-app --ts
|
||||
- npm install
|
||||
zig:
|
||||
- zig init
|
||||
@@ -130,6 +130,20 @@ fn package_steps_use_the_chosen_runner() {
|
||||
assert_eq!(argv(step, &values)[..2], ["bunx", "create-vite@latest"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn create_vue_runs_without_prompting() {
|
||||
let def = def("vue").unwrap();
|
||||
let mut values = with_defaults(def, "My App", &Values::new());
|
||||
// A valid package name, or create-vue asks for one.
|
||||
assert_eq!(argv(&def.steps[0], &values)[2..], ["create-vue@latest", "my-app", "--ts"]);
|
||||
values.insert("ts".into(), "false".into());
|
||||
assert!(argv(&def.steps[0], &values).ends_with(&["--oxlint".to_owned()]));
|
||||
for flag in ["router", "pinia", "vitest", "eslint"] {
|
||||
values.insert(flag.into(), "true".into());
|
||||
}
|
||||
assert!(argv(&def.steps[0], &values).ends_with(&["--router", "--pinia", "--vitest", "--eslint"].map(String::from)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_arguments() {
|
||||
let def = def("python").unwrap();
|
||||
|
||||
@@ -72,6 +72,10 @@ smoke! {
|
||||
astro: "astro", [], ["npm", "run", "build"];
|
||||
nestjs: "nestjs", [], ["npm", "run", "build"];
|
||||
express: "express", [], ["node", "--check", "index.js"];
|
||||
vue: "vue", [("router", "true"), ("pinia", "true"), ("vitest", "true"), ("eslint", "true")], ["npm", "run", "build"];
|
||||
expo: "expo", [], ["npx", "tsc", "--noEmit"];
|
||||
electron: "electron", [], ["npx", "tsc", "--noEmit"];
|
||||
electron_pnpm: "electron", [("pm", "pnpm")], ["pnpm", "exec", "tsc", "--noEmit"];
|
||||
html: "html", [], [];
|
||||
go: "go", [], ["go", "build", "./..."];
|
||||
rust: "rust", [], ["cargo", "build", "-q"];
|
||||
|
||||
@@ -1574,6 +1574,9 @@ pub fn configure_server(cfg: &mut LanguageServerConfig, root: &Path, server_root
|
||||
{
|
||||
cfg.command = bin.to_string_lossy().into_owned();
|
||||
}
|
||||
if name == crate::mdx::SERVER {
|
||||
crate::mdx::configure(cfg, root, server_root, s);
|
||||
}
|
||||
if name == crate::arduino::SERVER {
|
||||
crate::arduino::configure(cfg, root, server_root, s);
|
||||
}
|
||||
@@ -1649,6 +1652,32 @@ pub fn configure_path_aliases(cfg: &mut LanguageServerConfig, server_root: &Path
|
||||
true
|
||||
}
|
||||
|
||||
/// Lets vtsls load the tsserver plugins that the project's tsconfig.json / jsconfig.json
|
||||
/// declare (Next.js) with any TypeScript version, from a plugin probe location under
|
||||
/// `data_dir` that loads the project's packages (#6336). A plugin the IDE registers globally
|
||||
/// keeps the IDE's copy, also when a tsconfig names it, so call this after those are
|
||||
/// registered. No-op without declared plugins, and for TypeScript 7's native server.
|
||||
pub fn configure_tsconfig_plugins(cfg: &mut LanguageServerConfig, server_root: &Path, data_dir: &Path) -> bool {
|
||||
if cfg.name != "vtsls" || !cfg.tsserver_project {
|
||||
return false;
|
||||
}
|
||||
let options = cfg.initialization_options.as_ref().and_then(|v| serde_json::to_value(v).ok());
|
||||
let global: Vec<String> = options
|
||||
.as_ref()
|
||||
.and_then(|v| v.pointer("/vtsls/tsserver/globalPlugins")?.as_array().cloned())
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.filter_map(|p| p.get("name")?.as_str().map(str::to_owned))
|
||||
.collect();
|
||||
let mut declared = crate::tsconfig_plugins::declared(server_root);
|
||||
declared.packages.retain(|name, _| !global.contains(name));
|
||||
let Some(location) = crate::tsconfig_plugins::probe_location(data_dir, server_root, &declared) else {
|
||||
return false;
|
||||
};
|
||||
merge_init_options(cfg, json!({ "typescript": { "tsserver": { "pluginPaths": [location] } } }));
|
||||
true
|
||||
}
|
||||
|
||||
/// The servers `language` uses after Settings › Language Servers: the
|
||||
/// definition's ones that aren't disabled, then the ones defined in settings for it.
|
||||
pub fn language_servers(language: &str, defined: &[LanguageServerConfig], s: &Settings) -> Vec<LanguageServerConfig> {
|
||||
@@ -1925,7 +1954,7 @@ pub fn run_target<'a>(config: &RunConfig, settings: &'a Settings) -> Option<&'a
|
||||
}
|
||||
|
||||
fn is_python_config(config: &RunConfig, program: &str) -> bool {
|
||||
matches!(config.kind.as_str(), "python" | "pytest" | "django-test") || is_python_command(program)
|
||||
matches!(config.kind.as_str(), "python" | "pytest" | "unittest" | "django-test") || is_python_command(program)
|
||||
}
|
||||
|
||||
/// Whether the configuration's `JAVA_HOME` is the one Settings choose (the Maven runner JRE,
|
||||
@@ -2038,7 +2067,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
|
||||
resolve_run_command(c, root, s);
|
||||
let mut path_dirs: Vec<PathBuf> = Vec::new();
|
||||
match c.kind.as_str() {
|
||||
"python" | "pytest" | "django-test" => {
|
||||
"python" | "pytest" | "unittest" | "django-test" => {
|
||||
let command = Path::new(&c.command);
|
||||
let own = !c.detected && command.components().count() > 1 && is_python_command(&c.command);
|
||||
let python = if own {
|
||||
@@ -2056,7 +2085,7 @@ pub fn apply_to_run_configs_in(configs: &mut [RunConfig], root: &Path, fallback:
|
||||
let runner_options = runner
|
||||
&& c.args.first().map(String::as_str) == Some("run")
|
||||
&& c.args.get(1).is_some_and(|a| a.starts_with('-'));
|
||||
if (c.kind == "python" || c.kind == "django-test")
|
||||
if matches!(c.kind.as_str(), "python" | "unittest" | "django-test")
|
||||
&& !runner_options
|
||||
&& (runner || is_python_command(&c.command))
|
||||
{
|
||||
@@ -2689,6 +2718,47 @@ mod maven_linkage_tests {
|
||||
assert_eq!(options.pointer("/typescript/tsserver/maxTsServerMemory"), Some(&json!(6144)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vtsls_probes_the_tsconfig_plugins_but_not_its_global_ones() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let (root, data) = (tmp.path().join("app"), tmp.path().join("data"));
|
||||
std::fs::create_dir_all(root.join("node_modules/next")).unwrap();
|
||||
std::fs::create_dir_all(root.join("node_modules/@vue/typescript-plugin")).unwrap();
|
||||
let vtsls = || {
|
||||
let mut cfg = custom_server("vtsls", &LanguageServerSettings::default());
|
||||
cfg.tsserver_project = true;
|
||||
merge_init_options(
|
||||
&mut cfg,
|
||||
json!({ "vtsls": { "tsserver": { "globalPlugins": [{ "name": vue::PLUGIN }] } } }),
|
||||
);
|
||||
cfg
|
||||
};
|
||||
let probed = |cfg: &LanguageServerConfig| {
|
||||
serde_json::to_value(&cfg.initialization_options)
|
||||
.unwrap()
|
||||
.pointer("/typescript/tsserver/pluginPaths")
|
||||
.cloned()
|
||||
};
|
||||
std::fs::write(root.join("tsconfig.json"), r#"{"compilerOptions":{"strict":true}}"#).unwrap();
|
||||
let mut cfg = vtsls();
|
||||
assert!(!configure_tsconfig_plugins(&mut cfg, &root, &data));
|
||||
assert_eq!(probed(&cfg), None);
|
||||
|
||||
let plugins = format!(r#"[{{"name":"next"}},{{"name":"{}"}}]"#, vue::PLUGIN);
|
||||
std::fs::write(root.join("tsconfig.json"), format!(r#"{{"compilerOptions":{{"plugins":{plugins}}}}}"#))
|
||||
.unwrap();
|
||||
let mut cfg = vtsls();
|
||||
assert!(configure_tsconfig_plugins(&mut cfg, &root, &data));
|
||||
let location = PathBuf::from(probed(&cfg).unwrap()[0].as_str().unwrap());
|
||||
assert!(location.starts_with(&data) && location.join("node_modules/next/index.js").is_file());
|
||||
// The IDE's Vue plugin is not replaced by the project's.
|
||||
assert!(!location.join("node_modules").join(vue::PLUGIN).exists());
|
||||
// TypeScript 7's native server hosts no plugins.
|
||||
let mut native = vtsls();
|
||||
native.tsserver_project = false;
|
||||
assert!(!configure_tsconfig_plugins(&mut native, &root, &data));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typescript_7_keeps_vtsls_when_the_vue_server_is_installed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -22,12 +22,14 @@ pub mod libraries;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
pub mod maven_profiles;
|
||||
mod mdx;
|
||||
mod npm;
|
||||
mod path_aliases;
|
||||
pub mod php;
|
||||
pub mod pinned;
|
||||
pub mod python;
|
||||
pub mod ruby;
|
||||
mod tsconfig_plugins;
|
||||
mod vue;
|
||||
mod zig;
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//! The MDX language server (Volar) refuses to start without `typescript.tsdk`.
|
||||
|
||||
use crate::apply::{merge_init_options, setting_path, tsdk};
|
||||
use crate::discover::workspace_tsdk;
|
||||
use crate::npm::{own_typescript, package_dir};
|
||||
use ide_core::settings::Settings;
|
||||
use ide_core::tool_path::{find_command, search_path};
|
||||
use ide_language::LanguageServerConfig;
|
||||
use serde_json::json;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
|
||||
pub(crate) const SERVER: &str = "mdx-language-server";
|
||||
|
||||
/// The TypeScript vtsls runs with: the selected version, else vtsls' bundled one.
|
||||
/// Without vtsls, the one installed with the server, then the project's.
|
||||
pub(crate) fn configure(cfg: &mut LanguageServerConfig, root: &Path, server_root: &Path, s: &Settings) {
|
||||
let explicit = |o: Option<&toml::Value>| o.and_then(|o| o.get("typescript")?.get("tsdk")).is_some();
|
||||
let overridden = s.language_servers.get(SERVER).and_then(|ls| ls.initialization_options.as_ref());
|
||||
if explicit(cfg.initialization_options.as_ref())
|
||||
|| overridden.is_some_and(|o| o.pointer("/typescript/tsdk").is_some())
|
||||
{
|
||||
return;
|
||||
}
|
||||
let search = cfg.env.get("PATH").map_or_else(search_path, OsString::from);
|
||||
// Missing servers keep the normal install hint.
|
||||
let Some(bin) = find_command(&cfg.command, &search, server_root) else { return };
|
||||
let bundled = |command: &Path, package: &str| own_typescript(&package_dir(command, package)?);
|
||||
let vtsls = s
|
||||
.tool_path("vtsls")
|
||||
.and_then(|p| setting_path(root, p))
|
||||
.or_else(|| find_command("vtsls", &search, server_root));
|
||||
let lib = tsdk(server_root, s)
|
||||
.or_else(|| tsdk(root, s))
|
||||
.or_else(|| bundled(vtsls.as_deref()?, "@vtsls/language-server"))
|
||||
.or_else(|| bundled(&bin, "@mdx-js/language-server"))
|
||||
.or_else(|| workspace_tsdk(server_root))
|
||||
.or_else(|| workspace_tsdk(root));
|
||||
match lib {
|
||||
Some(lib) => merge_init_options(cfg, json!({ "typescript": { "tsdk": lib.to_string_lossy() } })),
|
||||
None => {
|
||||
cfg.launch_error = Some(
|
||||
"MDX Language Server needs TypeScript. Install typescript@6 in the project or select a TypeScript lib directory in Settings."
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_core::LanguageId;
|
||||
use ide_language::LanguageRegistry;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn touch(path: &Path) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "{}").unwrap();
|
||||
#[cfg(unix)]
|
||||
std::fs::set_permissions(path, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
|
||||
}
|
||||
|
||||
fn bin(dir: &Path, name: &str) {
|
||||
touch(&dir.join("node_modules/.bin").join(if cfg!(windows) { format!("{name}.cmd") } else { name.into() }));
|
||||
}
|
||||
|
||||
/// An npm install of `package` with command `bin` under `dir`, and its TypeScript lib.
|
||||
fn install(dir: &Path, package: &str, bin: &str, typescript: &Path) -> PathBuf {
|
||||
self::bin(dir, bin);
|
||||
touch(&dir.join("node_modules").join(package).join("package.json"));
|
||||
let lib = typescript.join("node_modules/typescript/lib");
|
||||
touch(&lib.join("typescript.js"));
|
||||
touch(&lib.join("tsserver.js"));
|
||||
lib
|
||||
}
|
||||
|
||||
fn sdk(root: &Path, path: &[&Path], settings: &Settings) -> LanguageServerConfig {
|
||||
let reg = LanguageRegistry::load(None).unwrap();
|
||||
let mut cfg = reg.get(&LanguageId::new("mdx")).unwrap().language_servers.remove(0);
|
||||
let bins: Vec<PathBuf> = path.iter().map(|p| p.join("node_modules/.bin")).collect();
|
||||
cfg.env.insert("PATH".into(), std::env::join_paths(bins).unwrap().to_string_lossy().into_owned());
|
||||
configure(&mut cfg, root, root, settings);
|
||||
cfg
|
||||
}
|
||||
|
||||
fn tsdk_of(cfg: &LanguageServerConfig) -> Option<PathBuf> {
|
||||
let options = cfg.initialization_options.as_ref()?;
|
||||
assert_eq!(options.get("typescript")?.get("enabled")?.as_bool(), Some(true));
|
||||
Some(PathBuf::from(options.get("typescript")?.get("tsdk")?.as_str()?))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uses_the_typescript_of_vtsls_then_its_own_then_the_project() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let t = dunce::canonicalize(tmp.path()).unwrap();
|
||||
let (mdx, vtsls, project) = (t.join("mdx"), t.join("vtsls"), t.join("project"));
|
||||
let own = install(&mdx, "@mdx-js/language-server", SERVER, &mdx);
|
||||
let vtsls_lib =
|
||||
install(&vtsls, "@vtsls/language-server", "vtsls", &vtsls.join("node_modules/@vtsls/language-server"));
|
||||
let workspace = project.join("node_modules/typescript/lib");
|
||||
touch(&workspace.join("tsserver.js"));
|
||||
let mut settings = Settings::default();
|
||||
|
||||
assert_eq!(tsdk_of(&sdk(&project, &[&mdx], &settings)), Some(own));
|
||||
assert_eq!(tsdk_of(&sdk(&project, &[&mdx, &vtsls], &settings)), Some(vtsls_lib));
|
||||
settings.languages.typescript.version = "workspace".into();
|
||||
assert_eq!(tsdk_of(&sdk(&project, &[&mdx, &vtsls], &settings)), Some(workspace));
|
||||
|
||||
// Missing server: the usual install hint, nothing derived.
|
||||
let missing = sdk(&project, &[&vtsls], &settings);
|
||||
assert_eq!((tsdk_of(&missing), missing.launch_error), (None, None));
|
||||
// No TypeScript anywhere.
|
||||
let bare = t.join("bare");
|
||||
bin(&bare, SERVER);
|
||||
let none = sdk(&t.join("empty"), &[&bare], &Settings::default());
|
||||
assert_eq!(tsdk_of(&none), None);
|
||||
assert!(none.launch_error.unwrap().contains("TypeScript"));
|
||||
}
|
||||
}
|
||||
@@ -564,6 +564,7 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
run("django-test", "uv", &["run", "python", "manage.py", "test"]),
|
||||
run("django-test", ".venv/bin/python", &["manage.py", "test", "polls"]),
|
||||
run("python", "uv", &["run", "--with", "rich", "--no-sync", "main.py"]),
|
||||
run("unittest", "uv", &["run", "python", "-m", "unittest", "tests"]),
|
||||
];
|
||||
apply_to_run_configs(&mut configs, tmp.path(), &s);
|
||||
assert_eq!(configs[0].command, python);
|
||||
@@ -581,6 +582,8 @@ fn run_configs_use_selected_interpreter_and_package_manager() {
|
||||
// uv's own options stay with uv (#5874).
|
||||
assert_eq!(configs[7].command, "uv");
|
||||
assert_eq!(configs[7].args, ["run", "--with", "rich", "--no-sync", "main.py"]);
|
||||
assert_eq!(configs[8].command, python);
|
||||
assert_eq!(configs[8].args, ["-m", "unittest", "tests"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -594,7 +597,7 @@ fn saved_python_configs_keep_their_explicit_interpreter() {
|
||||
settings.languages.python.interpreter = default.to_string_lossy().into_owned();
|
||||
|
||||
for command in [&override_python, relative_python] {
|
||||
for kind in ["python", "pytest", "django-test"] {
|
||||
for kind in ["python", "pytest", "unittest", "django-test"] {
|
||||
let command = command.to_string_lossy();
|
||||
let mut config = run(kind, &command, &["main.py"]);
|
||||
config.detected = false;
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The tsserver plugins a project's tsconfig.json / jsconfig.json declares
|
||||
//! (`compilerOptions.plugins`, e.g. Next.js' `{ "name": "next" }`). tsserver looks for them
|
||||
//! next to the TypeScript it runs from and in its plugin probe locations only, so with the
|
||||
//! bundled TypeScript they are never found unless the project's folder is a probe location.
|
||||
//! Language servers run in trusted projects only, so untrusted ones never load them.
|
||||
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const CONFIGS: [&str; 2] = ["tsconfig.json", "jsconfig.json"];
|
||||
|
||||
/// The plugins that the tsconfig.json / jsconfig.json files under a server root declare.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Declared {
|
||||
/// The plugins' packages by name, resolved as tsserver resolves a plugin from a probe
|
||||
/// location: `node_modules` in the configuration's folder or above.
|
||||
pub packages: BTreeMap<String, PathBuf>,
|
||||
/// The text of the configurations declaring them, with what they extend. When one changes,
|
||||
/// tsserver applies its plugins again on top of the loaded ones (each diagnostic of the
|
||||
/// Next.js plugin shows once more), so the probe location changes and vtsls restarts.
|
||||
pub sources: String,
|
||||
}
|
||||
|
||||
/// The plugins that the configurations under `server_root` declare. Logs the ones that are
|
||||
/// not installed; tsserver skips them.
|
||||
pub(crate) fn declared(server_root: &Path) -> Declared {
|
||||
// ponytail: bounded walk, as the path aliases'; deeper workspace members keep the old behaviour.
|
||||
const MAX_DEPTH: usize = 4;
|
||||
const MAX_ENTRIES: usize = 50_000;
|
||||
let mut walker = ignore::WalkBuilder::new(server_root);
|
||||
walker
|
||||
.max_depth(Some(MAX_DEPTH))
|
||||
.require_git(ide_core::ignored::inside_git_repo(server_root))
|
||||
.follow_links(false)
|
||||
.filter_entry(|e| e.file_name() != "node_modules");
|
||||
let mut configs: Vec<PathBuf> = walker
|
||||
.build()
|
||||
.take(MAX_ENTRIES)
|
||||
.flatten()
|
||||
.filter(|e| CONFIGS.iter().any(|c| e.file_name() == *c))
|
||||
.map(|e| e.into_path())
|
||||
.collect();
|
||||
configs.sort();
|
||||
// ponytail: one package per name; a monorepo with two versions of a plugin gets the first one's.
|
||||
let mut declared = Declared::default();
|
||||
for config in configs {
|
||||
let Some(dir) = config.parent() else { continue };
|
||||
let mut sources = String::new();
|
||||
let names = plugins(&config, 0, &mut sources);
|
||||
if !names.is_empty() {
|
||||
declared.sources.push_str(&sources);
|
||||
}
|
||||
for name in names.into_iter().filter(|n| package_name(n)) {
|
||||
match dir.ancestors().map(|d| d.join("node_modules").join(&name)).find(|p| p.is_dir()) {
|
||||
Some(package) => {
|
||||
declared.packages.entry(name).or_insert(package);
|
||||
}
|
||||
None => tracing::warn!("vtsls: tsserver plugin `{name}` from {} is not installed", config.display()),
|
||||
}
|
||||
}
|
||||
}
|
||||
declared
|
||||
}
|
||||
|
||||
/// A plugin probe location under `data_dir` holding a package for each of the `declared`
|
||||
/// plugins that loads the project's one, and nothing else: packages the project has under the
|
||||
/// names of the IDE's global plugins never shadow those, as the project folder itself would
|
||||
/// (vtsls puts `pluginPaths` before the global plugins' locations). Named after its contents
|
||||
/// and the declaring configurations, so a change is a new location (and a configuration change
|
||||
/// that restarts vtsls). `None` without plugins or when it cannot be written.
|
||||
pub(crate) fn probe_location(data_dir: &Path, server_root: &Path, declared: &Declared) -> Option<PathBuf> {
|
||||
let plugins = &declared.packages;
|
||||
if plugins.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let parent = data_dir.join("tsplugins").join("project").join(key(&server_root.to_string_lossy()));
|
||||
let location = parent.join(key(&format!("{}{}", serde_json::to_string(plugins).ok()?, declared.sources)));
|
||||
for (name, package) in plugins {
|
||||
let dir = location.join("node_modules").join(name);
|
||||
std::fs::create_dir_all(&dir).ok()?;
|
||||
let index = format!("module.exports = require({});\n", Value::from(package.to_string_lossy()));
|
||||
let manifest = serde_json::json!({ "name": name, "main": "index.js" }).to_string();
|
||||
for (file, content) in [("index.js", index), ("package.json", manifest)] {
|
||||
if std::fs::read(dir.join(file)).ok().as_deref() != Some(content.as_bytes()) {
|
||||
std::fs::write(dir.join(file), content).ok()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
// The previous contents: a running tsserver loaded its plugins already.
|
||||
for old in std::fs::read_dir(&parent).into_iter().flatten().flatten() {
|
||||
if old.path() != location {
|
||||
let _ = std::fs::remove_dir_all(old.path());
|
||||
}
|
||||
}
|
||||
Some(location)
|
||||
}
|
||||
|
||||
fn key(text: &str) -> String {
|
||||
Sha256::digest(text.as_bytes()).iter().take(8).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// An npm package name (`next`, `@scope/name`): it becomes a path under the data dir.
|
||||
fn package_name(name: &str) -> bool {
|
||||
let parts: Vec<&str> = name.split('/').collect();
|
||||
let part = |p: &str| {
|
||||
!p.is_empty() && p != "." && p != ".." && p.chars().all(|c| c.is_ascii_alphanumeric() || "-._~".contains(c))
|
||||
};
|
||||
match parts.as_slice() {
|
||||
[name] => part(name),
|
||||
[scope, name] => scope.strip_prefix('@').is_some_and(part) && part(name),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// `compilerOptions.plugins` names of `config`, else of the configurations it `extends`
|
||||
/// (the last of an `extends` array that has some wins, as tsc merges them). Appends the text
|
||||
/// of each file read, the whole `extends` chain, to `read`.
|
||||
fn plugins(config: &Path, depth: usize, read: &mut String) -> Vec<String> {
|
||||
let Ok(text) = std::fs::read_to_string(config) else { return Vec::new() };
|
||||
read.push_str(&text);
|
||||
let Ok(json) = serde_json::from_str::<Value>(&ide_core::jsonc::strip(&text)) else { return Vec::new() };
|
||||
let dir = config.parent().unwrap_or(Path::new(""));
|
||||
let extends = match json.get("extends") {
|
||||
Some(Value::String(s)) => vec![s.as_str()],
|
||||
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let inherited: Vec<Vec<String>> = if depth > 8 {
|
||||
Vec::new()
|
||||
} else {
|
||||
extends.into_iter().filter_map(|spec| extended(dir, spec)).map(|base| plugins(&base, depth + 1, read)).collect()
|
||||
};
|
||||
match json.pointer("/compilerOptions/plugins").and_then(Value::as_array) {
|
||||
Some(own) => own.iter().filter_map(|p| p.get("name")?.as_str().map(str::to_owned)).collect(),
|
||||
None => inherited.into_iter().rev().find(|p| !p.is_empty()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The file an `extends` entry names: a path relative to `dir`, or a package's file
|
||||
/// (`@tsconfig/next/tsconfig.json`, or a package's own `tsconfig.json`) in `node_modules`.
|
||||
fn extended(dir: &Path, spec: &str) -> Option<PathBuf> {
|
||||
let candidates = |base: PathBuf| [base.clone(), base.with_extension("json"), base.join("tsconfig.json")];
|
||||
if spec.starts_with('.') || Path::new(spec).is_absolute() {
|
||||
return candidates(dir.join(spec)).into_iter().find(|p| p.is_file());
|
||||
}
|
||||
dir.ancestors().flat_map(|d| candidates(d.join("node_modules").join(spec))).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn write(root: &Path, file: &str, text: &str) {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, text).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_plugins_resolve_to_the_project_packages() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path();
|
||||
write(root, "package.json", "{}");
|
||||
// A monorepo: the root tsconfig has no plugins, the Next.js app (comments, trailing commas) has.
|
||||
write(root, "tsconfig.json", r#"{ "compilerOptions": { "strict": true } }"#);
|
||||
write(
|
||||
root,
|
||||
"apps/web/tsconfig.json",
|
||||
"{\n // Next.js\n \"compilerOptions\": { \"plugins\": [{ \"name\": \"next\" },] } }",
|
||||
);
|
||||
write(root, "apps/web/node_modules/next/package.json", "{}");
|
||||
// Inherited from a shared configuration, in a package and in a relative file; resolved upwards.
|
||||
write(root, "apps/docs/tsconfig.json", r#"{ "extends": ["../../tsconfig.json", "@acme/tsconfig/next.json"] }"#);
|
||||
write(
|
||||
root,
|
||||
"node_modules/@acme/tsconfig/next.json",
|
||||
r#"{ "compilerOptions": { "plugins": [{ "name": "@acme/plugin" }] } }"#,
|
||||
);
|
||||
write(root, "node_modules/@acme/plugin/package.json", "{}");
|
||||
write(root, "apps/api/jsconfig.json", r#"{ "extends": "./base" }"#);
|
||||
write(
|
||||
root,
|
||||
"apps/api/base.json",
|
||||
r#"{ "compilerOptions": { "plugins": [{ "name": "missing-plugin" }, { "name": "../../escape" }] } }"#,
|
||||
);
|
||||
// An empty list overrides the inherited one; node_modules is never searched for configurations.
|
||||
write(
|
||||
root,
|
||||
"apps/plain/tsconfig.json",
|
||||
r#"{ "extends": "../api/base.json", "compilerOptions": { "plugins": [] } }"#,
|
||||
);
|
||||
write(root, "node_modules/x/tsconfig.json", r#"{ "compilerOptions": { "plugins": [{ "name": "x" }] } }"#);
|
||||
|
||||
let found = declared(root);
|
||||
let expected = [("@acme/plugin", "node_modules/@acme/plugin"), ("next", "apps/web/node_modules/next")];
|
||||
assert_eq!(found.packages, expected.map(|(n, p)| (n.to_owned(), root.join(p))).into_iter().collect());
|
||||
|
||||
// Forwarding packages, replaced when the plugins change.
|
||||
let data = tempfile::tempdir().unwrap();
|
||||
let location = probe_location(data.path(), root, &found).unwrap();
|
||||
let index = std::fs::read_to_string(location.join("node_modules/@acme/plugin/index.js")).unwrap();
|
||||
assert!(index.contains(&serde_json::to_string(&root.join("node_modules/@acme/plugin")).unwrap()), "{index}");
|
||||
let next_only =
|
||||
Declared { packages: found.packages.clone().into_iter().filter(|(n, _)| n == "next").collect(), ..found };
|
||||
let changed = probe_location(data.path(), root, &next_only).unwrap();
|
||||
assert_ne!(changed, location);
|
||||
assert!(!location.exists() && changed.join("node_modules/next/index.js").is_file());
|
||||
// Any edit of a declaring configuration (or one it extends) makes a new location.
|
||||
write(root, "tsconfig.json", r#"{ "compilerOptions": { "strict": false } }"#);
|
||||
let edited =
|
||||
probe_location(data.path(), root, &Declared { sources: declared(root).sources, ..next_only }).unwrap();
|
||||
assert_ne!(edited, changed);
|
||||
assert_eq!(probe_location(data.path(), root, &Declared::default()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plugin_names_are_package_names() {
|
||||
for ok in ["next", "@scope/name", "gql.tada", "@styled/typescript-styled-plugin"] {
|
||||
assert!(package_name(ok), "{ok}");
|
||||
}
|
||||
for bad in ["", "..", "../x", "a/b", "@scope", "@/x", "@scope/..", "a\\b", "/abs"] {
|
||||
assert!(!package_name(bad), "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projects_without_plugins_declare_none() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
write(tmp.path(), "tsconfig.json", r#"{ "extends": "./missing.json", "compilerOptions": {} }"#);
|
||||
assert!(declared(tmp.path()).packages.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,8 @@ impl SshManager {
|
||||
let config = self.config(id)?;
|
||||
let secret = self.secret(&config);
|
||||
let session = Arc::new(self.connect(id, &SshTarget::from(&config), secret.as_deref()).await?);
|
||||
// The shared session carries the config's port forwards, restarted on every reconnect.
|
||||
session.start_forwards().await;
|
||||
self.sessions.lock().insert(id.to_owned(), session.clone());
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
//! (or is recorded silently under `StrictHostKeyChecking accept-new`), and a
|
||||
//! changed key is refused unless host key checking is off.
|
||||
|
||||
use crate::target::{Hop, HostKeyPolicy, SshFiles, SshTarget, expand, home, resolve_hops};
|
||||
use crate::target::{
|
||||
ForwardDirection, Hop, HostKeyPolicy, PortForward, SshFiles, SshTarget, expand, home, resolve_hops,
|
||||
};
|
||||
use ide_core::remote_settings::SshAuth;
|
||||
use ide_core::{IdeError, IdeResult, error::ErrorKind};
|
||||
use parking_lot::Mutex;
|
||||
@@ -113,6 +115,18 @@ pub struct Session {
|
||||
/// Sessions of the `ProxyJump` hosts, kept alive under `handle`.
|
||||
_jumps: Vec<Handle<Client>>,
|
||||
label: String,
|
||||
/// The config's `LocalForward` / `RemoteForward`s, started by [`Session::start_forwards`].
|
||||
forwards: Vec<PortForward>,
|
||||
/// `LocalForward` listeners, stopped with the session.
|
||||
listeners: Mutex<Vec<tokio::task::AbortHandle>>,
|
||||
}
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
for listener in self.listeners.lock().drain(..) {
|
||||
listener.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
@@ -158,8 +172,50 @@ impl Session {
|
||||
sessions.push(handle);
|
||||
}
|
||||
let handle = sessions.pop().expect("at least one hop");
|
||||
let label = hops.last().expect("at least one hop").label();
|
||||
Ok(Session { handle, _jumps: sessions, label })
|
||||
let last = hops.last().expect("at least one hop");
|
||||
Ok(Session {
|
||||
handle,
|
||||
_jumps: sessions,
|
||||
label: last.label(),
|
||||
forwards: last.forwards.clone(),
|
||||
listeners: Mutex::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts the config's `LocalForward` / `RemoteForward`s, as `ssh` does on connecting: the
|
||||
/// SSH host listens for each `RemoteForward` (`tcpip-forward`), this machine for each
|
||||
/// `LocalForward`, until the session closes. A port that cannot be forwarded (in use, refused
|
||||
/// by the server) is skipped with a warning, as `ssh` goes on without it.
|
||||
pub async fn start_forwards(self: &Arc<Self>) {
|
||||
for f in &self.forwards {
|
||||
let what = format!("{}:{} → {}:{}", f.bind, f.port, f.host, f.host_port);
|
||||
match f.direction {
|
||||
ForwardDirection::Remote => match self.handle.tcpip_forward(f.bind.clone(), u32::from(f.port)).await {
|
||||
Ok(_) => tracing::info!("{}: RemoteForward {what}", self.label),
|
||||
Err(e) => tracing::warn!("{}: RemoteForward {what} failed: {e}", self.label),
|
||||
},
|
||||
ForwardDirection::Local => {
|
||||
let bind = match f.bind.as_str() {
|
||||
"localhost" => "127.0.0.1",
|
||||
"" => "0.0.0.0",
|
||||
b => b,
|
||||
};
|
||||
match tokio::net::TcpListener::bind((bind, f.port)).await {
|
||||
Ok(listener) => {
|
||||
let task = tokio::spawn(local_forward(
|
||||
listener,
|
||||
Arc::downgrade(self),
|
||||
f.host.clone(),
|
||||
f.host_port,
|
||||
));
|
||||
self.listeners.lock().push(task.abort_handle());
|
||||
tracing::info!("{}: LocalForward {what}", self.label);
|
||||
}
|
||||
Err(e) => tracing::warn!("{}: LocalForward {what} failed: {e}", self.label),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `user@host:port` of the target.
|
||||
@@ -404,6 +460,39 @@ fn io(message: impl Into<String>) -> IdeError {
|
||||
IdeError::new(ErrorKind::Io, message)
|
||||
}
|
||||
|
||||
/// A `LocalForward` listener: each connection goes through a `direct-tcpip` channel to
|
||||
/// `host:port` from the SSH host, while the session lives.
|
||||
async fn local_forward(listener: tokio::net::TcpListener, session: std::sync::Weak<Session>, host: String, port: u16) {
|
||||
while let Ok((mut socket, _)) = listener.accept().await {
|
||||
let Some(session) = session.upgrade().filter(|s| !s.is_closed()) else { return };
|
||||
let host = host.clone();
|
||||
tokio::spawn(async move {
|
||||
match session.direct_tcpip(&host, port).await {
|
||||
Ok(mut stream) => {
|
||||
drop(session);
|
||||
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
|
||||
}
|
||||
Err(e) => tracing::warn!("LocalForward: cannot open a channel to {host}:{port}: {e}"),
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// A `RemoteForward` connection: accepted once `host:port` here answers, then copied both ways.
|
||||
async fn remote_forward(channel: russh::Channel<Msg>, reply: client::ChannelOpenHandle, host: String, port: u16) {
|
||||
match tokio::net::TcpStream::connect((host.as_str(), port)).await {
|
||||
Ok(mut socket) => {
|
||||
reply.accept().await;
|
||||
let mut stream = channel.into_stream();
|
||||
let _ = tokio::io::copy_bidirectional(&mut socket, &mut stream).await;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("RemoteForward: cannot connect to {host}:{port}: {e}");
|
||||
reply.reject(russh::ChannelOpenFailure::ConnectFailed).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- connection ----------------------------------------------------------------
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -418,6 +507,8 @@ pub struct Client {
|
||||
known_hosts: PathBuf,
|
||||
host_key_policy: HostKeyPolicy,
|
||||
issue: Arc<Mutex<Option<HostKeyIssue>>>,
|
||||
/// The `RemoteForward`s whose connections this client accepts.
|
||||
remote_forwards: Vec<PortForward>,
|
||||
}
|
||||
|
||||
impl client::Handler for Client {
|
||||
@@ -442,6 +533,26 @@ impl client::Handler for Client {
|
||||
*self.issue.lock() = Some(issue);
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
async fn server_channel_open_forwarded_tcpip(
|
||||
&mut self,
|
||||
channel: russh::Channel<Msg>,
|
||||
_connected_address: &str,
|
||||
connected_port: u32,
|
||||
_originator_address: &str,
|
||||
_originator_port: u32,
|
||||
reply: client::ChannelOpenHandle,
|
||||
_session: &mut client::Session,
|
||||
) -> Result<(), Self::Error> {
|
||||
// Only a port this client asked the server to forward is accepted.
|
||||
match self.remote_forwards.iter().find(|f| u32::from(f.port) == connected_port) {
|
||||
Some(f) => {
|
||||
tokio::spawn(remote_forward(channel, reply, f.host.clone(), f.host_port));
|
||||
}
|
||||
None => reply.reject(russh::ChannelOpenFailure::AdministrativelyProhibited).await,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Client {
|
||||
@@ -600,6 +711,7 @@ where
|
||||
known_hosts: effective_known_hosts,
|
||||
host_key_policy: hop.host_key_policy,
|
||||
issue: issue.clone(),
|
||||
remote_forwards: hop.forwards.iter().filter(|f| f.direction == ForwardDirection::Remote).cloned().collect(),
|
||||
};
|
||||
let result = match stream {
|
||||
None => client::connect(config, (hop.host.as_str(), hop.port), handler).await,
|
||||
|
||||
@@ -54,6 +54,63 @@ pub(crate) struct Hop {
|
||||
pub host_key_policy: HostKeyPolicy,
|
||||
pub known_hosts: Option<PathBuf>,
|
||||
pub agent: Agent,
|
||||
/// `LocalForward` / `RemoteForward` of the config (the target's; jump hosts forward nothing).
|
||||
pub forwards: Vec<PortForward>,
|
||||
}
|
||||
|
||||
/// A `LocalForward` or `RemoteForward` of `~/.ssh/config`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PortForward {
|
||||
pub direction: ForwardDirection,
|
||||
/// Address the listening side binds: empty for every address, `localhost` by default.
|
||||
pub bind: String,
|
||||
pub port: u16,
|
||||
/// Where each connection goes, as the other side sees it.
|
||||
pub host: String,
|
||||
pub host_port: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ForwardDirection {
|
||||
/// `LocalForward`: this machine listens, connections go to `host:host_port` from the SSH host.
|
||||
Local,
|
||||
/// `RemoteForward`: the SSH host listens, connections go to `host:host_port` from this machine.
|
||||
Remote,
|
||||
}
|
||||
|
||||
/// `[bind_address:]port host:hostport` (or the one-argument `-L` / `-R` form with colons); IPv6
|
||||
/// addresses in brackets. `None` for what isn't a TCP forward: a Unix socket, or `RemoteForward`'s
|
||||
/// dynamic (SOCKS) form.
|
||||
pub(crate) fn parse_forward(direction: ForwardDirection, value: &str) -> Option<PortForward> {
|
||||
let spec = split_args(value).join(":");
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
let mut cur = String::new();
|
||||
let mut bracket = false;
|
||||
for ch in spec.chars() {
|
||||
match ch {
|
||||
'[' if cur.is_empty() => bracket = true,
|
||||
']' if bracket => bracket = false,
|
||||
':' if !bracket => parts.push(std::mem::take(&mut cur)),
|
||||
'/' => return None,
|
||||
_ => cur.push(ch),
|
||||
}
|
||||
}
|
||||
parts.push(cur);
|
||||
let (bind, port, host, host_port) = match parts.as_slice() {
|
||||
[port, host, host_port] => (None, port, host, host_port),
|
||||
[bind, port, host, host_port] => (Some(bind.as_str()), port, host, host_port),
|
||||
_ => return None,
|
||||
};
|
||||
let bind = match bind {
|
||||
None => "localhost".to_owned(),
|
||||
Some("*") | Some("") => String::new(),
|
||||
Some(b) => b.to_owned(),
|
||||
};
|
||||
let (port, host_port) = (port.parse().ok()?, host_port.parse().ok()?);
|
||||
if host.is_empty() || host_port == 0 {
|
||||
return None;
|
||||
}
|
||||
Some(PortForward { direction, bind, port, host: host.clone(), host_port })
|
||||
}
|
||||
|
||||
/// Where the SSH agent of a hop listens (`IdentityAgent`).
|
||||
@@ -158,6 +215,8 @@ struct RawConfig {
|
||||
host_key_policy: Option<HostKeyPolicy>,
|
||||
user_known_hosts_file: Option<String>,
|
||||
identity_agent: Option<String>,
|
||||
forwards: Vec<PortForward>,
|
||||
clear_forwardings: bool,
|
||||
}
|
||||
|
||||
fn strip_quotes(s: &str) -> &str {
|
||||
@@ -516,6 +575,23 @@ fn parse_config_file(
|
||||
out.user_known_hosts_file = Some(first);
|
||||
}
|
||||
}
|
||||
"localforward" | "remoteforward" => {
|
||||
let direction = if key.eq_ignore_ascii_case("localforward") {
|
||||
ForwardDirection::Local
|
||||
} else {
|
||||
ForwardDirection::Remote
|
||||
};
|
||||
match parse_forward(direction, value) {
|
||||
Some(f) if !out.forwards.contains(&f) => out.forwards.push(f),
|
||||
Some(_) => {}
|
||||
None => tracing::debug!("ssh config: {key} {value} is not a TCP port forward; skipped"),
|
||||
}
|
||||
}
|
||||
"clearallforwardings" => {
|
||||
if matches!(strip_quotes(value).to_ascii_lowercase().as_str(), "yes" | "true") {
|
||||
out.clear_forwardings = true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -559,7 +635,8 @@ fn config_hop(
|
||||
if null_known_hosts { HostKeyPolicy::Off } else { raw.host_key_policy.unwrap_or(HostKeyPolicy::Ask) };
|
||||
let agent =
|
||||
identity_agent(raw.identity_agent.as_deref(), |p| expand(&expand_tokens(p, alias, &host, port, &user, &local)));
|
||||
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent };
|
||||
let forwards = if raw.clear_forwardings { Vec::new() } else { raw.forwards };
|
||||
let hop = Hop { host, port, user, identity_files, proxy_command, host_key_policy, known_hosts, agent, forwards };
|
||||
(hop, proxy_jump)
|
||||
}
|
||||
|
||||
@@ -574,7 +651,7 @@ fn jump_hop(config: Option<&Path>, spec: &str) -> Hop {
|
||||
_ => (rest, None),
|
||||
};
|
||||
let (hop, _) = config_hop(config, host, port, user);
|
||||
hop
|
||||
Hop { forwards: Vec::new(), ..hop }
|
||||
}
|
||||
|
||||
/// The SSH hosts to go through, the target last.
|
||||
@@ -597,6 +674,7 @@ pub(crate) fn resolve_hops(target: &SshTarget, config: Option<&Path>) -> IdeResu
|
||||
host_key_policy: HostKeyPolicy::Ask,
|
||||
known_hosts: None,
|
||||
agent: Agent::Default,
|
||||
forwards: Vec::new(),
|
||||
},
|
||||
None,
|
||||
)
|
||||
@@ -636,6 +714,40 @@ pub fn openssh_args(target: &SshTarget) -> Vec<String> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_port_forwards_like_openssh() {
|
||||
let f = |d, v: &str| parse_forward(d, v).map(|f| (f.bind, f.port, f.host, f.host_port));
|
||||
let remote = ForwardDirection::Remote;
|
||||
assert_eq!(f(remote, "9222 127.0.0.1:9222"), Some(("localhost".into(), 9222, "127.0.0.1".into(), 9222)));
|
||||
assert_eq!(f(remote, "0.0.0.0:8080 web:80"), Some(("0.0.0.0".into(), 8080, "web".into(), 80)));
|
||||
assert_eq!(f(remote, "*:8080 web:80"), Some((String::new(), 8080, "web".into(), 80)));
|
||||
assert_eq!(f(remote, "[::1]:8080 [::1]:80"), Some(("::1".into(), 8080, "::1".into(), 80)));
|
||||
assert_eq!(f(ForwardDirection::Local, "5432:db:5432"), Some(("localhost".into(), 5432, "db".into(), 5432)));
|
||||
// Dynamic (SOCKS) and Unix socket forwards aren't TCP port forwards.
|
||||
assert_eq!(f(remote, "1080"), None);
|
||||
assert_eq!(f(remote, "/tmp/a.sock /tmp/b.sock"), None);
|
||||
assert_eq!(f(remote, "8080 web:http"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn config_forwards_belong_to_the_target_and_clear_all_forwardings_drops_them() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let config = dir.path().join("config");
|
||||
std::fs::write(
|
||||
&config,
|
||||
"Host box\n RemoteForward 9222 127.0.0.1:9222\n LocalForward 5432 db:5432\n ProxyJump gate\n\
|
||||
Host gate\n LocalForward 1 a:1\nHost quiet\n RemoteForward 9222 127.0.0.1:9222\n ClearAllForwardings yes\n",
|
||||
)
|
||||
.unwrap();
|
||||
let target = |host: &str| SshTarget { host: host.into(), auth: SshAuth::OpenSsh, ..Default::default() };
|
||||
let hops = resolve_hops(&target("box"), Some(&config)).unwrap();
|
||||
assert_eq!(hops.len(), 2);
|
||||
assert!(hops[0].forwards.is_empty(), "jump hosts forward nothing");
|
||||
let dirs: Vec<_> = hops[1].forwards.iter().map(|f| (f.direction, f.port)).collect();
|
||||
assert_eq!(dirs, [(ForwardDirection::Remote, 9222), (ForwardDirection::Local, 5432)]);
|
||||
assert!(resolve_hops(&target("quiet"), Some(&config)).unwrap()[0].forwards.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_aliases_and_proxy_jumps_from_ssh_config() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -98,6 +98,32 @@ impl server::Handler for Sshd {
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `RemoteForward`: listens on 127.0.0.1:`port` and forwards each connection back to the client.
|
||||
async fn tcpip_forward(
|
||||
&mut self,
|
||||
address: &str,
|
||||
port: &mut u32,
|
||||
session: &mut ServerSession,
|
||||
) -> Result<bool, Self::Error> {
|
||||
let Ok(listener) = TcpListener::bind(("127.0.0.1", *port as u16)).await else { return Ok(false) };
|
||||
let (handle, address, port) = (session.handle(), address.to_owned(), *port);
|
||||
tokio::spawn(async move {
|
||||
while let Ok((mut socket, peer)) = listener.accept().await {
|
||||
let Ok(channel) = handle
|
||||
.channel_open_forwarded_tcpip(address.clone(), port, "127.0.0.1", u32::from(peer.port()))
|
||||
.await
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
let mut stream = channel.into_stream();
|
||||
let _ = tokio::io::copy_bidirectional(&mut stream, &mut socket).await;
|
||||
});
|
||||
}
|
||||
});
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Echo server standing in for a remote service.
|
||||
@@ -443,3 +469,50 @@ async fn accept_new_records_an_unknown_key_and_still_refuses_a_changed_one() {
|
||||
let msg = denied(env.connect(&target, None).await);
|
||||
assert!(msg.contains("has changed"), "{msg}");
|
||||
}
|
||||
|
||||
/// A free local port (bound and released).
|
||||
fn free_port() -> u16 {
|
||||
std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
|
||||
}
|
||||
|
||||
async fn echoes(port: u16) {
|
||||
let mut s = TcpStream::connect(("127.0.0.1", port)).await.expect("forwarded port listens");
|
||||
s.write_all(b"ping").await.unwrap();
|
||||
let mut buf = [0u8; 4];
|
||||
s.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"ping");
|
||||
}
|
||||
|
||||
/// `RemoteForward` and `LocalForward` of `~/.ssh/config` are forwarded while the session lives (#6031).
|
||||
#[tokio::test]
|
||||
async fn config_port_forwards_follow_the_session() {
|
||||
let mut env = env().await;
|
||||
let (remote, local) = (free_port(), free_port());
|
||||
let config = env._tmp.path().join("ssh_config");
|
||||
std::fs::write(
|
||||
&config,
|
||||
format!(
|
||||
"Host box\n\tHostName 127.0.0.1\n\tStrictHostKeyChecking=no\n\tUserKnownHostsFile=/dev/null\n\
|
||||
\tRemoteForward {remote} 127.0.0.1:{echo}\n\tLocalForward 127.0.0.1:{local} localhost:{echo}\n\
|
||||
\tRemoteForward /tmp/remote.sock /tmp/local.sock\n",
|
||||
echo = env.echo_port
|
||||
),
|
||||
)
|
||||
.unwrap();
|
||||
env.files.config = Some(config);
|
||||
let target = SshTarget {
|
||||
host: "box".into(),
|
||||
port: Some(env.ssh_port),
|
||||
user: "coder".into(),
|
||||
auth: SshAuth::OpenSsh,
|
||||
..Default::default()
|
||||
};
|
||||
let session = Arc::new(env.connect(&target, None).await.expect("connects"));
|
||||
session.start_forwards().await;
|
||||
// The SSH host's port reaches the echo server here; the local port reaches it from the SSH host.
|
||||
echoes(remote).await;
|
||||
echoes(local).await;
|
||||
drop(session);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
assert!(TcpStream::connect(("127.0.0.1", local)).await.is_err(), "a closed session stops its LocalForward");
|
||||
}
|
||||
@@ -183,15 +183,10 @@ pub fn arguments(
|
||||
return vec!["format".into(), path];
|
||||
}
|
||||
if tool == "prettier" {
|
||||
let parser = if config.parser == "markdown" && file.extension().is_some_and(|s| s == "mdx") {
|
||||
"mdx"
|
||||
} else {
|
||||
&config.parser
|
||||
};
|
||||
args.extend(
|
||||
[
|
||||
"--parser",
|
||||
parser,
|
||||
config.parser.as_str(),
|
||||
"--config-precedence",
|
||||
"file-override",
|
||||
"--tab-width",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! without network.
|
||||
|
||||
use crate::platform::{Arch, Os, Platform};
|
||||
use crate::process::{Emit, Http};
|
||||
use crate::process::Emit;
|
||||
use crate::sources::Download;
|
||||
use crate::{InstallEvent, InstallGuard, Tools, archive, clear_quarantine, fetch_verified};
|
||||
use ide_core::error::ErrorKind;
|
||||
@@ -240,10 +240,6 @@ fn unpacked_root(pkg: &Path, home: &Path) -> PathBuf {
|
||||
}
|
||||
|
||||
impl Tools {
|
||||
fn http(&self) -> IdeResult<Http> {
|
||||
Http::new(&self.system_path)
|
||||
}
|
||||
|
||||
/// Java versions `vendor` publishes.
|
||||
pub fn jdk_releases(&self, vendor: &str, cancel: &CancellationToken) -> IdeResult<JdkReleases> {
|
||||
vendor_or_err(vendor)?;
|
||||
|
||||
@@ -557,6 +557,10 @@ impl Tools {
|
||||
&self.root
|
||||
}
|
||||
|
||||
pub(crate) fn http(&self) -> IdeResult<Http> {
|
||||
Ok(Http::new(&self.system_path)?.with_gh_from(&self.child_path))
|
||||
}
|
||||
|
||||
/// [`Tools::command`] in the project directory.
|
||||
fn command_in_project(&self, program: impl AsRef<std::ffi::OsStr>) -> Command {
|
||||
let mut cmd = self.command(program);
|
||||
@@ -902,7 +906,7 @@ impl Tools {
|
||||
_ => (ToolStatus::Missing, None, None),
|
||||
}
|
||||
}
|
||||
_ => match self.which(main) {
|
||||
_ => match self.which(main).or_else(|| self.found.get(main).cloned()) {
|
||||
Some(path) => {
|
||||
let version = self.query_version(spec, &path);
|
||||
(ToolStatus::OnPath, Some(path), version)
|
||||
@@ -1078,6 +1082,7 @@ impl Tools {
|
||||
},
|
||||
&specs,
|
||||
pnpm,
|
||||
!self.downloads.configured_registries_only,
|
||||
cancel,
|
||||
emit,
|
||||
)
|
||||
@@ -1249,7 +1254,8 @@ impl Tools {
|
||||
dotnet::SDK_DOWNLOAD_URL
|
||||
)));
|
||||
};
|
||||
let pick = Http::new(&self.system_path)
|
||||
let pick = self
|
||||
.http()
|
||||
.and_then(|http| dotnet::pick_tool_version(package, sdk.major, |url| http.get_text(url, cancel)));
|
||||
match pick {
|
||||
Ok(dotnet::ToolPick::Latest) => Ok(None),
|
||||
@@ -1463,6 +1469,12 @@ impl Tools {
|
||||
sources::openvsx_pick(&json, assets, self.platform)
|
||||
}
|
||||
ReleaseSource::MavenCentral { group, artifact } => {
|
||||
if self.downloads.configured_registries_only {
|
||||
return Err(IdeError::unavailable(format!(
|
||||
"{group}:{artifact} is downloaded from Maven Central, and Settings › Tools › Download Mirrors \
|
||||
allows only the configured package registries"
|
||||
)));
|
||||
}
|
||||
let xml = http.get_text(&sources::maven_metadata_url(group, artifact), cancel)?;
|
||||
sources::maven_pick(group, artifact, &xml)
|
||||
}
|
||||
@@ -1535,7 +1547,7 @@ impl Tools {
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<()> {
|
||||
let http = Http::new(&self.system_path)?;
|
||||
let http = self.http()?;
|
||||
let message = match source {
|
||||
ReleaseSource::GitHubTag { tag, .. } => format!("Resolving release {tag}…"),
|
||||
_ => "Resolving the latest release…".into(),
|
||||
@@ -1676,7 +1688,7 @@ impl Tools {
|
||||
fn latest_version(&self, method: Method, cancel: &CancellationToken) -> IdeResult<Option<String>> {
|
||||
match method {
|
||||
Method::Release { source, assets, .. } => {
|
||||
let http = Http::new(&self.system_path)?;
|
||||
let http = self.http()?;
|
||||
Ok(Some(self.resolve_release(&http, source, assets, cancel)?.version))
|
||||
}
|
||||
Method::Npm { packages } => {
|
||||
@@ -1690,7 +1702,7 @@ impl Tools {
|
||||
// on a slow registry takes several seconds per package, more when run side by side.
|
||||
let out = match view(&[]) {
|
||||
Some((true, out)) => Some(out),
|
||||
Some((false, out)) if is_npm_registry_miss(&out) => {
|
||||
Some((false, out)) if !self.downloads.configured_registries_only && is_npm_registry_miss(&out) => {
|
||||
let extra = npm_public_registry_args([packages[0]], pnpm);
|
||||
view(&extra).and_then(|(ok, retry)| ok.then_some(retry))
|
||||
}
|
||||
|
||||
@@ -112,7 +112,7 @@ mod tests {
|
||||
const ASSET: &str = "https://github.com/LuaLS/lua-language-server/releases/download/3.13.5/x.zip";
|
||||
|
||||
fn settings(mirror: &str) -> ToolDownloadSettings {
|
||||
ToolDownloadSettings { github_mirror: mirror.into() }
|
||||
ToolDownloadSettings { github_mirror: mirror.into(), ..Default::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -110,13 +110,15 @@ pub fn run_streamed_picking(
|
||||
}
|
||||
|
||||
/// 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
|
||||
/// error if the public registry is unreachable.
|
||||
/// corporate mirrors, proxies, and CAs), and with `public_fallback` retries once against
|
||||
/// [`PUBLIC_NPM_REGISTRY`] when the configured registry misses the package/version or rejects
|
||||
/// auth. Preserves the primary error if the public registry is unreachable. Without
|
||||
/// `public_fallback` (Settings › Tools › Download Mirrors) the configured registry's error stands.
|
||||
pub fn run_npm_with_public_fallback(
|
||||
mut build: impl FnMut(&[String]) -> Command,
|
||||
specs: &[String],
|
||||
pnpm: bool,
|
||||
public_fallback: bool,
|
||||
cancel: &CancellationToken,
|
||||
emit: Emit,
|
||||
) -> IdeResult<String> {
|
||||
@@ -127,7 +129,7 @@ pub fn run_npm_with_public_fallback(
|
||||
return Ok(output);
|
||||
}
|
||||
let err = failed_command(&label, &output, &status);
|
||||
if cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
if !public_fallback || cancel.is_cancelled() || !is_npm_registry_miss(&output) {
|
||||
return Err(err);
|
||||
}
|
||||
emit(InstallEvent::Line {
|
||||
@@ -439,6 +441,17 @@ impl Http {
|
||||
self
|
||||
}
|
||||
|
||||
/// Looks up `gh` on `search_path` (e.g. a path that includes IDE-managed tools).
|
||||
pub(crate) fn with_gh_from(mut self, search_path: &std::ffi::OsStr) -> Self {
|
||||
self.gh = which::which_in("gh", Some(search_path), ".").ok();
|
||||
self
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
pub(crate) fn gh_path(&self) -> Option<&Path> {
|
||||
self.gh.as_deref()
|
||||
}
|
||||
|
||||
/// Skips `GITHUB_TOKEN` / `GH_TOKEN` / `gh auth token` (e.g. retrying a public GitHub endpoint after HTTP 401).
|
||||
pub fn without_github_auth(mut self) -> Self {
|
||||
self.gh = None;
|
||||
|
||||
@@ -181,6 +181,28 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
needs: NODE,
|
||||
homepage: "https://github.com/devcontainers/cli",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "gh",
|
||||
display: "GitHub CLI",
|
||||
kind: Cli,
|
||||
commands: &["gh"],
|
||||
method: Method::Release {
|
||||
source: ReleaseSource::GitHub { repo: "cli/cli" },
|
||||
assets: &[
|
||||
rule(Mac, Arm64, "gh_*_macOS_arm64.zip"),
|
||||
rule(Mac, X64, "gh_*_macOS_amd64.zip"),
|
||||
rule(Linux, Arm64, "gh_*_linux_arm64.tar.gz"),
|
||||
rule(Linux, X64, "gh_*_linux_amd64.tar.gz"),
|
||||
rule(Windows, Arm64, "gh_*_windows_arm64.zip"),
|
||||
rule(Windows, X64, "gh_*_windows_amd64.zip"),
|
||||
],
|
||||
locate: &["gh"],
|
||||
},
|
||||
fallback: None,
|
||||
version: ver("gh"),
|
||||
needs: &[],
|
||||
homepage: "https://cli.github.com",
|
||||
},
|
||||
ToolSpec {
|
||||
name: "oxfmt",
|
||||
display: "oxfmt",
|
||||
@@ -424,6 +446,17 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/hrsh7th/vscode-langservers-extracted",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "some-sass-language-server",
|
||||
display: "Some Sass Language Server",
|
||||
kind: LanguageServer,
|
||||
commands: &["some-sass-language-server"],
|
||||
method: Method::Npm { packages: &["some-sass-language-server"] },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/wkillerud/some-sass",
|
||||
needs: &[],
|
||||
},
|
||||
ToolSpec {
|
||||
name: "vscode-html-language-server",
|
||||
display: "HTML Language Server",
|
||||
@@ -457,6 +490,17 @@ pub static TOOLS: &[ToolSpec] = &[
|
||||
homepage: "https://github.com/withastro/astro/tree/main/packages/language-tools",
|
||||
needs: NODE,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "mdx-language-server",
|
||||
display: "MDX Language Server",
|
||||
kind: LanguageServer,
|
||||
commands: &["mdx-language-server"],
|
||||
method: Method::Npm { packages: &["@mdx-js/language-server", TYPESCRIPT] },
|
||||
fallback: None,
|
||||
version: V,
|
||||
homepage: "https://github.com/mdx-js/mdx-analyzer",
|
||||
needs: NODE,
|
||||
},
|
||||
ToolSpec {
|
||||
name: "svelte-language-server",
|
||||
display: "Svelte Language Server",
|
||||
@@ -1483,4 +1527,56 @@ mod tests {
|
||||
let win_arm = Platform { os: Windows, arch: Arm64 };
|
||||
assert_eq!(select_asset(&names, rules, win_arm), Some("kotlin-server-263.7084.0-aarch64.win.zip"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gh_release_picks_portable_archive_for_every_supported_platform() {
|
||||
use crate::platform::{Platform, select_asset};
|
||||
let names = [
|
||||
"gh_2.106.0_checksums.txt",
|
||||
"gh_2.106.0_linux_386.deb",
|
||||
"gh_2.106.0_linux_386.tar.gz",
|
||||
"gh_2.106.0_linux_amd64.deb",
|
||||
"gh_2.106.0_linux_amd64.rpm",
|
||||
"gh_2.106.0_linux_amd64.tar.gz",
|
||||
"gh_2.106.0_linux_arm64.deb",
|
||||
"gh_2.106.0_linux_arm64.tar.gz",
|
||||
"gh_2.106.0_linux_armv6.tar.gz",
|
||||
"gh_2.106.0_macOS_amd64.zip",
|
||||
"gh_2.106.0_macOS_arm64.zip",
|
||||
"gh_2.106.0_macOS_universal.pkg",
|
||||
"gh_2.106.0_windows_386.zip",
|
||||
"gh_2.106.0_windows_amd64.msi",
|
||||
"gh_2.106.0_windows_amd64.zip",
|
||||
"gh_2.106.0_windows_arm64.msi",
|
||||
"gh_2.106.0_windows_arm64.zip",
|
||||
];
|
||||
let spec = find("gh").unwrap();
|
||||
assert_eq!(spec.kind, Cli);
|
||||
let rules = spec.asset_rules();
|
||||
for (os, arch, expected) in [
|
||||
(Mac, Arm64, "gh_2.106.0_macOS_arm64.zip"),
|
||||
(Mac, X64, "gh_2.106.0_macOS_amd64.zip"),
|
||||
(Linux, Arm64, "gh_2.106.0_linux_arm64.tar.gz"),
|
||||
(Linux, X64, "gh_2.106.0_linux_amd64.tar.gz"),
|
||||
(Windows, Arm64, "gh_2.106.0_windows_arm64.zip"),
|
||||
(Windows, X64, "gh_2.106.0_windows_amd64.zip"),
|
||||
] {
|
||||
assert_eq!(select_asset(&names, rules, Platform { os, arch }), Some(expected));
|
||||
}
|
||||
|
||||
let Method::Release { locate, .. } = &spec.method else { unreachable!() };
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let unix_bin = tmp.path().join("gh_2.106.0_macOS_arm64/bin/gh");
|
||||
std::fs::create_dir_all(unix_bin.parent().unwrap()).unwrap();
|
||||
std::fs::write(&unix_bin, "").unwrap();
|
||||
let unix_names: Vec<String> = locate.iter().map(|n| (*n).to_owned()).collect();
|
||||
assert_eq!(crate::archive::locate(tmp.path(), &unix_names), Some(unix_bin));
|
||||
|
||||
let win_dir = tempfile::tempdir().unwrap();
|
||||
let win_bin = win_dir.path().join("bin/gh.exe");
|
||||
std::fs::create_dir_all(win_bin.parent().unwrap()).unwrap();
|
||||
std::fs::write(&win_bin, "").unwrap();
|
||||
let win_names: Vec<String> = locate.iter().map(|n| format!("{n}.exe")).collect();
|
||||
assert_eq!(crate::archive::locate(win_dir.path(), &win_names), Some(win_bin));
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,11 @@ fn pick_release(
|
||||
let checksum_url = assets
|
||||
.iter()
|
||||
.find(|c| c.name == format!("{name}.sha256") || c.name == format!("{name}.sha256sum"))
|
||||
.or_else(|| {
|
||||
assets
|
||||
.iter()
|
||||
.find(|c| c.name.eq_ignore_ascii_case("checksums.txt") || c.name.ends_with("_checksums.txt"))
|
||||
})
|
||||
.map(|c| c.url.clone());
|
||||
return Ok(Download {
|
||||
version,
|
||||
@@ -622,6 +627,28 @@ mod tests {
|
||||
let sums = format!("{} other.zip\n{} *wanted.zip\n", "b".repeat(64), "C".repeat(64));
|
||||
assert_eq!(parse_checksum(&sums, "wanted.zip"), Some("c".repeat(64)));
|
||||
assert_eq!(parse_checksum(&sums, "missing.zip"), None);
|
||||
|
||||
let gh = serde_json::json!({
|
||||
"tag_name": "v2.106.0",
|
||||
"assets": [
|
||||
{
|
||||
"name": "gh_2.106.0_macOS_arm64.zip",
|
||||
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_macOS_arm64.zip"
|
||||
},
|
||||
{
|
||||
"name": "gh_2.106.0_checksums.txt",
|
||||
"browser_download_url": "https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt"
|
||||
}
|
||||
]
|
||||
})
|
||||
.to_string();
|
||||
let dl = github_pick(&gh, find("gh").unwrap().asset_rules(), MAC_ARM).unwrap();
|
||||
assert_eq!(dl.version, "2.106.0");
|
||||
assert_eq!(dl.name, "gh_2.106.0_macOS_arm64.zip");
|
||||
assert_eq!(
|
||||
dl.checksum_url.as_deref(),
|
||||
Some("https://github.com/cli/cli/releases/download/v2.106.0/gh_2.106.0_checksums.txt")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -181,6 +181,9 @@ fn everything_missing_on_an_empty_system() {
|
||||
assert!(find(&list, "solargraph").unavailable_reason.as_deref().unwrap().contains("Ruby"));
|
||||
// Shared npm package: each server is its own row.
|
||||
assert_eq!(find(&list, "vscode-css-language-server").install_method.as_deref(), Some("npm"));
|
||||
let sass = find(&list, "some-sass-language-server");
|
||||
assert_eq!(sass.install_method.as_deref(), Some("npm"));
|
||||
assert_eq!(sass.languages, ["Sass"]);
|
||||
assert!(find(&list, "delve").kind == ToolKind::Debugger);
|
||||
}
|
||||
|
||||
@@ -603,6 +606,34 @@ esac"#,
|
||||
assert!(!err.message.contains("ECONNRESET"), "{}", err.message);
|
||||
}
|
||||
|
||||
/// Settings › Tools › Download Mirrors › Use only the configured package registries: a registry
|
||||
/// that refuses a package (a firewall's 403) is the answer.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn configured_registries_only_never_reach_public_registries() {
|
||||
let env = Env::new();
|
||||
let log = env.root.parent().unwrap().join("npm-only.txt");
|
||||
env.script(&env.sys, "node", "exit 0");
|
||||
env.script(
|
||||
&env.sys,
|
||||
"npm",
|
||||
&format!(
|
||||
r#"echo "$@" >> '{log}'
|
||||
echo "npm error code E403" >&2
|
||||
echo "npm error 403 Forbidden - GET https://nexus.example/yaml-language-server - quarantined" >&2
|
||||
exit 1"#,
|
||||
log = log.display()
|
||||
),
|
||||
);
|
||||
let only = ToolDownloadSettings { configured_registries_only: true, ..Default::default() };
|
||||
let tools = env.tools().with_downloads(only);
|
||||
let err = tools.install("yaml-language-server", &langs(), &CancellationToken::new(), &|_| {}).unwrap_err();
|
||||
assert!(err.message.contains("quarantined"), "{}", err.message);
|
||||
let calls = fs::read_to_string(&log).unwrap();
|
||||
assert_eq!(calls.lines().count(), 1, "{calls}");
|
||||
assert!(!calls.contains("registry.npmjs.org"), "{calls}");
|
||||
}
|
||||
|
||||
/// Servers that load TypeScript as a library get one with its JS API: `@latest`
|
||||
/// is TypeScript 7 (native, no `ts.server`), which crashed vue-language-server (#25).
|
||||
/// Uninstalling one keeps the TypeScript another installed server still uses.
|
||||
@@ -624,6 +655,7 @@ for a in "$@"; do case "$a" in
|
||||
typescript-language-server@latest) n=typescript-language-server;;
|
||||
@vue/language-server@latest) n=vue-language-server; d=@vue/language-server;;
|
||||
@astrojs/language-server@latest) n=astro-ls; d=@astrojs/language-server;;
|
||||
@mdx-js/language-server@latest) n=mdx-language-server; d=@mdx-js/language-server;;
|
||||
*) continue;;
|
||||
esac
|
||||
d="${{d:-$n}}"; /bin/mkdir -p "$prefix/node_modules/$d"
|
||||
@@ -634,7 +666,7 @@ done"#,
|
||||
),
|
||||
);
|
||||
let tools = env.tools();
|
||||
for name in ["vue-language-server", "typescript-language-server", "astro-ls"] {
|
||||
for name in ["vue-language-server", "typescript-language-server", "astro-ls", "mdx-language-server"] {
|
||||
assert_eq!(
|
||||
tools.install(name, &langs(), &CancellationToken::new(), &|_| {}).unwrap().status,
|
||||
ToolStatus::Installed
|
||||
@@ -646,6 +678,7 @@ done"#,
|
||||
}
|
||||
assert!(installs.contains("@vue/language-server@latest"), "{installs}");
|
||||
assert!(installs.contains("@astrojs/language-server@latest"), "{installs}");
|
||||
assert!(installs.contains("@mdx-js/language-server@latest"), "{installs}");
|
||||
|
||||
fs::write(&log, "").unwrap();
|
||||
tools.uninstall("vue-language-server", &langs()).unwrap();
|
||||
@@ -1344,7 +1377,10 @@ esac"#,
|
||||
),
|
||||
);
|
||||
// The first mirror is down: the next one is tried before the official host.
|
||||
let downloads = ToolDownloadSettings { github_mirror: "https://down.mirror.test/, https://mirror.test/".into() };
|
||||
let downloads = ToolDownloadSettings {
|
||||
github_mirror: "https://down.mirror.test/, https://mirror.test/".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let emit = |_: InstallEvent| {};
|
||||
env.tools()
|
||||
.with_downloads(downloads)
|
||||
@@ -1397,3 +1433,27 @@ fn a_mirror_never_installs_what_it_alone_vouches_for() {
|
||||
let err = check_sha256(&archive, &dl(Some(&digest)), Some(&"0".repeat(64)), true, &emit).unwrap_err();
|
||||
assert!(err.message.contains("checksum mismatch"), "{}", err.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn managed_gh_is_detected_on_tools_bin_dirs_and_available_to_http() {
|
||||
let env = Env::new();
|
||||
env.script(&env.sys, "curl", "exit 0");
|
||||
let app_data = env.root.parent().unwrap();
|
||||
let gh_bin = env.root.join("gh/bin");
|
||||
assert!(tools_bin_dirs(app_data).contains(&gh_bin));
|
||||
|
||||
let missing = env.tools().info("gh", &[]).unwrap();
|
||||
assert_eq!(missing.kind, ToolKind::Cli);
|
||||
assert_eq!(missing.status, ToolStatus::Missing);
|
||||
assert!(missing.can_install);
|
||||
|
||||
env.script(&gh_bin, "gh", "echo 'gh version 2.106.0 (2026-11-20)'");
|
||||
let installed = env.tools().info("gh", &[]).unwrap();
|
||||
assert_eq!(installed.status, ToolStatus::Installed);
|
||||
assert_eq!(installed.version.as_deref(), Some("2.106.0"));
|
||||
assert!(installed.can_uninstall);
|
||||
|
||||
let http = env.tools().http().unwrap();
|
||||
assert_eq!(http.gh_path(), Some(gh_bin.join("gh").as_path()));
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::editorconfig::{EditorConfig, EditorConfigProps};
|
||||
use crate::file_defaults::FileDefaults;
|
||||
use crate::file_defaults::{EncodingSource, FileDefaults};
|
||||
use ide_core::error::ErrorKind;
|
||||
use ide_core::{ChangeSet, DocId, IdeError, IdeEvent, IdeResult, LanguageId, SharedSink, TextEdit};
|
||||
use ide_text::{AppliedChange, ByteEdit, Document, LineEnding};
|
||||
@@ -168,12 +168,17 @@ struct DocState {
|
||||
can_reload_encoding: bool,
|
||||
/// The user picked `encoding`; reloads keep it instead of detecting again.
|
||||
encoding_chosen: bool,
|
||||
/// The user converted the text to `encoding`; it is theirs to keep once a save writes it.
|
||||
encoding_unsaved: bool,
|
||||
/// Disk state we last loaded or wrote; changes matching it are our own.
|
||||
disk_mtime: f64,
|
||||
disk_len: u64,
|
||||
/// The file changed on disk while this buffer had unsaved changes; autosave leaves it
|
||||
/// alone until the user saves explicitly or the buffer is reloaded.
|
||||
disk_conflict: bool,
|
||||
/// External changes seen while the buffer had unsaved changes (each `disk_conflict`), so an
|
||||
/// undo of a refactoring can tell a write by another program from the IDE's own saves.
|
||||
external_writes: u64,
|
||||
/// Text as of that disk state: an edit that returns to it (undo) leaves the document clean.
|
||||
/// `None` for large files (no second copy), virtual documents, and once a pending encoding,
|
||||
/// line-ending or BOM change makes the buffer differ from the file whatever the text.
|
||||
@@ -191,6 +196,35 @@ impl DocState {
|
||||
self.disk_conflict = false;
|
||||
self.clean_text = (!self.large).then(|| self.doc.clone());
|
||||
}
|
||||
|
||||
/// The bytes saving `doc` with this document's encoding, BOM and conversion would write.
|
||||
fn bytes_for_save(&self, doc: &Document) -> IdeResult<Vec<u8>> {
|
||||
let text = doc.text_for_save();
|
||||
Ok(if self.native_to_ascii {
|
||||
ide_vfs::encode_properties_ascii(&text).into_bytes()
|
||||
} else {
|
||||
ide_vfs::encode(&text, &self.encoding, self.has_bom)?
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the file changed on disk since the buffer last matched it. A moved stamp with the
|
||||
/// same bytes (touch, a tool rewriting the file unchanged) is no change and its stamp is adopted. Reads the file
|
||||
/// only when the mtime moved but the length did not; without a clean text to compare (large
|
||||
/// files, a pending encoding, line-ending or BOM change, a reported conflict) a moved stamp counts.
|
||||
fn changed_on_disk(&mut self, meta: &std::fs::Metadata) -> bool {
|
||||
let mtime = ide_vfs::mtime_ms(meta);
|
||||
if mtime == self.disk_mtime && meta.len() == self.disk_len {
|
||||
return false;
|
||||
}
|
||||
let same_bytes = meta.len() == self.disk_len
|
||||
&& self.clean_text.as_ref().is_some_and(|clean| {
|
||||
self.bytes_for_save(clean).is_ok_and(|bytes| std::fs::read(&self.path).is_ok_and(|disk| disk == bytes))
|
||||
});
|
||||
if same_bytes {
|
||||
self.disk_mtime = mtime;
|
||||
}
|
||||
!same_bytes
|
||||
}
|
||||
}
|
||||
|
||||
fn keys_for(path: &Path) -> Vec<PathBuf> {
|
||||
@@ -215,19 +249,25 @@ fn disk_len(path: &Path) -> u64 {
|
||||
std::fs::metadata(path).map(|m| m.len()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn editorconfig_label(editorconfig: Option<&EditorConfigProps>, detected: &str, ascii: bool) -> Option<&'static str> {
|
||||
let (charset, _) = editorconfig?.encoding()?;
|
||||
let compatible = encoding_rs::Encoding::for_label(detected.as_bytes()).is_some_and(|e| e.is_ascii_compatible());
|
||||
(ascii && compatible && !charset.starts_with("utf-16")).then_some(charset)
|
||||
}
|
||||
|
||||
fn apply_editorconfig_charset(loaded: &mut ide_vfs::LoadedText, editorconfig: Option<&EditorConfigProps>) {
|
||||
if loaded.binary {
|
||||
return;
|
||||
}
|
||||
if let Some(charset) = editorconfig_label(editorconfig, &loaded.encoding, !loaded.has_bom && loaded.text.is_ascii())
|
||||
{
|
||||
loaded.encoding = charset.to_owned();
|
||||
/// EditorConfig takes precedence over File Encodings for legacy text and ASCII labels.
|
||||
/// UTF-16 is detected, not assumed; invalid UTF-8 still uses the File Encodings fallback.
|
||||
fn configured_fallback<'a>(
|
||||
defaults: &'a FileDefaults,
|
||||
path: &Path,
|
||||
editorconfig: Option<&EditorConfigProps>,
|
||||
) -> Option<ide_vfs::Fallback<'a>> {
|
||||
let path = absolute(path);
|
||||
let charset = editorconfig.filter(|_| defaults.editorconfig).and_then(EditorConfigProps::encoding);
|
||||
let inherited = defaults.inherited_encoding_for(&path);
|
||||
let fallback = if inherited.source == EncodingSource::Folder && charset.is_some() {
|
||||
defaults.project_encoding_for(&path).fallback()
|
||||
} else {
|
||||
inherited.fallback()
|
||||
};
|
||||
match charset {
|
||||
Some(("utf-8", _)) => fallback.map(|f| ide_vfs::Fallback { ascii: false, ..f }),
|
||||
Some((encoding, _)) if !encoding.starts_with("utf-16") => Some(ide_vfs::Fallback { encoding, ascii: true }),
|
||||
_ => fallback,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -333,17 +373,21 @@ impl Documents {
|
||||
/// Closed-file readers use the same decoding as document opening.
|
||||
pub fn load_file(&self, path: &Path) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let defaults = self.file_defaults();
|
||||
Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())
|
||||
Ok(Self::load_with_defaults(path, &defaults, self.editorconfig_for(path, &defaults).as_ref())?.0)
|
||||
}
|
||||
|
||||
/// Encoding of `bytes`, a revision of `path`, with the same rules as opening the file.
|
||||
pub fn detect_encoding(&self, path: &Path, bytes: &[u8]) -> &'static encoding_rs::Encoding {
|
||||
let defaults = self.file_defaults();
|
||||
let detected = ide_vfs::detect_encoding(bytes, defaults.fallback_for(&absolute(path)));
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
editorconfig_label(editorconfig.as_ref(), detected.name(), bytes.is_ascii())
|
||||
.and_then(|label| encoding_rs::Encoding::for_label(label.as_bytes()))
|
||||
.unwrap_or(detected)
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
if configured.source == EncodingSource::File
|
||||
&& let Some(enc) = encoding_rs::Encoding::for_label(configured.label.as_bytes())
|
||||
&& !enc.decode_with_bom_removal(bytes).0.contains(char::REPLACEMENT_CHARACTER)
|
||||
{
|
||||
return enc;
|
||||
}
|
||||
ide_vfs::detect_encoding(bytes, configured_fallback(&defaults, path, editorconfig.as_ref()))
|
||||
}
|
||||
|
||||
fn editorconfig_for(&self, path: &Path, defaults: &FileDefaults) -> Option<EditorConfigProps> {
|
||||
@@ -353,11 +397,23 @@ impl Documents {
|
||||
self.editorconfig.resolve(&absolute(path))
|
||||
}
|
||||
|
||||
/// Fallback encoding for closed-file search; ASCII relabelling does not affect its text.
|
||||
pub fn configured_encoding_for(&self, path: &Path) -> Option<String> {
|
||||
let defaults = self.file_defaults();
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
if configured.source == EncodingSource::File {
|
||||
return Some(configured.label.to_owned());
|
||||
}
|
||||
configured_fallback(&defaults, path, editorconfig.as_ref()).map(|f| f.encoding.to_owned())
|
||||
}
|
||||
|
||||
/// Bounded closed-file snapshots use the same project defaults as open documents.
|
||||
pub fn load_file_bounded(&self, path: &Path, max_bytes: usize) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let defaults = self.file_defaults();
|
||||
let mut loaded = ide_vfs::load_text_bounded(path, defaults.fallback_for(&absolute(path)), max_bytes)?;
|
||||
apply_editorconfig_charset(&mut loaded, self.editorconfig_for(path, &defaults).as_ref());
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let mut loaded =
|
||||
ide_vfs::load_text_bounded(path, configured_fallback(&defaults, path, editorconfig.as_ref()), max_bytes)?;
|
||||
if !loaded.binary && defaults.native_to_ascii_for(path) {
|
||||
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
|
||||
}
|
||||
@@ -368,17 +424,30 @@ impl Documents {
|
||||
Self::load_as(path, encoding, self.native_to_ascii_for(path))
|
||||
}
|
||||
|
||||
/// Loads `path` as the settings say. `true`: decoded in the encoding chosen for this
|
||||
/// very file, as "Reload with Encoding" does, instead of detecting it.
|
||||
fn load_with_defaults(
|
||||
path: &Path,
|
||||
defaults: &FileDefaults,
|
||||
editorconfig: Option<&EditorConfigProps>,
|
||||
) -> IdeResult<ide_vfs::LoadedText> {
|
||||
let mut loaded = ide_vfs::load_text_with_fallback(path, defaults.fallback_for(&absolute(path)))?;
|
||||
apply_editorconfig_charset(&mut loaded, editorconfig);
|
||||
) -> IdeResult<(ide_vfs::LoadedText, bool)> {
|
||||
let path_abs = absolute(path);
|
||||
let configured = defaults.configured_encoding_for(&path_abs);
|
||||
if configured.source == EncodingSource::File {
|
||||
let loaded = Self::load_as(path, configured.label, defaults.native_to_ascii_for(path))?;
|
||||
// The bytes are not text in that encoding (the file changed outside the IDE):
|
||||
// open it as if nothing was chosen, rather than show and save broken characters.
|
||||
// A single-byte encoding decodes any bytes, so this only catches the others.
|
||||
if !loaded.text.contains(char::REPLACEMENT_CHARACTER) {
|
||||
return Ok((loaded, true));
|
||||
}
|
||||
}
|
||||
let fallback = configured_fallback(defaults, path, editorconfig);
|
||||
let mut loaded = ide_vfs::load_text_with_fallback(path, fallback)?;
|
||||
if !loaded.binary && defaults.native_to_ascii_for(path) {
|
||||
loaded.text = ide_vfs::decode_properties_escapes(&loaded.text);
|
||||
}
|
||||
Ok(loaded)
|
||||
Ok((loaded, false))
|
||||
}
|
||||
|
||||
pub fn file_defaults(&self) -> FileDefaults {
|
||||
@@ -460,7 +529,7 @@ impl Documents {
|
||||
}
|
||||
let defaults = self.file_defaults();
|
||||
let editorconfig = self.editorconfig_for(path, &defaults);
|
||||
let loaded = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
|
||||
let (loaded, encoding_chosen) = Self::load_with_defaults(path, &defaults, editorconfig.as_ref())?;
|
||||
let editorconfig = editorconfig.filter(|_| !loaded.binary);
|
||||
let language = (self.detect_language)(path, loaded.text.lines().next());
|
||||
let ui_mode = (self.detect_ui_mode)(path, &language);
|
||||
@@ -476,8 +545,14 @@ impl Documents {
|
||||
// An empty file has nothing to detect: Code Style / File Encodings defaults apply.
|
||||
if empty_file && !loaded.binary {
|
||||
doc.set_line_ending(defaults.line_ending);
|
||||
encoding = defaults.encoding.clone();
|
||||
has_bom = defaults.encoding == "utf-8" && defaults.utf8_bom;
|
||||
if !encoding_chosen {
|
||||
let configured = defaults.configured_encoding_for(&absolute(path));
|
||||
encoding = match configured.source {
|
||||
EncodingSource::Folder => configured.label.to_owned(),
|
||||
_ => defaults.encoding.clone(),
|
||||
};
|
||||
has_bom = encoding == "utf-8" && defaults.utf8_bom;
|
||||
}
|
||||
}
|
||||
if let Some(ec) = &editorconfig {
|
||||
if let Some(le) = ec.end_of_line {
|
||||
@@ -485,6 +560,7 @@ impl Documents {
|
||||
}
|
||||
if let Some((enc, bom)) = ec.encoding()
|
||||
&& empty_file
|
||||
&& !encoding_chosen
|
||||
{
|
||||
(encoding, has_bom) = (enc.to_owned(), bom);
|
||||
}
|
||||
@@ -507,10 +583,12 @@ impl Documents {
|
||||
binary: loaded.binary,
|
||||
dirty: false,
|
||||
can_reload_encoding: true,
|
||||
encoding_chosen: false,
|
||||
encoding_chosen,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: loaded.mtime_ms,
|
||||
disk_len: disk_len(path),
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: None,
|
||||
@@ -584,9 +662,11 @@ impl Documents {
|
||||
dirty: false,
|
||||
can_reload_encoding,
|
||||
encoding_chosen: false,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: Some(uri.to_owned()),
|
||||
@@ -644,9 +724,11 @@ impl Documents {
|
||||
dirty: false,
|
||||
can_reload_encoding: false,
|
||||
encoding_chosen: false,
|
||||
encoding_unsaved: false,
|
||||
disk_mtime: 0.0,
|
||||
disk_len: 0,
|
||||
disk_conflict: false,
|
||||
external_writes: 0,
|
||||
clean_text: None,
|
||||
closed: false,
|
||||
uri: Some(key.to_string_lossy().into_owned()),
|
||||
@@ -919,20 +1001,7 @@ impl Documents {
|
||||
/// on disk after this buffer was edited, which only an explicit save may overwrite.
|
||||
pub fn autosave(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
// The watcher event for an external write may not have arrived yet: check the stamp now.
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& (ide_vfs::mtime_ms(&meta) != st.disk_mtime || meta.len() != st.disk_len)
|
||||
{
|
||||
st.disk_mtime = ide_vfs::mtime_ms(&meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
self.check_disk_conflict(doc, st);
|
||||
if st.dirty && st.disk_conflict {
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -940,6 +1009,29 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// An unsaved buffer whose file another program wrote: the watcher event may not have arrived
|
||||
/// yet, so check the stamp now.
|
||||
fn check_disk_conflict(&self, doc: DocId, st: &mut DocState) {
|
||||
if st.dirty
|
||||
&& !st.disk_conflict
|
||||
&& st.uri.is_none()
|
||||
&& let Ok(meta) = std::fs::metadata(&st.path)
|
||||
&& st.changed_on_disk(&meta)
|
||||
{
|
||||
self.disk_conflict(doc, st, &meta);
|
||||
}
|
||||
}
|
||||
|
||||
fn disk_conflict(&self, doc: DocId, st: &mut DocState, meta: &std::fs::Metadata) {
|
||||
st.disk_mtime = ide_vfs::mtime_ms(meta);
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
st.external_writes += 1;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc, path: st.path.to_string_lossy().into_owned() });
|
||||
}
|
||||
|
||||
fn write(&self, doc: DocId, st: &mut DocState) -> IdeResult<()> {
|
||||
{
|
||||
if !st.dirty || st.uri.is_some() {
|
||||
@@ -1246,6 +1338,30 @@ impl Documents {
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the encoding the user chose for `doc` is still to reach its file: the text was
|
||||
/// converted and not saved. It is then reported by [`Documents::take_saved_encodings`]
|
||||
/// once a save has written it.
|
||||
pub fn keep_encoding_when_saved(&self, doc: DocId) -> IdeResult<bool> {
|
||||
self.with_doc(doc, |st| {
|
||||
st.encoding_unsaved = st.dirty;
|
||||
Ok(st.dirty)
|
||||
})
|
||||
}
|
||||
|
||||
/// The files saved in the encoding their text was converted to since
|
||||
/// [`Documents::keep_encoding_when_saved`], with that encoding. Each is reported once.
|
||||
pub fn take_saved_encodings(&self) -> Vec<(PathBuf, String)> {
|
||||
let ids: Vec<DocId> = self.registry.lock().docs.keys().copied().collect();
|
||||
let saved = |id| {
|
||||
self.with_doc(id, |st| {
|
||||
let saved = st.encoding_unsaved && !st.dirty;
|
||||
st.encoding_unsaved &= st.dirty;
|
||||
Ok(saved.then(|| (st.path.clone(), st.encoding.clone())))
|
||||
})
|
||||
};
|
||||
ids.into_iter().filter_map(|id| saved(id).ok().flatten()).collect()
|
||||
}
|
||||
|
||||
/// Load Changes from Disk: drops the buffer's unsaved changes and reads its file again in
|
||||
/// the buffer's encoding, after the file changed on disk (`IdeEvent::DocDiskConflict`).
|
||||
pub fn discard_and_reload(&self, doc: DocId) -> IdeResult<()> {
|
||||
@@ -1255,6 +1371,7 @@ impl Documents {
|
||||
}
|
||||
let loaded = Self::load_as(&st.path, &st.encoding, st.native_to_ascii)?;
|
||||
st.has_bom = loaded.has_bom;
|
||||
st.encoding_unsaved = false;
|
||||
self.replace_locked(doc, st, &loaded.text)?;
|
||||
st.synced(loaded.mtime_ms);
|
||||
self.set_dirty(doc, st, false);
|
||||
@@ -1411,12 +1528,10 @@ impl Documents {
|
||||
return Ok(());
|
||||
}
|
||||
if st.dirty {
|
||||
st.disk_mtime = mtime;
|
||||
st.disk_len = meta.len();
|
||||
st.disk_conflict = true;
|
||||
// The text read before no longer matches the file: undoing back to it is not clean.
|
||||
st.clean_text = None;
|
||||
self.sink.emit(IdeEvent::DocDiskConflict { doc: id, path: st.path.to_string_lossy().into_owned() });
|
||||
if !st.changed_on_disk(&meta) {
|
||||
return Ok(());
|
||||
}
|
||||
self.disk_conflict(id, st, &meta);
|
||||
return Ok(());
|
||||
}
|
||||
let loaded = if force_clean {
|
||||
@@ -1427,7 +1542,7 @@ impl Documents {
|
||||
let loaded = if st.encoding_chosen {
|
||||
Self::load_as(&st.path, &st.encoding, native_to_ascii)?
|
||||
} else {
|
||||
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?
|
||||
Self::load_with_defaults(&st.path, &defaults, st.editorconfig.as_ref())?.0
|
||||
};
|
||||
st.native_to_ascii = native_to_ascii;
|
||||
loaded
|
||||
|
||||
@@ -100,6 +100,8 @@ struct Record {
|
||||
paths: Vec<SavedPath>,
|
||||
documents: Vec<(DocId, DocState)>,
|
||||
after: Vec<WorkspaceEditPrecondition>,
|
||||
/// External writes seen by each open document as of `after` (see [`Documents::external_writes`]).
|
||||
writes: Vec<(DocId, u64)>,
|
||||
}
|
||||
|
||||
fn stale(path: &Path) -> IdeError {
|
||||
@@ -314,12 +316,7 @@ fn hash_disk(hash: &mut blake3::Hasher, path: &Path, unsaved: &HashMap<PathBuf,
|
||||
|
||||
/// The bytes saving `state` would write.
|
||||
fn saved_bytes(state: &DocState) -> IdeResult<Vec<u8>> {
|
||||
let text = state.doc.text_for_save();
|
||||
Ok(if state.native_to_ascii {
|
||||
ide_vfs::encode_properties_ascii(&text).into_bytes()
|
||||
} else {
|
||||
ide_vfs::encode(&text, &state.encoding, state.has_bom)?
|
||||
})
|
||||
state.bytes_for_save(&state.doc)
|
||||
}
|
||||
|
||||
/// A reverted edit may leave the dirty flag set even when all saved bytes match.
|
||||
@@ -374,6 +371,35 @@ impl Documents {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// How many external writes each open document under `roots` has seen, with its path. An
|
||||
/// unsaved buffer's file is checked first, for a write the watcher hasn't reported yet.
|
||||
fn external_writes(&self, roots: &[PathBuf]) -> IdeResult<Vec<(DocId, u64, PathBuf)>> {
|
||||
let mut writes = Vec::new();
|
||||
for id in self.open_documents() {
|
||||
self.with_doc(id, |state| {
|
||||
if roots.iter().any(|p| text_path(&state.path).is_ok_and(|file| file.starts_with(p))) {
|
||||
self.check_disk_conflict(id, state);
|
||||
writes.push((id, state.external_writes, state.path.clone()));
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
Ok(writes)
|
||||
}
|
||||
|
||||
/// Fingerprints see an unsaved buffer in place of its file, so another program writing that
|
||||
/// file since the record was made shows only as a disk conflict. The IDE's own saves don't count.
|
||||
fn validate_external_writes(&self, record: &Record, roots: &[PathBuf]) -> IdeResult<()> {
|
||||
for (id, writes, path) in self.external_writes(roots)? {
|
||||
// A document opened since then starts at zero.
|
||||
let before = record.writes.iter().find(|(doc, _)| *doc == id).map_or(0, |(_, writes)| *writes);
|
||||
if writes != before {
|
||||
return Err(stale(&path));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_preconditions(&self, expected: &[WorkspaceEditPrecondition]) -> IdeResult<()> {
|
||||
let current = self.fingerprints(&expected.iter().map(|p| p.path.to_path_buf()).collect::<Vec<_>>())?;
|
||||
for (before, after) in expected.iter().zip(current) {
|
||||
@@ -474,6 +500,10 @@ impl Documents {
|
||||
Ok(after) => after,
|
||||
Err(error) => return Err(self.recover(record, error)),
|
||||
};
|
||||
record.writes = match self.external_writes(&roots) {
|
||||
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
|
||||
Err(error) => return Err(self.recover(record, error)),
|
||||
};
|
||||
if let Err(error) = fs::remove_file(record.directory.path().join("recovery")) {
|
||||
return Err(self.recover(record, error.into()));
|
||||
}
|
||||
@@ -573,6 +603,7 @@ impl Documents {
|
||||
paths,
|
||||
documents,
|
||||
after: Vec::new(),
|
||||
writes: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -819,7 +850,7 @@ impl Documents {
|
||||
let loaded = if state.encoding_chosen {
|
||||
Self::load_as(path, &state.encoding, native_to_ascii)?
|
||||
} else {
|
||||
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?
|
||||
Self::load_with_defaults(path, &defaults, state.editorconfig.as_ref())?.0
|
||||
};
|
||||
state.native_to_ascii = native_to_ascii;
|
||||
self.replace_locked(id, state, &loaded.text)?;
|
||||
@@ -874,8 +905,9 @@ impl Documents {
|
||||
if record.undone != redo {
|
||||
return Err(IdeError::invalid("the refactoring is already in the requested history state"));
|
||||
}
|
||||
self.validate_preconditions(&record.after)?;
|
||||
let roots = record.paths.iter().map(|p| p.path.clone()).collect::<Vec<_>>();
|
||||
self.validate_external_writes(record, &roots)?;
|
||||
self.validate_preconditions(&record.after)?;
|
||||
let mut current = self.backup(&roots)?;
|
||||
fs::write(current.directory.path().join("recovery"), b"history restore in progress")?;
|
||||
let _active = ActiveEdit::new(&self.workspace_edit_active);
|
||||
@@ -886,6 +918,10 @@ impl Documents {
|
||||
Ok(after) => after,
|
||||
Err(error) => return Err(self.recover(current, error)),
|
||||
};
|
||||
current.writes = match self.external_writes(&roots) {
|
||||
Ok(writes) => writes.into_iter().map(|(id, writes, _)| (id, writes)).collect(),
|
||||
Err(error) => return Err(self.recover(current, error)),
|
||||
};
|
||||
current.undone = !redo;
|
||||
current.created = record.created;
|
||||
if let Err(error) = fs::remove_file(current.directory.path().join("recovery")) {
|
||||
|
||||
@@ -34,7 +34,8 @@ pub struct EditorConfigProps {
|
||||
pub indent_size: Option<u32>,
|
||||
pub tab_width: Option<u32>,
|
||||
pub end_of_line: Option<LineEnding>,
|
||||
/// `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be` or `latin1`.
|
||||
/// `utf-8`, `utf-8-bom`, `utf-16le`, `utf-16be`, `latin1` or an encoding
|
||||
/// Settings › Editor › File Encodings lists (`iso-8859-15`, `windows-1252`, `gbk`, …).
|
||||
pub charset: Option<String>,
|
||||
pub trim_trailing_whitespace: Option<bool>,
|
||||
pub insert_final_newline: Option<bool>,
|
||||
@@ -48,17 +49,31 @@ impl EditorConfigProps {
|
||||
|
||||
/// WHATWG encoding label and BOM flag for `charset`.
|
||||
pub fn encoding(&self) -> Option<(&'static str, bool)> {
|
||||
Some(match self.charset.as_deref()? {
|
||||
"utf-8" => ("utf-8", false),
|
||||
"utf-8-bom" => ("utf-8", true),
|
||||
"utf-16le" => ("utf-16le", true),
|
||||
"utf-16be" => ("utf-16be", true),
|
||||
"latin1" => ("windows-1252", false),
|
||||
_ => return None,
|
||||
})
|
||||
charset_encoding(self.charset.as_deref()?)
|
||||
}
|
||||
}
|
||||
|
||||
/// WHATWG label and BOM flag of a lower-cased `charset` value: the five the spec
|
||||
/// defines and the other encodings Settings › Editor › File Encodings lists.
|
||||
fn charset_encoding(charset: &str) -> Option<(&'static str, bool)> {
|
||||
Some(match charset {
|
||||
"utf-8" => ("utf-8", false),
|
||||
"utf-8-bom" => ("utf-8", true),
|
||||
"utf-16le" => ("utf-16le", true),
|
||||
"utf-16be" => ("utf-16be", true),
|
||||
// WHATWG decodes ISO-8859-1 as windows-1252.
|
||||
"latin1" | "iso-8859-1" | "windows-1252" => ("windows-1252", false),
|
||||
"iso-8859-15" => ("iso-8859-15", false),
|
||||
"gbk" => ("gbk", false),
|
||||
"gb18030" => ("gb18030", false),
|
||||
"big5" => ("big5", false),
|
||||
"shift_jis" => ("shift_jis", false),
|
||||
"euc-kr" => ("euc-kr", false),
|
||||
"koi8-r" => ("koi8-r", false),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raw `key = value` pairs (keys lower-cased) in application order.
|
||||
type Pairs = Vec<(String, String)>;
|
||||
|
||||
@@ -200,8 +215,7 @@ fn props_from(map: &HashMap<String, String>) -> EditorConfigProps {
|
||||
Some("cr") => Some(LineEnding::Cr),
|
||||
_ => None,
|
||||
};
|
||||
let charset =
|
||||
get("charset").filter(|c| matches!(c.as_str(), "utf-8" | "utf-8-bom" | "utf-16le" | "utf-16be" | "latin1"));
|
||||
let charset = get("charset").filter(|c| charset_encoding(c).is_some());
|
||||
let max_line_length = get("max_line_length").and_then(|v| v.parse::<u32>().ok());
|
||||
EditorConfigProps {
|
||||
indent_style,
|
||||
@@ -406,4 +420,34 @@ mod tests {
|
||||
assert!(std::fs::read(r.join("new.l1")).unwrap().is_empty());
|
||||
assert!(create_file(&ec, &r.join("new.txt")).is_err(), "never truncates");
|
||||
}
|
||||
|
||||
/// The labels of `ENCODING_CHOICES` in `src/platform/editorSettings.ts`, copied by hand.
|
||||
#[test]
|
||||
fn charset_maps_the_listed_encodings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let r = tmp.path().canonicalize().unwrap();
|
||||
let listed = [
|
||||
("utf-8", "utf-8"),
|
||||
("utf-16le", "utf-16le"),
|
||||
("utf-16be", "utf-16be"),
|
||||
("gbk", "gbk"),
|
||||
("gb18030", "gb18030"),
|
||||
("big5", "big5"),
|
||||
("shift_jis", "shift_jis"),
|
||||
("euc-kr", "euc-kr"),
|
||||
("windows-1252", "windows-1252"),
|
||||
("iso-8859-1", "windows-1252"),
|
||||
("ISO-8859-15", "iso-8859-15"),
|
||||
("koi8-r", "koi8-r"),
|
||||
];
|
||||
let sections: String =
|
||||
listed.iter().enumerate().map(|(i, (c, _))| format!("[*.e{i}]\ncharset = {c}\n")).collect();
|
||||
write(&r.join(".editorconfig"), &format!("root = true\n{sections}"));
|
||||
let ec = EditorConfig::new();
|
||||
for (i, (charset, label)) in listed.iter().enumerate() {
|
||||
let encoding = ec.resolve(&r.join(format!("a.e{i}"))).and_then(|p| p.encoding());
|
||||
assert_eq!(encoding.map(|(label, _)| label), Some(*label), "charset = {charset}");
|
||||
assert!(encoding_rs::Encoding::for_label(label.as_bytes()).is_some(), "{label} is a WHATWG label");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
|
||||
use ide_core::settings::Settings;
|
||||
use ide_text::LineEnding;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct FileDefaults {
|
||||
@@ -21,6 +22,34 @@ pub struct FileDefaults {
|
||||
pub native_to_ascii: bool,
|
||||
pub editorconfig: bool,
|
||||
pub root: Option<PathBuf>,
|
||||
/// File Encodings mappings: a file's or a folder's path with its encoding. An entry
|
||||
/// naming the file itself is the user's choice for it; one naming a folder above it
|
||||
/// covers the files inside.
|
||||
pub mappings: Vec<(PathBuf, String)>,
|
||||
}
|
||||
|
||||
/// Where the encoding configured for a file comes from, strongest first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum EncodingSource {
|
||||
File,
|
||||
Properties,
|
||||
Folder,
|
||||
Project,
|
||||
Global,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ConfiguredEncoding<'a> {
|
||||
pub label: &'a str,
|
||||
pub source: EncodingSource,
|
||||
}
|
||||
|
||||
impl<'a> ConfiguredEncoding<'a> {
|
||||
/// The label for files that are not valid UTF-8 or are plain ASCII (`None`: detect).
|
||||
pub fn fallback(self) -> Option<ide_vfs::Fallback<'a>> {
|
||||
(self.label != "utf-8")
|
||||
.then_some(ide_vfs::Fallback { encoding: self.label, ascii: self.source != EncodingSource::Properties })
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FileDefaults {
|
||||
@@ -51,20 +80,47 @@ impl FileDefaults {
|
||||
native_to_ascii: enc.native_to_ascii,
|
||||
editorconfig: style.editorconfig,
|
||||
root: root.map(Path::to_path_buf),
|
||||
mappings: root.map(|root| mappings(root, &enc.mappings)).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding for `path` when it is not valid UTF-8 (`None`: detect). The project and
|
||||
/// global encodings also label plain ASCII; the properties encoding only decodes.
|
||||
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
|
||||
let (label, ascii) = if path.extension().is_some_and(|e| e == "properties") {
|
||||
(&self.properties_fallback, false)
|
||||
} else if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
|
||||
(&self.project_fallback, true)
|
||||
} else {
|
||||
(&self.global_fallback, true)
|
||||
/// The encoding the settings give `path`: the one chosen for the file itself, else the
|
||||
/// one it [inherits](Self::inherited_encoding_for).
|
||||
pub fn configured_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
match self.mappings.iter().find(|(mapped, _)| path == mapped) {
|
||||
Some((_, label)) => ConfiguredEncoding { label, source: EncodingSource::File },
|
||||
None => self.inherited_encoding_for(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// The encoding of `path` without a choice for the file itself: the `.properties`
|
||||
/// default, the nearest mapped folder above it, then the project's or the global one.
|
||||
pub fn inherited_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
let folder = || {
|
||||
let above = self.mappings.iter().filter(|(mapped, _)| path != mapped && path.starts_with(mapped));
|
||||
above.max_by_key(|(mapped, _)| mapped.components().count())
|
||||
};
|
||||
(label != "utf-8").then_some(ide_vfs::Fallback { encoding: label, ascii })
|
||||
if path.extension().is_some_and(|e| e == "properties") {
|
||||
ConfiguredEncoding { label: &self.properties_fallback, source: EncodingSource::Properties }
|
||||
} else if let Some((_, label)) = folder() {
|
||||
ConfiguredEncoding { label, source: EncodingSource::Folder }
|
||||
} else {
|
||||
self.project_encoding_for(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's encoding for a file inside it, the global one for any other.
|
||||
pub fn project_encoding_for(&self, path: &Path) -> ConfiguredEncoding<'_> {
|
||||
if self.root.as_ref().is_none_or(|r| path.starts_with(r)) {
|
||||
ConfiguredEncoding { label: &self.project_fallback, source: EncodingSource::Project }
|
||||
} else {
|
||||
ConfiguredEncoding { label: &self.global_fallback, source: EncodingSource::Global }
|
||||
}
|
||||
}
|
||||
|
||||
/// Encoding for `path` when it is not valid UTF-8 or is plain ASCII (`None`: detect).
|
||||
pub fn fallback_for(&self, path: &Path) -> Option<ide_vfs::Fallback<'_>> {
|
||||
self.configured_encoding_for(path).fallback()
|
||||
}
|
||||
|
||||
pub fn native_to_ascii_for(&self, path: &Path) -> bool {
|
||||
@@ -81,6 +137,49 @@ impl FileDefaults {
|
||||
}
|
||||
}
|
||||
|
||||
/// The `[editor.encodings.mappings]` key of `path`: its path inside the project `root`,
|
||||
/// with `/` separators. `None` for anything else.
|
||||
pub fn mapping_key(root: &Path, path: &Path) -> Option<String> {
|
||||
let segments: Option<Vec<&str>> = path
|
||||
.strip_prefix(root)
|
||||
.ok()?
|
||||
.components()
|
||||
.map(|c| match c {
|
||||
Component::Normal(name) => name.to_str(),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
segments.filter(|s| !s.is_empty()).map(|s| s.join("/"))
|
||||
}
|
||||
|
||||
/// The mapped paths under `root`. An entry whose key is not such a path, or whose value is
|
||||
/// not an encoding label, is left out.
|
||||
fn mappings(root: &Path, entries: &BTreeMap<String, String>) -> Vec<(PathBuf, String)> {
|
||||
let path_of = |key: &str| {
|
||||
let mut path = root.to_path_buf();
|
||||
for segment in key.strip_suffix('/').unwrap_or(key).split('/') {
|
||||
let mut components = Path::new(segment).components();
|
||||
let plain = matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none();
|
||||
if !plain || segment.contains('\\') {
|
||||
return None;
|
||||
}
|
||||
path.push(segment);
|
||||
}
|
||||
Some(path)
|
||||
};
|
||||
let mapping = |(key, label): (&String, &String)| {
|
||||
let label = normalize(label);
|
||||
match (path_of(key), ide_vfs::encode("", &label, false)) {
|
||||
(Some(path), Ok(_)) => Some((path, label)),
|
||||
_ => {
|
||||
tracing::warn!("ignoring the encoding mapping {key:?} = {label:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
entries.iter().filter_map(mapping).collect()
|
||||
}
|
||||
|
||||
fn normalize(label: &str) -> String {
|
||||
let l = label.trim().to_ascii_lowercase();
|
||||
match l.as_str() {
|
||||
@@ -108,4 +207,106 @@ mod tests {
|
||||
assert_eq!(d.fallback_for(Path::new("/p/a.properties")), fallback("iso-8859-1", false));
|
||||
assert!(d.new_file_bytes().is_empty(), "BOM only for UTF-8 new files");
|
||||
}
|
||||
|
||||
fn mapped(entries: &[(&str, &str)], root: &Path) -> FileDefaults {
|
||||
let mut s = Settings::default();
|
||||
s.editor.encodings.project = "gbk".into();
|
||||
s.editor.encodings.mappings = entries.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
FileDefaults::from_settings(&s, Some(root))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mappings_resolve_a_file_before_its_folders_and_the_project() {
|
||||
let root = Path::new("/p");
|
||||
let d = mapped(
|
||||
&[
|
||||
("src", "ISO-8859-15"),
|
||||
("src/legacy", "koi8-r"),
|
||||
("src/legacy/A.java", "windows-1252"),
|
||||
("src/utf", "utf-8"),
|
||||
("src/app.properties", "big5"),
|
||||
],
|
||||
root,
|
||||
);
|
||||
let fallback = |rel: &str| d.fallback_for(&root.join(rel));
|
||||
assert_eq!(fallback("src/legacy/A.java"), Some(ide_vfs::Fallback { encoding: "windows-1252", ascii: true }));
|
||||
assert_eq!(
|
||||
fallback("src/legacy/B.java"),
|
||||
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true }),
|
||||
"the longest folder wins"
|
||||
);
|
||||
assert_eq!(fallback("src/main/C.java"), Some(ide_vfs::Fallback { encoding: "iso-8859-15", ascii: true }));
|
||||
assert_eq!(
|
||||
fallback("srcs/C.java"),
|
||||
Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }),
|
||||
"a folder is matched by whole path segments"
|
||||
);
|
||||
assert_eq!(fallback("other/C.java"), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
|
||||
assert_eq!(fallback("src/utf/D.java"), None, "a UTF-8 mapping does not fall through to the project");
|
||||
// `.properties` keep their own default inside a mapped folder; only their own entry overrides it.
|
||||
assert_eq!(
|
||||
fallback("src/legacy/b.properties"),
|
||||
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
|
||||
);
|
||||
assert_eq!(fallback("src/app.properties"), Some(ide_vfs::Fallback { encoding: "big5", ascii: true }));
|
||||
assert_eq!(d.fallback_for(Path::new("/elsewhere/src/C.java")), None);
|
||||
|
||||
let source = |rel: &str| d.configured_encoding_for(&root.join(rel)).source;
|
||||
assert_eq!(source("src/legacy/A.java"), EncodingSource::File);
|
||||
assert_eq!(source("src/legacy/B.java"), EncodingSource::Folder);
|
||||
assert_eq!(source("src/legacy/b.properties"), EncodingSource::Properties);
|
||||
assert_eq!(source("other/C.java"), EncodingSource::Project);
|
||||
assert_eq!(d.configured_encoding_for(Path::new("/elsewhere/C.java")).source, EncodingSource::Global);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_encoding_mappings_are_dropped() {
|
||||
let root = Path::new("/p");
|
||||
let d = mapped(
|
||||
&[
|
||||
("ok", "iso-8859-15"),
|
||||
("unknown", "klingon-1"),
|
||||
("", "koi8-r"),
|
||||
("/abs", "koi8-r"),
|
||||
("../up", "koi8-r"),
|
||||
("a/./b", "koi8-r"),
|
||||
("a//b", "koi8-r"),
|
||||
("back\\slash", "koi8-r"),
|
||||
],
|
||||
root,
|
||||
);
|
||||
assert_eq!(d.mappings, [(root.join("ok"), "iso-8859-15".to_owned())]);
|
||||
assert_eq!(d.fallback_for(&root.join("up/A.java")), Some(ide_vfs::Fallback { encoding: "gbk", ascii: true }));
|
||||
assert!(mapped(&[("ok", "iso-8859-15")], root).mappings.len() == 1);
|
||||
// Without a project there is nothing the paths are relative to.
|
||||
let mut s = Settings::default();
|
||||
s.editor.encodings.mappings.insert("ok".into(), "gbk".into());
|
||||
assert!(FileDefaults::from_settings(&s, None).mappings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_key_is_the_path_inside_the_project_with_slashes() {
|
||||
let root = Path::new("/p");
|
||||
assert_eq!(mapping_key(root, &root.join("src").join("a.b").join("A.java")).as_deref(), Some("src/a.b/A.java"));
|
||||
assert_eq!(mapping_key(root, Path::new("/elsewhere/A.java")), None);
|
||||
assert_eq!(mapping_key(root, root), None);
|
||||
assert_eq!(mapping_key(root, Path::new("untitled:Untitled-1")), None);
|
||||
let d = mapped(&[("src/a.b/A.java", "koi8-r")], root);
|
||||
assert_eq!(
|
||||
d.fallback_for(&root.join("src/a.b/A.java")),
|
||||
Some(ide_vfs::Fallback { encoding: "koi8-r", ascii: true })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_mapped_resolves_as_before() {
|
||||
let d = FileDefaults::from_settings(&Settings::default(), Some(Path::new("/p")));
|
||||
assert!(d.mappings.is_empty());
|
||||
assert_eq!(d.fallback_for(Path::new("/p/src/A.java")), None);
|
||||
assert_eq!(
|
||||
d.fallback_for(Path::new("/p/a.properties")),
|
||||
Some(ide_vfs::Fallback { encoding: "iso-8859-1", ascii: false })
|
||||
);
|
||||
assert_eq!(d.configured_encoding_for(Path::new("/p/src/A.java")).label, "utf-8");
|
||||
}
|
||||
}
|
||||
@@ -392,8 +392,35 @@ impl SettingsStore {
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
|
||||
}
|
||||
self.set_segments(scope, key, &key.split('.').collect::<Vec<_>>(), value)
|
||||
}
|
||||
|
||||
/// Sets (`null`: removes) the `entry` of the map setting `map`, e.g. `editor.encodings.mappings`.
|
||||
/// Unlike a dotted key of [`set`](Self::set), `entry` may hold dots: a file path.
|
||||
pub fn set_map_entry(
|
||||
&self,
|
||||
scope: SettingsScope,
|
||||
map: &str,
|
||||
entry: &str,
|
||||
value: serde_json::Value,
|
||||
) -> IdeResult<Settings> {
|
||||
if scope == SettingsScope::Project
|
||||
&& let Some(setting) = user_only_setting(map, &serde_json::json!({ entry: value }))
|
||||
{
|
||||
return Err(IdeError::invalid(format!("{setting} belongs to user settings")));
|
||||
}
|
||||
let segments: Vec<&str> = map.split('.').chain([entry]).collect();
|
||||
self.set_segments(scope, &format!("{map}.{entry}"), &segments, value)
|
||||
}
|
||||
|
||||
fn set_segments(
|
||||
&self,
|
||||
scope: SettingsScope,
|
||||
key: &str,
|
||||
segments: &[&str],
|
||||
value: serde_json::Value,
|
||||
) -> IdeResult<Settings> {
|
||||
let file = self.file(scope).ok_or_else(|| IdeError::invalid("no project is open"))?.to_path_buf();
|
||||
let segments: Vec<&str> = key.split('.').collect();
|
||||
if segments.iter().any(|s| s.is_empty()) {
|
||||
return Err(IdeError::invalid(format!("invalid settings key {key:?}")));
|
||||
}
|
||||
@@ -421,7 +448,7 @@ impl SettingsStore {
|
||||
.parse()
|
||||
.map_err(|e| IdeError::invalid(format!("{} is not valid TOML; fix it first: {e}", file.display())))?;
|
||||
let new_value = if value.is_null() { None } else { Some(json_to_toml(&value)?) };
|
||||
set_in_document(&mut doc, &segments, new_value, map_entry);
|
||||
set_in_document(&mut doc, segments, new_value, map_entry);
|
||||
let new_text = doc.to_string();
|
||||
|
||||
// Validate the resulting stack before touching the disk.
|
||||
@@ -792,6 +819,52 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn map_entry_named_by_a_path_is_written_under_its_table() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let cfg = tmp.path().join("cfg");
|
||||
let proj = tmp.path().join("proj");
|
||||
let file = proj.join(".openidea/settings.toml");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, "[editor]\ntabSize = 8 # wide\n").unwrap();
|
||||
let store = SettingsStore::load(&cfg, Some(&proj));
|
||||
|
||||
let key = "editor.encodings.mappings";
|
||||
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
|
||||
assert_eq!(s.editor.encodings.mappings.get("src/a.b/A.java").map(String::as_str), Some("iso-8859-15"));
|
||||
assert_eq!(s.editor.tab_size, 8);
|
||||
let written =
|
||||
"[editor]\ntabSize = 8 # wide\n\n[editor.encodings.mappings]\n\"src/a.b/A.java\" = \"iso-8859-15\"\n";
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
|
||||
|
||||
// Setting it again changes nothing; another entry joins the table; `null` removes one.
|
||||
store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", json!("iso-8859-15")).unwrap();
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), written);
|
||||
store.set_map_entry(SettingsScope::Project, key, "web", json!("gbk")).unwrap();
|
||||
let s = store.set_map_entry(SettingsScope::Project, key, "src/a.b/A.java", Json::Null).unwrap();
|
||||
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("web".into(), "gbk".into())]);
|
||||
|
||||
for (map, entry) in [("editor.encodings.nope", "a"), (key, "")] {
|
||||
let err = store.set_map_entry(SettingsScope::Project, map, entry, json!("gbk")).unwrap_err();
|
||||
assert_eq!(err.kind, ide_core::error::ErrorKind::InvalidInput);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_encoding_mapping_that_is_not_a_label_does_not_drop_the_project_settings() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let proj = tmp.path().join("proj");
|
||||
std::fs::create_dir_all(proj.join(".openidea")).unwrap();
|
||||
std::fs::write(
|
||||
proj.join(".openidea/settings.toml"),
|
||||
"[editor]\ntabSize = 8\n[editor.encodings.mappings]\nsrc = \"gbk\"\ncount = 5\n",
|
||||
)
|
||||
.unwrap();
|
||||
let s = SettingsStore::load(&tmp.path().join("cfg"), Some(&proj)).effective();
|
||||
assert_eq!(s.editor.tab_size, 8);
|
||||
assert_eq!(s.editor.encodings.mappings.into_iter().collect::<Vec<_>>(), [("src".into(), "gbk".into())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_console_log_colors() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -350,6 +350,61 @@ fn autosave_checks_the_disk_before_the_watcher_reports_a_change() {
|
||||
);
|
||||
}
|
||||
|
||||
/// Writes `bytes` with an mtime clearly after the current one, whatever the filesystem's granularity.
|
||||
fn rewrite_later(path: &Path, bytes: &[u8]) {
|
||||
let mtime = fs::metadata(path).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
|
||||
fs::write(path, bytes).unwrap();
|
||||
fs::File::options().write(true).open(path).unwrap().set_modified(mtime).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewriting_the_same_bytes_is_no_disk_conflict() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
// A touch, or a tool rewriting the file unchanged: only the mtime moves.
|
||||
rewrite_later(&path, b"alpha\nbeta\n");
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
assert!(!f.events.lock().iter().any(|e| matches!(e, IdeEvent::DocDiskConflict { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_ignores_a_rewrite_of_the_same_bytes_before_the_watcher_reports_it() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("notes.txt");
|
||||
fs::write(&path, "alpha\nbeta\n").unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 5, "edited")).unwrap();
|
||||
rewrite_later(&path, b"alpha\nbeta\n");
|
||||
assert!(f.docs.autosave(info.id).unwrap(), "autosave stopped on a file whose bytes did not change");
|
||||
assert_eq!(fs::read_to_string(&path).unwrap(), "edited\nbeta\n");
|
||||
}
|
||||
|
||||
/// Opens `bytes`, edits the buffer, then rewrites the file as `external` (same text, other bytes).
|
||||
fn assert_other_bytes_conflict(name: &str, bytes: &[u8], external: &[u8]) {
|
||||
let f = fixture();
|
||||
let path = f.root.join(name);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let info = f.docs.open(&path).unwrap();
|
||||
f.docs.edit(info.id, 0, change(0, 0, "x")).unwrap();
|
||||
rewrite_later(&path, external);
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert!(!f.docs.autosave(info.id).unwrap(), "{name}: autosave overwrote other bytes of the same text");
|
||||
assert_eq!(fs::read(&path).unwrap(), external);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_text_in_other_bytes_is_still_a_disk_conflict() {
|
||||
assert_other_bytes_conflict("crlf.txt", b"alpha\nbeta\n", b"alpha\r\nbeta\r\n");
|
||||
assert_other_bytes_conflict("bom.txt", b"alpha\n", b"\xEF\xBB\xBFalpha\n");
|
||||
// Same length: only the byte comparison tells them apart.
|
||||
assert_other_bytes_conflict("utf16.txt", b"\xFF\xFEa\x00\n\x00", b"\xFE\xFF\x00a\x00\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autosave_leaves_a_file_changed_on_disk_after_an_edit() {
|
||||
let f = fixture();
|
||||
@@ -1512,3 +1567,298 @@ fn undo_back_to_the_disk_text_reloads_on_checkout() {
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
assert_eq!(f.docs.snapshot(id).unwrap().text, "checked out\n");
|
||||
}
|
||||
|
||||
fn project_encoding(f: &Fixture, label: &str) {
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = label.into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
}
|
||||
|
||||
fn latin9_editorconfig(f: &Fixture) {
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = iso-8859-15\n").unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_applies_to_an_existing_ascii_file_over_the_project_encoding() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "iso-8859-15");
|
||||
f.docs.edit(doc.id, doc.version, change(0, 0, "// ação €\n")).unwrap();
|
||||
f.docs.save(doc.id).unwrap();
|
||||
|
||||
assert_eq!(fs::read(&path).unwrap(), b"// a\xe7\xe3o \xa4\nclass A {}\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_decodes_a_legacy_file_over_the_project_encoding() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
let bytes = b"// a\xe7\xe3o \xa4\n";
|
||||
fs::write(&path, bytes).unwrap();
|
||||
|
||||
assert_eq!(f.docs.detect_encoding(&path, bytes), encoding_rs::ISO_8859_15);
|
||||
for loaded in [f.docs.load_file(&path).unwrap(), f.docs.load_file_bounded(&path, 1024).unwrap()] {
|
||||
assert_eq!((loaded.text.as_str(), loaded.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_survives_a_reload_from_disk() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
let reloaded = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_without_a_usable_charset_leaves_the_encoding_alone() {
|
||||
let open = |project: Option<&str>, editorconfig: &str, enabled: bool| {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
if let Some(project) = project {
|
||||
defaults.project_fallback = project.into();
|
||||
}
|
||||
defaults.editorconfig = enabled;
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), format!("root = true\n[*.java]\n{editorconfig}\n")).unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
f.docs.open(&path).unwrap().encoding
|
||||
};
|
||||
|
||||
assert_eq!(open(None, "indent_size = 2", true), "utf-8", "nothing configured");
|
||||
assert_eq!(open(None, "charset = ebcdic", true), "utf-8", "unknown charset");
|
||||
assert_eq!(open(Some("iso-8859-15"), "indent_size = 2", true), "iso-8859-15", "no charset: the project's");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = ebcdic", true), "iso-8859-15", "unknown charset: the project's");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = gbk", false), "iso-8859-15", "EditorConfig support is off");
|
||||
assert_eq!(open(Some("iso-8859-15"), "charset = utf-16le", true), "iso-8859-15", "UTF-16 is detected, not assumed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn utf16_text_without_a_bom_keeps_utf16_under_a_utf8_charset() {
|
||||
let f = fixture();
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, ide_vfs::encode("class A {}\n", "utf-16le", false).unwrap()).unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("class A {}\n", "utf-16le"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_utf8_text_keeps_utf8_under_a_legacy_charset() {
|
||||
let f = fixture();
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, "// ação\n").unwrap();
|
||||
|
||||
assert_eq!(f.docs.open(&path).unwrap().encoding, "utf-8");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_utf8_charset_survives_a_reload_from_disk() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
let reloaded = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!((reloaded.text.as_str(), reloaded.encoding.as_str()), ("class A { int changed; }\n", "utf-8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editorconfig_charset_wins_over_the_properties_encoding() {
|
||||
let f = fixture();
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.properties]\ncharset = iso-8859-15\n").unwrap();
|
||||
let path = f.root.join("messages.properties");
|
||||
fs::write(&path, b"price=10 \xa4\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("price=10 €\n", "iso-8859-15"));
|
||||
assert_eq!(f.docs.detect_encoding(&path, b"price=10\n"), encoding_rs::ISO_8859_15);
|
||||
assert_eq!(f.docs.detect_encoding(&f.root.join("unmatched.txt"), b"price=10\n"), encoding_rs::UTF_8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn switching_editorconfig_support_off_stops_the_charset_on_reload() {
|
||||
let f = fixture();
|
||||
project_encoding(&f, "gbk");
|
||||
latin9_editorconfig(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.editorconfig = false;
|
||||
f.docs.set_file_defaults(defaults);
|
||||
|
||||
fs::write(&path, b"class A { int changed; }\n").unwrap();
|
||||
f.docs.sync_from_disk();
|
||||
|
||||
assert_eq!(f.docs.snapshot(doc.id).unwrap().encoding, "gbk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_declared_utf8_that_is_not_utf8_is_decoded_with_the_project_encoding() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = utf-8\n").unwrap();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
|
||||
assert_eq!((doc.text.as_str(), doc.encoding.as_str()), ("// ação €\n", "iso-8859-15"));
|
||||
}
|
||||
|
||||
/// `[editor.encodings.mappings]` as the host hands it over: project paths with their labels.
|
||||
fn encoding_mappings(f: &Fixture, entries: &[(&str, &str)]) {
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.mappings = entries.iter().map(|(rel, label)| (in_root(f, rel), (*label).to_owned())).collect();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
}
|
||||
|
||||
fn in_root(f: &Fixture, rel: &str) -> PathBuf {
|
||||
rel.split('/').fold(f.root.clone(), |path, segment| path.join(segment))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_survives_closing_and_reopening_it() {
|
||||
let f = fixture();
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, "// ação\n").unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
f.docs.set_encoding(doc.id, "iso-8859-15", true).unwrap();
|
||||
let chosen = f.docs.snapshot(doc.id).unwrap();
|
||||
assert_eq!(chosen.text, "// ação\n");
|
||||
f.docs.close(doc.id);
|
||||
|
||||
encoding_mappings(&f, &[("A.java", "iso-8859-15")]);
|
||||
let reopened = f.docs.open(&path).unwrap();
|
||||
assert_eq!((reopened.encoding.as_str(), reopened.text.as_str()), ("iso-8859-15", chosen.text.as_str()));
|
||||
// A later change on disk is read in the remembered encoding too.
|
||||
fs::write(&path, b"// a\xe7\xe3o \xa4\n").unwrap();
|
||||
f.docs.on_disk_changed(std::slice::from_ref(&path));
|
||||
let reloaded = f.docs.snapshot(reopened.id).unwrap();
|
||||
assert_eq!((reloaded.encoding.as_str(), reloaded.text.as_str()), ("iso-8859-15", "// ação €\n"));
|
||||
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "iso-8859-15", "closed-file readers agree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_to_utf8_holds_in_a_latin_project() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"class A {}\n").unwrap();
|
||||
encoding_mappings(&f, &[("A.java", "utf-8")]);
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!(doc.encoding, "utf-8");
|
||||
f.docs.edit(doc.id, doc.version, change(0, 0, "// é\n")).unwrap();
|
||||
f.docs.save(doc.id).unwrap();
|
||||
assert_eq!(fs::read(&path).unwrap(), "// é\nclass A {}\n".as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_file_beats_editorconfig_and_a_folder_mapping_loses_to_it() {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\nend_of_line = crlf\n").unwrap();
|
||||
fs::create_dir(f.root.join("src")).unwrap();
|
||||
for name in ["src/A.java", "src/B.java", "src/notes.txt", "other.txt"] {
|
||||
fs::write(in_root(&f, name), b"plain ascii\n").unwrap();
|
||||
}
|
||||
fs::write(in_root(&f, "src/new.txt"), b"").unwrap();
|
||||
fs::write(in_root(&f, "src/latin.txt"), b"a\xe7\xe3o \xa4\n").unwrap();
|
||||
encoding_mappings(&f, &[("src", "iso-8859-15"), ("src/A.java", "koi8-r")]);
|
||||
let open = |name: &str| f.docs.open(&in_root(&f, name)).unwrap();
|
||||
|
||||
let file = open("src/A.java");
|
||||
assert_eq!(file.encoding, "koi8-r", "the file's own mapping beats .editorconfig");
|
||||
assert_eq!(file.line_ending, LineEnding::CrLf, ".editorconfig still sets the rest");
|
||||
assert_eq!(open("src/B.java").encoding, "windows-1252", ".editorconfig beats the folder mapping");
|
||||
assert_eq!(open("src/notes.txt").encoding, "iso-8859-15", "the folder mapping beats the project encoding");
|
||||
assert_eq!(open("src/new.txt").encoding, "iso-8859-15", "a new file takes its folder's encoding");
|
||||
assert_eq!(open("other.txt").encoding, "gbk");
|
||||
let latin = open("src/latin.txt");
|
||||
assert_eq!((latin.encoding.as_str(), latin.text.as_str()), ("iso-8859-15", "ação €\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_of_a_folder_is_left_out_where_editorconfig_sets_the_charset() {
|
||||
let f = fixture();
|
||||
let mut defaults = f.docs.file_defaults();
|
||||
defaults.project_fallback = "gbk".into();
|
||||
f.docs.set_file_defaults(defaults);
|
||||
fs::write(f.root.join(".editorconfig"), "root = true\n[*.java]\ncharset = latin1\n").unwrap();
|
||||
fs::create_dir(f.root.join("src")).unwrap();
|
||||
let path = in_root(&f, "src/B.java");
|
||||
fs::write(&path, b"// \xd6\xd0\n").unwrap();
|
||||
let unmapped = f.docs.open(&path).unwrap();
|
||||
f.docs.close(unmapped.id);
|
||||
|
||||
encoding_mappings(&f, &[("src", "koi8-r")]);
|
||||
let mapped = f.docs.open(&path).unwrap();
|
||||
assert_eq!((mapped.encoding, mapped.text), (unmapped.encoding, unmapped.text));
|
||||
assert_eq!(f.docs.load_file(&path).unwrap().encoding, "windows-1252", "closed-file readers agree");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoding_mapping_a_file_no_longer_decodes_in_falls_back_to_detection() {
|
||||
let f = fixture();
|
||||
latin_project(&f);
|
||||
let path = f.root.join("A.java");
|
||||
fs::write(&path, b"// a\xe7\xe3o\n").unwrap();
|
||||
encoding_mappings(&f, &[("A.java", "utf-8")]);
|
||||
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!((doc.encoding.as_str(), doc.text.as_str()), ("iso-8859-15", "// ação\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_encoding_mappings_files_open_as_before() {
|
||||
let f = fixture();
|
||||
let settings = ide_core::settings::Settings::default();
|
||||
f.docs.set_file_defaults(ide_workspace::FileDefaults::from_settings(&settings, Some(&f.root)));
|
||||
assert!(f.docs.file_defaults().mappings.is_empty());
|
||||
for (name, bytes) in [
|
||||
("ascii.java", &b"class A {}\n"[..]),
|
||||
("utf8.java", "// ação\n".as_bytes()),
|
||||
("latin.java", &b"// a\xe7\xe3o de gra\xe7a, cora\xe7\xe3o\n"[..]),
|
||||
("empty.java", &b""[..]),
|
||||
] {
|
||||
let path = f.root.join(name);
|
||||
fs::write(&path, bytes).unwrap();
|
||||
let detected = ide_vfs::load_text(&path).unwrap();
|
||||
let doc = f.docs.open(&path).unwrap();
|
||||
assert_eq!((doc.encoding, doc.text), (detected.encoding, detected.text), "{name}");
|
||||
}
|
||||
}
|
||||
@@ -138,17 +138,18 @@ fn rollback_keeps_a_disk_conflict_of_an_unsaved_buffer() {
|
||||
let info = docs.open(&first).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
|
||||
// An external write the undo record still accepts (same bytes, new mtime) under the unsaved buffer.
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
std::fs::write(&first, "old\n").unwrap();
|
||||
// An external write under the unsaved buffer, warned about before the refactoring.
|
||||
let mtime = std::fs::metadata(&first).unwrap().modified().unwrap() + std::time::Duration::from_secs(2);
|
||||
std::fs::write(&first, "ext\n").unwrap();
|
||||
std::fs::File::options().write(true).open(&first).unwrap().set_modified(mtime).unwrap();
|
||||
docs.on_disk_changed(std::slice::from_ref(&first));
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&first, "new")], ..Default::default() }).unwrap();
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
let snap = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!(snap.text, "own\n");
|
||||
assert!(snap.dirty);
|
||||
assert!(!docs.autosave(info.id).unwrap(), "autosave must not overwrite the external change");
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "old\n");
|
||||
assert_eq!(std::fs::read_to_string(&first).unwrap(), "ext\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -240,6 +241,21 @@ fn undo_keeps_the_encoding_chosen_for_a_file_opened_after_the_edit() {
|
||||
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("abcé", "windows-1252"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_the_editorconfig_charset_of_a_file_opened_after_the_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
std::fs::write(tmp.path().join(".editorconfig"), "root = true\n[*.txt]\ncharset = iso-8859-15\n").unwrap();
|
||||
let path = tmp.path().join("legacy.txt");
|
||||
std::fs::write(&path, b"abc\xA4").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
let info = docs.open(&path).unwrap();
|
||||
assert_eq!((info.text.as_str(), info.encoding.as_str()), ("new€", "iso-8859-15"));
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
let snapshot = docs.snapshot(info.id).unwrap();
|
||||
assert_eq!((snapshot.text.as_str(), snapshot.encoding.as_str()), ("abc€", "iso-8859-15"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_document_version_rejects_the_whole_edit() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
@@ -425,6 +441,80 @@ fn undo_refuses_later_changes_and_retains_the_record() {
|
||||
assert_eq!(std::fs::read_to_string(a).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
/// An open file with unsaved typing, refactored: its buffer holds `new`, the disk still `old`.
|
||||
fn refactored_unsaved(path: &Path) -> (Documents, Arc<Mutex<Vec<IdeEvent>>>, ide_core::DocId) {
|
||||
std::fs::write(path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(path).unwrap();
|
||||
docs.edit(info.id, info.version, ChangeSet { changes: vec![TextChange { from: 0, to: 3, insert: "own".into() }] })
|
||||
.unwrap();
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(path, "new")], ..Default::default() }).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "new\n");
|
||||
(docs, events, info.id)
|
||||
}
|
||||
|
||||
fn type_text(docs: &Documents, id: ide_core::DocId, text: &str) {
|
||||
let snapshot = docs.snapshot(id).unwrap();
|
||||
let to = snapshot.text.encode_utf16().count() as u32;
|
||||
docs.edit(id, snapshot.version, ChangeSet { changes: vec![TextChange { from: 0, to, insert: text.into() }] })
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_keeps_an_external_write_under_an_unsaved_buffer() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
// Not reported by a watcher: undo itself notices the write.
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert_eq!(docs.undo_workspace_edit(undo_id(&events)).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "new\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_after_saving_and_undoing_the_typing_is_allowed() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
type_text(&docs, id, "typed later\n");
|
||||
docs.save(id).unwrap();
|
||||
// The typing undone: the buffer is back to the refactoring's text, the IDE's own save on disk.
|
||||
type_text(&docs, id, "new\n");
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "old\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_allows_a_disk_conflict_from_before_the_refactoring() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
std::fs::write(&path, "old\n").unwrap();
|
||||
let (docs, events) = recorded_documents();
|
||||
let info = docs.open(&path).unwrap();
|
||||
type_text(&docs, info.id, "own\n");
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert!(!docs.autosave(info.id).unwrap(), "the external write is a disk conflict");
|
||||
docs.apply_workspace_edit(&WorkspaceEdit { files: vec![edit(&path, "new")], ..Default::default() }).unwrap();
|
||||
docs.undo_workspace_edit(undo_id(&events)).unwrap();
|
||||
assert_eq!(docs.snapshot(info.id).unwrap().text, "own\n");
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redo_keeps_an_external_write_made_after_the_undo() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let path = tmp.path().join("a.txt");
|
||||
let (docs, events, id) = refactored_unsaved(&path);
|
||||
let undo = undo_id(&events);
|
||||
docs.undo_workspace_edit(undo).unwrap();
|
||||
std::fs::write(&path, "external\n").unwrap();
|
||||
assert_eq!(docs.redo_workspace_edit(undo).unwrap_err().kind, ErrorKind::OutOfSync);
|
||||
assert_eq!(std::fs::read_to_string(&path).unwrap(), "external\n");
|
||||
assert_eq!(docs.snapshot(id).unwrap().text, "own\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_resource_operations_and_binary_deletion_are_undoable() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
|
||||
@@ -16,7 +16,7 @@ These agents are built in. Install the agent's own CLI and sign in once in a ter
|
||||
| Claude Code | `claude` | `claude` |
|
||||
| Codex | `codex app-server` | `codex login` |
|
||||
| Gemini CLI | `gemini --experimental-acp` | `gemini` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot` |
|
||||
| GitHub Copilot | `copilot --acp` | `copilot login` |
|
||||
| Cursor | `cursor-agent acp` | `cursor-agent login` |
|
||||
| OpenCode | `opencode acp` | `opencode auth login` |
|
||||
| Qwen Code | `qwen --experimental-acp` | `qwen` |
|
||||
@@ -132,6 +132,8 @@ Tasks are saved per project and survive restarts. When the agent supports resumi
|
||||
|
||||
For a built-in ACP agent launched directly, such as OMP, **Launch › Additional arguments** appends arguments to its existing launch command. Separate arguments with spaces and quote values that contain spaces. **Apply** saves the arguments for the next process launch; the command preview shows the saved result. **Reset additional arguments** clears just this field, leaving the executable, environment and any hand-written `args` in the agent file alone.
|
||||
|
||||
For **GitHub Copilot**, **Sign In › GitHub account** selects which GitHub account's Copilot subscription is used for AI model requests—either Copilot CLI's own default login (**Sign In…**) or any account signed into GitHub CLI (**Add account…**). When an agent or `gh` prints an OAuth device verification code during in-IDE sign-in (including on remote hosts), the sign-in dialog surfaces the one-time code above the terminal with **Copy** and **Copy Code & Open Browser** so you can authorize in your local browser in one click. **New Tasks** model options load automatically for the selected authenticated account, and **Apply** / **OK** saves the selection for new sessions.
|
||||
|
||||
**Settings › Agents › Chat** chooses what the task header shows: **Context window usage**, **Time spent on the task**, **Usage limits** (when the agent reports them, such as Claude Code) and **Session cost**.
|
||||
|
||||
### External MCP servers
|
||||
|
||||
@@ -61,7 +61,7 @@ Language servers that support LSP inline completion show a grey suggestion at th
|
||||
- Hold `⌘` / `Ctrl` and hover over a name to see it underlined as a link, with brief information about it.
|
||||
- Gutter icons mark types and methods that are implemented or overridden (↓) and methods that implement or override another (↑). Click one to go there.
|
||||
- **Navigate › Test** jumps between a class and its tests by naming convention and offers **Create New Test…** when there is none.
|
||||
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations. With several targets it shows a chooser.
|
||||
- **Navigate › Related Symbol…** goes to the files tied to the current one by convention: a C, C++ or Objective-C header and its source file, and in Rails a controller action and its views, a view and its action, a controller and its helper and model, a model and its controller and migrations, and a JavaScript or TypeScript component and the files beside it with the same name (an Angular component's template, styles and spec, or its `templateUrl` / `styleUrls`; `Button.tsx` and `Button.module.css`, `Button.test.tsx`, `Button.stories.tsx`). With several targets it shows a chooser.
|
||||
- In Rails, **Go to Declaration** also follows method symbols in callbacks (`before_action :load_user`, `if: :admin?`) to their `def`, and controller actions in `config/routes.rb` (`to: "users#index"`, `resources :users`) to the controller.
|
||||
|
||||
Going to files, classes and symbols by name is covered in [Search and navigation](/en/guide/search).
|
||||
@@ -75,7 +75,7 @@ Going to files, classes and symbols by name is covered in [Search and navigation
|
||||
| **Highlight Usages in File** | `⇧⌘F7` | `Ctrl+Shift+F7` |
|
||||
| **Next Highlighted Usage** / **Previous** | `⌃⌥↓` / `⌃⌥↑` | `Ctrl+Alt+Down` / `Ctrl+Alt+Up` |
|
||||
|
||||
**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. **Recent Find Usages** (from Find Action) lists the last ten searches, including those whose tab was closed, and runs the chosen one again. The occurrences of the symbol under the caret are highlighted in the editor as you move.
|
||||
**Find Usages** lists the results in the **Find Usages** tool window, grouped by file, with a preview. **Show Usages** shows them in a popup at the caret. **Recent Find Usages** (from Find Action) lists the last ten searches, including those whose tab was closed, and runs the chosen one again. **Export to Text File** in the tool window's toolbar saves the results as shown (with the access filter applied, without excluded usages) to a text file. The occurrences of the symbol under the caret are highlighted in the editor as you move.
|
||||
|
||||
Above declarations, a **N usages** hint and the last author of the code (from Git blame) are shown, with the date of that last change. Turn them off under **Code Vision** in **Settings › Editor › Inlay Hints**.
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
- Drag with `⌥` / `Alt` held (or with the middle mouse button on macOS and Windows) to make a rectangular selection without switching modes.
|
||||
- **Extend Selection** grows the selection to the enclosing word, expression, statement and block, using the syntax tree.
|
||||
- **Swap Selection Boundaries** moves the caret of each selection to its other end and keeps the text selected, so `⇧` / `Shift` with the arrow keys then extends or shrink it from that side. It has no default shortcut.
|
||||
- **Toggle Sticky Selection** starts a selection at each caret: arrow keys and other caret moves then extend it as if `⇧` / `Shift` were held. Run it again or press `Esc` to turn it off, which also removes the selection. Copying or editing the text turns it off too. It has no default shortcut.
|
||||
- **Select Line at Caret** selects the whole line at each caret together with its line break; a selection grows to the whole lines it touches. It has no default shortcut.
|
||||
|
||||
## Editing lines and code
|
||||
@@ -57,10 +58,12 @@ The editor follows IntelliJ IDEA's behaviour and default keymap. Shortcuts below
|
||||
|
||||
**Move Caret to Next Word** / **Previous Word in Different "CamelHumps" Mode** (and their **with Selection** variants), **Delete to Word Start** and **Delete to Word End in Different "CamelHumps" Mode** move or delete by word the other way from **Settings › Editor › General › Smart Keys › Use "CamelHumps" words**: by hump (`parse|HTML|Document`) while it is off, by whole word while it is on. They have no default shortcut.
|
||||
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones.
|
||||
**Edit › Sort Lines** and **Edit › Reverse Lines** reorder the selected lines (the whole file without a selection); they have no default shortcut. Sort Lines orders by character code, so uppercase letters come before lowercase ones. **Delete Duplicate Lines** works on the same lines and keeps only the first of each repeated line (the text must match exactly, whitespace included); run it from **Find Action** or assign a shortcut in **Settings › Keymap**.
|
||||
|
||||
**Cut up to Line End** cuts from each caret to the end of its line, together with the line break when only whitespace is left (or the caret is already at the line end), so pressing it again on the same caret cuts the next line too; those repeated cuts collect into one clipboard entry. **Delete to Line Start** and **Delete to Line End** delete the same way without copying (to the line start, or the line break before the caret at the line start), or delete the selection. They have no default shortcut except in the Eclipse keymaps (`⇧⌘⌦` / `Ctrl+Shift+Delete` for Delete to Line End).
|
||||
|
||||
**Kill to Word Start** and **Kill to Word End** cut from each caret back to the start of the previous word or on to the end of the next one, together with the whitespace and line breaks in between; with **Settings › Editor › General › Smart Keys › Use "CamelHumps" words** on they stop at humps (`parse|HTML|Document`). A selection is ignored. Repeated cuts at the same caret, and Cut up to Line End there, collect into one clipboard entry, the ones to the word start in front. They have no default shortcut.
|
||||
|
||||
**Hungry Backspace** deletes all the spaces, tabs and line breaks before each caret in one go, up to the previous non-whitespace character; after anything else, or with a selection, it works like `⌫` / `Backspace`. It has no default shortcut.
|
||||
|
||||
**Duplicate Entire Lines** copies every line touched by a caret or selection below itself, even when only part of a line is selected, and keeps the selection on the copy. It has no default shortcut; run it from **Find Action** or assign one in **Settings › Keymap**.
|
||||
@@ -114,6 +117,8 @@ All folding commands are also in **Code › Folding**. Fold regions come from th
|
||||
|
||||
Indentation and other style options are under **Settings › Editor › Code Style**, with a page per language. `.editorconfig` files in the project are read too.
|
||||
|
||||
Java has an **Imports** tab for IntelliSort-style options: **Class count to use import with '\*'** switches to a wildcard import once that many classes of one package are used, and **Names count to use static import with '\*'** does the same for statically imported names (999 keeps single imports). Both are passed through to the Java language server, whose defaults are 5 and 3, as in IDEA.
|
||||
|
||||
To format on every save, enable **Reformat code** (and optionally **Optimize imports**) in **Settings › Tools › Actions on Save**. Trailing spaces and the final line break on save are set in **Settings › Editor › General**, section **Save Files**.
|
||||
|
||||
## Tabs
|
||||
@@ -145,20 +150,26 @@ With tabs placed left or right, the tab column is as wide as its longest name, u
|
||||
|
||||
## View options
|
||||
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ---------------------- | ----- | --------------- |
|
||||
| **Increase Font Size** | `⌥⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size** | `⌥⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
| Action | macOS | Windows / Linux |
|
||||
| ------------------------------------- | ----- | --------------- |
|
||||
| **Increase Font Size in All Editors** | `⌃⇧.` | `Alt+Shift+.` |
|
||||
| **Decrease Font Size in All Editors** | `⌃⇧,` | `Alt+Shift+,` |
|
||||
| **Scroll to Center** | `⌃L` | `Ctrl+M` |
|
||||
| **Scroll Up** | — | `Ctrl+Up` |
|
||||
| **Scroll Down** | — | `Ctrl+Down` |
|
||||
| **Scroll Left** | — | — |
|
||||
| **Scroll Right** | — | — |
|
||||
| **Scroll Up and Move if Necessary** | — | — |
|
||||
| **Scroll Down and Move if Necessary** | — | — |
|
||||
| **Move Up and Scroll** | — | — |
|
||||
| **Move Down and Scroll** | — | — |
|
||||
| **Scroll to Top** | — | — |
|
||||
| **Scroll to Bottom** | — | — |
|
||||
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
**Scroll Up** and **Scroll Down** move the view by one line and leave the caret where it is, even when it scrolls out of sight; **Scroll Left** and **Scroll Right** do the same sideways, by one column. **Scroll Up and Move if Necessary** and **Scroll Down and Move if Necessary** also move the view by one line, but bring a caret the view doesn't show to its first or last line. **Move Up and Scroll** and **Move Down and Scroll** move the caret one line and the view with it, so the caret stays in the same place on screen; their **with Selection** variants select as they go. **Scroll to Top** and **Scroll to Bottom** show the start and the end of the file; the caret stays where it is too. They have no default shortcut: run them from Find Action or assign one in **Settings › Keymap**.
|
||||
|
||||
- **View › Active Editor › Soft-Wrap** wraps long lines in the current editor. To wrap some file types by default, use **Settings › Editor › General**, section **Soft Wraps**.
|
||||
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
|
||||
- **View › Reset Font Size** undoes font zoom in the active editor or focused surface (**View › Reset Font Size in All Editors** resets every open editor). **Increase Font Size in All Editors** and **Decrease Font Size in All Editors** resize every open editor together, starting from the active one, and have no default shortcut. Changing the font size with `⌘` / `Ctrl` + mouse wheel (scoped to **Active editor** by default, or **All editors**) can be turned on in **Settings › Editor › General**, section **Mouse Control**.
|
||||
- **View › Appearance › Enter Distraction Free Mode** hides tool windows, tabs, the status bar and the gutter and centres the text. Run the same command again to leave.
|
||||
- **View › Appearance › Enter Zen Mode** turns on Distraction Free Mode and full screen together; **Exit Zen Mode** turns both off.
|
||||
- **Show Line Numbers**, **Show Indent Guides**, **Show Sticky Lines** and **Show Whitespaces** turn these on or off in every editor. Run them from Find Action, or right-click the gutter and open **Appearance**.
|
||||
|
||||
@@ -9,9 +9,11 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
|
||||
|
||||
<Steps>
|
||||
<Step title="Install gh">
|
||||
Install the GitHub CLI. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`, then in
|
||||
`/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux) or `C:\Program Files\GitHub CLI\gh.exe`
|
||||
(Windows).
|
||||
Install the GitHub CLI, either from OpenIDEA's **Install GitHub CLI** button (in the **Pull Requests** tool window,
|
||||
**Clone Repository › GitHub**, **Settings › Agents › GitHub Copilot**, or **Settings › Languages & Frameworks ›
|
||||
Language Servers › Other Tools**) or manually. OpenIDEA looks for it in `OPENIDEA_GH` (a full path), then on `PATH`
|
||||
(including IDE-managed tools), then in `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/snap/bin` (macOS/Linux)
|
||||
or `C:\Program Files\GitHub CLI\gh.exe` (Windows).
|
||||
</Step>
|
||||
<Step title="Sign in">
|
||||
Run `gh auth login` in a terminal. If you open the **Pull Requests** tool window while signed out, it shows **Not
|
||||
@@ -22,6 +24,14 @@ OpenIDEA works with GitHub through the [GitHub CLI](https://cli.github.com) (`gh
|
||||
The project needs a Git remote on `github.com`. With one GitHub remote, OpenIDEA connects to it automatically. With
|
||||
several, the tool window asks you to pick a **Repository**; the choice is remembered per project. To switch later,
|
||||
use **Change Repository or Account…** in the tool window's `⋮` menu.
|
||||
|
||||
When multiple `github.com` accounts are signed into `gh`, **Automatic** uses `gh`'s own active account without
|
||||
setting `GH_TOKEN`. In **Settings › Version Control › GitHub** and in the **Pull Requests** header, OpenIDEA can
|
||||
suggest a matching account for the repository (**Use `<login>` for this project**) or let you choose one
|
||||
explicitly (saved in `.openidea/settings.toml`). Choosing an account passes its `GH_TOKEN` to processes started in
|
||||
that project (terminals, agents, Git, Pull Requests, and run configurations) without changing your global
|
||||
`gh auth switch` selection.
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
|
||||
@@ -163,6 +163,7 @@ Each launch opens a tab in the **Run** tool window (bottom). The toolbar has **R
|
||||
|
||||
- File paths and stack trace frames in the output are links. **Up the Stack Trace** / **Down the Stack Trace** in the toolbar (or **Previous / Next Occurrence**, `⌥⌘↑` / `⌥⌘↓`, `Ctrl+Alt+↑` / `Ctrl+Alt+↓` on Windows and Linux) select the previous / next one and open it; links in collapsed folds are skipped. In a test run these keys go through the failed tests instead.
|
||||
- Repeated lines can be folded; configure the patterns in **Settings › Build, Execution, Deployment › Console**, along with the buffer size and the console encoding. **Fold Lines Like This** in the console's context menu opens that page with the selected text (or the clicked line) added as a pattern.
|
||||
- **Search with Google** in the console's context menu searches the web for the selected output, such as an error message, in the browser.
|
||||
- Log lines can take the colour of their level (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`); colours the program prints itself are kept. Turn it on and pick the colours in **Settings › Build, Execution, Deployment › Console**.
|
||||
- For test runs the tab shows a test tree next to the output. See [Testing](/en/guide/testing).
|
||||
|
||||
|
||||
Loaded 100 of 503 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Заблокувати користувача