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