Compare commits

...
Sign in to create a new pull request.

7 commits

Author SHA1 Message Date
Lukas Wirth
9f54112e7f Fix venv path not being checked for existing 2025-08-18 15:26:20 +02:00
Lukas Wirth
7030465d04 Replace a smol::block_on 2025-08-18 13:14:06 +02:00
Lukas Wirth
dc0e81b13b Slowly disconnect venv handling from project/terminals.rs 2025-08-18 13:14:06 +02:00
Lukas Wirth
b756853407 project: Setup python venv via activate script irrespective of TerminalKind 2025-08-18 13:14:06 +02:00
Lukas Wirth
3758e8d663 Cleanup some error reporting 2025-08-18 13:14:06 +02:00
Lukas Wirth
eb086e3689 venv 2025-08-18 13:13:43 +02:00
Lukas Wirth
ac449d0ca8 project: Print error causes when failing to spawn lsp command 2025-08-18 13:13:43 +02:00
15 changed files with 337 additions and 445 deletions

1
Cargo.lock generated
View file

@ -9266,6 +9266,7 @@ dependencies = [
"snippet_provider", "snippet_provider",
"task", "task",
"tempfile", "tempfile",
"terminal",
"text", "text",
"theme", "theme",
"toml 0.8.20", "toml 0.8.20",

View file

@ -333,7 +333,7 @@ impl NativeAgent {
Err(err) => ( Err(err) => (
None, None,
Some(RulesLoadingError { Some(RulesLoadingError {
message: format!("{err}").into(), message: format!("{err:#}").into(),
}), }),
), ),
}; };

View file

@ -557,7 +557,7 @@ impl ChannelStore {
}; };
cx.background_spawn(async move { cx.background_spawn(async move {
task.await.map_err(|error| { task.await.map_err(|error| {
anyhow!("{error}").context(format!("failed to open channel {resource_name}")) anyhow!(error).context(format!("failed to open channel {resource_name}"))
}) })
}) })
} }

View file

