diff --git a/src/main/cpp/util/file_posix.cc b/src/main/cpp/util/file_posix.cc index 475de9ef18e74f..cdeb0ecd5b426a 100644 --- a/src/main/cpp/util/file_posix.cc +++ b/src/main/cpp/util/file_posix.cc @@ -299,6 +299,7 @@ bool MakeDirectories(const string &path, unsigned int mode) { return MakeDirectories(path, mode, true); } +#ifndef __CYGWIN__ string GetCwd() { char cwdbuf[PATH_MAX]; if (getcwd(cwdbuf, sizeof cwdbuf) == NULL) { @@ -306,6 +307,7 @@ string GetCwd() { } return string(cwdbuf); } +#endif // not __CYGWIN__ bool ChangeDirectory(const string& path) { return chdir(path.c_str()) == 0; diff --git a/src/main/cpp/util/file_windows.cc b/src/main/cpp/util/file_windows.cc index f947df150887f3..10d3e0604ccc4d 100644 --- a/src/main/cpp/util/file_windows.cc +++ b/src/main/cpp/util/file_windows.cc @@ -32,6 +32,14 @@ using std::unique_ptr; using std::vector; using std::wstring; +template +static bool HasUncPrefix(const char_type* path) { + return path[0] == '\\' && (path[1] == '\\' || path[1] == '?') && + (path[2] == '.' || path[2] == '?') && path[3] == '\\'; +} + +static unique_ptr GetCwdW(); + class WindowsPipe : public IPipe { public: WindowsPipe(const HANDLE& read_handle, const HANDLE& write_handle) @@ -101,9 +109,8 @@ static bool IsRootOrAbsolute(const string& path, bool must_be_root) { (path[2] == '/' || path[2] == '\\')) || // path is (or starts with) "\\?\c:\" or "\??\c:\" or similar ((must_be_root ? path.size() == 7 : path.size() >= 7) && - path[0] == '\\' && (path[1] == '\\' || path[1] == '?') && - path[2] == '?' && path[3] == '\\' && isalpha(path[4]) && - path[5] == ':' && path[6] == '\\'); + HasUncPrefix(path.c_str()) && isalpha(path[4]) && path[5] == ':' && + path[6] == '\\'); } pair SplitPath(const string& path) { @@ -525,14 +532,20 @@ bool MakeDirectories(const string& path, unsigned int mode) { #else // not COMPILER_MSVC #endif // COMPILER_MSVC -#ifdef COMPILER_MSVC +static unique_ptr GetCwdW() { + DWORD len = ::GetCurrentDirectoryW(0, nullptr); + unique_ptr cwd(new WCHAR[len]); + if (!::GetCurrentDirectoryW(len, cwd.get())) { + die(255, "GetCurrentDirectoryW failed, err=%d\n", GetLastError()); + } + return std::move(cwd); +} + string GetCwd() { - // TODO(bazel-team): implement this. - pdie(255, "blaze_util::GetCwd is not implemented on Windows"); - return ""; + unique_ptr cwd(GetCwdW()); + return string( + WstringToCstring(cwd.get() + (HasUncPrefix(cwd.get()) ? 4 : 0)).get()); } -#else // not COMPILER_MSVC -#endif // COMPILER_MSVC #ifdef COMPILER_MSVC bool ChangeDirectory(const string& path) {