Skip to content

Instantly share code, notes, and snippets.

@datsfilipe
Created September 7, 2023 06:52
Show Gist options
  • Save datsfilipe/28efd04b6a5b6cab590ce9f4f6c76c48 to your computer and use it in GitHub Desktop.
Save datsfilipe/28efd04b6a5b6cab590ce9f4f6c76c48 to your computer and use it in GitHub Desktop.
Only use prettierd with `formatter.nvim` if a prettier config file is found.
local ok, formatter = pcall(require, "formatter")
if not ok then
return
end
local util = require "formatter.util"
local find_git_ancestor = function ()
local path = util.get_current_buffer_file_path()
local root = path
while root ~= "/" do
local git_dir = root .. "/.git"
local fd = vim.loop.fs_opendir(git_dir)
if fd then
vim.loop.fs_closedir(fd)
return root
end
root = vim.fn.fnamemodify(root, ":h")
end
end
local prettierd = function()
local root = find_git_ancestor()
local possible_filenames = {
".prettierrc",
".prettierrc.json",
".prettierrc.json5",
".prettierrc.yaml",
".prettierrc.yml",
".prettierrc.js",
".prettier.config.js",
".prettierc.mjs",
".prettier.config.mjs",
".prettierrc.cjs",
".prettier.config.cjs"
}
for _, filename in ipairs(possible_filenames) do
local prettier_config = root .. "/" .. filename
local fd = vim.loop.fs_open(prettier_config, "r", 438)
if fd then
vim.loop.fs_close(fd)
return {
exe = "prettierd",
args = { "--stdin-filepath", vim.api.nvim_buf_get_name(0) },
stdin = true,
}
end
end
return nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment