Skip to content

Commit

Permalink
chore: update readme, timeout layer
Browse files Browse the repository at this point in the history
  • Loading branch information
Desdaemon committed Mar 28, 2024
1 parent 4f43c62 commit a48be9e
Show file tree
Hide file tree
Showing 8 changed files with 116 additions and 39 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ globwalk = "0.8.1"
miette = { version = "5.10.0", features = ["fancy"] }
futures = "0.3.28"
xmlparser = "0.13.5"
tower = "0.4.13"
tower = { version = "0.4.13", features = ["timeout"] }
pin-project-lite = "0.2.12"
tree-sitter.workspace = true
tree-sitter-python = "0.20.4"
Expand Down
33 changes: 24 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,11 @@ language-servers = [

### Neovim via [lsp-zero.nvim]

Instructions copied from [lsp-zero docs](https://lsp-zero.netlify.app/v3.x/language-server-configuration.html#custom-servers)

1. Ensure that you have `odoo-lsp` on your path
2. Configure your Neovim (Lua) configuration file e.g. at `~/.config/nvim/init.lua` to use [lsp-zero.nvim],
adding odoo-lsp as a new server using `lsp.new_server` before calling `lsp.setup()`:
adding odoo-lsp as a new server before calling `lsp.setup()`:

```lua
-- lsp-zero stanza
Expand All @@ -102,15 +104,28 @@ lsp.on_attach(function(client, bufnr)
lsp.default_keymaps({buffer = bufnr})
end)

local lspconfigs = require 'lspconfig.configs'

-- define our custom language server here
lsp.new_server({
name = 'odoo-lsp',
cmd = {'odoo-lsp'},
filetypes = {'javascript', 'xml', 'python'},
root_dir = function()
return lsp.dir.find_first({'.odoo_lsp', '.odoo_lsp.json', '.git'})
end,
})
lspconfigs.odoo_lsp = {
default_config = {
name = 'odoo-lsp',
cmd = {'odoo-lsp'},
filetypes = {'javascript', 'xml', 'python'},
root_dir = require('lspconfig.util').root_pattern('.odoo_lsp', '.odoo_lsp.json', '.git')
}
}

local configured_lsps = {
odoo_lsp = {},
-- optional but recommended, requires pyright-langserver on path
pyright = {},
}

local lspconfig = require 'lspconfig'
for name, config in pairs(configured_lsps) do
lspconfig[name].setup(config)
end

-- LSP setup done
lsp.setup()
Expand Down
46 changes: 31 additions & 15 deletions examples/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -37,27 +37,43 @@ lsp.on_attach(function(client, bufnr)
lsp.default_keymaps({buffer = bufnr})
end)

-- define our custom LSP here
lsp.new_server({
name = 'odoo-lsp',
cmd = {'odoo-lsp'},
filetypes = {'javascript', 'xml', 'python'},
root_dir = function()
return lsp.dir.find_first({'.odoo_lsp', '.odoo_lsp.json', '.git'})
end,
})
local lspconfigs = require 'lspconfig.configs'

-- define our custom language server here
lspconfigs.odoo_lsp = {
default_config = {
name = 'odoo-lsp',
cmd = {'odoo-lsp'},
filetypes = {'javascript', 'xml', 'python'},
root_dir = require('lspconfig.util').root_pattern('.odoo_lsp', '.odoo_lsp.json', '.git')
}
}

-- LSP setup done
lsp.setup()
local configured_lsps = {
odoo_lsp = {},
-- optional but recommended, requires pyright-langserver on path
-- see https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#pyright
-- pyright = {},
-- optional, this is the same LSP used by VSCode for XML
-- see https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#lemminx
-- lemminx = {},
-- optional, use `odoo-lsp tsconfig` to generate a tsconfig.json
-- see https://github.com/neovim/nvim-lspconfig/blob/master/doc/server_configurations.md#tsserver
-- tsserver = {},
}

local lspconfig = require 'lspconfig'
for name, config in pairs(configured_lsps) do
lspconfig[name].setup(config)
end

-- setup tab-completion
local cmp = require('cmp')
local cmp_action = require('lsp-zero').cmp_action()
cmp.setup({
require('cmp').setup {
mapping = {
['<Tab>'] = cmp_action.luasnip_supertab(),
['<S-Tab>'] = cmp_action.luasnip_shift_supertab(),
}
})
}

-- vim:ts=2:sw=2
-- vim:ts=2:sw=2
5 changes: 4 additions & 1 deletion src/index/common_names.txt
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,7 @@ res.currency
res.company
account.report
ir.attachment
res.groups
res.groups
inherit_id
parent_id
action
15 changes: 14 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::Relaxed;
use std::time::Duration;

use catch_panic::CatchPanic;
use dashmap::{DashMap, DashSet};
Expand Down Expand Up @@ -721,12 +722,21 @@ impl LanguageServer for Backend {

#[tokio::main]
async fn main() {
let outlog = std::env::var("ODOO_LSP_LOG").ok().map(|var| {
let path = match var.as_str() {
#[cfg(unix)]
"1" => Path::new("/tmp/odoo_lsp.log"),
_ => Path::new(&var),
};
std::fs::File::create(path).unwrap()
});
env_logger::Builder::new()
.filter_level(log::LevelFilter::Off)
.format_timestamp(None)
.format_indent(Some(2))
.format_target(true)
.format_module_path(cfg!(debug_assertions))
.target(env_logger::Target::Pipe(Box::new(FileTee::new(outlog))))
.parse_default_env()
.init();

Expand Down Expand Up @@ -780,6 +790,9 @@ async fn main() {
})
.finish();

let service = ServiceBuilder::new().layer_fn(CatchPanic).service(service);
let service = ServiceBuilder::new()
.layer_fn(CatchPanic)
.layer(tower::timeout::TimeoutLayer::new(Duration::from_secs(15)))
.service(service);
Server::new(stdin, stdout, socket).serve(service).await;
}
30 changes: 30 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use core::ops::{Add, Sub};
use std::borrow::Cow;
use std::fmt::Display;
use std::fs::File;
use std::io::BufWriter;
use std::sync::atomic::{AtomicBool, Ordering};

use dashmap::try_result::TryResult;
Expand Down Expand Up @@ -425,3 +427,31 @@ impl DisplayExt for std::fmt::Arguments<'_> {
Adapter(self)
}
}

pub struct FileTee {
file: Option<BufWriter<File>>,
}

impl FileTee {
pub fn new(file: Option<File>) -> Self {
Self {
file: file.map(BufWriter::new),
}
}
}

impl std::io::Write for FileTee {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if let Some(file) = &mut self.file {
_ = file.write(buf);
}
std::io::stderr().write(buf)
}
fn flush(&mut self) -> std::io::Result<()> {
if let Some(file) = &mut self.file {
file.flush()?;
}

Ok(())
}
}
23 changes: 11 additions & 12 deletions src/xml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::cmp::Ordering;
use std::path::Path;
use std::sync::Arc;

use lasso::{Spur, ThreadedRodeo};
use lasso::Spur;
use log::{debug, warn};
use miette::diagnostic;
use odoo_lsp::index::{interner, PathSymbol};
Expand All @@ -21,7 +21,7 @@ use odoo_lsp::{some, utils::*};
#[derive(Debug)]
enum RefKind<'a> {
/// `<field name=bar ref=".."/>`
Ref(Spur),
Ref(&'a str),
Model,
Id,
FieldName,
Expand Down Expand Up @@ -205,7 +205,7 @@ impl Backend {
ref_kind,
model_filter,
..
} = gather_refs(offset_at_cursor, &mut reader, interner(), &slice)?;
} = gather_refs(offset_at_cursor, &mut reader, &slice)?;
let (Some((value, value_range)), Some(record_field)) = (ref_at_cursor, ref_kind) else {
return Ok(None);
};
Expand All @@ -217,6 +217,7 @@ impl Backend {
let model = some!(interner().get(&model_key));
let fields = some!(self.index.models.populate_field_names(model.into(), &[]));
let fields = some!(fields.fields.as_ref());
let relation = some!(interner().get(relation));
let Some(Field {
kind: FieldKind::Relational(relation),
..
Expand Down Expand Up @@ -279,7 +280,7 @@ impl Backend {
ref_kind,
model_filter,
..
} = gather_refs(cursor_by_char, &mut reader, interner(), &slice)?;
} = gather_refs(cursor_by_char, &mut reader, &slice)?;

let Some((cursor_value, _)) = ref_at_cursor else {
return Ok(None);
Expand Down Expand Up @@ -309,7 +310,7 @@ impl Backend {
ref_at_cursor: cursor_value,
ref_kind,
..
} = gather_refs(cursor_by_char, &mut reader, interner(), &slice)?;
} = gather_refs(cursor_by_char, &mut reader, &slice)?;

let Some((cursor_value, _)) = cursor_value else {
return Ok(None);
Expand Down Expand Up @@ -338,7 +339,7 @@ impl Backend {
ref_at_cursor,
ref_kind,
model_filter,
} = gather_refs(offset_at_cursor, &mut reader, interner(), &slice)?;
} = gather_refs(offset_at_cursor, &mut reader, &slice)?;

let Some((ref_at_cursor, ref_range)) = ref_at_cursor else {
return Ok(None);
Expand Down Expand Up @@ -446,7 +447,6 @@ fn determine_csv_xmlid_subgroup<'text>(
fn gather_refs<'read>(
offset_at_cursor: ByteOffset,
reader: &mut Tokenizer<'read>,
interner: &ThreadedRodeo,
slice: &'read RopeSlice<'read>,
) -> miette::Result<XmlRefs<'read>> {
let mut tag = None;
Expand Down Expand Up @@ -500,8 +500,7 @@ fn gather_refs<'read>(
arch_mode = true;
arch_depth = depth
} else if local.as_str() == "name" {
let relation = interner.get_or_intern(value.as_str());
ref_kind = Some(RefKind::Ref(relation));
ref_kind = Some(RefKind::Ref(value.as_str()));
} else if local.as_str() == "groups" && value_in_range {
ref_kind = Some(RefKind::Id);
model_filter = Some("res.groups".to_string());
Expand All @@ -516,7 +515,7 @@ fn gather_refs<'read>(
&& matches!(local.as_str(), "inherit_id" | "t-call") =>
{
ref_at_cursor = Some((value.as_str(), value.range()));
ref_kind = Some(RefKind::Ref(interner.get_or_intern_static("inherit_id")));
ref_kind = Some(RefKind::Ref("inherit_id"));
}
// <record model=.. />
Ok(Token::Attribute { local, value, .. })
Expand Down Expand Up @@ -553,12 +552,12 @@ fn gather_refs<'read>(
match local.as_str() {
"parent" => {
ref_at_cursor = Some((value.as_str(), value.range()));
ref_kind = Some(RefKind::Ref(interner.get_or_intern_static("parent_id")));
ref_kind = Some(RefKind::Ref("parent_id"));
model_filter = Some("ir.ui.menu".to_string());
}
"action" => {
ref_at_cursor = Some((value.as_str(), value.range()));
ref_kind = Some(RefKind::Ref(interner.get_or_intern_static("action")));
ref_kind = Some(RefKind::Ref("action"));
model_filter = Some("ir.ui.menu".to_string());
}
"groups" => {
Expand Down

0 comments on commit a48be9e

Please sign in to comment.