1//! Baseline interface of Tasks in Zed: all tasks in Zed are intended to use those for implementing their own logic.
2#![deny(missing_docs)]
3
4pub mod static_source;
5mod task_template;
6mod vscode_format;
7
8use collections::HashMap;
9use gpui::ModelContext;
10use serde::Serialize;
11use std::any::Any;
12use std::borrow::Cow;
13use std::path::PathBuf;
14
15pub use task_template::{RevealStrategy, TaskTemplate, TaskTemplates};
16pub use vscode_format::VsCodeTaskFile;
17
18/// Task identifier, unique within the application.
19/// Based on it, task reruns and terminal tabs are managed.
20#[derive(Debug, Clone, PartialEq, Eq, Hash)]
21pub struct TaskId(pub String);
22
23/// Contains all information needed by Zed to spawn a new terminal tab for the given task.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct SpawnInTerminal {
26 /// Id of the task to use when determining task tab affinity.
27 pub id: TaskId,
28 /// Human readable name of the terminal tab.
29 pub label: String,
30 /// Executable command to spawn.
31 pub command: String,
32 /// Arguments to the command.
33 pub args: Vec<String>,
34 /// Current working directory to spawn the command into.
35 pub cwd: Option<PathBuf>,
36 /// Env overrides for the command, will be appended to the terminal's environment from the settings.
37 pub env: HashMap<String, String>,
38 /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
39 pub use_new_terminal: bool,
40 /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
41 pub allow_concurrent_runs: bool,
42 /// What to do with the terminal pane and tab, after the command was started.
43 pub reveal: RevealStrategy,
44}
45
46/// A final form of the [`TaskTemplate`], that got resolved with a particualar [`TaskContext`] and now is ready to spawn the actual task.
47#[derive(Clone, Debug, PartialEq, Eq)]
48pub struct ResolvedTask {
49 /// A way to distinguish tasks produced by the same template, but different contexts.
50 /// NOTE: Resolved tasks may have the same labels, commands and do the same things,
51 /// but still may have different ids if the context was different during the resolution.
52 /// Since the template has `env` field, for a generic task that may be a bash command,
53 /// so it's impossible to determine the id equality without more context in a generic case.
54 pub id: TaskId,
55 /// A template the task got resolved from.
56 pub original_task: TaskTemplate,
57 /// Full, unshortened label of the task after all resolutions are made.
58 pub resolved_label: String,
59 /// Further actions that need to take place after the resolved task is spawned,
60 /// with all task variables resolved.
61 pub resolved: Option<SpawnInTerminal>,
62}
63
64/// Variables, available for use in [`TaskContext`] when a Zed's [`TaskTemplate`] gets resolved into a [`ResolvedTask`].
65#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
66pub enum VariableName {
67 /// An absolute path of the currently opened file.
68 File,
69 /// An absolute path of the currently opened worktree, that contains the file.
70 WorktreeRoot,
71 /// A symbol text, that contains latest cursor/selection position.
72 Symbol,
73 /// A row with the latest cursor/selection position.
74 Row,
75 /// A column with the latest cursor/selection position.
76 Column,
77 /// Text from the latest selection.
78 SelectedText,
79 /// Custom variable, provided by the plugin or other external source.
80 /// Will be printed with `ZED_` prefix to avoid potential conflicts with other variables.
81 Custom(Cow<'static, str>),
82}
83
84impl VariableName {
85 /// Generates a `$VARIABLE`-like string value to be used in templates.
86 /// Custom variables are wrapped in `${}` to avoid substitution issues with whitespaces.
87 pub fn template_value(&self) -> String {
88 if matches!(self, Self::Custom(_)) {
89 format!("${{{self}}}")
90 } else {
91 format!("${self}")
92 }
93 }
94}
95
96/// A prefix that all [`VariableName`] variants are prefixed with when used in environment variables and similar template contexts.
97pub const ZED_VARIABLE_NAME_PREFIX: &str = "ZED_";
98
99impl std::fmt::Display for VariableName {
100 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
101 match self {
102 Self::File => write!(f, "{ZED_VARIABLE_NAME_PREFIX}FILE"),
103 Self::WorktreeRoot => write!(f, "{ZED_VARIABLE_NAME_PREFIX}WORKTREE_ROOT"),
104 Self::Symbol => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SYMBOL"),
105 Self::Row => write!(f, "{ZED_VARIABLE_NAME_PREFIX}ROW"),
106 Self::Column => write!(f, "{ZED_VARIABLE_NAME_PREFIX}COLUMN"),
107 Self::SelectedText => write!(f, "{ZED_VARIABLE_NAME_PREFIX}SELECTED_TEXT"),
108 Self::Custom(s) => write!(f, "{ZED_VARIABLE_NAME_PREFIX}CUSTOM_{s}"),
109 }
110 }
111}
112
113/// Container for predefined environment variables that describe state of Zed at the time the task was spawned.
114#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
115pub struct TaskVariables(HashMap<VariableName, String>);
116
117impl TaskVariables {
118 /// Converts the container into a map of environment variables and their values.
119 fn into_env_variables(self) -> HashMap<String, String> {
120 self.0
121 .into_iter()
122 .map(|(name, value)| (name.to_string(), value))
123 .collect()
124 }
125
126 /// Inserts another variable into the container, overwriting the existing one if it already exists — in this case, the old value is returned.
127 pub fn insert(&mut self, variable: VariableName, value: String) -> Option<String> {
128 self.0.insert(variable, value)
129 }
130
131 /// Extends the container with another one, overwriting the existing variables on collision.
132 pub fn extend(&mut self, other: Self) {
133 self.0.extend(other.0);
134 }
135}
136
137impl FromIterator<(VariableName, String)> for TaskVariables {
138 fn from_iter<T: IntoIterator<Item = (VariableName, String)>>(iter: T) -> Self {
139 Self(HashMap::from_iter(iter))
140 }
141}
142
143/// Keeps track of the file associated with a task and context of tasks execution (i.e. current file or current function).
144/// Keeps all Zed-related state inside, used to produce a resolved task out of its template.
145#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
146pub struct TaskContext {
147 /// A path to a directory in which the task should be executed.
148 pub cwd: Option<PathBuf>,
149 /// Additional environment variables associated with a given task.
150 pub task_variables: TaskVariables,
151}
152
153/// [`Source`] produces tasks that can be scheduled.
154///
155/// Implementations of this trait could be e.g. [`StaticSource`] that parses tasks from a .json files and provides process templates to be spawned;
156/// another one could be a language server providing lenses with tests or build server listing all targets for a given project.
157pub trait TaskSource: Any {
158 /// A way to erase the type of the source, processing and storing them generically.
159 fn as_any(&mut self) -> &mut dyn Any;
160 /// Collects all tasks available for scheduling.
161 fn tasks_to_schedule(&mut self, cx: &mut ModelContext<Box<dyn TaskSource>>) -> TaskTemplates;
162}