1use std::path::PathBuf;
2
3use anyhow::{bail, Context};
4use collections::{HashMap, HashSet};
5use schemars::{gen::SchemaSettings, JsonSchema};
6use serde::{Deserialize, Serialize};
7use sha2::{Digest, Sha256};
8use util::{truncate_and_remove_front, ResultExt};
9
10use crate::{
11 ResolvedTask, SpawnInTerminal, TaskContext, TaskId, TerminalWorkDir, VariableName,
12 ZED_VARIABLE_NAME_PREFIX,
13};
14
15/// A template definition of a Zed task to run.
16/// May use the [`VariableName`] to get the corresponding substitutions into its fields.
17///
18/// Template itself is not ready to spawn a task, it needs to be resolved with a [`TaskContext`] first, that
19/// contains all relevant Zed state in task variables.
20/// A single template may produce different tasks (or none) for different contexts.
21#[derive(Clone, Default, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
22#[serde(rename_all = "snake_case")]
23pub struct TaskTemplate {
24 /// Human readable name of the task to display in the UI.
25 pub label: String,
26 /// Executable command to spawn.
27 pub command: String,
28 /// Arguments to the command.
29 #[serde(default)]
30 pub args: Vec<String>,
31 /// Env overrides for the command, will be appended to the terminal's environment from the settings.
32 #[serde(default)]
33 pub env: HashMap<String, String>,
34 /// Current working directory to spawn the command into, defaults to current project root.
35 #[serde(default)]
36 pub cwd: Option<String>,
37 /// Whether to use a new terminal tab or reuse the existing one to spawn the process.
38 #[serde(default)]
39 pub use_new_terminal: bool,
40 /// Whether to allow multiple instances of the same task to be run, or rather wait for the existing ones to finish.
41 #[serde(default)]
42 pub allow_concurrent_runs: bool,
43 /// What to do with the terminal pane and tab, after the command was started:
44 /// * `always` — always show the terminal pane, add and focus the corresponding task's tab in it (default)
45 /// * `never` — avoid changing current terminal pane focus, but still add/reuse the task's tab there
46 #[serde(default)]
47 pub reveal: RevealStrategy,
48
49 /// Represents the tags which this template attaches to. Adding this removes this task from other UI.
50 #[serde(default)]
51 pub tags: Vec<String>,
52}
53
54/// What to do with the terminal pane and tab, after the command was started.
55#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
56#[serde(rename_all = "snake_case")]
57pub enum RevealStrategy {
58 /// Always show the terminal pane, add and focus the corresponding task's tab in it.
59 #[default]
60 Always,
61 /// Do not change terminal pane focus, but still add/reuse the task's tab there.
62 Never,
63}
64
65/// A group of Tasks defined in a JSON file.
66#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
67pub struct TaskTemplates(pub Vec<TaskTemplate>);
68
69impl TaskTemplates {
70 /// Generates JSON schema of Tasks JSON template format.
71 pub fn generate_json_schema() -> serde_json_lenient::Value {
72 let schema = SchemaSettings::draft07()
73 .with(|settings| settings.option_add_null_type = false)
74 .into_generator()
75 .into_root_schema_for::<Self>();
76
77 serde_json_lenient::to_value(schema).unwrap()
78 }
79}
80
81impl TaskTemplate {
82 /// Replaces all `VariableName` task variables in the task template string fields.
83 /// If any replacement fails or the new string substitutions still have [`ZED_VARIABLE_NAME_PREFIX`],
84 /// `None` is returned.
85 ///
86 /// Every [`ResolvedTask`] gets a [`TaskId`], based on the `id_base` (to avoid collision with various task sources),
87 /// and hashes of its template and [`TaskContext`], see [`ResolvedTask`] fields' documentation for more details.
88 pub fn resolve_task(&self, id_base: &str, cx: &TaskContext) -> Option<ResolvedTask> {
89 if self.label.trim().is_empty() || self.command.trim().is_empty() {
90 return None;
91 }
92
93 let mut variable_names = HashMap::default();
94 let mut substituted_variables = HashSet::default();
95 let task_variables = cx
96 .task_variables
97 .0
98 .iter()
99 .map(|(key, value)| {
100 let key_string = key.to_string();
101 if !variable_names.contains_key(&key_string) {
102 variable_names.insert(key_string.clone(), key.clone());
103 }
104 (key_string, value.as_str())
105 })
106 .collect::<HashMap<_, _>>();
107 let truncated_variables = truncate_variables(&task_variables);
108 let cwd = match self.cwd.as_deref() {
109 Some(cwd) => {
110 let substitured_cwd = substitute_all_template_variables_in_str(
111 cwd,
112 &task_variables,
113 &variable_names,
114 &mut substituted_variables,
115 )?;
116 Some(TerminalWorkDir::Local(PathBuf::from(substitured_cwd)))
117 }
118 None => None,
119 }
120 .or(cx
121 .cwd
122 .as_ref()
123 .map(|cwd| TerminalWorkDir::Local(cwd.clone())));
124 let human_readable_label = substitute_all_template_variables_in_str(
125 &self.label,
126 &truncated_variables,
127 &variable_names,
128 &mut substituted_variables,
129 )?
130 .lines()
131 .fold(String::new(), |mut string, line| {
132 if string.is_empty() {
133 string.push_str(line);
134 } else {
135 string.push_str("\\n");
136 string.push_str(line);
137 }
138 string
139 });
140 let full_label = substitute_all_template_variables_in_str(
141 &self.label,
142 &task_variables,
143 &variable_names,
144 &mut substituted_variables,
145 )?;
146 let command = substitute_all_template_variables_in_str(
147 &self.command,
148 &task_variables,
149 &variable_names,
150 &mut substituted_variables,
151 )?;
152 let args_with_substitutions = substitute_all_template_variables_in_vec(
153 &self.args,
154 &task_variables,
155 &variable_names,
156 &mut substituted_variables,
157 )?;
158
159 let task_hash = to_hex_hash(&self)
160 .context("hashing task template")
161 .log_err()?;
162 let variables_hash = to_hex_hash(&task_variables)
163 .context("hashing task variables")
164 .log_err()?;
165 let id = TaskId(format!("{id_base}_{task_hash}_{variables_hash}"));
166 let mut env = substitute_all_template_variables_in_map(
167 &self.env,
168 &task_variables,
169 &variable_names,
170 &mut substituted_variables,
171 )?;
172 env.extend(task_variables.into_iter().map(|(k, v)| (k, v.to_owned())));
173 Some(ResolvedTask {
174 id: id.clone(),
175 substituted_variables,
176 original_task: self.clone(),
177 resolved_label: full_label.clone(),
178 resolved: Some(SpawnInTerminal {
179 id,
180 cwd,
181 full_label,
182 label: human_readable_label,
183 command_label: args_with_substitutions.iter().fold(
184 command.clone(),
185 |mut command_label, arg| {
186 command_label.push(' ');
187 command_label.push_str(arg);
188 command_label
189 },
190 ),
191 command,
192 args: self.args.clone(),
193 env,
194 use_new_terminal: self.use_new_terminal,
195 allow_concurrent_runs: self.allow_concurrent_runs,
196 reveal: self.reveal,
197 }),
198 })
199 }
200}
201
202const MAX_DISPLAY_VARIABLE_LENGTH: usize = 15;
203
204fn truncate_variables(task_variables: &HashMap<String, &str>) -> HashMap<String, String> {
205 task_variables
206 .iter()
207 .map(|(key, value)| {
208 (
209 key.clone(),
210 truncate_and_remove_front(value, MAX_DISPLAY_VARIABLE_LENGTH),
211 )
212 })
213 .collect()
214}
215
216fn to_hex_hash(object: impl Serialize) -> anyhow::Result<String> {
217 let json = serde_json_lenient::to_string(&object).context("serializing the object")?;
218 let mut hasher = Sha256::new();
219 hasher.update(json.as_bytes());
220 Ok(hex::encode(hasher.finalize()))
221}
222
223fn substitute_all_template_variables_in_str<A: AsRef<str>>(
224 template_str: &str,
225 task_variables: &HashMap<String, A>,
226 variable_names: &HashMap<String, VariableName>,
227 substituted_variables: &mut HashSet<VariableName>,
228) -> Option<String> {
229 let substituted_string = shellexpand::env_with_context(template_str, |var| {
230 // 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.
231 let colon_position = var.find(':').unwrap_or(var.len());
232 let (variable_name, default) = var.split_at(colon_position);
233 if let Some(name) = task_variables.get(variable_name) {
234 if let Some(substituted_variable) = variable_names.get(variable_name) {
235 substituted_variables.insert(substituted_variable.clone());
236 }
237
238 let mut name = name.as_ref().to_owned();
239 // Got a task variable hit
240 if !default.is_empty() {
241 name.push_str(default);
242 }
243 return Ok(Some(name));
244 } else if variable_name.starts_with(ZED_VARIABLE_NAME_PREFIX) {
245 bail!("Unknown variable name: {variable_name}");
246 }
247 // This is an unknown variable.
248 // 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.
249 // If there's a default, we need to return the string verbatim as otherwise shellexpand will apply that default for us.
250 if !default.is_empty() {
251 return Ok(Some(format!("${{{var}}}")));
252 }
253 // Else we can just return None and that variable will be left as is.
254 Ok(None)
255 })
256 .ok()?;
257 Some(substituted_string.into_owned())
258}
259
260fn substitute_all_template_variables_in_vec(
261 template_strs: &[String],
262 task_variables: &HashMap<String, &str>,
263 variable_names: &HashMap<String, VariableName>,
264 substituted_variables: &mut HashSet<VariableName>,
265) -> Option<Vec<String>> {
266 let mut expanded = Vec::with_capacity(template_strs.len());
267 for variable in template_strs {
268 let new_value = substitute_all_template_variables_in_str(
269 variable,
270 task_variables,
271 variable_names,
272 substituted_variables,
273 )?;
274 expanded.push(new_value);
275 }
276 Some(expanded)
277}
278
279fn substitute_all_template_variables_in_map(
280 keys_and_values: &HashMap<String, String>,
281 task_variables: &HashMap<String, &str>,
282 variable_names: &HashMap<String, VariableName>,
283 substituted_variables: &mut HashSet<VariableName>,
284) -> Option<HashMap<String, String>> {
285 let mut new_map: HashMap<String, String> = Default::default();
286 for (key, value) in keys_and_values {
287 let new_value = substitute_all_template_variables_in_str(
288 &value,
289 task_variables,
290 variable_names,
291 substituted_variables,
292 )?;
293 let new_key = substitute_all_template_variables_in_str(
294 &key,
295 task_variables,
296 variable_names,
297 substituted_variables,
298 )?;
299 new_map.insert(new_key, new_value);
300 }
301 Some(new_map)
302}
303
304#[cfg(test)]
305mod tests {
306 use std::{borrow::Cow, path::Path};
307
308 use crate::{TaskVariables, VariableName};
309
310 use super::*;
311
312 const TEST_ID_BASE: &str = "test_base";
313
314 #[test]
315 fn test_resolving_templates_with_blank_command_and_label() {
316 let task_with_all_properties = TaskTemplate {
317 label: "test_label".to_string(),
318 command: "test_command".to_string(),
319 args: vec!["test_arg".to_string()],
320 env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
321 ..TaskTemplate::default()
322 };
323
324 for task_with_blank_property in &[
325 TaskTemplate {
326 label: "".to_string(),
327 ..task_with_all_properties.clone()
328 },
329 TaskTemplate {
330 command: "".to_string(),
331 ..task_with_all_properties.clone()
332 },
333 TaskTemplate {
334 label: "".to_string(),
335 command: "".to_string(),
336 ..task_with_all_properties.clone()
337 },
338 ] {
339 assert_eq!(
340 task_with_blank_property.resolve_task(TEST_ID_BASE, &TaskContext::default()),
341 None,
342 "should not resolve task with blank label and/or command: {task_with_blank_property:?}"
343 );
344 }
345 }
346
347 #[test]
348 fn test_template_cwd_resolution() {
349 let task_without_cwd = TaskTemplate {
350 cwd: None,
351 label: "test task".to_string(),
352 command: "echo 4".to_string(),
353 ..TaskTemplate::default()
354 };
355
356 let resolved_task = |task_template: &TaskTemplate, task_cx| {
357 let resolved_task = task_template
358 .resolve_task(TEST_ID_BASE, task_cx)
359 .unwrap_or_else(|| panic!("failed to resolve task {task_without_cwd:?}"));
360 assert_substituted_variables(&resolved_task, Vec::new());
361 resolved_task
362 .resolved
363 .clone()
364 .unwrap_or_else(|| {
365 panic!("failed to get resolve data for resolved task. Template: {task_without_cwd:?} Resolved: {resolved_task:?}")
366 })
367 };
368
369 let cx = TaskContext {
370 cwd: None,
371 task_variables: TaskVariables::default(),
372 };
373 assert_eq!(
374 resolved_task(&task_without_cwd, &cx).cwd,
375 None,
376 "When neither task nor task context have cwd, it should be None"
377 );
378
379 let context_cwd = Path::new("a").join("b").join("c");
380 let cx = TaskContext {
381 cwd: Some(context_cwd.clone()),
382 task_variables: TaskVariables::default(),
383 };
384 assert_eq!(
385 resolved_task(&task_without_cwd, &cx)
386 .cwd
387 .as_ref()
388 .and_then(|cwd| cwd.local_path()),
389 Some(context_cwd.as_path()),
390 "TaskContext's cwd should be taken on resolve if task's cwd is None"
391 );
392
393 let task_cwd = Path::new("d").join("e").join("f");
394 let mut task_with_cwd = task_without_cwd.clone();
395 task_with_cwd.cwd = Some(task_cwd.display().to_string());
396 let task_with_cwd = task_with_cwd;
397
398 let cx = TaskContext {
399 cwd: None,
400 task_variables: TaskVariables::default(),
401 };
402 assert_eq!(
403 resolved_task(&task_with_cwd, &cx)
404 .cwd
405 .as_ref()
406 .and_then(|cwd| cwd.local_path()),
407 Some(task_cwd.as_path()),
408 "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is None"
409 );
410
411 let cx = TaskContext {
412 cwd: Some(context_cwd.clone()),
413 task_variables: TaskVariables::default(),
414 };
415 assert_eq!(
416 resolved_task(&task_with_cwd, &cx)
417 .cwd
418 .as_ref()
419 .and_then(|cwd| cwd.local_path()),
420 Some(task_cwd.as_path()),
421 "TaskTemplate's cwd should be taken on resolve if TaskContext's cwd is not None"
422 );
423 }
424
425 #[test]
426 fn test_template_variables_resolution() {
427 let custom_variable_1 = VariableName::Custom(Cow::Borrowed("custom_variable_1"));
428 let custom_variable_2 = VariableName::Custom(Cow::Borrowed("custom_variable_2"));
429 let long_value = "01".repeat(MAX_DISPLAY_VARIABLE_LENGTH * 2);
430 let all_variables = [
431 (VariableName::Row, "1234".to_string()),
432 (VariableName::Column, "5678".to_string()),
433 (VariableName::File, "test_file".to_string()),
434 (VariableName::SelectedText, "test_selected_text".to_string()),
435 (VariableName::Symbol, long_value.clone()),
436 (VariableName::WorktreeRoot, "/test_root/".to_string()),
437 (
438 custom_variable_1.clone(),
439 "test_custom_variable_1".to_string(),
440 ),
441 (
442 custom_variable_2.clone(),
443 "test_custom_variable_2".to_string(),
444 ),
445 ];
446
447 let task_with_all_variables = TaskTemplate {
448 label: format!(
449 "test label for {} and {}",
450 VariableName::Row.template_value(),
451 VariableName::Symbol.template_value(),
452 ),
453 command: format!(
454 "echo {} {}",
455 VariableName::File.template_value(),
456 VariableName::Symbol.template_value(),
457 ),
458 args: vec![
459 format!("arg1 {}", VariableName::SelectedText.template_value()),
460 format!("arg2 {}", VariableName::Column.template_value()),
461 format!("arg3 {}", VariableName::Symbol.template_value()),
462 ],
463 env: HashMap::from_iter([
464 ("test_env_key".to_string(), "test_env_var".to_string()),
465 (
466 "env_key_1".to_string(),
467 VariableName::WorktreeRoot.template_value(),
468 ),
469 (
470 "env_key_2".to_string(),
471 format!(
472 "env_var_2 {} {}",
473 custom_variable_1.template_value(),
474 custom_variable_2.template_value()
475 ),
476 ),
477 (
478 "env_key_3".to_string(),
479 format!("env_var_3 {}", VariableName::Symbol.template_value()),
480 ),
481 ]),
482 ..TaskTemplate::default()
483 };
484
485 let mut first_resolved_id = None;
486 for i in 0..15 {
487 let resolved_task = task_with_all_variables.resolve_task(
488 TEST_ID_BASE,
489 &TaskContext {
490 cwd: None,
491 task_variables: TaskVariables::from_iter(all_variables.clone()),
492 },
493 ).unwrap_or_else(|| panic!("Should successfully resolve task {task_with_all_variables:?} with variables {all_variables:?}"));
494
495 match &first_resolved_id {
496 None => first_resolved_id = Some(resolved_task.id.clone()),
497 Some(first_id) => assert_eq!(
498 &resolved_task.id, first_id,
499 "Step {i}, for the same task template and context, there should be the same resolved task id"
500 ),
501 }
502
503 assert_eq!(
504 resolved_task.original_task, task_with_all_variables,
505 "Resolved task should store its template without changes"
506 );
507 assert_eq!(
508 resolved_task.resolved_label,
509 format!("test label for 1234 and {long_value}"),
510 "Resolved task label should be substituted with variables and those should not be shortened"
511 );
512 assert_substituted_variables(
513 &resolved_task,
514 all_variables.iter().map(|(name, _)| name.clone()).collect(),
515 );
516
517 let spawn_in_terminal = resolved_task
518 .resolved
519 .as_ref()
520 .expect("should have resolved a spawn in terminal task");
521 assert_eq!(
522 spawn_in_terminal.label,
523 format!(
524 "test label for 1234 and …{}",
525 &long_value[..=MAX_DISPLAY_VARIABLE_LENGTH]
526 ),
527 "Human-readable label should have long substitutions trimmed"
528 );
529 assert_eq!(
530 spawn_in_terminal.command,
531 format!("echo test_file {long_value}"),
532 "Command should be substituted with variables and those should not be shortened"
533 );
534 assert_eq!(
535 spawn_in_terminal.args,
536 &[
537 "arg1 $ZED_SELECTED_TEXT",
538 "arg2 $ZED_COLUMN",
539 "arg3 $ZED_SYMBOL",
540 ],
541 "Args should not be substituted with variables"
542 );
543 assert_eq!(
544 spawn_in_terminal.command_label,
545 format!("{} arg1 test_selected_text arg2 5678 arg3 {long_value}", spawn_in_terminal.command),
546 "Command label args should be substituted with variables and those should not be shortened"
547 );
548
549 assert_eq!(
550 spawn_in_terminal
551 .env
552 .get("test_env_key")
553 .map(|s| s.as_str()),
554 Some("test_env_var")
555 );
556 assert_eq!(
557 spawn_in_terminal.env.get("env_key_1").map(|s| s.as_str()),
558 Some("/test_root/")
559 );
560 assert_eq!(
561 spawn_in_terminal.env.get("env_key_2").map(|s| s.as_str()),
562 Some("env_var_2 test_custom_variable_1 test_custom_variable_2")
563 );
564 assert_eq!(
565 spawn_in_terminal.env.get("env_key_3"),
566 Some(&format!("env_var_3 {long_value}")),
567 "Env vars should be substituted with variables and those should not be shortened"
568 );
569 }
570
571 for i in 0..all_variables.len() {
572 let mut not_all_variables = all_variables.to_vec();
573 let removed_variable = not_all_variables.remove(i);
574 let resolved_task_attempt = task_with_all_variables.resolve_task(
575 TEST_ID_BASE,
576 &TaskContext {
577 cwd: None,
578 task_variables: TaskVariables::from_iter(not_all_variables),
579 },
580 );
581 assert_eq!(resolved_task_attempt, None, "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})");
582 }
583 }
584
585 #[test]
586 fn test_can_resolve_free_variables() {
587 let task = TaskTemplate {
588 label: "My task".into(),
589 command: "echo".into(),
590 args: vec!["$PATH".into()],
591 ..Default::default()
592 };
593 let resolved_task = task
594 .resolve_task(TEST_ID_BASE, &TaskContext::default())
595 .unwrap();
596 assert_substituted_variables(&resolved_task, Vec::new());
597 let resolved = resolved_task.resolved.unwrap();
598 assert_eq!(resolved.label, task.label);
599 assert_eq!(resolved.command, task.command);
600 assert_eq!(resolved.args, task.args);
601 }
602
603 #[test]
604 fn test_errors_on_missing_zed_variable() {
605 let task = TaskTemplate {
606 label: "My task".into(),
607 command: "echo".into(),
608 args: vec!["$ZED_VARIABLE".into()],
609 ..Default::default()
610 };
611 assert!(task
612 .resolve_task(TEST_ID_BASE, &TaskContext::default())
613 .is_none());
614 }
615
616 #[test]
617 fn test_symbol_dependent_tasks() {
618 let task_with_all_properties = TaskTemplate {
619 label: "test_label".to_string(),
620 command: "test_command".to_string(),
621 args: vec!["test_arg".to_string()],
622 env: HashMap::from_iter([("test_env_key".to_string(), "test_env_var".to_string())]),
623 ..TaskTemplate::default()
624 };
625 let cx = TaskContext {
626 cwd: None,
627 task_variables: TaskVariables::from_iter(Some((
628 VariableName::Symbol,
629 "test_symbol".to_string(),
630 ))),
631 };
632
633 for (i, symbol_dependent_task) in [
634 TaskTemplate {
635 label: format!("test_label_{}", VariableName::Symbol.template_value()),
636 ..task_with_all_properties.clone()
637 },
638 TaskTemplate {
639 command: format!("test_command_{}", VariableName::Symbol.template_value()),
640 ..task_with_all_properties.clone()
641 },
642 TaskTemplate {
643 args: vec![format!(
644 "test_arg_{}",
645 VariableName::Symbol.template_value()
646 )],
647 ..task_with_all_properties.clone()
648 },
649 TaskTemplate {
650 env: HashMap::from_iter([(
651 "test_env_key".to_string(),
652 format!("test_env_var_{}", VariableName::Symbol.template_value()),
653 )]),
654 ..task_with_all_properties.clone()
655 },
656 ]
657 .into_iter()
658 .enumerate()
659 {
660 let resolved = symbol_dependent_task
661 .resolve_task(TEST_ID_BASE, &cx)
662 .unwrap_or_else(|| panic!("Failed to resolve task {symbol_dependent_task:?}"));
663 assert_eq!(
664 resolved.substituted_variables,
665 HashSet::from_iter(Some(VariableName::Symbol)),
666 "(index {i}) Expected the task to depend on symbol task variable: {resolved:?}"
667 )
668 }
669 }
670
671 #[track_caller]
672 fn assert_substituted_variables(resolved_task: &ResolvedTask, mut expected: Vec<VariableName>) {
673 let mut resolved_variables = resolved_task
674 .substituted_variables
675 .iter()
676 .cloned()
677 .collect::<Vec<_>>();
678 resolved_variables.sort_by_key(|var| var.to_string());
679 expected.sort_by_key(|var| var.to_string());
680 assert_eq!(resolved_variables, expected)
681 }
682
683 #[test]
684 fn substitute_funky_labels() {
685 let faulty_go_test = TaskTemplate {
686 label: format!(
687 "go test {}/{}",
688 VariableName::Symbol.template_value(),
689 VariableName::Symbol.template_value(),
690 ),
691 command: "go".into(),
692 args: vec![format!(
693 "^{}$/^{}$",
694 VariableName::Symbol.template_value(),
695 VariableName::Symbol.template_value()
696 )],
697 ..TaskTemplate::default()
698 };
699 let mut context = TaskContext::default();
700 context
701 .task_variables
702 .insert(VariableName::Symbol, "my-symbol".to_string());
703 assert!(faulty_go_test.resolve_task("base", &context).is_some());
704 }
705}