task_template.rs

  1use std::path::PathBuf;
  2
  3use anyhow::{bail, Context};
  4use collections::HashMap;
  5use schemars::{gen::SchemaSettings, JsonSchema};
  6use serde::{Deserialize, Serialize};
  7use sha2::{Digest, Sha256};
  8use util::{truncate_and_remove_front, ResultExt};
  9
 10use crate::{ResolvedTask, SpawnInTerminal, TaskContext, TaskId, ZED_VARIABLE_NAME_PREFIX};
 11
 12/// A template definition of a Zed task to run.
 13/// May use the [`VariableName`] to get the corresponding substitutions into its fields.
 14///
 15/// Template itself is not ready to spawn a task, it needs to be resolved with a [`TaskContext`] first, that
 16/// contains all relevant Zed state in task variables.
 17/// A single template may produce different tasks (or none) for different contexts.
 18#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 19#[serde(rename_all = "snake_case")]
 20pub struct TaskTemplate {
 21    /// Human readable name of the task to display in the UI.
 22    pub label: String,
 23    /// Executable command to spawn.
 24    pub command: String,
 25    /// Arguments to the command.
 26    #[serde(default)]
 27    pub args: Vec<String>,
 28    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 29    #[serde(default)]
 30    pub env: HashMap<String, String>,
 31    /// Current working directory to spawn the command into, defaults to current project root.
 32    #[serde(default)]
 33    pub cwd: Option<String>,
 34    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 35    #[serde(default)]
 36    pub use_new_terminal: bool,
 37    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
 38    #[serde(default)]
 39    pub allow_concurrent_runs: bool,
 40    /// What to do with the terminal pane and tab, after the command was started:
 41    /// * `always` — always show the terminal pane, add and focus the corresponding task's tab in it (default)
 42    /// * `never` — avoid changing current terminal pane focus, but still add/reuse the task's tab there
 43    #[serde(default)]
 44    pub reveal: RevealStrategy,
 45}
 46
 47/// What to do with the terminal pane and tab, after the command was started.
 48#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 49#[serde(rename_all = "snake_case")]
 50pub enum RevealStrategy {
 51    /// Always show the terminal pane, add and focus the corresponding task's tab in it.
 52    #[default]
 53    Always,
 54    /// Do not change terminal pane focus, but still add/reuse the task's tab there.
 55    Never,
 56}
 57
 58/// A group of Tasks defined in a JSON file.
 59#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 60pub struct TaskTemplates(pub Vec<TaskTemplate>);
 61
 62impl TaskTemplates {
 63    /// Generates JSON schema of Tasks JSON template format.
 64    pub fn generate_json_schema() -> serde_json_lenient::Value {
 65        let schema = SchemaSettings::draft07()
 66            .with(|settings| settings.option_add_null_type = false)
 67            .into_generator()
 68            .into_root_schema_for::<Self>();
 69
 70        serde_json_lenient::to_value(schema).unwrap()
 71    }
 72}
 73
 74impl TaskTemplate {
 75    /// Replaces all `VariableName` task variables in the task template string fields.
 76    /// If any replacement fails or the new string substitutions still have [`ZED_VARIABLE_NAME_PREFIX`],
 77    /// `None` is returned.
 78    ///
 79    /// Every [`ResolvedTask`] gets a [`TaskId`], based on the `id_base` (to avoid collision with various task sources),
 80    /// and hashes of its template and [`TaskContext`], see [`ResolvedTask`] fields' documentation for more details.
 81    pub fn resolve_task(&self, id_base: &str, cx: TaskContext) -> Option<ResolvedTask> {
 82        if self.label.trim().is_empty() || self.command.trim().is_empty() {
 83            return None;
 84        }
 85        let TaskContext {
 86            cwd,
 87            task_variables,
 88        } = cx;
 89        let task_variables = task_variables.into_env_variables();
 90        let truncated_variables = truncate_variables(&task_variables);
 91        let cwd = match self.cwd.as_deref() {
 92            Some(cwd) => Some(substitute_all_template_variables_in_str(
 93                cwd,
 94                &task_variables,
 95            )?),
 96            None => None,
 97        }
 98        .map(PathBuf::from)
 99        .or(cwd);
100        let shortened_label =
101            substitute_all_template_variables_in_str(&self.label, &truncated_variables)?;
102        let full_label = substitute_all_template_variables_in_str(&self.label, &task_variables)?;
103        let command = substitute_all_template_variables_in_str(&self.command, &task_variables)?;
104        let args = substitute_all_template_variables_in_vec(self.args.clone(), &task_variables)?;
105
106        let task_hash = to_hex_hash(&self)
107            .context("hashing task template")
108            .log_err()?;
109        let variables_hash = to_hex_hash(&task_variables)
110            .context("hashing task variables")
111            .log_err()?;
112        let id = TaskId(format!("{id_base}_{task_hash}_{variables_hash}"));
113        let mut env = substitute_all_template_variables_in_map(self.env.clone(), &task_variables)?;
114        env.extend(task_variables);
115        Some(ResolvedTask {
116            id: id.clone(),
117            original_task: self.clone(),
118            resolved_label: full_label.clone(),
119            resolved: Some(SpawnInTerminal {
120                id,
121                cwd,
122                full_label,
123                label: shortened_label,
124                command,
125                args,
126                env,
127                use_new_terminal: self.use_new_terminal,
128                allow_concurrent_runs: self.allow_concurrent_runs,
129                reveal: self.reveal,
130            }),
131        })
132    }
133}
134
135const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
136
137fn truncate_variables(task_variables: &HashMap<String, String>) -> HashMap<String, String> {
138    task_variables
139        .iter()
140        .map(|(key, value)| {
141            (
142                key.clone(),
143                truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
144            )
145        })
146        .collect()
147}
148
149fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
150    let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
151    let mut hasher = Sha256::new();
152    hasher.update(json.as_bytes());
153    Ok(hex::encode(hasher.finalize()))
154}
155
156fn substitute_all_template_variables_in_str(
157    template_str: &str,
158    task_variables: &HashMap<String, String>,
159) -> Option<String> {
160    let substituted_string = shellexpand::env_with_context(&template_str, |var| {
161        // Colons denote a default value in case the variable is not set. We want to preserve that default, as otherwise shellexpand will substitute it for us.
162        let colon_position = var.find(':').unwrap_or(var.len());
163        let (variable_name, default) = var.split_at(colon_position);
164        let append_previous_default = |ret: &mut String| {
165            if !default.is_empty() {
166                ret.push_str(default);
167            }
168        };
169        if let Some(mut name) = task_variables.get(variable_name).cloned() {
170            // Got a task variable hit
171            append_previous_default(&mut name);
172            return Ok(Some(name));
173        } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
174            bail!("Unknown variable name: {}", variable_name);
175        }
176        // This is an unknown variable.
177        // We should not error out, as they may come from user environment (e.g. $PATH). That means that the variable substitution might not be perfect.
178        // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
179        if !default.is_empty() {
180            return Ok(Some(format!("${{{var}}}")));
181        }
182        // Else we can just return None and that variable will be left as is.
183        Ok(None)
184    })
185    .ok()?;
186    Some(substituted_string.into_owned())
187}
188
189fn substitute_all_template_variables_in_vec(
190    mut template_strs: Vec<String>,
191    task_variables: &HashMap<String, String>,
192) -> Option<Vec<String>> {
193    for variable in template_strs.iter_mut() {
194        let new_value = substitute_all_template_variables_in_str(&variable, task_variables)?;
195        *variable = new_value;
196    }
197    Some(template_strs)
198}
199
200fn substitute_all_template_variables_in_map(
201    keys_and_values: HashMap<String, String>,
202    task_variables: &HashMap<String, String>,
203) -> Option<HashMap<String, String>> {
204    let mut new_map: HashMap<String, String> = Default::default();
205    for (key, value) in keys_and_values {
206        let new_value = substitute_all_template_variables_in_str(&value, task_variables)?;
207        let new_key = substitute_all_template_variables_in_str(&key, task_variables)?;
208        new_map.insert(new_key, new_value);
209    }
210    Some(new_map)
211}
212
213#[cfg(test)]
214mod tests {
215    use std::{borrow::Cow, path::Path};
216
217    use crate::{TaskVariables, VariableName};
218
219    use super::*;
220
221    const TEST_ID_BASE: &str = "test_base";
222
223    #[test]
224    fn test_resolving_templates_with_blank_command_and_label() {
225        let task_with_all_properties = TaskTemplate {
226            label: "test_label".to_string(),
227            command: "test_command".to_string(),
228            args: vec!["test_arg".to_string()],
229            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
230            ..TaskTemplate::default()
231        };
232
233        for task_with_blank_property in &[
234            TaskTemplate {
235                label: "".to_string(),
236                ..task_with_all_properties.clone()
237            },
238            TaskTemplate {
239                command: "".to_string(),
240                ..task_with_all_properties.clone()
241            },
242            TaskTemplate {
243                label: "".to_string(),
244                command: "".to_string(),
245                ..task_with_all_properties.clone()
246            },
247        ] {
248            assert_eq!(
249                task_with_blank_property.resolve_task(TEST_ID_BASE, TaskContext::default()),
250                None,
251                "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
252            );
253        }
254    }
255
256    #[test]
257    fn test_template_cwd_resolution() {
258        let task_without_cwd = TaskTemplate {
259            cwd: None,
260            label: "test task".to_string(),
261            command: "echo 4".to_string(),
262            ..TaskTemplate::default()
263        };
264
265        let resolved_task = |task_template: &TaskTemplate, task_cx| {
266            let resolved_task = task_template
267                .resolve_task(TEST_ID_BASE, task_cx)
268                .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
269            resolved_task
270                .resolved
271                .clone()
272                .unwrap_or_else(|| {
273                    panic!("failed to get resolve data for resolved task. Template: {task_without_cwd:?} Resolved: {resolved_task:?}")
274                })
275        };
276
277        assert_eq!(
278            resolved_task(
279                &task_without_cwd,
280                TaskContext {
281                    cwd: None,
282                    task_variables: TaskVariables::default(),
283                }
284            )
285            .cwd,
286            None,
287            "When neither task nor task context have cwd, it should be None"
288        );
289
290        let context_cwd = Path::new("a").join("b").join("c");
291        assert_eq!(
292            resolved_task(
293                &task_without_cwd,
294                TaskContext {
295                    cwd: Some(context_cwd.clone()),
296                    task_variables: TaskVariables::default(),
297                }
298            )
299            .cwd
300            .as_deref(),
301            Some(context_cwd.as_path()),
302            "TaskContext's cwd should be taken on resolve if task's cwd is None"
303        );
304
305        let task_cwd = Path::new("d").join("e").join("f");
306        let mut task_with_cwd = task_without_cwd.clone();
307        task_with_cwd.cwd = Some(task_cwd.display().to_string());
308        let task_with_cwd = task_with_cwd;
309
310        assert_eq!(
311            resolved_task(
312                &task_with_cwd,
313                TaskContext {
314                    cwd: None,
315                    task_variables: TaskVariables::default(),
316                }
317            )
318            .cwd
319            .as_deref(),
320            Some(task_cwd.as_path()),
321            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
322        );
323
324        assert_eq!(
325            resolved_task(
326                &task_with_cwd,
327                TaskContext {
328                    cwd: Some(context_cwd.clone()),
329                    task_variables: TaskVariables::default(),
330                }
331            )
332            .cwd
333            .as_deref(),
334            Some(task_cwd.as_path()),
335            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
336        );
337    }
338
339    #[test]
340    fn test_template_variables_resolution() {
341        let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
342        let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
343        let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
344        let all_variables = [
345            (VariableName::Row, "1234".to_string()),
346            (VariableName::Column, "5678".to_string()),
347            (VariableName::File, "test_file".to_string()),
348            (VariableName::SelectedText, "test_selected_text".to_string()),
349            (VariableName::Symbol, long_value.clone()),
350            (VariableName::WorktreeRoot, "/test_root/".to_string()),
351            (
352                custom_variable_1.clone(),
353                "test_custom_variable_1".to_string(),
354            ),
355            (
356                custom_variable_2.clone(),
357                "test_custom_variable_2".to_string(),
358            ),
359        ];
360
361        let task_with_all_variables = TaskTemplate {
362            label: format!(
363                "test label for {} and {}",
364                VariableName::Row.template_value(),
365                VariableName::Symbol.template_value(),
366            ),
367            command: format!(
368                "echo {} {}",
369                VariableName::File.template_value(),
370                VariableName::Symbol.template_value(),
371            ),
372            args: vec![
373                format!("arg1 {}", VariableName::SelectedText.template_value()),
374                format!("arg2 {}", VariableName::Column.template_value()),
375                format!("arg3 {}", VariableName::Symbol.template_value()),
376            ],
377            env: HashMap::from_iter([
378                ("test_env_key".to_string(), "test_env_var".to_string()),
379                (
380                    "env_key_1".to_string(),
381                    VariableName::WorktreeRoot.template_value(),
382                ),
383                (
384                    "env_key_2".to_string(),
385                    format!(
386                        "env_var_2_{}_{}",
387                        custom_variable_1.template_value(),
388                        custom_variable_2.template_value()
389                    ),
390                ),
391                (
392                    "env_key_3".to_string(),
393                    format!("env_var_3_{}", VariableName::Symbol.template_value()),
394                ),
395            ]),
396            ..TaskTemplate::default()
397        };
398
399        let mut first_resolved_id = None;
400        for i in 0..15 {
401            let resolved_task = task_with_all_variables.resolve_task(
402                TEST_ID_BASE,
403                TaskContext {
404                    cwd: None,
405                    task_variables: TaskVariables::from_iter(all_variables.clone()),
406                },
407            ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
408
409            match &first_resolved_id {
410                None => first_resolved_id = Some(resolved_task.id),
411                Some(first_id) => assert_eq!(
412                    &resolved_task.id, first_id,
413                    "Step {i}, for the same task template and context, there should be the same resolved task id"
414                ),
415            }
416
417            assert_eq!(
418                resolved_task.original_task, task_with_all_variables,
419                "Resolved task should store its template without changes"
420            );
421            assert_eq!(
422                resolved_task.resolved_label,
423                format!("test label for 1234 and {long_value}"),
424                "Resolved task label should be substituted with variables and those should not be shortened"
425            );
426
427            let spawn_in_terminal = resolved_task
428                .resolved
429                .as_ref()
430                .expect("should have resolved a spawn in terminal task");
431            assert_eq!(
432                spawn_in_terminal.label,
433                format!(
434                    "test label for 1234 and …{}",
435                    &long_value[..=MAX_DISPLAY_VARIABLE_LENGTH]
436                ),
437                "Human-readable label should have long substitutions trimmed"
438            );
439            assert_eq!(
440                spawn_in_terminal.command,
441                format!("echo test_file {long_value}"),
442                "Command should be substituted with variables and those should not be shortened"
443            );
444            assert_eq!(
445                spawn_in_terminal.args,
446                &[
447                    "arg1 test_selected_text",
448                    "arg2 5678",
449                    &format!("arg3 {long_value}")
450                ],
451                "Args should be substituted with variables and those should not be shortened"
452            );
453
454            assert_eq!(
455                spawn_in_terminal
456                    .env
457                    .get("test_env_key")
458                    .map(|s| s.as_str()),
459                Some("test_env_var")
460            );
461            assert_eq!(
462                spawn_in_terminal.env.get("env_key_1").map(|s| s.as_str()),
463                Some("/test_root/")
464            );
465            assert_eq!(
466                spawn_in_terminal.env.get("env_key_2").map(|s| s.as_str()),
467                Some("env_var_2_test_custom_variable_1_test_custom_variable_2")
468            );
469            assert_eq!(
470                spawn_in_terminal.env.get("env_key_3"),
471                Some(&format!("env_var_3_{long_value}")),
472                "Env vars should be substituted with variables and those should not be shortened"
473            );
474        }
475
476        for i in 0..all_variables.len() {
477            let mut not_all_variables = all_variables.to_vec();
478            let removed_variable = not_all_variables.remove(i);
479            let resolved_task_attempt = task_with_all_variables.resolve_task(
480                TEST_ID_BASE,
481                TaskContext {
482                    cwd: None,
483                    task_variables: TaskVariables::from_iter(not_all_variables),
484                },
485            );
486            assert_eq!(resolved_task_attempt, None, "If any of the Zed task variables is not substituted, the task should not be resolved, but got some resolution without the variable {removed_variable:?} (index {i})");
487        }
488    }
489
490    #[test]
491    fn test_can_resolve_free_variables() {
492        let task = TaskTemplate {
493            label: "My task".into(),
494            command: "echo".into(),
495            args: vec!["$PATH".into()],
496            ..Default::default()
497        };
498        let resolved = task
499            .resolve_task(TEST_ID_BASE, TaskContext::default())
500            .unwrap()
501            .resolved
502            .unwrap();
503        assert_eq!(resolved.label, task.label);
504        assert_eq!(resolved.command, task.command);
505        assert_eq!(resolved.args, task.args);
506    }
507
508    #[test]
509    fn test_errors_on_missing_zed_variable() {
510        let task = TaskTemplate {
511            label: "My task".into(),
512            command: "echo".into(),
513            args: vec!["$ZED_VARIABLE".into()],
514            ..Default::default()
515        };
516        assert!(task
517            .resolve_task(TEST_ID_BASE, TaskContext::default())
518            .is_none());
519    }
520}