From 29884f0e0ca8c4e53940c5d81dafa14c44389044 Mon Sep 17 00:00:00 2001 From: pro100ton Date: Sun, 2 Feb 2025 15:54:21 +0300 Subject: [PATCH 1/3] Update binding for snippets and refactor python version getter --- lua/custom/README.md | 59 ++++++++++++++++++++++++++++++++++++++++++ lua/custom/lsp.lua | 38 ++++++++++++++++++++++++--- lua/custom/luasnip.lua | 4 +-- plugin/options.lua | 8 +++--- 4 files changed, 100 insertions(+), 9 deletions(-) create mode 100644 lua/custom/README.md diff --git a/lua/custom/README.md b/lua/custom/README.md new file mode 100644 index 0000000..d725dd7 --- /dev/null +++ b/lua/custom/README.md @@ -0,0 +1,59 @@ +# Справка по интересным моментам в коде +## Функция получения версии `python` в `lsp.lua` + +```lua +local function get_python_version() + local handle = io.popen("python --version 2>&1") -- Redirect stderr to stdout + if handle then + local result = handle:read("*a") + handle:close() + -- Check if the output contains a version number + local version = result:match("Python (%d+%.%d+%.%d+)") + if version then + return version + end + end + + handle = io.popen("python3 --version 2>&1") -- Redirect stderr to stdout + if handle then + local result = handle:read("*a") + handle:close() + -- Check if the output contains a version number + local version = result:match("Python (%d+%.%d+%.%d+)") + if version then + return version + end + end + -- TODO: Add some exception handling if python not installed on user machine + return "Python 0.0.0" +end +``` +Что тут есть примечательного: +- Получение данных, выполняя команду в shell оболочке системы с помощью + `io.popen`. *Важно*: Данная функция может работать не во всех ОС +- Функция выполняет команду, указанную в аргументе, и возвращает *файловый + дескриптор*, который можно использовать для чтения вывода команды (или + записи в нее) + +Разберем флоу подробнее: +Если про `python --version` - все понятно, то вот: +```lua +2>&1 +``` +Уже надо прояснить: +- В UNIX-подобных системах есть три стандартных потока - `stdin` = 0; `stdout` = 1; + `strerr` = 2; +- По умолчанию `io.popen` передает только вывод `stdout` в handle, поэтому для обработки +ошибок, надо дополнительно захватывать поток `stderr` +- `2>&1` означает, что мы хотим перенаправить поток ошибок 2 в стандартный вывод 1; +- Это нужно для того, чтобы захватить не только вывод команды, но и возможные ошибки +(например если питон не установлен); +- `>&` - оператор перенаправления потоков. + +Дополнительно: +`*a` внутри `read` - конструкция формата чтения файловых объектов в `Lua`. Они +указывают - как именно стоит читать данные из файла или потока. Помимо `a` есть +еще: +- `*a` - читать все содержимое +- `*l` - читать строку +- `*n` - читать число. diff --git a/lua/custom/lsp.lua b/lua/custom/lsp.lua index c04577a..00ccedc 100644 --- a/lua/custom/lsp.lua +++ b/lua/custom/lsp.lua @@ -92,13 +92,43 @@ local ensure_installed = { "prettier", } +local function get_python_version() + local handle = io.popen("python --version 2>&1") -- Redirect stderr to stdout + if handle then + local result = handle:read("*a") + handle:close() + -- Check if the output contains a version number + local version = result:match("Python (%d+%.%d+%.%d+)") + if version then + return version + end + end + + handle = io.popen("python3 --version 2>&1") -- Redirect stderr to stdout + if handle then + local result = handle:read("*a") + handle:close() + -- Check if the output contains a version number + local version = result:match("Python (%d+%.%d+%.%d+)") + if version then + return version + end + end + -- TODO: Add some exception handling if python not installed on user machine + return "Python 0.0.0" +end + -- Now we need to make things work in Astra --- Main Astra cockblock - low python version, that prevents installation of --- some modules, so in order to prevent mason from whining - disable some +-- Main Astra cockblock - low python version, that prevents installation of +-- some modules, so in order to prevent mason from whining - disable some -- autoinstall modules depending on currently installed python version -- NOTE: You must install removed dependencies manually -local python_version = io.popen("python --version"):read("*a") -local _, minor, _ = python_version:match("Python (%d+)%.(%d+)%.(%d+)") +local python_version = get_python_version() +print(python_version) +if python_version == nil then + python_version = "Python 3.13" +end +local _, minor, _ = python_version:match(".*(%d+)%.(%d+)%.(%d+)") if tonumber(minor) < 8 then for i, k in pairs(servers_to_install) do -- Ruff is not supported for python lower than 3.8 diff --git a/lua/custom/luasnip.lua b/lua/custom/luasnip.lua index 2c6820f..9b98678 100644 --- a/lua/custom/luasnip.lua +++ b/lua/custom/luasnip.lua @@ -8,13 +8,13 @@ ls.config.set_config { store_selection_keys = "", } -vim.keymap.set({ "i", "s" }, "", function() +vim.keymap.set({ "i", "s" }, "", function() if ls.expand_or_jumpable() then ls.expand_or_jump() end end, { silent = true }) -vim.keymap.set({ "i", "s" }, "", function() +vim.keymap.set({ "i", "s" }, "", function() if ls.jumpable() then ls.jump(-1) end diff --git a/plugin/options.lua b/plugin/options.lua index 36a9696..f0e1dae 100644 --- a/plugin/options.lua +++ b/plugin/options.lua @@ -3,7 +3,7 @@ local opt = vim.opt -- Command to show inline what are you trying to perform opt.inccommand = "split" --- Search settings to toggle "smart case" search only if 1+ uppercase char +-- Search settings to toggle "smart case" search only if 1+ uppercase char -- persist in search line opt.smartcase = true opt.ignorecase = true @@ -13,8 +13,8 @@ opt.number = true opt.relativenumber = true -- Tabulation and indentation settings -opt.shiftwidth = 2 -- Set spaces for tabs == 2 -opt.tabstop = 2 -- Set spaces for indent with == 2 +opt.shiftwidth = 2 -- Set spaces for tabs == 2 +opt.tabstop = 2 -- Set spaces for indent with == 2 opt.expandtab = true -- use number of spaces to insert a opt.softtabstop = 2 @@ -24,3 +24,5 @@ opt.swapfile = false -- Add line at 80 symbols opt.colorcolumn = "80" +-- config to set up clipboard as default register +opt.clipboard:append("unnamedplus") From 88b0c1ffc2098ea55bb9fa6fa444c37c35e9811d Mon Sep 17 00:00:00 2001 From: pro100ton Date: Sun, 2 Feb 2025 15:58:28 +0300 Subject: [PATCH 2/3] Add python snippet for creating sqlalchemy table --- lua/custom/snippets/python.lua | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/lua/custom/snippets/python.lua b/lua/custom/snippets/python.lua index 8540877..88fcb42 100644 --- a/lua/custom/snippets/python.lua +++ b/lua/custom/snippets/python.lua @@ -14,6 +14,24 @@ local fmta = require("luasnip.extras.fmt").fmta local rep = require("luasnip.extras").rep ls.add_snippets("python", { + s( + { trig = "ctable", dscr = "Create method or function with test stub" }, + fmt( + [[ + {} = Table( + "{}", + metadata_obj, + Column("id", Integer, primary_key=True), + {} + ) + ]], + { + i(1), + rep(1), + i(0) + } + ) + ), s({ trig = "cmethod", dscr = "Create method or function with test stub" }, fmta( [[ From 3af760037900991f2f056e12889197608b3fa35e Mon Sep 17 00:00:00 2001 From: pro100ton Date: Sun, 2 Feb 2025 18:05:53 +0300 Subject: [PATCH 3/3] Remove prints --- ftplugin/go.lua | 1 - lua/custom/lsp.lua | 1 - 2 files changed, 2 deletions(-) diff --git a/ftplugin/go.lua b/ftplugin/go.lua index 1473193..e69de29 100644 --- a/ftplugin/go.lua +++ b/ftplugin/go.lua @@ -1 +0,0 @@ -print("Hello from golang file") diff --git a/lua/custom/lsp.lua b/lua/custom/lsp.lua index 00ccedc..8b4dc8b 100644 --- a/lua/custom/lsp.lua +++ b/lua/custom/lsp.lua @@ -124,7 +124,6 @@ end -- autoinstall modules depending on currently installed python version -- NOTE: You must install removed dependencies manually local python_version = get_python_version() -print(python_version) if python_version == nil then python_version = "Python 3.13" end