local bin_name = "rust-analyzer"
local cmd = { bin_name }

local config = vim.fs.find("Cargo.toml", {
  upward = true,
  stop = vim.loop.os_homedir(),
  path = vim.fs.dirname(vim.api.nvim_buf_get_name(0)),
})

if next(config) then
  vim.api.nvim_create_autocmd("FileType", {
    pattern = "rust",
    callback = function()
      vim.lsp.start({
        name = "rust-analyzer",
        cmd = cmd,
        root_dir = config[1],
        settings = {
          ["rust-analyzer"] = {
            checkOnSave = {
              command = "clippy"
            },
            check = {
              command = "check"
            },
          },
        },
        capabilities = vim.lsp.protocol.make_client_capabilities(),
      })
    end,
  })

  vim.api.nvim_create_autocmd("BufWritePre", {
    pattern = "*.rs",
    callback = function()
      vim.lsp.buf.format({ timeout_ms = 2000 })
    end,
  })
end
