| 12 | namespace vfs { |
| 13 | |
| 14 | auto MkDir(const char* path) -> Expected<void> { |
| 15 | if (path == nullptr) { |
| 16 | return std::unexpected(Error(ErrorCode::kInvalidArgument)); |
| 17 | } |
| 18 | |
| 19 | LockGuard<SpinLock> guard(GetVfsState().vfs_lock_); |
| 20 | // 解析父目录路径和目录名 |
| 21 | char parent_path[512]; |
| 22 | char dir_name[256]; |
| 23 | const char* last_slash = strrchr(path, '/'); |
| 24 | if (last_slash == nullptr || last_slash == path) { |
| 25 | strncpy(parent_path, "/", sizeof(parent_path)); |
| 26 | const char* name_start = path[0] == '/' ? path + 1 : path; |
| 27 | if (strlen(name_start) >= sizeof(dir_name)) { |
| 28 | return std::unexpected(Error(ErrorCode::kFsInvalidPath)); |
| 29 | } |
| 30 | strncpy(dir_name, name_start, sizeof(dir_name)); |
| 31 | } else { |
| 32 | size_t parent_len = last_slash - path; |
| 33 | if (parent_len >= sizeof(parent_path)) { |
| 34 | return std::unexpected(Error(ErrorCode::kFsInvalidPath)); |
| 35 | } |
| 36 | strncpy(parent_path, path, parent_len); |
| 37 | parent_path[parent_len] = '\0'; |
| 38 | if (strlen(last_slash + 1) >= sizeof(dir_name)) { |
| 39 | return std::unexpected(Error(ErrorCode::kFsInvalidPath)); |
| 40 | } |
| 41 | strncpy(dir_name, last_slash + 1, sizeof(dir_name)); |
| 42 | } |
| 43 | dir_name[sizeof(dir_name) - 1] = '\0'; |
| 44 | |
| 45 | // 查找父目录 |
| 46 | auto parent_result = Lookup(parent_path); |
| 47 | if (!parent_result.has_value()) { |
| 48 | return std::unexpected(parent_result.error()); |
| 49 | } |
| 50 | |
| 51 | Dentry* parent_dentry = parent_result.value(); |
| 52 | if (parent_dentry->inode == nullptr || |
| 53 | parent_dentry->inode->type != FileType::kDirectory) { |
| 54 | return std::unexpected(Error(ErrorCode::kFsNotADirectory)); |
| 55 | } |
| 56 | |
| 57 | // 检查目录是否已存在 |
| 58 | if (FindChild(parent_dentry, dir_name) != nullptr) { |
| 59 | return std::unexpected(Error(ErrorCode::kFsFileExists)); |
| 60 | } |
| 61 | |
| 62 | // 创建目录 |
| 63 | if (parent_dentry->inode->ops == nullptr) { |
| 64 | return std::unexpected(Error(ErrorCode::kDeviceNotSupported)); |
| 65 | } |
| 66 | |
| 67 | auto result = |
| 68 | parent_dentry->inode->ops->Mkdir(parent_dentry->inode, dir_name); |
| 69 | if (!result.has_value()) { |
| 70 | return std::unexpected(result.error()); |
| 71 | } |