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