Inject venv environment via the toolchain (#36576)

Instead of manually constructing the venv we now ask the python
toolchain for the relevant information, unifying the approach of vent
inspection

Fixes https://github.com/zed-industries/zed/issues/27350

Release Notes:

- Improved the detection of python virtual environments for terminals
and tasks in remote projects.
This commit is contained in:
Lukas Wirth 2025-08-28 16:40:43 +02:00 committed by GitHub
parent 24ee98b3e1
commit 835e5ba662
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 725 additions and 672 deletions

View file

@ -2,7 +2,7 @@ use agent_client_protocol as acp;
use anyhow::Result; use anyhow::Result;
use futures::{FutureExt as _, future::Shared}; use futures::{FutureExt as _, future::Shared};
use gpui::{App, AppContext, Entity, SharedString, Task}; use gpui::{App, AppContext, Entity, SharedString, Task};
use project::{Project, terminals::TerminalKind}; use project::Project;
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{ use std::{
@ -144,14 +144,14 @@ impl AgentTool for TerminalTool {
let terminal = self let terminal = self
.project .project
.update(cx, |project, cx| { .update(cx, |project, cx| {
project.create_terminal( project.create_terminal_task(
TerminalKind::Task(task::SpawnInTerminal { task::SpawnInTerminal {
command: Some(program), command: Some(program),
args, args,
cwd: working_dir.clone(), cwd: working_dir.clone(),
env, env,
..Default::default() ..Default::default()
}), },
cx, cx,
) )
})? })?

View file

@ -15,7 +15,7 @@ use language::LineEnding;
use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat}; use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
use markdown::{Markdown, MarkdownElement, MarkdownStyle}; use markdown::{Markdown, MarkdownElement, MarkdownStyle};
use portable_pty::{CommandBuilder, PtySize, native_pty_system}; use portable_pty::{CommandBuilder, PtySize, native_pty_system};
use project::{Project, terminals::TerminalKind}; use project::Project;
use schemars::JsonSchema; use schemars::JsonSchema;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use settings::Settings; use settings::Settings;
@ -213,17 +213,16 @@ impl Tool for TerminalTool {
async move |cx| { async move |cx| {
let program = program.await; let program = program.await;
let env = env.await; let env = env.await;
project project
.update(cx, |project, cx| { .update(cx, |project, cx| {
project.create_terminal( project.create_terminal_task(
TerminalKind::Task(task::SpawnInTerminal { task::SpawnInTerminal {
command: Some(program), command: Some(program),
args, args,
cwd, cwd,
env, env,
..Default::default() ..Default::default()
}), },
cx, cx,
) )
})? })?

View file

@ -36,7 +36,6 @@ use module_list::ModuleList;
use project::{ use project::{
DebugScenarioContext, Project, WorktreeId, DebugScenarioContext, Project, WorktreeId,
debugger::session::{self, Session, SessionEvent, SessionStateEvent, ThreadId, ThreadStatus}, debugger::session::{self, Session, SessionEvent, SessionStateEvent, ThreadId, ThreadStatus},
terminals::TerminalKind,
}; };
use rpc::proto::ViewId; use rpc::proto::ViewId;
use serde_json::Value; use serde_json::Value;
@ -1040,12 +1039,11 @@ impl RunningState {
}; };
let terminal = project let terminal = project
.update(cx, |project, cx| { .update(cx, |project, cx| {
project.create_terminal( project.create_terminal_task(
TerminalKind::Task(task_with_shell.clone()), task_with_shell.clone(),
cx, cx,
) )
})? })?.await?;
.await?;
let terminal_view = cx.new_window_entity(|window, cx| { let terminal_view = cx.new_window_entity(|window, cx| {
TerminalView::new( TerminalView::new(
@ -1189,7 +1187,7 @@ impl RunningState {
.filter(|title| !title.is_empty()) .filter(|title| !title.is_empty())
.or_else(|| command.clone()) .or_else(|| command.clone())
.unwrap_or_else(|| "Debug terminal".to_string()); .unwrap_or_else(|| "Debug terminal".to_string());
let kind = TerminalKind::Task(task::SpawnInTerminal { let kind = task::SpawnInTerminal {
id: task::TaskId("debug".to_string()), id: task::TaskId("debug".to_string()),
full_label: title.clone(), full_label: title.clone(),
label: title.clone(), label: title.clone(),
@ -1207,12 +1205,13 @@ impl RunningState {
show_summary: false, show_summary: false,
show_command: false, show_command: false,
show_rerun: false, show_rerun: false,
}); };
let workspace = self.workspace.clone(); let workspace = self.workspace.clone();
let weak_project = project.downgrade(); let weak_project = project.downgrade();
let terminal_task = project.update(cx, |project, cx| project.create_terminal(kind, cx)); let terminal_task =
project.update(cx, |project, cx| project.create_terminal_task(kind, cx));
let terminal_task = cx.spawn_in(window, async move |_, cx| { let terminal_task = cx.spawn_in(window, async move |_, cx| {
let terminal = terminal_task.await?; let terminal = terminal_task.await?;

View file

@ -11,13 +11,14 @@ use std::{
use async_trait::async_trait; use async_trait::async_trait;
use collections::HashMap; use collections::HashMap;
use fs::Fs;
use gpui::{AsyncApp, SharedString}; use gpui::{AsyncApp, SharedString};
use settings::WorktreeId; use settings::WorktreeId;
use crate::{LanguageName, ManifestName}; use crate::{LanguageName, ManifestName};
/// Represents a single toolchain. /// Represents a single toolchain.
#[derive(Clone, Debug, Eq)] #[derive(Clone, Eq, Debug)]
pub struct Toolchain { pub struct Toolchain {
/// User-facing label /// User-facing label
pub name: SharedString, pub name: SharedString,
@ -29,21 +30,29 @@ pub struct Toolchain {
impl std::hash::Hash for Toolchain { impl std::hash::Hash for Toolchain {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) { fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.name.hash(state); let Self {
self.path.hash(state); name,
self.language_name.hash(state); path,
language_name,
as_json: _,
} = self;
name.hash(state);
path.hash(state);
language_name.hash(state);
} }
} }
impl PartialEq for Toolchain { impl PartialEq for Toolchain {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
let Self {
name,
path,
language_name,
as_json: _,
} = self;
// Do not use as_json for comparisons; it shouldn't impact equality, as it's not user-surfaced. // Do not use as_json for comparisons; it shouldn't impact equality, as it's not user-surfaced.
// Thus, there could be multiple entries that look the same in the UI. // Thus, there could be multiple entries that look the same in the UI.
(&self.name, &self.path, &self.language_name).eq(&( (name, path, language_name).eq(&(&other.name, &other.path, &other.language_name))
&other.name,
&other.path,
&other.language_name,
))
} }
} }
@ -59,6 +68,7 @@ pub trait ToolchainLister: Send + Sync {
fn term(&self) -> SharedString; fn term(&self) -> SharedString;
/// Returns the name of the manifest file for this toolchain. /// Returns the name of the manifest file for this toolchain.
fn manifest_name(&self) -> ManifestName; fn manifest_name(&self) -> ManifestName;
async fn activation_script(&self, toolchain: &Toolchain, fs: &dyn Fs) -> Option<String>;
} }
#[async_trait(?Send)] #[async_trait(?Send)]
@ -82,7 +92,7 @@ pub trait LocalLanguageToolchainStore: Send + Sync + 'static {
) -> Option<Toolchain>; ) -> Option<Toolchain>;
} }
#[async_trait(?Send )] #[async_trait(?Send)]
impl<T: LocalLanguageToolchainStore> LanguageToolchainStore for T { impl<T: LocalLanguageToolchainStore> LanguageToolchainStore for T {
async fn active_toolchain( async fn active_toolchain(
self: Arc<Self>, self: Arc<Self>,

View file

@ -2,6 +2,7 @@ use anyhow::{Context as _, 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;
use futures::AsyncBufReadExt;
use gpui::{App, Task}; use gpui::{App, Task};
use gpui::{AsyncApp, SharedString}; use gpui::{AsyncApp, SharedString};
use language::Toolchain; use language::Toolchain;
@ -30,8 +31,6 @@ use std::{
borrow::Cow, borrow::Cow,
ffi::OsString, ffi::OsString,
fmt::Write, fmt::Write,
fs,
io::{self, BufRead},
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
}; };
@ -741,14 +740,16 @@ fn env_priority(kind: Option<PythonEnvironmentKind>) -> usize {
/// Return the name of environment declared in <worktree-root/.venv. /// Return the name of environment declared in <worktree-root/.venv.
/// ///
/// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation /// https://virtualfish.readthedocs.io/en/latest/plugins.html#auto-activation-auto-activation
fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> { async fn get_worktree_venv_declaration(worktree_root: &Path) -> Option<String> {
fs::File::open(worktree_root.join(".venv")) let file = async_fs::File::open(worktree_root.join(".venv"))
.and_then(|file| { .await
let mut venv_name = String::new(); .ok()?;
io::BufReader::new(file).read_line(&mut venv_name)?; let mut venv_name = String::new();
Ok(venv_name.trim().to_string()) smol::io::BufReader::new(file)
}) .read_line(&mut venv_name)
.ok() .await
.ok()?;
Some(venv_name.trim().to_string())
} }
#[async_trait] #[async_trait]
@ -793,7 +794,7 @@ impl ToolchainLister for PythonToolchainProvider {
.map_or(Vec::new(), |mut guard| std::mem::take(&mut guard)); .map_or(Vec::new(), |mut guard| std::mem::take(&mut guard));
let wr = worktree_root; let wr = worktree_root;
let wr_venv = get_worktree_venv_declaration(&wr); let wr_venv = get_worktree_venv_declaration(&wr).await;
// Sort detected environments by: // Sort detected environments by:
// environment name matching activation file (<workdir>/.venv) // environment name matching activation file (<workdir>/.venv)
// environment project dir matching worktree_root // environment project dir matching worktree_root
@ -858,7 +859,7 @@ impl ToolchainLister for PythonToolchainProvider {
.into_iter() .into_iter()
.filter_map(|toolchain| { .filter_map(|toolchain| {
let mut name = String::from("Python"); let mut name = String::from("Python");
if let Some(ref version) = toolchain.version { if let Some(version) = &toolchain.version {
_ = write!(name, " {version}"); _ = write!(name, " {version}");
} }
@ -879,7 +880,7 @@ impl ToolchainLister for PythonToolchainProvider {
name: name.into(), name: name.into(),
path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(), path: toolchain.executable.as_ref()?.to_str()?.to_owned().into(),
language_name: LanguageName::new("Python"), language_name: LanguageName::new("Python"),
as_json: serde_json::to_value(toolchain).ok()?, as_json: serde_json::to_value(toolchain.clone()).ok()?,
}) })
}) })
.collect(); .collect();
@ -893,6 +894,23 @@ impl ToolchainLister for PythonToolchainProvider {
fn term(&self) -> SharedString { fn term(&self) -> SharedString {
self.term.clone() self.term.clone()
} }
async fn activation_script(&self, toolchain: &Toolchain, fs: &dyn Fs) -> Option<String> {
let toolchain = serde_json::from_value::<pet_core::python_environment::PythonEnvironment>(
toolchain.as_json.clone(),
)
.ok()?;
let mut activation_script = None;
if let Some(prefix) = &toolchain.prefix {
#[cfg(not(target_os = "windows"))]
let path = prefix.join(BINARY_DIR).join("activate");
#[cfg(target_os = "windows")]
let path = prefix.join(BINARY_DIR).join("activate.ps1");
if fs.is_file(&path).await {
activation_script = Some(format!(". {}", path.display()));
}
}
activation_script
}
} }
pub struct EnvironmentApi<'a> { pub struct EnvironmentApi<'a> {

View file

@ -276,6 +276,7 @@ impl DapStore {
&binary.arguments, &binary.arguments,
&binary.envs, &binary.envs,
binary.cwd.map(|path| path.display().to_string()), binary.cwd.map(|path| path.display().to_string()),
None,
port_forwarding, port_forwarding,
) )
})??; })??;

View file

@ -9222,6 +9222,9 @@ fn python_lang(fs: Arc<FakeFs>) -> Arc<Language> {
fn manifest_name(&self) -> ManifestName { fn manifest_name(&self) -> ManifestName {
SharedString::new_static("pyproject.toml").into() SharedString::new_static("pyproject.toml").into()
} }
async fn activation_script(&self, _: &Toolchain, _: &dyn Fs) -> Option<String> {
None
}
} }
Arc::new( Arc::new(
Language::new( Language::new(

View file

@ -1,44 +1,28 @@
use crate::{Project, ProjectPath}; use anyhow::Result;
use anyhow::{Context as _, Result};
use collections::HashMap; use collections::HashMap;
use gpui::{App, AppContext as _, Context, Entity, Task, WeakEntity}; use gpui::{App, AppContext as _, Context, Entity, Task, WeakEntity};
use itertools::Itertools;
use language::LanguageName; use language::LanguageName;
use remote::RemoteClient; use remote::RemoteClient;
use settings::{Settings, SettingsLocation}; use settings::{Settings, SettingsLocation};
use smol::channel::bounded; use smol::channel::bounded;
use std::{ use std::{
env::{self}, borrow::Cow,
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::Arc,
}; };
use task::{Shell, ShellBuilder, SpawnInTerminal}; use task::{Shell, ShellBuilder, SpawnInTerminal};
use terminal::{ use terminal::{
TaskState, TaskStatus, Terminal, TerminalBuilder, TaskState, TaskStatus, Terminal, TerminalBuilder, terminal_settings::TerminalSettings,
terminal_settings::{self, ActivateScript, TerminalSettings, VenvSettings},
}; };
use util::{ResultExt, paths::RemotePathBuf}; use util::{get_default_system_shell, get_system_shell, maybe};
/// The directory inside a Python virtual environment that contains executables use crate::{Project, ProjectPath};
const PYTHON_VENV_BIN_DIR: &str = if cfg!(target_os = "windows") {
"Scripts"
} else {
"bin"
};
pub struct Terminals { pub struct Terminals {
pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>, pub(crate) local_handles: Vec<WeakEntity<terminal::Terminal>>,
} }
/// Terminals are opened either for the users shell, or to run a task.
#[derive(Debug)]
pub enum TerminalKind {
/// Run a shell at the given path (or $HOME if None)
Shell(Option<PathBuf>),
/// Run a task.
Task(SpawnInTerminal),
}
impl Project { impl Project {
pub fn active_project_directory(&self, cx: &App) -> Option<Arc<Path>> { pub fn active_project_directory(&self, cx: &App) -> Option<Arc<Path>> {
self.active_entry() self.active_entry()
@ -58,20 +42,31 @@ impl Project {
} }
} }
pub fn create_terminal( pub fn create_terminal_task(
&mut self, &mut self,
kind: TerminalKind, spawn_task: SpawnInTerminal,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Task<Result<Entity<Terminal>>> { ) -> Task<Result<Entity<Terminal>>> {
let path: Option<Arc<Path>> = match &kind { let is_via_remote = self.remote_client.is_some();
TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())), let project_path_context = self
TerminalKind::Task(spawn_task) => { .active_entry()
if let Some(cwd) = &spawn_task.cwd { .and_then(|entry_id| self.worktree_id_for_entry(entry_id, cx))
Some(Arc::from(cwd.as_ref())) .or_else(|| self.visible_worktrees(cx).next().map(|wt| wt.read(cx).id()))
} else { .map(|worktree_id| ProjectPath {
self.active_project_directory(cx) worktree_id,
} path: Arc::from(Path::new("")),
});
let path: Option<Arc<Path>> = if let Some(cwd) = &spawn_task.cwd {
if is_via_remote {
Some(Arc::from(cwd.as_ref()))
} else {
let cwd = cwd.to_string_lossy();
let tilde_substituted = shellexpand::tilde(&cwd);
Some(Arc::from(Path::new(tilde_substituted.as_ref())))
} }
} else {
self.active_project_directory(cx)
}; };
let mut settings_location = None; let mut settings_location = None;
@ -83,24 +78,329 @@ impl Project {
path, path,
}); });
} }
let venv = TerminalSettings::get(settings_location, cx) let settings = TerminalSettings::get(settings_location, cx).clone();
.detect_venv let detect_venv = settings.detect_venv.as_option().is_some();
.clone();
let (completion_tx, completion_rx) = bounded(1);
// Start with the environment that we might have inherited from the Zed CLI.
let mut env = self
.environment
.read(cx)
.get_cli_environment()
.unwrap_or_default();
// Then extend it with the explicit env variables from the settings, so they take
// precedence.
env.extend(settings.env);
let local_path = if is_via_remote { None } else { path.clone() };
let task_state = Some(TaskState {
id: spawn_task.id,
full_label: spawn_task.full_label,
label: spawn_task.label,
command_label: spawn_task.command_label,
hide: spawn_task.hide,
status: TaskStatus::Running,
show_summary: spawn_task.show_summary,
show_command: spawn_task.show_command,
show_rerun: spawn_task.show_rerun,
completion_rx,
});
let remote_client = self.remote_client.clone();
let shell = match &remote_client {
Some(remote_client) => remote_client
.read(cx)
.shell()
.unwrap_or_else(get_default_system_shell),
None => match &settings.shell {
Shell::Program(program) => program.clone(),
Shell::WithArguments {
program,
args: _,
title_override: _,
} => program.clone(),
Shell::System => get_system_shell(),
},
};
let toolchain = project_path_context
.filter(|_| detect_venv)
.map(|p| self.active_toolchain(p, LanguageName::new("Python"), cx));
let lang_registry = self.languages.clone();
let fs = self.fs.clone();
cx.spawn(async move |project, cx| { cx.spawn(async move |project, cx| {
let python_venv_directory = if let Some(path) = path { let activation_script = maybe!(async {
project let toolchain = toolchain?.await?;
.update(cx, |this, cx| this.python_venv_directory(path, venv, cx))? lang_registry
.language_for_name(&toolchain.language_name.0)
.await .await
} else { .ok()?
None .toolchain_lister()?
}; .activation_script(&toolchain, fs.as_ref())
project.update(cx, |project, cx| { .await
project.create_terminal_with_venv(kind, python_venv_directory, cx) })
.await;
project.update(cx, move |this, cx| {
let shell = {
env.extend(spawn_task.env);
match remote_client {
Some(remote_client) => create_remote_shell(
spawn_task
.command
.as_ref()
.map(|command| (command, &spawn_task.args)),
&mut env,
path,
remote_client,
activation_script.clone(),
cx,
)?,
None => match activation_script.clone() {
Some(activation_script) => {
let to_run = if let Some(command) = spawn_task.command {
let command: Option<Cow<str>> = shlex::try_quote(&command).ok();
let args = spawn_task
.args
.iter()
.filter_map(|arg| shlex::try_quote(arg).ok());
command.into_iter().chain(args).join(" ")
} else {
format!("exec {shell} -l")
};
Shell::WithArguments {
program: get_default_system_shell(),
args: vec![
"-c".to_owned(),
format!("{activation_script}; {to_run}",),
],
title_override: None,
}
}
None => {
if let Some(program) = spawn_task.command {
Shell::WithArguments {
program,
args: spawn_task.args,
title_override: None,
}
} else {
Shell::System
}
}
},
}
};
TerminalBuilder::new(
local_path.map(|path| path.to_path_buf()),
task_state,
shell,
env,
settings.cursor_shape.unwrap_or_default(),
settings.alternate_scroll,
settings.max_scroll_history_lines,
is_via_remote,
cx.entity_id().as_u64(),
Some(completion_tx),
cx,
activation_script,
)
.map(|builder| {
let terminal_handle = cx.new(|cx| builder.subscribe(cx));
this.terminals
.local_handles
.push(terminal_handle.downgrade());
let id = terminal_handle.entity_id();
cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
let handles = &mut project.terminals.local_handles;
if let Some(index) = handles
.iter()
.position(|terminal| terminal.entity_id() == id)
{
handles.remove(index);
cx.notify();
}
})
.detach();
terminal_handle
})
})? })?
}) })
} }
pub fn create_terminal_shell(
&mut self,
cwd: Option<PathBuf>,
cx: &mut Context<Self>,
) -> Task<Result<Entity<Terminal>>> {
let project_path_context = self
.active_entry()
.and_then(|entry_id| self.worktree_id_for_entry(entry_id, cx))
.or_else(|| self.visible_worktrees(cx).next().map(|wt| wt.read(cx).id()))
.map(|worktree_id| ProjectPath {
worktree_id,
path: Arc::from(Path::new("")),
});
let path = cwd.map(|p| Arc::from(&*p));
let is_via_remote = self.remote_client.is_some();
let mut settings_location = None;
if let Some(path) = path.as_ref()
&& let Some((worktree, _)) = self.find_worktree(path, cx)
{
settings_location = Some(SettingsLocation {
worktree_id: worktree.read(cx).id(),
path,
});
}
let settings = TerminalSettings::get(settings_location, cx).clone();
let detect_venv = settings.detect_venv.as_option().is_some();
// Start with the environment that we might have inherited from the Zed CLI.
let mut env = self
.environment
.read(cx)
.get_cli_environment()
.unwrap_or_default();
// Then extend it with the explicit env variables from the settings, so they take
// precedence.
env.extend(settings.env);
let local_path = if is_via_remote { None } else { path.clone() };
let toolchain = project_path_context
.filter(|_| detect_venv)
.map(|p| self.active_toolchain(p, LanguageName::new("Python"), cx));
let remote_client = self.remote_client.clone();
let shell = match &remote_client {
Some(remote_client) => remote_client
.read(cx)
.shell()
.unwrap_or_else(get_default_system_shell),
None => match &settings.shell {
Shell::Program(program) => program.clone(),
Shell::WithArguments {
program,
args: _,
title_override: _,
} => program.clone(),
Shell::System => get_system_shell(),
},
};
let lang_registry = self.languages.clone();
let fs = self.fs.clone();
cx.spawn(async move |project, cx| {
let activation_script = maybe!(async {
let toolchain = toolchain?.await?;
let language = lang_registry
.language_for_name(&toolchain.language_name.0)
.await
.ok();
let lister = language?.toolchain_lister();
lister?.activation_script(&toolchain, fs.as_ref()).await
})
.await;
project.update(cx, move |this, cx| {
let shell = {
match remote_client {
Some(remote_client) => create_remote_shell(
None,
&mut env,
path,
remote_client,
activation_script.clone(),
cx,
)?,
None => match activation_script.clone() {
Some(activation_script) => Shell::WithArguments {
program: get_default_system_shell(),
args: vec![
"-c".to_owned(),
format!("{activation_script}; exec {shell} -l",),
],
title_override: Some(shell.into()),
},
None => settings.shell,
},
}
};
TerminalBuilder::new(
local_path.map(|path| path.to_path_buf()),
None,
shell,
env,
settings.cursor_shape.unwrap_or_default(),
settings.alternate_scroll,
settings.max_scroll_history_lines,
is_via_remote,
cx.entity_id().as_u64(),
None,
cx,
activation_script,
)
.map(|builder| {
let terminal_handle = cx.new(|cx| builder.subscribe(cx));
this.terminals
.local_handles
.push(terminal_handle.downgrade());
let id = terminal_handle.entity_id();
cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
let handles = &mut project.terminals.local_handles;
if let Some(index) = handles
.iter()
.position(|terminal| terminal.entity_id() == id)
{
handles.remove(index);
cx.notify();
}
})
.detach();
terminal_handle
})
})?
})
}
pub fn clone_terminal(
&mut self,
terminal: &Entity<Terminal>,
cx: &mut Context<'_, Project>,
cwd: impl FnOnce() -> Option<PathBuf>,
) -> Result<Entity<Terminal>> {
terminal.read(cx).clone_builder(cx, cwd).map(|builder| {
let terminal_handle = cx.new(|cx| builder.subscribe(cx));
self.terminals
.local_handles
.push(terminal_handle.downgrade());
let id = terminal_handle.entity_id();
cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
let handles = &mut project.terminals.local_handles;
if let Some(index) = handles
.iter()
.position(|terminal| terminal.entity_id() == id)
{
handles.remove(index);
cx.notify();
}
})
.detach();
terminal_handle
})
}
pub fn terminal_settings<'a>( pub fn terminal_settings<'a>(
&'a self, &'a self,
path: &'a Option<PathBuf>, path: &'a Option<PathBuf>,
@ -137,10 +437,15 @@ impl Project {
match remote_client { match remote_client {
Some(remote_client) => { Some(remote_client) => {
let command_template = let command_template = remote_client.read(cx).build_command(
remote_client Some(command),
.read(cx) &args,
.build_command(Some(command), &args, &env, None, None)?; &env,
None,
// todo
None,
None,
)?;
let mut command = std::process::Command::new(command_template.program); let mut command = std::process::Command::new(command_template.program);
command.args(command_template.args); command.args(command_template.args);
command.envs(command_template.env); command.envs(command_template.env);
@ -158,382 +463,6 @@ impl Project {
} }
} }
pub fn create_terminal_with_venv(
&mut self,
kind: TerminalKind,
python_venv_directory: Option<PathBuf>,
cx: &mut Context<Self>,
) -> Result<Entity<Terminal>> {
let is_via_remote = self.remote_client.is_some();
let path: Option<Arc<Path>> = match &kind {
TerminalKind::Shell(path) => path.as_ref().map(|path| Arc::from(path.as_ref())),
TerminalKind::Task(spawn_task) => {
if let Some(cwd) = &spawn_task.cwd {
if is_via_remote {
Some(Arc::from(cwd.as_ref()))
} else {
let cwd = cwd.to_string_lossy();
let tilde_substituted = shellexpand::tilde(&cwd);
Some(Arc::from(Path::new(tilde_substituted.as_ref())))
}
} else {
self.active_project_directory(cx)
}
}
};
let mut settings_location = None;
if let Some(path) = path.as_ref()
&& let Some((worktree, _)) = self.find_worktree(path, cx)
{
settings_location = Some(SettingsLocation {
worktree_id: worktree.read(cx).id(),
path,
});
}
let settings = TerminalSettings::get(settings_location, cx).clone();
let (completion_tx, completion_rx) = bounded(1);
// Start with the environment that we might have inherited from the Zed CLI.
let mut env = self
.environment
.read(cx)
.get_cli_environment()
.unwrap_or_default();
// Then extend it with the explicit env variables from the settings, so they take
// precedence.
env.extend(settings.env);
let local_path = if is_via_remote { None } else { path.clone() };
let mut python_venv_activate_command = Task::ready(None);
let remote_client = self.remote_client.clone();
let spawn_task;
let shell;
match kind {
TerminalKind::Shell(_) => {
if let Some(python_venv_directory) = &python_venv_directory {
python_venv_activate_command = self.python_activate_command(
python_venv_directory,
&settings.detect_venv,
&settings.shell,
cx,
);
}
spawn_task = None;
shell = match remote_client {
Some(remote_client) => {
create_remote_shell(None, &mut env, path, remote_client, cx)?
}
None => settings.shell,
};
}
TerminalKind::Task(task) => {
env.extend(task.env);
if let Some(venv_path) = &python_venv_directory {
env.insert(
"VIRTUAL_ENV".to_string(),
venv_path.to_string_lossy().to_string(),
);
}
spawn_task = Some(TaskState {
id: task.id,
full_label: task.full_label,
label: task.label,
command_label: task.command_label,
hide: task.hide,
status: TaskStatus::Running,
show_summary: task.show_summary,
show_command: task.show_command,
show_rerun: task.show_rerun,
completion_rx,
});
shell = match remote_client {
Some(remote_client) => {
let path_style = remote_client.read(cx).path_style();
if let Some(venv_directory) = &python_venv_directory
&& 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.insert("PATH".into(), format!("{}:$PATH ", path));
}
create_remote_shell(
task.command.as_ref().map(|command| (command, &task.args)),
&mut env,
path,
remote_client,
cx,
)?
}
None => {
if let Some(venv_path) = &python_venv_directory {
add_environment_path(&mut env, &venv_path.join(PYTHON_VENV_BIN_DIR))
.log_err();
}
if let Some(program) = task.command {
Shell::WithArguments {
program,
args: task.args,
title_override: None,
}
} else {
Shell::System
}
}
};
}
};
TerminalBuilder::new(
local_path.map(|path| path.to_path_buf()),
python_venv_directory,
spawn_task,
shell,
env,
settings.cursor_shape.unwrap_or_default(),
settings.alternate_scroll,
settings.max_scroll_history_lines,
is_via_remote,
cx.entity_id().as_u64(),
completion_tx,
cx,
)
.map(|builder| {
let terminal_handle = cx.new(|cx| builder.subscribe(cx));
self.terminals
.local_handles
.push(terminal_handle.downgrade());
let id = terminal_handle.entity_id();
cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
let handles = &mut project.terminals.local_handles;
if let Some(index) = handles
.iter()
.position(|terminal| terminal.entity_id() == id)
{
handles.remove(index);
cx.notify();
}
})
.detach();
self.activate_python_virtual_environment(
python_venv_activate_command,
&terminal_handle,
cx,
);
terminal_handle
})
}
fn python_venv_directory(
&self,
abs_path: Arc<Path>,
venv_settings: VenvSettings,
cx: &Context<Project>,
) -> Task<Option<PathBuf>> {
cx.spawn(async move |this, cx| {
if let Some((worktree, relative_path)) = this
.update(cx, |this, cx| this.find_worktree(&abs_path, cx))
.ok()?
{
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> {
venv_settings
.directories
.iter()
.map(|name| abs_path.join(name))
.find(|venv_path| {
let bin_path = venv_path.join(PYTHON_VENV_BIN_DIR);
self.find_worktree(&bin_path, cx)
.and_then(|(worktree, relative_path)| {
worktree.read(cx).entry_for_path(&relative_path)
})
.is_some_and(|entry| entry.is_dir())
})
}
fn find_venv_on_filesystem(
&self,
abs_path: &Path,
venv_settings: &terminal_settings::VenvSettingsContent,
cx: &App,
) -> Option<PathBuf> {
let (worktree, _) = self.find_worktree(abs_path, cx)?;
let fs = worktree.read(cx).as_local()?.fs();
venv_settings
.directories
.iter()
.map(|name| abs_path.join(name))
.find(|venv_path| {
let bin_path = venv_path.join(PYTHON_VENV_BIN_DIR);
// One-time synchronous check is acceptable for terminal/task initialization
smol::block_on(fs.metadata(&bin_path))
.ok()
.flatten()
.is_some_and(|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 {
return Task::ready(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 {
"windows" => "\r",
_ => "\n",
};
if venv_settings.venv_name.is_empty() {
let path = venv_base_directory
.join(PYTHON_VENV_BIN_DIR)
.join(activate_script_name)
.to_string_lossy()
.to_string();
let is_valid_path = self.resolve_abs_path(path.as_ref(), cx);
cx.background_spawn(async move {
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(
&self,
command: Task<Option<String>>,
terminal_handle: &Entity<Terminal>,
cx: &mut App,
) {
terminal_handle.update(cx, |_, cx| {
cx.spawn(async move |this, cx| {
if let Some(command) = command.await {
this.update(cx, |this, _| {
this.input(command.into_bytes());
})
.ok();
}
})
.detach()
});
}
pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> { pub fn local_terminal_handles(&self) -> &Vec<WeakEntity<terminal::Terminal>> {
&self.terminals.local_handles &self.terminals.local_handles
} }
@ -544,6 +473,7 @@ fn create_remote_shell(
env: &mut HashMap<String, String>, env: &mut HashMap<String, String>,
working_directory: Option<Arc<Path>>, working_directory: Option<Arc<Path>>,
remote_client: Entity<RemoteClient>, remote_client: Entity<RemoteClient>,
activation_script: Option<String>,
cx: &mut App, cx: &mut App,
) -> Result<Shell> { ) -> Result<Shell> {
// Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed // Alacritty sets its terminfo to `alacritty`, this requiring hosts to have it installed
@ -563,6 +493,7 @@ fn create_remote_shell(
args.as_slice(), args.as_slice(),
env, env,
working_directory.map(|path| path.display().to_string()), working_directory.map(|path| path.display().to_string()),
activation_script,
None, None,
)?; )?;
*env = command.env; *env = command.env;
@ -576,57 +507,3 @@ fn create_remote_shell(
title_override: Some(format!("{} — Terminal", host).into()), title_override: Some(format!("{} — Terminal", host).into()),
}) })
} }
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

@ -1,4 +1,5 @@
fn main() { fn main() {
println!("cargo:rerun-if-changed=proto");
let mut build = prost_build::Config::new(); let mut build = prost_build::Config::new();
build build
.type_attribute(".", "#[derive(serde::Serialize, serde::Deserialize)]") .type_attribute(".", "#[derive(serde::Serialize, serde::Deserialize)]")

View file

@ -757,6 +757,7 @@ impl RemoteClient {
args: &[String], args: &[String],
env: &HashMap<String, String>, env: &HashMap<String, String>,
working_dir: Option<String>, working_dir: Option<String>,
activation_script: Option<String>,
port_forward: Option<(u16, String, u16)>, port_forward: Option<(u16, String, u16)>,
) -> Result<CommandTemplate> { ) -> Result<CommandTemplate> {
let Some(connection) = self let Some(connection) = self
@ -766,7 +767,14 @@ impl RemoteClient {
else { else {
return Err(anyhow!("no connection")); return Err(anyhow!("no connection"));
}; };
connection.build_command(program, args, env, working_dir, port_forward) connection.build_command(
program,
args,
env,
working_dir,
activation_script,
port_forward,
)
} }
pub fn upload_directory( pub fn upload_directory(
@ -998,6 +1006,7 @@ pub(crate) trait RemoteConnection: Send + Sync {
args: &[String], args: &[String],
env: &HashMap<String, String>, env: &HashMap<String, String>,
working_dir: Option<String>, working_dir: Option<String>,
activation_script: Option<String>,
port_forward: Option<(u16, String, u16)>, port_forward: Option<(u16, String, u16)>,
) -> Result<CommandTemplate>; ) -> Result<CommandTemplate>;
fn connection_options(&self) -> SshConnectionOptions; fn connection_options(&self) -> SshConnectionOptions;
@ -1364,6 +1373,7 @@ mod fake {
args: &[String], args: &[String],
env: &HashMap<String, String>, env: &HashMap<String, String>,
_: Option<String>, _: Option<String>,
_: Option<String>,
_: Option<(u16, String, u16)>, _: Option<(u16, String, u16)>,
) -> Result<CommandTemplate> { ) -> Result<CommandTemplate> {
let ssh_program = program.unwrap_or_else(|| "sh".to_string()); let ssh_program = program.unwrap_or_else(|| "sh".to_string());

View file

@ -30,7 +30,10 @@ use std::{
time::Instant, time::Instant,
}; };
use tempfile::TempDir; use tempfile::TempDir;
use util::paths::{PathStyle, RemotePathBuf}; use util::{
get_default_system_shell,
paths::{PathStyle, RemotePathBuf},
};
pub(crate) struct SshRemoteConnection { pub(crate) struct SshRemoteConnection {
socket: SshSocket, socket: SshSocket,
@ -113,6 +116,7 @@ impl RemoteConnection for SshRemoteConnection {
input_args: &[String], input_args: &[String],
input_env: &HashMap<String, String>, input_env: &HashMap<String, String>,
working_dir: Option<String>, working_dir: Option<String>,
activation_script: Option<String>,
port_forward: Option<(u16, String, u16)>, port_forward: Option<(u16, String, u16)>,
) -> Result<CommandTemplate> { ) -> Result<CommandTemplate> {
use std::fmt::Write as _; use std::fmt::Write as _;
@ -134,6 +138,9 @@ impl RemoteConnection for SshRemoteConnection {
} else { } else {
write!(&mut script, "cd; ").unwrap(); write!(&mut script, "cd; ").unwrap();
}; };
if let Some(activation_script) = activation_script {
write!(&mut script, " {activation_script};").unwrap();
}
for (k, v) in input_env.iter() { for (k, v) in input_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()) {
@ -155,7 +162,8 @@ impl RemoteConnection for SshRemoteConnection {
write!(&mut script, "exec {shell} -l").unwrap(); write!(&mut script, "exec {shell} -l").unwrap();
}; };
let shell_invocation = format!("{shell} -c {}", shlex::try_quote(&script).unwrap()); let sys_shell = get_default_system_shell();
let shell_invocation = format!("{sys_shell} -c {}", shlex::try_quote(&script).unwrap());
let mut args = Vec::new(); let mut args = Vec::new();
args.extend(self.socket.ssh_args()); args.extend(self.socket.ssh_args());
@ -167,7 +175,6 @@ impl RemoteConnection for SshRemoteConnection {
args.push("-t".into()); args.push("-t".into());
args.push(shell_invocation); args.push(shell_invocation);
Ok(CommandTemplate { Ok(CommandTemplate {
program: "ssh".into(), program: "ssh".into(),
args, args,

View file

@ -1,3 +1,7 @@
use std::fmt;
use util::get_system_shell;
use crate::Shell; use crate::Shell;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
@ -11,9 +15,22 @@ pub enum ShellKind {
Cmd, Cmd,
} }
impl fmt::Display for ShellKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ShellKind::Posix => write!(f, "sh"),
ShellKind::Csh => write!(f, "csh"),
ShellKind::Fish => write!(f, "fish"),
ShellKind::Powershell => write!(f, "powershell"),
ShellKind::Nushell => write!(f, "nu"),
ShellKind::Cmd => write!(f, "cmd"),
}
}
}
impl ShellKind { impl ShellKind {
pub fn system() -> Self { pub fn system() -> Self {
Self::new(&system_shell()) Self::new(&get_system_shell())
} }
pub fn new(program: &str) -> Self { pub fn new(program: &str) -> Self {
@ -22,12 +39,12 @@ impl ShellKind {
#[cfg(not(windows))] #[cfg(not(windows))]
let (_, program) = program.rsplit_once('/').unwrap_or(("", program)); let (_, program) = program.rsplit_once('/').unwrap_or(("", program));
if program == "powershell" if program == "powershell"
|| program == "powershell.exe" || program.ends_with("powershell.exe")
|| program == "pwsh" || program == "pwsh"
|| program == "pwsh.exe" || program.ends_with("pwsh.exe")
{ {
ShellKind::Powershell ShellKind::Powershell
} else if program == "cmd" || program == "cmd.exe" { } else if program == "cmd" || program.ends_with("cmd.exe") {
ShellKind::Cmd ShellKind::Cmd
} else if program == "nu" { } else if program == "nu" {
ShellKind::Nushell ShellKind::Nushell
@ -178,18 +195,6 @@ impl ShellKind {
} }
} }
fn system_shell() -> String {
if cfg!(target_os = "windows") {
// `alacritty_terminal` uses this as default on Windows. See:
// https://github.com/alacritty/alacritty/blob/0d4ab7bca43213d96ddfe40048fc0f922543c6f8/alacritty_terminal/src/tty/windows/mod.rs#L130
// We could use `util::get_windows_system_shell()` here, but we are running tasks here, so leave it to `powershell.exe`
// should be okay.
"powershell.exe".to_string()
} else {
std::env::var("SHELL").unwrap_or("/bin/sh".to_string())
}
}
/// ShellBuilder is used to turn a user-requested task into a /// ShellBuilder is used to turn a user-requested task into a
/// program that can be executed by the shell. /// program that can be executed by the shell.
pub struct ShellBuilder { pub struct ShellBuilder {
@ -206,7 +211,7 @@ impl ShellBuilder {
let (program, args) = match remote_system_shell { let (program, args) = match remote_system_shell {
Some(program) => (program.to_string(), Vec::new()), Some(program) => (program.to_string(), Vec::new()),
None => match shell { None => match shell {
Shell::System => (system_shell(), Vec::new()), Shell::System => (get_system_shell(), Vec::new()),
Shell::Program(shell) => (shell.clone(), Vec::new()), Shell::Program(shell) => (shell.clone(), Vec::new()),
Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()), Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()),
}, },

View file

@ -344,7 +344,6 @@ 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>,
task: Option<TaskState>, task: Option<TaskState>,
shell: Shell, shell: Shell,
mut env: HashMap<String, String>, mut env: HashMap<String, String>,
@ -353,8 +352,9 @@ impl TerminalBuilder {
max_scroll_history_lines: Option<usize>, max_scroll_history_lines: Option<usize>,
is_ssh_terminal: bool, is_ssh_terminal: bool,
window_id: u64, window_id: u64,
completion_tx: Sender<Option<ExitStatus>>, completion_tx: Option<Sender<Option<ExitStatus>>>,
cx: &App, cx: &App,
activation_script: Option<String>,
) -> Result<TerminalBuilder> { ) -> Result<TerminalBuilder> {
// If the parent environment doesn't have a locale set // If the parent environment doesn't have a locale set
// (As is the case when launched from a .app on MacOS), // (As is the case when launched from a .app on MacOS),
@ -428,13 +428,10 @@ impl TerminalBuilder {
.clone() .clone()
.or_else(|| Some(home_dir().to_path_buf())), .or_else(|| Some(home_dir().to_path_buf())),
drain_on_exit: true, drain_on_exit: true,
env: env.into_iter().collect(), env: env.clone().into_iter().collect(),
} }
}; };
// 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.
@ -517,11 +514,19 @@ 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,
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,
activation_script,
template: CopyTemplate {
shell,
env,
cursor_shape,
alternate_scroll,
max_scroll_history_lines,
window_id,
},
}; };
Ok(TerminalBuilder { Ok(TerminalBuilder {
@ -683,7 +688,7 @@ pub enum SelectionPhase {
pub struct Terminal { pub struct Terminal {
pty_tx: Notifier, pty_tx: Notifier,
completion_tx: Sender<Option<ExitStatus>>, completion_tx: Option<Sender<Option<ExitStatus>>>,
term: Arc<FairMutex<Term<ZedListener>>>, term: Arc<FairMutex<Term<ZedListener>>>,
term_config: Config, term_config: Config,
events: VecDeque<InternalEvent>, events: VecDeque<InternalEvent>,
@ -695,7 +700,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,
@ -707,6 +711,17 @@ pub struct Terminal {
last_hyperlink_search_position: Option<Point<Pixels>>, last_hyperlink_search_position: Option<Point<Pixels>>,
#[cfg(windows)] #[cfg(windows)]
shell_program: Option<String>, shell_program: Option<String>,
template: CopyTemplate,
activation_script: Option<String>,
}
struct CopyTemplate {
shell: Shell,
env: HashMap<String, String>,
cursor_shape: CursorShape,
alternate_scroll: AlternateScroll,
max_scroll_history_lines: Option<usize>,
window_id: u64,
} }
pub struct TaskState { pub struct TaskState {
@ -1895,7 +1910,9 @@ impl Terminal {
} }
}); });
self.completion_tx.try_send(e).ok(); if let Some(tx) = &self.completion_tx {
tx.try_send(e).ok();
}
let task = match &mut self.task { let task = match &mut self.task {
Some(task) => task, Some(task) => task,
None => { None => {
@ -1950,6 +1967,28 @@ impl Terminal {
pub fn vi_mode_enabled(&self) -> bool { pub fn vi_mode_enabled(&self) -> bool {
self.vi_mode_enabled self.vi_mode_enabled
} }
pub fn clone_builder(
&self,
cx: &App,
cwd: impl FnOnce() -> Option<PathBuf>,
) -> Result<TerminalBuilder> {
let working_directory = self.working_directory().or_else(cwd);
TerminalBuilder::new(
working_directory,
None,
self.template.shell.clone(),
self.template.env.clone(),
self.template.cursor_shape,
self.template.alternate_scroll,
self.template.max_scroll_history_lines,
self.is_ssh_terminal,
self.template.window_id,
None,
cx,
self.activation_script.clone(),
)
}
} }
// Helper function to convert a grid row to a string // Helper function to convert a grid row to a string
@ -2164,7 +2203,6 @@ mod tests {
let (completion_tx, completion_rx) = smol::channel::unbounded(); let (completion_tx, completion_rx) = smol::channel::unbounded();
let terminal = cx.new(|cx| { let terminal = cx.new(|cx| {
TerminalBuilder::new( TerminalBuilder::new(
None,
None, None,
None, None,
task::Shell::WithArguments { task::Shell::WithArguments {
@ -2178,8 +2216,9 @@ mod tests {
None, None,
false, false,
0, 0,
completion_tx, Some(completion_tx),
cx, cx,
None,
) )
.unwrap() .unwrap()
.subscribe(cx) .subscribe(cx)

View file

@ -3,9 +3,9 @@ use async_recursion::async_recursion;
use collections::HashSet; use collections::HashSet;
use futures::{StreamExt as _, stream::FuturesUnordered}; use futures::{StreamExt as _, stream::FuturesUnordered};
use gpui::{AppContext as _, AsyncWindowContext, Axis, Entity, Task, WeakEntity}; use gpui::{AppContext as _, AsyncWindowContext, Axis, Entity, Task, WeakEntity};
use project::{Project, terminals::TerminalKind}; use project::Project;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use ui::{App, Context, Pixels, Window}; use ui::{App, Context, Pixels, Window};
use util::ResultExt as _; use util::ResultExt as _;
@ -246,11 +246,9 @@ async fn deserialize_pane_group(
.update(cx, |workspace, cx| default_working_directory(workspace, cx)) .update(cx, |workspace, cx| default_working_directory(workspace, cx))
.ok() .ok()
.flatten(); .flatten();
let kind = TerminalKind::Shell( let terminal = project.update(cx, |project, cx| {
working_directory.as_deref().map(Path::to_path_buf), project.create_terminal_shell(working_directory, cx)
); });
let terminal =
project.update(cx, |project, cx| project.create_terminal(kind, cx));
Some(Some(terminal)) Some(Some(terminal))
} else { } else {
Some(None) Some(None)

View file

@ -16,7 +16,7 @@ use gpui::{
Task, WeakEntity, Window, actions, Task, WeakEntity, Window, actions,
}; };
use itertools::Itertools; use itertools::Itertools;
use project::{Fs, Project, ProjectEntryId, terminals::TerminalKind}; use project::{Fs, Project, ProjectEntryId};
use search::{BufferSearchBar, buffer_search::DivRegistrar}; use search::{BufferSearchBar, buffer_search::DivRegistrar};
use settings::Settings; use settings::Settings;
use task::{RevealStrategy, RevealTarget, ShellBuilder, SpawnInTerminal, TaskId}; use task::{RevealStrategy, RevealTarget, ShellBuilder, SpawnInTerminal, TaskId};
@ -376,14 +376,19 @@ impl TerminalPanel {
} }
self.serialize(cx); self.serialize(cx);
} }
pane::Event::Split(direction) => { &pane::Event::Split(direction) => {
let Some(new_pane) = self.new_pane_with_cloned_active_terminal(window, cx) else { let fut = self.new_pane_with_cloned_active_terminal(window, cx);
return;
};
let pane = pane.clone(); let pane = pane.clone();
let direction = *direction; cx.spawn_in(window, async move |panel, cx| {
self.center.split(&pane, &new_pane, direction).log_err(); let Some(new_pane) = fut.await else {
window.focus(&new_pane.focus_handle(cx)); return;
};
_ = panel.update_in(cx, |panel, window, cx| {
panel.center.split(&pane, &new_pane, direction).log_err();
window.focus(&new_pane.focus_handle(cx));
});
})
.detach();
} }
pane::Event::Focus => { pane::Event::Focus => {
self.active_pane = pane.clone(); self.active_pane = pane.clone();
@ -400,57 +405,62 @@ impl TerminalPanel {
&mut self, &mut self,
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
) -> Option<Entity<Pane>> { ) -> Task<Option<Entity<Pane>>> {
let workspace = self.workspace.upgrade()?; let Some(workspace) = self.workspace.upgrade() else {
return Task::ready(None);
};
let workspace = workspace.read(cx); let workspace = workspace.read(cx);
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 active_pane = &self.active_pane;
.active_pane let terminal_view = 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| { let working_directory = terminal_view.as_ref().and_then(|terminal_view| {
let terminal = terminal_view.read(cx).terminal().read(cx); let terminal = terminal_view.read(cx).terminal().read(cx);
( terminal
terminal .working_directory()
.working_directory() .or_else(|| default_working_directory(workspace, cx))
.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
.update(cx, |project, cx| {
project.create_terminal_with_venv(kind, python_venv_directory, cx)
})
.ok()?;
let terminal_view = Box::new(cx.new(|cx| {
TerminalView::new(
terminal.clone(),
weak_workspace.clone(),
database_id,
project.downgrade(),
window,
cx,
)
}));
let pane = new_terminal_pane(
weak_workspace,
project,
self.active_pane.read(cx).is_zoomed(),
window,
cx,
);
self.apply_tab_bar_buttons(&pane, cx);
pane.update(cx, |pane, cx| {
pane.add_item(terminal_view, true, true, None, window, cx);
}); });
let is_zoomed = active_pane.read(cx).is_zoomed();
cx.spawn_in(window, async move |panel, cx| {
let terminal = project
.update(cx, |project, cx| match terminal_view {
Some(view) => Task::ready(project.clone_terminal(
&view.read(cx).terminal.clone(),
cx,
|| working_directory,
)),
None => project.create_terminal_shell(working_directory, cx),
})
.ok()?
.await
.ok()?;
Some(pane) panel
.update_in(cx, move |terminal_panel, window, cx| {
let terminal_view = Box::new(cx.new(|cx| {
TerminalView::new(
terminal.clone(),
weak_workspace.clone(),
database_id,
project.downgrade(),
window,
cx,
)
}));
let pane = new_terminal_pane(weak_workspace, project, is_zoomed, window, cx);
terminal_panel.apply_tab_bar_buttons(&pane, cx);
pane.update(cx, |pane, cx| {
pane.add_item(terminal_view, true, true, None, window, cx);
});
Some(pane)
})
.ok()
.flatten()
})
} }
pub fn open_terminal( pub fn open_terminal(
@ -465,8 +475,8 @@ impl TerminalPanel {
terminal_panel terminal_panel
.update(cx, |panel, cx| { .update(cx, |panel, cx| {
panel.add_terminal( panel.add_terminal_shell(
TerminalKind::Shell(Some(action.working_directory.clone())), Some(action.working_directory.clone()),
RevealStrategy::Always, RevealStrategy::Always,
window, window,
cx, cx,
@ -571,15 +581,16 @@ impl TerminalPanel {
) -> Task<Result<WeakEntity<Terminal>>> { ) -> Task<Result<WeakEntity<Terminal>>> {
let reveal = spawn_task.reveal; let reveal = spawn_task.reveal;
let reveal_target = spawn_task.reveal_target; let reveal_target = spawn_task.reveal_target;
let kind = TerminalKind::Task(spawn_task);
match reveal_target { match reveal_target {
RevealTarget::Center => self RevealTarget::Center => self
.workspace .workspace
.update(cx, |workspace, cx| { .update(cx, |workspace, cx| {
Self::add_center_terminal(workspace, kind, window, cx) Self::add_center_terminal(workspace, window, cx, |project, cx| {
project.create_terminal_task(spawn_task, cx)
})
}) })
.unwrap_or_else(|e| Task::ready(Err(e))), .unwrap_or_else(|e| Task::ready(Err(e))),
RevealTarget::Dock => self.add_terminal(kind, reveal, window, cx), RevealTarget::Dock => self.add_terminal_task(spawn_task, reveal, window, cx),
} }
} }
@ -594,11 +605,14 @@ impl TerminalPanel {
return; return;
}; };
let kind = TerminalKind::Shell(default_working_directory(workspace, cx));
terminal_panel terminal_panel
.update(cx, |this, cx| { .update(cx, |this, cx| {
this.add_terminal(kind, RevealStrategy::Always, window, cx) this.add_terminal_shell(
default_working_directory(workspace, cx),
RevealStrategy::Always,
window,
cx,
)
}) })
.detach_and_log_err(cx); .detach_and_log_err(cx);
} }
@ -660,9 +674,13 @@ impl TerminalPanel {
pub fn add_center_terminal( pub fn add_center_terminal(
workspace: &mut Workspace, workspace: &mut Workspace,
kind: TerminalKind,
window: &mut Window, window: &mut Window,
cx: &mut Context<Workspace>, cx: &mut Context<Workspace>,
create_terminal: impl FnOnce(
&mut Project,
&mut Context<Project>,
) -> Task<Result<Entity<Terminal>>>
+ 'static,
) -> Task<Result<WeakEntity<Terminal>>> { ) -> Task<Result<WeakEntity<Terminal>>> {
if !is_enabled_in_workspace(workspace, cx) { if !is_enabled_in_workspace(workspace, cx) {
return Task::ready(Err(anyhow!( return Task::ready(Err(anyhow!(
@ -671,9 +689,7 @@ impl TerminalPanel {
} }
let project = workspace.project().downgrade(); let project = workspace.project().downgrade();
cx.spawn_in(window, async move |workspace, cx| { cx.spawn_in(window, async move |workspace, cx| {
let terminal = project let terminal = project.update(cx, create_terminal)?.await?;
.update(cx, |project, cx| project.create_terminal(kind, cx))?
.await?;
workspace.update_in(cx, |workspace, window, cx| { workspace.update_in(cx, |workspace, window, cx| {
let terminal_view = cx.new(|cx| { let terminal_view = cx.new(|cx| {
@ -692,9 +708,9 @@ impl TerminalPanel {
}) })
} }
pub fn add_terminal( pub fn add_terminal_task(
&mut self, &mut self,
kind: TerminalKind, task: SpawnInTerminal,
reveal_strategy: RevealStrategy, reveal_strategy: RevealStrategy,
window: &mut Window, window: &mut Window,
cx: &mut Context<Self>, cx: &mut Context<Self>,
@ -710,7 +726,66 @@ impl TerminalPanel {
})?; })?;
let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?; let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
let terminal = project let terminal = project
.update(cx, |project, cx| project.create_terminal(kind, cx))? .update(cx, |project, cx| project.create_terminal_task(task, cx))?
.await?;
let result = workspace.update_in(cx, |workspace, window, cx| {
let terminal_view = Box::new(cx.new(|cx| {
TerminalView::new(
terminal.clone(),
workspace.weak_handle(),
workspace.database_id(),
workspace.project().downgrade(),
window,
cx,
)
}));
match reveal_strategy {
RevealStrategy::Always => {
workspace.focus_panel::<Self>(window, cx);
}
RevealStrategy::NoFocus => {
workspace.open_panel::<Self>(window, cx);
}
RevealStrategy::Never => {}
}
pane.update(cx, |pane, cx| {
let focus = pane.has_focus(window, cx)
|| matches!(reveal_strategy, RevealStrategy::Always);
pane.add_item(terminal_view, true, focus, None, window, cx);
});
Ok(terminal.downgrade())
})?;
terminal_panel.update(cx, |terminal_panel, cx| {
terminal_panel.pending_terminals_to_add =
terminal_panel.pending_terminals_to_add.saturating_sub(1);
terminal_panel.serialize(cx)
})?;
result
})
}
pub fn add_terminal_shell(
&mut self,
cwd: Option<PathBuf>,
reveal_strategy: RevealStrategy,
window: &mut Window,
cx: &mut Context<Self>,
) -> Task<Result<WeakEntity<Terminal>>> {
let workspace = self.workspace.clone();
cx.spawn_in(window, async move |terminal_panel, cx| {
if workspace.update(cx, |workspace, cx| !is_enabled_in_workspace(workspace, cx))? {
anyhow::bail!("terminal not yet supported for remote projects");
}
let pane = terminal_panel.update(cx, |terminal_panel, _| {
terminal_panel.pending_terminals_to_add += 1;
terminal_panel.active_pane.clone()
})?;
let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?;
let terminal = project
.update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
.await?; .await?;
let result = workspace.update_in(cx, |workspace, window, cx| { let result = workspace.update_in(cx, |workspace, window, cx| {
let terminal_view = Box::new(cx.new(|cx| { let terminal_view = Box::new(cx.new(|cx| {
@ -819,7 +894,7 @@ impl TerminalPanel {
})??; })??;
let new_terminal = project let new_terminal = project
.update(cx, |project, cx| { .update(cx, |project, cx| {
project.create_terminal(TerminalKind::Task(spawn_task), cx) project.create_terminal_task(spawn_task, cx)
})? })?
.await?; .await?;
terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| { terminal_to_replace.update_in(cx, |terminal_to_replace, window, cx| {
@ -1248,18 +1323,29 @@ impl Render for TerminalPanel {
let panes = terminal_panel.center.panes(); let panes = terminal_panel.center.panes();
if let Some(&pane) = panes.get(action.0) { if let Some(&pane) = panes.get(action.0) {
window.focus(&pane.read(cx).focus_handle(cx)); window.focus(&pane.read(cx).focus_handle(cx));
} else if let Some(new_pane) = } else {
terminal_panel.new_pane_with_cloned_active_terminal(window, cx) let future =
{ terminal_panel.new_pane_with_cloned_active_terminal(window, cx);
terminal_panel cx.spawn_in(window, async move |terminal_panel, cx| {
.center if let Some(new_pane) = future.await {
.split( _ = terminal_panel.update_in(
&terminal_panel.active_pane, cx,
&new_pane, |terminal_panel, window, cx| {
SplitDirection::Right, terminal_panel
) .center
.log_err(); .split(
window.focus(&new_pane.focus_handle(cx)); &terminal_panel.active_pane,
&new_pane,
SplitDirection::Right,
)
.log_err();
let new_pane = new_pane.read(cx);
window.focus(&new_pane.focus_handle(cx));
},
);
}
})
.detach();
} }
}), }),
) )
@ -1395,13 +1481,14 @@ impl Panel for TerminalPanel {
return; return;
} }
cx.defer_in(window, |this, window, cx| { cx.defer_in(window, |this, window, cx| {
let Ok(kind) = this.workspace.update(cx, |workspace, cx| { let Ok(kind) = this
TerminalKind::Shell(default_working_directory(workspace, cx)) .workspace
}) else { .update(cx, |workspace, cx| default_working_directory(workspace, cx))
else {
return; return;
}; };
this.add_terminal(kind, RevealStrategy::Always, window, cx) this.add_terminal_shell(kind, RevealStrategy::Always, window, cx)
.detach_and_log_err(cx) .detach_and_log_err(cx)
}) })
} }

View file

@ -364,7 +364,7 @@ fn possibly_open_target(
mod tests { mod tests {
use super::*; use super::*;
use gpui::TestAppContext; use gpui::TestAppContext;
use project::{Project, terminals::TerminalKind}; use project::Project;
use serde_json::json; use serde_json::json;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use terminal::{HoveredWord, alacritty_terminal::index::Point as AlacPoint}; use terminal::{HoveredWord, alacritty_terminal::index::Point as AlacPoint};
@ -405,8 +405,8 @@ mod tests {
app_cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx)); app_cx.add_window_view(|window, cx| Workspace::test_new(project.clone(), window, cx));
let terminal = project let terminal = project
.update(cx, |project, cx| { .update(cx, |project: &mut Project, cx| {
project.create_terminal(TerminalKind::Shell(None), cx) project.create_terminal_shell(None, cx)
}) })
.await .await
.expect("Failed to create a terminal"); .expect("Failed to create a terminal");

View file

@ -15,7 +15,7 @@ use gpui::{
deferred, div, deferred, div,
}; };
use persistence::TERMINAL_DB; use persistence::TERMINAL_DB;
use project::{Project, search::SearchQuery, terminals::TerminalKind}; use project::{Project, search::SearchQuery};
use schemars::JsonSchema; use schemars::JsonSchema;
use task::TaskId; use task::TaskId;
use terminal::{ use terminal::{
@ -204,12 +204,9 @@ impl TerminalView {
cx: &mut Context<Workspace>, cx: &mut Context<Workspace>,
) { ) {
let working_directory = default_working_directory(workspace, cx); let working_directory = default_working_directory(workspace, cx);
TerminalPanel::add_center_terminal( TerminalPanel::add_center_terminal(workspace, window, cx, |project, cx| {
workspace, project.create_terminal_shell(working_directory, cx)
TerminalKind::Shell(working_directory), })
window,
cx,
)
.detach_and_log_err(cx); .detach_and_log_err(cx);
} }
@ -1333,16 +1330,10 @@ 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); let cwd = project
let working_directory = terminal .active_project_directory(cx)
.working_directory() .map(|it| it.to_path_buf());
.or_else(|| Some(project.active_project_directory(cx)?.to_path_buf())); project.clone_terminal(self.terminal(), cx, || cwd)
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()?;
@ -1498,9 +1489,7 @@ impl SerializableItem for TerminalView {
.flatten(); .flatten();
let terminal = project let terminal = project
.update(cx, |project, cx| { .update(cx, |project, cx| project.create_terminal_shell(cwd, cx))?
project.create_terminal(TerminalKind::Shell(cwd), cx)
})?
.await?; .await?;
cx.update(|window, cx| { cx.update(|window, cx| {
cx.new(|cx| { cx.new(|cx| {

View file

@ -1057,6 +1057,18 @@ pub fn get_system_shell() -> String {
} }
} }
pub fn get_default_system_shell() -> String {
#[cfg(target_os = "windows")]
{
get_windows_system_shell()
}
#[cfg(not(target_os = "windows"))]
{
"/bin/sh".to_string()
}
}
#[derive(Debug)] #[derive(Debug)]
pub enum ConnectionResult<O> { pub enum ConnectionResult<O> {
Timeout, Timeout,

View file

@ -824,7 +824,6 @@ impl WorkspaceDb {
conn.exec_bound( conn.exec_bound(
sql!( sql!(
DELETE FROM breakpoints WHERE workspace_id = ?1; DELETE FROM breakpoints WHERE workspace_id = ?1;
DELETE FROM toolchains WHERE workspace_id = ?1;
) )
)?(workspace.id).context("Clearing old breakpoints")?; )?(workspace.id).context("Clearing old breakpoints")?;
@ -1097,7 +1096,6 @@ impl WorkspaceDb {
query! { query! {
pub async fn delete_workspace_by_id(id: WorkspaceId) -> Result<()> { pub async fn delete_workspace_by_id(id: WorkspaceId) -> Result<()> {
DELETE FROM toolchains WHERE workspace_id = ?1;
DELETE FROM workspaces DELETE FROM workspaces
WHERE workspace_id IS ? WHERE workspace_id IS ?
} }
@ -1424,24 +1422,24 @@ impl WorkspaceDb {
&self, &self,
workspace_id: WorkspaceId, workspace_id: WorkspaceId,
worktree_id: WorktreeId, worktree_id: WorktreeId,
relative_path: String, relative_worktree_path: String,
language_name: LanguageName, language_name: LanguageName,
) -> Result<Option<Toolchain>> { ) -> Result<Option<Toolchain>> {
self.write(move |this| { self.write(move |this| {
let mut select = this let mut select = this
.select_bound(sql!( .select_bound(sql!(
SELECT name, path, raw_json FROM toolchains WHERE workspace_id = ? AND language_name = ? AND worktree_id = ? AND relative_path = ? SELECT name, path, raw_json FROM toolchains WHERE workspace_id = ? AND language_name = ? AND worktree_id = ? AND relative_worktree_path = ?
)) ))
.context("Preparing insertion")?; .context("select toolchain")?;
let toolchain: Vec<(String, String, String)> = let toolchain: Vec<(String, String, String)> =
select((workspace_id, language_name.as_ref().to_string(), worktree_id.to_usize(), relative_path))?; select((workspace_id, language_name.as_ref().to_string(), worktree_id.to_usize(), relative_worktree_path))?;
Ok(toolchain.into_iter().next().and_then(|(name, path, raw_json)| Some(Toolchain { Ok(toolchain.into_iter().next().and_then(|(name, path, raw_json)| Some(Toolchain {
name: name.into(), name: name.into(),
path: path.into(), path: path.into(),
language_name, language_name,
as_json: serde_json::Value::from_str(&raw_json).ok()? as_json: serde_json::Value::from_str(&raw_json).ok()?,
}))) })))
}) })
.await .await
@ -1456,7 +1454,7 @@ impl WorkspaceDb {
.select_bound(sql!( .select_bound(sql!(
SELECT name, path, worktree_id, relative_worktree_path, language_name, raw_json FROM toolchains WHERE workspace_id = ? SELECT name, path, worktree_id, relative_worktree_path, language_name, raw_json FROM toolchains WHERE workspace_id = ?
)) ))
.context("Preparing insertion")?; .context("select toolchains")?;
let toolchain: Vec<(String, String, u64, String, String, String)> = let toolchain: Vec<(String, String, u64, String, String, String)> =
select(workspace_id)?; select(workspace_id)?;
@ -1465,7 +1463,7 @@ impl WorkspaceDb {
name: name.into(), name: name.into(),
path: path.into(), path: path.into(),
language_name: LanguageName::new(&language_name), language_name: LanguageName::new(&language_name),
as_json: serde_json::Value::from_str(&raw_json).ok()? as_json: serde_json::Value::from_str(&raw_json).ok()?,
}, WorktreeId::from_proto(worktree_id), Arc::from(relative_worktree_path.as_ref())))).collect()) }, WorktreeId::from_proto(worktree_id), Arc::from(relative_worktree_path.as_ref())))).collect())
}) })
.await .await