aboutsummaryrefslogtreecommitdiffstats
path: root/lua/config/worktree.lua
blob: dd4e8377ecef2da92302848255ccb4b887a68ce5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
-- Git worktrees nativos vía `git` + vim.ui (reemplaza ThePrimeagen/git-worktree.nvim).
-- vim.ui.select/input los provee Snacks, así que se elimina además una dependencia de telescope.
local M = {}

local function git(args)
  local res = vim.system(vim.list_extend({ "git" }, args), { text = true }):wait()
  return res.code == 0, vim.trim(res.stdout or ""), vim.trim(res.stderr or "")
end

function M.switch()
  local ok, out = git { "worktree", "list", "--porcelain" }
  if not ok then
    vim.notify("No es un repositorio git con worktrees", vim.log.levels.WARN)
    return
  end
  local trees = {}
  for path in out:gmatch "worktree (.-)\n" do
    table.insert(trees, path)
  end
  -- el último no termina en \n
  local last = out:match "worktree ([^\n]+)$"
  if last then
    table.insert(trees, last)
  end
  if #trees == 0 then
    vim.notify("Sin worktrees", vim.log.levels.WARN)
    return
  end
  vim.ui.select(trees, { prompt = "Cambiar a worktree" }, function(choice)
    if not choice then
      return
    end
    vim.cmd("cd " .. vim.fn.fnameescape(choice))
    vim.notify("Worktree: " .. choice)
  end)
end

function M.create()
  vim.ui.input({ prompt = "Nueva rama/worktree: " }, function(name)
    if not name or name == "" then
      return
    end
    local ok, root = git { "rev-parse", "--show-toplevel" }
    if not ok then
      vim.notify("No es un repositorio git", vim.log.levels.WARN)
      return
    end
    local path = vim.fn.fnamemodify(root, ":h") .. "/" .. name
    local cok, _, cerr = git { "worktree", "add", path, "-b", name }
    if not cok then
      vim.notify("Error al crear worktree: " .. cerr, vim.log.levels.ERROR)
      return
    end
    vim.cmd("cd " .. vim.fn.fnameescape(path))
    vim.notify("Worktree creado: " .. path)
  end)
end

return M