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::DefaultDenyUnknownFields;
8use util::serde::default_true;
9use util::{ResultExt, truncate_and_remove_front};
10
11use crate::{
12 AttachRequest, ResolvedTask, RevealTarget, Shell, SpawnInTerminal, TaskContext, TaskId,
13 VariableName, ZED_VARIABLE_NAME_PREFIX, serde_helpers::non_empty_string_vec,
14};
15
16/// A template definition of a Zed task to run.
17/// May use the [`VariableName`] to get the corresponding substitutions into its fields.
18///
19/// Template itself is not ready to spawn a task, it needs to be resolved with a [`TaskContext`] first, that
20/// contains all relevant Zed state in task variables.
21/// A single template may produce different tasks (or none) for different contexts.
22#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
23#[serde(rename_all = "snake_case")]
24pub struct TaskTemplate {
25 /// Human readable name of the task to display in the UI.
26 pub label: String,
27 /// Executable command to spawn.
28 pub command: String,
29 /// Arguments to the command.
30 #[serde(default)]
31 pub args: Vec<String>,
32 /// Env overrides for the command, will be appended to the terminal's environment from the settings.
33 #[serde(default)]
34 pub env: HashMap<String, String>,
35 /// Current working directory to spawn the command into, defaults to current project root.
36 #[serde(default)]
37 pub cwd: Option<String>,
38 /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
39 #[serde(default)]
40 pub use_new_terminal: bool,
41 /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
42 #[serde(default)]
43 pub allow_concurrent_runs: bool,
44 /// What to do with the terminal pane and tab, after the command was started:
45 /// * `always` — always show the task's pane, and focus the corresponding tab in it (default)
46 // * `no_focus` — always show the task's pane, add the task's tab in it, but don't focus it
47 // * `never` — do not alter focus, but still add/reuse the task's tab in its pane
48 #[serde(default)]
49 pub reveal: RevealStrategy,
50 /// Where to place the task's terminal item after starting the task.
51 /// * `dock` — in the terminal dock, "regular" terminal items' place (default).
52 /// * `center` — in the central pane group, "main" editor area.
53 #[serde(default)]
54 pub reveal_target: RevealTarget,
55 /// What to do with the terminal pane and tab, after the command had finished:
56 /// * `never` — do nothing when the command finishes (default)
57 /// * `always` — always hide the terminal tab, hide the pane also if it was the last tab in it
58 /// * `on_success` — hide the terminal tab on task success only, otherwise behaves similar to `always`.
59 #[serde(default)]
60 pub hide: HideStrategy,
61 /// Represents the tags which this template attaches to.
62 /// Adding this removes this task from other UI and gives you ability to run it by tag.
63 #[serde(default, deserialize_with = "non_empty_string_vec")]
64 #[schemars(length(min = 1))]
65 pub tags: Vec<String>,
66 /// Which shell to use when spawning the task.
67 #[serde(default)]
68 pub shell: Shell,
69 /// Whether to show the task line in the task output.
70 #[serde(default = "default_true")]
71 pub show_summary: bool,
72 /// Whether to show the command line in the task output.
73 #[serde(default = "default_true")]
74 pub show_command: bool,
75}
76
77#[derive(Deserialize, Eq, PartialEq, Clone, Debug)]
78/// Use to represent debug request type
79pub enum DebugArgsRequest {
80 /// launch (program, cwd) are stored in TaskTemplate as (command, cwd)
81 Launch,
82 /// Attach
83 Attach(AttachRequest),
84}
85
86/// What to do with the terminal pane and tab, after the command was started.
87#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
88#[serde(rename_all = "snake_case")]
89pub enum RevealStrategy {
90 /// Always show the task's pane, and focus the corresponding tab in it.
91 #[default]
92 Always,
93 /// Always show the task's pane, add the task's tab in it, but don't focus it.
94 NoFocus,
95 /// Do not alter focus, but still add/reuse the task's tab in its pane.
96 Never,
97}
98
99/// What to do with the terminal pane and tab, after the command has finished.
100#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
101#[serde(rename_all = "snake_case")]
102pub enum HideStrategy {
103 /// Do nothing when the command finishes.
104 #[default]
105 Never,
106 /// Always hide the terminal tab, hide the pane also if it was the last tab in it.
107 Always,
108 /// Hide the terminal tab on task success only, otherwise behaves similar to `Always`.
109 OnSuccess,
110}
111
112/// A group of Tasks defined in a JSON file.
113#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
114pub struct TaskTemplates(pub Vec<TaskTemplate>);
115
116impl TaskTemplates {
117 /// Generates JSON schema of Tasks JSON template format.
118 pub fn generate_json_schema() -> serde_json_lenient::Value {
119 let schema = schemars::generate::SchemaSettings::draft2019_09()
120 .with_transform(DefaultDenyUnknownFields)
121 .into_generator()
122 .root_schema_for::<Self>();
123
124 serde_json_lenient::to_value(schema).unwrap()
125 }
126}
127
128impl TaskTemplate {
129 /// Replaces all `VariableName` task variables in the task template string fields.
130 /// If any replacement fails or the new string substitutions still have [`ZED_VARIABLE_NAME_PREFIX`],
131 /// `None` is returned.
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
279const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
280
281fn truncate_variables(task_variables: &HashMap<String, &str>) -> HashMap<String, String> {
282 task_variables
283 .iter()
284 .map(|(key, value)| {
285 (
286 key.clone(),
287 truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
288 )
289 })
290 .collect()
291}
292
293fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
294 let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
295 let mut hasher = Sha256::new();
296 hasher.update(json.as_bytes());
297 Ok(hex::encode(hasher.finalize()))
298}
299
300pub fn substitute_variables_in_str(template_str: &str, context: &TaskContext) -> Option<String> {
301 let mut variable_names = HashMap::default();
302 let mut substituted_variables = HashSet::default();
303 let task_variables = context
304 .task_variables
305 .0
306 .iter()
307 .map(|(key, value)| {
308 let key_string = key.to_string();
309 if !variable_names.contains_key(&key_string) {
310 variable_names.insert(key_string.clone(), key.clone());
311 }
312 (key_string, value.as_str())
313 })
314 .collect::<HashMap<_, _>>();
315 substitute_all_template_variables_in_str(
316 template_str,
317 &task_variables,
318 &variable_names,
319 &mut substituted_variables,
320 )
321}
322fn substitute_all_template_variables_in_str<A: AsRef<str>>(
323 template_str: &str,
324 task_variables: &HashMap<String, A>,
325 variable_names: &HashMap<String, VariableName>,
326 substituted_variables: &mut HashSet<VariableName>,
327) -> Option<String> {
328 let substituted_string = shellexpand::env_with_context(template_str, |var| {
329 // 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.
330 let colon_position = var.find(':').unwrap_or(var.len());
331 let (variable_name, default) = var.split_at(colon_position);
332 if let Some(name) = task_variables.get(variable_name) {
333 if let Some(substituted_variable) = variable_names.get(variable_name) {
334 substituted_variables.insert(substituted_variable.clone());
335 }
336
337 let mut name = name.as_ref().to_owned();
338 // Got a task variable hit
339 if !default.is_empty() {
340 name.push_str(default);
341 }
342 return Ok(Some(name));
343 } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
344 bail!("Unknown variable name: {variable_name}");
345 }
346 // This is an unknown variable.
347 // 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.
348 // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
349 if !default.is_empty() {
350 return Ok(Some(format!("${{{var}}}")));
351 }
352 // Else we can just return None and that variable will be left as is.
353 Ok(None)
354 })
355 .ok()?;
356 Some(substituted_string.into_owned())
357}
358
359fn substitute_all_template_variables_in_vec(
360 template_strs: &[String],
361 task_variables: &HashMap<String, &str>,
362 variable_names: &HashMap<String, VariableName>,
363 substituted_variables: &mut HashSet<VariableName>,
364) -> Option<Vec<String>> {
365 let mut expanded = Vec::with_capacity(template_strs.len());
366 for variable in template_strs {
367 let new_value = substitute_all_template_variables_in_str(
368 variable,
369 task_variables,
370 variable_names,
371 substituted_variables,
372 )?;
373 expanded.push(new_value);
374 }
375 Some(expanded)
376}
377
378pub fn substitute_variables_in_map(
379 keys_and_values: &HashMap<String, String>,
380 context: &TaskContext,
381) -> Option<HashMap<String, String>> {
382 let mut variable_names = HashMap::default();
383 let mut substituted_variables = HashSet::default();
384 let task_variables = context
385 .task_variables
386 .0
387 .iter()
388 .map(|(key, value)| {
389 let key_string = key.to_string();
390 if !variable_names.contains_key(&key_string) {
391 variable_names.insert(key_string.clone(), key.clone());
392 }
393 (key_string, value.as_str())
394 })
395 .collect::<HashMap<_, _>>();
396 substitute_all_template_variables_in_map(
397 keys_and_values,
398 &task_variables,
399 &variable_names,
400 &mut substituted_variables,
401 )
402}
403fn substitute_all_template_variables_in_map(
404 keys_and_values: &HashMap<String, String>,
405 task_variables: &HashMap<String, &str>,
406 variable_names: &HashMap<String, VariableName>,
407 substituted_variables: &mut HashSet<VariableName>,
408) -> Option<HashMap<String, String>> {
409 let mut new_map: HashMap<String, String> = Default::default();
410 for (key, value) in keys_and_values {
411 let new_value = substitute_all_template_variables_in_str(
412 value,
413 task_variables,
414 variable_names,
415 substituted_variables,
416 )?;
417 let new_key = substitute_all_template_variables_in_str(
418 key,
419 task_variables,
420 variable_names,
421 substituted_variables,
422 )?;
423 new_map.insert(new_key, new_value);
424 }
425 Some(new_map)
426}
427
428#[cfg(test)]
429mod tests {
430 use std::{borrow::Cow, path::Path};
431
432 use crate::{TaskVariables, VariableName};
433
434 use super::*;
435
436 const TEST_ID_BASE: &str = "test_base";
437
438 #[test]
439 fn test_resolving_templates_with_blank_command_and_label() {
440 let task_with_all_properties = TaskTemplate {
441 label: "test_label".to_string(),
442 command: "test_command".to_string(),
443 args: vec!["test_arg".to_string()],
444 env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
445 ..TaskTemplate::default()
446 };
447
448 for task_with_blank_property in &[
449 TaskTemplate {
450 label: "".to_string(),
451 ..task_with_all_properties.clone()
452 },
453 TaskTemplate {
454 command: "".to_string(),
455 ..task_with_all_properties.clone()
456 },
457 TaskTemplate {
458 label: "".to_string(),
459 command: "".to_string(),
460 ..task_with_all_properties
461 },
462 ] {
463 assert_eq!(
464 task_with_blank_property.resolve_task(TEST_ID_BASE, &TaskContext::default()),
465 None,
466 "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
467 );
468 }
469 }
470
471 #[test]
472 fn test_template_cwd_resolution() {
473 let task_without_cwd = TaskTemplate {
474 cwd: None,
475 label: "test task".to_string(),
476 command: "echo 4".to_string(),
477 ..TaskTemplate::default()
478 };
479
480 let resolved_task = |task_template: &TaskTemplate, task_cx| {
481 let resolved_task = task_template
482 .resolve_task(TEST_ID_BASE, task_cx)
483 .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
484 assert_substituted_variables(&resolved_task, Vec::new());
485 resolved_task.resolved
486 };
487
488 let cx = TaskContext {
489 cwd: None,
490 task_variables: TaskVariables::default(),
491 project_env: HashMap::default(),
492 };
493 assert_eq!(
494 resolved_task(&task_without_cwd, &cx).cwd,
495 None,
496 "When neither task nor task context have cwd, it should be None"
497 );
498
499 let context_cwd = Path::new("a").join("b").join("c");
500 let cx = TaskContext {
501 cwd: Some(context_cwd.clone()),
502 task_variables: TaskVariables::default(),
503 project_env: HashMap::default(),
504 };
505 assert_eq!(
506 resolved_task(&task_without_cwd, &cx).cwd,
507 Some(context_cwd.clone()),
508 "TaskContext's cwd should be taken on resolve if task's cwd is None"
509 );
510
511 let task_cwd = Path::new("d").join("e").join("f");
512 let mut task_with_cwd = task_without_cwd.clone();
513 task_with_cwd.cwd = Some(task_cwd.display().to_string());
514 let task_with_cwd = task_with_cwd;
515
516 let cx = TaskContext {
517 cwd: None,
518 task_variables: TaskVariables::default(),
519 project_env: HashMap::default(),
520 };
521 assert_eq!(
522 resolved_task(&task_with_cwd, &cx).cwd,
523 Some(task_cwd.clone()),
524 "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
525 );
526
527 let cx = TaskContext {
528 cwd: Some(context_cwd),
529 task_variables: TaskVariables::default(),
530 project_env: HashMap::default(),
531 };
532 assert_eq!(
533 resolved_task(&task_with_cwd, &cx).cwd,
534 Some(task_cwd),
535 "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
536 );
537 }
538
539 #[test]
540 fn test_template_variables_resolution() {
541 let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
542 let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
543 let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
544 let all_variables = [
545 (VariableName::Row, "1234".to_string()),
546 (VariableName::Column, "5678".to_string()),
547 (VariableName::File, "test_file".to_string()),
548 (VariableName::SelectedText, "test_selected_text".to_string()),
549 (VariableName::Symbol, long_value.clone()),
550 (VariableName::WorktreeRoot, "/test_root/".to_string()),
551 (
552 custom_variable_1.clone(),
553 "test_custom_variable_1".to_string(),
554 ),
555 (
556 custom_variable_2.clone(),
557 "test_custom_variable_2".to_string(),
558 ),
559 ];
560
561 let task_with_all_variables = TaskTemplate {
562 label: format!(
563 "test label for {} and {}",
564 VariableName::Row.template_value(),
565 VariableName::Symbol.template_value(),
566 ),
567 command: format!(
568 "echo {} {}",
569 VariableName::File.template_value(),
570 VariableName::Symbol.template_value(),
571 ),
572 args: vec![
573 format!("arg1 {}", VariableName::SelectedText.template_value()),
574 format!("arg2 {}", VariableName::Column.template_value()),
575 format!("arg3 {}", VariableName::Symbol.template_value()),
576 ],
577 env: HashMap::from_iter([
578 ("test_env_key".to_string(), "test_env_var".to_string()),
579 (
580 "env_key_1".to_string(),
581 VariableName::WorktreeRoot.template_value(),
582 ),
583 (
584 "env_key_2".to_string(),
585 format!(
586 "env_var_2 {} {}",
587 custom_variable_1.template_value(),
588 custom_variable_2.template_value()
589 ),
590 ),
591 (
592 "env_key_3".to_string(),
593 format!("env_var_3 {}", VariableName::Symbol.template_value()),
594 ),
595 ]),
596 ..TaskTemplate::default()
597 };
598
599 let mut first_resolved_id = None;
600 for i in 0..15 {
601 let resolved_task = task_with_all_variables.resolve_task(
602 TEST_ID_BASE,
603 &TaskContext {
604 cwd: None,
605 task_variables: TaskVariables::from_iter(all_variables.clone()),
606 project_env: HashMap::default(),
607 },
608 ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
609
610 match &first_resolved_id {
611 None => first_resolved_id = Some(resolved_task.id.clone()),
612 Some(first_id) => assert_eq!(
613 &resolved_task.id, first_id,
614 "Step {i}, for the same task template and context, there should be the same resolved task id"
615 ),
616 }
617
618 assert_eq!(
619 resolved_task.original_task, task_with_all_variables,
620 "Resolved task should store its template without changes"
621 );
622 assert_eq!(
623 resolved_task.resolved_label,
624 format!("test label for 1234 and {long_value}"),
625 "Resolved task label should be substituted with variables and those should not be shortened"
626 );
627 assert_substituted_variables(
628 &resolved_task,
629 all_variables.iter().map(|(name, _)| name.clone()).collect(),
630 );
631
632 let spawn_in_terminal = &resolved_task.resolved;
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.clone().unwrap(),
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 test_selected_text",
650 "arg2 5678",
651 "arg3 010101010101010101010101010101010101010101010101010101010101",
652 ],
653 "Args should 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.clone().unwrap()
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;
717 assert_eq!(resolved.label, task.label);
718 assert_eq!(resolved.command, Some(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
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),
879 project_env,
880 };
881
882 let resolved = template
883 .resolve_task(TEST_ID_BASE, &context)
884 .unwrap()
885 .resolved;
886
887 assert_eq!(resolved.env["TASK_ENV_VAR1"], "TASK_ENV_VAR1_VALUE");
888 assert_eq!(resolved.env["TASK_ENV_VAR2"], "env_var_2 1234 5678");
889 assert_eq!(resolved.env["PROJECT_ENV_VAR1"], "PROJECT_ENV_VAR1_VALUE");
890 assert_eq!(
891 resolved.env["PROJECT_ENV_WILL_BE_OVERWRITTEN"],
892 "overwritten"
893 );
894 }
895}