| 629 | namespace { |
| 630 | |
| 631 | Result<bool> DoCreateDir(const PlatformFilename& dir_path, bool create_parents) { |
| 632 | #ifdef _WIN32 |
| 633 | const auto s = dir_path.ToNative().c_str(); |
| 634 | if (CreateDirectoryW(s, nullptr)) { |
| 635 | return true; |
| 636 | } |
| 637 | int errnum = GetLastError(); |
| 638 | if (errnum == ERROR_ALREADY_EXISTS) { |
| 639 | const auto attrs = GetFileAttributesW(s); |
| 640 | if (attrs == INVALID_FILE_ATTRIBUTES || !(attrs & FILE_ATTRIBUTE_DIRECTORY)) { |
| 641 | // Note we propagate the original error, not the GetFileAttributesW() error |
| 642 | return IOErrorFromWinError(ERROR_ALREADY_EXISTS, "Cannot create directory '", |
| 643 | dir_path.ToString(), "': non-directory entry exists"); |
| 644 | } |
| 645 | return false; |
| 646 | } |
| 647 | if (create_parents && errnum == ERROR_PATH_NOT_FOUND) { |
| 648 | auto parent_path = dir_path.Parent(); |
| 649 | if (parent_path != dir_path) { |
| 650 | RETURN_NOT_OK(DoCreateDir(parent_path, create_parents)); |
| 651 | return DoCreateDir(dir_path, false); // Retry |
| 652 | } |
| 653 | } |
| 654 | return IOErrorFromWinError(GetLastError(), "Cannot create directory '", |
| 655 | dir_path.ToString(), "'"); |
| 656 | #else |
| 657 | const auto s = dir_path.ToNative().c_str(); |
| 658 | if (mkdir(s, S_IRWXU | S_IRWXG | S_IRWXO) == 0) { |
| 659 | return true; |
| 660 | } |
| 661 | if (errno == EEXIST) { |
| 662 | struct stat st; |
| 663 | if (stat(s, &st) || !S_ISDIR(st.st_mode)) { |
| 664 | // Note we propagate the original errno, not the stat() errno |
| 665 | return IOErrorFromErrno(EEXIST, "Cannot create directory '", dir_path.ToString(), |
| 666 | "': non-directory entry exists"); |
| 667 | } |
| 668 | return false; |
| 669 | } |
| 670 | if (create_parents && errno == ENOENT) { |
| 671 | auto parent_path = dir_path.Parent(); |
| 672 | if (parent_path != dir_path) { |
| 673 | RETURN_NOT_OK(DoCreateDir(parent_path, create_parents)); |
| 674 | return DoCreateDir(dir_path, false); // Retry |
| 675 | } |
| 676 | } |
| 677 | return IOErrorFromErrno(errno, "Cannot create directory '", dir_path.ToString(), "'"); |
| 678 | #endif |
| 679 | } |
| 680 | |
| 681 | } // namespace |
| 682 |
no test coverage detected