getcwd(): Return empty string if CWD is invalid. #5292

Closes #5291

Restores behaviour identical to Vim. If the user calls the VimScript
function 'getcwd()' and the working directory cannot be found (for
example because the directory has been deleted since the last time it
was used) an empty string needs to be returned instead of throwing an
error.
This commit is contained in:
HiPhish 2016-09-04 12:28:01 +02:00 committed by Justin M. Keyes
parent 73b8424fad
commit cd321b7d0f
2 changed files with 27 additions and 13 deletions

View File

@ -9776,26 +9776,20 @@ static void f_getcwd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
if (from) { if (from) {
break; break;
} }
case kCdScopeTab: // FALLTHROUGH case kCdScopeTab: // FALLTHROUGH
assert(tp); assert(tp);
from = tp->localdir; from = tp->localdir;
if (from) { if (from) {
break; break;
} }
case kCdScopeGlobal: // FALLTHROUGH case kCdScopeGlobal: // FALLTHROUGH
// The `globaldir` variable is not always set. if (globaldir) { // `globaldir` is not always set.
if (globaldir) {
from = globaldir; from = globaldir;
} else { } else if (os_dirname(cwd, MAXPATHL) == FAIL) { // Get the OS CWD.
// We have to copy the OS path directly into output string. from = (char_u *)""; // Return empty string on failure.
if (os_dirname(cwd, MAXPATHL) == FAIL) {
EMSG(_("E41: Could not display path."));
goto end;
}
} }
break; break;
case kCdScopeInvalid: case kCdScopeInvalid: // We should never get here
// We should never get here
assert(false); assert(false);
} }
@ -9807,7 +9801,7 @@ static void f_getcwd(typval_T *argvars, typval_T *rettv, FunPtr fptr)
#ifdef BACKSLASH_IN_FILENAME #ifdef BACKSLASH_IN_FILENAME
slash_adjust(rettv->vval.v_string); slash_adjust(rettv->vval.v_string);
#endif #endif
end:
xfree(cwd); xfree(cwd);
} }

View File

@ -269,3 +269,23 @@ for _, cmd in ipairs {'getcwd', 'haslocaldir'} do
end) end)
end end
describe("getcwd()", function ()
local temp_dir = "Xtest-functional-ex_cmds-cd_spec.temp"
before_each(function()
clear()
lfs.mkdir(temp_dir)
end)
after_each(function()
helpers.rmdir(temp_dir)
end)
it("returns empty string if working directory does not exist", function()
execute("cd " .. temp_dir)
helpers.wait()
helpers.rmdir(temp_dir)
eq("", helpers.eval("getcwd()"))
end)
end)