├── .ci └── assets │ └── docs │ └── index.html ├── .github └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── bors.toml ├── examples └── goto_def.rs ├── rustfmt.toml ├── src ├── error.rs ├── lib.rs ├── msg.rs ├── req_queue.rs ├── socket.rs └── stdio.rs └── xtask ├── Cargo.toml ├── src └── main.rs └── tests └── tidy.rs /.ci/assets/docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 9 | 10 | 11 | 12 | start here 13 | 14 | 15 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | push: 5 | branches: [ "master", "staging", "trying" ] 6 | 7 | env: 8 | CARGO_INCREMENTAL: 0 9 | CARGO_NET_RETRY: 10 10 | CI: 1 11 | RUST_BACKTRACE: "short" 12 | RUSTFLAGS: "-D warnings" 13 | RUSTUP_MAX_RETRIES: 10 14 | 15 | jobs: 16 | rust: 17 | name: Rust 18 | runs-on: ubuntu-latest 19 | 20 | steps: 21 | - name: Checkout repository 22 | uses: actions/checkout@v2 23 | with: 24 | fetch-depth: 0 25 | 26 | - name: Install Rust toolchain 27 | uses: actions-rs/toolchain@v1 28 | with: 29 | toolchain: stable 30 | profile: minimal 31 | override: true 32 | 33 | - run: cargo run -p xtask -- ci 34 | env: 35 | CRATES_IO_TOKEN: ${{ secrets.CRATES_IO_TOKEN }} 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | edition = "2021" 3 | name = "lsp-server" 4 | version = "0.6.0" 5 | authors = ["rust-analyzer developers"] 6 | repository = "https://github.com/rust-analyzer/lsp-server" 7 | license = "MIT OR Apache-2.0" 8 | description = "Generic LSP server scaffold." 9 | 10 | [workspace] 11 | members = ["xtask"] 12 | 13 | [dependencies] 14 | log = "0.4.3" 15 | serde_json = "1.0.34" 16 | serde = { version = "1.0.83", features = ["derive"] } 17 | crossbeam-channel = "0.5.4" 18 | 19 | [dev-dependencies] 20 | lsp-types = "0.93.0" 21 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |

lsp-server

3 |

4 | 5 | 7 |

8 |

9 | 11 | 13 | 15 |

16 | A language server scaffold exposing a crossbeam-channel API. 17 |

This crate has been vendored into the rust-analyzer repo

