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