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