18 |
19 | 20 | ## Description 21 | 22 | This crate is a language server scaffold, exposing a synchronous crossbeam-channel based API. It handles protocol handshaking and parsing messages, while you control the message dispatch loop yourself. 23 | 24 | See `examples/goto_def.rs` for a minimal example LSP server that can only respond to the `gotoDefinition` request. To use the example, execute it and then send an `initialize` request. 25 | -------------------------------------------------------------------------------- /bors.toml: -------------------------------------------------------------------------------- 1 | status = [ "Rust" ] 2 | delete_merged_branches = true 3 | -------------------------------------------------------------------------------- /examples/goto_def.rs: -------------------------------------------------------------------------------- 1 | //! A minimal example LSP server that can only respond to the `gotoDefinition` request. To use 2 | //! this example, execute it and then send an `initialize` request. 3 | //! 4 | //! ```no_run 5 | //! Content-Length: 85 6 | //! 7 | //! {"jsonrpc": "2.0", "method": "initialize", "id": 1, "params": {"capabilities": {}}} 8 | //! ``` 9 | //! 10 | //! This will respond with a server response. Then send it a `initialized` notification which will 11 | //! have no response. 12 | //! 13 | //! ```no_run 14 | //! Content-Length: 59 15 | //! 16 | //! {"jsonrpc": "2.0", "method": "initialized", "params": {}} 17 | //! ``` 18 | //! 19 | //! Once these two are sent, then we enter the main loop of the server. The only request this 20 | //! example can handle is `gotoDefinition`: 21 | //! 22 | //! ```no_run 23 | //! Content-Length: 159 24 | //! 25 | //! {"jsonrpc": "2.0", "method": "textDocument/definition", "id": 2, "params": {"textDocument": {"uri": "file://temp"}, "position": {"line": 1, "character": 1}}} 26 | //! ``` 27 | //! 28 | //! To finish up without errors, send a shutdown request: 29 | //! 30 | //! ```no_run 31 | //! Content-Length: 67 32 | //! 33 | //! {"jsonrpc": "2.0", "method": "shutdown", "id": 3, "params": null} 34 | //! ``` 35 | //! 36 | //! The server will exit the main loop and finally we send a `shutdown` notification to stop 37 | //! the server. 38 | //! 39 | //! ``` 40 | //! Content-Length: 54 41 | //! 42 | //! {"jsonrpc": "2.0", "method": "exit", "params": null} 43 | //! ``` 44 | use std::error::Error; 45 | 46 | use lsp_types::OneOf; 47 | use lsp_types::{ 48 | request::GotoDefinition, GotoDefinitionResponse, InitializeParams, ServerCapabilities, 49 | }; 50 | 51 | use lsp_server::{Connection, ExtractError, Message, Request, RequestId, Response}; 52 | 53 | fn main() -> Result<(), Box> { 54 | // Note that we must have our logging only write out to stderr. 55 | eprintln!("starting generic LSP server"); 56 | 57 | // Create the transport. Includes the stdio (stdin and stdout) versions but this could 58 | // also be implemented to use sockets or HTTP. 59 | let (connection, io_threads) = Connection::stdio(); 60 | 61 | // Run the server and wait for the two threads to end (typically by trigger LSP Exit event). 62 | let server_capabilities = serde_json::to_value(&ServerCapabilities { 63 | definition_provider: Some(OneOf::Left(true)), 64 | ..Default::default() 65 | }) 66 | .unwrap(); 67 | let initialization_params = connection.initialize(server_capabilities)?; 68 | main_loop(connection, initialization_params)?; 69 | io_threads.join()?; 70 | 71 | // Shut down gracefully. 72 | eprintln!("shutting down server"); 73 | Ok(()) 74 | } 75 | 76 | fn main_loop( 77 | connection: Connection, 78 | params: serde_json::Value, 79 | ) -> Result<(), Box> { 80 | let _params: InitializeParams = serde_json::from_value(params).unwrap(); 81 | eprintln!("starting example main loop"); 82 | for msg in &connection.receiver { 83 | eprintln!("got msg: {:?}", msg); 84 | match msg { 85 | Message::Request(req) => { 86 | if connection.handle_shutdown(&req)? { 87 | return Ok(()); 88 | } 89 | eprintln!("got request: {:?}", req); 90 | match cast::(req) { 91 | Ok((id, params)) => { 92 | eprintln!("got gotoDefinition request #{}: {:?}", id, params); 93 | let result = Some(GotoDefinitionResponse::Array(Vec::new())); 94 | let result = serde_json::to_value(&result).unwrap(); 95 | let resp = Response { id, result: Some(result), error: None }; 96 | connection.sender.send(Message::Response(resp))?; 97 | continue; 98 | } 99 | Err(err @ ExtractError::JsonError { .. }) => panic!("{:?}", err), 100 | Err(ExtractError::MethodMismatch(req)) => req, 101 | }; 102 | // ... 103 | } 104 | Message::Response(resp) => { 105 | eprintln!("got response: {:?}", resp); 106 | } 107 | Message::Notification(not) => { 108 | eprintln!("got notification: {:?}", not); 109 | } 110 | } 111 | } 112 | Ok(()) 113 | } 114 | 115 | fn cast(req: Request) -> Result<(RequestId, R::Params), ExtractError> 116 | where 117 | R: lsp_types::request::Request, 118 | R::Params: serde::de::DeserializeOwned, 119 | { 120 | req.extract(R::METHOD) 121 | } 122 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | reorder_modules = false 2 | use_small_heuristics = "Max" 3 | -------------------------------------------------------------------------------- /src/error.rs: -------------------------------------------------------------------------------- 1 | use std::fmt; 2 | 3 | use crate::{Notification, Request}; 4 | 5 | #[derive(Debug, Clone)] 6 | pub struct ProtocolError(pub(crate) String); 7 | 8 | impl std::error::Error for ProtocolError {} 9 | 10 | impl fmt::Display for ProtocolError { 11 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 12 | fmt::Display::fmt(&self.0, f) 13 | } 14 | } 15 | 16 | #[derive(Debug)] 17 | pub enum ExtractError { 18 | /// The extracted message was of a different method than expected. 19 | MethodMismatch(T), 20 | /// Failed to deserialize the message. 21 | JsonError { method: String, error: serde_json::Error }, 22 | } 23 | 24 | impl std::error::Error for ExtractError {} 25 | impl fmt::Display for ExtractError { 26 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 27 | match self { 28 | ExtractError::MethodMismatch(req) => { 29 | write!(f, "Method mismatch for request '{}'", req.method) 30 | } 31 | ExtractError::JsonError { method, error } => { 32 | write!(f, "Invalid request\nMethod: {method}\n error: {error}",) 33 | } 34 | } 35 | } 36 | } 37 | 38 | impl std::error::Error for ExtractError {} 39 | impl fmt::Display for ExtractError { 40 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 41 | match self { 42 | ExtractError::MethodMismatch(req) => { 43 | write!(f, "Method mismatch for notification '{}'", req.method) 44 | } 45 | ExtractError::JsonError { method, error } => { 46 | write!(f, "Invalid notification\nMethod: {method}\n error: {error}") 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A language server scaffold, exposing a synchronous crossbeam-channel based API. 2 | //! This crate handles protocol handshaking and parsing messages, while you 3 | //! control the message dispatch loop yourself. 4 | //! 5 | //! Run with `RUST_LOG=lsp_server=debug` to see all the messages. 6 | mod msg; 7 | mod stdio; 8 | mod error; 9 | mod socket; 10 | mod req_queue; 11 | 12 | use std::{ 13 | io, 14 | net::{TcpListener, TcpStream, ToSocketAddrs}, 15 | }; 16 | 17 | use crossbeam_channel::{Receiver, Sender}; 18 | 19 | pub use crate::{ 20 | error::{ExtractError, ProtocolError}, 21 | msg::{ErrorCode, Message, Notification, Request, RequestId, Response, ResponseError}, 22 | req_queue::{Incoming, Outgoing, ReqQueue}, 23 | stdio::IoThreads, 24 | }; 25 | 26 | /// Connection is just a pair of channels of LSP messages. 27 | pub struct Connection { 28 | pub sender: Sender, 29 | pub receiver: Receiver, 30 | } 31 | 32 | impl Connection { 33 | /// Create connection over standard in/standard out. 34 | /// 35 | /// Use this to create a real language server. 36 | pub fn stdio() -> (Connection, IoThreads) { 37 | let (sender, receiver, io_threads) = stdio::stdio_transport(); 38 | (Connection { sender, receiver }, io_threads) 39 | } 40 | 41 | /// Open a connection over tcp. 42 | /// This call blocks until a connection is established. 43 | /// 44 | /// Use this to create a real language server. 45 | pub fn connect(addr: A) -> io::Result<(Connection, IoThreads)> { 46 | let stream = TcpStream::connect(addr)?; 47 | let (sender, receiver, io_threads) = socket::socket_transport(stream); 48 | Ok((Connection { sender, receiver }, io_threads)) 49 | } 50 | 51 | /// Listen for a connection over tcp. 52 | /// This call blocks until a connection is established. 53 | /// 54 | /// Use this to create a real language server. 55 | pub fn listen(addr: A) -> io::Result<(Connection, IoThreads)> { 56 | let listener = TcpListener::bind(addr)?; 57 | let (stream, _) = listener.accept()?; 58 | let (sender, receiver, io_threads) = socket::socket_transport(stream); 59 | Ok((Connection { sender, receiver }, io_threads)) 60 | } 61 | 62 | /// Creates a pair of connected connections. 63 | /// 64 | /// Use this for testing. 65 | pub fn memory() -> (Connection, Connection) { 66 | let (s1, r1) = crossbeam_channel::unbounded(); 67 | let (s2, r2) = crossbeam_channel::unbounded(); 68 | (Connection { sender: s1, receiver: r2 }, Connection { sender: s2, receiver: r1 }) 69 | } 70 | 71 | /// Starts the initialization process by waiting for an initialize 72 | /// request from the client. Use this for more advanced customization than 73 | /// `initialize` can provide. 74 | /// 75 | /// Returns the request id and serialized `InitializeParams` from the client. 76 | /// 77 | /// # Example 78 | /// 79 | /// ```no_run 80 | /// use std::error::Error; 81 | /// use lsp_types::{ClientCapabilities, InitializeParams, ServerCapabilities}; 82 | /// 83 | /// use lsp_server::{Connection, Message, Request, RequestId, Response}; 84 | /// 85 | /// fn main() -> Result<(), Box> { 86 | /// // Create the transport. Includes the stdio (stdin and stdout) versions but this could 87 | /// // also be implemented to use sockets or HTTP. 88 | /// let (connection, io_threads) = Connection::stdio(); 89 | /// 90 | /// // Run the server 91 | /// let (id, params) = connection.initialize_start()?; 92 | /// 93 | /// let init_params: InitializeParams = serde_json::from_value(params).unwrap(); 94 | /// let client_capabilities: ClientCapabilities = init_params.capabilities; 95 | /// let server_capabilities = ServerCapabilities::default(); 96 | /// 97 | /// let initialize_data = serde_json::json!({ 98 | /// "capabilities": server_capabilities, 99 | /// "serverInfo": { 100 | /// "name": "lsp-server-test", 101 | /// "version": "0.1" 102 | /// } 103 | /// }); 104 | /// 105 | /// connection.initialize_finish(id, initialize_data)?; 106 | /// 107 | /// // ... Run main loop ... 108 | /// 109 | /// Ok(()) 110 | /// } 111 | /// ``` 112 | pub fn initialize_start(&self) -> Result<(RequestId, serde_json::Value), ProtocolError> { 113 | loop { 114 | match self.receiver.recv() { 115 | Ok(Message::Request(req)) if req.is_initialize() => { 116 | return Ok((req.id, req.params)) 117 | } 118 | // Respond to non-initialize requests with ServerNotInitialized 119 | Ok(Message::Request(req)) => { 120 | let resp = Response::new_err( 121 | req.id.clone(), 122 | ErrorCode::ServerNotInitialized as i32, 123 | format!("expected initialize request, got {:?}", req), 124 | ); 125 | self.sender.send(resp.into()).unwrap(); 126 | } 127 | Ok(msg) => { 128 | return Err(ProtocolError(format!( 129 | "expected initialize request, got {:?}", 130 | msg 131 | ))) 132 | } 133 | Err(e) => { 134 | return Err(ProtocolError(format!( 135 | "expected initialize request, got error: {}", 136 | e 137 | ))) 138 | } 139 | }; 140 | } 141 | } 142 | 143 | /// Finishes the initialization process by sending an `InitializeResult` to the client 144 | pub fn initialize_finish( 145 | &self, 146 | initialize_id: RequestId, 147 | initialize_result: serde_json::Value, 148 | ) -> Result<(), ProtocolError> { 149 | let resp = Response::new_ok(initialize_id, initialize_result); 150 | self.sender.send(resp.into()).unwrap(); 151 | match &self.receiver.recv() { 152 | Ok(Message::Notification(n)) if n.is_initialized() => (), 153 | Ok(msg) => { 154 | return Err(ProtocolError(format!( 155 | "expected Message::Notification, got: {:?}", 156 | msg, 157 | ))) 158 | } 159 | Err(e) => { 160 | return Err(ProtocolError(format!( 161 | "expected initialized notification, got error: {}", 162 | e, 163 | ))) 164 | } 165 | } 166 | Ok(()) 167 | } 168 | 169 | /// Initialize the connection. Sends the server capabilities 170 | /// to the client and returns the serialized client capabilities 171 | /// on success. If more fine-grained initialization is required use 172 | /// `initialize_start`/`initialize_finish`. 173 | /// 174 | /// # Example 175 | /// 176 | /// ```no_run 177 | /// use std::error::Error; 178 | /// use lsp_types::ServerCapabilities; 179 | /// 180 | /// use lsp_server::{Connection, Message, Request, RequestId, Response}; 181 | /// 182 | /// fn main() -> Result<(), Box> { 183 | /// // Create the transport. Includes the stdio (stdin and stdout) versions but this could 184 | /// // also be implemented to use sockets or HTTP. 185 | /// let (connection, io_threads) = Connection::stdio(); 186 | /// 187 | /// // Run the server 188 | /// let server_capabilities = serde_json::to_value(&ServerCapabilities::default()).unwrap(); 189 | /// let initialization_params = connection.initialize(server_capabilities)?; 190 | /// 191 | /// // ... Run main loop ... 192 | /// 193 | /// Ok(()) 194 | /// } 195 | /// ``` 196 | pub fn initialize( 197 | &self, 198 | server_capabilities: serde_json::Value, 199 | ) -> Result { 200 | let (id, params) = self.initialize_start()?; 201 | 202 | let initialize_data = serde_json::json!({ 203 | "capabilities": server_capabilities, 204 | }); 205 | 206 | self.initialize_finish(id, initialize_data)?; 207 | 208 | Ok(params) 209 | } 210 | 211 | /// If `req` is `Shutdown`, respond to it and return `true`, otherwise return `false` 212 | pub fn handle_shutdown(&self, req: &Request) -> Result { 213 | if !req.is_shutdown() { 214 | return Ok(false); 215 | } 216 | let resp = Response::new_ok(req.id.clone(), ()); 217 | let _ = self.sender.send(resp.into()); 218 | match &self.receiver.recv_timeout(std::time::Duration::from_secs(30)) { 219 | Ok(Message::Notification(n)) if n.is_exit() => (), 220 | Ok(msg) => { 221 | return Err(ProtocolError(format!("unexpected message during shutdown: {:?}", msg))) 222 | } 223 | Err(e) => { 224 | return Err(ProtocolError(format!("unexpected error during shutdown: {}", e))) 225 | } 226 | } 227 | Ok(true) 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /src/msg.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt, 3 | io::{self, BufRead, Write}, 4 | }; 5 | 6 | use serde::{de::DeserializeOwned, Deserialize, Serialize}; 7 | 8 | use crate::error::ExtractError; 9 | 10 | #[derive(Serialize, Deserialize, Debug, Clone)] 11 | #[serde(untagged)] 12 | pub enum Message { 13 | Request(Request), 14 | Response(Response), 15 | Notification(Notification), 16 | } 17 | 18 | impl From for Message { 19 | fn from(request: Request) -> Message { 20 | Message::Request(request) 21 | } 22 | } 23 | 24 | impl From for Message { 25 | fn from(response: Response) -> Message { 26 | Message::Response(response) 27 | } 28 | } 29 | 30 | impl From for Message { 31 | fn from(notification: Notification) -> Message { 32 | Message::Notification(notification) 33 | } 34 | } 35 | 36 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] 37 | #[serde(transparent)] 38 | pub struct RequestId(IdRepr); 39 | 40 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] 41 | #[serde(untagged)] 42 | enum IdRepr { 43 | I32(i32), 44 | String(String), 45 | } 46 | 47 | impl From for RequestId { 48 | fn from(id: i32) -> RequestId { 49 | RequestId(IdRepr::I32(id)) 50 | } 51 | } 52 | 53 | impl From for RequestId { 54 | fn from(id: String) -> RequestId { 55 | RequestId(IdRepr::String(id)) 56 | } 57 | } 58 | 59 | impl fmt::Display for RequestId { 60 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 61 | match &self.0 { 62 | IdRepr::I32(it) => fmt::Display::fmt(it, f), 63 | // Use debug here, to make it clear that `92` and `"92"` are 64 | // different, and to reduce WTF factor if the sever uses `" "` as an 65 | // ID. 66 | IdRepr::String(it) => fmt::Debug::fmt(it, f), 67 | } 68 | } 69 | } 70 | 71 | #[derive(Debug, Serialize, Deserialize, Clone)] 72 | pub struct Request { 73 | pub id: RequestId, 74 | pub method: String, 75 | #[serde(default = "serde_json::Value::default")] 76 | #[serde(skip_serializing_if = "serde_json::Value::is_null")] 77 | pub params: serde_json::Value, 78 | } 79 | 80 | #[derive(Debug, Serialize, Deserialize, Clone)] 81 | pub struct Response { 82 | // JSON RPC allows this to be null if it was impossible 83 | // to decode the request's id. Ignore this special case 84 | // and just die horribly. 85 | pub id: RequestId, 86 | #[serde(skip_serializing_if = "Option::is_none")] 87 | pub result: Option, 88 | #[serde(skip_serializing_if = "Option::is_none")] 89 | pub error: Option, 90 | } 91 | 92 | #[derive(Debug, Serialize, Deserialize, Clone)] 93 | pub struct ResponseError { 94 | pub code: i32, 95 | pub message: String, 96 | #[serde(skip_serializing_if = "Option::is_none")] 97 | pub data: Option, 98 | } 99 | 100 | #[derive(Clone, Copy, Debug)] 101 | #[allow(unused)] 102 | pub enum ErrorCode { 103 | // Defined by JSON RPC: 104 | ParseError = -32700, 105 | InvalidRequest = -32600, 106 | MethodNotFound = -32601, 107 | InvalidParams = -32602, 108 | InternalError = -32603, 109 | ServerErrorStart = -32099, 110 | ServerErrorEnd = -32000, 111 | 112 | /// Error code indicating that a server received a notification or 113 | /// request before the server has received the `initialize` request. 114 | ServerNotInitialized = -32002, 115 | UnknownErrorCode = -32001, 116 | 117 | // Defined by the protocol: 118 | /// The client has canceled a request and a server has detected 119 | /// the cancel. 120 | RequestCanceled = -32800, 121 | 122 | /// The server detected that the content of a document got 123 | /// modified outside normal conditions. A server should 124 | /// NOT send this error code if it detects a content change 125 | /// in it unprocessed messages. The result even computed 126 | /// on an older state might still be useful for the client. 127 | /// 128 | /// If a client decides that a result is not of any use anymore 129 | /// the client should cancel the request. 130 | ContentModified = -32801, 131 | 132 | /// The server cancelled the request. This error code should 133 | /// only be used for requests that explicitly support being 134 | /// server cancellable. 135 | /// 136 | /// @since 3.17.0 137 | ServerCancelled = -32802, 138 | } 139 | 140 | #[derive(Debug, Serialize, Deserialize, Clone)] 141 | pub struct Notification { 142 | pub method: String, 143 | #[serde(default = "serde_json::Value::default")] 144 | #[serde(skip_serializing_if = "serde_json::Value::is_null")] 145 | pub params: serde_json::Value, 146 | } 147 | 148 | impl Message { 149 | pub fn read(r: &mut impl BufRead) -> io::Result> { 150 | Message::_read(r) 151 | } 152 | fn _read(r: &mut dyn BufRead) -> io::Result> { 153 | let text = match read_msg_text(r)? { 154 | None => return Ok(None), 155 | Some(text) => text, 156 | }; 157 | let msg = serde_json::from_str(&text)?; 158 | Ok(Some(msg)) 159 | } 160 | pub fn write(self, w: &mut impl Write) -> io::Result<()> { 161 | self._write(w) 162 | } 163 | fn _write(self, w: &mut dyn Write) -> io::Result<()> { 164 | #[derive(Serialize)] 165 | struct JsonRpc { 166 | jsonrpc: &'static str, 167 | #[serde(flatten)] 168 | msg: Message, 169 | } 170 | let text = serde_json::to_string(&JsonRpc { jsonrpc: "2.0", msg: self })?; 171 | write_msg_text(w, &text) 172 | } 173 | } 174 | 175 | impl Response { 176 | pub fn new_ok(id: RequestId, result: R) -> Response { 177 | Response { id, result: Some(serde_json::to_value(result).unwrap()), error: None } 178 | } 179 | pub fn new_err(id: RequestId, code: i32, message: String) -> Response { 180 | let error = ResponseError { code, message, data: None }; 181 | Response { id, result: None, error: Some(error) } 182 | } 183 | } 184 | 185 | impl Request { 186 | pub fn new(id: RequestId, method: String, params: P) -> Request { 187 | Request { id, method, params: serde_json::to_value(params).unwrap() } 188 | } 189 | pub fn extract( 190 | self, 191 | method: &str, 192 | ) -> Result<(RequestId, P), ExtractError> { 193 | if self.method == method { 194 | let params = serde_json::from_value(self.params) 195 | .map_err(|error| ExtractError::JsonError { method: self.method, error })?; 196 | Ok((self.id, params)) 197 | } else { 198 | Err(ExtractError::MethodMismatch(self)) 199 | } 200 | } 201 | 202 | pub(crate) fn is_shutdown(&self) -> bool { 203 | self.method == "shutdown" 204 | } 205 | pub(crate) fn is_initialize(&self) -> bool { 206 | self.method == "initialize" 207 | } 208 | } 209 | 210 | impl Notification { 211 | pub fn new(method: String, params: impl Serialize) -> Notification { 212 | Notification { method, params: serde_json::to_value(params).unwrap() } 213 | } 214 | pub fn extract( 215 | self, 216 | method: &str, 217 | ) -> Result> { 218 | if self.method == method { 219 | serde_json::from_value(self.params) 220 | .map_err(|error| ExtractError::JsonError { method: self.method, error }) 221 | } else { 222 | Err(ExtractError::MethodMismatch(self)) 223 | } 224 | } 225 | pub(crate) fn is_exit(&self) -> bool { 226 | self.method == "exit" 227 | } 228 | pub(crate) fn is_initialized(&self) -> bool { 229 | self.method == "initialized" 230 | } 231 | } 232 | 233 | fn read_msg_text(inp: &mut dyn BufRead) -> io::Result> { 234 | fn invalid_data(error: impl Into>) -> io::Error { 235 | io::Error::new(io::ErrorKind::InvalidData, error) 236 | } 237 | macro_rules! invalid_data { 238 | ($($tt:tt)*) => (invalid_data(format!($($tt)*))) 239 | } 240 | 241 | let mut size = None; 242 | let mut buf = String::new(); 243 | loop { 244 | buf.clear(); 245 | if inp.read_line(&mut buf)? == 0 { 246 | return Ok(None); 247 | } 248 | if !buf.ends_with("\r\n") { 249 | return Err(invalid_data!("malformed header: {:?}", buf)); 250 | } 251 | let buf = &buf[..buf.len() - 2]; 252 | if buf.is_empty() { 253 | break; 254 | } 255 | let mut parts = buf.splitn(2, ": "); 256 | let header_name = parts.next().unwrap(); 257 | let header_value = 258 | parts.next().ok_or_else(|| invalid_data!("malformed header: {:?}", buf))?; 259 | if header_name == "Content-Length" { 260 | size = Some(header_value.parse::().map_err(invalid_data)?); 261 | } 262 | } 263 | let size: usize = size.ok_or_else(|| invalid_data!("no Content-Length"))?; 264 | let mut buf = buf.into_bytes(); 265 | buf.resize(size, 0); 266 | inp.read_exact(&mut buf)?; 267 | let buf = String::from_utf8(buf).map_err(invalid_data)?; 268 | log::debug!("< {}", buf); 269 | Ok(Some(buf)) 270 | } 271 | 272 | fn write_msg_text(out: &mut dyn Write, msg: &str) -> io::Result<()> { 273 | log::debug!("> {}", msg); 274 | write!(out, "Content-Length: {}\r\n\r\n", msg.len())?; 275 | out.write_all(msg.as_bytes())?; 276 | out.flush()?; 277 | Ok(()) 278 | } 279 | 280 | #[cfg(test)] 281 | mod tests { 282 | use super::{Message, Notification, Request, RequestId}; 283 | 284 | #[test] 285 | fn shutdown_with_explicit_null() { 286 | let text = "{\"jsonrpc\": \"2.0\",\"id\": 3,\"method\": \"shutdown\", \"params\": null }"; 287 | let msg: Message = serde_json::from_str(text).unwrap(); 288 | 289 | assert!( 290 | matches!(msg, Message::Request(req) if req.id == 3.into() && req.method == "shutdown") 291 | ); 292 | } 293 | 294 | #[test] 295 | fn shutdown_with_no_params() { 296 | let text = "{\"jsonrpc\": \"2.0\",\"id\": 3,\"method\": \"shutdown\"}"; 297 | let msg: Message = serde_json::from_str(text).unwrap(); 298 | 299 | assert!( 300 | matches!(msg, Message::Request(req) if req.id == 3.into() && req.method == "shutdown") 301 | ); 302 | } 303 | 304 | #[test] 305 | fn notification_with_explicit_null() { 306 | let text = "{\"jsonrpc\": \"2.0\",\"method\": \"exit\", \"params\": null }"; 307 | let msg: Message = serde_json::from_str(text).unwrap(); 308 | 309 | assert!(matches!(msg, Message::Notification(not) if not.method == "exit")); 310 | } 311 | 312 | #[test] 313 | fn notification_with_no_params() { 314 | let text = "{\"jsonrpc\": \"2.0\",\"method\": \"exit\"}"; 315 | let msg: Message = serde_json::from_str(text).unwrap(); 316 | 317 | assert!(matches!(msg, Message::Notification(not) if not.method == "exit")); 318 | } 319 | 320 | #[test] 321 | fn serialize_request_with_null_params() { 322 | let msg = Message::Request(Request { 323 | id: RequestId::from(3), 324 | method: "shutdown".into(), 325 | params: serde_json::Value::Null, 326 | }); 327 | let serialized = serde_json::to_string(&msg).unwrap(); 328 | 329 | assert_eq!("{\"id\":3,\"method\":\"shutdown\"}", serialized); 330 | } 331 | 332 | #[test] 333 | fn serialize_notification_with_null_params() { 334 | let msg = Message::Notification(Notification { 335 | method: "exit".into(), 336 | params: serde_json::Value::Null, 337 | }); 338 | let serialized = serde_json::to_string(&msg).unwrap(); 339 | 340 | assert_eq!("{\"method\":\"exit\"}", serialized); 341 | } 342 | } 343 | -------------------------------------------------------------------------------- /src/req_queue.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | 3 | use serde::Serialize; 4 | 5 | use crate::{ErrorCode, Request, RequestId, Response, ResponseError}; 6 | 7 | /// Manages the set of pending requests, both incomming and outgoing. 8 | #[derive(Debug)] 9 | pub struct ReqQueue { 10 | pub incoming: Incoming, 11 | pub outgoing: Outgoing, 12 | } 13 | 14 | impl Default for ReqQueue { 15 | fn default() -> ReqQueue { 16 | ReqQueue { 17 | incoming: Incoming { pending: HashMap::default() }, 18 | outgoing: Outgoing { next_id: 0, pending: HashMap::default() }, 19 | } 20 | } 21 | } 22 | 23 | #[derive(Debug)] 24 | pub struct Incoming { 25 | pending: HashMap, 26 | } 27 | 28 | #[derive(Debug)] 29 | pub struct Outgoing { 30 | next_id: i32, 31 | pending: HashMap, 32 | } 33 | 34 | impl Incoming { 35 | pub fn register(&mut self, id: RequestId, data: I) { 36 | self.pending.insert(id, data); 37 | } 38 | pub fn cancel(&mut self, id: RequestId) -> Option { 39 | let _data = self.complete(id.clone())?; 40 | let error = ResponseError { 41 | code: ErrorCode::RequestCanceled as i32, 42 | message: "canceled by client".to_string(), 43 | data: None, 44 | }; 45 | Some(Response { id, result: None, error: Some(error) }) 46 | } 47 | pub fn complete(&mut self, id: RequestId) -> Option { 48 | self.pending.remove(&id) 49 | } 50 | } 51 | 52 | impl Outgoing { 53 | pub fn register(&mut self, method: String, params: P, data: O) -> Request { 54 | let id = RequestId::from(self.next_id); 55 | self.pending.insert(id.clone(), data); 56 | self.next_id += 1; 57 | Request::new(id, method, params) 58 | } 59 | pub fn complete(&mut self, id: RequestId) -> Option { 60 | self.pending.remove(&id) 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/socket.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | io::{self, BufReader}, 3 | net::TcpStream, 4 | thread, 5 | }; 6 | 7 | use crossbeam_channel::{bounded, Receiver, Sender}; 8 | 9 | use crate::{ 10 | stdio::{make_io_threads, IoThreads}, 11 | Message, 12 | }; 13 | 14 | pub(crate) fn socket_transport( 15 | stream: TcpStream, 16 | ) -> (Sender, Receiver, IoThreads) { 17 | let (reader_receiver, reader) = make_reader(stream.try_clone().unwrap()); 18 | let (writer_sender, writer) = make_write(stream.try_clone().unwrap()); 19 | let io_threads = make_io_threads(reader, writer); 20 | (writer_sender, reader_receiver, io_threads) 21 | } 22 | 23 | fn make_reader(stream: TcpStream) -> (Receiver, thread::JoinHandle>) { 24 | let (reader_sender, reader_receiver) = bounded::(0); 25 | let reader = thread::spawn(move || { 26 | let mut buf_read = BufReader::new(stream); 27 | while let Some(msg) = Message::read(&mut buf_read).unwrap() { 28 | let is_exit = matches!(&msg, Message::Notification(n) if n.is_exit()); 29 | reader_sender.send(msg).unwrap(); 30 | if is_exit { 31 | break; 32 | } 33 | } 34 | Ok(()) 35 | }); 36 | (reader_receiver, reader) 37 | } 38 | 39 | fn make_write(mut stream: TcpStream) -> (Sender, thread::JoinHandle>) { 40 | let (writer_sender, writer_receiver) = bounded::(0); 41 | let writer = thread::spawn(move || { 42 | writer_receiver.into_iter().try_for_each(|it| it.write(&mut stream)).unwrap(); 43 | Ok(()) 44 | }); 45 | (writer_sender, writer) 46 | } 47 | -------------------------------------------------------------------------------- /src/stdio.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | io::{self, stdin, stdout}, 3 | thread, 4 | }; 5 | 6 | use crossbeam_channel::{bounded, Receiver, Sender}; 7 | 8 | use crate::Message; 9 | 10 | /// Creates an LSP connection via stdio. 11 | pub(crate) fn stdio_transport() -> (Sender, Receiver, IoThreads) { 12 | let (writer_sender, writer_receiver) = bounded::(0); 13 | let writer = thread::spawn(move || { 14 | let stdout = stdout(); 15 | let mut stdout = stdout.lock(); 16 | writer_receiver.into_iter().try_for_each(|it| it.write(&mut stdout))?; 17 | Ok(()) 18 | }); 19 | let (reader_sender, reader_receiver) = bounded::(0); 20 | let reader = thread::spawn(move || { 21 | let stdin = stdin(); 22 | let mut stdin = stdin.lock(); 23 | while let Some(msg) = Message::read(&mut stdin)? { 24 | let is_exit = match &msg { 25 | Message::Notification(n) => n.is_exit(), 26 | _ => false, 27 | }; 28 | 29 | reader_sender.send(msg).unwrap(); 30 | 31 | if is_exit { 32 | break; 33 | } 34 | } 35 | Ok(()) 36 | }); 37 | let threads = IoThreads { reader, writer }; 38 | (writer_sender, reader_receiver, threads) 39 | } 40 | 41 | // Creates an IoThreads 42 | pub(crate) fn make_io_threads( 43 | reader: thread::JoinHandle>, 44 | writer: thread::JoinHandle>, 45 | ) -> IoThreads { 46 | IoThreads { reader, writer } 47 | } 48 | 49 | pub struct IoThreads { 50 | reader: thread::JoinHandle>, 51 | writer: thread::JoinHandle>, 52 | } 53 | 54 | impl IoThreads { 55 | pub fn join(self) -> io::Result<()> { 56 | match self.reader.join() { 57 | Ok(r) => r?, 58 | Err(err) => { 59 | println!("reader panicked!"); 60 | std::panic::panic_any(err) 61 | } 62 | } 63 | match self.writer.join() { 64 | Ok(r) => r, 65 | Err(err) => { 66 | println!("writer panicked!"); 67 | std::panic::panic_any(err); 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /xtask/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "xtask" 3 | version = "0.0.0" 4 | publish = false 5 | authors = ["Aleksey Kladov "] 6 | edition = "2018" 7 | 8 | [dependencies] 9 | xaction = "0.2" 10 | -------------------------------------------------------------------------------- /xtask/src/main.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | 3 | use xaction::{cargo_toml, cmd, git, section, Result}; 4 | 5 | fn main() { 6 | if let Err(err) = try_main() { 7 | eprintln!("error: {}", err); 8 | std::process::exit(1) 9 | } 10 | } 11 | 12 | fn try_main() -> Result<()> { 13 | let subcommand = std::env::args().nth(1); 14 | match subcommand { 15 | Some(it) if it == "ci" => (), 16 | _ => { 17 | print_usage(); 18 | Err("invalid arguments")? 19 | } 20 | } 21 | 22 | let cargo_toml = cargo_toml()?; 23 | 24 | { 25 | let _s = section("BUILD"); 26 | cmd!("cargo test --workspace --no-run").run()?; 27 | } 28 | 29 | { 30 | let _s = section("TEST"); 31 | cmd!("cargo test --workspace -- --nocapture").run()?; 32 | } 33 | 34 | let version = cargo_toml.version()?; 35 | let tag = format!("v{}", version); 36 | let dry_run = env::var("CI").is_err() 37 | || git::tag_list()?.contains(&tag) 38 | || git::current_branch()? != "master"; 39 | xaction::set_dry_run(dry_run); 40 | 41 | { 42 | let _s = section("PUBLISH"); 43 | cargo_toml.publish()?; 44 | git::tag(&tag)?; 45 | git::push_tags()?; 46 | } 47 | Ok(()) 48 | } 49 | 50 | fn print_usage() { 51 | eprintln!( 52 | "\ 53 | Usage: cargo run -p xtask 54 | 55 | SUBCOMMANDS: 56 | ci 57 | " 58 | ) 59 | } 60 | -------------------------------------------------------------------------------- /xtask/tests/tidy.rs: -------------------------------------------------------------------------------- 1 | use xaction::cmd; 2 | 3 | #[test] 4 | fn test_formatting() { 5 | cmd!("cargo fmt --all -- --check").run().unwrap() 6 | } 7 | --------------------------------------------------------------------------------