Add static Runnables (#8009)
Part of #7108 This PR includes just the static runnables part. We went with **not** having a dedicated panel for runnables. This is just a 1st PR out of N, as we want to start exploring the dynamic runnables front. Still, all that work is going to happen once this gets merged. Release Notes: - Added initial, static Runnables support to Zed. Such runnables are defined in `runnables.json` file (accessible via `zed: open runnables` action) and they can be spawned with `runnables: spawn` action. --------- Co-authored-by: Kirill Bulatov <kirill@zed.dev> Co-authored-by: Pitor <pitor@zed.dev> Co-authored-by: Beniamin <beniamin@zagan.be>
This commit is contained in:
co-authored by
Kirill Bulatov
Pitor
Beniamin
parent
ca251babcd
commit
f17d0b5729
@@ -0,0 +1,68 @@
|
||||
//! Baseline interface of Runnables in Zed: all runnables in Zed are intended to use those for implementing their own logic.
|
||||
#![deny(missing_docs)]
|
||||
|
||||
mod static_runnable;
|
||||
pub mod static_source;
|
||||
|
||||
pub use static_runnable::StaticRunnable;
|
||||
|
||||
use collections::HashMap;
|
||||
use gpui::ModelContext;
|
||||
use std::any::Any;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Runnable identifier, unique within the application.
|
||||
/// Based on it, runnable reruns and terminal tabs are managed.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct RunnableId(String);
|
||||
|
||||
/// Contains all information needed by Zed to spawn a new terminal tab for the given runnable.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SpawnInTerminal {
|
||||
/// Id of the runnable to use when determining task tab affinity.
|
||||
pub id: RunnableId,
|
||||
/// Human readable name of the terminal tab.
|
||||
pub label: String,
|
||||
/// Executable command to spawn.
|
||||
pub command: String,
|
||||
/// Arguments to the command.
|
||||
pub args: Vec<String>,
|
||||
/// Current working directory to spawn the command into.
|
||||
pub cwd: Option<PathBuf>,
|
||||
/// Env overrides for the command, will be appended to the terminal's environment from the settings.
|
||||
pub env: HashMap<String, String>,
|
||||
/// Whether to use a new terminal tab or reuse the existing one to spawn the process.
|
||||
pub use_new_terminal: bool,
|
||||
/// Whether to allow multiple instances of the same runnable to be run, or rather wait for the existing ones to finish.
|
||||
pub allow_concurrent_runs: bool,
|
||||
}
|
||||
|
||||
/// Represents a short lived recipe of a runnable, whose main purpose
|
||||
/// is to get spawned.
|
||||
pub trait Runnable {
|
||||
/// Unique identifier of the runnable to spawn.
|
||||
fn id(&self) -> &RunnableId;
|
||||
/// Human readable name of the runnable to display in the UI.
|
||||
fn name(&self) -> &str;
|
||||
/// Task's current working directory. If `None`, current project's root will be used.
|
||||
fn cwd(&self) -> Option<&Path>;
|
||||
/// Sets up everything needed to spawn the runnable in the given directory (`cwd`).
|
||||
/// If a runnable is intended to be spawned in the terminal, it should return the corresponding struct filled with the data necessary.
|
||||
fn exec(&self, cwd: Option<PathBuf>) -> Option<SpawnInTerminal>;
|
||||
}
|
||||
|
||||
/// [`Source`] produces runnables that can be scheduled.
|
||||
///
|
||||
/// Implementations of this trait could be e.g. [`StaticSource`] that parses runnables from a .json files and provides process templates to be spawned;
|
||||
/// another one could be a language server providing lenses with tests or build server listing all targets for a given project.
|
||||
pub trait Source: Any {
|
||||
/// A way to erase the type of the source, processing and storing them generically.
|
||||
fn as_any(&mut self) -> &mut dyn Any;
|
||||
/// Collects all runnables available for scheduling, for the path given.
|
||||
fn runnables_for_path(
|
||||
&mut self,
|
||||
path: Option<&Path>,
|
||||
cx: &mut ModelContext<Box<dyn Source>>,
|
||||
) -> Vec<Arc<dyn Runnable>>;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! Definitions of runnables with a static file config definition, not dependent on the application state.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::{static_source::Definition, Runnable, RunnableId, SpawnInTerminal};
|
||||
|
||||
/// A single config file entry with the deserialized runnable definition.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct StaticRunnable {
|
||||
id: RunnableId,
|
||||
definition: Definition,
|
||||
}
|
||||
|
||||
impl StaticRunnable {
|
||||
pub(super) fn new(id: usize, runnable: Definition) -> Self {
|
||||
Self {
|
||||
id: RunnableId(format!("static_{}_{}", runnable.label, id)),
|
||||
definition: runnable,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Runnable for StaticRunnable {
|
||||
fn exec(&self, cwd: Option<PathBuf>) -> Option<SpawnInTerminal> {
|
||||
Some(SpawnInTerminal {
|
||||
id: self.id.clone(),
|
||||
cwd,
|
||||
use_new_terminal: self.definition.use_new_terminal,
|
||||
allow_concurrent_runs: self.definition.allow_concurrent_runs,
|
||||
label: self.definition.label.clone(),
|
||||
command: self.definition.command.clone(),
|
||||
args: self.definition.args.clone(),
|
||||
env: self.definition.env.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn name(&self) -> &str {
|
||||
&self.definition.label
|
||||
}
|
||||
|
||||
fn id(&self) -> &RunnableId {
|
||||
&self.id
|
||||
}
|
||||
|
||||
fn cwd(&self) -> Option<&Path> {
|
||||
self.definition.cwd.as_deref()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
//! A source of runnables, based on a static configuration, deserialized from the runnables config file, and related infrastructure for tracking changes to the file.
|
||||
|
||||
use std::{
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use collections::HashMap;
|
||||
use futures::StreamExt;
|
||||
use gpui::{AppContext, Context, Model, ModelContext, Subscription};
|
||||
use schemars::{gen::SchemaSettings, JsonSchema};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use util::ResultExt;
|
||||
|
||||
use crate::{Runnable, Source, StaticRunnable};
|
||||
use futures::channel::mpsc::UnboundedReceiver;
|
||||
|
||||
/// The source of runnables defined in a runnables config file.
|
||||
pub struct StaticSource {
|
||||
runnables: Vec<StaticRunnable>,
|
||||
_definitions: Model<TrackedFile<DefinitionProvider>>,
|
||||
_subscription: Subscription,
|
||||
}
|
||||
|
||||
/// Static runnable definition from the runnables config file.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub(crate) struct Definition {
|
||||
/// Human readable name of the runnable to display in the UI.
|
||||
pub label: String,
|
||||
/// Executable command to spawn.
|
||||
pub command: String,
|
||||
/// Arguments to the command.
|
||||
#[serde(default)]
|
||||
pub args: Vec<String>,
|
||||
/// Env overrides for the command, will be appended to the terminal's environment from the settings.
|
||||
#[serde(default)]
|
||||
pub env: HashMap<String, String>,
|
||||
/// Current working directory to spawn the command into, defaults to current project root.
|
||||
#[serde(default)]
|
||||
pub cwd: Option<PathBuf>,
|
||||
/// Whether to use a new terminal tab or reuse the existing one to spawn the process.
|
||||
#[serde(default)]
|
||||
pub use_new_terminal: bool,
|
||||
/// Whether to allow multiple instances of the same runnable to be run, or rather wait for the existing ones to finish.
|
||||
#[serde(default)]
|
||||
pub allow_concurrent_runs: bool,
|
||||
}
|
||||
|
||||
/// A group of Runnables defined in a JSON file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct DefinitionProvider {
|
||||
version: String,
|
||||
runnables: Vec<Definition>,
|
||||
}
|
||||
|
||||
impl DefinitionProvider {
|
||||
/// Generates JSON schema of Runnables JSON definition format.
|
||||
pub fn generate_json_schema() -> serde_json_lenient::Value {
|
||||
let schema = SchemaSettings::draft07()
|
||||
.with(|settings| settings.option_add_null_type = false)
|
||||
.into_generator()
|
||||
.into_root_schema_for::<Self>();
|
||||
|
||||
serde_json_lenient::to_value(schema).unwrap()
|
||||
}
|
||||
}
|
||||
/// A Wrapper around deserializable T that keeps track of it's contents
|
||||
/// via a provided channel. Once T value changes, the observers of [`TrackedFile`] are
|
||||
/// notified.
|
||||
struct TrackedFile<T> {
|
||||
parsed_contents: T,
|
||||
}
|
||||
|
||||
impl<T: for<'a> Deserialize<'a> + PartialEq + 'static> TrackedFile<T> {
|
||||
fn new(
|
||||
parsed_contents: T,
|
||||
mut tracker: UnboundedReceiver<String>,
|
||||
cx: &mut AppContext,
|
||||
) -> Model<Self> {
|
||||
cx.new_model(move |cx| {
|
||||
cx.spawn(|tracked_file, mut cx| async move {
|
||||
while let Some(new_contents) = tracker.next().await {
|
||||
let Some(new_contents) = serde_json_lenient::from_str(&new_contents).log_err()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
tracked_file.update(&mut cx, |tracked_file: &mut TrackedFile<T>, cx| {
|
||||
if tracked_file.parsed_contents != new_contents {
|
||||
tracked_file.parsed_contents = new_contents;
|
||||
cx.notify();
|
||||
};
|
||||
})?;
|
||||
}
|
||||
anyhow::Ok(())
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
Self { parsed_contents }
|
||||
})
|
||||
}
|
||||
|
||||
fn get(&self) -> &T {
|
||||
&self.parsed_contents
|
||||
}
|
||||
}
|
||||
|
||||
impl StaticSource {
|
||||
/// Initializes the static source, reacting on runnables config changes.
|
||||
pub fn new(
|
||||
runnables_file_tracker: UnboundedReceiver<String>,
|
||||
cx: &mut AppContext,
|
||||
) -> Model<Box<dyn Source>> {
|
||||
let definitions =
|
||||
TrackedFile::new(DefinitionProvider::default(), runnables_file_tracker, cx);
|
||||
cx.new_model(|cx| {
|
||||
let _subscription = cx.observe(
|
||||
&definitions,
|
||||
|source: &mut Box<(dyn Source + 'static)>, new_definitions, cx| {
|
||||
if let Some(static_source) = source.as_any().downcast_mut::<Self>() {
|
||||
static_source.runnables = new_definitions
|
||||
.read(cx)
|
||||
.get()
|
||||
.runnables
|
||||
.clone()
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, definition)| StaticRunnable::new(id, definition))
|
||||
.collect();
|
||||
cx.notify();
|
||||
}
|
||||
},
|
||||
);
|
||||
Box::new(Self {
|
||||
runnables: Vec::new(),
|
||||
_definitions: definitions,
|
||||
_subscription,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Source for StaticSource {
|
||||
fn runnables_for_path(
|
||||
&mut self,
|
||||
_: Option<&Path>,
|
||||
_: &mut ModelContext<Box<dyn Source>>,
|
||||
) -> Vec<Arc<dyn Runnable>> {
|
||||
self.runnables
|
||||
.clone()
|
||||
.into_iter()
|
||||
.map(|runnable| Arc::new(runnable) as Arc<dyn Runnable>)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn as_any(&mut self) -> &mut dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user