diff --git a/lua/yazi/keybinding_helpers.lua b/lua/yazi/keybinding_helpers.lua index 48bc78f..67bf6f6 100644 --- a/lua/yazi/keybinding_helpers.lua +++ b/lua/yazi/keybinding_helpers.lua @@ -215,7 +215,19 @@ end ---@param context YaziActiveContext function YaziOpenerActions.change_working_directory(context) local last_directory = context.ya_process.cwd - if last_directory then + if not last_directory then + assert( + context.input_path, + "No input_path found. Expected yazi to be started with an input_path" + ) + if context.input_path:is_file() then + last_directory = context.input_path:parent().filename + else + last_directory = context.input_path.filename + end + end + + if last_directory ~= vim.fn.getcwd() then vim.notify('cwd changed to "' .. last_directory .. '"') vim.cmd({ cmd = "cd", args = { last_directory } }) end diff --git a/spec/yazi/keybinding_helpers_spec.lua b/spec/yazi/keybinding_helpers_spec.lua index 6c61149..1574442 100644 --- a/spec/yazi/keybinding_helpers_spec.lua +++ b/spec/yazi/keybinding_helpers_spec.lua @@ -2,15 +2,18 @@ local assert = require("luassert") local config_module = require("yazi.config") local keybinding_helpers = require("yazi.keybinding_helpers") local match = require("luassert.match") +local plenary_path = require("plenary.path") local stub = require("luassert.stub") describe("keybinding_helpers", function() local vim_cmd_stub + local vim_fn_stub local vim_notify_stub local snapshot before_each(function() snapshot = assert:snapshot() + vim_fn_stub = stub(vim.fn, "getcwd") vim_notify_stub = stub(vim, "notify") vim_cmd_stub = stub(vim, "cmd") end) @@ -155,17 +158,39 @@ describe("keybinding_helpers", function() end ) - it("should not crash when the cwd is not available", function() + it("uses yazi's input_path if no cwd is available yet", function() ---@diagnostic disable-next-line: missing-fields keybinding_helpers.change_working_directory({ + input_path = plenary_path:new("/tmp"), ---@diagnostic disable-next-line: missing-fields ya_process = { cwd = nil, }, }) - assert.stub(vim_cmd_stub).was_not_called() - assert.stub(vim_notify_stub).was_not_called() + assert + .stub(vim_cmd_stub) + .was_called_with({ cmd = "cd", args = { "/tmp" } }) + assert.stub(vim_notify_stub).was_called_with('cwd changed to "/tmp"') end) + + it( + "should not change the working directory if the new cwd is already the current one", + function() + vim_fn_stub.returns("/tmp") + ---@diagnostic disable-next-line: missing-fields + keybinding_helpers.change_working_directory({ + input_path = plenary_path:new("/tmp"), + ---@diagnostic disable-next-line: missing-fields + ya_process = { + cwd = "/tmp", + }, + }) + + assert.stub(vim_fn_stub).was_called_with() + assert.stub(vim_cmd_stub).was_not_called() + assert.stub(vim_notify_stub).was_not_called() + end + ) end) end)