Files
vern-nvim/lua/vern-nvim/langs/python.lua
T

139 lines
3.3 KiB
Lua

---@module "vern-nvim.core.fs"
local fs = require("vern-nvim.core.fs")
---@module "vern-nvim.core.terminal"
local term = require("vern-nvim.core.terminal")
local M = {}
M.attach = function()
local root = fs.root()
if not root then return end
local venv_dir = nil
if vim.uv.fs_stat(root .. "/venv/bin/python") then
venv_dir = root .. "/venv"
elseif vim.uv.fs_stat(root .. "/.venv/bin/python") then
venv_dir = root .. "/.venv"
end
if venv_dir then
vim.env.VIRTUAL_ENV = venv_dir
vim.env.PATH = venv_dir .. "/bin:" .. vim.env.PATH
end
end
---@param root string
M.create_project = function(root)
local obj = vim.system({ "python3", "-m", "venv", root .. "/venv" }):wait()
if obj.code ~= 0 then
vim.notify(
"Virtual environment failed to initialize " .. obj.stderr,
vim.log.levels.ERROR,
{ title = "Vern Python" }
)
end
end
---@type VernCreateFile
M.create_file = nil
---@param opts VernPythonConfig Takes a table for the runtime
M.run = function(opts)
opts = opts or {}
local root = fs.root()
local context = {
project_name = fs.name(),
company_name = opts.env.author,
file_name = "",
}
local bin = vim.tbl_get(opts.python.templates.project.primary)
local exe = vim.fs.joinpath(bin.path, bin.name)
local exe_path = fs.fmt_path(exe, opts.python.dirs, context)
local full_path = vim.fs.joinpath(vim.fn.expand(root), exe_path)
term.open({ "python3 " .. full_path }, opts.terminal or {}, false)
end
M.pip_install = function()
vim.ui.input({ prompt = "Enter pip module: " }, function(mod)
mod = mod and vim.trim(mod)
if not mod or mod == "" then
vim.notify(
"Pip Cancelled",
vim.log.levels.WARN,
{ title = "Vern Python" }
)
return
end
vim.notify(
"Installing " .. mod,
vim.log.levels.INFO,
{ title = "Vern Python" }
)
vim.system({ "pip", "install", mod }, { text = true }, function(obj)
vim.schedule(function()
if obj.code ~= 0 then
vim.notify(
"Pip failed: " .. obj.stderr,
vim.log.levels.WARN,
{ title = "Vern Python" }
)
else
vim.notify(
"Pip installed " .. mod,
vim.log.levels.INFO,
{ title = "Vern Python" }
)
end
end)
end)
end)
end
---@type VernLanguageConfig
M.python = {
root = "Python",
dirs = {
src = "src/{project_name}",
},
keybinds = {
["<leader>pi"] = {
user_command = "VernPythonPip",
desc = "Install python packages for environment",
action = M.pip_install,
},
},
templates = {
project = {
primary = {
path = "{dirs.src}",
name = "main.py",
kind = "main",
kind_path = "vern-nvim.templates.python",
},
manifest = {
path = ".",
name = "pyproject.toml",
kind = "pyproject",
kind_path = "vern-nvim.templates.python",
},
pkg_init = {
path = "{dirs.src}",
name = "__init__.py",
kind = "__init__",
kind_path = "vern-nvim.templates.python",
},
},
file = {
source = {
path = "{dirs.src}",
name = "{file_name}.py",
kind = "module",
kind_path = "vern-nvim.templates.python",
},
},
extras = nil,
},
}
return M