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