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