Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/starpls/src/commands/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ impl ServerCommand {
}),
declaration_provider: Some(DeclarationCapability::Simple(true)),
definition_provider: Some(OneOf::Left(true)),
document_formatting_provider: Some(OneOf::Left(true)),
document_symbol_provider: Some(OneOf::Left(true)),
hover_provider: Some(HoverProviderCapability::Simple(true)),
references_provider: Some(OneOf::Left(true)),
Expand Down
22 changes: 22 additions & 0 deletions crates/starpls/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
use lsp_types::ClientCapabilities;
use serde::Deserialize;
use serde_json::Value;

use crate::commands::server::ServerCommand;

#[derive(Deserialize, Default)]
#[serde(default)]
pub(crate) struct BuildifierConfig {
pub(crate) path: Option<String>,
pub(crate) args: Vec<String>,
}

#[derive(Deserialize)]
struct InitializationOptions {
buildifier: Option<BuildifierConfig>,
}

#[derive(Default)]
pub(crate) struct ServerConfig {
pub(crate) buildifier: Option<BuildifierConfig>,
pub(crate) args: ServerCommand,
pub(crate) caps: ClientCapabilities,
}
Expand All @@ -15,6 +30,13 @@ macro_rules! try_or_default {
}

impl ServerConfig {
pub(crate) fn from_json(value: Value) -> Self {
let mut config = ServerConfig::default();
if let Ok(opts) = serde_json::from_value::<InitializationOptions>(value) {
config.buildifier = opts.buildifier;
}
config
}
pub(crate) fn has_text_document_definition_link_support(&self) -> bool {
try_or_default!(self.caps.text_document.as_ref()?.definition?.link_support)
}
Expand Down
9 changes: 5 additions & 4 deletions crates/starpls/src/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,10 @@ pub fn process_connection(
initialize_params: InitializeParams,
) -> anyhow::Result<()> {
debug!("initializing state and starting event loop");
let config = ServerConfig {
args,
caps: initialize_params.capabilities,
};
let mut config =
ServerConfig::from_json(initialize_params.initialization_options.unwrap_or_default());
config.args = args;
config.caps = initialize_params.capabilities;
let server = Server::new(connection, config)?;
server.run()
}
Expand Down Expand Up @@ -218,6 +218,7 @@ impl Server {
.on::<lsp_types::request::HoverRequest>(requests::hover)
.on::<lsp_types::request::References>(requests::find_references)
.on::<lsp_types::request::SignatureHelpRequest>(requests::signature_help)
.on::<lsp_types::request::Formatting>(requests::formatting)
.finish();
}

Expand Down
72 changes: 72 additions & 0 deletions crates/starpls/src/handlers/requests.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::io::Write;

use anyhow::Ok;
use starpls_ide::CompletionItemKind;
use starpls_ide::CompletionMode::InsertText;
Expand Down Expand Up @@ -287,6 +289,76 @@ pub(crate) fn document_symbols(
}))
}

pub(crate) fn formatting(
snapshot: &ServerSnapshot,
params: lsp_types::DocumentFormattingParams,
) -> anyhow::Result<Option<Vec<lsp_types::TextEdit>>> {
let path = path_buf_from_url(&params.text_document.uri)?;
let file_id = try_opt!(snapshot.document_manager.read().lookup_by_path_buf(&path));
let line_index = try_opt!(snapshot.analysis_snapshot.line_index(file_id)?);
let default_buildifier_config;
let buildifier = match &snapshot.config.buildifier {
Some(config) => config,
None => {
default_buildifier_config = Default::default();
&default_buildifier_config
}
};

// Read the file's contents.
let contents = try_opt!(snapshot.analysis_snapshot.file_contents(file_id)?);

// Spawn buildifier.
let mut command =
std::process::Command::new(buildifier.path.as_deref().unwrap_or("buildifier"));
command.args(&buildifier.args);

// Set the `--type` argument based on the file extension.
let file_name = path.file_name().and_then(|name| name.to_str());
let file_type = match file_name {
Some("BUILD") | Some("BUILD.bazel") => "build",
Some("WORKSPACE") | Some("WORKSPACE.bazel") => "workspace",
Some("MODULE.bazel") => "module",
_ => match path.extension().and_then(|ext| ext.to_str()) {
Some("bzl") => "bzl",
_ => "default",
},
};
command.args(["--type", file_type]);

command.arg("-");
let mut child = command
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()?;

// Write the file's contents to stdin.
let mut stdin = child.stdin.take().unwrap();
stdin.write_all(contents.as_bytes())?;
drop(stdin);

// Read the formatted output from stdout.
let output = child.wait_with_output()?;
if !output.status.success() {
return Ok(None);
}
let new_text = String::from_utf8(output.stdout)?;

// Replace the entire document with the formatted text.
let range = lsp_types::Range {
start: lsp_types::Position {
line: 0,
character: 0,
},
end: lsp_types::Position {
line: line_index.len().into(),
character: 0,
},
};

Ok(Some(vec![lsp_types::TextEdit { range, new_text }]))
}

fn to_markup_doc(doc: String) -> lsp_types::Documentation {
lsp_types::Documentation::MarkupContent(lsp_types::MarkupContent {
kind: lsp_types::MarkupKind::Markdown,
Expand Down
4 changes: 4 additions & 0 deletions crates/starpls_ide/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,10 @@ impl AnalysisSnapshot {
self.query(|db| signature_help::signature_help(db, pos))
}

pub fn file_contents(&self, file_id: FileId) -> Cancellable<Option<String>> {
self.query(|db| db.get_file(file_id).map(|file| file.contents(db).clone()))
}

/// Helper method to handle Salsa cancellations.
fn query<'a, F, T>(&'a self, f: F) -> Cancellable<T>
where
Expand Down