|
| 1 | +local state = ya.sync(function(st) |
| 2 | + return { |
| 3 | + cwd = tostring(cx.active.current.cwd), |
| 4 | + empty = st.empty, |
| 5 | + } |
| 6 | +end) |
| 7 | + |
| 8 | +local set_state = ya.sync(function(st, empty) st.empty = empty end) |
| 9 | + |
| 10 | +local function notify(s, ...) |
| 11 | + ya.notify { title = "Zoxide", content = string.format(s, ...), timeout = 5, level = "error" } |
| 12 | +end |
| 13 | + |
| 14 | +local function head(cwd) |
| 15 | + local child = Command("zoxide"):args({ "query", "-l" }):stdout(Command.PIPED):spawn() |
| 16 | + if not child then |
| 17 | + return 0 |
| 18 | + end |
| 19 | + |
| 20 | + local n = 0 |
| 21 | + repeat |
| 22 | + local next, event = child:read_line() |
| 23 | + if event ~= 0 then |
| 24 | + break |
| 25 | + elseif cwd ~= next:gsub("\n$", "") then |
| 26 | + n = n + 1 |
| 27 | + end |
| 28 | + until n >= 2 |
| 29 | + |
| 30 | + child:start_kill() |
| 31 | + return n |
| 32 | +end |
| 33 | + |
| 34 | +local function setup(_, opts) |
| 35 | + opts = opts or {} |
| 36 | + |
| 37 | + if opts.update_db then |
| 38 | + ps.sub( |
| 39 | + "cd", |
| 40 | + function() |
| 41 | + ya.manager_emit("shell", { |
| 42 | + confirm = true, |
| 43 | + "zoxide add " .. ya.quote(tostring(cx.active.current.cwd)), |
| 44 | + }) |
| 45 | + end |
| 46 | + ) |
| 47 | + end |
| 48 | +end |
| 49 | + |
| 50 | +local function entry() |
| 51 | + local st = state() |
| 52 | + if st.empty == true then |
| 53 | + return notify("No directory history in the database, check out the `zoxide` docs to set it up.") |
| 54 | + elseif st.empty == nil and head(st.cwd) < 2 then |
| 55 | + set_state(true) |
| 56 | + return notify("No directory history in the database, check out the `zoxide` docs to set it up.") |
| 57 | + end |
| 58 | + |
| 59 | + local _permit = ya.hide() |
| 60 | + local child, err = Command("zoxide") |
| 61 | + :args({ "query", "-i", "--exclude" }) |
| 62 | + :arg(st.cwd) |
| 63 | + :stdin(Command.INHERIT) |
| 64 | + :stdout(Command.PIPED) |
| 65 | + :stderr(Command.INHERIT) |
| 66 | + :spawn() |
| 67 | + |
| 68 | + if not child then |
| 69 | + return notify("Spawn `zoxide` failed with error code %s. Do you have it installed?", err) |
| 70 | + end |
| 71 | + |
| 72 | + local output, err = child:wait_with_output() |
| 73 | + if not output then |
| 74 | + return notify("`zoxide` exited with error code %s", err) |
| 75 | + end |
| 76 | + ya.manager_emit("cd", { output.stdout:gsub("\n$", "") }) |
| 77 | +end |
| 78 | + |
| 79 | +return { setup = setup, entry = entry } |
0 commit comments