@ -686,7 +686,7 @@ impl Client {
} }
ConnectionResult::Result(r) => { ConnectionResult::Result(r) => {
if let Err(error) = r { if let Err(error) = r {
log::error!("failed to connect: {error}"); log::error!("failed to connect: {error:?}");
} else { } else {
break; break;
} }

View file

@ -874,7 +874,7 @@ fn operation_from_storage(
_format_version: i32, _format_version: i32,
) -> Result<proto::operation::Variant, Error> { ) -> Result<proto::operation::Variant, Error> {
let operation = let operation =
storage::Operation::decode(row.value.as_slice()).map_err(|error| anyhow!("{error}"))?; storage::Operation::decode(row.value.as_slice()).map_err(|error| anyhow!(error))?;
let version = version_from_storage(&operation.version); let version = version_from_storage(&operation.version);
Ok(if operation.is_undo { Ok(if operation.is_undo {
proto::operation::Variant::Undo(proto::operation::Undo { proto::operation::Variant::Undo(proto::operation::Undo {

View file

@ -1312,7 +1312,7 @@ pub async fn handle_metrics(Extension(server): Extension<Arc<Server>>) -> Result
let metric_families = prometheus::gather(); let metric_families = prometheus::gather();
let encoded_metrics = encoder let encoded_metrics = encoder
.encode_to_string(&metric_families) .encode_to_string(&metric_families)
.map_err(|err| anyhow!("{err}"))?; .map_err(|err| anyhow!(err))?;
Ok(encoded_metrics) Ok(encoded_metrics)
} }

View file

@ -1,5 +1,5 @@
use crate::*; use crate::*;
use anyhow::Context as _; use anyhow::{Context as _, anyhow, bail};
use dap::{DebugRequest, StartDebuggingRequestArguments, adapters::DebugTaskDefinition}; use dap::{DebugRequest, StartDebuggingRequestArguments, adapters::DebugTaskDefinition};
use fs::RemoveOptions; use fs::RemoveOptions;
use futures::{StreamExt, TryStreamExt}; use futures::{StreamExt, TryStreamExt};
@ -24,7 +24,7 @@ use util::{ResultExt, maybe};
#[derive(Default)] #[derive(Default)]
pub(crate) struct PythonDebugAdapter { pub(crate) struct PythonDebugAdapter {
debugpy_whl_base_path: OnceCell<Result<Arc<Path>, String>>, debugpy_whl_base_path: OnceCell<Arc<Path>>,
} }
impl PythonDebugAdapter { impl PythonDebugAdapter {
@ -91,13 +91,13 @@ impl PythonDebugAdapter {
}) })
} }
async fn fetch_wheel(delegate: &Arc<dyn DapDelegate>) -> Result<Arc<Path>, String> { async fn fetch_wheel(delegate: &Arc<dyn DapDelegate>) -> Result<Arc<Path>> {
let system_python = Self::system_python_name(delegate) let system_python = Self::system_python_name(delegate)
.await .await
.ok_or_else(|| String::from("Could not find a Python installation"))?; .ok_or_else(|| anyhow!("Could not find a Python installation"))?;
let command: &OsStr = system_python.as_ref(); let command: &OsStr = system_python.as_ref();
let download_dir = debug_adapters_dir().join(Self::ADAPTER_NAME).join("wheels"); let download_dir = debug_adapters_dir().join(Self::ADAPTER_NAME).join("wheels");
std::fs::create_dir_all(&download_dir).map_err(|e| e.to_string())?; std::fs::create_dir_all(&download_dir)?;
let installation_succeeded = util::command::new_smol_command(command) let installation_succeeded = util::command::new_smol_command(command)
.args([ .args([
"-m", "-m",
@ -109,32 +109,27 @@ impl PythonDebugAdapter {
download_dir.to_string_lossy().as_ref(), download_dir.to_string_lossy().as_ref(),
]) ])
.output() .output()
.await .await?
.map_err(|e| format!("{e}"))?
.status .status
.success(); .success();
if !installation_succeeded { if !installation_succeeded {
return Err("debugpy installation failed".into()); bail!("debugpy installation failed");
} }
let wheel_path = std::fs::read_dir(&download_dir) let wheel_path = std::fs::read_dir(&download_dir)?
.map_err(|e| e.to_string())?
.find_map(|entry| { .find_map(|entry| {
entry.ok().filter(|e| { entry.ok().filter(|e| {
e.file_type().is_ok_and(|typ| typ.is_file()) e.file_type().is_ok_and(|typ| typ.is_file())
&& Path::new(&e.file_name()).extension() == Some("whl".as_ref()) && Path::new(&e.file_name()).extension() == Some("whl".as_ref())
}) })
}) })
.ok_or_else(|| String::from("Did not find a .whl in {download_dir}"))?; .ok_or_else(|| anyhow!("Did not find a .whl in {download_dir:?}"))?;
util::archive::extract_zip( util::archive::extract_zip(
&debug_adapters_dir().join(Self::ADAPTER_NAME), &debug_adapters_dir().join(Self::ADAPTER_NAME),
File::open(&wheel_path.path()) File::open(&wheel_path.path()).await?,
.await
.map_err(|e| e.to_string())?,
) )
.await .await?;
.map_err(|e| e.to_string())?;
Ok(Arc::from(wheel_path.path())) Ok(Arc::from(wheel_path.path()))
} }
@ -198,20 +193,17 @@ impl PythonDebugAdapter {
.await; .await;
} }
async fn fetch_debugpy_whl( async fn fetch_debugpy_whl(&self, delegate: &Arc<dyn DapDelegate>) -> Arc<Path> {
&self,
delegate: &Arc<dyn DapDelegate>,
) -> Result<Arc<Path>, String> {
self.debugpy_whl_base_path self.debugpy_whl_base_path
.get_or_init(|| async move { .get_or_init(|| async move {
Self::maybe_fetch_new_wheel(delegate).await; Self::maybe_fetch_new_wheel(delegate).await;
Ok(Arc::from( Arc::from(
debug_adapters_dir() debug_adapters_dir()
.join(Self::ADAPTER_NAME) .join(Self::ADAPTER_NAME)
.join("debugpy") .join("debugpy")
.join("adapter") .join("adapter")
.as_ref(), .as_ref(),
)) )
}) })
.await .await
.clone() .clone()
@ -704,10 +696,7 @@ impl DebugAdapter for PythonDebugAdapter {
) )
.await; .await;
let debugpy_path = self let debugpy_path = self.fetch_debugpy_whl(delegate).await;
.fetch_debugpy_whl(delegate)
.await
.map_err(|e| anyhow::anyhow!("{e}"))?;
if let Some(toolchain) = &toolchain { if let Some(toolchain) = &toolchain {
log::debug!( log::debug!(
"Found debugpy in toolchain environment: {}", "Found debugpy in toolchain environment: {}",

View file

@ -72,6 +72,7 @@ smol.workspace = true
snippet_provider.workspace = true snippet_provider.workspace = true
task.workspace = true task.workspace = true
tempfile.workspace = true tempfile.workspace = true
terminal.workspace = true
toml.workspace = true toml.workspace = true
tree-sitter = { workspace = true, optional = true } tree-sitter = { workspace = true, optional = true }
tree-sitter-bash = { workspace = true, optional = true } tree-sitter-bash = { workspace = true, optional = true }

View file

@ -1,4 +1,4 @@
use anyhow::{Context as _, ensure}; use anyhow::{Context as _, Error, ensure};
use anyhow::{Result, anyhow}; use anyhow::{Result, anyhow};
use async_trait::async_trait; use async_trait::async_trait;
use collections::HashMap; use collections::HashMap;
@ -22,6 +22,7 @@ use project::lsp_store::language_server_settings;
use serde_json::{Value, json}; use serde_json::{Value, json};
use smol::lock::OnceCell; use smol::lock::OnceCell;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::ffi::OsStr;
use parking_lot::Mutex; use parking_lot::Mutex;
use std::str::FromStr; use std::str::FromStr;
@ -335,36 +336,20 @@ impl LspAdapter for PythonLspAdapter {
} }
let object = user_settings.as_object_mut().unwrap(); let object = user_settings.as_object_mut().unwrap();
let interpreter_path = toolchain.path.to_string(); let interpreter_path = toolchain.path.as_ref();
// Detect if this is a virtual environment let (venv_path, venv) = detect_venv(&**adapter, interpreter_path);
if let Some(interpreter_dir) = Path::new(&interpreter_path).parent() { if let Some(venv) = venv {
if let Some(venv_dir) = interpreter_dir.parent() { object.insert(
// Check if this looks like a virtual environment "venv".to_owned(),
if venv_dir.join("pyvenv.cfg").exists() Value::String(venv.to_string_lossy().into_owned()),
|| venv_dir.join("bin/activate").exists() );
|| venv_dir.join("Scripts/activate.bat").exists() }
{ if let Some(venv_path) = venv_path {
// Set venvPath and venv at the root level object.insert(
// This matches the format of a pyrightconfig.json file "venvPath".to_string(),
if let Some(parent) = venv_dir.parent() { Value::String(venv_path.to_string_lossy().into_owned()),
// Use relative path if the venv is inside the workspace );
let venv_path = if parent == adapter.worktree_root_path() {
".".to_string()
} else {
parent.to_string_lossy().into_owned()
};
object.insert("venvPath".to_string(), Value::String(venv_path));
}
if let Some(venv_name) = venv_dir.file_name() {
object.insert(
"venv".to_owned(),
Value::String(venv_name.to_string_lossy().into_owned()),
);
}
}
}
} }
// Always set the python interpreter path // Always set the python interpreter path
@ -378,11 +363,11 @@ impl LspAdapter for PythonLspAdapter {
// Set both pythonPath and defaultInterpreterPath for compatibility // Set both pythonPath and defaultInterpreterPath for compatibility
python.insert( python.insert(
"pythonPath".to_owned(), "pythonPath".to_owned(),
Value::String(interpreter_path.clone()), Value::String(interpreter_path.to_owned()),
); );
python.insert( python.insert(
"defaultInterpreterPath".to_owned(), "defaultInterpreterPath".to_owned(),
Value::String(interpreter_path), Value::String(interpreter_path.to_owned()),
); );
} }
@ -967,7 +952,7 @@ impl pet_core::os_environment::Environment for EnvironmentApi<'_> {
} }
pub(crate) struct PyLspAdapter { pub(crate) struct PyLspAdapter {
python_venv_base: OnceCell<Result<Arc<Path>, String>>, python_venv_base: OnceCell<Result<Arc<Path>, Arc<Error>>>,
} }
impl PyLspAdapter { impl PyLspAdapter {
const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp"); const SERVER_NAME: LanguageServerName = LanguageServerName::new_static("pylsp");
@ -1009,13 +994,9 @@ impl PyLspAdapter {
None None
} }
async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> { async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, Arc<Error>> {
self.python_venv_base self.python_venv_base
.get_or_init(move || async move { .get_or_init(move || async move { Self::ensure_venv(delegate).await.map_err(Arc::new) })
Self::ensure_venv(delegate)
.await
.map_err(|e| format!("{e}"))
})
.await .await
.clone() .clone()
} }
@ -1027,6 +1008,12 @@ const BINARY_DIR: &str = if cfg!(target_os = "windows") {
"bin" "bin"
}; };
const ACTIVATE_PATH: &str = if cfg!(target_os = "windows") {
"Scripts/activate.bat"
} else {
"bin/activate"
};
#[async_trait(?Send)] #[async_trait(?Send)]
impl LspAdapter for PyLspAdapter { impl LspAdapter for PyLspAdapter {
fn name(&self) -> LanguageServerName { fn name(&self) -> LanguageServerName {
@ -1263,7 +1250,7 @@ impl LspAdapter for PyLspAdapter {
} }
pub(crate) struct BasedPyrightLspAdapter { pub(crate) struct BasedPyrightLspAdapter {
python_venv_base: OnceCell<Result<Arc<Path>, String>>, python_venv_base: OnceCell<Result<Arc<Path>, Arc<Error>>>,
} }
impl BasedPyrightLspAdapter { impl BasedPyrightLspAdapter {
@ -1310,13 +1297,9 @@ impl BasedPyrightLspAdapter {
None None
} }
async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, String> { async fn base_venv(&self, delegate: &dyn LspAdapterDelegate) -> Result<Arc<Path>, Arc<Error>> {
self.python_venv_base self.python_venv_base
.get_or_init(move || async move { .get_or_init(move || async move { Self::ensure_venv(delegate).await.map_err(Arc::new) })
Self::ensure_venv(delegate)
.await
.map_err(|e| format!("{e}"))
})
.await .await
.clone() .clone()
} }
@ -1523,36 +1506,20 @@ impl LspAdapter for BasedPyrightLspAdapter {
} }
let object = user_settings.as_object_mut().unwrap(); let object = user_settings.as_object_mut().unwrap();
let interpreter_path = toolchain.path.to_string(); let interpreter_path = toolchain.path.as_ref();
// Detect if this is a virtual environment let (venv_path, venv) = detect_venv(&**adapter, interpreter_path);
if let Some(interpreter_dir) = Path::new(&interpreter_path).parent() { if let Some(venv) = venv {
if let Some(venv_dir) = interpreter_dir.parent() { object.insert(
// Check if this looks like a virtual environment "venv".to_owned(),
if venv_dir.join("pyvenv.cfg").exists() Value::String(venv.to_string_lossy().into_owned()),
|| venv_dir.join("bin/activate").exists() );
|| venv_dir.join("Scripts/activate.bat").exists() }
{ if let Some(venv_path) = venv_path {
// Set venvPath and venv at the root level object.insert(
// This matches the format of a pyrightconfig.json file "venvPath".to_string(),
if let Some(parent) = venv_dir.parent() { Value::String(venv_path.to_string_lossy().into_owned()),
// Use relative path if the venv is inside the workspace );
let venv_path = if parent == adapter.worktree_root_path() {
".".to_string()
} else {
parent.to_string_lossy().into_owned()
};
object.insert("venvPath".to_string(), Value::String(venv_path));
}
if let Some(venv_name) = venv_dir.file_name() {
object.insert(
"venv".to_owned(),
Value::String(venv_name.to_string_lossy().into_owned()),
);
}
}
}
} }
// Always set the python interpreter path // Always set the python interpreter path
@ -1566,11 +1533,11 @@ impl LspAdapter for BasedPyrightLspAdapter {
// Set both pythonPath and defaultInterpreterPath for compatibility // Set both pythonPath and defaultInterpreterPath for compatibility
python.insert( python.insert(
"pythonPath".to_owned(), "pythonPath".to_owned(),
Value::String(interpreter_path.clone()), Value::String(interpreter_path.to_owned()),
); );
python.insert( python.insert(
"defaultInterpreterPath".to_owned(), "defaultInterpreterPath".to_owned(),
Value::String(interpreter_path), Value::String(interpreter_path.to_owned()),
); );
} }
@ -1583,6 +1550,38 @@ impl LspAdapter for BasedPyrightLspAdapter {
} }
} }
/// Detect if the interpreter path belongs to a virtual environment
fn detect_venv<'p>(
adapter: &dyn LspAdapterDelegate,
interpreter_path: &'p str,
) -> (Option<&'p Path>, Option<&'p OsStr>) {
let mut venv_path = None;
let mut venv = None;
// Detect if this is a virtual environment
if let Some(interpreter_dir) = Path::new(interpreter_path).parent() {
if let Some(venv_dir) = interpreter_dir.parent() {
// Check if this looks like a virtual environment
if venv_dir.join("pyvenv.cfg").exists() || venv_dir.join(ACTIVATE_PATH).exists() {
// Set venvPath and venv at the root level
// This matches the format of a pyrightconfig.json file
if let Some(parent) = venv_dir.parent() {
// Use relative path if the venv is inside the workspace
venv_path = Some(if parent == adapter.worktree_root_path() {
Path::new(".")
} else {
parent
});
}
if let Some(venv_name) = venv_dir.file_name() {
venv = Some(venv_name);
}
}
}
}
(venv_path, venv)
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext}; use gpui::{AppContext as _, BorrowAppContext, Context, TestAppContext};

View file

@ -287,7 +287,6 @@ impl DapStore {
.map(|command| (command, &binary.arguments)), .map(|command| (command, &binary.arguments)),
binary.cwd.as_deref(), binary.cwd.as_deref(),
binary.envs, binary.envs,
None,
path_style, path_style,
); );

View file

@ -1,7 +1,7 @@
use crate::{Project, ProjectPath}; use crate::{Project, ProjectPath};
use anyhow::{Context as _, Result}; use anyhow::Result;
use collections::HashMap; use collections::HashMap;
use gpui::{App, AppContext as _, Context, Entity, Task, WeakEntity}; use gpui::{App, AppContext as _, AsyncApp, Context, Entity, Task, WeakEntity};
use itertools::Itertools; use itertools::Itertools;
use language::LanguageName; use language::LanguageName;
use remote::ssh_session::SshArgs; use remote::ssh_session::SshArgs;
@ -9,7 +9,6 @@ use settings::{Settings, SettingsLocation};
use smol::channel::bounded; use smol::channel::bounded;
use std::{ use std::{
borrow::Cow, borrow::Cow,
env::{self},
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
}; };
@ -18,10 +17,7 @@ use terminal::{
TaskState, TaskStatus, Terminal, TerminalBuilder, TaskState, TaskStatus, Terminal, TerminalBuilder,
terminal_settings::{self, ActivateScript, TerminalSettings, VenvSettings}, terminal_settings::{self, ActivateScript, TerminalSettings, VenvSettings},
}; };
use util::{ use util::paths::{PathStyle, RemotePathBuf};
ResultExt,
paths::{PathStyle, RemotePathBuf},
};
pub struct Terminals { pub struct Terminals {
pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>, pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>,
@ -126,14 +122,104 @@ impl Project {
cx.spawn(async move |project, cx| { cx.spawn(async move |project, cx| {
let python_venv_directory = if let Some(path) = path { let python_venv_directory = if let Some(path) = path {
project match project.upgrade() {
.update(cx, |this, cx| this.python_venv_directory(path, venv, cx))? Some(project) => {
.await let venv_dir =
Self::python_venv_directory(project.clone(), path, venv.clone(), cx)
.await?;
match venv_dir {
Some(venv_dir)
if project
.update(cx, |project, cx| {
project.resolve_abs_path(
&venv_dir
.join(BINARY_DIR)
.join("activate")
.to_string_lossy(),
cx,
)
})?
.await
.is_some_and(|m| m.is_file()) =>
{
Some((venv_dir, venv))
}
_ => None,
}
}
None => None,
}
} else { } else {
None None
}; };
// todo lw: move all this out of here?
let startup_script = move |shell: &_| {
let Some((python_venv_directory, venv)) = &python_venv_directory else {
return None;
};
// todo: If this returns `None` we may don't have a venv, but we may still have a python toolchiain
// we should modify the PATH here still
let venv_settings = venv.as_option()?;
// todo: handle ssh!
let script_kind = if venv_settings.activate_script
== terminal_settings::ActivateScript::Default
{
match shell {
Shell::Program(program) => ActivateScript::by_shell(program),
Shell::WithArguments {
program,
args: _,
title_override: _,
} => ActivateScript::by_shell(program),
Shell::System => None,
}
} else {
Some(venv_settings.activate_script)
}
.or_else(|| ActivateScript::by_env());
let script_kind = match script_kind {
Some(activate) => activate,
None => ActivateScript::Default,
};
let activate_script_name = match script_kind {
terminal_settings::ActivateScript::Default
| terminal_settings::ActivateScript::Pyenv => "activate",
terminal_settings::ActivateScript::Csh => "activate.csh",
terminal_settings::ActivateScript::Fish => "activate.fish",
terminal_settings::ActivateScript::Nushell => "activate.nu",
terminal_settings::ActivateScript::PowerShell => "activate.ps1",
};
let activate_keyword = match script_kind {
terminal_settings::ActivateScript::Nushell => "overlay use",
terminal_settings::ActivateScript::PowerShell => ".",
terminal_settings::ActivateScript::Pyenv => "pyenv",
terminal_settings::ActivateScript::Default
| terminal_settings::ActivateScript::Csh
| terminal_settings::ActivateScript::Fish => "source",
};
let line_ending = if cfg!(windows) { '\r' } else { '\n' };
if venv_settings.venv_name.is_empty() {
let path = python_venv_directory
.join(BINARY_DIR)
.join(activate_script_name)
.to_string_lossy()
.to_string();
let quoted = shlex::try_quote(&path).ok()?;
Some(format!("{activate_keyword} {quoted}{line_ending}",))
} else {
Some(format!(
"{activate_keyword} {activate_script_name} {name}{line_ending}",
name = venv_settings.venv_name
))
}
};
project.update(cx, |project, cx| { project.update(cx, |project, cx| {
project.create_terminal_with_venv(kind, python_venv_directory, cx) project.create_terminal_with_startup(kind, startup_script, cx)
})? })?
}) })
} }
@ -182,7 +268,6 @@ impl Project {
Some((&command, &args)), Some((&command, &args)),
path.as_deref(), path.as_deref(),
env, env,
None,
path_style, path_style,
); );
let mut command = std::process::Command::new(command); let mut command = std::process::Command::new(command);
@ -204,10 +289,30 @@ impl Project {
} }
} }
pub fn create_terminal_with_venv( pub fn clone_terminal(
&mut self,
terminal: &Entity<Terminal>,
cx: &mut Context<Self>,
) -> Result<Entity<Terminal>> {
let terminal = terminal.read(cx);
let working_directory = terminal
.working_directory()
.or_else(|| Some(self.active_project_directory(cx)?.to_path_buf()));
let startup_script = terminal.startup_script.clone();
self.create_terminal_with_startup(
TerminalKind::Shell(working_directory),
|_| {
// The shell shouldn't change here
startup_script
},
cx,
)
}
pub fn create_terminal_with_startup(
&mut self, &mut self,
kind: TerminalKind, kind: TerminalKind,
python_venv_directory: Option<PathBuf>, startup_script: impl FnOnce(&Shell) -> Option<String> + 'static,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Result<Entity<Terminal>> { ) -> Result<Entity<Terminal>> {
let this = &mut *self; let this = &mut *self;
@ -256,19 +361,8 @@ impl Project {
let local_path = if is_ssh_terminal { None } else { path.clone() }; let local_path = if is_ssh_terminal { None } else { path.clone() };
let mut python_venv_activate_command = Task::ready(None);
let (spawn_task, shell) = match kind { let (spawn_task, shell) = match kind {
TerminalKind::Shell(_) => { TerminalKind::Shell(_) => {
if let Some(python_venv_directory) = &python_venv_directory {
python_venv_activate_command = this.python_activate_command(
python_venv_directory,
&settings.detect_venv,
&settings.shell,
cx,
);
}
match ssh_details { match ssh_details {
Some(SshDetails { Some(SshDetails {
host, host,
@ -285,14 +379,8 @@ impl Project {
env.entry("TERM".to_string()) env.entry("TERM".to_string())
.or_insert_with(|| "xterm-256color".to_string()); .or_insert_with(|| "xterm-256color".to_string());
let (program, args) = wrap_for_ssh( let (program, args) =
&ssh_command, wrap_for_ssh(&ssh_command, None, path.as_deref(), env, path_style);
None,
path.as_deref(),
env,
None,
path_style,
);
env = HashMap::default(); env = HashMap::default();
if let Some(envs) = envs { if let Some(envs) = envs {
env.extend(envs); env.extend(envs);
@ -325,13 +413,6 @@ impl Project {
env.extend(spawn_task.env); env.extend(spawn_task.env);
if let Some(venv_path) = &python_venv_directory {
env.insert(
"VIRTUAL_ENV".to_string(),
venv_path.to_string_lossy().to_string(),
);
}
match ssh_details { match ssh_details {
Some(SshDetails { Some(SshDetails {
host, host,
@ -342,6 +423,7 @@ impl Project {
log::debug!("Connecting to a remote server: {ssh_command:?}"); log::debug!("Connecting to a remote server: {ssh_command:?}");
env.entry("TERM".to_string()) env.entry("TERM".to_string())
.or_insert_with(|| "xterm-256color".to_string()); .or_insert_with(|| "xterm-256color".to_string());
let (program, args) = wrap_for_ssh( let (program, args) = wrap_for_ssh(
&ssh_command, &ssh_command,
spawn_task spawn_task
@ -350,7 +432,6 @@ impl Project {
.map(|command| (command, &spawn_task.args)), .map(|command| (command, &spawn_task.args)),
path.as_deref(), path.as_deref(),
env, env,
python_venv_directory.as_deref(),
path_style, path_style,
); );
env = HashMap::default(); env = HashMap::default();
@ -367,10 +448,6 @@ impl Project {
) )
} }
None => { None => {
if let Some(venv_path) = &python_venv_directory {
add_environment_path(&mut env, &venv_path.join("bin")).log_err();
}
let shell = if let Some(program) = spawn_task.command { let shell = if let Some(program) = spawn_task.command {
Shell::WithArguments { Shell::WithArguments {
program, program,
@ -385,9 +462,11 @@ impl Project {
} }
} }
}; };
let startup_script = startup_script(&shell);
TerminalBuilder::new( TerminalBuilder::new(
local_path.map(|path| path.to_path_buf()), local_path.map(|path| path.to_path_buf()),
python_venv_directory, startup_script,
spawn_task, spawn_task,
shell, shell,
env, env,
@ -420,220 +499,92 @@ impl Project {
}) })
.detach(); .detach();
this.activate_python_virtual_environment(
python_venv_activate_command,
&terminal_handle,
cx,
);
terminal_handle terminal_handle
}) })
} }
fn python_venv_directory( async fn python_venv_directory(
&self, this: Entity<Self>,
abs_path: Arc<Path>, abs_path: Arc<Path>,
venv_settings: VenvSettings, venv_settings: VenvSettings,
cx: &Context<Project>, cx: &mut AsyncApp,
) -> Task<Option<PathBuf>> { ) -> Result<Option<PathBuf>> {
cx.spawn(async move |this, cx| { let Some((worktree, relative_path)) =
if let Some((worktree, relative_path)) = this this.update(cx, |this, cx| this.find_worktree(&abs_path, cx))?
.update(cx, |this, cx| this.find_worktree(&abs_path, cx)) else {
.ok()? return Ok(None);
{
let toolchain = this
.update(cx, |this, cx| {
this.active_toolchain(
ProjectPath {
worktree_id: worktree.read(cx).id(),
path: relative_path.into(),
},
LanguageName::new("Python"),
cx,
)
})
.ok()?
.await;
if let Some(toolchain) = toolchain {
let toolchain_path = Path::new(toolchain.path.as_ref());
return Some(toolchain_path.parent()?.parent()?.to_path_buf());
}
}
let venv_settings = venv_settings.as_option()?;
this.update(cx, move |this, cx| {
if let Some(path) = this.find_venv_in_worktree(&abs_path, &venv_settings, cx) {
return Some(path);
}
this.find_venv_on_filesystem(&abs_path, &venv_settings, cx)
})
.ok()
.flatten()
})
}
fn find_venv_in_worktree(
&self,
abs_path: &Path,
venv_settings: &terminal_settings::VenvSettingsContent,
cx: &App,
) -> Option<PathBuf> {
let bin_dir_name = match std::env::consts::OS {
"windows" => "Scripts",
_ => "bin",
}; };
venv_settings let toolchain = this
.directories .update(cx, |this, cx| {
.iter() this.active_toolchain(
.map(|name| abs_path.join(name)) ProjectPath {
.find(|venv_path| { worktree_id: worktree.read(cx).id(),
let bin_path = venv_path.join(bin_dir_name); path: relative_path.into(),
self.find_worktree(&bin_path, cx) },
.and_then(|(worktree, relative_path)| { LanguageName::new("Python"),
worktree.read(cx).entry_for_path(&relative_path) cx,
}) )
.is_some_and(|entry| entry.is_dir()) })?
}) .await;
}
fn find_venv_on_filesystem( if let Some(toolchain) = toolchain {
&self, let toolchain_path = Path::new(toolchain.path.as_ref());
abs_path: &Path, return Ok(toolchain_path
venv_settings: &terminal_settings::VenvSettingsContent, .parent()
cx: &App, .and_then(|p| Some(p.parent()?.to_path_buf())));
) -> Option<PathBuf> {
let (worktree, _) = self.find_worktree(abs_path, cx)?;
let fs = worktree.read(cx).as_local()?.fs();
let bin_dir_name = match std::env::consts::OS {
"windows" => "Scripts",
_ => "bin",
};
venv_settings
.directories
.iter()
.map(|name| abs_path.join(name))
.find(|venv_path| {
let bin_path = venv_path.join(bin_dir_name);
// One-time synchronous check is acceptable for terminal/task initialization
smol::block_on(fs.metadata(&bin_path))
.ok()
.flatten()
.map_or(false, |meta| meta.is_dir)
})
}
fn activate_script_kind(shell: Option<&str>) -> ActivateScript {
let shell_env = std::env::var("SHELL").ok();
let shell_path = shell.or_else(|| shell_env.as_deref());
let shell = std::path::Path::new(shell_path.unwrap_or(""))
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("");
match shell {
"fish" => ActivateScript::Fish,
"tcsh" => ActivateScript::Csh,
"nu" => ActivateScript::Nushell,
"powershell" | "pwsh" => ActivateScript::PowerShell,
_ => ActivateScript::Default,
} }
}
fn python_activate_command(
&self,
venv_base_directory: &Path,
venv_settings: &VenvSettings,
shell: &Shell,
cx: &mut App,
) -> Task<Option<String>> {
let Some(venv_settings) = venv_settings.as_option() else { let Some(venv_settings) = venv_settings.as_option() else {
return Task::ready(None); return Ok(None);
};
let activate_keyword = match venv_settings.activate_script {
terminal_settings::ActivateScript::Default => match std::env::consts::OS {
"windows" => ".",
_ => ".",
},
terminal_settings::ActivateScript::Nushell => "overlay use",
terminal_settings::ActivateScript::PowerShell => ".",
terminal_settings::ActivateScript::Pyenv => "pyenv",
_ => "source",
};
let script_kind =
if venv_settings.activate_script == terminal_settings::ActivateScript::Default {
match shell {
Shell::Program(program) => Self::activate_script_kind(Some(program)),
Shell::WithArguments {
program,
args: _,
title_override: _,
} => Self::activate_script_kind(Some(program)),
Shell::System => Self::activate_script_kind(None),
}
} else {
venv_settings.activate_script
};
let activate_script_name = match script_kind {
terminal_settings::ActivateScript::Default
| terminal_settings::ActivateScript::Pyenv => "activate",
terminal_settings::ActivateScript::Csh => "activate.csh",
terminal_settings::ActivateScript::Fish => "activate.fish",
terminal_settings::ActivateScript::Nushell => "activate.nu",
terminal_settings::ActivateScript::PowerShell => "activate.ps1",
}; };
let line_ending = match std::env::consts::OS { let tool = this.update(cx, |this, cx| {
"windows" => "\r", venv_settings
_ => "\n", .directories
}; .iter()
.map(|name| abs_path.join(name))
if venv_settings.venv_name.is_empty() { .find(|venv_path| {
let path = venv_base_directory let bin_path = venv_path.join(BINARY_DIR);
.join(match std::env::consts::OS { this.find_worktree(&bin_path, cx)
"windows" => "Scripts", .and_then(|(worktree, relative_path)| {
_ => "bin", worktree.read(cx).entry_for_path(&relative_path)
})
.is_some_and(|entry| entry.is_dir())
}) })
.join(activate_script_name) })?;
.to_string_lossy()
.to_string();
let is_valid_path = self.resolve_abs_path(path.as_ref(), cx); if let Some(toolchain_path) = tool {
cx.background_spawn(async move { return Ok(Some(toolchain_path));
let quoted = shlex::try_quote(&path).ok()?;
if is_valid_path.await.is_some_and(|meta| meta.is_file()) {
Some(format!(
"{} {} ; clear{}",
activate_keyword, quoted, line_ending
))
} else {
None
}
})
} else {
Task::ready(Some(format!(
"{activate_keyword} {activate_script_name} {name}; clear{line_ending}",
name = venv_settings.venv_name
)))
} }
}
fn activate_python_virtual_environment( let r = this.update(cx, move |_, cx| {
&self, let map: Vec<_> = venv_settings
command: Task<Option<String>>, .directories
terminal_handle: &Entity<Terminal>, .iter()
cx: &mut App, .map(|name| abs_path.join(name))
) { .collect();
terminal_handle.update(cx, |_, cx| { Some(cx.spawn(async move |project, cx| {
cx.spawn(async move |this, cx| { for venv_path in map {
if let Some(command) = command.await { let bin_path = venv_path.join(BINARY_DIR);
this.update(cx, |this, _| { let exists = project
this.input(command.into_bytes()); .upgrade()?
}) .update(cx, |project, cx| {
.ok(); project.resolve_abs_path(&bin_path.to_string_lossy(), cx)
})
.ok()?
.await
.map_or(false, |meta| meta.is_dir());
if exists {
return Some(venv_path);
}
} }
}) None
.detach() }))
}); })?;
Ok(match r {
Some(task) => task.await,
None => None,
})
} }
pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> { pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> {
@ -641,12 +592,17 @@ impl Project {
} }
} }
const BINARY_DIR: &str = if cfg!(target_os = "windows") {
"Scripts"
} else {
"bin"
};
pub fn wrap_for_ssh( pub fn wrap_for_ssh(
ssh_command: &SshCommand, ssh_command: &SshCommand,
command: Option<(&String, &Vec<String>)>, command: Option<(&String, &Vec<String>)>,
path: Option<&Path>, path: Option<&Path>,
env: HashMap<String, String>, env: HashMap<String, String>,
venv_directory: Option<&Path>,
path_style: PathStyle, path_style: PathStyle,
) -> (String, Vec<String>) { ) -> (String, Vec<String>) {
let to_run = if let Some((command, args)) = command { let to_run = if let Some((command, args)) = command {
@ -665,13 +621,7 @@ pub fn wrap_for_ssh(
let mut env_changes = String::new(); let mut env_changes = String::new();
for (k, v) in env.iter() { for (k, v) in env.iter() {
if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) { if let Some((k, v)) = shlex::try_quote(k).ok().zip(shlex::try_quote(v).ok()) {
env_changes.push_str(&format!("{}={} ", k, v)); env_changes.push_str(&format!("{k}={v} "));
}
}
if let Some(venv_directory) = venv_directory {
if let Ok(str) = shlex::try_quote(venv_directory.to_string_lossy().as_ref()) {
let path = RemotePathBuf::new(PathBuf::from(str.to_string()), path_style).to_string();
env_changes.push_str(&format!("PATH={}:$PATH ", path));
} }
} }
@ -702,57 +652,3 @@ pub fn wrap_for_ssh(
args.push(shell_invocation); args.push(shell_invocation);
(program, args) (program, args)
} }
fn add_environment_path(env: &mut HashMap<String, String>, new_path: &Path) -> Result<()> {
let mut env_paths = vec![new_path.to_path_buf()];
if let Some(path) = env.get("PATH").or(env::var("PATH").ok().as_ref()) {
let mut paths = std::env::split_paths(&path).collect::<Vec<_>>();
env_paths.append(&mut paths);
}
let paths = std::env::join_paths(env_paths).context("failed to create PATH env variable")?;
env.insert("PATH".to_string(), paths.to_string_lossy().to_string());
Ok(())
}
#[cfg(test)]
mod tests {
use collections::HashMap;
#[test]
fn test_add_environment_path_with_existing_path() {
let tmp_path = std::path::PathBuf::from("/tmp/new");
let mut env = HashMap::default();
let old_path = if cfg!(windows) {
"/usr/bin;/usr/local/bin"
} else {
"/usr/bin:/usr/local/bin"
};
env.insert("PATH".to_string(), old_path.to_string());
env.insert("OTHER".to_string(), "aaa".to_string());
super::add_environment_path(&mut env, &tmp_path).unwrap();
if cfg!(windows) {
assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", old_path));
} else {
assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", old_path));
}
assert_eq!(env.get("OTHER").unwrap(), "aaa");
}
#[test]
fn test_add_environment_path_with_empty_path() {
let tmp_path = std::path::PathBuf::from("/tmp/new");
let mut env = HashMap::default();
env.insert("OTHER".to_string(), "aaa".to_string());
let os_path = std::env::var("PATH").unwrap();
super::add_environment_path(&mut env, &tmp_path).unwrap();
if cfg!(windows) {
assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new;{}", os_path));
} else {
assert_eq!(env.get("PATH").unwrap(), &format!("/tmp/new:{}", os_path));
}
assert_eq!(env.get("OTHER").unwrap(), "aaa");
}
}

View file

@ -344,7 +344,7 @@ pub struct TerminalBuilder {
impl TerminalBuilder { impl TerminalBuilder {
pub fn new( pub fn new(
working_directory: Option<PathBuf>, working_directory: Option<PathBuf>,
python_venv_directory: Option<PathBuf>, startup_script: Option<String>,
task: Option<TaskState>, task: Option<TaskState>,
shell: Shell, shell: Shell,
mut env: HashMap<String, String>, mut env: HashMap<String, String>,
@ -432,9 +432,6 @@ impl TerminalBuilder {
} }
}; };
// Setup Alacritty's env, which modifies the current process's environment
alacritty_terminal::tty::setup_env();
let default_cursor_style = AlacCursorStyle::from(cursor_shape); let default_cursor_style = AlacCursorStyle::from(cursor_shape);
let scrolling_history = if task.is_some() { let scrolling_history = if task.is_some() {
// Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling. // Tasks like `cargo build --all` may produce a lot of output, ergo allow maximum scrolling.
@ -495,8 +492,8 @@ impl TerminalBuilder {
//Kick things off //Kick things off
let pty_tx = event_loop.channel(); let pty_tx = event_loop.channel();
let _io_thread = event_loop.spawn(); // DANGER let _io_thread = event_loop.spawn(); // DANGER
let activate = startup_script.clone();
let terminal = Terminal { let mut terminal = Terminal {
task, task,
pty_tx: Notifier(pty_tx), pty_tx: Notifier(pty_tx),
completion_tx, completion_tx,
@ -517,13 +514,17 @@ impl TerminalBuilder {
hyperlink_regex_searches: RegexSearches::new(), hyperlink_regex_searches: RegexSearches::new(),
vi_mode_enabled: false, vi_mode_enabled: false,
is_ssh_terminal, is_ssh_terminal,
python_venv_directory, startup_script,
last_mouse_move_time: Instant::now(), last_mouse_move_time: Instant::now(),
last_hyperlink_search_position: None, last_hyperlink_search_position: None,
#[cfg(windows)] #[cfg(windows)]
shell_program, shell_program,
}; };
if let Some(activate) = activate {
terminal.input(activate.into_bytes());
}
Ok(TerminalBuilder { Ok(TerminalBuilder {
terminal, terminal,
events_rx, events_rx,
@ -687,6 +688,8 @@ pub struct Terminal {
term: Arc<FairMutex<Term<ZedListener>>>, term: Arc<FairMutex<Term<ZedListener>>>,
term_config: Config, term_config: Config,
events: VecDeque<InternalEvent>, events: VecDeque<InternalEvent>,
// TODO lw: type this better
pub startup_script: Option<String>,
/// This is only used for mouse mode cell change detection /// This is only used for mouse mode cell change detection
last_mouse: Option<(AlacPoint, AlacDirection)>, last_mouse: Option<(AlacPoint, AlacDirection)>,
pub matches: Vec<RangeInclusive<AlacPoint>>, pub matches: Vec<RangeInclusive<AlacPoint>>,
@ -695,7 +698,6 @@ pub struct Terminal {
pub breadcrumb_text: String, pub breadcrumb_text: String,
pub pty_info: PtyProcessInfo, pub pty_info: PtyProcessInfo,
title_override: Option<SharedString>, title_override: Option<SharedString>,
pub python_venv_directory: Option<PathBuf>,
scroll_px: Pixels, scroll_px: Pixels,
next_link_id: usize, next_link_id: usize,
selection_phase: SelectionPhase, selection_phase: SelectionPhase,

View file

@ -135,6 +135,27 @@ pub enum ActivateScript {
Pyenv, Pyenv,
} }
impl ActivateScript {
pub fn by_shell(shell: &str) -> Option<Self> {
Some(match shell {
"fish" => ActivateScript::Fish,
"tcsh" => ActivateScript::Csh,
"nu" => ActivateScript::Nushell,
"powershell" | "pwsh" => ActivateScript::PowerShell,
"sh" => ActivateScript::Default,
_ => return None,
})
}
pub fn by_env() -> Option<Self> {
let shell = std::env::var("SHELL").ok()?;
let shell = std::path::Path::new(&shell)
.file_name()
.and_then(|name| name.to_str())?;
Self::by_shell(shell)
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct TerminalSettingsContent { pub struct TerminalSettingsContent {
/// What shell to use when opening a terminal. /// What shell to use when opening a terminal.

View file

@ -416,25 +416,18 @@ impl TerminalPanel {
let database_id = workspace.database_id(); let database_id = workspace.database_id();
let weak_workspace = self.workspace.clone(); let weak_workspace = self.workspace.clone();
let project = workspace.project().clone(); let project = workspace.project().clone();
let (working_directory, python_venv_directory) = self let terminal = self
.active_pane .active_pane
.read(cx) .read(cx)
.active_item() .active_item()
.and_then(|item| item.downcast::<TerminalView>()) .and_then(|item| item.downcast::<TerminalView>())
.map(|terminal_view| { .map(|terminal_view| terminal_view.read(cx).terminal().clone());
let terminal = terminal_view.read(cx).terminal().read(cx);
(
terminal
.working_directory()
.or_else(|| default_working_directory(workspace, cx)),
terminal.python_venv_directory.clone(),
)
})
.unwrap_or((None, None));
let kind = TerminalKind::Shell(working_directory);
let terminal = project let terminal = project
.update(cx, |project, cx| { .update(cx, |project, cx| match terminal {
project.create_terminal_with_venv(kind, python_venv_directory, cx) Some(terminal) => project.clone_terminal(&terminal, cx),
None => {
project.create_terminal_with_startup(TerminalKind::Shell(None), |_| None, cx)
}
}) })
.ok()?; .ok()?;

View file

@ -1668,16 +1668,7 @@ impl Item for TerminalView {
let terminal = self let terminal = self
.project .project
.update(cx, |project, cx| { .update(cx, |project, cx| {
let terminal = self.terminal().read(cx); project.clone_terminal(self.terminal(), cx)
let working_directory = terminal
.working_directory()
.or_else(|| Some(project.active_project_directory(cx)?.to_path_buf()));
let python_venv_directory = terminal.python_venv_directory.clone();
project.create_terminal_with_venv(
TerminalKind::Shell(working_directory),
python_venv_directory,
cx,
)
}) })
.ok()? .ok()?
.log_err()?; .log_err()?;