Files
nvim/lua/projects.lua
T
2026-07-09 16:43:59 +01:00

80 lines
2.4 KiB
Lua

-- Project specific settings
local M = {}
-- Helper to create mappings
local helpers = require 'helpers'
local map = helpers.map
local function relevant_directory_from_cwd(cwd)
local basename = vim.fn.fnamemodify(cwd, ':t')
local nested_folder_names = { 'server', 'frontend', 'frontend2', 'client', 'backend' }
if vim.tbl_contains(nested_folder_names, basename) then
local parent = vim.fn.fnamemodify(cwd, ':h')
return relevant_directory_from_cwd(parent)
end
return cwd
end
-- Get the last folder name from a path
local function project_name_from_dir(dir)
return vim.fn.fnamemodify(dir, ':t')
end
local last_applied = nil
function M.apply(cwd)
local dir = relevant_directory_from_cwd(cwd or vim.fn.getcwd())
local name = project_name_from_dir(dir)
if last_applied == name then
return
end
last_applied = name
-- Check if project lua file exists in nvim config path
if vim.fn.filereadable(vim.fn.stdpath 'config' .. '/lua/projects/' .. name .. '.lua') == 1 then
local setup = require('projects.' .. name)
helpers.edit_cf('w', '/lua/projects/' .. name .. '.lua')
setup(dir)
vim.notify(('Project config loaded: %s'):format(name), vim.log.levels.INFO, { title = 'projects.lua' })
-- Source the project file to apply any new settings
vim.api.nvim_create_autocmd({ 'BufWritePost' }, {
pattern = { vim.fn.stdpath 'config' .. '/lua/projects/' .. name .. '.lua' },
callback = function()
package.loaded['projects.' .. name] = nil
local setup = require('projects.' .. name)
setup(dir)
vim.notify(('Project config reloaded: %s'):format(name), vim.log.levels.INFO, { title = 'projects.lua' })
end,
})
end
end
-- Apply on startup and when the working directory changes
do
local grp = vim.api.nvim_create_augroup('ProjectConfig', { clear = true })
vim.api.nvim_create_autocmd('VimEnter', {
group = grp,
callback = function()
M.apply()
end,
})
vim.api.nvim_create_autocmd('DirChanged', {
group = grp,
callback = function(args)
-- args.file is the new cwd for DirChanged
M.apply(args and args.file or nil)
end,
})
end
-- Optional command to manually re-apply
vim.api.nvim_create_user_command('ProjectReload', function()
last_applied = nil
M.apply()
end, {})