task_template.rs

  1use anyhow::{Context as _, bail};
  2use collections::{HashMap, HashSet};
  3use schemars::JsonSchema;
  4use serde::{Deserialize, Serialize};
  5use sha2::{Digest, Sha256};
  6use std::path::PathBuf;
  7use util::schemars::DefaultDenyUnknownFields;
  8use util::serde::default_true;
  9use util::{ResultExt, truncate_and_remove_front};
 10
 11use crate::{
 12    AttachRequest, ResolvedTask, RevealTarget, Shell, SpawnInTerminal, TaskContext, TaskId,
 13    VariableName, ZED_VARIABLE_NAME_PREFIX, serde_helpers::non_empty_string_vec,
 14};
 15
 16/// A template definition of a Zed task to run.
 17/// May use the [`VariableName`] to get the corresponding substitutions into its fields.
 18///
 19/// Template itself is not ready to spawn a task, it needs to be resolved with a [`TaskContext`] first, that
 20/// contains all relevant Zed state in task variables.
 21/// A single template may produce different tasks (or none) for different contexts.
 22#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 23#[serde(rename_all = "snake_case")]
 24pub struct TaskTemplate {
 25    /// Human readable name of the task to display in the UI.
 26    pub label: String,
 27    /// Executable command to spawn.
 28    pub command: String,
 29    /// Arguments to the command.
 30    #[serde(default)]
 31    pub args: Vec<String>,
 32    /// Env overrides for the command, will be appended to the terminal's environment from the settings.
 33    #[serde(default)]
 34    pub env: HashMap<String, String>,
 35    /// Current working directory to spawn the command into, defaults to current project root.
 36    #[serde(default)]
 37    pub cwd: Option<String>,
 38    /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
 39    #[serde(default)]
 40    pub use_new_terminal: bool,
 41    /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
 42    #[serde(default)]
 43    pub allow_concurrent_runs: bool,
 44    /// What to do with the terminal pane and tab, after the command was started:
 45    /// * `always` — always show the task's pane, and focus the corresponding tab in it (default)
 46    // * `no_focus` — always show the task's pane, add the task's tab in it, but don't focus it
 47    // * `never` — do not alter focus, but still add/reuse the task's tab in its pane
 48    #[serde(default)]
 49    pub reveal: RevealStrategy,
 50    /// Where to place the task's terminal item after starting the task.
 51    /// * `dock` — in the terminal dock, "regular" terminal items' place (default).
 52    /// * `center` — in the central pane group, "main" editor area.
 53    #[serde(default)]
 54    pub reveal_target: RevealTarget,
 55    /// What to do with the terminal pane and tab, after the command had finished:
 56    /// * `never` — do nothing when the command finishes (default)
 57    /// * `always` — always hide the terminal tab, hide the pane also if it was the last tab in it
 58    /// * `on_success` — hide the terminal tab on task success only, otherwise behaves similar to `always`.
 59    #[serde(default)]
 60    pub hide: HideStrategy,
 61    /// Represents the tags which this template attaches to.
 62    /// Adding this removes this task from other UI and gives you ability to run it by tag.
 63    #[serde(default, deserialize_with = "non_empty_string_vec")]
 64    #[schemars(length(min = 1))]
 65    pub tags: Vec<String>,
 66    /// Which shell to use when spawning the task.
 67    #[serde(default)]
 68    pub shell: Shell,
 69    /// Whether to show the task line in the task output.
 70    #[serde(default = "default_true")]
 71    pub show_summary: bool,
 72    /// Whether to show the command line in the task output.
 73    #[serde(default = "default_true")]
 74    pub show_command: bool,
 75}
 76
 77#[derive(Deserialize, Eq, PartialEq, Clone, Debug)]
 78/// Use to represent debug request type
 79pub enum DebugArgsRequest {
 80    /// launch (program, cwd) are stored in TaskTemplate as (command, cwd)
 81    Launch,
 82    /// Attach
 83    Attach(AttachRequest),
 84}
 85
 86/// What to do with the terminal pane and tab, after the command was started.
 87#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
 88#[serde(rename_all = "snake_case")]
 89pub enum RevealStrategy {
 90    /// Always show the task's pane, and focus the corresponding tab in it.
 91    #[default]
 92    Always,
 93    /// Always show the task's pane, add the task's tab in it, but don't focus it.
 94    NoFocus,
 95    /// Do not alter focus, but still add/reuse the task's tab in its pane.
 96    Never,
 97}
 98
 99/// What to do with the terminal pane and tab, after the command has finished.
