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        let task_hash = to_hex_hash(self)
106            .context("hashing task template")
107            .log_err()?;
108        let variables_hash = to_hex_hash(&task_variables)
109            .context("hashing task variables")
110            .log_err()?;
111        let id = TaskId(format!("{id_base}_{task_hash}_{variables_hash}"));
112        let mut env = substitute_all_template_variables_in_map(self.env.clone(), &task_variables)?;
113        env.extend(task_variables);
114        Some(ResolvedTask {
115            id: id.clone(),
116            original_task: self.clone(),
117            resolved_label: full_label,
118            resolved: Some(SpawnInTerminal {
119                id,
120                cwd,
121                label: shortened_label,
122                command,
123                args,
124                env,
125                use_new_terminal: self.use_new_terminal,
126                allow_concurrent_runs: self.allow_concurrent_runs,
127                reveal: self.reveal,
128            }),
129        })
130    }
131}
132
133const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
134
135fn truncate_variables(task_variables: &HashMap<String, String>) -> HashMap<String, String> {
136    task_variables
137        .iter()
138        .map(|(key, value)| {
139            (
140                key.clone(),
141                truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
142            )
143        })
144        .collect()
145}
146
147fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
148    let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
149    let mut hasher = Sha256::new();
150    hasher.update(json.as_bytes());
151    Ok(hex::encode(hasher.finalize()))
152}
153
154fn substitute_all_template_variables_in_str(
155    template_str: &str,
156    task_variables: &HashMap<String, String>,
157) -> Option<String> {
158    let substituted_string = shellexpand::env_with_context(&template_str, |var| {
159        // 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.
160        let colon_position = var.find(':').unwrap_or(var.len());
161        let (variable_name, default) = var.split_at(colon_position);
162        let append_previous_default = |ret: &mut String| {
163            if !default.is_empty() {
164                ret.push_str(default);
165            }
166        };
167        if let Some(mut name) = task_variables.get(variable_name).cloned() {
168            // Got a task variable hit
169            append_previous_default(&mut name);
170            return Ok(Some(name));
171        } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
172            bail!("Unknown variable name: {}", variable_name);
173        }
174        // This is an unknown variable.
175        // 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.
176        // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
177        if !default.is_empty() {
178            return Ok(Some(format!("${{{var}}}")));
179        }
180        // Else we can just return None and that variable will be left as is.
181        Ok(None)
182    })
183    .ok()?;
184    Some(substituted_string.into_owned())
185}
186
187fn substitute_all_template_variables_in_vec(
188    mut template_strs: Vec<String>,
189    task_variables: &HashMap<String, String>,
190) -> Option<Vec<String>> {
191    for variable in template_strs.iter_mut() {
192        let new_value = substitute_all_template_variables_in_str(&variable, task_variables)?;
193        *variable = new_value;
194    }
195    Some(template_strs)
196}
197
198fn substitute_all_template_variables_in_map(
199    keys_and_values: HashMap<String, String>,
200    task_variables: &HashMap<String, String>,
201) -> Option<HashMap<String, String>> {
202    let mut new_map: HashMap<String, String> = Default::default();
203    for (key, value) in keys_and_values {
204        let new_value = substitute_all_template_variables_in_str(&value, task_variables)?;
205        let new_key = substitute_all_template_variables_in_str(&key, task_variables)?;
206        new_map.insert(new_key, new_value);
207    }
208    Some(new_map)
209}
210
211#[cfg(test)]
212mod tests {
213    use std::{borrow::Cow, path::Path};
214
215    use crate::{TaskVariables, VariableName};
216
217    use super::*;
218
219    const TEST_ID_BASE: &str = "test_base";
220
221    #[test]
222    fn test_resolving_templates_with_blank_command_and_label() {
223        let task_with_all_properties = TaskTemplate {
224            label: "test_label".to_string(),
225            command: "test_command".to_string(),
226            args: vec!["test_arg".to_string()],
227            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
228            ..TaskTemplate::default()
229        };
230
231        for task_with_blank_property in &[
232            TaskTemplate {
233                label: "".to_string(),
234                ..task_with_all_properties.clone()
235            },
236            TaskTemplate {
237                command: "".to_string(),
238                ..task_with_all_properties.clone()
239            },
240            TaskTemplate {
241                label: "".to_string(),
242                command: "".to_string(),
243                ..task_with_all_properties.clone()
244            },
245        ] {
246            assert_eq!(
247                task_with_blank_property.resolve_task(TEST_ID_BASE, TaskContext::default()),
248                None,
249                "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
250            );
251        }
252    }
253
254    #[test]
255    fn test_template_cwd_resolution() {
256        let task_without_cwd = TaskTemplate {
257            cwd: None,
258            label: "test task".to_string(),
259            command: "echo 4".to_string(),
260            ..TaskTemplate::default()
261        };
262
263        let resolved_task = |task_template: &TaskTemplate, task_cx| {
264            let resolved_task = task_template
265                .resolve_task(TEST_ID_BASE, task_cx)
266                .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
267            resolved_task
268                .resolved
269                .clone()
270                .unwrap_or_else(|| {
271                    panic!("failed to get resolve data for resolved task. Template: {task_without_cwd:?} Resolved: {resolved_task:?}")
272                })
273        };
274
275        assert_eq!(
276            resolved_task(
277                &task_without_cwd,
278                TaskContext {
279                    cwd: None,
280                    task_variables: TaskVariables::default(),
281                }
282            )
283            .cwd,
284            None,
285            "When neither task nor task context have cwd, it should be None"
286        );
287
288        let context_cwd = Path::new("a").join("b").join("c");
289        assert_eq!(
290            resolved_task(
291                &task_without_cwd,
292                TaskContext {
293                    cwd: Some(context_cwd.clone()),
294                    task_variables: TaskVariables::default(),
295                }
296            )
297            .cwd
298            .as_deref(),
299            Some(context_cwd.as_path()),
300            "TaskContext's cwd should be taken on resolve if task's cwd is None"
301        );
302
303        let task_cwd = Path::new("d").join("e").join("f");
304        let mut task_with_cwd = task_without_cwd.clone();
305        task_with_cwd.cwd = Some(task_cwd.display().to_string());
306        let task_with_cwd = task_with_cwd;
307
308        assert_eq!(
309            resolved_task(
310                &task_with_cwd,
311                TaskContext {
312                    cwd: None,
313                    task_variables: TaskVariables::default(),
314                }
315            )
316            .cwd
317            .as_deref(),
318            Some(task_cwd.as_path()),
319            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
320        );
321
322        assert_eq!(
323            resolved_task(
324                &task_with_cwd,
325                TaskContext {
326                    cwd: Some(context_cwd.clone()),
327                    task_variables: TaskVariables::default(),
328                }
329            )
330            .cwd
331            .as_deref(),
332            Some(task_cwd.as_path()),
333            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
334        );
335    }
336
337    #[test]
338    fn test_template_variables_resolution() {
339        let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
340        let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
341        let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
342        let all_variables = [
343            (VariableName::Row, "1234".to_string()),
344            (VariableName::Column, "5678".to_string()),
345            (VariableName::File, "test_file".to_string()),
346            (VariableName::SelectedText, "test_selected_text".to_string()),
347            (VariableName::Symbol, long_value.clone()),
348            (VariableName::WorktreeRoot, "/test_root/".to_string()),
349            (
350                custom_variable_1.clone(),
351                "test_custom_variable_1".to_string(),
352            ),
353            (
354                custom_variable_2.clone(),
355                "test_custom_variable_2".to_string(),
356            ),
357        ];
358
359        let task_with_all_variables = TaskTemplate {
360            label: format!(
361                "test label for {} and {}",
362                VariableName::Row.template_value(),
363                VariableName::Symbol.template_value(),
364            ),
365            command: format!(
366                "echo {} {}",
367                VariableName::File.template_value(),
368                VariableName::Symbol.template_value(),
369            ),
370            args: vec![
371                format!("arg1 {}", VariableName::SelectedText.template_value()),
372                format!("arg2 {}", VariableName::Column.template_value()),
373                format!("arg3 {}", VariableName::Symbol.template_value()),
374            ],
375            env: HashMap::from_iter([
376                ("test_env_key".to_string(), "test_env_var".to_string()),
377                (
378                    "env_key_1".to_string(),
379                    VariableName::WorktreeRoot.template_value(),
380                ),
381                (
382                    "env_key_2".to_string(),
383                    format!(
384                        "env_var_2_{}_{}",
385                        custom_variable_1.template_value(),
386                        custom_variable_2.template_value()
387                    ),
388                ),
389                (
390                    "env_key_3".to_string(),
391                    format!("env_var_3_{}", VariableName::Symbol.template_value()),
392                ),
393            ]),
394            ..TaskTemplate::default()
395        };
396
397        let mut first_resolved_id = None;
398        for i in 0..15 {
399            let resolved_task = task_with_all_variables.resolve_task(
400                TEST_ID_BASE,
401                TaskContext {
402                    cwd: None,
403                    task_variables: TaskVariables::from_iter(all_variables.clone()),
404                },
405            ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
406
407            match &first_resolved_id {
408                None => first_resolved_id = Some(resolved_task.id),
409                Some(first_id) => assert_eq!(
410                    &resolved_task.id, first_id,
411                    "Step {i}, for the same task template and context, there should be the same resolved task id"
412                ),
413            }
414
415            assert_eq!(
416                resolved_task.original_task, task_with_all_variables,
417                "Resolved task should store its template without changes"
418            );
419            assert_eq!(
420                resolved_task.resolved_label,
421                format!("test label for 1234 and {long_value}"),
422                "Resolved task label should be substituted with variables and those should not be shortened"
423            );
424
425            let spawn_in_terminal = resolved_task
426                .resolved
427                .as_ref()
428                .expect("should have resolved a spawn in terminal task");
429            assert_eq!(
430                spawn_in_terminal.label,
431                format!(
432                    "test label for 1234 and …{}",
433                    &long_value[..=MAX_DISPLAY_VARIABLE_LENGTH]
434                ),
435                "Human-readable label should have long substitutions trimmed"
436            );
437            assert_eq!(
438                spawn_in_terminal.command,
439                format!("echo test_file {long_value}"),
440                "Command should be substituted with variables and those should not be shortened"
441            );
442            assert_eq!(
443                spawn_in_terminal.args,
444                &[
445                    "arg1 test_selected_text",
446                    "arg2 5678",
447                    &format!("arg3 {long_value}")
448                ],
449                "Args should be substituted with variables and those should not be shortened"
450            );
451
452            assert_eq!(
453                spawn_in_terminal
454                    .env
455                    .get("test_env_key")
456                    .map(|s| s.as_str()),
457                Some("test_env_var")
458            );
459            assert_eq!(
460                spawn_in_terminal.env.get("env_key_1").map(|s| s.as_str()),
461                Some("/test_root/")
462            );
463            assert_eq!(
464                spawn_in_terminal.env.get("env_key_2").map(|s| s.as_str()),
465                Some("env_var_2_test_custom_variable_1_test_custom_variable_2")
466            );
467            assert_eq!(
468                spawn_in_terminal.env.get("env_key_3"),
469                Some(&format!("env_var_3_{long_value}")),
470                "Env vars should be substituted with variables and those should not be shortened"
471            );
472        }
473
474        for i in 0..all_variables.len() {
475            let mut not_all_variables = all_variables.to_vec();
476            let removed_variable = not_all_variables.remove(i);
477            let resolved_task_attempt = task_with_all_variables.resolve_task(
478                TEST_ID_BASE,
479                TaskContext {
480                    cwd: None,
481                    task_variables: TaskVariables::from_iter(not_all_variables),
482                },
483            );
484            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})");
485        }
486    }
487
488    #[test]
489    fn test_can_resolve_free_variables() {
490        let task = TaskTemplate {
491            label: "My task".into(),
492            command: "echo".into(),
493            args: vec!["$PATH".into()],
494            ..Default::default()
495        };
496        let resolved = task
497            .resolve_task(TEST_ID_BASE, TaskContext::default())
498            .unwrap()
499            .resolved
500            .unwrap();
501        assert_eq!(resolved.label, task.label);
502        assert_eq!(resolved.command, task.command);
503        assert_eq!(resolved.args, task.args);
504    }
505
506    #[test]
507    fn test_errors_on_missing_zed_variable() {
508        let task = TaskTemplate {
509            label: "My task".into(),
510            command: "echo".into(),
511            args: vec!["$ZED_VARIABLE".into()],
512            ..Default::default()
513        };
514        assert!(task
515            .resolve_task(TEST_ID_BASE, TaskContext::default())
516            .is_none());
517    }
518}