1use anyhow::{Context as _, 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::{
11 AttachRequest, ResolvedTask, RevealTarget, Shell, SpawnInTerminal, TaskContext, TaskId,
12 VariableName, ZED_VARIABLE_NAME_PREFIX,
13 serde_helpers::{non_empty_string_vec, non_empty_string_vec_json_schema},
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(schema_with = "non_empty_string_vec_json_schema")]
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 = SchemaSettings::draft07()
120 .with(|settings| settings.option_add_null_type = false)
121 .into_generator()
122 .into_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 full_label.clone()
187 }
188 .lines()
189 .fold(String::new(), |mut string, line| {
190 if string.is_empty() {
191 string.push_str(line);
192 } else {
193 string.push_str("\\n");
194 string.push_str(line);
195 }
196 string
197 });
198
199 let command = substitute_all_template_variables_in_str(
200 &self.command,
201 &task_variables,
202 &variable_names,
203 &mut substituted_variables,
204 )?;
205 let args_with_substitutions = substitute_all_template_variables_in_vec(
206 &self.args,
207 &task_variables,
208 &variable_names,
209 &mut substituted_variables,
210 )?;
211
212 let task_hash = to_hex_hash(self)
213 .context("hashing task template")
214 .log_err()?;
215 let variables_hash = to_hex_hash(&task_variables)
216 .context("hashing task variables")
217 .log_err()?;
218 let id = TaskId(format!("{id_base}_{task_hash}_{variables_hash}"));
219
220 let env = {
221 // Start with the project environment as the base.
222 let mut env = cx.project_env.clone();
223
224 // Extend that environment with what's defined in the TaskTemplate
225 env.extend(self.env.clone());
226
227 // Then we replace all task variables that could be set in environment variables
228 let mut env = substitute_all_template_variables_in_map(
229 &env,
230 &task_variables,
231 &variable_names,
232 &mut substituted_variables,
233 )?;
234
235 // Last step: set the task variables as environment variables too
236 env.extend(task_variables.into_iter().map(|(k, v)| (k, v.to_owned())));
237 env
238 };
239
240 // We filter out env variables here that aren't set so we don't have extra white space in args
241 let args = self
242 .args
243 .iter()
244 .filter(|arg| {
245 arg.starts_with('$')
246 .then(|| env.get(&arg[1..]).is_some_and(|arg| !arg.trim().is_empty()))
247 .unwrap_or(true)
248 })
249 .cloned()
250 .collect();
251
252 Some(ResolvedTask {
253 id: id.clone(),
254 substituted_variables,
255 original_task: self.clone(),
256 resolved_label: full_label.clone(),
257 resolved: SpawnInTerminal {
258 id,
259 cwd,
260 full_label,
261 label: human_readable_label,
262 command_label: args_with_substitutions.iter().fold(
263 command.clone(),
264 |mut command_label, arg| {
265 command_label.push(' ');
266 command_label.push_str(arg);
267 command_label
268 },
269 ),
270 command,
271 args,
272 env,
273 use_new_terminal: self.use_new_terminal,
274 allow_concurrent_runs: self.allow_concurrent_runs,
275 reveal: self.reveal,
276 reveal_target: self.reveal_target,
277 hide: self.hide,
278 shell: self.shell.clone(),
279 show_summary: self.show_summary,
280 show_command: self.show_command,
281 show_rerun: true,
282 },
283 })
284 }
285}
286
287const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
288
289fn truncate_variables(task_variables: &HashMap<String, &str>) -> HashMap<String, String> {
290 task_variables
291 .iter()
292 .map(|(key, value)| {
293 (
294 key.clone(),
295 truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
296 )
297 })
298 .collect()
299}
300
301fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
302 let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
303 let mut hasher = Sha256::new();
304 hasher.update(json.as_bytes());
305 Ok(hex::encode(hasher.finalize()))
306}
307
308pub fn substitute_variables_in_str(template_str: &str, context: &TaskContext) -> Option<String> {
309 let mut variable_names = HashMap::default();
310 let mut substituted_variables = HashSet::default();
311 let task_variables = context
312 .task_variables
313 .0
314 .iter()
315 .map(|(key, value)| {
316 let key_string = key.to_string();
317 if !variable_names.contains_key(&key_string) {
318 variable_names.insert(key_string.clone(), key.clone());
319 }
320 (key_string, value.as_str())
321 })
322 .collect::<HashMap<_, _>>();
323 substitute_all_template_variables_in_str(
324 template_str,
325 &task_variables,
326 &variable_names,
327 &mut substituted_variables,
328 )
329}
330fn substitute_all_template_variables_in_str<A: AsRef<str>>(
331 template_str: &str,
332 task_variables: &HashMap<String, A>,
333 variable_names: &HashMap<String, VariableName>,
334 substituted_variables: &mut HashSet<VariableName>,
335) -> Option<String> {
336 let substituted_string = shellexpand::env_with_context(template_str, |var| {
337 // 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.
338 let colon_position = var.find(':').unwrap_or(var.len());
339 let (variable_name, default) = var.split_at(colon_position);
340 if let Some(name) = task_variables.get(variable_name) {
341 if let Some(substituted_variable) = variable_names.get(variable_name) {
342 substituted_variables.insert(substituted_variable.clone());
343 }
344
345 let mut name = name.as_ref().to_owned();
346 // Got a task variable hit
347 if !default.is_empty() {
348 name.push_str(default);
349 }
350 return Ok(Some(name));
351 } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
352 bail!("Unknown variable name: {variable_name}");
353 }
354 // This is an unknown variable.
355 // 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.
356 // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
357 if !default.is_empty() {
358 return Ok(Some(format!("${{{var}}}")));
359 }
360 // Else we can just return None and that variable will be left as is.
361 Ok(None)
362 })
363 .ok()?;
364 Some(substituted_string.into_owned())
365}
366
367fn substitute_all_template_variables_in_vec(
368 template_strs: &[String],
369 task_variables: &HashMap<String, &str>,
370 variable_names: &HashMap<String, VariableName>,
371 substituted_variables: &mut HashSet<VariableName>,
372) -> Option<Vec<String>> {
373 let mut expanded = Vec::with_capacity(template_strs.len());
374 for variable in template_strs {
375 let new_value = substitute_all_template_variables_in_str(
376 variable,
377 task_variables,
378 variable_names,
379 substituted_variables,
380 )?;
381 expanded.push(new_value);
382 }
383 Some(expanded)
384}
385
386pub fn substitute_variables_in_map(
387 keys_and_values: &HashMap<String, String>,
388 context: &TaskContext,
389) -> Option<HashMap<String, String>> {
390 let mut variable_names = HashMap::default();
391 let mut substituted_variables = HashSet::default();
392 let task_variables = context
393 .task_variables
394 .0
395 .iter()
396 .map(|(key, value)| {
397 let key_string = key.to_string();
398 if !variable_names.contains_key(&key_string) {
399 variable_names.insert(key_string.clone(), key.clone());
400 }
401 (key_string, value.as_str())
402 })
403 .collect::<HashMap<_, _>>();
404 substitute_all_template_variables_in_map(
405 keys_and_values,
406 &task_variables,
407 &variable_names,
408 &mut substituted_variables,
409 )
410}
411fn substitute_all_template_variables_in_map(
412 keys_and_values: &HashMap<String, String>,
413 task_variables: &HashMap<String, &str>,
414 variable_names: &HashMap<String, VariableName>,
415 substituted_variables: &mut HashSet<VariableName>,
416) -> Option<HashMap<String, String>> {
417 let mut new_map: HashMap<String, String> = Default::default();
418 for (key, value) in keys_and_values {
419 let new_value = substitute_all_template_variables_in_str(
420 value,
421 task_variables,
422 variable_names,
423 substituted_variables,
424 )?;
425 let new_key = substitute_all_template_variables_in_str(
426 key,
427 task_variables,
428 variable_names,
429 substituted_variables,
430 )?;
431 new_map.insert(new_key, new_value);
432 }
433 Some(new_map)
434}
435
436#[cfg(test)]
437mod tests {
438 use std::{borrow::Cow, path::Path};
439
440 use crate::{TaskVariables, VariableName};
441
442 use super::*;
443
444 const TEST_ID_BASE: &str = "test_base";
445
446 #[test]
447 fn test_resolving_templates_with_blank_command_and_label() {
448 let task_with_all_properties = TaskTemplate {
449 label: "test_label".to_string(),
450 command: "test_command".to_string(),
451 args: vec!["test_arg".to_string()],
452 env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
453 ..TaskTemplate::default()
454 };
455
456 for task_with_blank_property in &[
457 TaskTemplate {
458 label: "".to_string(),
459 ..task_with_all_properties.clone()
460 },
461 TaskTemplate {
462 command: "".to_string(),
463 ..task_with_all_properties.clone()
464 },
465 TaskTemplate {
466 label: "".to_string(),
467 command: "".to_string(),
468 ..task_with_all_properties.clone()
469 },
470 ] {
471 assert_eq!(
472 task_with_blank_property.resolve_task(TEST_ID_BASE, &TaskContext::default()),
473 None,
474 "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
475 );
476 }
477 }
478
479 #[test]
480 fn test_template_cwd_resolution() {
481 let task_without_cwd = TaskTemplate {
482 cwd: None,
483 label: "test task".to_string(),
484 command: "echo 4".to_string(),
485 ..TaskTemplate::default()
486 };
487
488 let resolved_task = |task_template: &TaskTemplate, task_cx| {
489 let resolved_task = task_template
490 .resolve_task(TEST_ID_BASE, task_cx)
491 .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
492 assert_substituted_variables(&resolved_task, Vec::new());
493 resolved_task.resolved
494 };
495
496 let cx = TaskContext {
497 cwd: None,
498 task_variables: TaskVariables::default(),
499 project_env: HashMap::default(),
500 };
501 assert_eq!(
502 resolved_task(&task_without_cwd, &cx).cwd,
503 None,
504 "When neither task nor task context have cwd, it should be None"
505 );
506
507 let context_cwd = Path::new("a").join("b").join("c");
508 let cx = TaskContext {
509 cwd: Some(context_cwd.clone()),
510 task_variables: TaskVariables::default(),
511 project_env: HashMap::default(),
512 };
513 assert_eq!(
514 resolved_task(&task_without_cwd, &cx).cwd,
515 Some(context_cwd.clone()),
516 "TaskContext's cwd should be taken on resolve if task's cwd is None"
517 );
518
519 let task_cwd = Path::new("d").join("e").join("f");
520 let mut task_with_cwd = task_without_cwd.clone();
521 task_with_cwd.cwd = Some(task_cwd.display().to_string());
522 let task_with_cwd = task_with_cwd;
523
524 let cx = TaskContext {
525 cwd: None,
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.clone()),
532 "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
533 );
534
535 let cx = TaskContext {
536 cwd: Some(context_cwd.clone()),
537 task_variables: TaskVariables::default(),
538 project_env: HashMap::default(),
539 };
540 assert_eq!(
541 resolved_task(&task_with_cwd, &cx).cwd,
542 Some(task_cwd),
543 "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
544 );
545 }
546
547 #[test]
548 fn test_template_variables_resolution() {
549 let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
550 let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
551 let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
552 let all_variables = [
553 (VariableName::Row, "1234".to_string()),
554 (VariableName::Column, "5678".to_string()),
555 (VariableName::File, "test_file".to_string()),
556 (VariableName::SelectedText, "test_selected_text".to_string()),
557 (VariableName::Symbol, long_value.clone()),
558 (VariableName::WorktreeRoot, "/test_root/".to_string()),
559 (
560 custom_variable_1.clone(),
561 "test_custom_variable_1".to_string(),
562 ),
563 (
564 custom_variable_2.clone(),
565 "test_custom_variable_2".to_string(),
566 ),
567 ];
568
569 let task_with_all_variables = TaskTemplate {
570 label: format!(
571 "test label for {} and {}",
572 VariableName::Row.template_value(),
573 VariableName::Symbol.template_value(),
574 ),
575 command: format!(
576 "echo {} {}",
577 VariableName::File.template_value(),
578 VariableName::Symbol.template_value(),
579 ),
580 args: vec![
581 format!("arg1 {}", VariableName::SelectedText.template_value()),
582 format!("arg2 {}", VariableName::Column.template_value()),
583 format!("arg3 {}", VariableName::Symbol.template_value()),
584 ],
585 env: HashMap::from_iter([
586 ("test_env_key".to_string(), "test_env_var".to_string()),
587 (
588 "env_key_1".to_string(),
589 VariableName::WorktreeRoot.template_value(),
590 ),
591 (
592 "env_key_2".to_string(),
593 format!(
594 "env_var_2 {} {}",
595 custom_variable_1.template_value(),
596 custom_variable_2.template_value()
597 ),
598 ),
599 (
600 "env_key_3".to_string(),
601 format!("env_var_3 {}", VariableName::Symbol.template_value()),
602 ),
603 ]),
604 ..TaskTemplate::default()
605 };
606
607 let mut first_resolved_id = None;
608 for i in 0..15 {
609 let resolved_task = task_with_all_variables.resolve_task(
610 TEST_ID_BASE,
611 &TaskContext {
612 cwd: None,
613 task_variables: TaskVariables::from_iter(all_variables.clone()),
614 project_env: HashMap::default(),
615 },
616 ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
617
618 match &first_resolved_id {
619 None => first_resolved_id = Some(resolved_task.id.clone()),
620 Some(first_id) => assert_eq!(
621 &resolved_task.id, first_id,
622 "Step {i}, for the same task template and context, there should be the same resolved task id"
623 ),
624 }
625
626 assert_eq!(
627 resolved_task.original_task, task_with_all_variables,
628 "Resolved task should store its template without changes"
629 );
630 assert_eq!(
631 resolved_task.resolved_label,
632 format!("test label for 1234 and {long_value}"),
633 "Resolved task label should be substituted with variables and those should not be shortened"
634 );
635 assert_substituted_variables(
636 &resolved_task,
637 all_variables.iter().map(|(name, _)| name.clone()).collect(),
638 );
639
640 let spawn_in_terminal = &resolved_task.resolved;
641 assert_eq!(
642 spawn_in_terminal.label,
643 format!(
644 "test label for 1234 and …{}",
645 &long_value[long_value.len() - MAX_DISPLAY_VARIABLE_LENGTH..]
646 ),
647 "Human-readable label should have long substitutions trimmed"
648 );
649 assert_eq!(
650 spawn_in_terminal.command,
651 format!("echo test_file {long_value}"),
652 "Command should be substituted with variables and those should not be shortened"
653 );
654 assert_eq!(
655 spawn_in_terminal.args,
656 &[
657 "arg1 $ZED_SELECTED_TEXT",
658 "arg2 $ZED_COLUMN",
659 "arg3 $ZED_SYMBOL",
660 ],
661 "Args should not be substituted with variables"
662 );
663 assert_eq!(
664 spawn_in_terminal.command_label,
665 format!(
666 "{} arg1 test_selected_text arg2 5678 arg3 {long_value}",
667 spawn_in_terminal.command
668 ),
669 "Command label args should be substituted with variables and those should not be shortened"
670 );
671
672 assert_eq!(
673 spawn_in_terminal
674 .env
675 .get("test_env_key")
676 .map(|s| s.as_str()),
677 Some("test_env_var")
678 );
679 assert_eq!(
680 spawn_in_terminal.env.get("env_key_1").map(|s| s.as_str()),
681 Some("/test_root/")
682 );
683 assert_eq!(
684 spawn_in_terminal.env.get("env_key_2").map(|s| s.as_str()),
685 Some("env_var_2 test_custom_variable_1 test_custom_variable_2")
686 );
687 assert_eq!(
688 spawn_in_terminal.env.get("env_key_3"),
689 Some(&format!("env_var_3 {long_value}")),
690 "Env vars should be substituted with variables and those should not be shortened"
691 );
692 }
693
694 for i in 0..all_variables.len() {
695 let mut not_all_variables = all_variables.to_vec();
696 let removed_variable = not_all_variables.remove(i);
697 let resolved_task_attempt = task_with_all_variables.resolve_task(
698 TEST_ID_BASE,
699 &TaskContext {
700 cwd: None,
701 task_variables: TaskVariables::from_iter(not_all_variables),
702 project_env: HashMap::default(),
703 },
704 );
705 assert_eq!(
706 resolved_task_attempt, None,
707 "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})"
708 );
709 }
710 }
711
712 #[test]
713 fn test_can_resolve_free_variables() {
714 let task = TaskTemplate {
715 label: "My task".into(),
716 command: "echo".into(),
717 args: vec!["$PATH".into()],
718 env: HashMap::from_iter([("PATH".to_owned(), "non-empty".to_owned())]),
719 ..TaskTemplate::default()
720 };
721 let resolved_task = task
722 .resolve_task(TEST_ID_BASE, &TaskContext::default())
723 .unwrap();
724 assert_substituted_variables(&resolved_task, Vec::new());
725 let resolved = resolved_task.resolved;
726 assert_eq!(resolved.label, task.label);
727 assert_eq!(resolved.command, task.command);
728 assert_eq!(resolved.args, task.args);
729 }
730
731 #[test]
732 fn test_empty_env_variables_excluded_from_args() {
733 let task = TaskTemplate {
734 label: "My task".into(),
735 command: "echo".into(),
736 args: vec![
737 "$EMPTY_VAR".into(),
738 "hello".into(),
739 "$WHITESPACE_VAR".into(),
740 "$UNDEFINED_VAR".into(),
741 "$WORLD".into(),
742 ],
743 env: HashMap::from_iter([
744 ("EMPTY_VAR".to_owned(), "".to_owned()),
745 ("WHITESPACE_VAR".to_owned(), " ".to_owned()),
746 ("WORLD".to_owned(), "non-empty".to_owned()),
747 ]),
748 ..TaskTemplate::default()
749 };
750 let resolved_task = task
751 .resolve_task(TEST_ID_BASE, &TaskContext::default())
752 .unwrap();
753 let resolved = resolved_task.resolved;
754 assert_eq!(resolved.args, vec!["hello", "$WORLD"]);
755 }
756
757 #[test]
758 fn test_errors_on_missing_zed_variable() {
759 let task = TaskTemplate {
760 label: "My task".into(),
761 command: "echo".into(),
762 args: vec!["$ZED_VARIABLE".into()],
763 ..TaskTemplate::default()
764 };
765 assert!(
766 task.resolve_task(TEST_ID_BASE, &TaskContext::default())
767 .is_none()
768 );
769 }
770
771 #[test]
772 fn test_symbol_dependent_tasks() {
773 let task_with_all_properties = TaskTemplate {
774 label: "test_label".to_string(),
775 command: "test_command".to_string(),
776 args: vec!["test_arg".to_string()],
777 env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
778 ..TaskTemplate::default()
779 };
780 let cx = TaskContext {
781 cwd: None,
782 task_variables: TaskVariables::from_iter(Some((
783 VariableName::Symbol,
784 "test_symbol".to_string(),
785 ))),
786 project_env: HashMap::default(),
787 };
788
789 for (i, symbol_dependent_task) in [
790 TaskTemplate {
791 label: format!("test_label_{}", VariableName::Symbol.template_value()),
792 ..task_with_all_properties.clone()
793 },
794 TaskTemplate {
795 command: format!("test_command_{}", VariableName::Symbol.template_value()),
796 ..task_with_all_properties.clone()
797 },
798 TaskTemplate {
799 args: vec![format!(
800 "test_arg_{}",
801 VariableName::Symbol.template_value()
802 )],
803 ..task_with_all_properties.clone()
804 },
805 TaskTemplate {
806 env: HashMap::from_iter([(
807 "test_env_key".to_string(),
808 format!("test_env_var_{}", VariableName::Symbol.template_value()),
809 )]),
810 ..task_with_all_properties.clone()
811 },
812 ]
813 .into_iter()
814 .enumerate()
815 {
816 let resolved = symbol_dependent_task
817 .resolve_task(TEST_ID_BASE, &cx)
818 .unwrap_or_else(|| panic!("Failed to resolve task {symbol_dependent_task:?}"));
819 assert_eq!(
820 resolved.substituted_variables,
821 HashSet::from_iter(Some(VariableName::Symbol)),
822 "(index {i}) Expected the task to depend on symbol task variable: {resolved:?}"
823 )
824 }
825 }
826
827 #[track_caller]
828 fn assert_substituted_variables(resolved_task: &ResolvedTask, mut expected: Vec<VariableName>) {
829 let mut resolved_variables = resolved_task
830 .substituted_variables
831 .iter()
832 .cloned()
833 .collect::<Vec<_>>();
834 resolved_variables.sort_by_key(|var| var.to_string());
835 expected.sort_by_key(|var| var.to_string());
836 assert_eq!(resolved_variables, expected)
837 }
838
839 #[test]
840 fn substitute_funky_labels() {
841 let faulty_go_test = TaskTemplate {
842 label: format!(
843 "go test {}/{}",
844 VariableName::Symbol.template_value(),
845 VariableName::Symbol.template_value(),
846 ),
847 command: "go".into(),
848 args: vec![format!(
849 "^{}$/^{}$",
850 VariableName::Symbol.template_value(),
851 VariableName::Symbol.template_value()
852 )],
853 ..TaskTemplate::default()
854 };
855 let mut context = TaskContext::default();
856 context
857 .task_variables
858 .insert(VariableName::Symbol, "my-symbol".to_string());
859 assert!(faulty_go_test.resolve_task("base", &context).is_some());
860 }
861
862 #[test]
863 fn test_project_env() {
864 let all_variables = [
865 (VariableName::Row, "1234".to_string()),
866 (VariableName::Column, "5678".to_string()),
867 (VariableName::File, "test_file".to_string()),
868 (VariableName::Symbol, "my symbol".to_string()),
869 ];
870
871 let template = TaskTemplate {
872 label: "my task".to_string(),
873 command: format!(
874 "echo {} {}",
875 VariableName::File.template_value(),
876 VariableName::Symbol.template_value(),
877 ),
878 args: vec![],
879 env: HashMap::from_iter([
880 (
881 "TASK_ENV_VAR1".to_string(),
882 "TASK_ENV_VAR1_VALUE".to_string(),
883 ),
884 (
885 "TASK_ENV_VAR2".to_string(),
886 format!(
887 "env_var_2 {} {}",
888 VariableName::Row.template_value(),
889 VariableName::Column.template_value()
890 ),
891 ),
892 (
893 "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
894 "overwritten".to_string(),
895 ),
896 ]),
897 ..TaskTemplate::default()
898 };
899
900 let project_env = HashMap::from_iter([
901 (
902 "PROJECT_ENV_VAR1".to_string(),
903 "PROJECT_ENV_VAR1_VALUE".to_string(),
904 ),
905 (
906 "PROJECT_ENV_WILL_BE_OVERWRITTEN".to_string(),
907 "PROJECT_ENV_WILL_BE_OVERWRITTEN_VALUE".to_string(),
908 ),
909 ]);
910
911 let context = TaskContext {
912 cwd: None,
913 task_variables: TaskVariables::from_iter(all_variables.clone()),
914 project_env,
915 };
916
917 let resolved = template
918 .resolve_task(TEST_ID_BASE, &context)
919 .unwrap()
920 .resolved;
921
922 assert_eq!(resolved.env["TASK_ENV_VAR1"], "TASK_ENV_VAR1_VALUE");
923 assert_eq!(resolved.env["TASK_ENV_VAR2"], "env_var_2 1234 5678");
924 assert_eq!(resolved.env["PROJECT_ENV_VAR1"], "PROJECT_ENV_VAR1_VALUE");
925 assert_eq!(
926 resolved.env["PROJECT_ENV_WILL_BE_OVERWRITTEN"],
927 "overwritten"
928 );
929 }
930}