Skip to content

Commit 93e6138

Browse files
committed
integate reloading
1 parent bd0a2c8 commit 93e6138

File tree

13 files changed

+150
-48
lines changed

13 files changed

+150
-48
lines changed

Cargo.lock

Lines changed: 23 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

crates/flycheck/src/json_workspace.rs

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
use std::{io, process::Command};
33

44
use crossbeam_channel::Sender;
5-
use paths::AbsPathBuf;
5+
use paths::Utf8PathBuf;
66
use project_model::ProjectJsonData;
77
use serde::{Deserialize, Serialize};
88

@@ -16,21 +16,29 @@ pub struct JsonWorkspace {
1616
sender: Sender<DiscoverProjectMessage>,
1717
}
1818

19+
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
20+
#[serde(rename_all = "camelCase")]
21+
pub enum JsonArguments {
22+
Path(Utf8PathBuf),
23+
Label(String),
24+
}
25+
1926
impl JsonWorkspace {
2027
/// Create a new [JsonWorkspace].
2128
pub fn new(sender: Sender<DiscoverProjectMessage>, command: Vec<String>) -> Self {
2229
Self { sender, command }
2330
}
2431

2532
/// Spawn the command inside [JsonWorkspace] and report progress, if any.
26-
pub fn spawn(&self, files: Vec<AbsPathBuf>) -> io::Result<JsonWorkspaceHandle> {
33+
pub fn spawn(&self, arg: JsonArguments) -> io::Result<JsonWorkspaceHandle> {
2734
let command = &self.command[0];
2835
let args = &self.command[1..];
29-
let first_file: &AbsPathBuf = &files[0];
3036

3137
let mut cmd = Command::new(command);
3238
cmd.args(args);
33-
cmd.arg(first_file);
39+
40+
let arg = serde_json::to_string(&arg)?;
41+
cmd.arg(arg);
3442

3543
Ok(JsonWorkspaceHandle { _handle: CommandHandle::spawn(cmd, self.sender.clone())? })
3644
}
@@ -48,7 +56,13 @@ pub struct JsonWorkspaceHandle {
4856
pub enum DiscoverProjectMessage {
4957
Error { message: String, context: Option<String> },
5058
Progress { message: String },
51-
Finished { project_json: Vec<ProjectJsonData> },
59+
Finished(FinishedOutput),
60+
}
61+
62+
#[derive(Debug, PartialEq, Clone, Deserialize, Serialize)]
63+
pub struct FinishedOutput {
64+
pub project: ProjectJsonData,
65+
pub buildfile: Utf8PathBuf,
5266
}
5367

5468
impl ParseFromLine for DiscoverProjectMessage {
@@ -57,8 +71,8 @@ impl ParseFromLine for DiscoverProjectMessage {
5771
return Some(DiscoverProjectMessage::Error { message: line.to_owned(), context: None });
5872
};
5973

60-
if let Ok(project) = serde_json::from_value::<ProjectJsonData>(value.clone()) {
61-
return Some(DiscoverProjectMessage::Finished { project_json: vec![project] });
74+
if let Ok(project) = serde_json::from_value::<FinishedOutput>(value.clone()) {
75+
return Some(DiscoverProjectMessage::Finished(project));
6276
}
6377

6478
if let Some(message) = value.pointer("/fields/message") {

crates/flycheck/src/lib.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,9 @@ mod json_workspace;
2626
mod test_runner;
2727

2828
use command::{CommandHandle, ParseFromLine};
29-
pub use json_workspace::{DiscoverProjectMessage, JsonWorkspace, JsonWorkspaceHandle};
29+
pub use json_workspace::{
30+
DiscoverProjectMessage, JsonArguments, JsonWorkspace, JsonWorkspaceHandle,
31+
};
3032
pub use test_runner::{CargoTestHandle, CargoTestMessage, TestState};
3133

3234
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]

crates/project-model/src/project_json.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,15 @@ impl ProjectJson {
222222
self.manifest.as_ref()
223223
}
224224

225+
pub fn crate_by_buildfile(&self, path: &AbsPath) -> Option<Build> {
226+
let path: &std::path::Path = path.as_ref();
227+
self.crates
228+
.iter()
229+
.filter(|krate| krate.is_workspace_member)
230+
.filter_map(|krate| krate.build.clone())
231+
.find(|build| build.build_file.as_std_path() == path)
232+
}
233+
225234
/// Returns the path to the project's manifest or root folder, if no manifest exists.
226235
pub fn manifest_or_root(&self) -> &AbsPath {
227236
self.manifest.as_ref().map_or(&self.project_root, |manifest| manifest.as_ref())
@@ -279,7 +288,7 @@ enum EditionData {
279288
Edition2024,
280289
}
281290

282-
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
291+
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
283292
pub struct BuildData {
284293
label: String,
285294
build_file: Utf8PathBuf,
@@ -366,7 +375,7 @@ pub(crate) struct Dep {
366375
pub(crate) name: CrateName,
367376
}
368377

369-
#[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
378+
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
370379
struct CrateSource {
371380
include_dirs: Vec<Utf8PathBuf>,
372381
exclude_dirs: Vec<Utf8PathBuf>,

crates/rust-analyzer/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ mimalloc = { version = "0.1.30", default-features = false, optional = true }
3939
lsp-server.workspace = true
4040
tracing.workspace = true
4141
tracing-subscriber.workspace = true
42+
pretty_assertions = "1.4"
4243
tracing-tree.workspace = true
4344
triomphe.workspace = true
4445
toml = "0.8.8"

crates/rust-analyzer/src/config.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2349,7 +2349,7 @@ mod single_or_array {
23492349
}
23502350
}
23512351

2352-
#[derive(Serialize, Deserialize, Debug, Clone)]
2352+
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
23532353
#[serde(untagged)]
23542354
enum ManifestOrProjectJson {
23552355
Manifest(Utf8PathBuf),

crates/rust-analyzer/src/global_state.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use project_model::{ManifestPath, ProjectWorkspace, ProjectWorkspaceKind, Worksp
2222
use rustc_hash::{FxHashMap, FxHashSet};
2323
use tracing::{span, trace, Level};
2424
use triomphe::Arc;
25-
use vfs::{AnchoredPathBuf, ChangeKind, Vfs};
25+
use vfs::{AbsPathBuf, AnchoredPathBuf, Vfs};
2626

2727
use crate::{
2828
config::{Config, ConfigChange, ConfigErrors},
@@ -139,7 +139,7 @@ pub(crate) struct GlobalState {
139139

140140
// op queues
141141
pub(crate) fetch_workspaces_queue:
142-
OpQueue<bool, Option<(Vec<anyhow::Result<ProjectWorkspace>>, bool)>>,
142+
OpQueue<(Option<AbsPathBuf>, bool), Option<(Vec<anyhow::Result<ProjectWorkspace>>, bool)>>,
143143
pub(crate) fetch_build_data_queue:
144144
OpQueue<(), (Arc<Vec<ProjectWorkspace>>, Vec<anyhow::Result<WorkspaceBuildScripts>>)>,
145145
pub(crate) fetch_proc_macros_queue: OpQueue<Vec<ProcMacroPaths>, bool>,
@@ -434,7 +434,7 @@ impl GlobalState {
434434

435435
self.fetch_workspaces_queue.request_op(
436436
format!("workspace vfs file change: {path}"),
437-
force_crate_graph_reload,
437+
(Some(path.to_owned()), force_crate_graph_reload),
438438
);
439439
}
440440
}

crates/rust-analyzer/src/handlers/notification.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -152,13 +152,15 @@ pub(crate) fn handle_did_save_text_document(
152152
// Re-fetch workspaces if a workspace related file has changed
153153
if let Some(abs_path) = vfs_path.as_path() {
154154
if reload::should_refresh_for_change(abs_path, ChangeKind::Modify) {
155-
state
156-
.fetch_workspaces_queue
157-
.request_op(format!("workspace vfs file change saved {abs_path}"), false);
155+
state.fetch_workspaces_queue.request_op(
156+
format!("workspace vfs file change saved {abs_path}"),
157+
(Some(abs_path.to_owned()), false),
158+
);
158159
} else if state.detached_files.contains(abs_path) {
159-
state
160-
.fetch_workspaces_queue
161-
.request_op(format!("detached file saved {abs_path}"), false);
160+
state.fetch_workspaces_queue.request_op(
161+
format!("detached file saved {abs_path}"),
162+
(Some(abs_path.to_owned()), false),
163+
);
162164
}
163165
}
164166

@@ -240,7 +242,9 @@ pub(crate) fn handle_did_change_workspace_folders(
240242

241243
if !config.has_linked_projects() && config.detached_files().is_empty() {
242244
config.rediscover_workspaces();
243-
state.fetch_workspaces_queue.request_op("client workspaces changed".to_owned(), false)
245+
state
246+
.fetch_workspaces_queue
247+
.request_op("client workspaces changed".to_owned(), (None, false));
244248
}
245249

246250
Ok(())

crates/rust-analyzer/src/handlers/request.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ pub(crate) fn handle_workspace_reload(state: &mut GlobalState, _: ()) -> anyhow:
5757
state.proc_macro_clients = Arc::from_iter([]);
5858
state.build_deps_changed = false;
5959

60-
state.fetch_workspaces_queue.request_op("reload workspace request".to_owned(), false);
60+
state.fetch_workspaces_queue.request_op("reload workspace request".to_owned(), (None, false));
6161
Ok(())
6262
}
6363

crates/rust-analyzer/src/main_loop.rs

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,14 @@ use std::{
99

1010
use always_assert::always;
1111
use crossbeam_channel::{select, Receiver};
12+
use flycheck::JsonArguments;
1213
use ide_db::base_db::{SourceDatabase, SourceDatabaseExt, VfsPath};
1314
use lsp_server::{Connection, Notification, Request};
1415
use lsp_types::{notification::Notification as _, TextDocumentIdentifier, Url};
16+
use paths::Utf8PathBuf;
1517
use stdx::thread::ThreadIntent;
1618
use tracing::{span, Level};
17-
use vfs::{AbsPathBuf, FileId};
19+
use vfs::FileId;
1820

1921
use crate::{
2022
config::Config,
@@ -88,7 +90,7 @@ pub(crate) enum QueuedTask {
8890
#[derive(Debug)]
8991
pub(crate) enum Task {
9092
Response(lsp_server::Response),
91-
DiscoverLinkedProjects(Url),
93+
DiscoverLinkedProjects(DiscoverProjectParam),
9294
Retry(lsp_server::Request),
9395
Diagnostics(DiagnosticsGeneration, Vec<(FileId, Vec<lsp_types::Diagnostic>)>),
9496
DiscoverTest(lsp_ext::DiscoverTestResults),
@@ -99,6 +101,12 @@ pub(crate) enum Task {
99101
BuildDepsHaveChanged,
100102
}
101103

104+
#[derive(Debug)]
105+
pub(crate) enum DiscoverProjectParam {
106+
Label(String),
107+
Path(Url),
108+
}
109+
102110
#[derive(Debug)]
103111
pub(crate) enum PrimeCachesProgress {
104112
Begin,
@@ -150,11 +158,11 @@ impl GlobalState {
150158
}
151159

152160
if self.config.discover_command().is_none() {
153-
self.fetch_workspaces_queue.request_op("startup".to_owned(), false);
154-
if let Some((cause, force_crate_graph_reload)) =
161+
self.fetch_workspaces_queue.request_op("startup".to_owned(), (None, false));
162+
if let Some((cause, (path, force_crate_graph_reload))) =
155163
self.fetch_workspaces_queue.should_start_op()
156164
{
157-
self.fetch_workspaces(cause, force_crate_graph_reload);
165+
self.fetch_workspaces(cause, path, force_crate_graph_reload);
158166
}
159167
}
160168

@@ -195,7 +203,12 @@ impl GlobalState {
195203
lsp_types::DocumentFilter {
196204
language: None,
197205
scheme: None,
198-
pattern: Some("**/rust-analyzer.toml".into()),
206+
pattern: Some("**/BUCK".into()),
207+
},
208+
lsp_types::DocumentFilter {
209+
language: None,
210+
scheme: None,
211+
pattern: Some("**/TARGETS".into()),
199212
},
200213
]),
201214
},
@@ -442,10 +455,10 @@ impl GlobalState {
442455
}
443456

444457
if self.config.cargo_autoreload_config() || self.config.discover_command().is_some() {
445-
if let Some((cause, force_crate_graph_reload)) =
458+
if let Some((cause, (path, force_crate_graph_reload))) =
446459
self.fetch_workspaces_queue.should_start_op()
447460
{
448-
self.fetch_workspaces(cause, force_crate_graph_reload);
461+
self.fetch_workspaces(cause, path, force_crate_graph_reload);
449462
}
450463
}
451464

@@ -658,23 +671,29 @@ impl GlobalState {
658671

659672
self.report_progress("Fetching", state, msg, None, None);
660673
}
661-
Task::DiscoverLinkedProjects(url) => {
674+
Task::DiscoverLinkedProjects(arg) => {
662675
if let Some(command) = self.config.discover_command() {
663676
if !self.discover_workspace_queue.op_in_progress() {
664677
let discover =
665678
flycheck::JsonWorkspace::new(self.discover_sender.clone(), command);
666679

667-
let path = url
668-
.to_file_path()
669-
.unwrap_or_else(|_| panic!("Unable to get file path from {}", url));
670-
let files = vec![AbsPathBuf::try_from(path).unwrap()];
671-
672680
self.report_progress("Buck", Progress::Begin, None, None, None);
673681
self.discover_workspace_queue
674682
.request_op("Discovering workspace".to_owned(), ());
675683
let _ = self.discover_workspace_queue.should_start_op();
676684

677-
let handle = discover.spawn(files).unwrap();
685+
let arg = match arg {
686+
DiscoverProjectParam::Label(label) => JsonArguments::Label(label),
687+
DiscoverProjectParam::Path(path) => {
688+
let path =
689+
path.to_file_path().expect("unable to convert to PathBuf");
690+
let path = Utf8PathBuf::from_path_buf(path)
691+
.expect("Unable to convert to Utf8PathBuf");
692+
JsonArguments::Path(path)
693+
}
694+
};
695+
696+
let handle = discover.spawn(arg).unwrap();
678697
self.discover_handle = Some(handle);
679698
}
680699
}
@@ -788,7 +807,8 @@ impl GlobalState {
788807
if let Ok(crates) = &snap.analysis.crates_for(id) {
789808
if crates.is_empty() {
790809
if snap.config.discover_command().is_some() {
791-
sender.send(Task::DiscoverLinkedProjects(uri)).unwrap();
810+
let arg = DiscoverProjectParam::Path(uri);
811+
sender.send(Task::DiscoverLinkedProjects(arg)).unwrap();
792812
}
793813
} else {
794814
tracing::debug!(?uri, "is indexed");
@@ -820,11 +840,11 @@ impl GlobalState {
820840

821841
fn handle_discover_msg(&mut self, message: flycheck::DiscoverProjectMessage) {
822842
match message {
823-
flycheck::DiscoverProjectMessage::Finished { project_json } => {
843+
flycheck::DiscoverProjectMessage::Finished(output) => {
824844
self.report_progress("Buck", Progress::End, None, None, None);
825845
self.discover_workspace_queue.op_completed(());
826846
let mut config = Config::clone(&*self.config);
827-
config.add_linked_projects(project_json);
847+
config.add_linked_projects(output.project);
828848
self.update_configuration(config);
829849
}
830850
flycheck::DiscoverProjectMessage::Progress { message } => {

crates/rust-analyzer/src/op_queue.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
44
pub(crate) type Cause = String;
55

6+
#[derive(Debug)]
67
pub(crate) struct OpQueue<Args = (), Output = ()> {
78
op_requested: Option<(Cause, Args)>,
89
op_in_progress: bool,

0 commit comments

Comments
 (0)