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