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::{AllowTrailingCommas, 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::Value {
119        let schema = schemars::generate::SchemaSettings::draft2019_09()
120            .with_transform(DefaultDenyUnknownFields)
121            .with_transform(AllowTrailingCommas)
122            .into_generator()
123            .root_schema_for::<Self>();
124
125        serde_json::to_value(schema).unwrap()
126    }
127}
128
129impl TaskTemplate {
130    /// Replaces all `VariableName` task variables in the task template string fields.
131    /// If any replacement fails or the new string substitutions still have [`ZED_VARIABLE_NAME_PREFIX`],
132    /// `None` is returned.
133    ///
134    /// Every [`ResolvedTask`] gets a [`TaskId`], based on the `id_base` (to avoid collision with various task sources),
135    /// and hashes of its template and [`TaskContext`], see [`ResolvedTask`] fields' documentation for more details.
136    pub fn resolve_task(&self, id_base: &str, cx: &TaskContext) -> Option<ResolvedTask> {
137        if self.label.trim().is_empty() || self.command.trim().is_empty() {
138            return None;
139        }
140
141        let mut variable_names = HashMap::default();
142        let mut substituted_variables = HashSet::default();
143        let task_variables = cx
144            .task_variables
145            .0
146            .iter()
147            .map(|(key, value)| {
148                let key_string = key.to_string();
149                if !variable_names.contains_key(&key_string) {
150                    variable_names.insert(key_string.clone(), key.clone());
151                }
152                (key_string, value.as_str())
153            })
154            .collect::<HashMap<_, _>>();
155        let truncated_variables = truncate_variables(&task_variables);
156        let cwd = match self.cwd.as_deref() {
157            Some(cwd) => {
158                let substituted_cwd = substitute_all_template_variables_in_str(
159                    cwd,
160                    &task_variables,
161                    &variable_names,
162                    &mut substituted_variables,
163                )?;
164                Some(PathBuf::from(substituted_cwd))
165            }
166            None => None,
167        }
168        .or(cx.cwd.clone());
169        let full_label = substitute_all_template_variables_in_str(
170            &self.label,
171            &task_variables,
172            &variable_names,
173            &mut substituted_variables,
174        )?;
175
176        // Arbitrarily picked threshold below which we don't truncate any variables.
177        const TRUNCATION_THRESHOLD: usize = 64;
178
179        let human_readable_label = if full_label.len() > TRUNCATION_THRESHOLD {
180            substitute_all_template_variables_in_str(
181                &self.label,
182                &truncated_variables,
183                &variable_names,
184                &mut substituted_variables,
185            )?
186        } else {
187            #[allow(
188                clippy::redundant_clone,
189                reason = "We want to clone the full_label to avoid borrowing it in the fold closure"
190            )]
191            full_label.clone()
192        }
193        .lines()
194        .fold(String::new(), |mut string, line| {
195            if string.is_empty() {
196                string.push_str(line);
197            } else {
198                string.push_str("\\n");
199                string.push_str(line);
200            }
201            string
202        });
203
204        let command = substitute_all_template_variables_in_str(
205            &self.command,
206            &task_variables,
207            &variable_names,
208            &mut substituted_variables,
209        )?;
210        let args_with_substitutions = substitute_all_template_variables_in_vec(
211            &self.args,
212            &task_variables,
213            &variable_names,
214            &mut substituted_variables,
215        )?;
216
217        let task_hash = to_hex_hash(self)
218            .context("hashing task template")
219            .log_err()?;
220        let variables_hash = to_hex_hash(&task_variables)
221            .context("hashing task variables")
222            .log_err()?;
223        let id = TaskId(format!("{id_base}_{task_hash}_{variables_hash}"));
224
225        let env = {
226            // Start with the project environment as the base.
227            let mut env = cx.project_env.clone();
228
229            // Extend that environment with what's defined in the TaskTemplate
230            env.extend(self.env.clone());
231
232            // Then we replace all task variables that could be set in environment variables
233            let mut env = substitute_all_template_variables_in_map(
234                &env,
235                &task_variables,
236                &variable_names,
237                &mut substituted_variables,
238            )?;
239
240            // Last step: set the task variables as environment variables too
241            env.extend(task_variables.into_iter().map(|(k, v)| (k, v.to_owned())));
242            env
243        };
244
245        Some(ResolvedTask {
246            id: id.clone(),
247            substituted_variables,
248            original_task: self.clone(),
249            resolved_label: full_label.clone(),
250            resolved: SpawnInTerminal {
251                id,
252                cwd,
253                full_label,
254                label: human_readable_label,
255                command_label: args_with_substitutions.iter().fold(
256                    command.clone(),
257                    |mut command_label, arg| {
258                        command_label.push(' ');
259                        command_label.push_str(arg);
260                        command_label
261                    },
262                ),
263                command: Some(command),
264                args: args_with_substitutions,
265                env,
266                use_new_terminal: self.use_new_terminal,
267                allow_concurrent_runs: self.allow_concurrent_runs,
268                reveal: self.reveal,
269                reveal_target: self.reveal_target,
270                hide: self.hide,
271                shell: self.shell.clone(),
272                show_summary: self.show_summary,
273                show_command: self.show_command,
274                show_rerun: true,
275            },
276        })
277    }
278}
279
280const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
281
282fn truncate_variables(task_variables: &HashMap<String, &str>) -> HashMap<String, String> {
283    task_variables
284        .iter()
285        .map(|(key, value)| {
286            (
287                key.clone(),
288                truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
289            )
290        })
291        .collect()
292}
293
294fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
295    let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
296    let mut hasher = Sha256::new();
297    hasher.update(json.as_bytes());
298    Ok(hex::encode(hasher.finalize()))
299}
300
301pub fn substitute_variables_in_str(template_str: &str, context: &TaskContext) -> Option<String> {
302    let mut variable_names = HashMap::default();
303    let mut substituted_variables = HashSet::default();
304    let task_variables = context
305        .task_variables
306        .0
307        .iter()
308        .map(|(key, value)| {
309            let key_string = key.to_string();
310            if !variable_names.contains_key(&key_string) {
311                variable_names.insert(key_string.clone(), key.clone());
312            }
313            (key_string, value.as_str())
314        })
315        .collect::<HashMap<_, _>>();
316    substitute_all_template_variables_in_str(
317        template_str,
318        &task_variables,
319        &variable_names,
320        &mut substituted_variables,
321    )
322}
323fn substitute_all_template_variables_in_str<A: AsRef<str>>(
324    template_str: &str,
325    task_variables: &HashMap<String, A>,
326    variable_names: &HashMap<String, VariableName>,
327    substituted_variables: &mut HashSet<VariableName>,
328) -> Option<String> {
329    let substituted_string = shellexpand::env_with_context(template_str, |var| {
330        // 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.
331        let colon_position = var.find(':').unwrap_or(var.len());
332        let (variable_name, default) = var.split_at(colon_position);
333        if let Some(name) = task_variables.get(variable_name) {
334            if let Some(substituted_variable) = variable_names.get(variable_name) {
335                substituted_variables.insert(substituted_variable.clone());
336            }
337            // Got a task variable hit - use the variable value, ignore default
338            return Ok(Some(name.as_ref().to_owned()));
339        } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
340            // Unknown ZED variable - use default if available
341            if !default.is_empty() {
342                // Strip the colon and return the default value
343                return Ok(Some(default[1..].to_owned()));
344            } else {
345                bail!("Unknown variable name: {variable_name}");
346            }
347        }
348        // This is an unknown variable.
349        // 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.
350        // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
351        if !default.is_empty() {
352            return Ok(Some(format!("${{{var}}}")));
353        }
354        // Else we can just return None and that variable will be left as is.
355        Ok(None)
356    })
357    .ok()?;
358    Some(substituted_string.into_owned())
359}
360
361fn substitute_all_template_variables_in_vec(
362    template_strs: &[String],
363    task_variables: &HashMap<String, &str>,
364    variable_names: &HashMap<String, VariableName>,
365    substituted_variables: &mut HashSet<VariableName>,
366) -> Option<Vec<String>> {
367    let mut expanded = Vec::with_capacity(template_strs.len());
368    for variable in template_strs {
369        let new_value = substitute_all_template_variables_in_str(
370            variable,
371            task_variables,
372            variable_names,
373            substituted_variables,
374        )?;
375        expanded.push(new_value);
376    }
377    Some(expanded)
378}
379
380pub fn substitute_variables_in_map(
381    keys_and_values: &HashMap<String, String>,
382    context: &TaskContext,
383) -> Option<HashMap<String, String>> {
384    let mut variable_names = HashMap::default();
385    let mut substituted_variables = HashSet::default();
386    let task_variables = context
387        .task_variables
388        .0
389        .iter()
390        .map(|(key, value)| {
391            let key_string = key.to_string();
392            if !variable_names.contains_key(&key_string) {
393                variable_names.insert(key_string.clone(), key.clone());
394            }
395            (key_string, value.as_str())
396        })
397        .collect::<HashMap<_, _>>();
398    substitute_all_template_variables_in_map(
399        keys_and_values,
400        &task_variables,
401        &variable_names,
402        &mut substituted_variables,
403    )
404}
405fn substitute_all_template_variables_in_map(
406    keys_and_values: &HashMap<String, String>,
407    task_variables: &HashMap<String, &str>,
408    variable_names: &HashMap<String, VariableName>,
409    substituted_variables: &mut HashSet<VariableName>,
410) -> Option<HashMap<String, String>> {
411    let mut new_map: HashMap<String, String> = Default::default();
412    for (key, value) in keys_and_values {
413        let new_value = substitute_all_template_variables_in_str(
414            value,
415            task_variables,
416            variable_names,
417            substituted_variables,
418        )?;
419        let new_key = substitute_all_template_variables_in_str(
420            key,
421            task_variables,
422            variable_names,
423            substituted_variables,
424        )?;
425        new_map.insert(new_key, new_value);
426    }
427    Some(new_map)
428}
429
430#[cfg(test)]
431mod tests {
432    use std::{borrow::Cow, path::Path};
433
434    use crate::{TaskVariables, VariableName};
435
436    use super::*;
437
438    const TEST_ID_BASE: &str = "test_base";
439
440    #[test]
441    fn test_resolving_templates_with_blank_command_and_label() {
442        let task_with_all_properties = TaskTemplate {
443            label: "test_label".to_string(),
444            command: "test_command".to_string(),
445            args: vec!["test_arg".to_string()],
446            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
447            ..TaskTemplate::default()
448        };
449
450        for task_with_blank_property in &[
451            TaskTemplate {
452                label: "".to_string(),
453                ..task_with_all_properties.clone()
454            },
455            TaskTemplate {
456                command: "".to_string(),
457                ..task_with_all_properties.clone()
458            },
459            TaskTemplate {
460                label: "".to_string(),
461                command: "".to_string(),
462                ..task_with_all_properties
463            },
464        ] {
465            assert_eq!(
466                task_with_blank_property.resolve_task(TEST_ID_BASE, &TaskContext::default()),
467                None,
468                "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
469            );
470        }
471    }
472
473    #[test]
474    fn test_template_cwd_resolution() {
475        let task_without_cwd = TaskTemplate {
476            cwd: None,
477            label: "test task".to_string(),
478            command: "echo 4".to_string(),
479            ..TaskTemplate::default()
480        };
481
482        let resolved_task = |task_template: &TaskTemplate, task_cx| {
483            let resolved_task = task_template
484                .resolve_task(TEST_ID_BASE, task_cx)
485                .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
486            assert_substituted_variables(&resolved_task, Vec::new());
487            resolved_task.resolved
488        };
489
490        let cx = TaskContext {
491            cwd: None,
492            task_variables: TaskVariables::default(),
493            project_env: HashMap::default(),
494        };
495        assert_eq!(
496            resolved_task(&task_without_cwd, &cx).cwd,
497            None,
498            "When neither task nor task context have cwd, it should be None"
499        );
500
501        let context_cwd = Path::new("a").join("b").join("c");
502        let cx = TaskContext {
503            cwd: Some(context_cwd.clone()),
504            task_variables: TaskVariables::default(),
505            project_env: HashMap::default(),
506        };
507        assert_eq!(
508            resolved_task(&task_without_cwd, &cx).cwd,
509            Some(context_cwd.clone()),
510            "TaskContext's cwd should be taken on resolve if task's cwd is None"
511        );
512
513        let task_cwd = Path::new("d").join("e").join("f");
514        let mut task_with_cwd = task_without_cwd.clone();
515        task_with_cwd.cwd = Some(task_cwd.display().to_string());
516        let task_with_cwd = task_with_cwd;
517
518        let cx = TaskContext {
519            cwd: None,
520            task_variables: TaskVariables::default(),
521            project_env: HashMap::default(),
522        };
523        assert_eq!(
524            resolved_task(&task_with_cwd, &cx).cwd,
525            Some(task_cwd.clone()),
526            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
527        );
528
529        let cx = TaskContext {
530            cwd: Some(context_cwd),
531            task_variables: TaskVariables::default(),
532            project_env: HashMap::default(),
533        };
534        assert_eq!(
535            resolved_task(&task_with_cwd, &cx).cwd,
536            Some(task_cwd),
537            "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
538        );
539    }
540
541    #[test]
542    fn test_template_variables_resolution() {
543        let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
544        let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
545        let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
546        let all_variables = [
547            (VariableName::Row, "1234".to_string()),
548            (VariableName::Column, "5678".to_string()),
549            (VariableName::File, "test_file".to_string()),
550            (VariableName::SelectedText, "test_selected_text".to_string()),
551            (VariableName::Symbol, long_value.clone()),
552            (VariableName::WorktreeRoot, "/test_root/".to_string()),
553            (
554                custom_variable_1.clone(),
555                "test_custom_variable_1".to_string(),
556            ),
557            (
558                custom_variable_2.clone(),
559                "test_custom_variable_2".to_string(),
560            ),
561        ];
562
563        let task_with_all_variables = TaskTemplate {
564            label: format!(
565                "test label for {} and {}",
566                VariableName::Row.template_value(),
567                VariableName::Symbol.template_value(),
568            ),
569            command: format!(
570                "echo {} {}",
571                VariableName::File.template_value(),
572                VariableName::Symbol.template_value(),
573            ),
574            args: vec![
575                format!("arg1 {}", VariableName::SelectedText.template_value()),
576                format!("arg2 {}", VariableName::Column.template_value()),
577                format!("arg3 {}", VariableName::Symbol.template_value()),
578            ],
579            env: HashMap::from_iter([
580                ("test_env_key".to_string(), "test_env_var".to_string()),
581                (
582                    "env_key_1".to_string(),
583                    VariableName::WorktreeRoot.template_value(),
584                ),
585                (
586                    "env_key_2".to_string(),
587                    format!(
588                        "env_var_2 {} {}",
589                        custom_variable_1.template_value(),
590                        custom_variable_2.template_value()
591                    ),
592                ),
593                (
594                    "env_key_3".to_string(),
595                    format!("env_var_3 {}", VariableName::Symbol.template_value()),
596                ),
597            ]),
598            ..TaskTemplate::default()
599        };
600
601        let mut first_resolved_id = None;
602        for i in 0..15 {
603            let resolved_task = task_with_all_variables.resolve_task(
604                TEST_ID_BASE,
605                &TaskContext {
606                    cwd: None,
607                    task_variables: TaskVariables::from_iter(all_variables.clone()),
608                    project_env: HashMap::default(),
609                },
610            ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
611
612            match &first_resolved_id {
613                None => first_resolved_id = Some(resolved_task.id.clone()),
614                Some(first_id) => assert_eq!(
615                    &resolved_task.id, first_id,
616                    "Step {i}, for the same task template and context, there should be the same resolved task id"
617                ),
618            }
619
620            assert_eq!(
621                resolved_task.original_task, task_with_all_variables,
622                "Resolved task should store its template without changes"
623            );
624            assert_eq!(
625                resolved_task.resolved_label,
626                format!("test label for 1234 and {long_value}"),
627                "Resolved task label should be substituted with variables and those should not be shortened"
628            );
629            assert_substituted_variables(
630                &resolved_task,
631                all_variables.iter().map(|(name, _)| name.clone()).collect(),
632            );
633
634            let spawn_in_terminal = &resolved_task.resolved;
635            assert_eq!(
636                spawn_in_terminal.label,
637                format!(
638                    "test label for 1234 and …{}",
639                    &long_value[long_value.len() - MAX_DISPLAY_VARIABLE_LENGTH..]
640                ),
641                "Human-readable label should have long substitutions trimmed"
642            );
643            assert_eq!(
644                spawn_in_terminal.command.clone().unwrap(),
645                format!("echo test_file {long_value}"),
646                "Command should be substituted with variables and those should not be shortened"
647            );
648            assert_eq!(
649                spawn_in_terminal.args,
650                &[
651                    "arg1 test_selected_text",
652                    "arg2 5678",
653                    "arg3 010101010101010101010101010101010101010101010101010101010101",
654                ],
655                "Args should be substituted with variables"
656            );
657            assert_eq!(
658                spawn_in_terminal.command_label,
659                format!(
660                    "{} arg1 test_selected_text arg2 5678 arg3 {long_value}",
661                    spawn_in_terminal.command.clone().unwrap()
662                ),
663                "Command label args should be substituted with variables and those should not be shortened"
664            );
665
666            assert_eq!(
667                spawn_in_terminal
668                    .env
669                    .get("test_env_key")
670                    .map(|s| s.as_str()),
671                Some("test_env_var")
672            );
673            assert_eq!(
674                spawn_in_terminal.env.get("env_key_1").map(|s| s.as_str()),
675                Some("/test_root/")
676            );
677            assert_eq!(
678                spawn_in_terminal.env.get("env_key_2").map(|s| s.as_str()),
679                Some("env_var_2 test_custom_variable_1 test_custom_variable_2")
680            );
681            assert_eq!(
682                spawn_in_terminal.env.get("env_key_3"),
683                Some(&format!("env_var_3 {long_value}")),
684                "Env vars should be substituted with variables and those should not be shortened"
685            );
686        }
687
688        for i in 0..all_variables.len() {
689            let mut not_all_variables = all_variables.to_vec();
690            let removed_variable = not_all_variables.remove(i);
691            let resolved_task_attempt = task_with_all_variables.resolve_task(
692                TEST_ID_BASE,
693                &TaskContext {
694                    cwd: None,
695                    task_variables: TaskVariables::from_iter(not_all_variables),
696                    project_env: HashMap::default(),
697                },
698            );
699            assert_eq!(
700                resolved_task_attempt, None,
701                "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})"
702            );
703        }
704    }
705
706    #[test]
707    fn test_can_resolve_free_variables() {
708        let task = TaskTemplate {
709            label: "My task".into(),
710            command: "echo".into(),
711            args: vec!["$PATH".into()],
712            ..TaskTemplate::default()
713        };
714        let resolved_task = task
715            .resolve_task(TEST_ID_BASE, &TaskContext::default())
716            .unwrap();
717        assert_substituted_variables(&resolved_task, Vec::new());
718        let resolved = resolved_task.resolved;
719        assert_eq!(resolved.label, task.label);
720        assert_eq!(resolved.command, Some(task.command));
721        assert_eq!(resolved.args, task.args);
722    }
723
724    #[test]
725    fn test_errors_on_missing_zed_variable() {
726        let task = TaskTemplate {
727            label: "My task".into(),
728            command: "echo".into(),
729            args: vec!["$ZED_VARIABLE".into()],
730            ..TaskTemplate::default()
731        };
732        assert!(
733            task.resolve_task(TEST_ID_BASE, &TaskContext::default())
734                .is_none()
735        );
736    }
737
738    #[test]
739    fn test_symbol_dependent_tasks() {
740        let task_with_all_properties = TaskTemplate {
741            label: "test_label".to_string(),
742            command: "test_command".to_string(),
743            args: vec!["test_arg".to_string()],
744            env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
745            ..TaskTemplate::default()
746        };
747        let cx = TaskContext {
748            cwd: None,
749            task_variables: TaskVariables::from_iter(Some((
750                VariableName::Symbol,
751                "test_symbol".to_string(),
752            ))),
753            project_env: HashMap::default(),
754        };
755
756        for (i, symbol_dependent_task) in [
757            TaskTemplate {
758                label: format!("test_label_{}", VariableName::Symbol.template_value()),
759                ..task_with_all_properties.clone()
760            },
761            TaskTemplate {
762                command: format!("test_command_{}", VariableName::Symbol.template_value()),
763                ..task_with_all_properties.clone()
764            },
765            TaskTemplate {
766                args: vec![format!(
767                    "test_arg_{}",
768                    VariableName::Symbol.template_value()
769                )],
770                ..task_with_all_properties.clone()
771            },
772            TaskTemplate {
773                env: HashMap::from_iter([(
774                    "test_env_key".to_string(),
775                    format!("test_env_var_{}", VariableName::Symbol.template_value()),
776                )]),
777                ..task_with_all_properties
778            },
779        ]
780        .into_iter()
781        .enumerate()
782        {
783            let resolved = symbol_dependent_task
784                .resolve_task(TEST_ID_BASE, &cx)
785                .unwrap_or_else(|| panic!("Failed to resolve task {symbol_dependent_task:?}"));
786            assert_eq!(
787                resolved.substituted_variables,
788                HashSet::from_iter(Some(VariableName::Symbol)),
789                "(index {i}) Expected the task to depend on symbol task variable: {resolved:?}"
790            )
791        }
792    }
793
794    #[track_caller]
795    fn assert_substituted_variables(resolved_task: &ResolvedTask, mut expected: Vec<VariableName>) {
796        let mut resolved_variables = resolved_task
797            .substituted_variables
798            .iter()
799            .cloned()
800            .collect::<Vec<_>>();
801        resolved_variables.sort_by_key(|var| var.to_string());
802        expected.sort_by_key(|var| var.to_string());
803        assert_eq!(resolved_variables, expected)
804    }
805
806    #[test]
807    fn substitute_funky_labels() {
808        let faulty_go_test = TaskTemplate {
809            label: format!(
810                "go test {}/{}",
811                VariableName::Symbol.template_value(),
812                VariableName::Symbol.template_value(),
813            ),
814            command: "go".into(),
815            args: vec![format!(
816                "^{}$/^{}$",
817                VariableName::Symbol.template_value(),
818                VariableName::Symbol.template_value()
819            )],
820            ..TaskTemplate::default()
821        };
822        let mut context = TaskContext::default();
823        context
824            .task_variables
825            .insert(VariableName::Symbol, "my-symbol".to_string());
826        assert!(faulty_go_test.resolve_task("base", &context).is_some());
827    }
828
829    #[test]
830    fn test_project_env() {
831        let all_variables = [
832            (VariableName::Row, "1234".to_string()),
833            (VariableName::Column, "5678".to_string()),
834            (VariableName::File, "test_file".to_string()),
835            (VariableName::Symbol, "my symbol".to_string()),
836        ];
837
838        let template = TaskTemplate {
839            label: "my task".to_string(),
840            command: format!(
841                "echo {} {}",
842                VariableName::File.template_value(),
843                VariableName::Symbol.template_value(),
844            ),
845            args: vec![],
846            env: HashMap::from_iter([
847                (
848                    "TASK_ENV_VAR1".to_string(),
849                    "TASK_ENV_VAR1_VALUE".to_string(),
850                ),
851                (
852                    "TASK_ENV_VAR2".to_string(),
853                    format!(
854                        "env_var_2 {} {}",
855                        VariableName::Row.template_value(),
856                        VariableName::Column.template_value()
857                    ),
858                ),
859                (
860                    "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
861                    "overwritten".to_string(),
862                ),
863            ]),
864            ..TaskTemplate::default()
865        };
866
867        let project_env = HashMap::from_iter([
868            (
869                "PROJECT_ENV_VAR1".to_string(),
870                "PROJECT_ENV_VAR1_VALUE".to_string(),
871            ),
872            (
873                "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
874                "PROJECT_ENV_WILL_BE_OVERWRITTEN_VALUE".to_string(),
875            ),
876        ]);
877
878        let context = TaskContext {
879            cwd: None,
880            task_variables: TaskVariables::from_iter(all_variables),
881            project_env,
882        };
883
884        let resolved = template
885            .resolve_task(TEST_ID_BASE, &context)
886            .unwrap()
887            .resolved;
888
889        assert_eq!(resolved.env["TASK_ENV_VAR1"], "TASK_ENV_VAR1_VALUE");
890        assert_eq!(resolved.env["TASK_ENV_VAR2"], "env_var_2 1234 5678");
891        assert_eq!(resolved.env["PROJECT_ENV_VAR1"], "PROJECT_ENV_VAR1_VALUE");
892        assert_eq!(
893            resolved.env["PROJECT_ENV_WILL_BE_OVERWRITTEN"],
894            "overwritten"
895        );
896    }
897
898    #[test]
899    fn test_variable_default_values() {
900        let task_with_defaults = TaskTemplate {
901            label: "test with defaults".to_string(),
902            command: format!(
903                "echo ${{{}}}",
904                VariableName::File.to_string() + ":fallback.txt"
905            ),
906            args: vec![
907                "${ZED_MISSING_VAR:default_value}".to_string(),
908                format!("${{{}}}", VariableName::Row.to_string() + ":42"),
909            ],
910            ..TaskTemplate::default()
911        };
912
913        // Test 1: When ZED_FILE exists, should use actual value and ignore default
914        let context_with_file = TaskContext {
915            cwd: None,
916            task_variables: TaskVariables::from_iter(vec![
917                (VariableName::File, "actual_file.rs".to_string()),
918                (VariableName::Row, "123".to_string()),
919            ]),
920            project_env: HashMap::default(),
921        };
922
923        let resolved = task_with_defaults
924            .resolve_task(TEST_ID_BASE, &context_with_file)
925            .expect("Should resolve task with existing variables");
926
927        assert_eq!(
928            resolved.resolved.command.unwrap(),
929            "echo actual_file.rs",
930            "Should use actual ZED_FILE value, not default"
931        );
932        assert_eq!(
933            resolved.resolved.args,
934            vec!["default_value", "123"],
935            "Should use default for missing var, actual value for existing var"
936        );
937
938        // Test 2: When ZED_FILE doesn't exist, should use default value
939        let context_without_file = TaskContext {
940            cwd: None,
941            task_variables: TaskVariables::from_iter(vec![(VariableName::Row, "456".to_string())]),
942            project_env: HashMap::default(),
943        };
944
945        let resolved = task_with_defaults
946            .resolve_task(TEST_ID_BASE, &context_without_file)
947            .expect("Should resolve task using default values");
948
949        assert_eq!(
950            resolved.resolved.command.unwrap(),
951            "echo fallback.txt",
952            "Should use default value when ZED_FILE is missing"
953        );
954        assert_eq!(
955            resolved.resolved.args,
956            vec!["default_value", "456"],
957            "Should use defaults for missing vars"
958        );
959
960        // Test 3: Missing ZED variable without default should fail
961        let task_no_default = TaskTemplate {
962            label: "test no default".to_string(),
963            command: "${ZED_MISSING_NO_DEFAULT}".to_string(),
964            ..TaskTemplate::default()
965        };
966
967        assert!(
968            task_no_default
969                .resolve_task(TEST_ID_BASE, &TaskContext::default())
970                .is_none(),
971            "Should fail when ZED variable has no default and doesn't exist"
972        );
973    }
974}