1use std::path::PathBuf;
2
3use editor::Editor;
4use gpui::{AppContext, ViewContext, WindowContext};
5use language::Point;
6use modal::{Spawn, TasksModal};
7use project::{Location, WorktreeId};
8use task::{Task, TaskContext, TaskVariables};
9use util::ResultExt;
10use workspace::Workspace;
11
12mod modal;
13
14pub fn init(cx: &mut AppContext) {
15 cx.observe_new_views(
16 |workspace: &mut Workspace, _: &mut ViewContext<Workspace>| {
17 workspace
18 .register_action(spawn_task_or_modal)
19 .register_action(move |workspace, action: &modal::Rerun, cx| {
20 if let Some((task, old_context)) =
21 workspace.project().update(cx, |project, cx| {
22 project
23 .task_inventory()
24 .update(cx, |inventory, cx| inventory.last_scheduled_task(cx))
25 })
26 {
27 let task_context = if action.reevaluate_context {
28 let cwd = task_cwd(workspace, cx).log_err().flatten();
29 task_context(workspace, cwd, cx)
30 } else {
31 old_context
32 };
33
34 schedule_task(workspace, task.as_ref(), task_context, false, cx)
35 };
36 });
37 },
38 )
39 .detach();
40}
41
42fn spawn_task_or_modal(workspace: &mut Workspace, action: &Spawn, cx: &mut ViewContext<Workspace>) {
43 let inventory = workspace.project().read(cx).task_inventory().clone();
44 let workspace_handle = workspace.weak_handle();
45 let cwd = task_cwd(workspace, cx).log_err().flatten();
46 let task_context = task_context(workspace, cwd, cx);
47 if let Some(name) = action.task_name.clone() {
48 // Do not actually show the modal.
49 spawn_task_with_name(name.clone(), cx);
50 } else {
51 workspace.toggle_modal(cx, |cx| {
52 TasksModal::new(inventory, task_context, workspace_handle, cx)
53 })
54 }
55}
56
57fn spawn_task_with_name(name: String, cx: &mut ViewContext<Workspace>) {
58 cx.spawn(|workspace, mut cx| async move {
59 let did_spawn = workspace
60 .update(&mut cx, |this, cx| {
61 let active_item = this
62 .active_item(cx)
63 .and_then(|item| item.project_path(cx))
64 .map(|path| path.worktree_id);
65 let tasks = this.project().update(cx, |project, cx| {
66 project.task_inventory().update(cx, |inventory, cx| {
67 inventory.list_tasks(None, active_item, false, cx)
68 })
69 });
70 let (_, target_task) = tasks.into_iter().find(|(_, task)| task.name() == name)?;
71 let cwd = task_cwd(this, cx).log_err().flatten();
72 let task_context = task_context(this, cwd, cx);
73 schedule_task(this, target_task.as_ref(), task_context, false, cx);
74 Some(())
75 })
76 .ok()
77 .flatten()
78 .is_some();
79 if !did_spawn {
80 workspace
81 .update(&mut cx, |workspace, cx| {
82 spawn_task_or_modal(workspace, &Spawn::default(), cx);
83 })
84 .ok();
85 }
86 })
87 .detach();
88}
89
90fn task_context(
91 workspace: &Workspace,
92 cwd: Option<PathBuf>,
93 cx: &mut WindowContext<'_>,
94) -> TaskContext {
95 let current_editor = workspace
96 .active_item(cx)
97 .and_then(|item| item.act_as::<Editor>(cx))
98 .clone();
99 if let Some(current_editor) = current_editor {
100 (|| {
101 let editor = current_editor.read(cx);
102 let selection = editor.selections.newest::<usize>(cx);
103 let (buffer, _, _) = editor
104 .buffer()
105 .read(cx)
106 .point_to_buffer_offset(selection.start, cx)?;
107
108 current_editor.update(cx, |editor, cx| {
109 let snapshot = editor.snapshot(cx);
110 let selection_range = selection.range();
111 let start = snapshot
112 .display_snapshot
113 .buffer_snapshot
114 .anchor_after(selection_range.start)
115 .text_anchor;
116 let end = snapshot
117 .display_snapshot
118 .buffer_snapshot
119 .anchor_after(selection_range.end)
120 .text_anchor;
121 let Point { row, column } = snapshot
122 .display_snapshot
123 .buffer_snapshot
124 .offset_to_point(selection_range.start);
125 let row = row + 1;
126 let column = column + 1;
127 let location = Location {
128 buffer: buffer.clone(),
129 range: start..end,
130 };
131
132 let current_file = location
133 .buffer
134 .read(cx)
135 .file()
136 .and_then(|file| file.as_local())
137 .map(|file| file.abs_path(cx).to_string_lossy().to_string());
138 let worktree_id = location
139 .buffer
140 .read(cx)
141 .file()
142 .map(|file| WorktreeId::from_usize(file.worktree_id()));
143 let context = buffer
144 .read(cx)
145 .language()
146 .and_then(|language| language.context_provider())
147 .and_then(|provider| provider.build_context(location, cx).ok());
148
149 let worktree_path = worktree_id.and_then(|worktree_id| {
150 workspace
151 .project()
152 .read(cx)
153 .worktree_for_id(worktree_id, cx)
154 .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().to_string())
155 });
156
157 let selected_text = buffer.read(cx).chars_for_range(selection_range).collect();
158
159 let mut task_variables = TaskVariables::from_iter([
160 ("ZED_ROW".into(), row.to_string()),
161 ("ZED_COLUMN".into(), column.to_string()),
162 ("ZED_SELECTED_TEXT".into(), selected_text),
163 ]);
164 if let Some(path) = current_file {
165 task_variables.0.insert("ZED_FILE".into(), path);
166 }
167 if let Some(worktree_path) = worktree_path {
168 task_variables
169 .0
170 .insert("ZED_WORKTREE_ROOT".into(), worktree_path);
171 }
172 if let Some(language_context) = context {
173 task_variables.0.extend(language_context.0);
174 }
175
176 Some(TaskContext {
177 cwd: cwd.clone(),
178 task_variables,
179 })
180 })
181 })()
182 .unwrap_or_else(|| TaskContext {
183 cwd,
184 task_variables: Default::default(),
185 })
186 } else {
187 TaskContext {
188 cwd,
189 task_variables: Default::default(),
190 }
191 }
192}
193
194fn schedule_task(
195 workspace: &Workspace,
196 task: &dyn Task,
197 task_cx: TaskContext,
198 omit_history: bool,
199 cx: &mut ViewContext<'_, Workspace>,
200) {
201 let spawn_in_terminal = task.exec(task_cx.clone());
202 if let Some(spawn_in_terminal) = spawn_in_terminal {
203 if !omit_history {
204 workspace.project().update(cx, |project, cx| {
205 project.task_inventory().update(cx, |inventory, _| {
206 inventory.task_scheduled(task.id().clone(), task_cx);
207 })
208 });
209 }
210 cx.emit(workspace::Event::SpawnTask(spawn_in_terminal));
211 }
212}
213
214fn task_cwd(workspace: &Workspace, cx: &mut WindowContext) -> anyhow::Result<Option<PathBuf>> {
215 let project = workspace.project().read(cx);
216 let available_worktrees = project
217 .worktrees()
218 .filter(|worktree| {
219 let worktree = worktree.read(cx);
220 worktree.is_visible()
221 && worktree.is_local()
222 && worktree.root_entry().map_or(false, |e| e.is_dir())
223 })
224 .collect::<Vec<_>>();
225 let cwd = match available_worktrees.len() {
226 0 => None,
227 1 => Some(available_worktrees[0].read(cx).abs_path()),
228 _ => {
229 let cwd_for_active_entry = project.active_entry().and_then(|entry_id| {
230 available_worktrees.into_iter().find_map(|worktree| {
231 let worktree = worktree.read(cx);
232 if worktree.contains_entry(entry_id) {
233 Some(worktree.abs_path())
234 } else {
235 None
236 }
237 })
238 });
239 anyhow::ensure!(
240 cwd_for_active_entry.is_some(),
241 "Cannot determine task cwd for multiple worktrees"
242 );
243 cwd_for_active_entry
244 }
245 };
246 Ok(cwd.map(|path| path.to_path_buf()))
247}
248
249#[cfg(test)]
250mod tests {
251 use std::sync::Arc;
252
253 use editor::Editor;
254 use gpui::{Entity, TestAppContext};
255 use language::{Language, LanguageConfig, SymbolContextProvider};
256 use project::{FakeFs, Project, TaskSourceKind};
257 use serde_json::json;
258 use task::{oneshot_source::OneshotSource, TaskContext, TaskVariables};
259 use ui::VisualContext;
260 use workspace::{AppState, Workspace};
261
262 use crate::{task_context, task_cwd};
263
264 #[gpui::test]
265 async fn test_default_language_context(cx: &mut TestAppContext) {
266 init_test(cx);
267 let fs = FakeFs::new(cx.executor());
268 fs.insert_tree(
269 "/dir",
270 json!({
271 ".zed": {
272 "tasks.json": r#"[
273 {
274 "label": "example task",
275 "command": "echo",
276 "args": ["4"]
277 },
278 {
279 "label": "another one",
280 "command": "echo",
281 "args": ["55"]
282 },
283 ]"#,
284 },
285 "a.ts": "function this_is_a_test() { }",
286 "rust": {
287 "b.rs": "use std; fn this_is_a_rust_file() { }",
288 }
289
290 }),
291 )
292 .await;
293
294 let rust_language = Arc::new(
295 Language::new(
296 LanguageConfig::default(),
297 Some(tree_sitter_rust::language()),
298 )
299 .with_outline_query(
300 r#"(function_item
301 "fn" @context
302 name: (_) @name) @item"#,
303 )
304 .unwrap()
305 .with_context_provider(Some(Arc::new(SymbolContextProvider))),
306 );
307
308 let typescript_language = Arc::new(
309 Language::new(
310 LanguageConfig::default(),
311 Some(tree_sitter_typescript::language_typescript()),
312 )
313 .with_outline_query(
314 r#"(function_declaration
315 "async"? @context
316 "function" @context
317 name: (_) @name
318 parameters: (formal_parameters
319 "(" @context
320 ")" @context)) @item"#,
321 )
322 .unwrap()
323 .with_context_provider(Some(Arc::new(SymbolContextProvider))),
324 );
325 let project = Project::test(fs, ["/dir".as_ref()], cx).await;
326 project.update(cx, |project, cx| {
327 project.task_inventory().update(cx, |inventory, cx| {
328 inventory.add_source(TaskSourceKind::UserInput, |cx| OneshotSource::new(cx), cx)
329 })
330 });
331 let worktree_id = project.update(cx, |project, cx| {
332 project.worktrees().next().unwrap().read(cx).id()
333 });
334 let (workspace, cx) = cx.add_window_view(|cx| Workspace::test_new(project.clone(), cx));
335
336 let buffer1 = workspace
337 .update(cx, |this, cx| {
338 this.project()
339 .update(cx, |this, cx| this.open_buffer((worktree_id, "a.ts"), cx))
340 })
341 .await
342 .unwrap();
343 buffer1.update(cx, |this, cx| {
344 this.set_language(Some(typescript_language), cx)
345 });
346 let editor1 = cx.new_view(|cx| Editor::for_buffer(buffer1, Some(project.clone()), cx));
347 let buffer2 = workspace
348 .update(cx, |this, cx| {
349 this.project().update(cx, |this, cx| {
350 this.open_buffer((worktree_id, "rust/b.rs"), cx)
351 })
352 })
353 .await
354 .unwrap();
355 buffer2.update(cx, |this, cx| this.set_language(Some(rust_language), cx));
356 let editor2 = cx.new_view(|cx| Editor::for_buffer(buffer2, Some(project), cx));
357 workspace.update(cx, |this, cx| {
358 this.add_item_to_center(Box::new(editor1.clone()), cx);
359 this.add_item_to_center(Box::new(editor2.clone()), cx);
360 assert_eq!(this.active_item(cx).unwrap().item_id(), editor2.entity_id());
361 assert_eq!(
362 task_context(this, task_cwd(this, cx).unwrap(), cx),
363 TaskContext {
364 cwd: Some("/dir".into()),
365 task_variables: TaskVariables::from_iter([
366 ("ZED_FILE".into(), "/dir/rust/b.rs".into()),
367 ("ZED_WORKTREE_ROOT".into(), "/dir".into()),
368 ("ZED_ROW".into(), "1".into()),
369 ("ZED_COLUMN".into(), "1".into()),
370 ("ZED_SELECTED_TEXT".into(), "".into())
371 ])
372 }
373 );
374 // And now, let's select an identifier.
375 editor2.update(cx, |this, cx| {
376 this.change_selections(None, cx, |selections| selections.select_ranges([14..18]))
377 });
378 assert_eq!(
379 task_context(this, task_cwd(this, cx).unwrap(), cx),
380 TaskContext {
381 cwd: Some("/dir".into()),
382 task_variables: TaskVariables::from_iter([
383 ("ZED_FILE".into(), "/dir/rust/b.rs".into()),
384 ("ZED_WORKTREE_ROOT".into(), "/dir".into()),
385 ("ZED_SYMBOL".into(), "this_is_a_rust_file".into()),
386 ("ZED_ROW".into(), "1".into()),
387 ("ZED_COLUMN".into(), "15".into()),
388 ("ZED_SELECTED_TEXT".into(), "is_i".into()),
389 ])
390 }
391 );
392
393 // Now, let's switch the active item to .ts file.
394 this.activate_item(&editor1, cx);
395 assert_eq!(
396 task_context(this, task_cwd(this, cx).unwrap(), cx),
397 TaskContext {
398 cwd: Some("/dir".into()),
399 task_variables: TaskVariables::from_iter([
400 ("ZED_FILE".into(), "/dir/a.ts".into()),
401 ("ZED_WORKTREE_ROOT".into(), "/dir".into()),
402 ("ZED_SYMBOL".into(), "this_is_a_test".into()),
403 ("ZED_ROW".into(), "1".into()),
404 ("ZED_COLUMN".into(), "1".into()),
405 ("ZED_SELECTED_TEXT".into(), "".into()),
406 ])
407 }
408 );
409 });
410 }
411
412 pub(crate) fn init_test(cx: &mut TestAppContext) -> Arc<AppState> {
413 cx.update(|cx| {
414 let state = AppState::test(cx);
415 language::init(cx);
416 crate::init(cx);
417 editor::init(cx);
418 workspace::init_settings(cx);
419 Project::init_settings(cx);
420 state
421 })
422 }
423}