100#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
101#[serde(rename_all = "snake_case")]
102pub enum HideStrategy {
103    /// Do nothing when the command finishes.
104    #[default]
105    Never,
106    /// Always hide the terminal tab, hide the pane also if it was the last tab in it.
107    Always,
108    /// Hide the terminal tab on task success only, otherwise behaves similar to `Always`.
109    OnSuccess,
110}
111
112/// A group of Tasks defined in a JSON file.
113#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
114pub struct TaskTemplates(pub Vec<TaskTemplate>);
115
116impl TaskTemplates {
117    /// Generates JSON schema of Tasks JSON template format.
118    pub fn generate_json_schema() -> serde_json_lenient::Value {
119        let schema = schemars::generate::SchemaSettings::draft2019_09()
120            .with_transform(DefaultDenyUnknownFields)
121            .into_generator()
122            .root_schema_for::<Self>();
123
124        serde_json_lenient::to_value(schema).unwrap()
125    }
126}
127
128impl TaskTemplate {
129    /// Replaces all `VariableName` task variables in the task template string fields.
130    /// If any replacement fails or the new string substitutions still have [`ZED_VARIABLE_NAME_PREFIX`],
131    /// `None` is returned.
132    ///
133    /// Every [`ResolvedTask`] gets a [`TaskId`], based on the `id_base` (to avoid collision with various task sources),
134    /// and hashes of its template and [`TaskContext`], see [`ResolvedTask`] fields' documentation for more details.
135    pub fn resolve_task(&self, id_base: &str, cx: &TaskContext) -> Option<ResolvedTask> {
136        if self.label.trim().is_empty() || self.command.trim().is_empty() {
137            return None;
138        }
139
140        let mut variable_names = HashMap::default();
141        let mut substituted_variables = HashSet::default();
142        let task_variables = cx
143            .task_variables
144            .0
145            .iter()
146            .map(|(key, value)| {
147                let key_string = key.to_string();
148                if !variable_names.contains_key(&key_string) {
149                    variable_names.insert(key_string.clone(), key.clone());
150                }
151                (key_string, value.as_str())
152            })
153            .collect::<HashMap<_, _>>();
154        let truncated_variables = truncate_variables(&task_variables);
155        let cwd = match self.cwd.as_deref() {
156            Some(cwd) => {
157                let substituted_cwd = substitute_all_template_variables_in_str(
158                    cwd,
159                    &task_variables,
160                    &variable_names,
161                    &mut substituted_variables,
162                )?;
163                Some(PathBuf::from(substituted_cwd))
164            }
165            None => None,
166        }
167        .or(cx.cwd.clone());
168        let full_label = substitute_all_template_variables_in_str(
169            &self.label,
170            &task_variables,
171            &variable_names,
172            &mut substituted_variables,
173        )?;
174
175        // Arbitrarily picked threshold below which we don't truncate any variables.
176        const TRUNCATION_THRESHOLD: usize = 64;
177
178        let human_readable_label = if full_label.len() > TRUNCATION_THRESHOLD {
179            substitute_all_template_variables_in_str(
180                &self.label,
181                &truncated_variables,
182                &variable_names,
183                &mut substituted_variables,
184            )?
185        } else {
186            full_label.clone()
187        }
188        .lines()
189        .fold(String::new(), |mut string, line| {
190            if string.is_empty() {
191                string.push_str(line);
192            } else {
193                string.push_str("\\n");
194                string.push_str(line);
195            }
196            string
197        });
198
199        let command = substitute_all_template_variables_in_str(
200            &self.command,
201            &task_variables,
202            &variable_names,
203            &mut substituted_variables,
204        )?;
205        let args_with_substitutions = substitute_all_template_variables_in_vec(
206            &self.args,
207            &task_variables,
208            &variable_names,
209            &mut substituted_variables,
210        )?;
211
212        let task_hash = to_hex_hash(self)
213            .context("hashing task template")
214            .log_err()?;
215        let variables_hash = to_hex_hash(&task_variables)
216            .context("hashing task variables")
217            .log_err()?;
218        let id = TaskId(format!("{id_base}_{task_hash}_{variables_hash}"));
219
220        let env = {
221            // Start with the project environment as the base.
222            let mut env = cx.project_env.clone();
223
224            // Extend that environment with what's defined in the TaskTemplate
225            env.extend(self.env.clone());
226
227            // Then we replace all task variables that could be set in environment variables
228            let mut env = substitute_all_template_variables_in_map(
229                &env,
230                &task_variables,
231                &variable_names,
232                &mut substituted_variables,
233            )?;
234
235            // Last step: set the task variables as environment variables too
236            env.extend(task_variables.into_iter().map(|(k, v)| (k, v.to_owned())));
237            env
238        };
239
240        Some(ResolvedTask {
241            id: id.clone(),
242            substituted_variables,
243            original_task: self.clone(),
244            resolved_label: full_label.clone(),
245            resolved: SpawnInTerminal {
246                id,
247                cwd,
248                full_label,
249                label: human_readable_label,
250                command_label: args_with_substitutions.iter().fold(
251                    command.clone(),
252                    |mut command_label, arg| {
253                        command_label.push(' ');
254                        command_label.push_str(arg);
255                        command_label
256                    },
257                ),
258                command: Some(command),
259                args: args_with_substitutions,
260                env,
261                use_new_terminal: self.use_new_terminal,
262                allow_concurrent_runs: self.allow_concurrent_runs,
263                reveal: self.reveal,
264                reveal_target: self.reveal_target,
265                hide: self.hide,
266                shell: self.shell.clone(),
267                show_summary: self.show_summary,
268                show_command: self.show_command,
269                show_rerun: true,
270            },
271        })
272    }
273}
274
275const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
276
277fn truncate_variables(task_variables: &HashMap<String, &str>) -> HashMap<String, String> {
278    task_variables
279        .iter()
280        .map(|(key, value)| {
281            (
282                key.clone(),
283                truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
284            )
285        })
286        .collect()
287}
288
289fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
290    let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
291    let mut hasher = Sha256::new();
292    hasher.update(json.as_bytes());
293    Ok(hex::encode(hasher.finalize()))
294}
295
296pub fn substitute_variables_in_str(template_str: &str, context: &TaskContext) -> Option<String> {
297    let mut variable_names = HashMap::default();
298    let mut substituted_variables = HashSet::default();
299    let task_variables = context
300        .task_variables
301        .0
302        .iter()
303        .map(|(key, value)| {
304            let key_string = key.to_string();
305            if !variable_names.contains_key(&key_string) {
306                variable_names.insert(key_string.clone(), key.clone());
307            }
308            (key_string, value.as_str())
309        })
310        .collect::<HashMap<_, _>>();
311    substitute_all_template_variables_in_str(
312        template_str,
313        &task_variables,
314        &variable_names,
315        &mut substituted_variables,
316    )
317}
318fn substitute_all_template_variables_in_str<A: AsRef<str>>(
319    template_str: &str,
320    task_variables: &HashMap<String, A>,
321    variable_names: &HashMap<String, VariableName>,
322    substituted_variables: &mut HashSet<VariableName>,
323) -> Option<String> {
324    let substituted_string = shellexpand::env_with_context(template_str, |var| {
325        // 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.
326        let colon_position = var.find(':').unwrap_or(var.len());
327        let (variable_name, default) = var.split_at(colon_position);
328        if let Some(name) = task_variables.get(variable_name) {
329            if let Some(substituted_variable) = variable_names.get(variable_name) {
330                substituted_variables.insert(substituted_variable.clone());
331            }
332
333            let mut name = name.as_ref().to_owned();
334            // Got a task variable hit
335            if !default.is_empty() {
336                name.push_str(default);
337            }
338            return Ok(Some(name));
339        } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
340            bail!("Unknown variable name: {variable_name}");
341        }
342        // This is an unknown variable.
343        // 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.
344        // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
345        if !default.is_empty() {
346            return Ok(Some(format!("${{{var}}}")));
347        }
348        // Else we can just return None and that variable will be left as is.
349        Ok(None)
350    })
351    .ok()?;
352    Some(substituted_string.into_owned())
353}
354
355fn substitute_all_template_variables_in_vec(
356    template_strs: &[String],
357    task_variables: &HashMap<String, &str>,
358    variable_names: &HashMap<String, VariableName>,
359    substituted_variables: &mut HashSet<VariableName>,
360) -> Option<Vec<String>> {
361    let mut expanded = Vec::with_capacity(template_strs.len());
362    for variable in template_strs {
363        let new_value = substitute_all_template_variables_in_str(
364            variable,
365            task_variables,
366            variable_names,
367            substituted_variables,
368        )?;
369        expanded.push(new_value);
370    }
371    Some(expanded)
372}
373
374pub fn substitute_variables_in_map(
375    keys_and_values: &HashMap<String, String>,
376    context: &TaskContext,
377) -> Option<HashMap<String, String>> {
378    let mut variable_names = HashMap::default();
379    let mut substituted_variables = HashSet::default();
380    let task_variables = context
381        .task_variables
382        .0
383        .iter()
384        .map(|(key, value)| {
385            let key_string = key.to_string();
386            if !variable_names.contains_key(&key_string) {
387                variable_names.insert(key_string.clone(), key.clone());
388            }
389            (key_string, value.as_str())
390        })
391        .collect::<HashMap<_, _>>();
392    substitute_all_template_variables_in_map(
393        keys_and_values,
394        &task_variables,
395        &variable_names,
396        &mut substituted_variables,
397    )
398}
399fn substitute_all_template_variables_in_map(
400    keys_and_values: &HashMap<String, String>,
401    task_variables: &HashMap<String, &str>,
402    variable_names: &HashMap<String, VariableName>,
403    substituted_variables: &mut HashSet<VariableName>,
404) -> Option<HashMap<String, String>> {
405    let mut new_map: HashMap<String, String> = Default::default();
406    for (key, value) in keys_and_values {
407        let new_value = substitute_all_template_variables_in_str(
408            value,
409            task_variables,
410            variable_names,
411            substituted_variables,
412        )?;
413        let new_key = substitute_all_template_variables_in_str(
414            key,
415            task_variables,
416            variable_names,
417            substituted_variables,
418        )?;
419        new_map.insert(new_key, new_value);
420    }
421    Some(new_map)
422}
423
424#[cfg(test)]
425mod tests {
426    use std::{borrow::Cow, path::Path};
427
428    use crate::{TaskVariables, VariableName};
429
430    use super::*;
431
432    const TEST_ID_BASE: &str = "test_base";
433
434    #[test]
435    fn test_resolving_templates_with_blank_command_and_label() {
436        let task_with_all_properties = TaskTemplate {
437            label: "test_label".to_string(),
438            command: "test_command".to_string(),
439            args: vec!["test_arg".to_string()],
440            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
441            ..TaskTemplate::default()
442        };
443
444        for task_with_blank_property in &[
445            TaskTemplate {
446                label: "".to_string(),
447                ..task_with_all_properties.clone()
448            },
449            TaskTemplate {
450                command: "".to_string(),
451                ..task_with_all_properties.clone()
452            },
453            TaskTemplate {
454                label: "".to_string(),
455                command: "".to_string(),
456                ..task_with_all_properties.clone()
457            },
458        ] {
459            assert_eq!(
460                task_with_blank_property.resolve_task(TEST_ID_BASE, &TaskContext::default()),
461                None,
462                "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
463            );
464        }
465    }
466
467    #[test]
468    fn test_template_cwd_resolution() {
469        let task_without_cwd = TaskTemplate {
470            cwd: None,
471            label: "test task".to_string(),
472            command: "echo 4".to_string(),
473            ..TaskTemplate::default()
474        };
475
476        let resolved_task = |task_template: &TaskTemplate, task_cx| {
477            let resolved_task = task_template
478                .resolve_task(TEST_ID_BASE, task_cx)
479                .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
480            assert_substituted_variables(&resolved_task, Vec::new());
481            resolved_task.resolved
482        };
483
484        let cx = TaskContext {
485            cwd: None,
486            task_variables: TaskVariables::default(),
487            project_env: HashMap::default(),
488        };
489        assert_eq!(
490            resolved_task(&task_without_cwd, &cx).cwd,
491            None,
492            "When neither task nor task context have cwd, it should be None"
493        );
494
495        let context_cwd = Path::new("a").join("b").join("c");
496        let cx = TaskContext {
497            cwd: Some(context_cwd.clone()),
498            task_variables: TaskVariables::default(),
499            project_env: HashMap::default(),
500        };
501        assert_eq!(
502            resolved_task(&task_without_cwd, &cx).cwd,
503            Some(context_cwd.clone()),
504            "TaskContext's cwd should be taken on resolve if task's cwd is None"
505        );
506
507        let task_cwd = Path::new("d").join("e").join("f");
508        let mut task_with_cwd = task_without_cwd.clone();
509        task_with_cwd.cwd = Some(task_cwd.display().to_string());
510        let task_with_cwd = task_with_cwd;
511
512        let cx = TaskContext {
513            cwd: None,
514            task_variables: TaskVariables::default(),
515            project_env: HashMap::default(),
516        };
517        assert_eq!(
518            resolved_task(&task_with_cwd, &cx).cwd,
519            Some(task_cwd.clone()),
520            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
521        );
522
523        let cx = TaskContext {
524            cwd: Some(context_cwd.clone()),
525            task_variables: TaskVariables::default(),
526            project_env: HashMap::default(),
527        };
528        assert_eq!(
529            resolved_task(&task_with_cwd, &cx).cwd,
530            Some(task_cwd),
531            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
532        );
533    }
534
535    #[test]
536    fn test_template_variables_resolution() {
537        let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
538        let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
539        let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
540        let all_variables = [
541            (VariableName::Row, "1234".to_string()),
542            (VariableName::Column, "5678".to_string()),
543            (VariableName::File, "test_file".to_string()),
544            (VariableName::SelectedText, "test_selected_text".to_string()),
545            (VariableName::Symbol, long_value.clone()),
546            (VariableName::WorktreeRoot, "/test_root/".to_string()),
547            (
548                custom_variable_1.clone(),
549                "test_custom_variable_1".to_string(),
550            ),
551            (
552                custom_variable_2.clone(),
553                "test_custom_variable_2".to_string(),
554            ),
555        ];
556
557        let task_with_all_variables = TaskTemplate {
558            label: format!(
559                "test label for {} and {}",
560                VariableName::Row.template_value(),
561                VariableName::Symbol.template_value(),
562            ),
563            command: format!(
564                "echo {} {}",
565                VariableName::File.template_value(),
566                VariableName::Symbol.template_value(),
567            ),
568            args: vec![
569                format!("arg1 {}", VariableName::SelectedText.template_value()),
570                format!("arg2 {}", VariableName::Column.template_value()),
571                format!("arg3 {}", VariableName::Symbol.template_value()),
572            ],
573            env: HashMap::from_iter([
574                ("test_env_key".to_string(), "test_env_var".to_string()),
575                (
576                    "env_key_1".to_string(),
577                    VariableName::WorktreeRoot.template_value(),
578                ),
579                (
580                    "env_key_2".to_string(),
581                    format!(
582                        "env_var_2 {} {}",
583                        custom_variable_1.template_value(),
584                        custom_variable_2.template_value()
585                    ),
586                ),
587                (
588                    "env_key_3".to_string(),
589                    format!("env_var_3 {}", VariableName::Symbol.template_value()),
590                ),
591            ]),
592            ..TaskTemplate::default()
593        };
594
595        let mut first_resolved_id = None;
596        for i in 0..15 {
597            let resolved_task = task_with_all_variables.resolve_task(
598                TEST_ID_BASE,
599                &TaskContext {
600                    cwd: None,
601                    task_variables: TaskVariables::from_iter(all_variables.clone()),
602                    project_env: HashMap::default(),
603                },
604            ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
605
606            match &first_resolved_id {
607                None => first_resolved_id = Some(resolved_task.id.clone()),
608                Some(first_id) => assert_eq!(
609                    &resolved_task.id, first_id,
610                    "Step {i}, for the same task template and context, there should be the same resolved task id"
611                ),
612            }
613
614            assert_eq!(
615                resolved_task.original_task, task_with_all_variables,
616                "Resolved task should store its template without changes"
617            );
618            assert_eq!(
619                resolved_task.resolved_label,
620                format!("test label for 1234 and {long_value}"),
621                "Resolved task label should be substituted with variables and those should not be shortened"
622            );
623            assert_substituted_variables(
624                &resolved_task,
625                all_variables.iter().map(|(name, _)| name.clone()).collect(),
626            );
627
628            let spawn_in_terminal = &resolved_task.resolved;
629            assert_eq!(
630                spawn_in_terminal.label,
631                format!(
632                    "test label for 1234 and …{}",
633                    &long_value[long_value.len() - MAX_DISPLAY_VARIABLE_LENGTH..]
634                ),
635                "Human-readable label should have long substitutions trimmed"
636            );
637            assert_eq!(
638                spawn_in_terminal.command.clone().unwrap(),
639                format!("echo test_file {long_value}"),
640                "Command should be substituted with variables and those should not be shortened"
641            );
642            assert_eq!(
643                spawn_in_terminal.args,
644                &[
645                    "arg1 test_selected_text",
646                    "arg2 5678",
647                    "arg3 010101010101010101010101010101010101010101010101010101010101",
648                ],
649                "Args should be substituted with variables"
650            );
651            assert_eq!(
652                spawn_in_terminal.command_label,
653                format!(
654                    "{} arg1 test_selected_text arg2 5678 arg3 {long_value}",
655                    spawn_in_terminal.command.clone().unwrap()
656                ),
657                "Command label args should be substituted with variables and those should not be shortened"
658            );
659
660            assert_eq!(
661                spawn_in_terminal
662                    .env
663                    .get("test_env_key")
664                    .map(|s| s.as_str()),
665                Some("test_env_var")
666            );
667            assert_eq!(
668                spawn_in_terminal.env.get("env_key_1").map(|s| s.as_str()),
669                Some("/test_root/")
670            );
671            assert_eq!(
672                spawn_in_terminal.env.get("env_key_2").map(|s| s.as_str()),
673                Some("env_var_2 test_custom_variable_1 test_custom_variable_2")
674            );
675            assert_eq!(
676                spawn_in_terminal.env.get("env_key_3"),
677                Some(&format!("env_var_3 {long_value}")),
678                "Env vars should be substituted with variables and those should not be shortened"
679            );
680        }
681
682        for i in 0..all_variables.len() {
683            let mut not_all_variables = all_variables.to_vec();
684            let removed_variable = not_all_variables.remove(i);
685            let resolved_task_attempt = task_with_all_variables.resolve_task(
686                TEST_ID_BASE,
687                &TaskContext {
688                    cwd: None,
689                    task_variables: TaskVariables::from_iter(not_all_variables),
690                    project_env: HashMap::default(),
691                },
692            );
693            assert_eq!(
694                resolved_task_attempt, None,
695                "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})"
696            );
697        }
698    }
699
700    #[test]
701    fn test_can_resolve_free_variables() {
702        let task = TaskTemplate {
703            label: "My task".into(),
704            command: "echo".into(),
705            args: vec!["$PATH".into()],
706            ..TaskTemplate::default()
707        };
708        let resolved_task = task
709            .resolve_task(TEST_ID_BASE, &TaskContext::default())
710            .unwrap();
711        assert_substituted_variables(&resolved_task, Vec::new());
712        let resolved = resolved_task.resolved;
713        assert_eq!(resolved.label, task.label);
714        assert_eq!(resolved.command, Some(task.command));
715        assert_eq!(resolved.args, task.args);
716    }
717
718    #[test]
719    fn test_errors_on_missing_zed_variable() {
720        let task = TaskTemplate {
721            label: "My task".into(),
722            command: "echo".into(),
723            args: vec!["$ZED_VARIABLE".into()],
724            ..TaskTemplate::default()
725        };
726        assert!(
727            task.resolve_task(TEST_ID_BASE, &TaskContext::default())
728                .is_none()
729        );
730    }
731
732    #[test]
733    fn test_symbol_dependent_tasks() {
734        let task_with_all_properties = TaskTemplate {
735            label: "test_label".to_string(),
736            command: "test_command".to_string(),
737            args: vec!["test_arg".to_string()],
738            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
739            ..TaskTemplate::default()
740        };
741        let cx = TaskContext {
742            cwd: None,
743            task_variables: TaskVariables::from_iter(Some((
744                VariableName::Symbol,
745                "test_symbol".to_string(),
746            ))),
747            project_env: HashMap::default(),
748        };
749
750        for (i, symbol_dependent_task) in [
751            TaskTemplate {
752                label: format!("test_label_{}", VariableName::Symbol.template_value()),
753                ..task_with_all_properties.clone()
754            },
755            TaskTemplate {
756                command: format!("test_command_{}", VariableName::Symbol.template_value()),
757                ..task_with_all_properties.clone()
758            },
759            TaskTemplate {
760                args: vec![format!(
761                    "test_arg_{}",
762                    VariableName::Symbol.template_value()
763                )],
764                ..task_with_all_properties.clone()
765            },
766            TaskTemplate {
767                env: HashMap::from_iter([(
768                    "test_env_key".to_string(),
769                    format!("test_env_var_{}", VariableName::Symbol.template_value()),
770                )]),
771                ..task_with_all_properties.clone()
772            },
773        ]
774        .into_iter()
775        .enumerate()
776        {
777            let resolved = symbol_dependent_task
778                .resolve_task(TEST_ID_BASE, &cx)
779                .unwrap_or_else(|| panic!("Failed to resolve task {symbol_dependent_task:?}"));
780            assert_eq!(
781                resolved.substituted_variables,
782                HashSet::from_iter(Some(VariableName::Symbol)),
783                "(index {i}) Expected the task to depend on symbol task variable: {resolved:?}"
784            )
785        }
786    }
787
788    #[track_caller]
789    fn assert_substituted_variables(resolved_task: &ResolvedTask, mut expected: Vec<VariableName>) {
790        let mut resolved_variables = resolved_task
791            .substituted_variables
792            .iter()
793            .cloned()
794            .collect::<Vec<_>>();
795        resolved_variables.sort_by_key(|var| var.to_string());
796        expected.sort_by_key(|var| var.to_string());
797        assert_eq!(resolved_variables, expected)
798    }
799
800    #[test]
801    fn substitute_funky_labels() {
802        let faulty_go_test = TaskTemplate {
803            label: format!(
804                "go test {}/{}",
805                VariableName::Symbol.template_value(),
806                VariableName::Symbol.template_value(),
807            ),
808            command: "go".into(),
809            args: vec![format!(
810                "^{}$/^{}$",
811                VariableName::Symbol.template_value(),
812                VariableName::Symbol.template_value()
813            )],
814            ..TaskTemplate::default()
815        };
816        let mut context = TaskContext::default();
817        context
818            .task_variables
819            .insert(VariableName::Symbol, "my-symbol".to_string());
820        assert!(faulty_go_test.resolve_task("base", &context).is_some());
821    }
822
823    #[test]
824    fn test_project_env() {
825        let all_variables = [
826            (VariableName::Row, "1234".to_string()),
827            (VariableName::Column, "5678".to_string()),
828            (VariableName::File, "test_file".to_string()),
829            (VariableName::Symbol, "my symbol".to_string()),
830        ];
831
832        let template = TaskTemplate {
833            label: "my task".to_string(),
834            command: format!(
835                "echo {} {}",
836                VariableName::File.template_value(),
837                VariableName::Symbol.template_value(),
838            ),
839            args: vec![],
840            env: HashMap::from_iter([
841                (
842                    "TASK_ENV_VAR1".to_string(),
843                    "TASK_ENV_VAR1_VALUE".to_string(),
844                ),
845                (
846                    "TASK_ENV_VAR2".to_string(),
847                    format!(
848                        "env_var_2 {} {}",
849                        VariableName::Row.template_value(),
850                        VariableName::Column.template_value()
851                    ),
852                ),
853                (
854                    "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
855                    "overwritten".to_string(),
856                ),
857            ]),
858            ..TaskTemplate::default()
859        };
860
861        let project_env = HashMap::from_iter([
862            (
863                "PROJECT_ENV_VAR1".to_string(),
864                "PROJECT_ENV_VAR1_VALUE".to_string(),
865            ),
866            (
867                "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
868                "PROJECT_ENV_WILL_BE_OVERWRITTEN_VALUE".to_string(),
869            ),
870        ]);
871
872        let context = TaskContext {
873            cwd: None,
874            task_variables: TaskVariables::from_iter(all_variables.clone()),
875            project_env,
876        };
877
878        let resolved = template
879            .resolve_task(TEST_ID_BASE, &context)
880            .unwrap()
881            .resolved;
882
883        assert_eq!(resolved.env["TASK_ENV_VAR1"], "TASK_ENV_VAR1_VALUE");
884        assert_eq!(resolved.env["TASK_ENV_VAR2"], "env_var_2 1234 5678");
885        assert_eq!(resolved.env["PROJECT_ENV_VAR1"], "PROJECT_ENV_VAR1_VALUE");
886        assert_eq!(
887            resolved.env["PROJECT_ENV_WILL_BE_OVERWRITTEN"],
888            "overwritten"
889        );
890    }
891}